From bcac208e56c9cd76c1e3675fc09c85ed5afbba90 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 01:53:00 -0700 Subject: [PATCH 01/27] feat(inference): add dual DGX Spark express profile --- ci/platform-matrix.json | 4 +- ci/source-architecture-budget.json | 2 +- docs/get-started/prerequisites.mdx | 2 +- docs/index.yml | 9 + .../set-up-vllm-on-two-dgx-sparks.mdx | 231 ++++ docs/inference/set-up-vllm.mdx | 13 +- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 13 +- docs/reference/host-files-and-state.mdx | 4 + docs/reference/platform-support.mdx | 2 +- ...park-gb10.dual.deepseek-v4-flash-0731.yaml | 38 + ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 123 ++ managed-inference/schemas/catalog.schema.json | 70 + managed-inference/schemas/preset.schema.json | 134 ++ managed-inference/schemas/recipe.schema.json | 137 ++ package.json | 5 +- scripts/install.sh | 5 +- scripts/managed-inference/compile-catalog.mts | 312 +++++ .../uninstall/run-plan-dual-station.test.ts | 195 ++- .../run-plan-gateway-segregation.test.ts | 8 +- src/lib/actions/uninstall/run-plan.ts | 99 +- src/lib/inference/context-window.ts | 6 +- src/lib/inference/local-vllm-auth.test.ts | 84 +- src/lib/inference/local.ts | 169 ++- .../inference/serving/catalog-integrity.ts | 54 + src/lib/inference/serving/catalog-types.ts | 217 +++ src/lib/inference/serving/catalog.test.ts | 56 + src/lib/inference/serving/catalog.ts | 84 ++ .../dual-spark-discovery-production.ts | 1231 +++++++++++++++++ .../serving/dual-spark-discovery.test.ts | 813 +++++++++++ .../inference/serving/dual-spark-discovery.ts | 1218 ++++++++++++++++ .../serving/dual-spark-executor.test.ts | 623 +++++++++ .../inference/serving/dual-spark-executor.ts | 1035 ++++++++++++++ .../dual-spark-fixture.test-support.ts | 97 ++ .../serving/dual-spark-installer.test.ts | 475 +++++++ .../inference/serving/dual-spark-installer.ts | 431 ++++++ .../serving/dual-spark-lifecycle.test.ts | 458 ++++++ .../inference/serving/dual-spark-lifecycle.ts | 851 ++++++++++++ .../serving/dual-spark-materialize.test.ts | 193 +++ .../serving/dual-spark-materialize.ts | 422 ++++++ .../serving/dual-spark-topology.test.ts | 404 ++++++ .../inference/serving/dual-spark-topology.ts | 785 +++++++++++ .../inference/serving/generated/catalog.json | 249 ++++ .../serving/managed-runtime-receipts.ts | 86 ++ src/lib/inference/serving/resolver.test.ts | 272 ++++ src/lib/inference/serving/resolver.ts | 239 ++++ .../serving/spark-runtime-receipt-path.ts | 5 + .../serving/spark-runtime-receipt.ts | 523 +++++++ .../inference/serving/vllm-managed-support.ts | 12 + src/lib/inference/vllm-api-key.ts | 36 +- src/lib/inference/vllm-docker-env.ts | 55 + src/lib/inference/vllm-dual-station.test.ts | 3 + .../inference/vllm-managed-recovery.test.ts | 51 + .../vllm-managed-runtime-receipts.test.ts | 126 ++ .../vllm-spark-runtime-receipt.test.ts | 364 +++++ .../vllm-station-lifecycle-lock.test.ts | 26 + .../inference/vllm-station-lifecycle-lock.ts | 20 +- .../vllm-station-runtime-cleanup-entry.ts | 80 +- src/lib/inference/vllm.ts | 76 +- src/lib/onboard.ts | 4 +- src/lib/onboard/setup-inference.ts | 7 +- src/lib/onboard/setup-nim-vllm.test.ts | 22 +- src/lib/onboard/setup-nim-vllm.ts | 30 +- test/helpers/vitest-watch-triggers.ts | 8 + test/install-express-prompt.test.ts | 13 +- ...managed-inference-catalog-compiler.test.ts | 104 ++ test/vitest-watch-triggers.test.ts | 8 + 66 files changed, 13349 insertions(+), 182 deletions(-) create mode 100644 docs/inference/set-up-vllm-on-two-dgx-sparks.mdx create mode 100644 managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml create mode 100644 managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml create mode 100644 managed-inference/schemas/catalog.schema.json create mode 100644 managed-inference/schemas/preset.schema.json create mode 100644 managed-inference/schemas/recipe.schema.json create mode 100644 scripts/managed-inference/compile-catalog.mts create mode 100644 src/lib/inference/serving/catalog-integrity.ts create mode 100644 src/lib/inference/serving/catalog-types.ts create mode 100644 src/lib/inference/serving/catalog.test.ts create mode 100644 src/lib/inference/serving/catalog.ts create mode 100644 src/lib/inference/serving/dual-spark-discovery-production.ts create mode 100644 src/lib/inference/serving/dual-spark-discovery.test.ts create mode 100644 src/lib/inference/serving/dual-spark-discovery.ts create mode 100644 src/lib/inference/serving/dual-spark-executor.test.ts create mode 100644 src/lib/inference/serving/dual-spark-executor.ts create mode 100644 src/lib/inference/serving/dual-spark-fixture.test-support.ts create mode 100644 src/lib/inference/serving/dual-spark-installer.test.ts create mode 100644 src/lib/inference/serving/dual-spark-installer.ts create mode 100644 src/lib/inference/serving/dual-spark-lifecycle.test.ts create mode 100644 src/lib/inference/serving/dual-spark-lifecycle.ts create mode 100644 src/lib/inference/serving/dual-spark-materialize.test.ts create mode 100644 src/lib/inference/serving/dual-spark-materialize.ts create mode 100644 src/lib/inference/serving/dual-spark-topology.test.ts create mode 100644 src/lib/inference/serving/dual-spark-topology.ts create mode 100644 src/lib/inference/serving/generated/catalog.json create mode 100644 src/lib/inference/serving/managed-runtime-receipts.ts create mode 100644 src/lib/inference/serving/resolver.test.ts create mode 100644 src/lib/inference/serving/resolver.ts create mode 100644 src/lib/inference/serving/spark-runtime-receipt-path.ts create mode 100644 src/lib/inference/serving/spark-runtime-receipt.ts create mode 100644 src/lib/inference/serving/vllm-managed-support.ts create mode 100644 src/lib/inference/vllm-managed-recovery.test.ts create mode 100644 src/lib/inference/vllm-managed-runtime-receipts.test.ts create mode 100644 src/lib/inference/vllm-spark-runtime-receipt.test.ts create mode 100644 test/managed-inference-catalog-compiler.test.ts diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index 2e27ab585ab..ec00a4a267b 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -1,7 +1,7 @@ { "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nSingle source of truth for NemoClaw launch claims and platform support. Covers platforms, inference providers, supported agents, messaging integrations, and deployment paths. Scripts read this to generate README and docs tables. QA/CI update platform/provider rows; the engineering owner reviews other rows. Docs are derived.", "version": "1.1", - "updated": "2026-07-21", + "updated": "2026-08-02", "project_status": { "stage": "alpha", @@ -47,7 +47,7 @@ "status": "tested", "prd_priority": "P1", "ci_tested": true, - "notes": "Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw)." + "notes": "Use the standard installer and `$$nemoclaw onboard`. The automatic two-DGX Spark managed-vLLM profile is Experimental, and physical two-node end-to-end validation is pending. For the profile requirements and controls, see [Set Up vLLM on Two DGX Sparks](../inference/local-inference/set-up-vllm-on-two-dgx-sparks). For the validated single-DGX Spark walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw)." }, { "name": "Windows WSL2", diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 8d1def477b4..de561b85725 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -46,7 +46,7 @@ "src/lib/actions/sandbox/snapshot.ts": 39, "src/lib/actions/uninstall/run-plan.ts": 25, "src/lib/inference/onboard-probes.ts": 21, - "src/lib/inference/vllm.ts": 23, + "src/lib/inference/vllm.ts": 21, "src/lib/onboard.ts": 225, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/sandbox/config.ts": 22, diff --git a/docs/get-started/prerequisites.mdx b/docs/get-started/prerequisites.mdx index e9db60e9caf..9e7c1cd46c9 100644 --- a/docs/get-started/prerequisites.mdx +++ b/docs/get-started/prerequisites.mdx @@ -101,7 +101,7 @@ The table comes from [`ci/platform-matrix.json`](https://github.com/NVIDIA/NemoC {/* platform-matrix:begin */} | OS | Container runtime | Status | Notes | |----|-------------------|--------|-------| -| DGX OS (Spark) | Docker | Tested | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | +| DGX OS (Spark) | Docker | Tested | Use the standard installer and `$$nemoclaw onboard`. The automatic two-DGX Spark managed-vLLM profile is Experimental, and physical two-node end-to-end validation is pending. For the profile requirements and controls, see [Set Up vLLM on Two DGX Sparks](../inference/local-inference/set-up-vllm-on-two-dgx-sparks). For the validated single-DGX Spark walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | DGX OS (Station) | Docker | Tested with limitations | Tested with limitations across qualified profiles on one physical DGX Station GB300; see [Additional Setup for DGX Station](additional-setup/dgx-station-preparation) for accepted profiles, the pending no-OTA DGX OS `7.6.x` end-to-end qualification, runtime gates, and current dual-Station and dedicated CI limitations. | | Linux | Docker | Tested | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | | macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | Start the container runtime (Colima or Docker Desktop) before running the installer. When Homebrew is available, OpenShell uses its official formula and the gateway appears in `brew services list` as `openshell`; without Homebrew, NemoClaw uses the standalone OpenShell install and detached gateway fallback. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | diff --git a/docs/index.yml b/docs/index.yml index ea0ad6939e0..13caa87fb02 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -101,6 +101,9 @@ navigation: - page: "Set Up vLLM" path: _build/agent-variants/inference/set-up-vllm.openclaw.generated.mdx slug: set-up-vllm + - page: "Set Up vLLM on Two DGX Sparks" + path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-sparks.openclaw.generated.mdx + slug: set-up-vllm-on-two-dgx-sparks - page: "Set Up vLLM on Two DGX Stations" path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-stations.openclaw.generated.mdx slug: set-up-vllm-on-two-dgx-stations @@ -507,6 +510,9 @@ navigation: - page: "Set Up vLLM" path: _build/agent-variants/inference/set-up-vllm.deepagents.generated.mdx slug: set-up-vllm + - page: "Set Up vLLM on Two DGX Sparks" + path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-sparks.deepagents.generated.mdx + slug: set-up-vllm-on-two-dgx-sparks - page: "Set Up vLLM on Two DGX Stations" path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-stations.deepagents.generated.mdx slug: set-up-vllm-on-two-dgx-stations @@ -832,6 +838,9 @@ navigation: - page: "Set Up vLLM" path: _build/agent-variants/inference/set-up-vllm.hermes.generated.mdx slug: set-up-vllm + - page: "Set Up vLLM on Two DGX Sparks" + path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-sparks.hermes.generated.mdx + slug: set-up-vllm-on-two-dgx-sparks - page: "Set Up vLLM on Two DGX Stations" path: _build/agent-variants/inference/set-up-vllm-on-two-dgx-stations.hermes.generated.mdx slug: set-up-vllm-on-two-dgx-stations diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx new file mode 100644 index 00000000000..6130456437d --- /dev/null +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -0,0 +1,231 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Set Up vLLM on Two DGX Sparks" +sidebar-title: "Set Up vLLM on Two DGX Sparks" +description: "Qualify two trusted DGX Spark systems and start NemoClaw's Experimental distributed DeepSeek V4 Flash vLLM profile." +description-agent: "Sets up the Experimental managed vLLM profile for two DGX Spark systems, including selection, qualification, runtime ownership, and cleanup. Use when configuring NEMOCLAW_DGX_SPARK_PEER or NEMOCLAW_SERVING_PRESET." +keywords: ["nemoclaw dual dgx spark", "two dgx spark vllm", "deepseek v4 flash"] +content: + type: "how_to" +--- + +Use this workflow to let DGX Spark Express qualify two trusted DGX Spark systems for distributed vLLM serving. +The profile serves DeepSeek V4 Flash 0731 through the managed `inference.local` route. + + +This profile is Experimental because physical two-node end-to-end (E2E) validation is pending. +Use it only for evaluation until the required physical validation is complete. + + +## Understand Profile Selection + +DGX Spark Express attempts automatic profile selection only after it selects the managed vLLM provider. +A provider other than `install-vllm`, an existing local inference route, `NEMOCLAW_VLLM_MODEL`, or `NEMOCLAW_VLLM_EXTRA_ARGS_JSON` remains authoritative. +Without explicit inference intent, the detector derives one exact counterpart from each qualified private `/30` rail. +It does not scan a subnet, add SSH host keys, add authorized keys, or change SSH configuration. + +Both derived addresses must already have strict public-key SSH trust. +They must identify the same physical peer and the same SSH host key. +The detector performs read-only host probes only through that pinned identity. +After you confirm setup, NemoClaw repeats the read-only pair qualification and then writes an owner-only temporary SSH binding at `/dual-spark-managed-serving.json.ssh-binding/` for the install transaction. +The selected state root is `~/.nemoclaw/` for the default gateway or `~/.nemoclaw/gateways//` for a non-default gateway. +Declining setup creates no binding. After confirmation, NemoClaw attempts to remove the binding when setup fails or the durable runtime receipt is committed. +If cleanup cannot be confirmed and the claim remains without a durable runtime receipt, a new managed-vLLM install stops before mutation and preserves the claim for explicit recovery or removal. + +When no pair qualifies during automatic selection, NemoClaw retains the existing single-DGX Spark managed vLLM path. +This ordinary no-match result occurs before the distributed image or model download starts. + +Existing related runtime state is not an ordinary no-match result. +NemoClaw stops when either host has a related vLLM or DGX Station container, an ambiguous runtime inspection, or a listener on port `8000` or `25000`. +An existing durable dual-Spark or dual-Station runtime receipt, either receipt's copied SSH binding, an orphaned temporary dual-Spark discovery claim, or an SSH binding that conflicts with the new transaction also stops setup. +NemoClaw leaves the existing files, containers, and listeners untouched instead of replacing, repairing, adopting, or removing them. + +Set `NEMOCLAW_DGX_SPARK_PEER` to request one exact pretrusted peer. +Set `NEMOCLAW_SERVING_PRESET=vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731` to request the exact serving profile. +Either setting makes qualification strict, so a missed requirement stops setup instead of selecting the single-DGX Spark profile. + +## Prepare Both Systems + +Prepare both DGX Spark systems before you run the installer. +The automatic path requires all of these conditions on both systems: + +- The host is an `arm64` DGX Spark with exactly one GB10 GPU. +- The current controller is a non-root user whose user ID (UID) matches the local host probe. +- Docker, NVIDIA Container Toolkit, Container Device Interface (CDI), and NVIDIA GPU readiness checks pass. +- One direct ConnectX-7 physical port exposes exactly two active `200,000 Mbps` Ethernet rails. +- Each rail has a maximum transmission unit (MTU) of at least `9,000` bytes and exactly one usable private IPv4 `/30` address. +- The two rails use distinct interfaces, MAC addresses, subnets, and reciprocal peer addresses. +- Each selected rail address has a dynamically resolved remote direct memory access over Converged Ethernet version 2 (RoCEv2) global identifier (GID). +- Both derived peer addresses have existing strict host-key and public-key SSH trust. +- `~/.cache/huggingface` already exists, belongs to the probed numeric Unix user ID and Unix group ID, and is writable by that user. +- Docker storage and the Hugging Face cache each report at least `1,024` available inodes. +- If `earlyoom` is installed, its active state is `inactive` on both systems. + +NemoClaw treats an active or uninspectable `earlyoom` service as an unmet two-node requirement. +It does not stop, disable, or reconfigure that service. +An explicit pair or preset stops when this requirement is not met. + +Refer to the [NVIDIA DGX Spark clustering guide](https://docs.nvidia.com/dgx/dgx-spark/spark-clustering.html) for the physical connection workflow. +The NemoClaw checks above remain the exact profile requirements. + +### Reserve Storage on Each System + +The profile verifies storage before it pulls the image or downloads the model on either system. +For a cold cache, each system needs these approximate capacities: + +| Filesystem | Required capacity | Included data | +|---|---:|---| +| Hugging Face cache | `170.936 GB` | `166.899 GB` model snapshot, `3.221 GB` staging reserve, and `0.816 GB` writable allowance. | +| Docker storage | `32.584 GB` | Three times the `9.788 GB` compressed image size plus a `3.221 GB` staging reserve. | +| Shared filesystem | `203.520 GB` | The combined cold-cache requirement when both paths share one filesystem. | + +An exact cached image or exact pinned model snapshot removes its corresponding download requirement. +An unavailable capacity, ownership, directory, writability, or inode result leaves the two-node profile unqualified. + +## Restrict Network Access + +Apply network controls before you start the distributed containers. + + +The pinned image runs as root in both containers. +Each container receives all host GPUs, `/dev/infiniband`, Docker host networking, host inter-process communication, `64 GB` of shared memory, and unlimited locked memory. +The launch does not use a read-only root filesystem, drop Linux capabilities, or set `no-new-privileges`. +The head binds HTTP port `8000` only to the qualified primary rail address. +vLLM applies bearer API key authentication to its authenticated API routes, including the inventory and chat routes that NemoClaw verifies. +The API key does not authenticate every endpoint on port `8000`. +vLLM exposes unauthenticated inference and operational endpoints on that port. +Trusted Docker administrators can inspect that API key in the head container environment. +The distributed rendezvous and RoCE traffic do not use that bearer credential. + +Treat both DGX Spark systems and every host that can reach the direct rails as one trusted runtime boundary. +Allow port `8000` only from the OpenShell Docker subnet to the selected head rail address. +Deny port `8000` on management, LAN, and internet-facing interfaces. +Restrict port `25000`, NVIDIA Collective Communications Library (NCCL), and RoCE traffic to the exact reciprocal private rail addresses. +The address-specific bind reduces listener exposure but does not replace these firewall and trusted-boundary controls. + + +The detector qualifies both ConnectX-7 rails. +This profile revision binds vLLM, NCCL, Gloo, and tensor-parallel traffic to the first qualified rail in deterministic interface order. +Do not interpret two qualified `200,000 Mbps` rails as measured aggregate serving throughput. + +## Run Automatic Express Installation + +Run the interactive installer on the system that should become the head. + +```bash +curl -fsSL https://www.nvidia.com/nemoclaw.sh | \ + + NEMOCLAW_AGENT=openclaw \ + + + NEMOCLAW_AGENT=hermes \ + + + NEMOCLAW_AGENT=langchain-deepagents-code \ + + bash +``` + +Accept the usage notice and the **Run express install with these settings?** prompt. +DGX Spark Express prints the selected topology, immutable image, pinned model revision, cache paths, and worker-first launch order before image, model, or container mutation. + +For optional authenticated model downloads, follow [Authenticate Hugging Face Downloads](set-up-vllm#authenticate-hugging-face-downloads) before you start the installer. +The public model can download anonymously, but Hugging Face can rate-limit anonymous transfers. + +## Select an Exact Pair + +Use strict selection when you already know the pretrusted peer and want setup to stop on any missed requirement. +The following first-install example also selects the exact serving preset. + +```bash +curl -fsSL https://www.nvidia.com/nemoclaw.sh | \ + + NEMOCLAW_AGENT=openclaw \ + + + NEMOCLAW_AGENT=hermes \ + + + NEMOCLAW_AGENT=langchain-deepagents-code \ + + NEMOCLAW_NON_INTERACTIVE=1 \ + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 \ + NEMOCLAW_PROVIDER=install-vllm \ + NEMOCLAW_DGX_SPARK_PEER="" \ + NEMOCLAW_SERVING_PRESET=vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731 \ + NEMOCLAW_SANDBOX_NAME=my-assistant \ + bash +``` + +The peer must already pass strict public-key authentication and host-key checking without an interactive prompt. +The explicit target still must match the exact reciprocal rail topology. + +## Understand the Distributed Runtime + +The compiled profile pins these artifacts: + +- The image is `ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8`. +- The model is `deepseek-ai/DeepSeek-V4-Flash-0731` at revision `9e165c30e2704aec5d9d593cce3eebd58bbef1cb`. +- The served model ID is `deepseek-v4-flash-0731`. +- The context window is `1,048,576` tokens, with tensor parallelism `2` and pipeline parallelism `1`. + +NemoClaw stages the exact image and model snapshot on both systems. +It mounts the pinned Hugging Face model data read-only into each long-running container. +It resolves the selected RoCEv2 GID during qualification instead of assuming a fixed GID index. + +NemoClaw starts the headless rank-1 worker container before the rank-0 head container. +The worker must remain alive while waiting at the distributed rendezvous before the head starts. +NemoClaw passes the bearer API key only through the head container environment. +It does not add the credential or an environment-variable expansion to the vLLM process arguments. +The worker does not receive the API key. +Setup commits only after both container identities remain exact and authenticated model inventory and chat requests succeed. + +## Verify the Installed Route + +After the installer completes, inspect the live route and sandbox inference health. + +```bash +$$nemoclaw my-assistant inference get +$$nemoclaw my-assistant status +``` + +Confirm that `inference get` reports the `vllm-local` provider and `deepseek-v4-flash-0731` model. +Continue only when the `Inference` row reports `reachable`. +This result confirms inference route reachability. +It does not establish physical two-node E2E validation or product support. + +## Preserve Ownership and Uninstall State + +After runtime validation, NemoClaw writes the owner-only host-global receipt `~/.nemoclaw/dual-spark-vllm-runtime.json`. +It copies the pinned SSH binding to `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/`. +The receipt contains the exact plan, container IDs, peer identity, and API key fingerprint, but not the API key. + +NemoClaw stores the host-global bearer API key in the owner-only `~/.nemoclaw/dual-station-vllm-api-key` file. +The filename remains stable for managed vLLM compatibility across distributed profiles. +Users with Docker control can inspect the head container environment, so restrict Docker access to trusted administrators. + +If receipt persistence fails, NemoClaw attempts to remove only the exact containers created by that attempt and reports any rollback removal it cannot confirm. +It does not remove an exact pair that existed before the attempt. + +The containers have no Docker restart policy. +NemoClaw does not provide automatic runtime persistence across a Docker daemon restart or host reboot. +A stopped, partial, mismatched, or unhealthy pair remains a conflict and is not repaired automatically. + +Run a full uninstall to remove the exact receipt-owned pair. + +```bash +$$nemoclaw uninstall +``` + +Full uninstall revalidates both exact container IDs before it removes them and retires the receipt and copied SSH binding. +If revalidation or removal fails, uninstall stops before other cleanup and preserves the receipt for a retry. +A gateway-scoped uninstall preserves the host-global pair, receipt, SSH binding, and API key while another gateway remains. +Pair cleanup does not delete the Hugging Face model cache. + +## Related Topics + +- [Set Up vLLM](set-up-vllm) for existing servers, single-host managed setup, model selection, and download authentication. +- [Set Up vLLM on Two DGX Stations](set-up-vllm-on-two-dgx-stations) for the separate DGX Station distributed profile. +- [Uninstall NemoClaw](../../manage-sandboxes/operate-sandboxes/uninstall-nemoclaw) for full and gateway-scoped uninstall behavior. +- [Host Files and State](../../reference/host-files-and-state) for managed inference receipt and API key locations. diff --git a/docs/inference/set-up-vllm.mdx b/docs/inference/set-up-vllm.mdx index 1d89ed802e6..a922f58bbff 100644 --- a/docs/inference/set-up-vllm.mdx +++ b/docs/inference/set-up-vllm.mdx @@ -24,8 +24,8 @@ Use a host firewall with default-deny inbound rules. Allow TCP port `8000` 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. -The qualified dual-DGX Station path instead binds its bearer-protected `/v1` API to one selected private rail address and uses host networking on both runtime containers. -Follow [Set Up vLLM on Two DGX Stations](set-up-vllm-on-two-dgx-stations) for its isolation requirements. +The qualified two-DGX Spark and two-DGX Station paths use bearer-protected `/v1` routes and Docker host networking on both runtime containers; network isolation remains required for other endpoints and distributed traffic. +Follow [Set Up vLLM on Two DGX Sparks](set-up-vllm-on-two-dgx-sparks) or [Set Up vLLM on Two DGX Stations](set-up-vllm-on-two-dgx-stations) for their isolation requirements. ## Use an Existing Server @@ -83,7 +83,8 @@ Generic Linux NVIDIA GPU hosts require `NEMOCLAW_EXPERIMENTAL=1` or `NEMOCLAW_PR In an interactive run, the managed path lists the supported model registry for your host profile. Press **Enter** to use the profile default or select another validated model with its registered `vllm serve` arguments. -NemoClaw pulls the vLLM image, downloads model weights into `~/.cache/huggingface`, starts the `nemoclaw-vllm` container on `localhost:8000`, streams Hugging Face download progress, and polls `/v1/models` until the model is ready. +The single-host path pulls the vLLM image, downloads model weights into `~/.cache/huggingface`, and starts the `nemoclaw-vllm` container on `localhost:8000`. +The distributed DGX pages document their separate container names, endpoints, and lifecycle checks. The container carries a NemoClaw ownership label so later onboarding runs can distinguish it from a bring-your-own server without trusting the container name alone. If an existing `nemoclaw-vllm` container does not carry that label, NemoClaw preserves it and asks you to remove or rename it before installing managed vLLM. @@ -102,7 +103,7 @@ The two-Station page records the distributed recipe's image and runtime versions The first run duration depends on image and model size, storage performance, and network throughput. Later runs reuse the cached image and model weights. -The managed container uses Docker's `--restart unless-stopped` policy, so Docker restarts it unless an operator explicitly stops it. +The single-host managed container uses Docker's `--restart unless-stopped` policy, so Docker restarts it unless an operator explicitly stops it. ### Authenticate Hugging Face Downloads @@ -198,6 +199,9 @@ On DGX Station, accepting the installer express prompt selects `NEMOCLAW_VLLM_MO Express uses the single-Station Ultra recipe unless a trusted reciprocal pair qualifies for distributed serving. Refer to [Set Up vLLM on Two DGX Stations](set-up-vllm-on-two-dgx-stations) for pair qualification, lifecycle receipts, runtime topology, and network controls. +On DGX Spark, Express selects the pinned two-node profile when exactly one pretrusted reciprocal pair qualifies and no inference intent or related runtime conflicts. +Refer to [Set Up vLLM on Two DGX Sparks](set-up-vllm-on-two-dgx-sparks) for automatic and explicit selection, profile requirements, and cleanup behavior. + To select the existing `deepseek-v4-flash` recipe while retaining the same one-confirmation express flow, run: ```bash @@ -331,6 +335,7 @@ If the selected image does not support an argument, the managed container exits ## Related Topics - [Choose a Local Inference Server](choose-local-inference-server) to compare vLLM with Ollama and NVIDIA NIM. +- [Set Up vLLM on Two DGX Sparks](set-up-vllm-on-two-dgx-sparks) for the Experimental distributed DeepSeek V4 Flash profile. - [Set Up vLLM on Two DGX Stations](set-up-vllm-on-two-dgx-stations) for the Deferred distributed-serving workflow. - [Configure Inference Timeouts](../manage-inference/configure-inference-timeouts) when model startup or validation needs more time. - [Verify the Inference Route](../validate-inference/verify-inference-route) after setup. diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 1cc05d7b8ea..efcf75e2af2 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -36,19 +36,24 @@ It also preserves the gateway process, supervisor resources, marked Linux unit, A custom-port uninstall does not stop or remove the default gateway service or its environment file. +In this section, `` is `~/.nemoclaw/` for the default gateway or `~/.nemoclaw/gateways//` for a non-default gateway. For the default gateway, the uninstall command preserves `~/.nemoclaw/rebuild-backups/`, `~/.nemoclaw/backups/`, and `~/.nemoclaw/sandboxes.json` by default. A non-default gateway uses the corresponding entries under `~/.nemoclaw/gateways//`. When uninstall confirms that no sibling gateways remain, it also removes the shared CLI, services, images, providers, configuration, models, and swap. -During full uninstall, a managed dual-Station cleanup receipt makes NemoClaw first revalidate the recorded peer, cluster, and GPU identities and remove both exact managed vLLM containers. +During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first revalidate the recorded peer, plan, cluster, GPU, and container identities. +It then removes only both exact receipt-owned containers. +The dual-DGX Spark receipt is host-global under `~/.nemoclaw/`, while a dual-DGX Station receipt uses the selected gateway state root. Only after that pair cleanup succeeds does NemoClaw start the remaining full-uninstall steps. +If an interrupted dual-DGX Spark transaction leaves `/dual-spark-managed-serving.json.ssh-binding/` without a durable runtime receipt, full uninstall fails closed before cleanup or other mutation and preserves the claim for explicit recovery or removal. If validation or pair cleanup fails, uninstall exits nonzero and keeps the receipt so you can resolve the reported SSH, Docker, or peer-host error and retry. -Pair cleanup can partially complete before an error, so inspect both Stations before retrying. +Pair cleanup can partially complete before an error, so inspect both systems before retrying. When sibling gateways remain, it removes only the selected gateway's resources and port-scoped state and preserves those shared host resources. -This gateway-scoped path leaves the managed pair running and preserves its cleanup receipt and copied SSH binding, including when you pass `--destroy-user-data`. +This gateway-scoped path leaves a managed distributed pair running and preserves its cleanup receipt, copied SSH binding, any temporary dual-Spark discovery claim, and host-global API key. +This preservation also applies when you pass `--destroy-user-data`. If the OpenShell command is unavailable or its gateway list cannot be read, uninstall cannot confirm that the selected gateway is the last one, so it uses the same scoped path and preserves the shared resources. When the command itself is unavailable, uninstall exits nonzero before OpenShell cleanup so you can restore the command and retry. The preserved `rebuild-backups/`, `backups/`, and `sandboxes.json` entries stay unless you pass `--destroy-user-data`. -That flag does not override gateway-scoped preservation of the managed pair receipt or its copied SSH binding. +That flag does not override gateway-scoped preservation of the managed pair receipt, its copied SSH binding, or a temporary dual-Spark discovery claim. Interactive runs prompt before they remove the preserved entries, and the default answer keeps them. For non-interactive runs using `--yes`, `NEMOCLAW_NON_INTERACTIVE=1`, or a non-TTY shell, pass `--destroy-user-data` or set `NEMOCLAW_UNINSTALL_DESTROY_USER_DATA=1` to acknowledge data loss and remove the preserved entries. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index db37110da7e..708fc26a3a4 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -34,6 +34,10 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/onboard-session.json` | Resume marker for an onboarding attempt that failed before completion. | Yes, when you intentionally want to discard the failed session and start over. Prefer `$$nemoclaw onboard --fresh` when available. | | `~/.nemoclaw/usage-notice.json` | Records the third-party software notice version in `acceptedVersion` and the acceptance time in `acceptedAt`. Install, onboarding, and rebuild flows consult this file and prompt again when its recorded version differs from the current notice or the file is absent. | Yes; deleting it makes the next applicable install, onboarding, or rebuild flow prompt for acceptance again. | | `~/.nemoclaw/ollama-proxy-token` | Local auth token used by the host-side Ollama auth proxy. | Yes, but re-run onboarding afterward so NemoClaw recreates and registers the proxy token. | +| `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by NemoClaw-managed distributed vLLM profiles. | No while a managed distributed runtime exists. Full uninstall removes it only after managed runtime cleanup succeeds and no sibling gateway remains. | +| `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, and container identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | +| `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded DGX Spark worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds. | +| `/dual-spark-managed-serving.json.ssh-binding/` | Owner-only temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. Gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index f63b51ed299..f641e8114b7 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -78,7 +78,7 @@ For install requirements and the shorter setup-oriented platform view, refer to {/* platform-matrix-full:begin */} | OS | Container runtime | Status | PRD priority | CI | Notes | |----|-------------------|--------|--------------|----|-------| -| DGX OS (Spark) | Docker | Tested | P1 | Yes | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | +| DGX OS (Spark) | Docker | Tested | P1 | Yes | Use the standard installer and `$$nemoclaw onboard`. The automatic two-DGX Spark managed-vLLM profile is Experimental, and physical two-node end-to-end validation is pending. For the profile requirements and controls, see [Set Up vLLM on Two DGX Sparks](../inference/local-inference/set-up-vllm-on-two-dgx-sparks). For the validated single-DGX Spark walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | DGX OS (Station) | Docker | Tested with limitations | P1 | No | The PRD marks this platform as P1. Physical validation on one DGX Station GB300 covers generic Ubuntu 24.04 ARM64, stock DGX OS `7.5.0`, the April 2026 NVIDIA Colossus BaseOS profile, and the June 2026 NVIDIA AI Developer Tools profile. A physical no-OTA DGX OS `7.6.0` host provided the release and hardware profile used for its stable workstation-family classifier and passed read-only eligibility and runtime-command preflight. Full Station Express end-to-end qualification for the accepted no-OTA DGX OS `7.6.x` profile is pending. The profile remains subject to the same physical GB300, driver, ECC, Docker, CDI, and container GPU validation. Clean-host end-to-end validation passed on generic Ubuntu and Colossus BaseOS; stock DGX OS and AI Developer Tools completed Station Express validation. The DGX OS `7.5.0` run used released OpenShell `0.0.85`, local Nemotron Ultra serving, sandbox `cuInit(0)`, and a Hermes write/read file-tool task. A dual-Station configuration has not been validated, and dedicated CI coverage is not available. Direct-GPU policies expose only the exact read-only BDF directory for each discovered display-class PCI device with NVIDIA vendor ID (`0x10de`) and GB300 device ID (`0x31c2` or `0x31c3`) plus required existing topology and module paths; they do not expose `/sys`, the PCI parent subtree, or sysfs write access. During physical validation, reads of `/sys/fs/cgroup/cgroup.controllers` and `/sys/class/net/lo/address` remained denied. For canonical hardware qualification, image requirements, preparation, repair limits, reboot handoff, and the explicit temporary metadata override, see [Prepare DGX Station to Install NemoClaw](../get-started/additional-setup/dgx-station-preparation). | | Linux | Docker | Tested | P0 | Yes | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | | macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | P0 | Yes | Start the container runtime (Colima or Docker Desktop) before running the installer. When Homebrew is available, OpenShell uses its official formula and the gateway appears in `brew services list` as `openshell`; without Homebrew, NemoClaw uses the standalone OpenShell install and detached gateway fallback. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | diff --git a/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml new file mode 100644 index 00000000000..7cf41c71891 --- /dev/null +++ b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +apiVersion: nemoclaw.nvidia.com/managed-inference/v1 +kind: ServingPreset + +metadata: + id: vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731 + displayName: DeepSeek V4 Flash 0731 on two DGX Sparks + +spec: + selection: automatic + + requirements: + all: + - readiness: + scope: everyNode + kind: qualification + id: host.platform.dgx_spark + status: qualified + - fact: cluster.nodeCount + state: present + operator: equals + value: 2 + - topologyQualification: + id: dgx-spark.gb10.dual-cx7 + schemaVersion: 1 + status: qualified + + plan: + backend: vllm + recipeRef: vllm.deepseek-v4-flash-0731.spark-dual.v1 + bindings: + sparkTopology: + valueFromTopologyQualification: + id: dgx-spark.gb10.dual-cx7 + schemaVersion: 1 + output: topology diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml new file mode 100644 index 00000000000..46b2f783590 --- /dev/null +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -0,0 +1,123 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +apiVersion: nemoclaw.nvidia.com/managed-inference/v1 +kind: ServingRecipe + +metadata: + id: vllm.deepseek-v4-flash-0731.spark-dual.v1 + displayName: DeepSeek V4 Flash 0731 on two DGX Sparks + +spec: + backend: vllm + + bindings: + sparkTopology: + type: topologyQualificationOutput + qualificationId: dgx-spark.gb10.dual-cx7 + schemaVersion: 1 + outputSchema: nemoclaw.nvidia.com/dual-spark-topology/v1 + + model: + id: deepseek-ai/DeepSeek-V4-Flash-0731 + revision: 9e165c30e2704aec5d9d593cce3eebd58bbef1cb + servedName: deepseek-v4-flash-0731 + downloadSizeBytes: 166898661074 + preparationRef: deepseek-v4-flash-0731/v1 + encodingPath: encoding/encoding_dsv4.py + + runtime: + image: ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8 + imageDownloadSizeBytes: 9787537825 + architecture: arm64 + networkMode: host + ipcMode: host + sharedMemoryBytes: 68719476736 + devices: + - /dev/infiniband + environment: + CUTE_DSL_ARCH: sm_121a + DG_JIT_NVCC_COMPILER: /usr/local/cuda/bin/nvcc + DG_JIT_USE_NVRTC: "0" + FLASHINFER_CUDA_ARCH_LIST: 12.1a + FLASHINFER_DISABLE_VERSION_CHECK: "1" + FLASHINFER_WORKSPACE_BASE: /cache/huggingface/flashinfer + HF_HOME: /cache/huggingface + HF_HUB_DISABLE_XET: "1" + HF_HUB_OFFLINE: "1" + NCCL_CROSS_NIC: "1" + NCCL_CUMEM_ENABLE: "0" + NCCL_DEBUG: WARN + NCCL_IB_DISABLE: "0" + NCCL_IGNORE_CPU_AFFINITY: "1" + NCCL_NET: IB + NCCL_NVLS_ENABLE: "0" + PYTORCH_CUDA_ALLOC_CONF: expandable_segments:True + TILELANG_CLEANUP_TEMP_FILES: "1" + TORCH_CUDA_ARCH_LIST: 12.1a + TRANSFORMERS_OFFLINE: "1" + VLLM_ALLOW_LONG_MAX_MODEL_LEN: "1" + VLLM_B12X_W4A16_FORCE_BLOCKS_MAX_M: "16" + VLLM_B12X_W4A16_FORCE_BLOCKS_PER_SM: "0" + VLLM_CACHE_ROOT: /cache/huggingface/vllm-cache + VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS: "0" + VLLM_SPARSE_INDEXER_MAX_LOGITS_MB: "256" + VLLM_USE_B12X_MOE: "1" + VLLM_USE_BREAKABLE_CUDAGRAPH: "0" + VLLM_USE_FLASHINFER_SAMPLER: "1" + + execution: + materializerRef: vllm.dual-dgx-spark/v1 + lifecycleRef: vllm.dual-dgx-spark/v1 + topologyBinding: sparkTopology + nodeCount: 2 + tensorParallelSize: 2 + pipelineParallelSize: 1 + distributedExecutorBackend: mp + + serve: + authentication: bearer + arguments: + - name: --port + value: 8000 + - name: --trust-remote-code + - name: --kv-cache-dtype + value: nvfp4_ds_mla + - name: --block-size + value: 256 + - name: --max-model-len + value: 1048576 + - name: --max-num-seqs + value: 6 + - name: --max-num-batched-tokens + value: 8192 + - name: --max-cudagraph-capture-size + value: 36 + - name: --gpu-memory-utilization + value: 0.8 + - name: --enable-prefix-caching + - name: --enable-prompt-tokens-details + - name: --async-scheduling + - name: --enable-chunked-prefill + - name: --speculative-config + value: '{"method":"dspark","num_speculative_tokens":5,"draft_sample_method":"probabilistic"}' + - name: --tokenizer-mode + value: deepseek_v4 + - name: --moe-backend + value: flashinfer_b12x + - name: --tool-call-parser + value: deepseek_v4 + - name: --enable-auto-tool-choice + - name: --reasoning-parser + value: deepseek_v4 + - name: --reasoning-config + value: '{"reasoning_parser":"deepseek_v4","reasoning_start_str":"","reasoning_end_str":""}' + - name: --default-chat-template-kwargs + value: '{"thinking":true,"reasoning_effort":"low"}' + - name: --generation-config + value: vllm + - name: --enable-flashinfer-autotune + + readiness: + timeoutSeconds: 3600 + expectedModel: deepseek-v4-flash-0731 diff --git a/managed-inference/schemas/catalog.schema.json b/managed-inference/schemas/catalog.schema.json new file mode 100644 index 00000000000..49c9178f856 --- /dev/null +++ b/managed-inference/schemas/catalog.schema.json @@ -0,0 +1,70 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/catalog.schema.json", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "type": "object", + "required": ["catalogDigest", "compilerVersion", "presets", "recipes", "schemaVersion", "sourceFiles", "sourceRevision"], + "properties": { + "catalogDigest": { "$ref": "#/$defs/digest" }, + "compilerVersion": { "const": "1.0.0" }, + "presets": { + "type": "array", + "items": { + "allOf": [ + { "$ref": "#/$defs/compiledDefinition" }, + { + "type": "object", + "properties": { + "definition": { "$ref": "preset.schema.json" } + } + } + ] + } + }, + "recipes": { + "type": "array", + "items": { + "allOf": [ + { "$ref": "#/$defs/compiledDefinition" }, + { + "type": "object", + "properties": { + "definition": { "$ref": "recipe.schema.json" } + } + } + ] + } + }, + "schemaVersion": { "const": "1.0.0" }, + "sourceFiles": { + "type": "array", + "items": { + "type": "object", + "required": ["digest", "path"], + "properties": { + "digest": { "$ref": "#/$defs/digest" }, + "path": { "type": "string", "pattern": "^managed-inference/(?:presets|recipes)/[a-z0-9._-]+\\.yaml$" } + }, + "additionalProperties": false + } + }, + "sourceRevision": { "$ref": "#/$defs/digest" } + }, + "additionalProperties": false, + "$defs": { + "digest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "compiledDefinition": { + "type": "object", + "required": ["definition", "definitionDigest", "sourceFile"], + "properties": { + "definition": { "type": "object" }, + "definitionDigest": { "$ref": "#/$defs/digest" }, + "sourceFile": { "type": "string" } + }, + "additionalProperties": false + } + } +} diff --git a/managed-inference/schemas/preset.schema.json b/managed-inference/schemas/preset.schema.json new file mode 100644 index 00000000000..4618248dd6c --- /dev/null +++ b/managed-inference/schemas/preset.schema.json @@ -0,0 +1,134 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/preset.schema.json", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "type": "object", + "required": ["apiVersion", "kind", "metadata", "spec"], + "properties": { + "apiVersion": { "const": "nemoclaw.nvidia.com/managed-inference/v1" }, + "kind": { "const": "ServingPreset" }, + "metadata": { "$ref": "#/$defs/metadata" }, + "spec": { + "type": "object", + "required": ["selection", "requirements", "plan"], + "properties": { + "selection": { "const": "automatic" }, + "requirements": { + "type": "object", + "required": ["all"], + "properties": { + "all": { + "type": "array", + "minItems": 1, + "items": { + "oneOf": [ + { "$ref": "#/$defs/readinessRequirement" }, + { "$ref": "#/$defs/factRequirement" }, + { "$ref": "#/$defs/topologyRequirement" } + ] + } + } + }, + "additionalProperties": false + }, + "plan": { + "type": "object", + "required": ["backend", "recipeRef", "bindings"], + "properties": { + "backend": { "const": "vllm" }, + "recipeRef": { "$ref": "#/$defs/stableId" }, + "bindings": { + "type": "object", + "required": ["sparkTopology"], + "properties": { + "sparkTopology": { + "type": "object", + "required": ["valueFromTopologyQualification"], + "properties": { + "valueFromTopologyQualification": { + "type": "object", + "required": ["id", "schemaVersion", "output"], + "properties": { + "id": { "const": "dgx-spark.gb10.dual-cx7" }, + "schemaVersion": { "const": 1 }, + "output": { "const": "topology" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false, + "$defs": { + "metadata": { + "type": "object", + "required": ["id", "displayName"], + "properties": { + "id": { "$ref": "#/$defs/stableId" }, + "displayName": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + }, + "stableId": { + "type": "string", + "pattern": "^[a-z][a-z0-9]*(?:[._/-][a-z0-9]+)+$", + "maxLength": 160 + }, + "readinessRequirement": { + "type": "object", + "required": ["readiness"], + "properties": { + "readiness": { + "type": "object", + "required": ["scope", "kind", "id", "status"], + "properties": { + "scope": { "const": "everyNode" }, + "kind": { "const": "qualification" }, + "id": { "const": "host.platform.dgx_spark" }, + "status": { "const": "qualified" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "factRequirement": { + "type": "object", + "required": ["fact", "state", "operator", "value"], + "properties": { + "fact": { "const": "cluster.nodeCount" }, + "state": { "const": "present" }, + "operator": { "const": "equals" }, + "value": { "type": "integer", "minimum": 1 } + }, + "additionalProperties": false + }, + "topologyRequirement": { + "type": "object", + "required": ["topologyQualification"], + "properties": { + "topologyQualification": { + "type": "object", + "required": ["id", "schemaVersion", "status"], + "properties": { + "id": { "const": "dgx-spark.gb10.dual-cx7" }, + "schemaVersion": { "const": 1 }, + "status": { "const": "qualified" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + } +} diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json new file mode 100644 index 00000000000..a8ae01dd7ac --- /dev/null +++ b/managed-inference/schemas/recipe.schema.json @@ -0,0 +1,137 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/recipe.schema.json", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "type": "object", + "required": ["apiVersion", "kind", "metadata", "spec"], + "properties": { + "apiVersion": { "const": "nemoclaw.nvidia.com/managed-inference/v1" }, + "kind": { "const": "ServingRecipe" }, + "metadata": { "$ref": "#/$defs/metadata" }, + "spec": { + "type": "object", + "required": ["backend", "bindings", "model", "runtime", "execution", "serve", "readiness"], + "properties": { + "backend": { "const": "vllm" }, + "bindings": { + "type": "object", + "required": ["sparkTopology"], + "properties": { + "sparkTopology": { + "type": "object", + "required": ["type", "qualificationId", "schemaVersion", "outputSchema"], + "properties": { + "type": { "const": "topologyQualificationOutput" }, + "qualificationId": { "const": "dgx-spark.gb10.dual-cx7" }, + "schemaVersion": { "const": 1 }, + "outputSchema": { "const": "nemoclaw.nvidia.com/dual-spark-topology/v1" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "model": { + "type": "object", + "required": ["id", "revision", "servedName", "downloadSizeBytes", "preparationRef", "encodingPath"], + "properties": { + "id": { "type": "string", "pattern": "^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$" }, + "revision": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "servedName": { "$ref": "#/$defs/stableId" }, + "downloadSizeBytes": { "type": "integer", "minimum": 1 }, + "preparationRef": { "const": "deepseek-v4-flash-0731/v1" }, + "encodingPath": { "const": "encoding/encoding_dsv4.py" } + }, + "additionalProperties": false + }, + "runtime": { + "type": "object", + "required": ["image", "imageDownloadSizeBytes", "architecture", "networkMode", "ipcMode", "sharedMemoryBytes", "devices", "environment"], + "properties": { + "image": { "type": "string", "pattern": "^[a-z0-9.-]+(?:/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$" }, + "imageDownloadSizeBytes": { "type": "integer", "minimum": 1 }, + "architecture": { "const": "arm64" }, + "networkMode": { "const": "host" }, + "ipcMode": { "const": "host" }, + "sharedMemoryBytes": { "type": "integer", "minimum": 1 }, + "devices": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { "type": "string", "pattern": "^/dev/[A-Za-z0-9._/-]+$" } + }, + "environment": { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[A-Z][A-Z0-9_]*$" }, + "additionalProperties": { "type": "string", "maxLength": 1024 } + } + }, + "additionalProperties": false + }, + "execution": { + "type": "object", + "required": ["materializerRef", "lifecycleRef", "topologyBinding", "nodeCount", "tensorParallelSize", "pipelineParallelSize", "distributedExecutorBackend"], + "properties": { + "materializerRef": { "const": "vllm.dual-dgx-spark/v1" }, + "lifecycleRef": { "const": "vllm.dual-dgx-spark/v1" }, + "topologyBinding": { "const": "sparkTopology" }, + "nodeCount": { "const": 2 }, + "tensorParallelSize": { "const": 2 }, + "pipelineParallelSize": { "const": 1 }, + "distributedExecutorBackend": { "const": "mp" } + }, + "additionalProperties": false + }, + "serve": { + "type": "object", + "required": ["authentication", "arguments"], + "properties": { + "authentication": { "const": "bearer" }, + "arguments": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["name"], + "properties": { + "name": { "type": "string", "pattern": "^--[a-z0-9]+(?:-[a-z0-9]+)*$" }, + "value": { "type": ["string", "number", "boolean"] } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + }, + "readiness": { + "type": "object", + "required": ["timeoutSeconds", "expectedModel"], + "properties": { + "timeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 7200 }, + "expectedModel": { "$ref": "#/$defs/stableId" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false, + "$defs": { + "metadata": { + "type": "object", + "required": ["id", "displayName"], + "properties": { + "id": { "const": "vllm.deepseek-v4-flash-0731.spark-dual.v1" }, + "displayName": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + }, + "stableId": { + "type": "string", + "pattern": "^[a-z][a-z0-9]*(?:[._/-][a-z0-9]+)+$", + "maxLength": 160 + } + } +} diff --git a/package.json b/package.json index 92b617dee5c..434e74223de 100644 --- a/package.json +++ b/package.json @@ -55,7 +55,9 @@ "check:installer-hash": "bash scripts/check-installer-hash.sh", "typecheck": "tsc -p jsconfig.json", "build:policy-boundary": "tsc -p nemoclaw/tsconfig.shared.json", - "build:cli": "npm run build:policy-boundary && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", + "catalog:compile": "tsx scripts/managed-inference/compile-catalog.mts --write", + "catalog:check": "tsx scripts/managed-inference/compile-catalog.mts", + "build:cli": "npm run catalog:check && npm run build:policy-boundary && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", "clean:cli": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", "typecheck:cli": "tsc -p tsconfig.cli.json", "validate:configs": "tsx scripts/validate-configs.mts", @@ -115,6 +117,7 @@ "nemoclaw/openclaw.plugin.json", "nemoclaw/package.json", "nemoclaw-blueprint/", + "managed-inference/", "schemas/network-policy.schema.json", "schemas/sandbox-policy.schema.json", "scripts/", diff --git a/scripts/install.sh b/scripts/install.sh index a34dba8d1a7..23b415f48d9 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -4512,10 +4512,11 @@ describe_express_install() { "DGX Spark") if [ -n "${NEMOCLAW_VLLM_MODEL:-}" ]; then inference_summary="managed local vLLM with model ${NEMOCLAW_VLLM_MODEL}" + inference_disclosure="The explicit model remains authoritative, so this run keeps the existing single-Spark profile. Managed vLLM pulls the configured image/model and runs only its dedicated container." else - inference_summary="managed local vLLM using the DGX Spark profile default model" + inference_summary="managed vLLM with automatic DGX Spark serving-profile selection" + inference_disclosure="With no explicit inference intent or related runtime, one exactly qualified pretrusted two-Spark topology selects the pinned distributed profile. An ordinary no-match keeps the existing single-Spark profile; any related or ambiguous setup remains untouched and stops installation. Managed vLLM pulls the selected image/model and runs only its dedicated containers. The two-Spark profile is experimental pending physical end-to-end validation." fi - inference_disclosure="Managed vLLM pulls the configured vLLM image/model and runs a local vLLM inference container." sandbox_summary="${NEMOCLAW_SANDBOX_NAME:-my-assistant}" ;; "DGX Station") diff --git a/scripts/managed-inference/compile-catalog.mts b/scripts/managed-inference/compile-catalog.mts new file mode 100644 index 00000000000..763b4b9862f --- /dev/null +++ b/scripts/managed-inference/compile-catalog.mts @@ -0,0 +1,312 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import Ajv2020, { type AnySchema, type ValidateFunction } from "ajv/dist/2020.js"; +import { parseDocument } from "yaml"; + +import catalogSchema from "../../managed-inference/schemas/catalog.schema.json" with { + type: "json", +}; +import presetSchema from "../../managed-inference/schemas/preset.schema.json" with { type: "json" }; +import recipeSchema from "../../managed-inference/schemas/recipe.schema.json" with { type: "json" }; +import * as catalogIntegrityModule from "../../src/lib/inference/serving/catalog-integrity.ts"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, +} from "../../src/lib/inference/serving/catalog-types.ts"; +import * as catalogTypesModule from "../../src/lib/inference/serving/catalog-types.ts"; + +const compatibleCatalogIntegrityModule = catalogIntegrityModule as unknown as { + default?: typeof catalogIntegrityModule; +}; +const { canonicalManagedInferenceJson, managedInferenceDigest, managedInferenceTextDigest } = + compatibleCatalogIntegrityModule.default ?? catalogIntegrityModule; +const compatibleCatalogTypesModule = catalogTypesModule as unknown as { + default?: typeof catalogTypesModule; +}; +const { + DUAL_SPARK_PRESET_ID, + DUAL_SPARK_RECIPE_ID, + DUAL_SPARK_RECIPE_SPEC_DIGEST, + isManagedInferenceMaterializerOwnedArgument, + MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, + MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, +} = compatibleCatalogTypesModule.default ?? catalogTypesModule; + +const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; +const GENERATED_CATALOG_PATH = "src/lib/inference/serving/generated/catalog.json"; +const RECIPE_SCHEMA_ID = recipeSchema.$id; +const PRESET_SCHEMA_ID = presetSchema.$id; +const SHA256 = /^sha256:[0-9a-f]{64}$/u; + +export interface ManagedInferenceCatalogSource { + readonly path: string; + readonly contents: string; +} + +export interface CompiledManagedInferenceCatalogResult { + readonly catalog: CompiledManagedInferenceCatalog; + readonly json: string; +} + +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function validationError(label: string, validate: ValidateFunction): Error { + const details = validate.errors + ?.map((error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`) + .join("; "); + return new Error(`${label} failed schema validation${details ? `: ${details}` : ""}`); +} + +function parseYamlSource(source: ManagedInferenceCatalogSource): unknown { + const document = parseDocument(source.contents, { + schema: "core", + strict: true, + uniqueKeys: true, + }); + if (document.errors.length > 0) { + throw new Error( + `${source.path} is invalid YAML: ${document.errors[0]?.message ?? "parse failed"}`, + ); + } + try { + return document.toJS({ maxAliasCount: 0 }); + } catch (error) { + throw new Error( + `${source.path} is invalid YAML: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} + +function createValidators(): { + validateCatalog: ValidateFunction; + validatePreset: ValidateFunction; + validateRecipe: ValidateFunction; +} { + const ajv = new Ajv2020({ allErrors: true, allowUnionTypes: true, strict: true }); + ajv.addSchema(recipeSchema as AnySchema); + ajv.addSchema(presetSchema as AnySchema); + const validateRecipe = ajv.getSchema(RECIPE_SCHEMA_ID); + const validatePreset = ajv.getSchema(PRESET_SCHEMA_ID); + if (!validateRecipe || !validatePreset) throw new Error("managed inference schemas did not load"); + return { + validateCatalog: ajv.compile(catalogSchema as AnySchema), + validatePreset, + validateRecipe, + }; +} + +function validateRecipeSemantics(recipe: ManagedInferenceServingRecipe): void { + if (recipe.metadata.id !== DUAL_SPARK_RECIPE_ID) { + throw new Error(`unsupported serving recipe ${recipe.metadata.id}`); + } + if (!SHA256.test(recipe.spec.runtime.image.slice(recipe.spec.runtime.image.indexOf("@") + 1))) { + throw new Error(`${recipe.metadata.id} must pin its runtime image by sha256 digest`); + } + const seenArguments = new Set(); + for (const argument of recipe.spec.serve.arguments) { + if (seenArguments.has(argument.name)) { + throw new Error(`${recipe.metadata.id} contains duplicate serving argument ${argument.name}`); + } + if (isManagedInferenceMaterializerOwnedArgument(argument.name)) { + throw new Error(`${recipe.metadata.id} assigns materializer-owned argument ${argument.name}`); + } + seenArguments.add(argument.name); + } + if (managedInferenceDigest(recipe.spec) !== DUAL_SPARK_RECIPE_SPEC_DIGEST) { + throw new Error(`${recipe.metadata.id} contract changed without a new recipe ID`); + } +} + +function validatePresetSemantics( + preset: ManagedInferenceServingPreset, + recipes: ReadonlyMap, +): void { + if (preset.metadata.id !== DUAL_SPARK_PRESET_ID) { + throw new Error(`unsupported serving preset ${preset.metadata.id}`); + } + if (preset.spec.selection !== "automatic") { + throw new Error(`${preset.metadata.id} must remain an automatic preset`); + } + const recipe = recipes.get(preset.spec.plan.recipeRef); + if (!recipe) + throw new Error( + `${preset.metadata.id} references unknown recipe ${preset.spec.plan.recipeRef}`, + ); + if (recipe.spec.backend !== preset.spec.plan.backend) { + throw new Error(`${preset.metadata.id} backend does not match its recipe`); + } + + const readinessRequirements = preset.spec.requirements.all.filter( + (requirement) => "readiness" in requirement, + ); + const nodeCountRequirements = preset.spec.requirements.all.filter( + (requirement) => "fact" in requirement, + ); + const topologyRequirements = preset.spec.requirements.all.filter( + (requirement) => "topologyQualification" in requirement, + ); + if ( + readinessRequirements.length !== 1 || + readinessRequirements[0]?.readiness.status !== "qualified" + ) { + throw new Error( + `${preset.metadata.id} must require qualified DGX Spark readiness on every node`, + ); + } + if ( + nodeCountRequirements.length !== 1 || + nodeCountRequirements[0]?.state !== "present" || + nodeCountRequirements[0]?.value !== recipe.spec.execution.nodeCount + ) { + throw new Error(`${preset.metadata.id} must require the recipe's exact node count`); + } + const topology = topologyRequirements[0]?.topologyQualification; + const recipeTopology = recipe.spec.bindings.sparkTopology; + if ( + topologyRequirements.length !== 1 || + topology?.status !== "qualified" || + topology.id !== recipeTopology.qualificationId || + topology.schemaVersion !== recipeTopology.schemaVersion + ) { + throw new Error(`${preset.metadata.id} topology requirement does not match its recipe binding`); + } +} + +function sortedJson(value: unknown): unknown { + return JSON.parse(canonicalManagedInferenceJson(value)); +} + +export function compileManagedInferenceCatalogSources( + sources: readonly ManagedInferenceCatalogSource[], +): CompiledManagedInferenceCatalogResult { + const sortedSources = [...sources].sort((left, right) => compareStrings(left.path, right.path)); + if (new Set(sortedSources.map((source) => source.path)).size !== sortedSources.length) { + throw new Error("managed inference catalog contains a duplicate source path"); + } + const { validateCatalog, validatePreset, validateRecipe } = createValidators(); + const recipes: { + definition: ManagedInferenceServingRecipe; + definitionDigest: string; + sourceFile: string; + }[] = []; + const presets: { + definition: ManagedInferenceServingPreset; + definitionDigest: string; + sourceFile: string; + }[] = []; + + for (const source of sortedSources) { + if (!/^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u.test(source.path)) { + throw new Error(`unsupported managed inference source path ${source.path}`); + } + const parsed = parseYamlSource(source); + const kind = + typeof parsed === "object" && parsed !== null + ? (parsed as { readonly kind?: unknown }).kind + : undefined; + if (kind === "ServingRecipe") { + if (!source.path.startsWith("managed-inference/recipes/") || !validateRecipe(parsed)) { + throw validationError(source.path, validateRecipe); + } + recipes.push({ + definition: parsed as ManagedInferenceServingRecipe, + definitionDigest: managedInferenceDigest(parsed), + sourceFile: source.path, + }); + } else if (kind === "ServingPreset") { + if (!source.path.startsWith("managed-inference/presets/") || !validatePreset(parsed)) { + throw validationError(source.path, validatePreset); + } + presets.push({ + definition: parsed as ManagedInferenceServingPreset, + definitionDigest: managedInferenceDigest(parsed), + sourceFile: source.path, + }); + } else { + throw new Error(`${source.path} has unsupported kind ${String(kind)}`); + } + } + + if (recipes.length !== 1 || presets.length !== 1) { + throw new Error("managed inference catalog v1 requires exactly one recipe and one preset"); + } + for (const { definition } of recipes) validateRecipeSemantics(definition); + const recipesById = new Map( + recipes.map(({ definition }) => [definition.metadata.id, definition]), + ); + for (const { definition } of presets) validatePresetSemantics(definition, recipesById); + + const sourceFiles = sortedSources.map((source) => ({ + digest: managedInferenceTextDigest(source.contents), + path: source.path, + })); + const withoutDigest = { + compilerVersion: MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, + presets, + recipes, + schemaVersion: MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, + sourceFiles, + sourceRevision: managedInferenceDigest(sourceFiles), + } as const; + const catalog = sortedJson({ + ...withoutDigest, + catalogDigest: managedInferenceDigest(withoutDigest), + }) as CompiledManagedInferenceCatalog; + if (!validateCatalog(catalog)) + throw validationError("compiled managed inference catalog", validateCatalog); + return { catalog, json: `${JSON.stringify(catalog, null, 2)}\n` }; +} + +function readCatalogSources(repositoryRoot: string): ManagedInferenceCatalogSource[] { + return SOURCE_DIRECTORIES.flatMap((directory) => { + const absoluteDirectory = path.join(repositoryRoot, directory); + return fs + .readdirSync(absoluteDirectory, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".yaml")) + .map((entry) => { + const sourcePath = `${directory}/${entry.name}`; + return { + path: sourcePath, + contents: fs.readFileSync(path.join(repositoryRoot, sourcePath), "utf8"), + }; + }); + }); +} + +export function compileManagedInferenceCatalog( + repositoryRoot = REPOSITORY_ROOT, +): CompiledManagedInferenceCatalogResult { + return compileManagedInferenceCatalogSources(readCatalogSources(repositoryRoot)); +} + +function main(): void { + const unknownArguments = process.argv.slice(2).filter((argument) => argument !== "--write"); + if (unknownArguments.length > 0) throw new Error(`unknown argument ${unknownArguments[0]}`); + const { json } = compileManagedInferenceCatalog(); + const outputPath = path.join(REPOSITORY_ROOT, GENERATED_CATALOG_PATH); + if (process.argv.includes("--write")) { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, json, "utf8"); + return; + } + const current = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : ""; + if (current !== json) throw new Error(`${GENERATED_CATALOG_PATH} is stale; rerun with --write`); +} + +if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index 3570e727f3c..20ed99298fc 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -40,12 +40,15 @@ function okWithKnownGatewayList(command: string, args: readonly string[]): RunRe : ok(); } -describe("dual-Station runtime uninstall", () => { - it("removes a managed pair before the remaining full-uninstall steps", () => { +describe("managed distributed vLLM runtime uninstall", () => { + it.each([ + "dual-station-vllm-runtime.json", + "dual-spark-vllm-runtime.json", + ])("removes the pair owned by %s before the remaining full-uninstall steps", (receiptFile) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-pair-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); - fs.writeFileSync(path.join(stateDir, "dual-station-vllm-runtime.json"), "{}\n", { + fs.writeFileSync(path.join(stateDir, receiptFile), "{}\n", { mode: 0o600, }); const runDualStationRuntimeCleanup = vi.fn(() => ok()); @@ -79,6 +82,45 @@ describe("dual-Station runtime uninstall", () => { } }); + it("targets the exact Station receipt found under a stale non-default gateway root", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-stale-station-")); + const receiptPath = path.join( + home, + ".nemoclaw", + "gateways", + "18080", + "dual-station-vllm-runtime.json", + ); + fs.mkdirSync(path.dirname(receiptPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync(receiptPath, "{}\n", { mode: 0o600 }); + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync: vi.fn(), + run: okWithKnownGatewayList, + runDocker: () => ok(), + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(0); + expect(runDualStationRuntimeCleanup).toHaveBeenCalledWith( + receiptPath, + expect.objectContaining({ stdio: "inherit" }), + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("does not start the remaining uninstall steps when managed pair cleanup fails", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-fail-")); const stateDir = path.join(home, ".nemoclaw"); @@ -115,9 +157,154 @@ describe("dual-Station runtime uninstall", () => { expect(rmSync).not.toHaveBeenCalled(); expect(runDocker).not.toHaveBeenCalled(); expect(errors).toContain( - "Managed dual-Station cleanup did not complete. NemoClaw did not start the remaining uninstall steps. Resolve the reported cleanup error and retry uninstall.", + "Managed distributed vLLM cleanup did not complete. NemoClaw did not start the remaining uninstall steps. Resolve the reported cleanup error and retry uninstall.", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("refuses ambiguous Spark and Station receipts before cleanup or other mutation", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-conflict-")); + const stateDir = path.join(home, ".nemoclaw"); + fs.mkdirSync(stateDir, { mode: 0o700 }); + for (const name of ["dual-spark-vllm-runtime.json", "dual-station-vllm-runtime.json"]) { + fs.writeFileSync(path.join(stateDir, name), "{}\n", { mode: 0o600 }); + } + const errors: string[] = []; + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + const runDocker = vi.fn(() => ok()); + const rmSync = vi.fn(); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + error: (message) => errors.push(message), + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync, + run: okWithKnownGatewayList, + runDocker, + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(1); + expect(runDualStationRuntimeCleanup).not.toHaveBeenCalled(); + expect(runDocker).not.toHaveBeenCalled(); + expect(rmSync).not.toHaveBeenCalled(); + expect(errors).toContain( + "Both dual-Spark and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each([ + "dual-spark-vllm-runtime.json", + "dual-spark-managed-serving.json", + "dual-station-vllm-runtime.json", + ])("refuses an orphaned %s SSH binding before cleanup or other mutation", (receiptFile) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-binding-orphan-")); + const stateDir = path.join(home, ".nemoclaw"); + const bindingPath = path.join(stateDir, `${receiptFile}.ssh-binding`); + fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); + const errors: string[] = []; + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + const runDocker = vi.fn(() => ok()); + const rmSync = vi.fn(); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + error: (message) => errors.push(message), + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync, + run: okWithKnownGatewayList, + runDocker, + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(1); + expect(runDualStationRuntimeCleanup).not.toHaveBeenCalled(); + expect(runDocker).not.toHaveBeenCalled(); + expect(rmSync).not.toHaveBeenCalled(); + expect(errors.join("\n")).toContain( + "Managed distributed vLLM SSH binding exists without its ownership receipt", + ); + expect(fs.existsSync(bindingPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it("finds the host-global Spark receipt from a non-default gateway selection", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-global-")); + const stateDir = path.join(home, ".nemoclaw"); + fs.mkdirSync(stateDir, { mode: 0o700 }); + fs.writeFileSync(path.join(stateDir, "dual-spark-vllm-runtime.json"), "{}\n", { + mode: 0o600, + }); + fs.mkdirSync(path.join(stateDir, "dual-spark-vllm-runtime.json.ssh-binding"), { + mode: 0o700, + }); + fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${"a".repeat(64)}\n`, { + mode: 0o600, + }); + fs.mkdirSync(path.join(stateDir, "state", "mcp-lifecycle-locks"), { + recursive: true, + mode: 0o700, + }); + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + + try { + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); + vi.resetModules(); + const { runUninstallPlan: runFreshUninstallPlan } = await import("./run-plan"); + const result = runFreshUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home, NEMOCLAW_GATEWAY_PORT: "18080" }, + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync: vi.fn(), + run: (command, args) => + command === "openshell" && args[0] === "gateway" && args[1] === "list" + ? ok(JSON.stringify([{ name: "nemoclaw-18080" }])) + : ok(), + runDocker: () => ok(), + runDualStationRuntimeCleanup, + resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({ + gatewayName, + gatewayPort, + mode: "nemoclaw-managed", + source: "standalone", + endpoint: null, + stateDir: null, + supervisor: null, + requiredCapabilities: [], + }), + }, ); + + expect(result.exitCode).toBe(0); + expect(runDualStationRuntimeCleanup).toHaveBeenCalledOnce(); } finally { + vi.unstubAllEnvs(); + vi.resetModules(); fs.rmSync(home, { recursive: true, force: true }); } }); diff --git a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts index 245af303be7..3e157881a4f 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts @@ -1072,11 +1072,15 @@ describe("uninstall gateway-port segregation (#3053)", () => { }, }), ); - const runtimeReceipt = path.join(stateDir, "dual-station-vllm-runtime.json"); + const runtimeReceipt = path.join(stateDir, "dual-spark-vllm-runtime.json"); const runtimeBinding = `${runtimeReceipt}.ssh-binding`; + const discoveryBinding = path.join(stateDir, "dual-spark-managed-serving.json.ssh-binding"); + const managedApiKey = path.join(stateDir, "dual-station-vllm-api-key"); fs.writeFileSync(runtimeReceipt, "{}\n", { mode: 0o600 }); fs.mkdirSync(runtimeBinding, { mode: 0o700 }); + fs.mkdirSync(discoveryBinding, { mode: 0o700 }); fs.writeFileSync(path.join(runtimeBinding, "known_hosts"), "host-key\n", { mode: 0o600 }); + fs.writeFileSync(managedApiKey, `${"a".repeat(64)}\n`, { mode: 0o600 }); const logs: string[] = []; const openshellCalls: string[][] = []; const result = runUninstallPlan( @@ -1102,6 +1106,8 @@ describe("uninstall gateway-port segregation (#3053)", () => { expect(logs.join("\n")).toContain("Sibling gateways remain"); expect(fs.existsSync(runtimeReceipt)).toBe(true); expect(fs.existsSync(runtimeBinding)).toBe(true); + expect(fs.existsSync(discoveryBinding)).toBe(true); + expect(fs.existsSync(managedApiKey)).toBe(true); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index c87a4d560e3..2b4e00b7a8f 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -27,7 +27,14 @@ import { } from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { isOllamaAuthProxyCommandLine } from "../../inference/ollama/process"; -import { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../../inference/vllm-station-runtime-receipt-path"; +import { + DUAL_SPARK_MANAGED_SERVING_STATE_FILE, + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, + DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, + findManagedDistributedVllmRuntimeReceipts, + MANAGED_VLLM_API_KEY_FILE, + MCP_LIFECYCLE_LOCK_DIRNAME, +} from "../../inference/serving/managed-runtime-receipts"; import { buildDockerGatewayDebEnvFile } from "../../onboard/docker-driver-gateway-env"; import { getNemoclawOpenShellGatewayUserServicePath, @@ -89,7 +96,7 @@ export interface UninstallRunDeps { rmSync?: typeof fs.rmSync; run?: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; runDocker?: (args: string[], options?: SpawnSyncOptions) => RunResult; - runDualStationRuntimeCleanup?: (options?: SpawnSyncOptions) => RunResult; + runDualStationRuntimeCleanup?: (receiptPath: string, options?: SpawnSyncOptions) => RunResult; } export interface UninstallRunOutcome { @@ -251,9 +258,29 @@ const SHARED_HOST_STATE_ENTRIES = new Set([ "source", GATEWAYS_SUBDIR, "managed_swap", + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, + `${DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, + `${DUAL_SPARK_MANAGED_SERVING_STATE_FILE}.ssh-binding`, + MANAGED_VLLM_API_KEY_FILE, ...HTTPS_PIN_RUNTIME_ADAPTER_STATE_ENTRIES, ]); +function dormantHostGlobalLifecycleState(sharedRoot: string): boolean { + const stateDir = path.join(sharedRoot, "state"); + try { + const state = fs.lstatSync(stateDir); + if (state.isSymbolicLink() || !state.isDirectory()) return false; + const entries = fs.readdirSync(stateDir); + if (entries.length === 0) return true; + if (entries.length !== 1 || entries[0] !== MCP_LIFECYCLE_LOCK_DIRNAME) return false; + const locksDir = path.join(stateDir, MCP_LIFECYCLE_LOCK_DIRNAME); + const locks = fs.lstatSync(locksDir); + return !locks.isSymbolicLink() && locks.isDirectory() && fs.readdirSync(locksDir).length === 0; + } catch { + return false; + } +} + function removePathExcept( target: string, preserve: readonly string[], @@ -339,7 +366,7 @@ interface UninstallRuntime { rmSync: typeof fs.rmSync; run: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; runDocker: (args: string[], options?: SpawnSyncOptions) => RunResult; - runDualStationRuntimeCleanup: (options?: SpawnSyncOptions) => RunResult; + runDualStationRuntimeCleanup: (receiptPath: string, options?: SpawnSyncOptions) => RunResult; warn: (message: string) => void; } @@ -375,7 +402,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { runDocker: deps.runDocker ?? defaultRunDocker, runDualStationRuntimeCleanup: deps.runDualStationRuntimeCleanup ?? - ((options = {}) => + ((receiptPath, options = {}) => defaultRun( process.execPath, [ @@ -386,6 +413,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { "inference", "vllm-station-runtime-cleanup-entry.js", ), + receiptPath, ], options, )), @@ -1205,25 +1233,52 @@ function dockerIsAvailable(runtime: UninstallRuntime): boolean { return true; } -function removeManagedDualStationRuntime( - paths: UninstallPaths, - runtime: UninstallRuntime, -): boolean { - const receiptPath = path.join(paths.nemoclawStateDir, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE); +function removeManagedDistributedVllmRuntime(runtime: UninstallRuntime): boolean { + let state: ReturnType; try { - fs.lstatSync(receiptPath); + state = findManagedDistributedVllmRuntimeReceipts({ + homeDir: runtime.env.HOME || os.homedir(), + }); } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; - runtime.error(`Could not inspect managed dual-Station rollback state: ${formatError(error)}`); + runtime.error( + `Could not inspect managed distributed vLLM rollback state: ${formatError(error)}`, + ); return false; } - const result = runtime.runDualStationRuntimeCleanup({ + const receipts = [...(state.sparkPath ? [state.sparkPath] : []), ...state.stationPaths]; + const bindingPaths = [ + ...(state.sparkBindingPath ? [state.sparkBindingPath] : []), + ...state.sparkDiscoveryBindingPaths, + ...state.stationBindingPaths, + ]; + const expectedBindingPaths = new Set(receipts.map((receiptPath) => `${receiptPath}.ssh-binding`)); + const orphanBinding = bindingPaths.find((bindingPath) => !expectedBindingPaths.has(bindingPath)); + if (orphanBinding) { + runtime.error( + `Managed distributed vLLM SSH binding exists without its ownership receipt at ${orphanBinding}. NemoClaw refused uninstall before making changes. Recover or remove that state explicitly, then retry.`, + ); + return false; + } + if (receipts.length === 0) return true; + if (state.sparkPath && state.stationPaths.length > 0) { + runtime.error( + "Both dual-Spark and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", + ); + return false; + } + if (receipts.length !== 1) { + runtime.error( + "Multiple managed distributed vLLM runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", + ); + return false; + } + const result = runtime.runDualStationRuntimeCleanup(receipts[0]!, { env: runtime.env, stdio: "inherit", }); if (result.status === 0) return true; runtime.error( - "Managed dual-Station cleanup did not complete. NemoClaw did not start the remaining uninstall steps. Resolve the reported cleanup error and retry uninstall.", + "Managed distributed vLLM cleanup did not complete. NemoClaw did not start the remaining uninstall steps. Resolve the reported cleanup error and retry uninstall.", ); return false; } @@ -1378,7 +1433,15 @@ function inspectOtherGatewayEnvironments( if (!selectedIsDefault && pathEntryExists(sharedRoot, runtime)) { try { - if (fs.readdirSync(sharedRoot).some((entry) => !SHARED_HOST_STATE_ENTRIES.has(entry))) { + if ( + fs + .readdirSync(sharedRoot) + .some( + (entry) => + !SHARED_HOST_STATE_ENTRIES.has(entry) && + !(entry === "state" && dormantHostGlobalLifecycleState(sharedRoot)), + ) + ) { return { otherGatewayEnvironmentsRemain: true, sharedRegistryMustBePreserved: false, @@ -1553,7 +1616,7 @@ function executePlan( for (const [index, step] of plan.steps.entries()) { runtime.log(`[${index + 1}/${plan.steps.length}] ${planStepDisplayName(step.name, branding)}`); if (step.name === "Stopping services") { - if (!scopedToSelectedGateway && !removeManagedDualStationRuntime(paths, runtime)) { + if (!scopedToSelectedGateway && !removeManagedDistributedVllmRuntime(runtime)) { return { ok: false }; } if ( @@ -1745,8 +1808,12 @@ function executePlan( ...(scopedToSelectedGateway ? [ ...HTTPS_PIN_RUNTIME_ADAPTER_STATE_ENTRIES, + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, + `${DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, + `${DUAL_SPARK_MANAGED_SERVING_STATE_FILE}.ssh-binding`, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, `${DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, + MANAGED_VLLM_API_KEY_FILE, ] : []), ], diff --git a/src/lib/inference/context-window.ts b/src/lib/inference/context-window.ts index 433a091814e..b18cbf4952b 100644 --- a/src/lib/inference/context-window.ts +++ b/src/lib/inference/context-window.ts @@ -13,7 +13,7 @@ import { DEFAULT_CONTEXT_WINDOW } from "./config"; import { getLocalProviderHealthEndpoint, - getManagedDualStationVllmProviderBinding, + getManagedVllmProviderBinding, getOllamaWarmupCommand, probeVllmModels, type RunCaptureFn, @@ -46,9 +46,9 @@ const defaultContextWindowDeps: ContextWindowDeps = { probeVllmContextWindow: (model: string): number | null => { // Same source onboard uses: GET /v1/models on the host vLLM server and read // max_model_len (handles both NemoClaw-launched and bring-your-own vLLM). - let managedBinding: ReturnType; + let managedBinding: ReturnType; try { - managedBinding = getManagedDualStationVllmProviderBinding(); + managedBinding = getManagedVllmProviderBinding(); } catch { return null; } diff --git a/src/lib/inference/local-vllm-auth.test.ts b/src/lib/inference/local-vllm-auth.test.ts index 4c8390143a5..39d25e8004f 100644 --- a/src/lib/inference/local-vllm-auth.test.ts +++ b/src/lib/inference/local-vllm-auth.test.ts @@ -14,10 +14,23 @@ interface ManagedBaseUrlOverrides { const lifecycle = vi.hoisted(() => ({ baseUrl: vi.fn<(overrides?: ManagedBaseUrlOverrides) => string | null>(), })); +const sparkRecovery = vi.hoisted(() => ({ + endpoint: vi.fn(), +})); +const managedKey = vi.hoisted(() => ({ + load: vi.fn(), +})); vi.mock("./vllm-station-cluster-lifecycle", () => ({ getDualStationManagedVllmBaseUrl: lifecycle.baseUrl, })); +vi.mock("./serving/spark-runtime-receipt", () => ({ + recoverInstalledDualSparkVllmEndpoint: sparkRecovery.endpoint, +})); +vi.mock("./vllm-api-key", async (importOriginal) => ({ + ...(await importOriginal()), + loadManagedVllmApiKey: managedKey.load, +})); import { CONTAINER_REACHABILITY_IMAGE, @@ -25,8 +38,8 @@ import { getLocalProviderContainerReachabilityCheck, getLocalProviderHealthCheck, getLocalProviderHealthEndpoint, - getManagedDualStationVllmProviderBinding, - getManagedDualStationVllmProviderState, + getManagedVllmProviderBinding, + getManagedVllmProviderState, LOCAL_INFERENCE_SANDBOX_HOST_URL_ENV, probeLocalProviderHealth, probeVllmModels, @@ -80,6 +93,10 @@ function productionManagedBaseUrlResolver( beforeEach(() => { vi.stubEnv(LOCAL_INFERENCE_SANDBOX_HOST_URL_ENV, undefined); + sparkRecovery.endpoint.mockReset(); + sparkRecovery.endpoint.mockReturnValue(null); + managedKey.load.mockReset(); + managedKey.load.mockReturnValue(API_KEY); lifecycle.baseUrl.mockReset(); lifecycle.baseUrl.mockImplementation( (overrides) => MANAGED_BASE_URL_BY_API_KEY.get(overrides?.loadApiKey?.()) ?? null, @@ -88,19 +105,68 @@ beforeEach(() => { afterEach(() => vi.unstubAllEnvs()); -describe("managed dual-Station vLLM authentication", () => { +describe("managed vLLM authentication", () => { it("keeps an explicit sandbox host override ahead of managed endpoint recovery", () => { const loadApiKeyImpl = vi.fn(() => API_KEY); expect(getLocalProviderBaseUrl("vllm-local", { hostUrl: "http://explicit-host" })).toBe( "http://explicit-host:8000/v1", ); expect( - getManagedDualStationVllmProviderBinding({ + getManagedVllmProviderBinding({ hostUrl: "http://explicit-host", loadApiKeyImpl, }), ).toBeNull(); expect(loadApiKeyImpl).not.toHaveBeenCalled(); + expect(sparkRecovery.endpoint).not.toHaveBeenCalled(); + }); + + it("recovers a receipt-owned Spark endpoint before checking Station state", () => { + const events: string[] = []; + const recoverSparkVllmEndpointImpl = vi.fn(() => { + events.push("spark"); + return { baseUrl: BASE_URL, apiKey: API_KEY }; + }); + const getManagedBaseUrlImpl = vi.fn(() => { + events.push("station"); + return null; + }); + + expect( + getManagedVllmProviderBinding({ + getManagedBaseUrlImpl, + recoverSparkVllmEndpointImpl, + }), + ).toEqual({ baseUrl: `${BASE_URL}/v1`, apiKey: API_KEY }); + expect(events).toEqual(["spark", "station"]); + }); + + it("does not fall through to Station when Spark recovery is unsafe", () => { + const getManagedBaseUrlImpl = vi.fn(() => BASE_URL); + + expect(() => + getManagedVllmProviderBinding({ + getManagedBaseUrlImpl, + recoverSparkVllmEndpointImpl: () => { + throw new Error("Spark receipt identity changed"); + }, + }), + ).toThrow("Spark receipt identity changed"); + expect(getManagedBaseUrlImpl).not.toHaveBeenCalled(); + }); + + it("stops when Spark and Station managed state are both present", () => { + expect(() => + getManagedVllmProviderBinding({ + loadApiKeyImpl: () => API_KEY, + recoverSparkVllmEndpointImpl: () => ({ baseUrl: BASE_URL, apiKey: API_KEY }), + getManagedBaseUrlImpl: (overrides) => { + overrides?.onManagedHeadObserved?.(); + overrides?.loadApiKey?.(); + return BASE_URL; + }, + }), + ).toThrow("Both managed Spark and Station vLLM state are present"); }); it("does not load a stale or unsafe key without a recovered managed endpoint", () => { @@ -109,7 +175,7 @@ describe("managed dual-Station vLLM authentication", () => { }); lifecycle.baseUrl.mockReturnValue(null); - expect(getManagedDualStationVllmProviderBinding({ loadApiKeyImpl })).toBeNull(); + expect(getManagedVllmProviderBinding({ loadApiKeyImpl })).toBeNull(); expect(loadApiKeyImpl).not.toHaveBeenCalled(); }); @@ -146,11 +212,11 @@ describe("managed dual-Station vLLM authentication", () => { }); it("returns one atomic provider endpoint and credential binding", () => { - expect(getManagedDualStationVllmProviderBinding({ loadApiKeyImpl: () => API_KEY })).toEqual({ + expect(getManagedVllmProviderBinding({ loadApiKeyImpl: () => API_KEY })).toEqual({ baseUrl: `${BASE_URL}/v1`, apiKey: API_KEY, }); - expect(getManagedDualStationVllmProviderState({ loadApiKeyImpl: () => API_KEY })).toEqual({ + expect(getManagedVllmProviderState({ loadApiKeyImpl: () => API_KEY })).toEqual({ kind: "ready", baseUrl: `${BASE_URL}/v1`, apiKey: API_KEY, @@ -294,7 +360,7 @@ describe("managed dual-Station vLLM authentication", () => { it("returns invalid-auth when the private key does not match the managed lifecycle", () => { expect( - getManagedDualStationVllmProviderState({ + getManagedVllmProviderState({ getManagedBaseUrlImpl: productionManagedBaseUrlResolver(OTHER_API_KEY), loadApiKeyImpl: () => API_KEY, }), @@ -312,7 +378,7 @@ describe("managed dual-Station vLLM authentication", () => { expect(runCurlProbeImpl).not.toHaveBeenCalled(); expect(result).toMatchObject({ ok: false, - endpoint: "managed dual-Station vLLM", + endpoint: "managed vLLM", failureLabel: "unhealthy", }); }); diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index c9c29d970b4..478f9d5168a 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -45,7 +45,11 @@ import { resetOllamaRuntimeContextWindowAutoState, resolveOllamaRuntimeContextWindow as resolveOllamaRuntimeContextWindowWithHost, } from "./ollama-runtime-context"; -import { loadDualStationVllmApiKey } from "./vllm-api-key"; +import { + type RecoveredDualSparkVllmEndpoint, + recoverInstalledDualSparkVllmEndpoint, +} from "./serving/spark-runtime-receipt"; +import { loadManagedVllmApiKey } from "./vllm-api-key"; import { applyVllmRuntimeContextWindow as applyVllmRuntimeContextWindowFromModels } from "./vllm-runtime-context"; import { getDualStationManagedVllmBaseUrl } from "./vllm-station-cluster-lifecycle"; @@ -252,10 +256,12 @@ export interface LocalProviderHealthProbeOptions { * state root (written by inference/ollama/proxy.ts during onboard). */ loadOllamaProxyTokenImpl?: () => string | null; - /** Reads the managed dual-Station vLLM key. Injectable so tests stay deterministic. */ + /** Reads the host-global managed vLLM key. Injectable so tests stay deterministic. */ loadVllmApiKeyImpl?: () => string | null; - /** Recovers an owned managed endpoint while validating the injected key in one lifecycle read. */ - getManagedVllmBaseUrlImpl?: ManagedDualStationVllmBaseUrlResolver; + /** Recovers a managed Station endpoint while validating the injected key. */ + getManagedVllmBaseUrlImpl?: ManagedStationVllmBaseUrlResolver; + /** Recovers a receipt-owned managed Spark endpoint. */ + recoverSparkVllmEndpointImpl?: ManagedSparkVllmEndpointResolver; } function defaultLoadOllamaProxyToken(): string | null { @@ -408,39 +414,42 @@ function configuredLocalInferenceHostUrl(hostUrl?: string | null): string | null ); } -function recoveredManagedDualStationVllmBaseUrl(): string | null { - return configuredLocalInferenceHostUrl() ? null : getDualStationManagedVllmBaseUrl(); +function recoveredManagedVllmBaseUrl(): string | null { + if (configuredLocalInferenceHostUrl()) return null; + return getManagedVllmProviderBinding()?.baseUrl.replace(/\/v1\/?$/, "") ?? null; } -export interface ManagedDualStationVllmProviderBinding { +export interface ManagedVllmProviderBinding { baseUrl: string; apiKey: string; } -type ManagedDualStationVllmBaseUrlResolver = (overrides?: { +type ManagedStationVllmBaseUrlResolver = (overrides?: { loadApiKey?: () => string | null; onManagedHeadObserved?: () => void; }) => string | null; -export type ManagedDualStationVllmProviderState = +type ManagedSparkVllmEndpointResolver = (options?: { + loadApiKey?: () => string | null; +}) => Pick | null; + +export type ManagedVllmProviderState = | { kind: "absent" } | { kind: "invalid-auth"; reason: "missing" | "unsafe" | "mismatched" } - | ({ kind: "ready" } & ManagedDualStationVllmProviderBinding); + | ({ kind: "ready" } & ManagedVllmProviderBinding); -export interface ManagedDualStationVllmProviderBindingOptions { +export interface ManagedVllmProviderBindingOptions { hostUrl?: string | null; - getManagedBaseUrlImpl?: ManagedDualStationVllmBaseUrlResolver; + /** Compatibility seam for the Station lifecycle resolver. */ + getManagedBaseUrlImpl?: ManagedStationVllmBaseUrlResolver; loadApiKeyImpl?: () => string | null; + recoverSparkVllmEndpointImpl?: ManagedSparkVllmEndpointResolver; } -/** Recover endpoint and credential as one lifecycle-validated state. */ -export function getManagedDualStationVllmProviderState( - options: ManagedDualStationVllmProviderBindingOptions = {}, -): ManagedDualStationVllmProviderState { - const configuredHostUrl = configuredLocalInferenceHostUrl(options.hostUrl); - if (configuredHostUrl) return { kind: "absent" }; - - const loadApiKey = options.loadApiKeyImpl ?? loadDualStationVllmApiKey; +function getManagedStationVllmProviderState( + options: ManagedVllmProviderBindingOptions, + loadApiKey: () => string | null, +): ManagedVllmProviderState { let keyRead = false; let managedHeadObserved = false; let apiKey: string | null = null; @@ -479,24 +488,75 @@ export function getManagedDualStationVllmProviderState( if (!managedBaseUrl || !apiKey) { return { kind: "invalid-auth", reason: authFailure ?? "mismatched" }; } - return { kind: "ready", baseUrl: `${managedBaseUrl}/v1`, apiKey }; + return { kind: "ready", baseUrl: `${managedBaseUrl.replace(/\/+$/, "")}/v1`, apiKey }; } -/** Compatibility binding for onboarding and context-window callers. */ -export function getManagedDualStationVllmProviderBinding( - options: ManagedDualStationVllmProviderBindingOptions = {}, -): ManagedDualStationVllmProviderBinding | null { - const state = getManagedDualStationVllmProviderState(options); +/** Recover the one owned managed endpoint and credential as a validated state. */ +export function getManagedVllmProviderState( + options: ManagedVllmProviderBindingOptions = {}, +): ManagedVllmProviderState { + if (configuredLocalInferenceHostUrl(options.hostUrl)) return { kind: "absent" }; + + const loadApiKey = options.loadApiKeyImpl ?? loadManagedVllmApiKey; + let sparkAuthFailure: "missing" | "unsafe" | null = null; + let sparkEndpoint: Pick | null; + try { + sparkEndpoint = (options.recoverSparkVllmEndpointImpl ?? recoverInstalledDualSparkVllmEndpoint)( + { + loadApiKey: () => { + try { + const apiKey = loadApiKey(); + if (!apiKey) sparkAuthFailure = "missing"; + return apiKey; + } catch { + sparkAuthFailure = "unsafe"; + return null; + } + }, + }, + ); + } catch (error) { + if (sparkAuthFailure) return { kind: "invalid-auth", reason: sparkAuthFailure }; + throw error; + } + + const stationState = getManagedStationVllmProviderState(options, loadApiKey); + if (!sparkEndpoint) return stationState; + if (stationState.kind !== "absent") { + throw new Error( + "Both managed Spark and Station vLLM state are present; refusing to select either endpoint.", + ); + } + return { + kind: "ready", + baseUrl: `${sparkEndpoint.baseUrl.replace(/\/+$/, "")}/v1`, + apiKey: sparkEndpoint.apiKey, + }; +} + +export function getManagedVllmProviderBinding( + options: ManagedVllmProviderBindingOptions = {}, +): ManagedVllmProviderBinding | null { + const state = getManagedVllmProviderState(options); if (state.kind === "absent") return null; if (state.kind === "invalid-auth") { if (state.reason !== "missing") { - throw new Error("Managed dual-Station vLLM authentication is unsafe or mismatched."); + throw new Error("Managed vLLM authentication is unsafe or mismatched."); } - throw new Error("Managed dual-Station vLLM authentication is missing."); + throw new Error("Managed vLLM authentication is missing."); } return { baseUrl: state.baseUrl, apiKey: state.apiKey }; } +export type ManagedDualStationVllmProviderBinding = ManagedVllmProviderBinding; +export type ManagedDualStationVllmProviderState = ManagedVllmProviderState; +export type ManagedDualStationVllmProviderBindingOptions = ManagedVllmProviderBindingOptions; + +/** @deprecated Use getManagedVllmProviderState. */ +export const getManagedDualStationVllmProviderState = getManagedVllmProviderState; +/** @deprecated Use getManagedVllmProviderBinding. */ +export const getManagedDualStationVllmProviderBinding = getManagedVllmProviderBinding; + export function getLocalProviderBaseUrl( provider: string, options: { hostUrl?: string | null } = {}, @@ -506,8 +566,8 @@ export function getLocalProviderBaseUrl( switch (provider) { case "vllm-local": { if (!configuredHostUrl) { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); - if (dualStationBaseUrl) return `${dualStationBaseUrl}/v1`; + const managedBaseUrl = recoveredManagedVllmBaseUrl(); + if (managedBaseUrl) return `${managedBaseUrl}/v1`; } return `${hostUrl}:${VLLM_PORT}/v1`; } @@ -522,8 +582,8 @@ export function getLocalProviderBaseUrl( export function getLocalProviderValidationBaseUrl(provider: string): string | null { switch (provider) { case "vllm-local": { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); - return dualStationBaseUrl ? `${dualStationBaseUrl}/v1` : `http://127.0.0.1:${VLLM_PORT}/v1`; + const managedBaseUrl = recoveredManagedVllmBaseUrl(); + return managedBaseUrl ? `${managedBaseUrl}/v1` : `http://127.0.0.1:${VLLM_PORT}/v1`; } case "ollama-local": return `http://${getResolvedOllamaHost()}:${OLLAMA_PORT}/v1`; @@ -535,9 +595,9 @@ export function getLocalProviderValidationBaseUrl(provider: string): string | nu export function getLocalProviderHealthEndpoint(provider: string): string | null { switch (provider) { case "vllm-local": { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); - return dualStationBaseUrl - ? `${dualStationBaseUrl}/v1/models` + const managedBaseUrl = recoveredManagedVllmBaseUrl(); + return managedBaseUrl + ? `${managedBaseUrl}/v1/models` : `http://127.0.0.1:${VLLM_PORT}/v1/models`; } case "ollama-local": @@ -550,8 +610,8 @@ export function getLocalProviderHealthEndpoint(provider: string): string | null /** Lightweight endpoint used only to prove that the local service is reachable. */ export function getLocalProviderAvailabilityEndpoint(provider: string): string | null { if (provider === "vllm-local") { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); - if (dualStationBaseUrl) return `${dualStationBaseUrl}/health`; + const managedBaseUrl = recoveredManagedVllmBaseUrl(); + if (managedBaseUrl) return `${managedBaseUrl}/health`; } return getLocalProviderHealthEndpoint(provider); } @@ -742,22 +802,23 @@ export function probeLocalProviderHealth( const providerLabel = getLocalProviderLabel(provider); if (!providerLabel) return null; - let managedState: ManagedDualStationVllmProviderState = { kind: "absent" }; + let managedState: ManagedVllmProviderState = { kind: "absent" }; if (provider === "vllm-local") { try { - managedState = getManagedDualStationVllmProviderState({ + managedState = getManagedVllmProviderState({ getManagedBaseUrlImpl: options.getManagedVllmBaseUrlImpl, loadApiKeyImpl: options.loadVllmApiKeyImpl, + recoverSparkVllmEndpointImpl: options.recoverSparkVllmEndpointImpl, }); } catch { return { ok: false, providerLabel, - endpoint: "managed dual-Station vLLM", + endpoint: "managed vLLM", failureLabel: "unhealthy", probeLabel: "vllm backend", detail: - "Local vLLM authentication state could not be inspected safely. Re-run `nemoclaw onboard` to repair the managed dual-Station provider.", + "Managed vLLM state could not be inspected safely. Re-run `nemoclaw onboard` to repair the provider.", }; } } @@ -766,12 +827,12 @@ export function probeLocalProviderHealth( return { ok: false, providerLabel, - endpoint: "managed dual-Station vLLM", + endpoint: "managed vLLM", failureLabel: missingAuth ? "unauthorized" : "unhealthy", probeLabel: "vllm backend", detail: missingAuth - ? "Local vLLM requires its managed bearer credential, but no private key is available. Re-run `nemoclaw onboard` to repair the dual-Station provider." - : "Local vLLM authentication state is unsafe or does not match the managed service. Re-run `nemoclaw onboard` to repair the managed dual-Station provider.", + ? "Managed vLLM requires its bearer credential, but no private key is available. Re-run `nemoclaw onboard` to repair the provider." + : "Managed vLLM authentication state is unsafe or does not match the service. Re-run `nemoclaw onboard` to repair the provider.", }; } const managedBinding = managedState.kind === "ready" ? managedState : null; @@ -889,9 +950,9 @@ export function probeLocalProviderHealth( export function getLocalProviderContainerReachabilityCheck(provider: string): string[] | null { switch (provider) { case "vllm-local": { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); + const managedBaseUrl = recoveredManagedVllmBaseUrl(); return [ - ...(dualStationBaseUrl ? ["docker", "--context", "default"] : ["docker"]), + ...(managedBaseUrl ? ["docker", "--context", "default"] : ["docker"]), "run", "--rm", "--add-host", @@ -901,11 +962,11 @@ export function getLocalProviderContainerReachabilityCheck(provider: string): st "5", "--max-time", "10", - ...(dualStationBaseUrl ? ["--noproxy", "*"] : []), + ...(managedBaseUrl ? ["--noproxy", "*"] : []), "-sf", - ...(dualStationBaseUrl ? ["-w", "%{http_code}"] : []), - dualStationBaseUrl - ? `${dualStationBaseUrl}/health` + ...(managedBaseUrl ? ["-w", "%{http_code}"] : []), + managedBaseUrl + ? `${managedBaseUrl}/health` : `http://host.openshell.internal:${VLLM_PORT}/v1/models`, ]; } @@ -1024,9 +1085,9 @@ export function validateLocalProvider( function getContainerCheckUrl(provider: string): string { switch (provider) { case "vllm-local": { - const dualStationBaseUrl = recoveredManagedDualStationVllmBaseUrl(); - return dualStationBaseUrl - ? `${dualStationBaseUrl}/health` + const managedBaseUrl = recoveredManagedVllmBaseUrl(); + return managedBaseUrl + ? `${managedBaseUrl}/health` : `http://host.openshell.internal:${VLLM_PORT}/v1/models`; } case "ollama-local": @@ -1039,7 +1100,7 @@ function getContainerCheckUrl(provider: string): string { function collectContainerDiagnostic(provider: string, capture: RunCaptureFn): string { const url = getContainerCheckUrl(provider); const dockerCommand = - provider === "vllm-local" && recoveredManagedDualStationVllmBaseUrl() + provider === "vllm-local" && recoveredManagedVllmBaseUrl() ? ["docker", "--context", "default"] : ["docker"]; try { diff --git a/src/lib/inference/serving/catalog-integrity.ts b/src/lib/inference/serving/catalog-integrity.ts new file mode 100644 index 00000000000..a449c8540c2 --- /dev/null +++ b/src/lib/inference/serving/catalog-integrity.ts @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; + +type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject; +type JsonObject = { readonly [key: string]: JsonValue }; + +function canonicalize(value: unknown, path: string): JsonValue { + if (value === null || typeof value === "string" || typeof value === "boolean") return value; + if (typeof value === "number") { + if (!Number.isFinite(value)) throw new Error(`${path} contains a non-finite number`); + return Object.is(value, -0) ? 0 : value; + } + if (Array.isArray(value)) { + return value.map((item, index) => canonicalize(item, `${path}[${String(index)}]`)); + } + if (typeof value !== "object") throw new Error(`${path} is not JSON-serializable`); + + const output: Record = {}; + for (const key of Object.keys(value).sort()) { + const child = (value as Record)[key]; + if (child === undefined) throw new Error(`${path}.${key} is undefined`); + output[key] = canonicalize(child, `${path}.${key}`); + } + return output; +} + +export function canonicalManagedInferenceJson(value: unknown): string { + return JSON.stringify(canonicalize(value, "catalog")); +} + +export function managedInferenceDigest(value: unknown): string { + return `sha256:${managedInferenceHexDigest(value)}`; +} + +export function managedInferenceHexDigest(value: unknown): string { + return createHash("sha256").update(canonicalManagedInferenceJson(value)).digest("hex"); +} + +export function managedInferenceTextDigest(value: string): string { + return `sha256:${createHash("sha256").update(value).digest("hex")}`; +} + +function deepFreeze(value: T): T { + if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value; + Object.freeze(value); + for (const child of Object.values(value)) deepFreeze(child); + return value; +} + +export function immutableManagedInferenceCopy(value: T): T { + return deepFreeze(JSON.parse(canonicalManagedInferenceJson(value)) as T); +} diff --git a/src/lib/inference/serving/catalog-types.ts b/src/lib/inference/serving/catalog-types.ts new file mode 100644 index 00000000000..4712a2385a9 --- /dev/null +++ b/src/lib/inference/serving/catalog-types.ts @@ -0,0 +1,217 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { SystemReadinessReport } from "../../readiness/types.js"; + +export const MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION = "1.0.0" as const; +export const MANAGED_INFERENCE_CATALOG_COMPILER_VERSION = "1.0.0" as const; +export const DUAL_SPARK_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731" as const; +export const DUAL_SPARK_RECIPE_ID = "vllm.deepseek-v4-flash-0731.spark-dual.v1" as const; +export const DUAL_SPARK_RECIPE_SPEC_DIGEST = + "sha256:32d4233427cc9fe99a143a52887b66232aeaf650712ad1b8b6ff673743fe9637" as const; +export const DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID = "dgx-spark.gb10.dual-cx7" as const; +export const DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION = 1 as const; + +const MATERIALIZER_OWNED_SERVE_ARGUMENTS = new Set([ + "--api-key", + "--distributed-executor-backend", + "--headless", + "--host", + "--master-addr", + "--master-port", + "--nnodes", + "--node-rank", + "--pipeline-parallel-size", + "--served-model-name", + "--tensor-parallel-size", +]); + +export function isManagedInferenceMaterializerOwnedArgument(name: string): boolean { + return MATERIALIZER_OWNED_SERVE_ARGUMENTS.has(name); +} + +export interface ManagedInferenceMetadata { + readonly id: string; + readonly displayName: string; +} + +export interface ManagedInferenceServingArgument { + readonly name: string; + readonly value?: string | number | boolean; +} + +export interface ManagedInferenceServingRecipe { + readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; + readonly kind: "ServingRecipe"; + readonly metadata: ManagedInferenceMetadata; + readonly spec: { + readonly backend: "vllm"; + readonly bindings: { + readonly sparkTopology: { + readonly type: "topologyQualificationOutput"; + readonly qualificationId: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; + readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + readonly outputSchema: "nemoclaw.nvidia.com/dual-spark-topology/v1"; + }; + }; + readonly model: { + readonly id: string; + readonly revision: string; + readonly servedName: string; + readonly downloadSizeBytes: number; + readonly preparationRef: "deepseek-v4-flash-0731/v1"; + readonly encodingPath: "encoding/encoding_dsv4.py"; + }; + readonly runtime: { + readonly image: string; + readonly imageDownloadSizeBytes: number; + readonly architecture: "arm64"; + readonly networkMode: "host"; + readonly ipcMode: "host"; + readonly sharedMemoryBytes: number; + readonly devices: readonly string[]; + readonly environment: Readonly>; + }; + readonly execution: { + readonly materializerRef: "vllm.dual-dgx-spark/v1"; + readonly lifecycleRef: "vllm.dual-dgx-spark/v1"; + readonly topologyBinding: "sparkTopology"; + readonly nodeCount: 2; + readonly tensorParallelSize: 2; + readonly pipelineParallelSize: 1; + readonly distributedExecutorBackend: "mp"; + }; + readonly serve: { + readonly authentication: "bearer"; + readonly arguments: readonly ManagedInferenceServingArgument[]; + }; + readonly readiness: { + readonly timeoutSeconds: number; + readonly expectedModel: string; + }; + }; +} + +export type ManagedInferencePresetRequirement = + | { + readonly readiness: { + readonly scope: "everyNode"; + readonly kind: "qualification"; + readonly id: "host.platform.dgx_spark"; + readonly status: "qualified"; + }; + } + | { + readonly fact: "cluster.nodeCount"; + readonly state: "present"; + readonly operator: "equals"; + readonly value: number; + } + | { + readonly topologyQualification: { + readonly id: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; + readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + readonly status: "qualified"; + }; + }; + +export interface ManagedInferenceServingPreset { + readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; + readonly kind: "ServingPreset"; + readonly metadata: ManagedInferenceMetadata; + readonly spec: { + readonly selection: "automatic"; + readonly requirements: { + readonly all: readonly ManagedInferencePresetRequirement[]; + }; + readonly plan: { + readonly backend: "vllm"; + readonly recipeRef: string; + readonly bindings: { + readonly sparkTopology: { + readonly valueFromTopologyQualification: { + readonly id: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; + readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + readonly output: "topology"; + }; + }; + }; + }; + }; +} + +export interface CompiledManagedInferenceDefinition { + readonly definition: TDefinition; + readonly definitionDigest: string; + readonly sourceFile: string; +} + +export interface CompiledManagedInferenceCatalog { + readonly catalogDigest: string; + readonly compilerVersion: typeof MANAGED_INFERENCE_CATALOG_COMPILER_VERSION; + readonly presets: readonly CompiledManagedInferenceDefinition[]; + readonly recipes: readonly CompiledManagedInferenceDefinition[]; + readonly schemaVersion: typeof MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION; + readonly sourceFiles: readonly { + readonly digest: string; + readonly path: string; + }[]; + readonly sourceRevision: string; +} + +export interface ManagedInferenceTopologyQualification { + readonly id: string; + readonly schemaVersion: number; + readonly status: "qualified" | "unqualified" | "unknown"; + readonly subjectNodeIds: readonly string[]; + readonly subjectDigest: string; + readonly outputDigest: string; + readonly output: TOutput; +} + +export interface ManagedInferenceReadinessSource { + readonly nodeId: string; + readonly report: SystemReadinessReport; +} + +export interface ManagedInferenceSelectionIntent { + readonly provider?: string; + readonly vllmModel?: string; + readonly vllmExtraArguments?: readonly string[]; + readonly preset?: string; +} + +export interface ManagedInferenceResolverInput { + readonly readinessReports: readonly ManagedInferenceReadinessSource[]; + readonly topologyQualifications: readonly ManagedInferenceTopologyQualification[]; + readonly intent?: ManagedInferenceSelectionIntent; + readonly now?: Date; + readonly maxReadinessAgeMs?: number; +} + +export interface ResolvedManagedInferenceSelection { + readonly outcome: "selected"; + readonly selection: "automatic" | "explicit"; + readonly catalogDigest: string; + readonly preset: ManagedInferenceServingPreset; + readonly recipe: ManagedInferenceServingRecipe; + readonly topologyQualification: ManagedInferenceTopologyQualification; +} + +export type ManagedInferenceResolution = + | ResolvedManagedInferenceSelection + | { + readonly outcome: "no-match"; + readonly code: "explicit-intent" | "requirements-not-met"; + readonly message: string; + } + | { + readonly outcome: "rejected"; + readonly code: + | "unknown-preset" + | "incompatible-intent" + | "invalid-readiness" + | "invalid-topology" + | "requirements-not-met"; + readonly message: string; + }; diff --git a/src/lib/inference/serving/catalog.test.ts b/src/lib/inference/serving/catalog.test.ts new file mode 100644 index 00000000000..61e4db678be --- /dev/null +++ b/src/lib/inference/serving/catalog.test.ts @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { + DUAL_SPARK_PRESET_ID, + DUAL_SPARK_RECIPE_ID, + DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, +} from "./catalog-types.js"; + +describe("managed inference catalog", () => { + it("loads the immutable two-Spark recipe from compiled JSON", () => { + const catalog = loadManagedInferenceCatalog(); + const recipe = catalog.recipes[0]?.definition; + const preset = catalog.presets[0]?.definition; + + expect(catalog.catalogDigest).toMatch(/^sha256:[0-9a-f]{64}$/u); + expect(recipe?.metadata.id).toBe(DUAL_SPARK_RECIPE_ID); + expect(recipe?.spec.model).toMatchObject({ + id: "deepseek-ai/DeepSeek-V4-Flash-0731", + revision: "9e165c30e2704aec5d9d593cce3eebd58bbef1cb", + downloadSizeBytes: 166_898_661_074, + preparationRef: "deepseek-v4-flash-0731/v1", + }); + expect(recipe?.spec.runtime).toMatchObject({ + image: + "ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8", + imageDownloadSizeBytes: 9_787_537_825, + }); + expect(recipe?.spec.execution).toMatchObject({ + materializerRef: "vllm.dual-dgx-spark/v1", + lifecycleRef: "vllm.dual-dgx-spark/v1", + nodeCount: 2, + tensorParallelSize: 2, + }); + expect(preset?.metadata.id).toBe(DUAL_SPARK_PRESET_ID); + expect(preset?.spec.requirements.all).toContainEqual({ + topologyQualification: { + id: DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, + schemaVersion: 1, + status: "qualified", + }, + }); + }); + + it("returns one deeply frozen catalog instance", () => { + const first = loadManagedInferenceCatalog(); + const second = loadManagedInferenceCatalog(); + + expect(second).toBe(first); + expect(Object.isFrozen(first)).toBe(true); + expect(Object.isFrozen(first.recipes[0]?.definition.spec.runtime.environment)).toBe(true); + }); +}); diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts new file mode 100644 index 00000000000..96c041db129 --- /dev/null +++ b/src/lib/inference/serving/catalog.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { immutableManagedInferenceCopy, managedInferenceDigest } from "./catalog-integrity.js"; +import { + type CompiledManagedInferenceCatalog, + DUAL_SPARK_PRESET_ID, + DUAL_SPARK_RECIPE_ID, + DUAL_SPARK_RECIPE_SPEC_DIGEST, + MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, + MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, +} from "./catalog-types.js"; +import generatedCatalog from "./generated/catalog.json"; + +const SHA256 = /^sha256:[0-9a-f]{64}$/u; + +function assertCatalogIntegrity(value: unknown): asserts value is CompiledManagedInferenceCatalog { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error("managed inference catalog must be an object"); + } + const catalog = value as Partial; + if ( + catalog.schemaVersion !== MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION || + catalog.compilerVersion !== MANAGED_INFERENCE_CATALOG_COMPILER_VERSION + ) { + throw new Error("managed inference catalog version is unsupported"); + } + if (!SHA256.test(catalog.catalogDigest ?? "") || !SHA256.test(catalog.sourceRevision ?? "")) { + throw new Error("managed inference catalog provenance is invalid"); + } + if ( + !Array.isArray(catalog.sourceFiles) || + !Array.isArray(catalog.recipes) || + !Array.isArray(catalog.presets) + ) { + throw new Error("managed inference catalog definitions are invalid"); + } + + const { catalogDigest, ...withoutDigest } = catalog as CompiledManagedInferenceCatalog; + if (managedInferenceDigest(withoutDigest) !== catalogDigest) { + throw new Error("managed inference catalog digest does not match its contents"); + } + if (managedInferenceDigest(catalog.sourceFiles) !== catalog.sourceRevision) { + throw new Error("managed inference catalog source revision does not match its provenance"); + } + if (catalog.recipes.length !== 1 || catalog.presets.length !== 1) { + throw new Error("managed inference catalog must contain the supported recipe and preset"); + } + + const recipe = catalog.recipes[0]; + const preset = catalog.presets[0]; + if ( + !recipe || + !preset || + recipe.definition.metadata.id !== DUAL_SPARK_RECIPE_ID || + preset.definition.metadata.id !== DUAL_SPARK_PRESET_ID + ) { + throw new Error("managed inference catalog contains an unsupported definition"); + } + if (managedInferenceDigest(recipe.definition.spec) !== DUAL_SPARK_RECIPE_SPEC_DIGEST) { + throw new Error("managed inference recipe ID does not match its immutable contract"); + } + for (const compiled of [recipe, preset]) { + if ( + !SHA256.test(compiled.definitionDigest) || + compiled.definitionDigest !== managedInferenceDigest(compiled.definition) || + !catalog.sourceFiles.some(({ path }) => path === compiled.sourceFile) + ) { + throw new Error(`managed inference definition ${compiled.definition.metadata.id} is invalid`); + } + } + if (preset.definition.spec.plan.recipeRef !== recipe.definition.metadata.id) { + throw new Error("managed inference preset references an unknown recipe"); + } +} + +let loadedCatalog: CompiledManagedInferenceCatalog | undefined; + +export function loadManagedInferenceCatalog(): CompiledManagedInferenceCatalog { + if (loadedCatalog) return loadedCatalog; + assertCatalogIntegrity(generatedCatalog); + loadedCatalog = immutableManagedInferenceCopy(generatedCatalog); + return loadedCatalog; +} diff --git a/src/lib/inference/serving/dual-spark-discovery-production.ts b/src/lib/inference/serving/dual-spark-discovery-production.ts new file mode 100644 index 00000000000..7ef4910408e --- /dev/null +++ b/src/lib/inference/serving/dual-spark-discovery-production.ts @@ -0,0 +1,1231 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type SpawnSyncOptionsWithStringEncoding, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; + +import type { BuildIdentity } from "../../core/version.js"; +import { getBuildIdentity } from "../../core/version.js"; +import { assessHost } from "../../onboard/preflight.js"; +import { createHostReadinessReport } from "../../readiness/host.js"; +import { collectPlatformIdentity } from "../../readiness/platform-qualification.js"; +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { managedVllmStateDir } from "../vllm-api-key.js"; +import { buildLocalDualStationDockerEnv, buildVllmSshTransportEnv } from "../vllm-docker-env.js"; +import { + clearDualStationSshBinding, + dualStationSshBindingDirectory, + encodeDualStationSshBindingHandoff, + type QualifiedStationSshIdentity, + stationKnownHostsDigest, + strictStationSshTransportArgs, + writeDualStationSshBinding, +} from "../vllm-station-ssh-binding.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import type { + DualSparkCommandResult, + DualSparkConnectivityRequest, + DualSparkDiscoveryDeps, + DualSparkHostObservation, + DualSparkPinnedPeerTransport, + DualSparkReadOnlyHostTransport, +} from "./dual-spark-discovery.js"; +import { + DUAL_SPARK_VLLM_IMAGE, + DUAL_SPARK_VLLM_MODEL, + DUAL_SPARK_VLLM_MODEL_REVISION, +} from "./dual-spark-materialize.js"; +import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./spark-runtime-receipt-path.js"; + +const COMMAND_TIMEOUT_MS = 20_000; +const MAX_COMMAND_OUTPUT_BYTES = 4 * 1024 * 1024; +const MAX_LOCAL_FILE_BYTES = 1024 * 1024; +const MAX_DIRECTORY_ENTRIES = 4096; +const SAFE_TARGET_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; +const SAFE_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const MAC_PATTERN = /^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/; +const SHA256_PATTERN = /^[a-f0-9]{64}$/; +const SAFE_SSH_KEY_TYPE_PATTERN = /^(?:ssh-|ecdsa-|sk-)[A-Za-z0-9@._+-]+$/; +const SAFE_SSH_KEY_DATA_PATTERN = /^[A-Za-z0-9+/]+={0,3}$/; + +export type DualSparkSpawnSync = ( + file: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, +) => { + readonly status: number | null; + readonly stdout: string | null; + readonly stderr: string | null; + readonly error?: Error; +}; + +export type DualSparkHostParser = (value: unknown) => DualSparkHostObservation; + +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function validatePeerTarget(raw: string): string { + if ( + raw.length === 0 || + raw.length > 286 || + raw !== raw.trim() || + /[/,:;`'"\\$(){}[\]<>|&!?*\s\u0000-\u001f\u007f]/.test(raw) + ) { + throw new Error("DGX Spark SSH peer target is invalid"); + } + const parts = raw.split("@"); + const username = parts.length === 2 ? parts[0] : ""; + const hostname = parts.at(-1) ?? ""; + if ( + parts.length > 2 || + (parts.length === 2 && !username) || + (username !== "" && !SAFE_USERNAME_PATTERN.test(username)) || + (net.isIP(hostname) !== 4 && !SAFE_TARGET_PATTERN.test(hostname)) + ) { + throw new Error("DGX Spark SSH peer target is invalid"); + } + return raw; +} + +const REMOTE_ARGV_EXECUTOR = String.raw` +import base64 +import json +import subprocess +import sys + +try: + encoded = sys.argv[1] + padding = "=" * ((4 - len(encoded) % 4) % 4) + request = json.loads(base64.urlsafe_b64decode(encoded + padding)) + argv = request["argv"] + if ( + not isinstance(argv, list) + or not argv + or len(argv) > 128 + or any(not isinstance(value, str) or not value or "\x00" in value for value in argv) + or sum(len(value) for value in argv) > 262144 + ): + raise ValueError("invalid argv") + result = subprocess.run( + argv, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=15, + check=False, + shell=False, + ) + sys.stdout.buffer.write(result.stdout) + sys.stderr.buffer.write(result.stderr) + raise SystemExit(result.returncode) +except subprocess.TimeoutExpired: + raise SystemExit(124) +except Exception: + raise SystemExit(125) +`; + +const READ_FILE_SCRIPT = String.raw` +import os +import sys + +path = sys.argv[1] +fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) +try: + data = os.read(fd, 1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise SystemExit(2) + sys.stdout.buffer.write(data) +finally: + os.close(fd) +`; + +const READDIR_SCRIPT = String.raw` +import json +import os +import sys + +entries = sorted(os.listdir(sys.argv[1])) +if len(entries) > 4096: + raise SystemExit(2) +print(json.dumps(entries, separators=(",", ":"))) +`; + +const HOST_PROBE_SCRIPT = String.raw` +import csv +import ipaddress +import json +import os +from pathlib import Path +import pwd +import re +import shutil +import socket +import subprocess +import sys + +MODEL_ID, MODEL_REVISION, IMAGE_REF, MODEL_BYTES_TEXT = sys.argv[1:5] +MODEL_BYTES = int(MODEL_BYTES_TEXT) +DOCKER_ENV_NAMES = ( + "DOCKER_API_VERSION", + "DOCKER_CERT_PATH", + "DOCKER_CONFIG", + "DOCKER_CONTEXT", + "DOCKER_HOST", + "DOCKER_TLS", + "DOCKER_TLS_VERIFY", +) + +def run(argv, timeout=10): + try: + env = None + if argv and argv[0] == "docker": + env = os.environ.copy() + for name in DOCKER_ENV_NAMES: + env.pop(name, None) + env["DOCKER_CONTEXT"] = "default" + result = subprocess.run( + argv, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=timeout, + check=False, + shell=False, + env=env, + ) + return result.returncode, result.stdout + except Exception: + return 125, "" + +def read_text(path, default=""): + try: + return Path(path).read_text(encoding="utf-8", errors="replace")[:4096].strip() + except Exception: + return default + +def read_int(path, default=-1): + try: + return int(read_text(path)) + except Exception: + return default + +def ipv4_addresses(netdev): + code, output = run(["ip", "-j", "address", "show", "dev", netdev]) + if code != 0: + return [] + try: + payload = json.loads(output) + result = [] + for interface in payload: + for address in interface.get("addr_info", []): + if address.get("family") == "inet": + result.append({ + "address": address["local"], + "prefixLength": int(address["prefixlen"]), + }) + return result + except Exception: + return [] + +def gid_ipv4(value): + try: + mapped = ipaddress.IPv6Address(value).ipv4_mapped + return str(mapped) if mapped is not None else "" + except Exception: + return "" + +def pci_name(address): + if not address: + return "" + code, output = run(["lspci", "-D", "-s", address]) + return output.strip()[:512] if code == 0 else "" + +def physical_adapter_id(pci_address): + if re.fullmatch(r"[0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}\.[0-7]", pci_address): + return "pci-" + pci_address.rsplit(".", 1)[0].lower() + return "unknown" + +def collect_rails(): + rails = [] + root = Path("/sys/class/infiniband") + if not root.is_dir(): + return rails + for hca in sorted(root.iterdir(), key=lambda item: item.name)[:32]: + ports = hca / "ports" + if not ports.is_dir(): + continue + for port_path in sorted(ports.iterdir(), key=lambda item: item.name)[:16]: + try: + port = int(port_path.name) + except Exception: + continue + ndevs = port_path / "gid_attrs" / "ndevs" + types = port_path / "gid_attrs" / "types" + gids = port_path / "gids" + if not ndevs.is_dir() or not types.is_dir() or not gids.is_dir(): + continue + by_netdev = {} + for ndev_file in sorted(ndevs.iterdir(), key=lambda item: item.name)[:4096]: + try: + index = int(ndev_file.name) + except Exception: + continue + netdev = read_text(ndev_file) + gid_type = read_text(types / ndev_file.name) + gid = read_text(gids / ndev_file.name).lower() + if not netdev or "roce v2" not in gid_type.lower(): + continue + address = gid_ipv4(gid) + if not address: + continue + by_netdev.setdefault(netdev, []).append({ + "index": index, + "value": gid, + "ipv4Address": address, + }) + for netdev, roce_gids in sorted(by_netdev.items()): + net_root = Path("/sys/class/net") / netdev + if not net_root.is_dir(): + continue + try: + pci_address = (net_root / "device").resolve(strict=True).name + except Exception: + pci_address = "" + rails.append({ + "physicalPortId": physical_adapter_id(pci_address), + "netdev": netdev, + "hcaDevice": hca.name, + "hcaPort": port, + "macAddress": read_text(net_root / "address").lower(), + "pciAddress": pci_address, + "pciName": pci_name(pci_address), + "state": read_text(port_path / "state"), + "operState": read_text(net_root / "operstate"), + "carrier": read_text(net_root / "carrier") == "1", + "linkLayer": read_text(port_path / "link_layer"), + "speedMbps": read_int(net_root / "speed"), + "mtu": read_int(net_root / "mtu"), + "ipv4Addresses": ipv4_addresses(netdev), + "roceV2Ipv4Gids": sorted(roce_gids, key=lambda gid: (gid["index"], gid["value"])), + }) + return rails + +def collect_gpus(): + code, output = run([ + "nvidia-smi", + "--query-gpu=index,name,uuid", + "--format=csv,noheader,nounits", + ]) + if code != 0: + return [] + result = [] + try: + for row in csv.reader(output.splitlines()): + if len(row) != 3: + return [] + result.append({"index": int(row[0].strip()), "name": row[1].strip(), "uuid": row[2].strip()}) + except Exception: + return [] + return result + +def listening_ports(): + ports = set() + complete = True + for source in ("/proc/net/tcp", "/proc/net/tcp6"): + try: + lines = Path(source).read_text(encoding="ascii").splitlines()[1:] + for line in lines: + fields = line.split() + if len(fields) >= 4 and fields[3] == "0A": + ports.add(int(fields[1].split(":")[1], 16)) + except Exception: + complete = False + return sorted(ports), complete + +def containers(): + code, output = run(["docker", "ps", "-aq", "--no-trunc"]) + if code != 0: + return [], False + ids = [line.strip() for line in output.splitlines() if line.strip()] + if len(ids) > 256: + return [], False + if not ids: + return [], True + code, output = run(["docker", "inspect", *ids]) + if code != 0: + return [], False + try: + inspected = json.loads(output) + result = [] + for item in inspected: + state = item.get("State") or {} + health = state.get("Health") or {} + container_id = str(item.get("Id", "")) + name = str(item.get("Name", "")).lstrip("/") + image = str((item.get("Config") or {}).get("Image", "")) + labels = (item.get("Config") or {}).get("Labels") or {} + if ( + not re.fullmatch(r"[a-f0-9]{64}", container_id) + or not name or len(name) > 256 + or not image or len(image) > 1024 + or not isinstance(labels, dict) or len(labels) > 128 + or any( + not isinstance(key, str) or not key or len(key) > 256 + or not isinstance(value, str) or len(value) > 4096 + for key, value in labels.items() + ) + ): + return [], False + result.append({ + "id": container_id, + "name": name, + "image": image, + "running": bool(state.get("Running", False)), + "healthy": health.get("Status") == "healthy", + "labels": labels, + }) + return result, len(result) == len(ids) + except Exception: + return [], False + +def nearest_capacity(requested): + try: + candidate = Path(requested).expanduser() + while not candidate.exists() and candidate != candidate.parent: + candidate = candidate.parent + if not candidate.exists(): + raise RuntimeError("no existing parent") + resolved = candidate.resolve(strict=True) + stats = os.stat(resolved) + fs_stats = os.statvfs(resolved) + return { + "requestedPath": str(Path(requested).expanduser()), + "probePath": str(resolved), + "filesystemId": str(stats.st_dev), + "availableBytes": int(fs_stats.f_bavail * fs_stats.f_frsize), + "availableInodes": int(fs_stats.f_favail), + "ownerUid": int(stats.st_uid), + "ownerGid": int(stats.st_gid), + "isDirectory": resolved.is_dir(), + "writableByUser": os.access(resolved, os.W_OK | os.X_OK), + } + except Exception: + return { + "requestedPath": str(Path(requested).expanduser()), + "probePath": None, + "filesystemId": None, + "availableBytes": None, + "availableInodes": None, + "ownerUid": None, + "ownerGid": None, + "isDirectory": False, + "writableByUser": False, + } + +def snapshot_state(snapshot, cache_root): + if not snapshot.is_dir(): + return 0, False + total = 0 + seen = set() + count = 0 + try: + cache_real = cache_root.resolve(strict=True) + for root, dirs, files in os.walk(snapshot, followlinks=False): + dirs.sort() + files.sort() + for name in files: + count += 1 + if count > 100000 or name.endswith(".incomplete"): + return None, False + file_path = Path(root) / name + real = file_path.resolve(strict=True) + if os.path.commonpath([str(cache_real), str(real)]) != str(cache_real): + return None, False + stats = real.stat() + identity = (stats.st_dev, stats.st_ino) + if identity not in seen: + seen.add(identity) + total += stats.st_size + required = [snapshot / "config.json", snapshot / "encoding" / "encoding_dsv4.py"] + complete = total >= MODEL_BYTES and all(item.is_file() for item in required) + return total, complete + except Exception: + return None, False + +uid = os.getuid() +gid = os.getgid() +account = pwd.getpwuid(uid) +home = Path(account.pw_dir).resolve() +hf_home = home / ".cache" / "huggingface" +hub = hf_home / "hub" +snapshot = hub / ("models--" + MODEL_ID.replace("/", "--")) / "snapshots" / MODEL_REVISION +snapshot_bytes, snapshot_cached = snapshot_state(snapshot, hub) +hf_capacity = nearest_capacity(hf_home) + +docker_root = None +docker_info_code, docker_info_output = run(["docker", "info", "--format", "{{json .}}"]) +if docker_info_code == 0: + try: + docker_root = json.loads(docker_info_output).get("DockerRootDir") + except Exception: + docker_root = None +docker_capacity = nearest_capacity(docker_root or "/var/lib/docker") +image_code, _ = run(["docker", "image", "inspect", IMAGE_REF]) +observed_containers, containers_complete = containers() +ports, ports_complete = listening_ports() + +earlyoom_units = [ + Path("/etc/systemd/system/earlyoom.service"), + Path("/lib/systemd/system/earlyoom.service"), + Path("/usr/lib/systemd/system/earlyoom.service"), +] +earlyoom_service_installed = any(unit.exists() for unit in earlyoom_units) +earlyoom_installed = bool(shutil.which("earlyoom")) or earlyoom_service_installed +earlyoom_active = "unknown" if earlyoom_installed else "inactive" +earlyoom_enabled = "disabled" +if earlyoom_installed: + service_active = False if not earlyoom_service_installed else None + process_active = None + if earlyoom_service_installed and shutil.which("systemctl"): + active_code, active_output = run(["systemctl", "is-active", "earlyoom.service"]) + enabled_code, enabled_output = run(["systemctl", "is-enabled", "earlyoom.service"]) + service_active = True if active_code == 0 and active_output.strip() == "active" else False if active_output.strip() in ("inactive", "failed") else None + earlyoom_enabled = "enabled" if enabled_code == 0 and enabled_output.strip() == "enabled" else "disabled" if enabled_output.strip() in ("disabled", "masked", "static") else "unknown" + if shutil.which("pgrep"): + process_code, process_output = run(["pgrep", "-x", "earlyoom"]) + process_active = True if process_code == 0 and process_output.strip() else False if process_code == 1 else None + earlyoom_active = "active" if service_active is True or process_active is True else "inactive" if service_active is False and process_active is False else "unknown" + +result = { + "schemaVersion": 1, + "hostname": socket.gethostname(), + "nodeId": read_text("/etc/machine-id"), + "productName": read_text("/sys/class/dmi/id/product_name"), + "architecture": os.uname().machine, + "home": str(home), + "username": account.pw_name, + "uid": uid, + "gid": gid, + "gpus": collect_gpus(), + "rails": collect_rails(), + "earlyoom": { + "installed": earlyoom_installed, + "active": earlyoom_active, + "enabled": earlyoom_enabled, + }, + "runtimeInspectionComplete": containers_complete and ports_complete, + "runtimeSnapshot": {"containers": observed_containers, "listeningPorts": ports}, + "storage": { + "huggingFace": { + **hf_capacity, + "cacheRoot": str(hf_home), + "snapshotPath": str(snapshot), + "snapshotBytes": snapshot_bytes, + "exactSnapshotCached": snapshot_cached, + }, + "docker": { + **docker_capacity, + "dockerRootDir": docker_root, + "exactImageCached": image_code == 0, + }, + }, +} +print(json.dumps(result, separators=(",", ":"), sort_keys=True)) +`; + +function defaultSpawnSync( + file: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, +): ReturnType { + const result = spawnSync(file, [...args], options); + return { + status: result.status, + stdout: result.stdout, + stderr: result.stderr, + ...(result.error ? { error: result.error } : {}), + }; +} + +function validateArgv(argv: readonly string[]): void { + if ( + argv.length === 0 || + argv.length > 128 || + argv.some((value) => !value || value.includes("\0")) || + argv.reduce((total, value) => total + Buffer.byteLength(value, "utf8"), 0) > 262_144 + ) { + throw new Error("DGX Spark probe argv is invalid"); + } +} + +function runCommand( + spawn: DualSparkSpawnSync, + file: string, + args: readonly string[], + input = "", + env: Readonly> = buildVllmSshTransportEnv({ LC_ALL: "C", LANG: "C" }), +): DualSparkCommandResult { + const result = spawn(file, args, { + encoding: "utf8", + input, + timeout: COMMAND_TIMEOUT_MS, + maxBuffer: MAX_COMMAND_OUTPUT_BYTES, + killSignal: "SIGKILL", + windowsHide: true, + env, + }); + return { + status: result.status, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + ...(result.error ? { error: result.error.message } : {}), + }; +} + +function commandSucceeded(result: DualSparkCommandResult, requireOutput = false): boolean { + return ( + result.status === 0 && + result.error === undefined && + (!requireOutput || result.stdout.trim().length > 0) + ); +} + +function readBoundedLocalFile(filePath: string): string { + const flags = + fs.constants.O_RDONLY | + (typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0); + const descriptor = fs.openSync(filePath, flags); + try { + const metadata = fs.fstatSync(descriptor); + if (!metadata.isFile() || metadata.size > MAX_LOCAL_FILE_BYTES) { + throw new Error(`DGX Spark probe file ${filePath} is invalid`); + } + const contents = fs.readFileSync(descriptor); + if (contents.length > MAX_LOCAL_FILE_BYTES) { + throw new Error(`DGX Spark probe file ${filePath} is too large`); + } + return contents.toString("utf8"); + } finally { + fs.closeSync(descriptor); + } +} + +function readBoundedDirectory(directory: string): string[] { + const entries = fs.readdirSync(directory); + if (entries.length > MAX_DIRECTORY_ENTRIES) { + throw new Error(`DGX Spark probe directory ${directory} is too large`); + } + return entries.sort(compareStrings); +} + +function createLocalTransport(spawn: DualSparkSpawnSync): DualSparkReadOnlyHostTransport { + return { + execute(argv) { + validateArgv(argv); + return runCommand( + spawn, + argv[0]!, + argv.slice(1), + "", + buildLocalDualStationDockerEnv({ LC_ALL: "C", LANG: "C" }), + ); + }, + readFile: readBoundedLocalFile, + readdir: readBoundedDirectory, + }; +} + +function parseJsonCommandResult(result: DualSparkCommandResult, label: string): unknown { + if (!commandSucceeded(result, true)) throw new Error(`${label} failed`); + if (Buffer.byteLength(result.stdout, "utf8") > MAX_COMMAND_OUTPUT_BYTES) { + throw new Error(`${label} output is too large`); + } + try { + return JSON.parse(result.stdout); + } catch { + throw new Error(`${label} returned invalid JSON`); + } +} + +function probeHostWithTransport( + transport: DualSparkReadOnlyHostTransport, + parseHost: DualSparkHostParser, +): DualSparkHostObservation { + const recipe = loadManagedInferenceCatalog().recipes[0]?.definition; + if (!recipe) throw new Error("Managed inference recipe is unavailable"); + const result = transport.execute([ + "python3", + "-c", + HOST_PROBE_SCRIPT, + DUAL_SPARK_VLLM_MODEL, + DUAL_SPARK_VLLM_MODEL_REVISION, + DUAL_SPARK_VLLM_IMAGE, + String(recipe.spec.model.downloadSizeBytes), + ]); + return parseHost(parseJsonCommandResult(result, "DGX Spark host probe")); +} + +type SshConfiguration = ReadonlyMap; + +function parseSshConfiguration(stdout: string): SshConfiguration { + const values = new Map(); + for (const rawLine of stdout.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line) continue; + const separator = line.search(/\s/); + if (separator <= 0) throw new Error("ssh -G returned malformed effective configuration"); + const key = line.slice(0, separator).toLowerCase(); + const value = line.slice(separator).trim(); + values.set(key, [...(values.get(key) ?? []), value]); + } + return values; +} + +function oneSshConfigurationValue(values: SshConfiguration, key: string): string { + const entries = values.get(key) ?? []; + if (entries.length !== 1 || !entries[0]) { + throw new Error(`Effective SSH configuration must define exactly one ${key}`); + } + return entries[0]; +} + +function assertStrictSshConfiguration(values: SshConfiguration): void { + const exactly = (key: string, allowed: readonly string[]): boolean => { + const observed = (values.get(key) ?? []).map((value) => value.toLowerCase()); + return observed.length === 1 && allowed.includes(observed[0]!); + }; + const absentOrNone = (key: string): boolean => { + const observed = (values.get(key) ?? []).map((value) => value.toLowerCase()); + return observed.length === 0 || (observed.length === 1 && observed[0] === "none"); + }; + const preferred = (values.get("preferredauthentications") ?? []).flatMap((value) => + value.toLowerCase().split(",").filter(Boolean), + ); + const sendEnv = (values.get("sendenv") ?? []).map((value) => value.toLowerCase()); + if ( + !exactly("batchmode", ["yes"]) || + !exactly("stricthostkeychecking", ["yes", "true"]) || + !exactly("passwordauthentication", ["no", "false"]) || + !exactly("kbdinteractiveauthentication", ["no", "false"]) || + !exactly("numberofpasswordprompts", ["0"]) || + preferred.length !== 1 || + preferred[0] !== "publickey" || + !exactly("permitlocalcommand", ["no"]) || + !exactly("forwardagent", ["no"]) || + !exactly("forwardx11", ["no"]) || + !exactly("forwardx11trusted", ["no"]) || + !exactly("tunnel", ["false", "no"]) || + !exactly("updatehostkeys", ["false", "no"]) || + !exactly("controlmaster", ["false", "no"]) || + !absentOrNone("controlpath") || + !absentOrNone("remotecommand") || + !absentOrNone("proxycommand") || + !absentOrNone("proxyjump") || + !absentOrNone("localcommand") || + !absentOrNone("knownhostscommand") || + values.has("localforward") || + values.has("remoteforward") || + values.has("dynamicforward") || + values.has("setenv") || + !sendEnv.every((value) => value === "lang" || value === "lc_*") + ) { + throw new Error("Effective SSH configuration is unsafe for DGX Spark discovery"); + } +} + +function canonicalSshHost(value: string): boolean { + return net.isIP(value) === 4 || SAFE_TARGET_PATTERN.test(value); +} + +function trustedKnownHostLines( + spawn: DualSparkSpawnSync, + lookupHost: string, + files: readonly string[], +): string[] | null { + const lines = new Set(); + let positive = false; + for (const file of files) { + if (!path.isAbsolute(file) || path.normalize(file) !== file) continue; + let metadata: fs.Stats; + try { + metadata = fs.lstatSync(file); + } catch { + continue; + } + const uid = process.getuid?.(); + if ( + uid === undefined || + metadata.isSymbolicLink() || + !metadata.isFile() || + (metadata.uid !== uid && metadata.uid !== 0) || + (metadata.mode & 0o022) !== 0 + ) { + continue; + } + const result = runCommand(spawn, "ssh-keygen", ["-F", lookupHost, "-f", file]); + if (!commandSucceeded(result, true)) continue; + for (const rawLine of result.stdout.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith("#") || /[\u0000\r\n]/.test(line)) continue; + const fields = line.split(/\s+/); + const marker = fields[0]?.startsWith("@") ? fields.shift() : ""; + if ((marker !== "" && marker !== "@revoked") || fields.length < 3) continue; + const keyType = fields[1] ?? ""; + const keyData = fields[2] ?? ""; + if (!SAFE_SSH_KEY_TYPE_PATTERN.test(keyType) || !SAFE_SSH_KEY_DATA_PATTERN.test(keyData)) { + continue; + } + lines.add(line); + if (marker === "") positive = true; + } + } + if (!positive || lines.size === 0) return null; + const result = [...lines].sort(compareStrings); + stationKnownHostsDigest(`${result.join("\n")}\n`); + return result; +} + +function inspectPretrustedTarget( + spawn: DualSparkSpawnSync, + rawTarget: string, +): QualifiedStationSshIdentity | null { + const target = validatePeerTarget(rawTarget); + const result = runCommand(spawn, "ssh", ["-G", ...strictStationSshTransportArgs(), "--", target]); + if (!commandSucceeded(result, true)) return null; + const config = parseSshConfiguration(result.stdout); + assertStrictSshConfiguration(config); + const resolvedHost = oneSshConfigurationValue(config, "hostname"); + const sshUser = oneSshConfigurationValue(config, "user"); + const port = Number(oneSshConfigurationValue(config, "port")); + if (!canonicalSshHost(resolvedHost) || !SAFE_USERNAME_PATTERN.test(sshUser)) { + throw new Error("Effective SSH endpoint is invalid"); + } + if (!Number.isInteger(port) || port < 1 || port > 65_535) { + throw new Error("Effective SSH port is invalid"); + } + const requestedHost = target.slice(target.lastIndexOf("@") + 1); + if (net.isIP(requestedHost) === 4 && resolvedHost !== requestedHost) { + throw new Error("Automatic rail target was remapped by SSH configuration"); + } + const alias = config.get("hostkeyalias")?.[0]; + const baseLookupHost = alias && alias.toLowerCase() !== "none" ? alias : resolvedHost; + if (!canonicalSshHost(baseLookupHost)) throw new Error("Effective SSH host-key alias is invalid"); + const lookupHost = port === 22 ? baseLookupHost : `[${baseLookupHost}]:${String(port)}`; + const files = [ + ...(config.get("userknownhostsfile") ?? []), + ...(config.get("globalknownhostsfile") ?? []), + ].flatMap((entry) => entry.split(/\s+/).filter((value) => value && value !== "none")); + const knownHostsLines = trustedKnownHostLines(spawn, lookupHost, files); + if (!knownHostsLines) return null; + return { + requestedTarget: target, + sshTarget: target, + resolvedHost, + sshUser, + port, + lookupHost, + hostKeyDigest: stationKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), + knownHostsLines, + }; +} + +function assertPinnedIdentity(identity: QualifiedStationSshIdentity): void { + if ( + validatePeerTarget(identity.sshTarget) !== identity.sshTarget || + identity.requestedTarget !== identity.sshTarget || + !canonicalSshHost(identity.resolvedHost) || + !SAFE_USERNAME_PATTERN.test(identity.sshUser) || + !Number.isInteger(identity.port) || + identity.port < 1 || + identity.port > 65_535 || + !SHA256_PATTERN.test(identity.hostKeyDigest) + ) { + throw new Error("Qualified DGX Spark SSH identity is invalid"); + } + const expectedLookup = + identity.port === 22 + ? identity.resolvedHost + : `[${identity.resolvedHost}]:${String(identity.port)}`; + if (identity.lookupHost !== expectedLookup) { + throw new Error("Qualified DGX Spark SSH host-key lookup is invalid"); + } + const contents = `${identity.knownHostsLines.join("\n")}\n`; + if ( + identity.knownHostsLines.length === 0 || + identity.knownHostsLines.some( + (line) => !line || line !== line.trim() || /[\u0000\r\n]/.test(line), + ) || + stationKnownHostsDigest(contents) !== identity.hostKeyDigest + ) { + throw new Error("Qualified DGX Spark SSH host-key evidence is invalid"); + } +} + +function assertTemporaryPinnedFiles( + directory: string, + knownHostsFile: string, + expectedDigest: string, +): void { + const uid = process.getuid?.(); + if (uid === undefined) throw new Error("DGX Spark discovery requires a POSIX user identity"); + const directoryMetadata = fs.lstatSync(directory); + const fileMetadata = fs.lstatSync(knownHostsFile); + if ( + directoryMetadata.isSymbolicLink() || + !directoryMetadata.isDirectory() || + directoryMetadata.uid !== uid || + (directoryMetadata.mode & 0o777) !== 0o700 || + fileMetadata.isSymbolicLink() || + !fileMetadata.isFile() || + fileMetadata.uid !== uid || + (fileMetadata.mode & 0o777) !== 0o600 || + fs.readdirSync(directory).some((entry) => entry !== path.basename(knownHostsFile)) || + stationKnownHostsDigest(readBoundedLocalFile(knownHostsFile)) !== expectedDigest + ) { + throw new Error("Temporary DGX Spark SSH host-key pin is unsafe"); + } +} + +function openPinnedPeerTransport( + spawn: DualSparkSpawnSync, + identity: QualifiedStationSshIdentity, +): DualSparkPinnedPeerTransport { + assertPinnedIdentity(identity); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dual-spark-")); + fs.chmodSync(directory, 0o700); + const knownHostsFile = path.join(directory, "known_hosts"); + try { + fs.writeFileSync(knownHostsFile, `${identity.knownHostsLines.join("\n")}\n`, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); + fs.chmodSync(knownHostsFile, 0o600); + assertTemporaryPinnedFiles(directory, knownHostsFile, identity.hostKeyDigest); + } catch (error) { + try { + if (fs.existsSync(knownHostsFile)) fs.unlinkSync(knownHostsFile); + fs.rmdirSync(directory); + } catch { + // The exact owner-only temporary path is retained for inspection if safe cleanup fails. + } + throw error; + } + + const execute = (argv: readonly string[]): DualSparkCommandResult => { + validateArgv(argv); + assertTemporaryPinnedFiles(directory, knownHostsFile, identity.hostKeyDigest); + const request = Buffer.from(JSON.stringify({ argv }), "utf8").toString("base64url"); + return runCommand( + spawn, + "ssh", + [ + "-F", + "/dev/null", + ...strictStationSshTransportArgs(), + "-o", + `UserKnownHostsFile=${knownHostsFile}`, + "-o", + "GlobalKnownHostsFile=/dev/null", + "-o", + `HostKeyAlias=${identity.lookupHost}`, + "-o", + `Hostname=${identity.resolvedHost}`, + "-o", + `User=${identity.sshUser}`, + "-o", + `Port=${String(identity.port)}`, + "--", + identity.sshTarget, + "python3", + "-", + request, + ], + REMOTE_ARGV_EXECUTOR, + ); + }; + const transport: DualSparkReadOnlyHostTransport = { + execute, + readFile(filePath) { + if (!path.posix.isAbsolute(filePath) || path.posix.normalize(filePath) !== filePath) { + throw new Error("Remote DGX Spark probe file path is invalid"); + } + const result = execute(["python3", "-c", READ_FILE_SCRIPT, filePath]); + if (!commandSucceeded(result)) throw new Error(`Remote file ${filePath} could not be read`); + if (Buffer.byteLength(result.stdout, "utf8") > MAX_LOCAL_FILE_BYTES) { + throw new Error(`Remote file ${filePath} is too large`); + } + return result.stdout; + }, + readdir(directoryPath) { + if ( + !path.posix.isAbsolute(directoryPath) || + path.posix.normalize(directoryPath) !== directoryPath + ) { + throw new Error("Remote DGX Spark probe directory path is invalid"); + } + const result = execute(["python3", "-c", READDIR_SCRIPT, directoryPath]); + const value = parseJsonCommandResult(result, `Remote directory ${directoryPath}`); + if ( + !Array.isArray(value) || + value.length > MAX_DIRECTORY_ENTRIES || + value.some( + (entry) => + typeof entry !== "string" || + !entry || + entry === "." || + entry === ".." || + entry.includes("/") || + entry.includes("\0"), + ) + ) { + throw new Error(`Remote directory ${directoryPath} returned invalid entries`); + } + return (value as string[]).sort(compareStrings); + }, + }; + return { + transport, + close() { + assertTemporaryPinnedFiles(directory, knownHostsFile, identity.hostKeyDigest); + fs.unlinkSync(knownHostsFile); + fs.rmdirSync(directory); + }, + }; +} + +function isRecordArray(value: unknown): value is Record[] { + return Array.isArray(value) && value.every(isRecord); +} + +function connectivityCheck( + transport: DualSparkReadOnlyHostTransport, + request: DualSparkConnectivityRequest, +): boolean { + const routeResult = transport.execute([ + "ip", + "-j", + "route", + "get", + request.peerAddress, + "from", + request.sourceAddress, + "oif", + request.netdev, + ]); + let routeValue: unknown; + try { + routeValue = parseJsonCommandResult(routeResult, "DGX Spark direct route probe"); + } catch { + return false; + } + if (!isRecordArray(routeValue) || routeValue.length !== 1) return false; + const route = routeValue[0]!; + const routeSource = route.prefsrc ?? route.src; + if ( + route.dev !== request.netdev || + routeSource !== request.sourceAddress || + route.gateway !== undefined || + (route.scope !== undefined && String(route.scope).toLowerCase() !== "link") + ) { + return false; + } + const ping = transport.execute([ + "ping", + "-c", + "1", + "-W", + "2", + "-M", + "do", + "-s", + "8972", + "-I", + request.sourceAddress, + request.peerAddress, + ]); + if (!commandSucceeded(ping)) return false; + const neighborResult = transport.execute([ + "ip", + "-j", + "neigh", + "show", + "to", + request.peerAddress, + "dev", + request.netdev, + ]); + let neighborValue: unknown; + try { + neighborValue = parseJsonCommandResult(neighborResult, "DGX Spark neighbor probe"); + } catch { + return false; + } + if (!isRecordArray(neighborValue) || neighborValue.length !== 1) return false; + const neighbor = neighborValue[0]!; + const states = Array.isArray(neighbor.state) ? neighbor.state : [neighbor.state]; + return ( + String(neighbor.dst ?? "") === request.peerAddress && + String(neighbor.dev ?? "") === request.netdev && + String(neighbor.lladdr ?? "").toLowerCase() === request.expectedPeerMac && + states.length > 0 && + states.every( + (state) => + typeof state === "string" && + /^(?:REACHABLE|STALE|DELAY|PROBE|PERMANENT|NOARP)$/i.test(state), + ) + ); +} + +function probeConnectivity( + transport: DualSparkReadOnlyHostTransport, + requests: readonly DualSparkConnectivityRequest[], +): boolean { + if ( + requests.length !== 2 || + new Set(requests.map(({ netdev }) => netdev)).size !== 2 || + requests.some( + ({ netdev, sourceAddress, peerAddress, expectedPeerMac }) => + !SAFE_DEVICE_PATTERN.test(netdev) || + net.isIP(sourceAddress) !== 4 || + net.isIP(peerAddress) !== 4 || + !MAC_PATTERN.test(expectedPeerMac), + ) + ) { + return false; + } + return requests.every((request) => connectivityCheck(transport, request)); +} + +function createCanonicalReadiness( + host: DualSparkHostObservation, + transport: DualSparkReadOnlyHostTransport, + buildIdentity: BuildIdentity, + now: Date, +): SystemReadinessReport { + const runCaptureImpl = ( + argv: readonly string[], + options?: { readonly ignoreError?: boolean }, + ): string => { + const result = transport.execute(argv); + if (!commandSucceeded(result) && options?.ignoreError !== true) { + throw new Error(`Readiness command ${argv[0] ?? "unknown"} failed`); + } + return commandSucceeded(result) ? result.stdout : ""; + }; + const releaseResult = transport.execute(["uname", "-r"]); + if (!commandSucceeded(releaseResult, true)) { + throw new Error("DGX Spark kernel release could not be observed"); + } + let procVersion = ""; + try { + procVersion = transport.readFile("/proc/version"); + } catch { + // assessHost treats an unavailable proc version as absent WSL evidence. + } + const assessment = assessHost({ + platform: "linux", + env: {}, + release: releaseResult.stdout.trim(), + procVersion, + readFileImpl: (filePath) => transport.readFile(filePath), + readdirImpl: (directory) => transport.readdir(directory), + runCaptureImpl, + gpuProbeImpl: () => host.gpus.length === 1, + }); + const platformIdentity = collectPlatformIdentity({ + readFile: (filePath) => transport.readFile(filePath), + readdir: (directory) => transport.readdir(directory), + }); + return createHostReadinessReport( + { + nemoclawVersion: buildIdentity.nemoclawVersion, + sourceRevision: buildIdentity.sourceRevision, + now: () => now, + }, + { + now: () => now, + architecture: "arm64", + assess: () => assessment, + detectHostGpuPlatform: () => "spark", + collectPlatformIdentity: () => platformIdentity, + }, + ); +} + +function claimBinding(statePath: string): boolean { + const bindingDirectory = dualStationSshBindingDirectory(statePath); + const parent = path.dirname(bindingDirectory); + const uid = process.getuid?.(); + if (uid === undefined) throw new Error("DGX Spark binding claim requires a POSIX user identity"); + const parentMetadata = fs.lstatSync(parent); + if ( + parentMetadata.isSymbolicLink() || + !parentMetadata.isDirectory() || + parentMetadata.uid !== uid || + (parentMetadata.mode & 0o777) !== 0o700 + ) { + throw new Error("DGX Spark binding parent is unsafe"); + } + try { + fs.mkdirSync(bindingDirectory, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") return false; + throw error; + } + try { + fs.chmodSync(bindingDirectory, 0o700); + const descriptor = fs.openSync(parent, fs.constants.O_RDONLY); + try { + fs.fsyncSync(descriptor); + } finally { + fs.closeSync(descriptor); + } + } catch (error) { + try { + fs.rmdirSync(bindingDirectory); + } catch { + // Retain the exclusive claim if its safe cleanup cannot be completed. + } + throw error; + } + return true; +} + +/** + * Construct the production discovery seams. The optional spawn adapter exists + * only so strict SSH argv behavior can be tested without network or host mutation. + */ +export function createProductionDualSparkDiscoveryDeps( + parseHost: DualSparkHostParser, + spawn: DualSparkSpawnSync = defaultSpawnSync, +): DualSparkDiscoveryDeps { + return { + now: () => new Date(), + currentUid: () => process.getuid?.() ?? null, + getBuildIdentity, + localTransport: () => createLocalTransport(spawn), + probeHost: (transport) => probeHostWithTransport(transport, parseHost), + inspectPretrustedTarget: (target) => inspectPretrustedTarget(spawn, target), + openPinnedPeerTransport: (identity) => openPinnedPeerTransport(spawn, identity), + createReadiness: createCanonicalReadiness, + probeConnectivity, + claimBinding, + writeBinding: writeDualStationSshBinding, + clearBinding: clearDualStationSshBinding, + encodeBinding: encodeDualStationSshBindingHandoff, + resolveBindingStatePath: () => + path.join(managedVllmStateDir(), DUAL_SPARK_MANAGED_SERVING_STATE_FILE), + }; +} diff --git a/src/lib/inference/serving/dual-spark-discovery.test.ts b/src/lib/inference/serving/dual-spark-discovery.test.ts new file mode 100644 index 00000000000..3b03a389b01 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-discovery.test.ts @@ -0,0 +1,813 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { SpawnSyncOptionsWithStringEncoding } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { + type DualStationSshBinding, + type QualifiedStationSshIdentity, + stationKnownHostsDigest, +} from "../vllm-station-ssh-binding.js"; +import { DUAL_SPARK_PRESET_ID } from "./catalog-types.js"; +import { + confirmDualSparkManagedServingCapability, + createDualSparkDiscoveryDeps, + type DualSparkDiscoveryDeps, + type DualSparkHostObservation, + type DualSparkReadOnlyHostTransport, + type DualSparkSpawnSync, + NEMOCLAW_DGX_SPARK_PEER_ENV, + NEMOCLAW_SERVING_PRESET_ENV, + parseDualSparkHostObservation, + probeDualSparkManagedServingCapability, +} from "./dual-spark-discovery.js"; +import { DUAL_SPARK_MANAGED_LABEL } from "./dual-spark-materialize.js"; + +const NOW = new Date("2026-08-02T20:00:00.000Z"); +const SOURCE_REVISION = "1d6948d89b46eab739728215f9a19ef40b8f6121"; +const REQUIRED_CAPABILITIES = [ + "host.platform.supported", + "host.platform.dgx_spark", + "host.docker.available", + "host.docker.daemon_reachable", + "host.docker.runtime_supported", + "host.docker.storage_compatible", + "host.gpu.nvidia_available", + "host.gpu.container_toolkit_available", + "host.gpu.cdi_healthy", +] as const; + +type StoppedForeignContainerFixture = { + readonly signal: string; + readonly name: string; + readonly image: string; + readonly labels: Readonly>; +}; + +const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixture[] = [ + { + signal: "name", + name: "foreign-vllm-server", + image: "example.invalid/inference:latest", + labels: {}, + }, + { + signal: "image", + name: "foreign-inference", + image: "vllm/vllm-openai:latest", + labels: {}, + }, + { + signal: "managed label", + name: "foreign-inference", + image: "example.invalid/inference:latest", + labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + }, +]; + +function readiness(overrides: Partial = {}): SystemReadinessReport { + return { + schemaVersion: "1.1.0", + status: "supported", + exitCode: 0, + mutated: false, + provenance: { + nemoclawVersion: "0.1.0", + sourceRevision: SOURCE_REVISION, + observedAt: NOW.toISOString(), + }, + observations: [], + capabilities: REQUIRED_CAPABILITIES.map((id) => ({ id, state: "present" as const })), + qualifications: [ + { + id: "host.platform.dgx_spark", + status: "qualified", + capabilityIds: ["host.platform.dgx_spark"], + }, + ], + findings: [], + evidence: [], + ...overrides, + } as SystemReadinessReport; +} + +function capacity( + requestedPath: string, + uid: number, + gid: number, + overrides: Record = {}, +) { + return { + requestedPath, + probePath: requestedPath, + filesystemId: requestedPath.includes("docker") ? "docker-fs" : "home-fs", + availableBytes: 400_000_000_000, + availableInodes: 1_000_000, + ownerUid: uid, + ownerGid: gid, + isDirectory: true, + writableByUser: true, + ...overrides, + }; +} + +function host( + role: "local" | "peer", + overrides: Partial = {}, +): DualSparkHostObservation { + const local = role === "local"; + const uid = 1000; + const gid = 1000; + const home = "/home/nvidia"; + const rail = (index: 0 | 1) => { + const third = 100 + index; + const address = `192.168.${String(third)}.${local ? "1" : "2"}`; + return { + physicalPortId: local ? "cx7-local" : "cx7-peer", + netdev: `enp${String(index + 1)}s0f0np0`, + hcaDevice: `rocep${String(index + 1)}s0f0`, + hcaPort: 1, + macAddress: local + ? `02:00:00:00:00:0${String(index + 1)}` + : `02:00:00:00:01:0${String(index + 1)}`, + pciAddress: `0000:0${String(index + 1)}:00.0`, + pciName: "NVIDIA Mellanox ConnectX-7", + state: "4: ACTIVE", + operState: "up", + carrier: true, + linkLayer: "Ethernet", + speedMbps: 200_000, + mtu: 9000, + ipv4Addresses: [{ address, prefixLength: 30 }], + roceV2Ipv4Gids: [ + { + index: 3 + index, + value: `::ffff:192.168.${String(third)}.${local ? "1" : "2"}`, + ipv4Address: address, + }, + ], + }; + }; + const cacheRoot = `${home}/.cache/huggingface`; + return { + schemaVersion: 1, + hostname: local ? "spark-head" : "spark-worker", + nodeId: local ? "11111111111111111111111111111111" : "22222222222222222222222222222222", + productName: "NVIDIA DGX Spark", + architecture: "aarch64", + home, + username: "nvidia", + uid, + gid, + gpus: [ + { + index: 0, + name: "NVIDIA GB10", + uuid: local + ? "GPU-11111111-1111-1111-1111-111111111111" + : "GPU-22222222-2222-2222-2222-222222222222", + }, + ], + rails: [rail(0), rail(1)], + earlyoom: { installed: false, active: "inactive", enabled: "disabled" }, + runtimeInspectionComplete: true, + runtimeSnapshot: { containers: [], listeningPorts: [] }, + storage: { + huggingFace: { + ...capacity(cacheRoot, uid, gid), + cacheRoot, + snapshotPath: `${cacheRoot}/hub/models--deepseek/snapshots/revision`, + snapshotBytes: 0, + exactSnapshotCached: false, + }, + docker: { + ...capacity("/var/lib/docker", 0, 0), + dockerRootDir: "/var/lib/docker", + exactImageCached: false, + }, + }, + ...overrides, + }; +} + +const transport = (name: string): DualSparkReadOnlyHostTransport => ({ + execute: () => ({ status: 0, stdout: name, stderr: "" }), + readFile: () => name, + readdir: () => [], +}); + +function identity(target: string): QualifiedStationSshIdentity { + const knownHostsLines = [`${target} ssh-ed25519 AAAA`]; + return { + requestedTarget: target, + sshTarget: target, + resolvedHost: target, + sshUser: "nvidia", + port: 22, + lookupHost: target, + hostKeyDigest: stationKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), + knownHostsLines, + }; +} + +function binding(peerIdentity: QualifiedStationSshIdentity): DualStationSshBinding { + return { + schemaVersion: 2, + peerTarget: peerIdentity.sshTarget, + resolvedHost: peerIdentity.resolvedHost, + sshUser: peerIdentity.sshUser, + port: peerIdentity.port, + lookupHost: peerIdentity.lookupHost, + hostKeyDigest: peerIdentity.hostKeyDigest, + bindingFile: "/state/binding.json", + dockerCliFile: "/usr/bin/docker", + dockerShimFile: "/state/docker", + dockerShimSha256: "a".repeat(64), + knownHostsFile: "/state/known_hosts", + knownHostsSha256: "b".repeat(64), + sshWrapperDirectory: "/state/bin", + sshWrapperFile: "/state/bin/ssh", + sshWrapperSha256: "c".repeat(64), + }; +} + +function fixture(overrides: Partial = {}) { + const events: string[] = []; + const localTransport = transport("local"); + const peerTransports = new Map([ + ["192.168.100.2", transport("peer-100")], + ["192.168.101.2", transport("peer-101")], + ]); + let bindingWrites = 0; + const deps: DualSparkDiscoveryDeps = { + now: () => NOW, + currentUid: () => 1000, + getBuildIdentity: () => ({ nemoclawVersion: "0.1.0", sourceRevision: SOURCE_REVISION }), + localTransport: () => localTransport, + probeHost: (candidate) => (candidate === localTransport ? host("local") : host("peer")), + inspectPretrustedTarget: (target) => identity(target), + openPinnedPeerTransport: (peerIdentity) => { + events.push(`open:${peerIdentity.requestedTarget}`); + return { + transport: peerTransports.get(peerIdentity.requestedTarget) ?? transport("explicit-peer"), + close: () => events.push(`close:${peerIdentity.requestedTarget}`), + }; + }, + createReadiness: (observedHost) => { + events.push(`readiness:${observedHost.hostname}`); + return readiness(); + }, + probeConnectivity: (_candidate, requests) => { + events.push(`connectivity:${requests[0]?.sourceAddress ?? "missing"}`); + return true; + }, + claimBinding: () => true, + writeBinding: (_statePath, peerIdentity) => { + bindingWrites += 1; + events.push("write-binding"); + return binding(peerIdentity); + }, + clearBinding: () => events.push("clear-binding"), + encodeBinding: () => "binding-token", + resolveBindingStatePath: () => "/state/dual-spark.json", + ...overrides, + }; + return { deps, events, bindingWrites: () => bindingWrites, localTransport }; +} + +describe("dual DGX Spark managed-serving discovery", () => { + it("accepts the bounded production observation and rejects malformed cache metadata", () => { + const observed = host("local"); + expect(parseDualSparkHostObservation(observed)).toBe(observed); + expect(() => + parseDualSparkHostObservation({ + ...observed, + storage: { + ...observed.storage, + huggingFace: { ...observed.storage.huggingFace, isDirectory: "yes" }, + }, + }), + ).toThrow("DGX Spark host observation is invalid"); + }); + + it("does nothing when another serving preset is selected", () => { + const { deps, events, bindingWrites } = fixture({ + localTransport: () => { + throw new Error("must not probe"); + }, + }); + + expect( + probeDualSparkManagedServingCapability({ + env: { [NEMOCLAW_SERVING_PRESET_ENV]: "another-preset" }, + deps, + }), + ).toEqual({ + kind: "not-selected", + code: "no-match", + reason: "Another managed inference preset is selected.", + }); + expect(events).toEqual([]); + expect(bindingWrites()).toBe(0); + }); + + it("persists one binding only after the detected pair is confirmed and revalidated", () => { + const { deps, events, bindingWrites } = fixture(); + + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + + expect(detected).toMatchObject({ + kind: "ready", + selectionIntent: "automatic", + peerSshBindingStatePath: "/state/dual-spark.json", + local: { hostname: "spark-head", uid: 1000 }, + peer: { hostname: "spark-worker", uid: 1000 }, + topology: { status: "qualified" }, + }); + expect(bindingWrites()).toBe(0); + expect(events).not.toContain("write-binding"); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + + const confirmed = confirmDualSparkManagedServingCapability(detected, { env: {}, deps }); + + expect(confirmed).toMatchObject({ + kind: "ready", + peerSshBindingHandle: "binding-token", + topology: { + output: { peer: { sshBindingHandle: "binding-token" } }, + }, + }); + expect(bindingWrites()).toBe(1); + expect(events.filter((event) => event.startsWith("open:"))).toEqual([ + "open:192.168.100.2", + "open:192.168.101.2", + "open:192.168.100.2", + "open:192.168.101.2", + ]); + expect(events.indexOf("write-binding")).toBeGreaterThan( + events.lastIndexOf("readiness:spark-worker"), + ); + expect(events.filter((event) => event.startsWith("close:"))).toHaveLength(4); + }); + + it("returns an ordinary automatic no-match when both rails are not pretrusted", () => { + const { deps, bindingWrites } = fixture({ inspectPretrustedTarget: () => null }); + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "not-selected", + code: "no-match", + }); + expect(bindingWrites()).toBe(0); + }); + + it("makes the same peer failure hard when the exact preset was requested", () => { + const { deps } = fixture({ inspectPretrustedTarget: () => null }); + + expect( + probeDualSparkManagedServingCapability({ + env: { [NEMOCLAW_SERVING_PRESET_ENV]: DUAL_SPARK_PRESET_ID }, + deps, + }), + ).toMatchObject({ kind: "unavailable", code: "peer-trust-unavailable" }); + }); + + it("makes an explicit peer failure hard", () => { + const { deps } = fixture({ inspectPretrustedTarget: () => null }); + + expect( + probeDualSparkManagedServingCapability({ + env: { [NEMOCLAW_DGX_SPARK_PEER_ENV]: "spark-worker.local" }, + deps, + }), + ).toMatchObject({ kind: "unavailable", code: "peer-trust-unavailable" }); + }); + + it("does not merge rail addresses that have different host-key identities", () => { + const { deps, bindingWrites } = fixture({ + inspectPretrustedTarget: (target) => { + const observed = identity(target); + return target.endsWith("101.2") ? { ...observed, hostKeyDigest: "f".repeat(64) } : observed; + }, + }); + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "not-selected", + code: "no-match", + }); + expect(bindingWrites()).toBe(0); + }); + + it.each( + STOPPED_FOREIGN_CONTAINER_FIXTURES, + )("preserves a stopped foreign vLLM setup identified by $signal", (container) => { + const base = fixture(); + const deps = { + ...base.deps, + probeHost: (candidate: DualSparkReadOnlyHostTransport) => + candidate === base.localTransport + ? host("local", { + runtimeSnapshot: { + containers: [ + { + id: "9".repeat(64), + name: container.name, + image: container.image, + running: false, + healthy: false, + labels: container.labels, + }, + ], + listeningPorts: [], + }, + }) + : host("peer"), + }; + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "not-selected", + code: "runtime-conflict", + }); + expect(base.bindingWrites()).toBe(0); + expect(base.events).not.toContain("write-binding"); + }); + + it("does not classify an arbitrary stopped container as a managed vLLM setup", () => { + const base = fixture(); + const deps = { + ...base.deps, + probeHost: (candidate: DualSparkReadOnlyHostTransport) => + candidate === base.localTransport + ? host("local", { + runtimeSnapshot: { + containers: [ + { + id: "9".repeat(64), + name: "unrelated-service", + image: "example.invalid/worker:latest", + running: false, + healthy: false, + labels: { "example.foreign": "true" }, + }, + ], + listeningPorts: [], + }, + }) + : host("peer"), + }; + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "ready", + }); + expect(base.bindingWrites()).toBe(0); + }); + + it.each([ + { + name: "an active earlyoom service", + mutate: (value: DualSparkHostObservation) => ({ + ...value, + earlyoom: { installed: true, active: "active" as const, enabled: "enabled" as const }, + }), + code: "no-match", + }, + { + name: "a related runtime", + mutate: (value: DualSparkHostObservation) => ({ + ...value, + runtimeSnapshot: { + containers: [], + listeningPorts: [8000], + }, + }), + code: "runtime-conflict", + }, + { + name: "an inconclusive runtime inspection", + mutate: (value: DualSparkHostObservation) => ({ ...value, runtimeInspectionComplete: false }), + code: "runtime-unknown", + }, + { + name: "a missing exact cache root", + mutate: (value: DualSparkHostObservation) => ({ + ...value, + storage: { + ...value.storage, + huggingFace: { ...value.storage.huggingFace, probePath: value.home }, + }, + }), + code: "no-match", + }, + ])("preserves host state for $name", ({ mutate, code }) => { + const base = fixture(); + const deps = { + ...base.deps, + probeHost: (candidate: DualSparkReadOnlyHostTransport) => + candidate === base.localTransport ? mutate(host("local")) : host("peer"), + }; + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "not-selected", + code, + }); + expect(base.bindingWrites()).toBe(0); + expect(base.events).not.toContain("write-binding"); + }); + + it("does not claim when the exact pretrusted peer identity changes after confirmation", () => { + const base = fixture(); + let inspections = 0; + const deps: DualSparkDiscoveryDeps = { + ...base.deps, + inspectPretrustedTarget: (target) => { + inspections += 1; + const observed = identity(target); + return inspections > 2 + ? { ...observed, sshTarget: "spark-worker.local", resolvedHost: "spark-worker.local" } + : observed; + }, + claimBinding: () => { + base.events.push("claim-binding"); + return true; + }, + }; + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + + expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + kind: "unavailable", + code: "peer-identity-ambiguous", + }); + expect(base.events).not.toContain("claim-binding"); + expect(base.bindingWrites()).toBe(0); + }); + + it("rechecks related runtime and listeners before claiming the binding", () => { + const base = fixture(); + let runtimeAppeared = false; + const deps: DualSparkDiscoveryDeps = { + ...base.deps, + probeHost: (candidate) => + candidate === base.localTransport && runtimeAppeared + ? host("local", { runtimeSnapshot: { containers: [], listeningPorts: [8000] } }) + : candidate === base.localTransport + ? host("local") + : host("peer"), + claimBinding: () => { + base.events.push("claim-binding"); + return true; + }, + }; + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + runtimeAppeared = true; + + expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + kind: "unavailable", + code: "runtime-conflict", + }); + expect(base.events).not.toContain("claim-binding"); + expect(base.bindingWrites()).toBe(0); + }); + + it("preserves an existing binding as a hard automatic conflict", () => { + const { deps, events, bindingWrites } = fixture({ claimBinding: () => false }); + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + + expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + kind: "unavailable", + code: "binding-conflict", + }); + expect(bindingWrites()).toBe(0); + expect(events).not.toContain("clear-binding"); + }); + + it("cleans only the new transaction binding when persistence fails", () => { + const { deps, events } = fixture({ + writeBinding: () => { + events.push("write-binding"); + throw new Error("partial write"); + }, + }); + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + + expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + kind: "unavailable", + code: "binding-persistence-failed", + }); + expect(events).toContain("clear-binding"); + expect(events.indexOf("clear-binding")).toBeGreaterThan(events.indexOf("write-binding")); + }); + + it("cleans its claimed binding when handle encoding fails", () => { + const base = fixture(); + const deps = { + ...base.deps, + encodeBinding: () => { + base.events.push("encode-binding"); + throw new Error("encode failed"); + }, + }; + const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + if (detected.kind !== "ready") throw new Error("expected a detected pair"); + + expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + kind: "unavailable", + code: "binding-persistence-failed", + }); + expect(base.events.filter((event) => event === "clear-binding")).toEqual(["clear-binding"]); + expect(base.events.indexOf("clear-binding")).toBeGreaterThan( + base.events.indexOf("encode-binding"), + ); + }); + + it("fails closed when the controller UID differs from the local cache owner", () => { + const { deps, bindingWrites } = fixture({ currentUid: () => 2000 }); + + expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + kind: "not-selected", + code: "no-match", + }); + expect(bindingWrites()).toBe(0); + }); +}); + +describe("production pinned peer transport", () => { + it("atomically preserves an existing binding-root owner", () => { + const parent = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-spark-binding-")); + fs.chmodSync(parent, 0o700); + const statePath = path.join(parent, "dual-spark.json"); + const bindingRoot = `${statePath}.ssh-binding`; + const deps = createDualSparkDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "" })); + + try { + expect(deps.claimBinding(statePath)).toBe(true); + fs.writeFileSync(path.join(bindingRoot, "owner"), "first\n", { mode: 0o600 }); + expect(deps.claimBinding(statePath)).toBe(false); + expect(fs.readFileSync(path.join(bindingRoot, "owner"), "utf8")).toBe("first\n"); + } finally { + deps.clearBinding(statePath); + fs.rmdirSync(parent); + } + }); + + it("pins local and remote host probes to the physical default Docker daemon", () => { + const calls: Array<{ + file: string; + args: readonly string[]; + options: SpawnSyncOptionsWithStringEncoding; + }> = []; + const spawn: DualSparkSpawnSync = (file, args, options) => { + calls.push({ file, args: [...args], options }); + return { + status: 0, + stdout: JSON.stringify(calls.length === 1 ? host("local") : host("peer")), + stderr: "", + }; + }; + const dockerNames = ["DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG"] as const; + const previous = new Map(dockerNames.map((name) => [name, process.env[name]])); + process.env.DOCKER_HOST = "tcp://ambient.example:2376"; + process.env.DOCKER_CONTEXT = "ambient-remote"; + process.env.DOCKER_CONFIG = "/tmp/ambient-docker-config"; + + try { + const deps = createDualSparkDiscoveryDeps(spawn); + expect(deps.probeHost(deps.localTransport()).hostname).toBe("spark-head"); + const pinned = deps.openPinnedPeerTransport(identity("192.168.100.2")); + try { + expect(deps.probeHost(pinned.transport).hostname).toBe("spark-worker"); + } finally { + pinned.close(); + } + } finally { + for (const name of dockerNames) { + const value = previous.get(name); + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } + + expect(calls).toHaveLength(2); + const local = calls[0]!; + expect(local.file).toBe("python3"); + expect(local.options.env).toMatchObject({ DOCKER_CONTEXT: "default" }); + expect(local.options.env).not.toHaveProperty("DOCKER_HOST"); + expect(local.options.env).not.toHaveProperty("DOCKER_CONFIG"); + + const remote = calls[1]!; + expect(remote.file).toBe("ssh"); + expect(remote.options.env).not.toHaveProperty("DOCKER_HOST"); + expect(remote.options.env).not.toHaveProperty("DOCKER_CONTEXT"); + expect(remote.options.env).not.toHaveProperty("DOCKER_CONFIG"); + const request = JSON.parse(Buffer.from(remote.args.at(-1)!, "base64url").toString("utf8")); + const script = request.argv[2] as string; + expect(script).toContain("env.pop(name, None)"); + expect(script).toContain('env["DOCKER_CONTEXT"] = "default"'); + }); + + it("requires direct routes, exact neighbors, and jumbo reachability on both rails", () => { + const deps = createDualSparkDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "" })); + const requests = [ + { + netdev: "enp1s0f0np0", + sourceAddress: "192.168.100.1", + peerAddress: "192.168.100.2", + expectedPeerMac: "02:00:00:00:01:01", + }, + { + netdev: "enp2s0f0np0", + sourceAddress: "192.168.101.1", + peerAddress: "192.168.101.2", + expectedPeerMac: "02:00:00:00:01:02", + }, + ]; + let routedThroughGateway = false; + const directTransport: DualSparkReadOnlyHostTransport = { + execute: (argv) => { + if (argv[1] === "-j" && argv[2] === "route") { + return { + status: 0, + stdout: JSON.stringify([ + { + dev: argv.at(-1), + prefsrc: argv[6], + scope: "link", + ...(routedThroughGateway ? { gateway: "192.168.100.254" } : {}), + }, + ]), + stderr: "", + }; + } + if (argv[0] === "ping") return { status: 0, stdout: "", stderr: "" }; + const request = requests.find(({ peerAddress }) => peerAddress === argv[5])!; + return { + status: 0, + stdout: JSON.stringify([ + { + dst: request.peerAddress, + dev: request.netdev, + lladdr: request.expectedPeerMac, + state: ["REACHABLE"], + }, + ]), + stderr: "", + }; + }, + readFile: () => "", + readdir: () => [], + }; + + expect(deps.probeConnectivity(directTransport, requests)).toBe(true); + routedThroughGateway = true; + expect(deps.probeConnectivity(directTransport, requests)).toBe(false); + }); + + it("uses strict SSH and a fixed argv executor without interpolated shell", () => { + const calls: Array<{ + file: string; + args: readonly string[]; + options: SpawnSyncOptionsWithStringEncoding; + }> = []; + const spawn: DualSparkSpawnSync = (file, args, options) => { + calls.push({ file, args: [...args], options }); + return { status: 0, stdout: "aarch64\n", stderr: "" }; + }; + const deps = createDualSparkDiscoveryDeps(spawn); + const pinned = deps.openPinnedPeerTransport(identity("192.168.100.2")); + + try { + expect(pinned.transport.execute(["uname", "-m"])).toMatchObject({ status: 0 }); + } finally { + pinned.close(); + } + + expect(calls).toHaveLength(1); + const call = calls[0]!; + expect(call.file).toBe("ssh"); + expect(call.args.slice(0, 2)).toEqual(["-F", "/dev/null"]); + expect(call.args).toEqual( + expect.arrayContaining([ + "BatchMode=yes", + "StrictHostKeyChecking=yes", + "PasswordAuthentication=no", + "ProxyCommand=none", + "ProxyJump=none", + "GlobalKnownHostsFile=/dev/null", + ]), + ); + expect(call.args.slice(-4, -1)).toEqual(["192.168.100.2", "python3", "-"]); + const request = JSON.parse(Buffer.from(call.args.at(-1)!, "base64url").toString("utf8")); + expect(request).toEqual({ argv: ["uname", "-m"] }); + expect(call.options.input).toContain("subprocess.run("); + expect(call.options.input).toContain("shell=False"); + expect(call.options.input).not.toContain("uname"); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-discovery.ts b/src/lib/inference/serving/dual-spark-discovery.ts new file mode 100644 index 00000000000..6cff0448627 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-discovery.ts @@ -0,0 +1,1218 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import net from "node:net"; +import path from "node:path"; + +import type { BuildIdentity } from "../../core/version.js"; +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { + type DualStationSshBinding, + type QualifiedStationSshIdentity, +} from "../vllm-station-ssh-binding.js"; +import { imageStorageRequirementBytes, modelStorageRequirementBytes } from "../vllm-storage.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; +import { DUAL_SPARK_PRESET_ID } from "./catalog-types.js"; +import { createProductionDualSparkDiscoveryDeps } from "./dual-spark-discovery-production.js"; +import { + type DualSparkNodeSnapshot, + type DualSparkObservedContainer, + isRelatedManagedVllmContainer, +} from "./dual-spark-lifecycle.js"; +import { DUAL_SPARK_VLLM_API_PORT, DUAL_SPARK_VLLM_MASTER_PORT } from "./dual-spark-materialize.js"; +import { + type DualSparkNodeObservation, + type DualSparkPeerObservation, + type DualSparkRailObservation, + type DualSparkTopologyArtifact, + type DualSparkTopologyOutput, + dualSparkTopologyOutputDigest, + getDualSparkTopologyArtifactError, + qualifyDualSparkTopology, +} from "./dual-spark-topology.js"; + +export const NEMOCLAW_DGX_SPARK_PEER_ENV = "NEMOCLAW_DGX_SPARK_PEER" as const; +export const NEMOCLAW_SERVING_PRESET_ENV = "NEMOCLAW_SERVING_PRESET" as const; + +const HOST_PROBE_SCHEMA_VERSION = 1; +const DIRECT_RAIL_PREFIX_LENGTH = 30; +const EXPECTED_CX7_SPEED_MBPS = 200_000; +const MINIMUM_CX7_MTU = 9_000; +const VLLM_WRITABLE_ALLOWANCE_BYTES = 816_000_000n; +const MINIMUM_AVAILABLE_INODES = 1_024; +const SAFE_TARGET_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; +const SAFE_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const GPU_UUID_PATTERN = /^GPU-[A-Za-z0-9-]+$/; +const MACHINE_ID_PATTERN = /^[a-f0-9]{32}$/; +const MAC_PATTERN = /^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/; +const PCI_ADDRESS_PATTERN = /^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/; +const SHA256_PATTERN = /^[a-f0-9]{64}$/; + +export interface DualSparkCommandResult { + readonly status: number | null; + readonly stdout: string; + readonly stderr: string; + readonly error?: string; +} + +export interface DualSparkReadOnlyHostTransport { + execute(argv: readonly string[]): DualSparkCommandResult; + readFile(filePath: string): string; + readdir(directory: string): string[]; +} + +export interface DualSparkGpuObservation { + readonly index: number; + readonly name: string; + readonly uuid: string; +} + +export interface DualSparkIpv4Observation { + readonly address: string; + readonly prefixLength: number; +} + +export interface DualSparkRoceGidHostObservation { + readonly index: number; + readonly value: string; + readonly ipv4Address: string; +} + +export interface DualSparkCx7RailHostObservation { + readonly physicalPortId: string; + readonly netdev: string; + readonly hcaDevice: string; + readonly hcaPort: number; + readonly macAddress: string; + readonly pciAddress: string; + readonly pciName: string; + readonly state: string; + readonly operState: string; + readonly carrier: boolean; + readonly linkLayer: string; + readonly speedMbps: number; + readonly mtu: number; + readonly ipv4Addresses: readonly DualSparkIpv4Observation[]; + readonly roceV2Ipv4Gids: readonly DualSparkRoceGidHostObservation[]; +} + +export interface DualSparkEarlyoomObservation { + readonly installed: boolean; + readonly active: "active" | "inactive" | "unknown"; + readonly enabled: "enabled" | "disabled" | "unknown"; +} + +export interface DualSparkStorageCapacityObservation { + readonly requestedPath: string; + readonly probePath: string | null; + readonly filesystemId: string | null; + readonly availableBytes: number | null; + readonly availableInodes: number | null; + readonly ownerUid: number | null; + readonly ownerGid: number | null; + readonly isDirectory: boolean; + readonly writableByUser: boolean; +} + +export interface DualSparkStorageObservation { + readonly huggingFace: DualSparkStorageCapacityObservation & { + readonly cacheRoot: string; + readonly snapshotPath: string; + readonly snapshotBytes: number | null; + readonly exactSnapshotCached: boolean; + }; + readonly docker: DualSparkStorageCapacityObservation & { + readonly dockerRootDir: string | null; + readonly exactImageCached: boolean; + }; +} + +export interface DualSparkHostObservation { + readonly schemaVersion: 1; + readonly hostname: string; + readonly nodeId: string; + readonly productName: string; + readonly architecture: string; + readonly home: string; + readonly username: string; + readonly uid: number; + readonly gid: number; + readonly gpus: readonly DualSparkGpuObservation[]; + readonly rails: readonly DualSparkCx7RailHostObservation[]; + readonly earlyoom: DualSparkEarlyoomObservation; + readonly runtimeInspectionComplete: boolean; + readonly runtimeSnapshot: DualSparkNodeSnapshot; + readonly storage: DualSparkStorageObservation; +} + +export interface DualSparkPinnedPeerTransport { + readonly transport: DualSparkReadOnlyHostTransport; + close(): void; +} + +export interface DualSparkConnectivityRequest { + readonly netdev: string; + readonly sourceAddress: string; + readonly peerAddress: string; + readonly expectedPeerMac: string; +} + +export interface DualSparkDiscoveryDeps { + now(): Date; + currentUid(): number | null; + getBuildIdentity(): BuildIdentity; + localTransport(): DualSparkReadOnlyHostTransport; + probeHost(transport: DualSparkReadOnlyHostTransport): DualSparkHostObservation; + inspectPretrustedTarget(target: string): QualifiedStationSshIdentity | null; + openPinnedPeerTransport(identity: QualifiedStationSshIdentity): DualSparkPinnedPeerTransport; + createReadiness( + host: DualSparkHostObservation, + transport: DualSparkReadOnlyHostTransport, + buildIdentity: BuildIdentity, + now: Date, + ): SystemReadinessReport; + probeConnectivity( + transport: DualSparkReadOnlyHostTransport, + requests: readonly DualSparkConnectivityRequest[], + ): boolean; + /** Atomically claim a new binding root. False means an existing owner won. */ + claimBinding(statePath: string): boolean; + writeBinding(statePath: string, identity: QualifiedStationSshIdentity): DualStationSshBinding; + clearBinding(statePath: string): void; + encodeBinding(binding: DualStationSshBinding): string; + resolveBindingStatePath(): string; +} + +export type DualSparkManagedServingFailureCode = + | "no-match" + | "incompatible-selection" + | "invalid-peer" + | "local-host-unavailable" + | "peer-trust-unavailable" + | "peer-identity-ambiguous" + | "peer-host-unavailable" + | "host-unqualified" + | "earlyoom-active" + | "earlyoom-unknown" + | "storage-unavailable" + | "storage-insufficient" + | "runtime-conflict" + | "runtime-unknown" + | "fabric-unavailable" + | "connectivity-unavailable" + | "readiness-unavailable" + | "binding-conflict" + | "binding-persistence-failed" + | "topology-unavailable"; + +export type DualSparkDetectedManagedServingCapability = { + readonly kind: "ready"; + readonly selectionIntent: "automatic" | "explicit"; + readonly topology: DualSparkTopologyArtifact; + readonly local: DualSparkHostObservation; + readonly peer: DualSparkHostObservation; + readonly readiness: readonly [ + { readonly nodeId: string; readonly report: SystemReadinessReport }, + { readonly nodeId: string; readonly report: SystemReadinessReport }, + ]; + /** Exact transaction state path that may be claimed only after confirmation. */ + readonly peerSshBindingStatePath: string; + readonly peerSshIdentity: QualifiedStationSshIdentity; +}; + +export type DualSparkManagedServingCapability = + | { + readonly kind: "not-selected"; + readonly code: DualSparkManagedServingFailureCode; + readonly reason: string; + } + | { + readonly kind: "unavailable"; + readonly code: DualSparkManagedServingFailureCode; + readonly reason: string; + } + | DualSparkDetectedManagedServingCapability; + +export type DualSparkConfirmedManagedServingCapability = + DualSparkDetectedManagedServingCapability & { + readonly peerSshBinding: DualStationSshBinding; + readonly peerSshBindingHandle: string; + }; + +export type DualSparkManagedServingConfirmation = + | Exclude + | DualSparkConfirmedManagedServingCapability; + +export interface ProbeDualSparkManagedServingOptions { + readonly env?: NodeJS.ProcessEnv; + readonly deps?: DualSparkDiscoveryDeps; + readonly bindingStatePath?: string; + readonly maxReadinessAgeMs?: number; +} + +interface QualifiedRail { + readonly host: DualSparkCx7RailHostObservation; + readonly address: string; + readonly peerAddress: string; + readonly subnet: string; + readonly gid: DualSparkRoceGidHostObservation; +} + +interface QualifiedHost { + readonly host: DualSparkHostObservation; + readonly gpu: DualSparkGpuObservation; + readonly rails: readonly [QualifiedRail, QualifiedRail]; +} + +interface PairPlan { + readonly local: QualifiedHost; + readonly peer: QualifiedHost; + readonly localConnectivity: readonly [DualSparkConnectivityRequest, DualSparkConnectivityRequest]; + readonly peerConnectivity: readonly [DualSparkConnectivityRequest, DualSparkConnectivityRequest]; +} + +type DiscoveryFailure = { + readonly code: DualSparkManagedServingFailureCode; + readonly reason: string; +}; + +type Selection = { + readonly strict: boolean; + readonly intent: "automatic" | "explicit"; + readonly explicitPeer: string | null; +}; + +function notSelected( + code: DualSparkManagedServingFailureCode, + reason: string, +): DualSparkManagedServingCapability { + return { kind: "not-selected", code, reason }; +} + +function unavailable( + code: DualSparkManagedServingFailureCode, + reason: string, +): DualSparkManagedServingCapability { + return { kind: "unavailable", code, reason }; +} + +function disposition( + selection: Selection, + result: DiscoveryFailure, +): DualSparkManagedServingCapability { + if (selection.strict) return unavailable(result.code, result.reason); + const code: DualSparkManagedServingFailureCode = [ + "runtime-conflict", + "runtime-unknown", + "binding-conflict", + "binding-persistence-failed", + ].includes(result.code) + ? result.code + : "no-match"; + return notSelected(code, result.reason); +} + +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function validatePeerTarget(raw: string): string { + if ( + raw.length === 0 || + raw.length > 286 || + raw !== raw.trim() || + /[/,:;`'"\\$(){}[\]<>|&!?*\s\u0000-\u001f\u007f]/.test(raw) + ) { + throw new Error(`${NEMOCLAW_DGX_SPARK_PEER_ENV} must name one canonical SSH host or user@host`); + } + const parts = raw.split("@"); + const username = parts.length === 2 ? parts[0] : ""; + const hostname = parts.at(-1) ?? ""; + if ( + parts.length > 2 || + (parts.length === 2 && !username) || + (username !== "" && !SAFE_USERNAME_PATTERN.test(username)) || + (net.isIP(hostname) !== 4 && !SAFE_TARGET_PATTERN.test(hostname)) + ) { + throw new Error(`${NEMOCLAW_DGX_SPARK_PEER_ENV} must name one canonical SSH host or user@host`); + } + return raw; +} + +function selectionFromEnvironment( + env: NodeJS.ProcessEnv, +): Selection | DualSparkManagedServingCapability { + const preset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); + const peer = String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim(); + if (preset && preset !== DUAL_SPARK_PRESET_ID) { + return peer + ? unavailable( + "incompatible-selection", + `${NEMOCLAW_DGX_SPARK_PEER_ENV} cannot be combined with another serving preset.`, + ) + : notSelected("no-match", "Another managed inference preset is selected."); + } + if (peer) { + try { + return { strict: true, intent: "explicit", explicitPeer: validatePeerTarget(peer) }; + } catch (error) { + return unavailable("invalid-peer", (error as Error).message); + } + } + return { + strict: preset === DUAL_SPARK_PRESET_ID, + intent: preset === DUAL_SPARK_PRESET_ID ? "explicit" : "automatic", + explicitPeer: null, + }; +} + +function ipv4ToNumber(address: string): number { + return address + .split(".") + .map(Number) + .reduce((value, octet) => value * 256 + octet, 0); +} + +function numberToIpv4(value: number): string { + return [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join("."); +} + +function privateIpv4(address: string): boolean { + const value = ipv4ToNumber(address); + return ( + (value >= ipv4ToNumber("10.0.0.0") && value <= ipv4ToNumber("10.255.255.255")) || + (value >= ipv4ToNumber("172.16.0.0") && value <= ipv4ToNumber("172.31.255.255")) || + (value >= ipv4ToNumber("192.168.0.0") && value <= ipv4ToNumber("192.168.255.255")) + ); +} + +function slash30Counterpart(address: string, prefixLength: number): string | null { + if (prefixLength !== DIRECT_RAIL_PREFIX_LENGTH || net.isIP(address) !== 4) return null; + if (!privateIpv4(address)) return null; + const value = ipv4ToNumber(address); + const network = Math.floor(value / 4) * 4; + const host = value - network; + if (host === 1) return numberToIpv4(network + 2); + if (host === 2) return numberToIpv4(network + 1); + return null; +} + +function slash30Subnet(address: string): string { + return `${numberToIpv4(Math.floor(ipv4ToNumber(address) / 4) * 4)}/30`; +} + +function isSafeText(value: unknown, maximum = 4096): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= maximum && + value === value.trim() && + !/[\u0000-\u001f\u007f]/.test(value) + ); +} + +function isSafeInteger( + value: unknown, + minimum = 0, + maximum = Number.MAX_SAFE_INTEGER, +): value is number { + return Number.isInteger(value) && (value as number) >= minimum && (value as number) <= maximum; +} + +function validStorageCapacity(value: unknown): value is DualSparkStorageCapacityObservation { + if ( + !isRecord(value) || + !isSafeText(value.requestedPath) || + !path.isAbsolute(value.requestedPath) + ) { + return false; + } + return ( + (value.probePath === null || + (isSafeText(value.probePath) && path.isAbsolute(value.probePath))) && + (value.filesystemId === null || isSafeText(value.filesystemId, 128)) && + (value.availableBytes === null || isSafeInteger(value.availableBytes)) && + (value.availableInodes === null || isSafeInteger(value.availableInodes)) && + (value.ownerUid === null || isSafeInteger(value.ownerUid, 0, 2 ** 31 - 1)) && + (value.ownerGid === null || isSafeInteger(value.ownerGid, 0, 2 ** 31 - 1)) && + typeof value.isDirectory === "boolean" && + typeof value.writableByUser === "boolean" + ); +} + +function validGpu(value: unknown): value is DualSparkGpuObservation { + return ( + isRecord(value) && + isSafeInteger(value.index, 0, 1024) && + isSafeText(value.name, 256) && + isSafeText(value.uuid, 128) && + GPU_UUID_PATTERN.test(value.uuid) + ); +} + +function validRail(value: unknown): value is DualSparkCx7RailHostObservation { + if ( + !isRecord(value) || + !isSafeText(value.physicalPortId, 128) || + !SAFE_DEVICE_PATTERN.test(value.physicalPortId) || + !isSafeText(value.netdev, 64) || + !SAFE_DEVICE_PATTERN.test(value.netdev) || + !isSafeText(value.hcaDevice, 64) || + !SAFE_DEVICE_PATTERN.test(value.hcaDevice) || + !isSafeInteger(value.hcaPort, 1, 255) || + !isSafeText(value.macAddress, 17) || + !MAC_PATTERN.test(value.macAddress) || + value.macAddress === "00:00:00:00:00:00" || + !isSafeText(value.pciAddress, 32) || + !PCI_ADDRESS_PATTERN.test(value.pciAddress) || + !isSafeText(value.pciName, 512) || + !isSafeText(value.state, 64) || + !isSafeText(value.operState, 32) || + typeof value.carrier !== "boolean" || + !isSafeText(value.linkLayer, 64) || + !isSafeInteger(value.speedMbps, -1, 1_000_000) || + !isSafeInteger(value.mtu, 0, 1_000_000) || + !Array.isArray(value.ipv4Addresses) || + value.ipv4Addresses.length > 16 || + !Array.isArray(value.roceV2Ipv4Gids) || + value.roceV2Ipv4Gids.length > 64 + ) { + return false; + } + return ( + value.ipv4Addresses.every( + (address) => + isRecord(address) && + isSafeText(address.address, 15) && + net.isIP(address.address) === 4 && + isSafeInteger(address.prefixLength, 1, 32), + ) && + value.roceV2Ipv4Gids.every( + (gid) => + isRecord(gid) && + isSafeInteger(gid.index, 0, 4095) && + isSafeText(gid.value, 64) && + net.isIP(gid.value) === 6 && + gid.value !== "::" && + isSafeText(gid.ipv4Address, 15) && + net.isIP(gid.ipv4Address) === 4, + ) + ); +} + +function validContainer(value: unknown): value is DualSparkObservedContainer { + if ( + !isRecord(value) || + !isSafeText(value.id, 64) || + !SHA256_PATTERN.test(value.id) || + !isSafeText(value.name, 256) || + !isSafeText(value.image, 1024) || + typeof value.running !== "boolean" || + typeof value.healthy !== "boolean" || + !isRecord(value.labels) || + Object.keys(value.labels).length > 128 + ) { + return false; + } + return Object.entries(value.labels).every( + ([key, label]) => + key.length > 0 && key.length <= 256 && typeof label === "string" && label.length <= 4096, + ); +} + +export function parseDualSparkHostObservation(value: unknown): DualSparkHostObservation { + if ( + !isRecord(value) || + value.schemaVersion !== HOST_PROBE_SCHEMA_VERSION || + !isSafeText(value.hostname, 256) || + !isSafeText(value.nodeId, 64) || + !MACHINE_ID_PATTERN.test(value.nodeId) || + !isSafeText(value.productName, 512) || + !isSafeText(value.architecture, 64) || + !isSafeText(value.home) || + !path.isAbsolute(value.home) || + !isSafeText(value.username, 64) || + !SAFE_USERNAME_PATTERN.test(value.username) || + !isSafeInteger(value.uid, 1, 2 ** 31 - 1) || + !isSafeInteger(value.gid, 0, 2 ** 31 - 1) || + !Array.isArray(value.gpus) || + value.gpus.length > 16 || + !value.gpus.every(validGpu) || + !Array.isArray(value.rails) || + value.rails.length > 16 || + !value.rails.every(validRail) || + !isRecord(value.earlyoom) || + typeof value.earlyoom.installed !== "boolean" || + !["active", "inactive", "unknown"].includes(String(value.earlyoom.active)) || + !["enabled", "disabled", "unknown"].includes(String(value.earlyoom.enabled)) || + typeof value.runtimeInspectionComplete !== "boolean" || + !isRecord(value.runtimeSnapshot) || + !Array.isArray(value.runtimeSnapshot.containers) || + value.runtimeSnapshot.containers.length > 256 || + !value.runtimeSnapshot.containers.every(validContainer) || + !Array.isArray(value.runtimeSnapshot.listeningPorts) || + value.runtimeSnapshot.listeningPorts.length > 65_535 || + !value.runtimeSnapshot.listeningPorts.every((port) => isSafeInteger(port, 1, 65_535)) || + new Set(value.runtimeSnapshot.listeningPorts).size !== + value.runtimeSnapshot.listeningPorts.length || + new Set(value.runtimeSnapshot.containers.map((container) => container.id)).size !== + value.runtimeSnapshot.containers.length || + !isRecord(value.storage) || + !isRecord(value.storage.huggingFace) || + !validStorageCapacity(value.storage.huggingFace) || + !isSafeText(value.storage.huggingFace.cacheRoot) || + !path.isAbsolute(value.storage.huggingFace.cacheRoot) || + !isSafeText(value.storage.huggingFace.snapshotPath) || + !path.isAbsolute(value.storage.huggingFace.snapshotPath) || + (value.storage.huggingFace.snapshotBytes !== null && + !isSafeInteger(value.storage.huggingFace.snapshotBytes)) || + typeof value.storage.huggingFace.exactSnapshotCached !== "boolean" || + !isRecord(value.storage.docker) || + !validStorageCapacity(value.storage.docker) || + (value.storage.docker.dockerRootDir !== null && + (!isSafeText(value.storage.docker.dockerRootDir) || + !path.isAbsolute(value.storage.docker.dockerRootDir))) || + typeof value.storage.docker.exactImageCached !== "boolean" + ) { + throw new Error("DGX Spark host observation is invalid"); + } + return value as unknown as DualSparkHostObservation; +} +function qualifyHost( + host: DualSparkHostObservation, + label: string, +): QualifiedHost | DiscoveryFailure { + if ( + !/DGX[_\s-]+Spark/i.test(host.productName) || + !/^(?:aarch64|arm64)$/i.test(host.architecture) + ) { + return { code: "host-unqualified", reason: `${label} is not an arm64 DGX Spark.` }; + } + const gpus = host.gpus.filter(({ name }) => /\bGB10\b/i.test(name)); + if (gpus.length !== 1 || host.gpus.length !== 1) { + return { code: "host-unqualified", reason: `${label} must expose exactly one GB10 GPU.` }; + } + const cx7 = host.rails.filter(({ pciName }) => /ConnectX[- ]?7|\bCX-?7\b/i.test(pciName)); + if (cx7.length !== 2 || host.rails.length !== 2) { + return { + code: "fabric-unavailable", + reason: `${label} must expose exactly two ConnectX-7 logical rails.`, + }; + } + const qualified: QualifiedRail[] = []; + for (const [index, rail] of cx7.entries()) { + if ( + !/\bACTIVE\b/i.test(rail.state) || + rail.operState.toLowerCase() !== "up" || + !rail.carrier || + rail.linkLayer.toLowerCase() !== "ethernet" || + rail.speedMbps !== EXPECTED_CX7_SPEED_MBPS || + rail.mtu < MINIMUM_CX7_MTU + ) { + return { + code: "fabric-unavailable", + reason: `${label} rail ${String(index + 1)} is not active 200G Ethernet with jumbo MTU.`, + }; + } + const addresses = rail.ipv4Addresses + .map((address) => ({ + address, + peer: slash30Counterpart(address.address, address.prefixLength), + })) + .filter( + (entry): entry is { address: DualSparkIpv4Observation; peer: string } => + entry.peer !== null, + ); + if (addresses.length !== 1) { + return { + code: "fabric-unavailable", + reason: `${label} rail ${String(index + 1)} must have one usable private /30 address.`, + }; + } + const selectedAddress = addresses[0]!; + const gids = rail.roceV2Ipv4Gids + .filter(({ ipv4Address }) => ipv4Address === selectedAddress.address.address) + .sort((left, right) => left.index - right.index || compareStrings(left.value, right.value)); + if (gids.length === 0) { + return { + code: "fabric-unavailable", + reason: `${label} rail ${String(index + 1)} has no usable dynamically resolved RoCEv2 GID.`, + }; + } + qualified.push({ + host: rail, + address: selectedAddress.address.address, + peerAddress: selectedAddress.peer, + subnet: slash30Subnet(selectedAddress.address.address), + gid: gids[0]!, + }); + } + if ( + new Set(qualified.map(({ host: rail }) => rail.netdev)).size !== 2 || + new Set(qualified.map(({ host: rail }) => rail.macAddress)).size !== 2 || + new Set(qualified.map(({ subnet }) => subnet)).size !== 2 || + new Set(qualified.map(({ peerAddress }) => peerAddress)).size !== 2 + ) { + return { code: "fabric-unavailable", reason: `${label} ConnectX-7 identity is ambiguous.` }; + } + qualified.sort((left, right) => compareStrings(left.subnet, right.subnet)); + return { host, gpu: gpus[0]!, rails: [qualified[0]!, qualified[1]!] }; +} + +function runtimeFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { + if (!host.runtimeInspectionComplete) { + return { code: "runtime-unknown", reason: `${label} runtime inspection is inconclusive.` }; + } + const container = host.runtimeSnapshot.containers.find(isRelatedManagedVllmContainer); + if (container) { + return { + code: "runtime-conflict", + reason: `${label} already has related container ${container.name}; it was not changed.`, + }; + } + const port = host.runtimeSnapshot.listeningPorts.find( + (entry) => entry === DUAL_SPARK_VLLM_API_PORT || entry === DUAL_SPARK_VLLM_MASTER_PORT, + ); + return port === undefined + ? null + : { + code: "runtime-conflict", + reason: `${label} port ${String(port)} is already in use; its listener was not changed.`, + }; +} + +function earlyoomFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { + if (!host.earlyoom.installed) return null; + if (host.earlyoom.active === "active") { + return { + code: "earlyoom-active", + reason: `${label} has active earlyoom; NemoClaw did not stop or disable it.`, + }; + } + return host.earlyoom.active === "inactive" + ? null + : { code: "earlyoom-unknown", reason: `${label} earlyoom state is inconclusive.` }; +} + +function validCapacity(capacity: DualSparkStorageCapacityObservation): boolean { + return ( + capacity.probePath !== null && + capacity.filesystemId !== null && + capacity.availableBytes !== null && + capacity.availableInodes !== null && + capacity.availableInodes >= MINIMUM_AVAILABLE_INODES && + capacity.ownerUid !== null && + capacity.ownerGid !== null && + capacity.isDirectory + ); +} + +function storageFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { + const catalog = loadManagedInferenceCatalog(); + const recipe = catalog.recipes[0]?.definition; + if (!recipe) + return { code: "storage-unavailable", reason: "Managed inference recipe is unavailable." }; + const huggingFace = host.storage.huggingFace; + const docker = host.storage.docker; + if (!validCapacity(huggingFace) || !validCapacity(docker)) { + return { + code: "storage-unavailable", + reason: `${label} cache or Docker filesystem capacity could not be proven.`, + }; + } + if (!huggingFace.writableByUser) { + return { + code: "storage-unavailable", + reason: `${label} Hugging Face cache is not writable by the probed non-root user.`, + }; + } + if ( + huggingFace.probePath !== huggingFace.cacheRoot || + huggingFace.requestedPath !== huggingFace.cacheRoot || + !huggingFace.isDirectory + ) { + return { + code: "storage-unavailable", + reason: `${label} exact Hugging Face cache root must already exist as a directory.`, + }; + } + if (huggingFace.ownerUid !== host.uid || huggingFace.ownerGid !== host.gid) { + return { + code: "storage-unavailable", + reason: `${label} Hugging Face cache ownership does not match the probed non-root user.`, + }; + } + + const requirements = new Map(); + const available = new Map(); + const add = (capacity: DualSparkStorageCapacityObservation, required: bigint): void => { + const filesystemId = capacity.filesystemId!; + requirements.set(filesystemId, (requirements.get(filesystemId) ?? 0n) + required); + const bytes = BigInt(capacity.availableBytes!); + const prior = available.get(filesystemId); + available.set(filesystemId, prior === undefined || bytes < prior ? bytes : prior); + }; + add( + huggingFace, + (huggingFace.exactSnapshotCached + ? 0n + : modelStorageRequirementBytes(recipe.spec.model.downloadSizeBytes)) + + VLLM_WRITABLE_ALLOWANCE_BYTES, + ); + add( + docker, + docker.exactImageCached + ? 0n + : imageStorageRequirementBytes(recipe.spec.runtime.imageDownloadSizeBytes), + ); + for (const [filesystemId, required] of requirements) { + if ((available.get(filesystemId) ?? -1n) < required) { + return { + code: "storage-insufficient", + reason: `${label} filesystem ${filesystemId} lacks capacity for the pinned image, model, staging, and writable allowance.`, + }; + } + } + return null; +} + +function pairHosts(local: QualifiedHost, peer: QualifiedHost): PairPlan | DiscoveryFailure { + if (local.host.nodeId === peer.host.nodeId || local.gpu.uuid === peer.gpu.uuid) { + return { + code: "peer-identity-ambiguous", + reason: "The peer resolves back to the local DGX Spark.", + }; + } + const matches = local.rails.map((localRail) => { + const peers = peer.rails.filter( + (peerRail) => + peerRail.subnet === localRail.subnet && + peerRail.address === localRail.peerAddress && + peerRail.peerAddress === localRail.address, + ); + return peers.length === 1 ? { local: localRail, peer: peers[0]! } : null; + }); + if (matches.some((match) => match === null)) { + return { + code: "fabric-unavailable", + reason: "The peer rails are not exact reciprocal /30 endpoints.", + }; + } + const exact = matches as Array<{ local: QualifiedRail; peer: QualifiedRail }>; + return { + local, + peer, + localConnectivity: exact.map(({ local: localRail, peer: peerRail }) => ({ + netdev: localRail.host.netdev, + sourceAddress: localRail.address, + peerAddress: peerRail.address, + expectedPeerMac: peerRail.host.macAddress, + })) as [DualSparkConnectivityRequest, DualSparkConnectivityRequest], + peerConnectivity: exact.map(({ local: localRail, peer: peerRail }) => ({ + netdev: peerRail.host.netdev, + sourceAddress: peerRail.address, + peerAddress: localRail.address, + expectedPeerMac: localRail.host.macAddress, + })) as [DualSparkConnectivityRequest, DualSparkConnectivityRequest], + }; +} + +function topologyRail(rail: QualifiedRail, peerNodeId: string): DualSparkRailObservation { + return { + adapter: "connectx-7", + path: "direct", + physicalPortId: rail.host.physicalPortId, + netdev: rail.host.netdev, + hcaDevice: rail.host.hcaDevice, + hcaPort: rail.host.hcaPort, + address: rail.address, + prefixLength: DIRECT_RAIL_PREFIX_LENGTH, + peerNodeId, + peerAddress: rail.peerAddress, + linkState: "up", + connectivity: "reachable", + roceGid: { state: "resolved", index: rail.gid.index, value: rail.gid.value }, + }; +} + +function topologyObservations( + pair: PairPlan, + localReadiness: SystemReadinessReport, + peerReadiness: SystemReadinessReport, + identity: QualifiedStationSshIdentity, + bindingHandle: string, +): { local: DualSparkNodeObservation; peer: DualSparkPeerObservation } { + return { + local: { + nodeId: pair.local.host.nodeId, + gpuIds: [pair.local.gpu.uuid], + readiness: localReadiness, + runtimeState: "clear", + rails: pair.local.rails.map((rail) => topologyRail(rail, pair.peer.host.nodeId)), + }, + peer: { + nodeId: pair.peer.host.nodeId, + gpuIds: [pair.peer.gpu.uuid], + readiness: peerReadiness, + runtimeState: "clear", + rails: pair.peer.rails.map((rail) => topologyRail(rail, pair.local.host.nodeId)), + sshBinding: { + state: "pretrusted", + fromNodeId: pair.local.host.nodeId, + toNodeId: pair.peer.host.nodeId, + peerTarget: identity.sshTarget, + handle: bindingHandle, + }, + }, + }; +} + +function hostPolicyFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { + return earlyoomFailure(host, label) ?? runtimeFailure(host, label) ?? storageFailure(host, label); +} + +function samePhysicalSshIdentity( + left: QualifiedStationSshIdentity, + right: QualifiedStationSshIdentity, +): boolean { + return ( + left.sshUser === right.sshUser && + left.port === right.port && + left.hostKeyDigest === right.hostKeyDigest + ); +} + +function sameExactSshIdentity( + left: QualifiedStationSshIdentity, + right: QualifiedStationSshIdentity, +): boolean { + return ( + left.requestedTarget === right.requestedTarget && + left.sshTarget === right.sshTarget && + left.resolvedHost === right.resolvedHost && + left.sshUser === right.sshUser && + left.port === right.port && + left.lookupHost === right.lookupHost && + left.hostKeyDigest === right.hostKeyDigest && + left.knownHostsLines.length === right.knownHostsLines.length && + left.knownHostsLines.every((line, index) => line === right.knownHostsLines[index]) + ); +} + +function samePhysicalHost( + left: DualSparkHostObservation, + right: DualSparkHostObservation, +): boolean { + return ( + left.nodeId === right.nodeId && + left.gpus.length === 1 && + right.gpus.length === 1 && + left.gpus[0]?.uuid === right.gpus[0]?.uuid + ); +} + +function topologyFailureReason(result: ReturnType): string { + return result.outcome === "qualified" ? "" : result.message; +} + +function sameDetectedPair( + detected: DualSparkDetectedManagedServingCapability, + revalidated: DualSparkDetectedManagedServingCapability, +): boolean { + return ( + detected.selectionIntent === revalidated.selectionIntent && + detected.peerSshBindingStatePath === revalidated.peerSshBindingStatePath && + sameExactSshIdentity(detected.peerSshIdentity, revalidated.peerSshIdentity) && + detected.local.nodeId === revalidated.local.nodeId && + detected.local.hostname === revalidated.local.hostname && + detected.local.username === revalidated.local.username && + detected.local.uid === revalidated.local.uid && + detected.local.gid === revalidated.local.gid && + detected.local.home === revalidated.local.home && + detected.local.gpus[0]?.uuid === revalidated.local.gpus[0]?.uuid && + detected.local.storage.huggingFace.cacheRoot === + revalidated.local.storage.huggingFace.cacheRoot && + detected.peer.nodeId === revalidated.peer.nodeId && + detected.peer.hostname === revalidated.peer.hostname && + detected.peer.username === revalidated.peer.username && + detected.peer.uid === revalidated.peer.uid && + detected.peer.gid === revalidated.peer.gid && + detected.peer.home === revalidated.peer.home && + detected.peer.gpus[0]?.uuid === revalidated.peer.gpus[0]?.uuid && + detected.peer.storage.huggingFace.cacheRoot === + revalidated.peer.storage.huggingFace.cacheRoot && + detected.topology.subjectDigest === revalidated.topology.subjectDigest && + detected.topology.outputDigest === revalidated.topology.outputDigest + ); +} + +function topologyWithBinding( + detected: DualSparkDetectedManagedServingCapability, + peerSshBindingHandle: string, +): DualSparkTopologyArtifact { + const output: DualSparkTopologyOutput = { + ...detected.topology.output, + peer: { + ...detected.topology.output.peer, + sshBindingHandle: peerSshBindingHandle, + }, + }; + const artifact = immutableManagedInferenceCopy({ + ...detected.topology, + output, + outputDigest: dualSparkTopologyOutputDigest(output), + }); + const error = getDualSparkTopologyArtifactError(artifact); + if (error) throw new Error(error); + return artifact; +} + +function confirmationUnavailable( + code: DualSparkManagedServingFailureCode, + reason: string, +): DualSparkManagedServingConfirmation { + return { kind: "unavailable", code, reason }; +} + +export function probeDualSparkManagedServingCapability( + options: ProbeDualSparkManagedServingOptions = {}, +): DualSparkManagedServingCapability { + const selection = selectionFromEnvironment(options.env ?? process.env); + if (!("strict" in selection)) return selection; + const deps = options.deps ?? defaultDualSparkDiscoveryDeps; + const opened: DualSparkPinnedPeerTransport[] = []; + let local: DualSparkHostObservation; + let qualifiedLocal: QualifiedHost; + let localTransport: DualSparkReadOnlyHostTransport; + try { + localTransport = deps.localTransport(); + local = deps.probeHost(localTransport); + const effectiveUid = deps.currentUid(); + if (effectiveUid === null || effectiveUid !== local.uid) { + return disposition(selection, { + code: "host-unqualified", + reason: "The local DGX Spark probe does not match the current non-root controller UID.", + }); + } + const candidate = qualifyHost(local, "Local DGX Spark"); + if ("code" in candidate) return disposition(selection, candidate); + qualifiedLocal = candidate; + const policyFailure = hostPolicyFailure(local, "Local DGX Spark"); + if (policyFailure) return disposition(selection, policyFailure); + } catch { + return disposition(selection, { + code: "local-host-unavailable", + reason: "The local DGX Spark read-only probe failed closed.", + }); + } + + try { + let selectedIdentity: QualifiedStationSshIdentity; + let selectedTransport: DualSparkReadOnlyHostTransport; + let peer: DualSparkHostObservation; + if (selection.explicitPeer) { + const identity = deps.inspectPretrustedTarget(selection.explicitPeer); + if (!identity) { + return disposition(selection, { + code: "peer-trust-unavailable", + reason: "The explicit DGX Spark peer lacks usable pre-existing SSH trust.", + }); + } + const pinned = deps.openPinnedPeerTransport(identity); + opened.push(pinned); + selectedIdentity = identity; + selectedTransport = pinned.transport; + peer = deps.probeHost(selectedTransport); + } else { + const targets = qualifiedLocal.rails.map(({ peerAddress }) => peerAddress); + const identities = targets.map((target) => deps.inspectPretrustedTarget(target)); + if (identities.some((identity) => identity === null)) { + return disposition(selection, { + code: "peer-trust-unavailable", + reason: "Both derived /30 peer addresses require pre-existing SSH host-key trust.", + }); + } + const trusted = identities as QualifiedStationSshIdentity[]; + if (!samePhysicalSshIdentity(trusted[0]!, trusted[1]!)) { + return disposition(selection, { + code: "peer-identity-ambiguous", + reason: "The two derived rail addresses map to different SSH identities.", + }); + } + const probes = trusted.map((identity) => { + const pinned = deps.openPinnedPeerTransport(identity); + opened.push(pinned); + return { identity, pinned, host: deps.probeHost(pinned.transport) }; + }); + if (!samePhysicalHost(probes[0]!.host, probes[1]!.host)) { + return disposition(selection, { + code: "peer-identity-ambiguous", + reason: "The two derived rail addresses do not resolve to one physical DGX Spark.", + }); + } + probes.sort((left, right) => + compareStrings(left.identity.requestedTarget, right.identity.requestedTarget), + ); + selectedIdentity = probes[0]!.identity; + selectedTransport = probes[0]!.pinned.transport; + peer = probes[0]!.host; + } + + const qualifiedPeer = qualifyHost(peer, "Peer DGX Spark"); + if ("code" in qualifiedPeer) return disposition(selection, qualifiedPeer); + if (peer.username !== selectedIdentity.sshUser || peer.uid <= 0) { + return disposition(selection, { + code: "peer-identity-ambiguous", + reason: "The peer SSH user does not own the probed non-root cache identity.", + }); + } + const peerPolicyFailure = hostPolicyFailure(peer, "Peer DGX Spark"); + if (peerPolicyFailure) return disposition(selection, peerPolicyFailure); + const pair = pairHosts(qualifiedLocal, qualifiedPeer); + if ("code" in pair) return disposition(selection, pair); + if ( + !deps.probeConnectivity(localTransport, pair.localConnectivity) || + !deps.probeConnectivity(selectedTransport, pair.peerConnectivity) + ) { + return disposition(selection, { + code: "connectivity-unavailable", + reason: "Direct route, neighbor, or jumbo connectivity failed on a DGX Spark rail.", + }); + } + + const now = deps.now(); + const buildIdentity = deps.getBuildIdentity(); + let localReadiness: SystemReadinessReport; + let peerReadiness: SystemReadinessReport; + try { + localReadiness = deps.createReadiness(local, localTransport, buildIdentity, now); + peerReadiness = deps.createReadiness(peer, selectedTransport, buildIdentity, now); + } catch { + return disposition(selection, { + code: "readiness-unavailable", + reason: "Canonical readiness could not be generated for both DGX Spark nodes.", + }); + } + const temporary = topologyObservations( + pair, + localReadiness, + peerReadiness, + selectedIdentity, + `pretrusted:${selectedIdentity.hostKeyDigest}`, + ); + const temporaryQualification = qualifyDualSparkTopology({ + intent: selection.intent, + evaluatedAt: now.toISOString(), + maxReadinessAgeMs: options.maxReadinessAgeMs ?? 60_000, + local: temporary.local, + peers: [temporary.peer], + }); + if (temporaryQualification.outcome !== "qualified") { + return disposition(selection, { + code: "topology-unavailable", + reason: topologyFailureReason(temporaryQualification), + }); + } + + const statePath = options.bindingStatePath ?? deps.resolveBindingStatePath(); + return { + kind: "ready", + selectionIntent: selection.intent, + topology: temporaryQualification.artifact, + local, + peer, + readiness: [ + { nodeId: local.nodeId, report: localReadiness }, + { nodeId: peer.nodeId, report: peerReadiness }, + ], + peerSshBindingStatePath: statePath, + peerSshIdentity: selectedIdentity, + }; + } catch { + return disposition(selection, { + code: "peer-host-unavailable", + reason: "The peer DGX Spark read-only probe failed closed.", + }); + } finally { + for (const pinned of opened.reverse()) { + try { + pinned.close(); + } catch { + // The pinned temporary directory contains public host-key material only. + } + } + } +} + +/** Revalidate the detected pair, then claim and persist its SSH binding after confirmation. */ +export function confirmDualSparkManagedServingCapability( + detected: DualSparkDetectedManagedServingCapability, + options: ProbeDualSparkManagedServingOptions = {}, +): DualSparkManagedServingConfirmation { + const deps = options.deps ?? defaultDualSparkDiscoveryDeps; + const revalidated = probeDualSparkManagedServingCapability({ + ...options, + deps, + bindingStatePath: detected.peerSshBindingStatePath, + }); + if (revalidated.kind !== "ready") { + return confirmationUnavailable( + revalidated.code, + `The confirmed DGX Spark pair no longer qualifies: ${revalidated.reason}`, + ); + } + if (!sameDetectedPair(detected, revalidated)) { + return confirmationUnavailable( + "peer-identity-ambiguous", + "The confirmed DGX Spark pair or its exact pretrusted SSH identity changed after selection.", + ); + } + + const statePath = revalidated.peerSshBindingStatePath; + if (!deps.claimBinding(statePath)) { + return confirmationUnavailable( + "binding-conflict", + "An existing DGX Spark SSH binding was preserved and not replaced.", + ); + } + try { + const peerSshBinding = deps.writeBinding(statePath, revalidated.peerSshIdentity); + const peerSshBindingHandle = deps.encodeBinding(peerSshBinding); + return { + ...revalidated, + topology: topologyWithBinding(revalidated, peerSshBindingHandle), + peerSshBinding, + peerSshBindingHandle, + }; + } catch { + try { + deps.clearBinding(statePath); + } catch { + return confirmationUnavailable( + "binding-persistence-failed", + "The DGX Spark SSH binding failed and its new state could not be cleaned safely.", + ); + } + return confirmationUnavailable( + "binding-persistence-failed", + "The confirmed DGX Spark SSH binding could not be persisted.", + ); + } +} + +export type { DualSparkSpawnSync } from "./dual-spark-discovery-production.js"; + +export function createDualSparkDiscoveryDeps( + spawn?: import("./dual-spark-discovery-production.js").DualSparkSpawnSync, +): DualSparkDiscoveryDeps { + return createProductionDualSparkDiscoveryDeps(parseDualSparkHostObservation, spawn); +} + +const defaultDualSparkDiscoveryDeps = createDualSparkDiscoveryDeps(); diff --git a/src/lib/inference/serving/dual-spark-executor.test.ts b/src/lib/inference/serving/dual-spark-executor.test.ts new file mode 100644 index 00000000000..4e3ebe7392b --- /dev/null +++ b/src/lib/inference/serving/dual-spark-executor.test.ts @@ -0,0 +1,623 @@ +// 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 { + createDualStationSshBindingFixture, + type DualStationSshBindingFixture, +} from "../vllm-station-ssh-binding.test-support.js"; +import { + assertDualSparkVllmExecutorConfig, + buildDualSparkVllmRunArgs, + createDualSparkVllmExecutor, + type DualSparkVllmExecutorRuntimeDeps, + inspectDualSparkVllmNodesSync, +} from "./dual-spark-executor.js"; +import { fixtureDualSparkPlan } from "./dual-spark-fixture.test-support.js"; +import { + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_MANAGED_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + type DualSparkVllmPlan, + type DualSparkVllmRole, + type DualSparkVllmRolePlan, +} from "./dual-spark-materialize.js"; + +const API_KEY = "a".repeat(64); +const FINGERPRINT = "b".repeat(64); +const TRANSACTION_ID = "c".repeat(32); +const HEAD_ID = "1".repeat(64); +const FOREIGN_ID = "2".repeat(64); +const WORKER_ID = "3".repeat(64); +const LOCAL_CACHE_ROOT = "/home/nvidia/.cache/huggingface"; +const PEER_CACHE_ROOT = "/home/spark/.cache/huggingface"; + +type DockerCaptureOptions = NonNullable< + Parameters[1] +>; + +type StoppedForeignContainerFixture = { + readonly signal: string; + readonly name: string; + readonly image: string; + readonly labels: Readonly>; +}; + +const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixture[] = [ + { + signal: "name", + name: "foreign-vllm-server", + image: "example.invalid/inference:latest", + labels: {}, + }, + { + signal: "image", + name: "foreign-inference", + image: "vllm/vllm-openai:latest", + labels: {}, + }, + { + signal: "managed label", + name: "foreign-inference", + image: "example.invalid/inference:latest", + labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + }, +]; + +function bindPlan(fixture: DualStationSshBindingFixture): DualSparkVllmPlan { + const plan = fixtureDualSparkPlan(); + return { + ...plan, + roles: { + head: plan.roles.head, + worker: { + ...plan.roles.worker, + execution: { + kind: "ssh", + expectedTarget: fixture.binding.peerTarget, + bindingHandle: fixture.token, + }, + }, + }, + }; +} + +function launchLabels(rolePlan: DualSparkVllmRolePlan): Record { + return { + ...rolePlan.baseLabels, + [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: FINGERPRINT, + [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + }; +} + +function inspectionRow(input: { + id: string; + name: string; + image: string; + running: boolean; + labels: Readonly>; +}): string { + return JSON.stringify([input.id, `/${input.name}`, input.image, input.running, input.labels]); +} + +function successfulDockerResult(stdout = "") { + return { + pid: 123, + output: [null, stdout, ""], + stdout, + stderr: "", + status: 0, + signal: null, + error: undefined, + }; +} + +function runtimeOverrides( + overrides: Partial = {}, +): Partial { + return { + dockerCapture: vi.fn(() => ""), + dockerForceRm: vi.fn(() => successfulDockerResult()), + dockerRunDetached: vi.fn(() => successfulDockerResult()), + captureListeners: vi.fn(() => ""), + createTransactionId: vi.fn(() => TRANSACTION_ID), + now: vi.fn(() => 0), + sleep: vi.fn(async () => undefined), + withLifecycleLock: vi.fn(async (operation) => await operation()), + ...overrides, + }; +} + +describe("dual-DGX-Spark vLLM executor", () => { + let bindingFixture: DualStationSshBindingFixture; + let plan: DualSparkVllmPlan; + + beforeEach(() => { + bindingFixture = createDualStationSshBindingFixture("spark-worker.local"); + plan = bindPlan(bindingFixture); + }); + + afterEach(() => { + bindingFixture.cleanup(); + vi.restoreAllMocks(); + }); + + it("builds the pinned host-network role launch without a restart policy or bearer value", () => { + const head = plan.roles.head; + const args = buildDualSparkVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)); + const command = args.at(-1)!; + + expect(args).toEqual( + expect.arrayContaining([ + "--pull=never", + "--init", + "--network", + "host", + "--ipc", + "host", + "--shm-size", + "64g", + "--gpus", + "all", + "--device", + "/dev/infiniband", + "--ulimit", + "memlock=-1", + "stack=67108864", + "--tmpfs", + "/cache/huggingface:rw,nosuid,nodev,exec,size=17179869184,mode=0700", + "/tmp:rw,nosuid,nodev,exec,size=17179869184,mode=1777", + "--volume", + `${LOCAL_CACHE_ROOT}/hub:/cache/huggingface/hub:ro`, + "--env", + "VLLM_API_KEY", + head.image, + ]), + ); + expect(args).not.toContain("--restart"); + expect(args).not.toContain(`${LOCAL_CACHE_ROOT}:/cache/huggingface`); + expect(JSON.stringify(args)).not.toContain(API_KEY); + expect(command).toContain("install -m 0644 --"); + expect(command).toContain("deepseek_v4_encoding.py"); + expect(command).toContain("reasoning compatibility source text did not match exactly once"); + expect(command).not.toContain("--api-key"); + expect(command).not.toContain("$VLLM_API_KEY"); + expect(command).toContain("'--host' '192.168.100.10'"); + expect(command).toContain("exec '/usr/local/bin/vllm'"); + }); + + it("keeps the worker launch headless and free of the bearer environment key", () => { + const worker = plan.roles.worker; + const args = buildDualSparkVllmRunArgs(worker, PEER_CACHE_ROOT, launchLabels(worker)); + + expect(args).not.toContain("VLLM_API_KEY"); + expect(args.at(-1)).toContain("'--headless'"); + expect(args.at(-1)).toContain("'--host' '192.168.100.11'"); + expect(args.at(-1)).not.toContain("--api-key"); + expect(args.at(-1)).not.toContain("$VLLM_API_KEY"); + }); + + it("rejects a changed binding handoff before any Docker operation", () => { + const changedPlan = { + ...plan, + roles: { + ...plan.roles, + worker: { + ...plan.roles.worker, + execution: { + kind: "ssh" as const, + expectedTarget: bindingFixture.binding.peerTarget, + bindingHandle: "changed", + }, + }, + }, + }; + + expect(() => + createDualSparkVllmExecutor( + { + plan: changedPlan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides(), + ), + ).toThrow(/qualified binding and plan/); + }); + + it("revalidates catalog-derived commands and exposes the same synchronous inspector", () => { + const config = { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }; + expect(inspectDualSparkVllmNodesSync(config, runtimeOverrides())).toEqual({ + head: { containers: [], listeningPorts: [] }, + worker: { containers: [], listeningPorts: [] }, + }); + + const changedPlan: DualSparkVllmPlan = { + ...plan, + roles: { + ...plan.roles, + head: { + ...plan.roles.head, + command: { + ...plan.roles.head.command, + arguments: [...plan.roles.head.command.arguments, "--changed"], + }, + }, + }, + }; + expect(() => assertDualSparkVllmExecutorConfig({ ...config, plan: changedPlan })).toThrow( + /catalog-derived adapter contract/, + ); + }); + + it("inspects every container plus host listeners and marks only the exact live role healthy", async () => { + const headLabels = launchLabels(plan.roles.head); + const foreignLabels = { "example.foreign": "true" }; + const dockerCapture = vi.fn((args: readonly string[]) => { + if (args.includes("--quiet")) return `${HEAD_ID}\n${FOREIGN_ID}\n`; + if (args.includes("inspect")) { + return [ + inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: true, + labels: headLabels, + }), + inspectionRow({ + id: FOREIGN_ID, + name: "unrelated-service", + image: "example.invalid/foreign:latest", + running: true, + labels: foreignLabels, + }), + ].join("\n"); + } + if (args[0] === "exec") return "ready"; + throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + }); + const captureListeners = vi.fn( + () => "LISTEN 0 4096 0.0.0.0:8000 0.0.0.0:*\nLISTEN 0 128 [::]:25000 [::]:*\n", + ); + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ dockerCapture, captureListeners }), + ); + + const snapshot = await executor.inspectNode(plan.roles.head); + + expect(snapshot.listeningPorts).toEqual([8000, 25000]); + expect(snapshot.containers).toHaveLength(2); + expect(snapshot.containers[0]).toMatchObject({ id: HEAD_ID, healthy: true }); + expect(snapshot.containers[1]).toMatchObject({ id: FOREIGN_ID, healthy: false }); + expect(dockerCapture).toHaveBeenCalledWith( + expect.arrayContaining(["container", "inspect", HEAD_ID, FOREIGN_ID]), + expect.any(Object), + ); + }); + + it("fails closed when listener inspection is malformed", async () => { + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ captureListeners: vi.fn(() => "not-an-ss-row") }), + ); + + await expect(executor.inspectNode(plan.roles.head)).rejects.toThrow(/listener inspection/); + }); + + it("does not declare the worker-first boundary once a head setup appears", async () => { + const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => { + const role = options?.env?.DOCKER_HOST ? "worker" : "head"; + const rolePlan = plan.roles[role]; + const id = role === "worker" ? WORKER_ID : HEAD_ID; + if (args.includes("--quiet")) return id; + if (args.includes("inspect")) { + return inspectionRow({ + id, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + labels: launchLabels(rolePlan), + }); + } + if (args[0] === "exec") return "ready"; + throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + }); + let tick = 0; + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ + dockerCapture, + now: vi.fn(() => (tick += 1_000)), + }), + ); + + await expect( + executor.waitForWorkerDistributedReady({ + rolePlan: plan.roles.worker, + containerId: WORKER_ID, + expectedLabels: launchLabels(plan.roles.worker), + timeoutMs: 1, + }), + ).resolves.toBe(false); + }); + + it.each( + STOPPED_FOREIGN_CONTAINER_FIXTURES, + )("keeps the worker-first boundary closed for a stopped foreign $signal", async (foreign) => { + const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => { + const role = options?.env?.DOCKER_HOST ? "worker" : "head"; + const id = role === "worker" ? WORKER_ID : FOREIGN_ID; + if (args.includes("--quiet")) return id; + if (args.includes("inspect")) { + return role === "worker" + ? inspectionRow({ + id, + name: plan.roles.worker.containerName, + image: plan.roles.worker.image, + running: true, + labels: launchLabels(plan.roles.worker), + }) + : inspectionRow({ + id, + name: foreign.name, + image: foreign.image, + running: false, + labels: foreign.labels, + }); + } + if (args[0] === "exec") return "ready"; + throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + }); + let tick = 0; + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ + dockerCapture, + now: vi.fn(() => (tick += 1_000)), + }), + ); + + await expect( + executor.waitForWorkerDistributedReady({ + rolePlan: plan.roles.worker, + containerId: WORKER_ID, + expectedLabels: launchLabels(plan.roles.worker), + timeoutMs: 1, + }), + ).resolves.toBe(false); + }); + + it("starts one exact head with the bearer only in the Docker subprocess environment", async () => { + const labels = launchLabels(plan.roles.head); + const dockerCapture = vi.fn((args: readonly string[]) => { + if (args.includes("--quiet")) return HEAD_ID; + if (args.includes("inspect")) { + return inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: true, + labels, + }); + } + if (args[0] === "exec") return "ready"; + throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + }); + const dockerRunDetached = vi.fn(() => + successfulDockerResult(`${HEAD_ID}\n`), + ); + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ dockerCapture, dockerRunDetached }), + ); + + const result = await executor.startContainer({ + rolePlan: plan.roles.head, + labels, + preparation: plan.roles.head.preparation, + bearerApiKey: API_KEY, + }); + + expect(result).toEqual({ ok: true, containerId: HEAD_ID }); + const [argv, options] = dockerRunDetached.mock.calls[0]!; + expect(JSON.stringify(argv)).not.toContain(API_KEY); + expect(JSON.stringify(argv)).not.toContain("--api-key"); + expect(JSON.stringify(argv)).not.toContain("$VLLM_API_KEY"); + expect(argv).toContain("VLLM_API_KEY"); + expect(options?.env?.VLLM_API_KEY).toBe(API_KEY); + expect(options?.suppressOutput).toBe(true); + expect(JSON.stringify(labels)).not.toContain(API_KEY); + }); + + it("injects staging targets but leaves cleanup construction usable without staging", async () => { + const stageNode = vi.fn(async () => ({ ok: true })); + const withStage = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + stageNode, + }, + runtimeOverrides(), + ); + const withoutStage = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides(), + ); + + expect( + await withStage.stageNode({ + rolePlan: plan.roles.worker, + preparation: plan.roles.worker.preparation, + }), + ).toEqual({ ok: true }); + expect(stageNode).toHaveBeenCalledWith( + expect.any(Object), + expect.objectContaining({ + role: "worker", + modelCacheRoot: PEER_CACHE_ROOT, + peerSshBinding: bindingFixture.binding, + }), + ); + await expect( + withoutStage.stageNode({ + rolePlan: plan.roles.head, + preparation: plan.roles.head.preparation, + }), + ).resolves.toMatchObject({ ok: false, reason: expect.stringContaining("not configured") }); + }); + + it("removes only the revalidated exact container ID", async () => { + const labels = launchLabels(plan.roles.head); + const dockerCapture = vi.fn((args: readonly string[]) => { + if (args.includes("--quiet")) return HEAD_ID; + if (args.includes("inspect")) { + return inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: false, + labels, + }); + } + return ""; + }); + const dockerForceRm = vi.fn(() => successfulDockerResult()); + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ dockerCapture, dockerForceRm }), + ); + + await expect(executor.removeContainer(plan.roles.head, HEAD_ID)).resolves.toEqual({ ok: true }); + expect(dockerForceRm).toHaveBeenCalledWith(HEAD_ID, expect.any(Object)); + expect(dockerForceRm).not.toHaveBeenCalledWith( + plan.roles.head.containerName, + expect.anything(), + ); + }); + + it("performs bounded authenticated model and chat probes without putting the key in argv", async () => { + const cleanup = vi.fn(); + const createBearerAuthConfig = vi.fn(() => ({ + args: ["--config", "/tmp/nemoclaw-probe/auth.conf"], + trustedConfigFiles: ["/tmp/nemoclaw-probe/auth.conf"], + cleanup, + })); + const runCurlProbe = vi + .fn() + .mockReturnValueOnce({ + ok: true, + httpStatus: 200, + curlStatus: 0, + body: JSON.stringify({ data: [{ id: plan.model.servedName }] }), + stderr: "", + message: "", + }) + .mockReturnValueOnce({ + ok: true, + httpStatus: 200, + curlStatus: 0, + body: JSON.stringify({ model: plan.model.servedName, choices: [{ message: {} }] }), + stderr: "", + message: "", + }); + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ createBearerAuthConfig, runCurlProbe }), + ); + const request = { + baseUrl: plan.roles.head.endpoint!, + apiKey: API_KEY, + expectedModel: plan.model.servedName, + timeoutMs: 10_000, + }; + + await expect(executor.probeModels(request)).resolves.toBe(true); + await expect(executor.probeChat(request)).resolves.toBe(true); + await expect( + executor.probeModels({ ...request, baseUrl: "http://attacker.invalid:8000" }), + ).resolves.toBe(false); + for (const [argv, options] of runCurlProbe.mock.calls) { + expect(JSON.stringify(argv)).not.toContain(API_KEY); + expect(argv).toContain("--config"); + expect(options.pinnedAddresses).toEqual([]); + expect(options.timeoutMs).toBeLessThanOrEqual(35_000); + } + expect(createBearerAuthConfig).toHaveBeenCalledWith(API_KEY, expect.any(Object)); + expect(cleanup).toHaveBeenCalledTimes(2); + expect(runCurlProbe).toHaveBeenCalledTimes(2); + }); + + it("generates 32-hex transactions and serializes through the shared lifecycle lock", async () => { + let lockCalls = 0; + const withLifecycleLock = async (operation: () => Promise): Promise => { + lockCalls += 1; + return await operation(); + }; + const executor = createDualSparkVllmExecutor( + { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }, + runtimeOverrides({ + createTransactionId: () => "d".repeat(32), + withLifecycleLock, + }), + ); + + expect(executor.createTransactionId()).toMatch(/^[a-f0-9]{32}$/); + await expect(executor.withLifecycleLock(plan, async () => "done")).resolves.toBe("done"); + expect(lockCalls).toBe(1); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-executor.ts b/src/lib/inference/serving/dual-spark-executor.ts new file mode 100644 index 00000000000..f08b80b336a --- /dev/null +++ b/src/lib/inference/serving/dual-spark-executor.ts @@ -0,0 +1,1035 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { randomBytes } from "node:crypto"; +import net from "node:net"; +import path from "node:path"; +import { isDeepStrictEqual } from "node:util"; + +import { dockerForceRm, dockerRunDetached } from "../../adapters/docker/container.js"; +import { dockerCapture } from "../../adapters/docker/run.js"; +import { createBearerAuthConfig } from "../../adapters/http/auth-config.js"; +import { runCurlProbe } from "../../adapters/http/probe.js"; +import { + buildLocalDualStationDockerEnv, + buildRemoteVllmDockerEnv, + captureManagedVllmTcpListeners, +} from "../vllm-docker-env.js"; +import { withHostGlobalVllmLifecycleLock } from "../vllm-station-lifecycle-lock.js"; +import { + type DualStationSshBinding, + encodeDualStationSshBindingHandoff, +} from "../vllm-station-ssh-binding.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { + type DualSparkApiProbeRequest, + type DualSparkContainerStartRequest, + type DualSparkContainerWaitRequest, + type DualSparkNodeSnapshot, + type DualSparkObservedContainer, + type DualSparkStageRequest, + type DualSparkVllmLifecycleDeps, + isRelatedManagedVllmContainer, +} from "./dual-spark-lifecycle.js"; +import { + DUAL_SPARK_ADAPTER_LABEL, + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_CLUSTER_LABEL, + DUAL_SPARK_GPU_LABEL, + DUAL_SPARK_IMAGE_LABEL, + DUAL_SPARK_MANAGED_LABEL, + DUAL_SPARK_MODEL_REVISION_LABEL, + DUAL_SPARK_PLAN_LABEL, + DUAL_SPARK_PRESET_LABEL, + DUAL_SPARK_RECIPE_LABEL, + DUAL_SPARK_ROLE_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + DUAL_SPARK_VLLM_ADAPTER_ID, + DUAL_SPARK_VLLM_API_PORT, + DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, + DUAL_SPARK_VLLM_MASTER_PORT, + DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, + type DualSparkVllmPlan, + type DualSparkVllmRole, + type DualSparkVllmRolePlan, +} from "./dual-spark-materialize.js"; +import { + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, +} from "./dual-spark-topology.js"; + +const API_KEY_PATTERN = /^[a-f0-9]{64}$/; +const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/; +const HEX64_PATTERN = /^[a-f0-9]{64}$/; +const SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/; +const TRANSACTION_ID_PATTERN = /^[a-f0-9]{32}$/; +const LABEL_NAME_PATTERN = /^[a-z0-9][a-z0-9._/-]{0,255}$/; +const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const MAX_CONTAINERS = 256; +const DOCKER_INSPECTION_TIMEOUT_MS = 20_000; +const DOCKER_MUTATION_TIMEOUT_MS = 120_000; +const PROCESS_PROBE_TIMEOUT_MS = 10_000; +const PROCESS_PROBE_INTERVAL_MS = 1_000; +const MAX_PROCESS_WAIT_MS = 120_000; +const API_PROBE_INTERVAL_MS = 2_000; +const MAX_MODELS_PROBE_MS = 3_600_000; +const MAX_CHAT_PROBE_MS = 120_000; + +const CONTAINER_INSPECTION_FORMAT = + "[{{json .Id}},{{json .Name}},{{json .Config.Image}},{{json .State.Running}},{{json .Config.Labels}}]"; + +const PROCESS_PROBE_SCRIPT = String.raw` +import base64, glob, json, sys +expected = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==")) +for item in glob.glob("/proc/[0-9]*/cmdline"): + try: + raw = open(item, "rb").read(1024 * 1024) + argv = [part.decode("utf-8") for part in raw.split(b"\0") if part] + except (OSError, UnicodeDecodeError): + continue + try: + index = argv.index("/usr/local/bin/vllm") + except ValueError: + continue + actual = argv[index:] + if actual[:len(expected)] != expected: + continue + tail = actual[len(expected):] + if not tail: + print("ready") + raise SystemExit(0) +raise SystemExit(1) +`.trim(); + +const REASONING_REPLACEMENT_SCRIPT = String.raw` +import base64, pathlib, sys +target = pathlib.Path(sys.argv[1]) +existing = base64.urlsafe_b64decode(sys.argv[2] + "==").decode("utf-8") +replacement = base64.urlsafe_b64decode(sys.argv[3] + "==").decode("utf-8") +content = target.read_text(encoding="utf-8") +if content.count(existing) != 1: + raise SystemExit("reasoning compatibility source text did not match exactly once") +target.write_text(content.replace(existing, replacement), encoding="utf-8") +`.trim(); + +export interface DualSparkExecutorStageTarget { + readonly role: DualSparkVllmRole; + readonly dockerEnv: Readonly>; + readonly modelCacheRoot: string; + readonly peerSshBinding?: DualStationSshBinding; +} + +export type DualSparkExecutorStageNode = ( + request: DualSparkStageRequest, + target: DualSparkExecutorStageTarget, +) => Promise<{ ok: boolean; reason?: string }>; + +export interface CreateDualSparkVllmExecutorOptions { + readonly plan: DualSparkVllmPlan; + readonly peerSshBinding: DualStationSshBinding; + readonly localCacheRoot: string; + readonly peerCacheRoot: string; + readonly stageNode?: DualSparkExecutorStageNode; +} + +export interface DualSparkVllmExecutorRuntimeDeps { + dockerCapture: typeof dockerCapture; + dockerForceRm: typeof dockerForceRm; + dockerRunDetached: typeof dockerRunDetached; + captureListeners(role: DualSparkVllmRole, binding: DualStationSshBinding): string; + createBearerAuthConfig: typeof createBearerAuthConfig; + createTransactionId(): string; + now(): number; + runCurlProbe: typeof runCurlProbe; + sleep(ms: number): Promise; + withLifecycleLock(operation: () => Promise): Promise; +} + +type ShippedRecipe = ReturnType< + typeof loadManagedInferenceCatalog +>["recipes"][number]["definition"]["spec"]; + +const DEFAULT_DEPS: DualSparkVllmExecutorRuntimeDeps = { + dockerCapture, + dockerForceRm, + dockerRunDetached, + captureListeners: (role, binding) => + captureManagedVllmTcpListeners(role, binding, DOCKER_INSPECTION_TIMEOUT_MS), + createBearerAuthConfig, + createTransactionId: () => randomBytes(16).toString("hex"), + now: () => Date.now(), + runCurlProbe, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + withLifecycleLock: (operation) => withHostGlobalVllmLifecycleLock(operation), +}; + +function normalizedAbsoluteHostPath(value: string, label: string): string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > 4096 || + !path.posix.isAbsolute(value) || + path.posix.normalize(value) !== value || + value.includes(path.posix.delimiter) || + /[\u0000-\u001f\u007f]/.test(value) + ) { + throw new Error(`${label} must be a normalized absolute POSIX path`); + } + return value; +} + +function exactKeys(actual: object, expected: readonly string[], label: string): void { + const keys = Object.keys(actual).sort(); + if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) { + throw new Error(`${label} does not match the dual-Spark adapter contract`); + } +} + +function recipeCommandArguments( + rolePlan: DualSparkVllmRolePlan, + plan: DualSparkVllmPlan, + recipe: ShippedRecipe, +): string[] { + const staticArguments = recipe.serve.arguments.flatMap(({ name, value }) => + value === undefined ? [name] : [name, String(value)], + ); + return [ + "serve", + recipe.model.id, + "--served-model-name", + recipe.model.servedName, + "--host", + rolePlan.fabric.address, + ...staticArguments, + "--tensor-parallel-size", + String(recipe.execution.tensorParallelSize), + "--pipeline-parallel-size", + String(recipe.execution.pipelineParallelSize), + "--distributed-executor-backend", + recipe.execution.distributedExecutorBackend, + "--nnodes", + String(recipe.execution.nodeCount), + "--node-rank", + String(rolePlan.rank), + "--master-addr", + plan.masterAddress, + "--master-port", + String(plan.masterPort), + ...(rolePlan.role === "worker" ? ["--headless"] : []), + ]; +} + +function assertRolePlan( + rolePlan: DualSparkVllmRolePlan, + plan: DualSparkVllmPlan, + recipe: ShippedRecipe, +): void { + const isHead = rolePlan.role === "head"; + const environment = { + ...recipe.runtime.environment, + VLLM_HOST_IP: rolePlan.fabric.address, + NCCL_IB_HCA: `${rolePlan.fabric.hcaDevice}:${String(rolePlan.fabric.hcaPort)}`, + NCCL_SOCKET_IFNAME: rolePlan.fabric.netdev, + TP_SOCKET_IFNAME: rolePlan.fabric.netdev, + GLOO_SOCKET_IFNAME: rolePlan.fabric.netdev, + NCCL_IB_GID_INDEX: String(rolePlan.fabric.roceGidIndex), + MASTER_ADDR: plan.masterAddress, + MASTER_PORT: String(plan.masterPort), + NODE_RANK: String(rolePlan.rank), + HEADLESS: isHead ? "" : "1", + }; + const baseLabels = { + [DUAL_SPARK_MANAGED_LABEL]: "true", + [DUAL_SPARK_ADAPTER_LABEL]: DUAL_SPARK_VLLM_ADAPTER_ID, + [DUAL_SPARK_PRESET_LABEL]: plan.presetId, + [DUAL_SPARK_RECIPE_LABEL]: plan.recipeId, + [DUAL_SPARK_ROLE_LABEL]: rolePlan.role, + [DUAL_SPARK_CLUSTER_LABEL]: plan.clusterId, + [DUAL_SPARK_PLAN_LABEL]: plan.planId, + [DUAL_SPARK_GPU_LABEL]: rolePlan.gpuId, + [DUAL_SPARK_IMAGE_LABEL]: recipe.runtime.image, + [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.model.revision, + }; + const preparation = { + ref: recipe.model.preparationRef, + phase: "container-before-exec", + modelId: recipe.model.id, + modelRevision: recipe.model.revision, + modelDownloadSizeBytes: recipe.model.downloadSizeBytes, + encodingPath: recipe.model.encodingPath, + encodingSourcePath: `/cache/huggingface/hub/models--${recipe.model.id.replaceAll("/", "--")}/snapshots/${recipe.model.revision}/${recipe.model.encodingPath}`, + encodingTargetPath: + "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py", + reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py", + reasoningCompatibility: { + existingText: + 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n else:\n reasoning_effort = "high"', + replacementText: + 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n elif reasoning_effort == "high":\n reasoning_effort = "high"\n else:\n reasoning_effort = "low"', + }, + }; + const fabric = { + primaryRailIndex: rolePlan.fabric.primaryRailIndex, + netdev: rolePlan.fabric.netdev, + hcaDevice: rolePlan.fabric.hcaDevice, + hcaPort: rolePlan.fabric.hcaPort, + address: rolePlan.fabric.address, + roceGidIndex: rolePlan.fabric.roceGidIndex, + roceGidValue: rolePlan.fabric.roceGidValue, + }; + const expected = { + role: rolePlan.role, + rank: isHead ? 0 : 1, + nodeId: rolePlan.nodeId, + gpuId: rolePlan.gpuId, + containerName: isHead + ? DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME + : DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, + execution: rolePlan.execution, + image: recipe.runtime.image, + runtime: { + networkMode: recipe.runtime.networkMode, + ipcMode: recipe.runtime.ipcMode, + sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, + gpuRequest: "all", + devices: recipe.runtime.devices, + imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, + ulimits: { memlock: -1, stack: 67_108_864 }, + modelCache: { source: "huggingface-cache", target: "/cache/huggingface" }, + }, + preparation, + fabric, + environment, + command: { + executable: "/usr/local/bin/vllm", + arguments: recipeCommandArguments(rolePlan, plan, recipe), + }, + endpoint: isHead ? `http://${plan.masterAddress}:${String(DUAL_SPARK_VLLM_API_PORT)}` : null, + baseLabels, + }; + if ( + !isDeepStrictEqual(rolePlan, expected) || + !rolePlan.nodeId || + rolePlan.nodeId.length > 256 || + !/^GPU-[A-Za-z0-9-]+$/.test(rolePlan.gpuId) || + rolePlan.fabric.primaryRailIndex !== 0 || + !SAFE_DEVICE_PATTERN.test(rolePlan.fabric.netdev) || + !SAFE_DEVICE_PATTERN.test(rolePlan.fabric.hcaDevice) || + net.isIP(rolePlan.fabric.address) !== 4 || + net.isIP(rolePlan.fabric.roceGidValue) !== 6 || + !Number.isInteger(rolePlan.fabric.hcaPort) || + !Number.isInteger(rolePlan.fabric.roceGidIndex) + ) { + throw new Error(`${rolePlan.role} role does not match the catalog-derived adapter contract`); + } +} + +/** Read-only validation shared by installer, receipt, recovery, and cleanup. */ +export function assertDualSparkVllmExecutorConfig( + config: CreateDualSparkVllmExecutorOptions, +): void { + exactKeys( + config, + [ + "localCacheRoot", + "peerCacheRoot", + "peerSshBinding", + "plan", + ...(Object.hasOwn(config, "stageNode") ? ["stageNode"] : []), + ], + "Dual-Spark executor configuration", + ); + normalizedAbsoluteHostPath(config.localCacheRoot, "Local model cache root"); + normalizedAbsoluteHostPath(config.peerCacheRoot, "Peer model cache root"); + const { plan, peerSshBinding: binding } = config; + const catalog = loadManagedInferenceCatalog(); + const recipe = catalog.recipes[0]!.definition.spec; + const expectedPlan = { + schemaVersion: 1, + adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + catalogDigest: catalog.catalogDigest, + presetId: catalog.presets[0]!.definition.metadata.id, + recipeId: catalog.recipes[0]!.definition.metadata.id, + topologyId: DUAL_SPARK_TOPOLOGY_ID, + topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + topologySubjectDigest: plan.topologySubjectDigest, + topologyOutputDigest: plan.topologyOutputDigest, + clusterId: plan.clusterId, + planId: plan.planId, + model: { + id: recipe.model.id, + revision: recipe.model.revision, + servedName: recipe.model.servedName, + }, + apiPort: DUAL_SPARK_VLLM_API_PORT, + masterAddress: plan.masterAddress, + masterPort: DUAL_SPARK_VLLM_MASTER_PORT, + readiness: { + timeoutMs: recipe.readiness.timeoutSeconds * 1000, + expectedModel: recipe.readiness.expectedModel, + }, + roles: plan.roles, + }; + if ( + !isDeepStrictEqual(plan, expectedPlan) || + plan.masterAddress !== plan.roles.head.fabric.address || + !HEX64_PATTERN.test(plan.clusterId) || + !HEX64_PATTERN.test(plan.planId) || + !SHA256_PATTERN.test(plan.topologySubjectDigest) || + !SHA256_PATTERN.test(plan.topologyOutputDigest) || + !isDeepStrictEqual(plan.roles.head.execution, { kind: "local" }) || + !isDeepStrictEqual(plan.roles.worker.execution, { + kind: "ssh", + expectedTarget: binding.peerTarget, + bindingHandle: encodeDualStationSshBindingHandoff(binding), + }) + ) { + throw new Error("Dual-Spark executor input does not match its qualified binding and plan"); + } + assertRolePlan(plan.roles.head, plan, recipe); + assertRolePlan(plan.roles.worker, plan, recipe); +} + +function shellQuote(value: string): string { + if (value.includes("\0")) throw new Error("Dual-Spark command value contains a NUL byte"); + return `'${value.replaceAll("'", `'"'"'`)}'`; +} + +function base64url(value: string): string { + return Buffer.from(value, "utf8").toString("base64url"); +} + +function preparationCommand(rolePlan: DualSparkVllmRolePlan): string { + const preparation = rolePlan.preparation; + const command = [ + "set -Eeuo pipefail", + `test -f ${shellQuote(preparation.encodingSourcePath)}`, + `install -m 0644 -- ${shellQuote(preparation.encodingSourcePath)} ${shellQuote(preparation.encodingTargetPath)}`, + [ + "python3", + "-c", + shellQuote(REASONING_REPLACEMENT_SCRIPT), + shellQuote(preparation.reasoningModulePath), + shellQuote(base64url(preparation.reasoningCompatibility.existingText)), + shellQuote(base64url(preparation.reasoningCompatibility.replacementText)), + ].join(" "), + ]; + const executable = shellQuote(rolePlan.command.executable); + const commandArguments = rolePlan.command.arguments.map(shellQuote).join(" "); + command.push(`exec ${executable} ${commandArguments}`); + return command.join(" && "); +} + +function validateLaunchLabels( + rolePlan: DualSparkVllmRolePlan, + labels: Readonly>, +): void { + const expectedKeys = [ + ...Object.keys(rolePlan.baseLabels), + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + ].sort(); + exactKeys(labels, expectedKeys, `${rolePlan.role} launch labels`); + for (const [name, value] of Object.entries(labels)) { + if ( + !LABEL_NAME_PATTERN.test(name) || + typeof value !== "string" || + value.length === 0 || + value.length > 4096 || + /[\u0000\r\n]/.test(value) + ) { + throw new Error(`${rolePlan.role} launch labels are unsafe`); + } + } + if ( + !Object.entries(rolePlan.baseLabels).every(([name, value]) => labels[name] === value) || + !HEX64_PATTERN.test(labels[DUAL_SPARK_API_KEY_FINGERPRINT_LABEL] ?? "") || + !TRANSACTION_ID_PATTERN.test(labels[DUAL_SPARK_TRANSACTION_LABEL] ?? "") + ) { + throw new Error(`${rolePlan.role} launch labels do not match its plan`); + } +} + +/** Build the exact, non-secret Docker run argv for one materialized role. */ +export function buildDualSparkVllmRunArgs( + rolePlan: DualSparkVllmRolePlan, + modelCacheRoot: string, + labels: Readonly>, +): string[] { + const cacheRoot = normalizedAbsoluteHostPath(modelCacheRoot, `${rolePlan.role} model cache root`); + validateLaunchLabels(rolePlan, labels); + const args = [ + "--pull=never", + "--init", + "--network", + "host", + "--ipc", + "host", + "--shm-size", + "64g", + "--gpus", + "all", + "--device", + "/dev/infiniband", + "--ulimit", + "memlock=-1", + "--ulimit", + "stack=67108864", + "--tmpfs", + "/cache/huggingface:rw,nosuid,nodev,exec,size=17179869184,mode=0700", + "--tmpfs", + "/tmp:rw,nosuid,nodev,exec,size=17179869184,mode=1777", + "--volume", + `${cacheRoot}/hub:${rolePlan.runtime.modelCache.target}/hub:ro`, + ]; + for (const [name, value] of Object.entries(rolePlan.environment).sort(([left], [right]) => + left.localeCompare(right), + )) { + args.push("--env", `${name}=${value}`); + } + if (rolePlan.role === "head") args.push("--env", "VLLM_API_KEY"); + for (const [name, value] of Object.entries(labels).sort(([left], [right]) => + left.localeCompare(right), + )) { + args.push("--label", `${name}=${value}`); + } + args.push( + "--name", + rolePlan.containerName, + "--entrypoint", + "/bin/bash", + rolePlan.image, + "-lc", + preparationCommand(rolePlan), + ); + return args; +} + +function parseJsonField(value: string, label: string): T { + try { + return JSON.parse(value) as T; + } catch { + throw new Error(`${label} returned malformed JSON`); + } +} + +function parseLabels(value: unknown): Readonly> { + if (value === null) return {}; + if (typeof value !== "object" || Array.isArray(value) || Object.keys(value).length > 128) { + throw new Error("Docker container labels are malformed"); + } + const labels: Record = {}; + for (const [name, item] of Object.entries(value)) { + if ( + !LABEL_NAME_PATTERN.test(name) || + typeof item !== "string" || + item.length > 4096 || + /[\u0000\r\n]/.test(item) + ) { + throw new Error("Docker container labels are malformed"); + } + labels[name] = item; + } + return labels; +} + +interface InspectedContainer { + id: string; + name: string; + image: string; + running: boolean; + labels: Readonly>; +} + +function parseContainerRows(output: string, expectedIds: readonly string[]): InspectedContainer[] { + const lines = output.split(/\r?\n/).filter(Boolean); + if (lines.length !== expectedIds.length) { + throw new Error("Docker container inspection was incomplete or ambiguous"); + } + const containers = lines.map((line, index) => { + const fields = parseJsonField(line, "Docker container inspection"); + if (!Array.isArray(fields) || fields.length !== 5) { + throw new Error("Docker container inspection was malformed"); + } + const [id, rawName, image, running, rawLabels] = fields; + const labels = parseLabels(rawLabels); + const name = + typeof rawName === "string" && rawName.startsWith("/") ? rawName.slice(1) : rawName; + if ( + typeof id !== "string" || + !CONTAINER_ID_PATTERN.test(id) || + id !== expectedIds[index] || + typeof name !== "string" || + name.length === 0 || + name.length > 256 || + typeof image !== "string" || + image.length === 0 || + image.length > 1024 || + typeof running !== "boolean" + ) { + throw new Error("Docker container inspection was malformed"); + } + return { id, name, image, running, labels }; + }); + if (new Set(containers.map(({ id }) => id)).size !== containers.length) { + throw new Error("Docker container inspection returned duplicate IDs"); + } + return containers; +} + +function parseListeningPorts(output: string): number[] { + if (!output.trim()) return []; + const ports = output + .trim() + .split(/\r?\n/) + .map((line) => { + const fields = line.trim().split(/\s+/); + const local = fields[3]; + const match = local?.match(/:([0-9]{1,5})$/); + const port = match ? Number(match[1]) : Number.NaN; + if (fields[0] !== "LISTEN" || !Number.isInteger(port) || port < 1 || port > 65_535) { + throw new Error("Host listener inspection was malformed"); + } + return port; + }); + return [...new Set(ports)].sort((left, right) => left - right); +} + +function labelsMatch( + actual: Readonly>, + expected: Readonly>, +): boolean { + return Object.entries(expected).every(([name, value]) => actual[name] === value); +} + +function mutationSucceeded(result: ReturnType): boolean { + return result.status === 0 && !result.error && !result.signal; +} + +function modelCacheFor( + role: DualSparkVllmRole, + config: CreateDualSparkVllmExecutorOptions, +): string { + return role === "head" ? config.localCacheRoot : config.peerCacheRoot; +} + +function roleDockerEnv( + rolePlan: DualSparkVllmRolePlan, + config: CreateDualSparkVllmExecutorOptions, +): Record { + const env = + rolePlan.role === "head" + ? buildLocalDualStationDockerEnv() + : buildRemoteVllmDockerEnv(config.peerSshBinding); + delete env.VLLM_API_KEY; + return env; +} + +function processMatchesRole( + rolePlan: DualSparkVllmRolePlan, + containerId: string, + env: Record, + deps: DualSparkVllmExecutorRuntimeDeps, +): boolean { + const expected = base64url( + JSON.stringify([rolePlan.command.executable, ...rolePlan.command.arguments]), + ); + try { + return ( + deps + .dockerCapture(["exec", containerId, "python3", "-c", PROCESS_PROBE_SCRIPT, expected], { + env, + timeout: PROCESS_PROBE_TIMEOUT_MS, + }) + .trim() === "ready" + ); + } catch { + return false; + } +} + +function inspectRoleNode( + rolePlan: DualSparkVllmRolePlan, + config: CreateDualSparkVllmExecutorOptions, + deps: DualSparkVllmExecutorRuntimeDeps, +): DualSparkNodeSnapshot { + const env = roleDockerEnv(rolePlan, config); + const rawIds = deps.dockerCapture(["container", "ls", "--all", "--no-trunc", "--quiet"], { + env, + timeout: DOCKER_INSPECTION_TIMEOUT_MS, + }); + const ids = rawIds.split(/\r?\n/).filter(Boolean); + if ( + ids.length > MAX_CONTAINERS || + ids.some((id) => !CONTAINER_ID_PATTERN.test(id)) || + new Set(ids).size !== ids.length + ) { + throw new Error(`${rolePlan.role} Docker container inventory is malformed or too large`); + } + const inspected = ids.length + ? parseContainerRows( + deps.dockerCapture( + ["container", "inspect", "--format", CONTAINER_INSPECTION_FORMAT, ...ids], + { env, timeout: DOCKER_INSPECTION_TIMEOUT_MS }, + ), + ids, + ) + : []; + const containers: DualSparkObservedContainer[] = inspected.map((container) => ({ + ...container, + healthy: + container.running && + container.name === rolePlan.containerName && + container.image === rolePlan.image && + labelsMatch(container.labels, rolePlan.baseLabels) && + processMatchesRole(rolePlan, container.id, env, deps), + })); + const listeningPorts = parseListeningPorts( + deps.captureListeners(rolePlan.role, config.peerSshBinding), + ); + return { containers, listeningPorts }; +} + +export interface DualSparkVllmNodeSnapshots { + readonly head: DualSparkNodeSnapshot; + readonly worker: DualSparkNodeSnapshot; +} + +/** Synchronous read-only recovery seam backed by the production inspector. */ +export function inspectDualSparkVllmNodesSync( + config: CreateDualSparkVllmExecutorOptions, + overrides: Partial = {}, +): DualSparkVllmNodeSnapshots { + const deps = { ...DEFAULT_DEPS, ...overrides }; + assertDualSparkVllmExecutorConfig(config); + return { + head: inspectRoleNode(config.plan.roles.head, config, deps), + worker: inspectRoleNode(config.plan.roles.worker, config, deps), + }; +} + +function exactWaitObservation( + snapshot: DualSparkNodeSnapshot, + request: DualSparkContainerWaitRequest, +): DualSparkObservedContainer | null { + const matches = snapshot.containers.filter(({ id }) => id === request.containerId); + if (matches.length !== 1) return null; + const observed = matches[0]!; + return observed.name === request.rolePlan.containerName && + observed.image === request.rolePlan.image && + labelsMatch(observed.labels, request.expectedLabels) + ? observed + : null; +} + +function workerFirstBoundaryIsClear(snapshot: DualSparkNodeSnapshot): boolean { + return ( + !snapshot.listeningPorts.some( + (port) => port === DUAL_SPARK_VLLM_API_PORT || port === DUAL_SPARK_VLLM_MASTER_PORT, + ) && !snapshot.containers.some(isRelatedManagedVllmContainer) + ); +} + +async function waitForRoleProcess( + request: DualSparkContainerWaitRequest, + config: CreateDualSparkVllmExecutorOptions, + deps: DualSparkVllmExecutorRuntimeDeps, + stableChecks: number, + requireHeadAbsent = false, +): Promise { + const deadline = deps.now() + Math.min(Math.max(1, request.timeoutMs), MAX_PROCESS_WAIT_MS); + let consecutive = 0; + do { + try { + const observed = exactWaitObservation( + await inspectRoleNode(request.rolePlan, config, deps), + request, + ); + const headAbsent = + !requireHeadAbsent || + workerFirstBoundaryIsClear(inspectRoleNode(config.plan.roles.head, config, deps)); + consecutive = observed?.running && observed.healthy && headAbsent ? consecutive + 1 : 0; + if (consecutive >= stableChecks) return true; + } catch { + consecutive = 0; + } + const remaining = deadline - deps.now(); + if (remaining <= 0) return false; + await deps.sleep(Math.min(PROCESS_PROBE_INTERVAL_MS, remaining)); + } while (deps.now() <= deadline); + return false; +} + +function validApiBody(body: string, expectedModel: string, kind: "models" | "chat"): boolean { + try { + const parsed = JSON.parse(body) as { data?: unknown; model?: unknown; choices?: unknown }; + if (kind === "models") { + const item = Array.isArray(parsed.data) && parsed.data.length === 1 ? parsed.data[0] : null; + return ( + !!item && + typeof item === "object" && + !Array.isArray(item) && + (item as { id?: unknown }).id === expectedModel + ); + } + return ( + parsed.model === expectedModel && + Array.isArray(parsed.choices) && + parsed.choices.length === 1 && + typeof parsed.choices[0] === "object" && + parsed.choices[0] !== null + ); + } catch { + return false; + } +} + +async function probeAuthenticatedApi( + request: DualSparkApiProbeRequest, + kind: "models" | "chat", + deps: DualSparkVllmExecutorRuntimeDeps, +): Promise { + if (!API_KEY_PATTERN.test(request.apiKey)) return false; + const maximum = kind === "models" ? MAX_MODELS_PROBE_MS : MAX_CHAT_PROBE_MS; + const deadline = deps.now() + Math.min(Math.max(1, request.timeoutMs), maximum); + do { + const remaining = Math.max(1, deadline - deps.now()); + const maxTimeSeconds = Math.max(1, Math.min(30, Math.ceil(remaining / 1000))); + let authConfig: ReturnType | undefined; + try { + authConfig = deps.createBearerAuthConfig(request.apiKey, { + prefix: "nemoclaw-dual-spark-vllm-probe", + }); + const baseUrl = request.baseUrl.replace(/\/+$/, ""); + const body = + kind === "chat" + ? JSON.stringify({ + model: request.expectedModel, + messages: [{ role: "user", content: "Reply with OK." }], + max_tokens: 1, + temperature: 0, + }) + : null; + const result = deps.runCurlProbe( + [ + "-sS", + "--connect-timeout", + "3", + "--max-time", + String(maxTimeSeconds), + ...(body ? ["-H", "Content-Type: application/json", "-d", body] : []), + ...authConfig.args, + `${baseUrl}/v1/${kind === "models" ? "models" : "chat/completions"}`, + ], + { + trustedConfigFiles: authConfig.trustedConfigFiles, + pinnedAddresses: [], + timeoutMs: (maxTimeSeconds + 5) * 1000, + }, + ); + if (result.ok && validApiBody(result.body, request.expectedModel, kind)) { + return true; + } + } catch { + // Retry until the caller-owned, bounded readiness deadline. + } finally { + authConfig?.cleanup(); + } + const retryRemaining = deadline - deps.now(); + if (retryRemaining <= 0) return false; + await deps.sleep(Math.min(API_PROBE_INTERVAL_MS, retryRemaining)); + } while (deps.now() <= deadline); + return false; +} + +/** + * Bind the code-owned lifecycle to two exact Docker daemons and the qualified, + * owner-only SSH handoff. Staging stays caller-injected so this module does not + * depend on installer/model-download orchestration. + */ +export function createDualSparkVllmExecutor( + config: CreateDualSparkVllmExecutorOptions, + overrides: Partial = {}, +): DualSparkVllmLifecycleDeps { + const deps = { ...DEFAULT_DEPS, ...overrides }; + assertDualSparkVllmExecutorConfig(config); + const capturedPlan = structuredClone(config.plan); + const assertPlan = (plan: DualSparkVllmPlan): void => { + if (!isDeepStrictEqual(plan, capturedPlan)) { + throw new Error("Dual-Spark executor refused a changed materialized plan"); + } + assertDualSparkVllmExecutorConfig(config); + }; + const assertRole = (rolePlan: DualSparkVllmRolePlan): void => { + assertPlan(config.plan); + if (!isDeepStrictEqual(rolePlan, config.plan.roles[rolePlan.role])) { + throw new Error("Dual-Spark executor refused a role outside its materialized plan"); + } + }; + + return { + async inspectNode(rolePlan) { + assertRole(rolePlan); + return inspectRoleNode(rolePlan, config, deps); + }, + async stageNode(request) { + assertRole(request.rolePlan); + if (!isDeepStrictEqual(request.preparation, request.rolePlan.preparation)) { + return { ok: false, reason: `${request.rolePlan.role} preparation contract changed` }; + } + if (!config.stageNode) { + return { ok: false, reason: "dual-Spark model and image staging is not configured" }; + } + const dockerEnv = roleDockerEnv(request.rolePlan, config); + return await config.stageNode(request, { + role: request.rolePlan.role, + dockerEnv, + modelCacheRoot: modelCacheFor(request.rolePlan.role, config), + ...(request.rolePlan.role === "worker" ? { peerSshBinding: config.peerSshBinding } : {}), + }); + }, + async startContainer(request: DualSparkContainerStartRequest) { + assertRole(request.rolePlan); + if (!isDeepStrictEqual(request.preparation, request.rolePlan.preparation)) { + return { ok: false, reason: `${request.rolePlan.role} preparation contract changed` }; + } + const isHead = request.rolePlan.role === "head"; + if ( + (isHead && !API_KEY_PATTERN.test(request.bearerApiKey ?? "")) || + (!isHead && request.bearerApiKey !== undefined) || + (request.bearerApiKey && Object.values(request.labels).includes(request.bearerApiKey)) + ) { + return { ok: false, reason: `${request.rolePlan.role} bearer-key boundary is invalid` }; + } + let args: string[]; + try { + args = buildDualSparkVllmRunArgs( + request.rolePlan, + modelCacheFor(request.rolePlan.role, config), + request.labels, + ); + } catch (error) { + return { ok: false, reason: (error as Error).message }; + } + if (request.bearerApiKey && JSON.stringify(args).includes(request.bearerApiKey)) { + return { ok: false, reason: "dual-Spark bearer key entered Docker argv" }; + } + const env = roleDockerEnv(request.rolePlan, config); + if (isHead) env.VLLM_API_KEY = request.bearerApiKey!; + let result: ReturnType | null = null; + try { + result = deps.dockerRunDetached(args, { + env, + ignoreError: true, + suppressOutput: true, + timeout: DOCKER_MUTATION_TIMEOUT_MS, + }); + } catch { + // Reconcile an exact transaction-owned create below. + } + let observed: DualSparkObservedContainer | null = null; + try { + const snapshot = await inspectRoleNode(request.rolePlan, config, deps); + const candidates = snapshot.containers.filter( + (container) => + container.name === request.rolePlan.containerName && + container.image === request.rolePlan.image && + labelsMatch(container.labels, request.labels), + ); + if (candidates.length === 1) observed = candidates[0]!; + } catch { + // A missing exact observation leaves the mutation uncommitted here. + } + const capturedId = String(result?.stdout ?? "").trim(); + const exactId = CONTAINER_ID_PATTERN.test(capturedId) ? capturedId : observed?.id; + if ( + exactId && + observed?.id === exactId && + observed.running && + (result === null || mutationSucceeded(result)) + ) { + return { ok: true, containerId: exactId }; + } + return { + ok: false, + ...(exactId ? { containerId: exactId } : {}), + reason: `${request.rolePlan.role} Docker create did not commit one exact running container`, + }; + }, + async waitForContainerReady(request) { + assertRole(request.rolePlan); + return await waitForRoleProcess(request, config, deps, 1); + }, + async waitForWorkerDistributedReady(request) { + assertRole(request.rolePlan); + if (request.rolePlan.role !== "worker") return false; + // Two spaced exact-process observations prove rank 1 remained alive + // while rank 0 was still absent, the worker-first rendezvous boundary. + return await waitForRoleProcess(request, config, deps, 2, true); + }, + async removeContainer(rolePlan, exactContainerId) { + assertRole(rolePlan); + if (!CONTAINER_ID_PATTERN.test(exactContainerId)) { + return { ok: false, reason: `${rolePlan.role} cleanup container ID is invalid` }; + } + const before = await inspectRoleNode(rolePlan, config, deps); + const matches = before.containers.filter(({ id }) => id === exactContainerId); + if ( + matches.length !== 1 || + matches[0]!.name !== rolePlan.containerName || + matches[0]!.image !== rolePlan.image || + !labelsMatch(matches[0]!.labels, rolePlan.baseLabels) + ) { + return { ok: false, reason: `${rolePlan.role} exact cleanup ownership changed` }; + } + const env = roleDockerEnv(rolePlan, config); + let removed = false; + try { + removed = mutationSucceeded( + deps.dockerForceRm(exactContainerId, { + env, + ignoreError: true, + suppressOutput: true, + timeout: DOCKER_MUTATION_TIMEOUT_MS, + }), + ); + } catch { + // Reconcile the exact ID below. + } + if (!removed) { + try { + const after = await inspectRoleNode(rolePlan, config, deps); + removed = !after.containers.some(({ id }) => id === exactContainerId); + } catch { + removed = false; + } + } + return removed + ? { ok: true } + : { ok: false, reason: `${rolePlan.role} exact container removal failed` }; + }, + async probeModels(request) { + if ( + request.baseUrl !== config.plan.roles.head.endpoint || + request.expectedModel !== config.plan.readiness.expectedModel + ) { + return false; + } + return await probeAuthenticatedApi(request, "models", deps); + }, + async probeChat(request) { + if ( + request.baseUrl !== config.plan.roles.head.endpoint || + request.expectedModel !== config.plan.readiness.expectedModel + ) { + return false; + } + return await probeAuthenticatedApi(request, "chat", deps); + }, + createTransactionId: deps.createTransactionId, + async withLifecycleLock(plan, operation) { + assertPlan(plan); + return await deps.withLifecycleLock(operation); + }, + }; +} diff --git a/src/lib/inference/serving/dual-spark-fixture.test-support.ts b/src/lib/inference/serving/dual-spark-fixture.test-support.ts new file mode 100644 index 00000000000..5f454308fe8 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-fixture.test-support.ts @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { loadManagedInferenceCatalog } from "./catalog.js"; +import type { ResolvedManagedInferenceSelection } from "./catalog-types.js"; +import { type DualSparkVllmPlan, materializeDualSparkVllmPlan } from "./dual-spark-materialize.js"; +import { + type DualSparkTopologyOutput, + dualSparkTopologyOutputDigest, + dualSparkTopologySubjectDigest, +} from "./dual-spark-topology.js"; + +export function fixtureDualSparkSelection(): ResolvedManagedInferenceSelection { + const catalog = loadManagedInferenceCatalog(); + const preset = structuredClone(catalog.presets[0]?.definition); + const recipe = structuredClone(catalog.recipes[0]?.definition); + if (!preset || !recipe) throw new Error("managed inference fixture catalog is incomplete"); + const subjectNodeIds = ["spark-head", "spark-worker"] as const; + const output: DualSparkTopologyOutput = { + headNodeId: "spark-head", + workerNodeId: "spark-worker", + nodes: [ + { nodeId: "spark-head", gpuId: "GPU-head", role: "head" }, + { nodeId: "spark-worker", gpuId: "GPU-worker", role: "worker" }, + ], + rails: [ + { + index: 0, + head: { + nodeId: "spark-head", + netdev: "enp1s0f0np0", + hcaDevice: "rocep1s0f0", + hcaPort: 1, + address: "192.168.100.10", + prefixLength: 24, + peerAddress: "192.168.100.11", + roceGid: { index: 3, value: "::ffff:c0a8:640a" }, + }, + worker: { + nodeId: "spark-worker", + netdev: "enp1s0f1np1", + hcaDevice: "rocep1s0f1", + hcaPort: 1, + address: "192.168.100.11", + prefixLength: 24, + peerAddress: "192.168.100.10", + roceGid: { index: 6, value: "::ffff:c0a8:640b" }, + }, + }, + { + index: 1, + head: { + nodeId: "spark-head", + netdev: "enP2p1s0f0np0", + hcaDevice: "roceP2p1s0f0", + hcaPort: 1, + address: "192.168.101.10", + prefixLength: 24, + peerAddress: "192.168.101.11", + roceGid: { index: 4, value: "::ffff:c0a8:650a" }, + }, + worker: { + nodeId: "spark-worker", + netdev: "enP2p1s0f1np1", + hcaDevice: "roceP2p1s0f1", + hcaPort: 1, + address: "192.168.101.11", + prefixLength: 24, + peerAddress: "192.168.101.10", + roceGid: { index: 7, value: "::ffff:c0a8:650b" }, + }, + }, + ], + masterAddress: "192.168.100.10", + peer: { target: "spark-worker.local", sshBindingHandle: "state/dual-spark/peer" }, + }; + return { + outcome: "selected", + selection: "automatic", + catalogDigest: catalog.catalogDigest, + preset, + recipe, + topologyQualification: { + id: "dgx-spark.gb10.dual-cx7", + schemaVersion: 1, + status: "qualified", + subjectNodeIds, + subjectDigest: dualSparkTopologySubjectDigest(subjectNodeIds), + outputDigest: dualSparkTopologyOutputDigest(output), + output, + }, + }; +} + +export function fixtureDualSparkPlan(): DualSparkVllmPlan { + return materializeDualSparkVllmPlan(fixtureDualSparkSelection()); +} diff --git a/src/lib/inference/serving/dual-spark-installer.test.ts b/src/lib/inference/serving/dual-spark-installer.test.ts new file mode 100644 index 00000000000..d9045638cdb --- /dev/null +++ b/src/lib/inference/serving/dual-spark-installer.test.ts @@ -0,0 +1,475 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { + DualSparkConfirmedManagedServingCapability, + DualSparkDetectedManagedServingCapability, +} from "./dual-spark-discovery.js"; +import type { + CreateDualSparkVllmExecutorOptions, + DualSparkExecutorStageNode, +} from "./dual-spark-executor.js"; +import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { + type DualSparkInstallerEffects, + tryInstallDualSparkManagedVllm, +} from "./dual-spark-installer.js"; +import type { DualSparkVllmLifecycleDeps } from "./dual-spark-lifecycle.js"; + +const API_KEY = "a".repeat(64); +const HEAD_ID = "b".repeat(64); +const WORKER_ID = "c".repeat(64); + +function readyCapability(): DualSparkDetectedManagedServingCapability { + const selection = fixtureDualSparkSelection(); + const host = (hostname: string, home: string, uid: number) => ({ + hostname, + home, + uid, + gid: uid, + storage: { huggingFace: { cacheRoot: `${home}/.cache/huggingface` } }, + }); + return { + kind: "ready", + selectionIntent: "automatic", + topology: selection.topologyQualification, + local: host("spark-a", "/home/alice", 1000), + peer: host("spark-b", "/home/bob", 1001), + readiness: [], + peerSshBindingStatePath: "/state/dual-spark-managed-serving.json", + peerSshIdentity: { sshTarget: "spark-b" }, + } as unknown as DualSparkDetectedManagedServingCapability; +} + +function confirmedCapability( + detected: DualSparkDetectedManagedServingCapability, +): DualSparkConfirmedManagedServingCapability { + return { + ...detected, + peerSshBinding: { peerTarget: "spark-b" }, + peerSshBindingHandle: "binding", + } as unknown as DualSparkConfirmedManagedServingCapability; +} + +function effects(): DualSparkInstallerEffects { + return { + prerequisites: vi.fn(() => ({ ok: true })), + pullImage: vi.fn(async () => ({ ok: true })), + downloadModel: vi.fn(async () => ({ ok: true })), + printDownloadAuthentication: vi.fn(), + }; +} + +function successfulStart(reusedExisting = false) { + return { + ok: true as const, + reusedExisting, + baseUrl: "http://192.168.100.10:8000", + headContainerId: HEAD_ID, + workerContainerId: WORKER_ID, + apiKeyFingerprint: "d".repeat(64), + }; +} + +describe("two-Spark managed vLLM installer selection", () => { + beforeEach(() => vi.restoreAllMocks()); + + it("leaves non-Spark and conflict-free explicit legacy vLLM intent untouched", async () => { + const probeCapability = vi.fn(); + await expect( + tryInstallDualSparkManagedVllm( + { platform: "station", nonInteractive: true, promptFn: vi.fn() }, + effects(), + { probeCapability }, + ), + ).resolves.toEqual({ kind: "not-selected" }); + await expect( + tryInstallDualSparkManagedVllm( + { + platform: "spark", + env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, + nonInteractive: true, + promptFn: vi.fn(), + }, + effects(), + { + probeCapability: () => ({ + kind: "not-selected", + code: "no-match", + reason: "no related distributed runtime", + }), + }, + ), + ).resolves.toEqual({ kind: "not-selected" }); + expect(probeCapability).not.toHaveBeenCalled(); + }); + + it("does not let explicit legacy intent bypass a related-runtime conflict", async () => { + const installEffects = effects(); + const result = await tryInstallDualSparkManagedVllm( + { + platform: "spark", + env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, + nonInteractive: true, + promptFn: vi.fn(), + }, + installEffects, + { + probeCapability: () => ({ + kind: "not-selected", + code: "runtime-conflict", + reason: "existing related setup was preserved", + }), + error: vi.fn(), + }, + ); + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(installEffects.pullImage).not.toHaveBeenCalled(); + expect(installEffects.downloadModel).not.toHaveBeenCalled(); + }); + + it("defers qualified explicit legacy intent without claiming binding state", async () => { + const capability = readyCapability(); + const clearBinding = vi.fn(); + const confirmCapability = vi.fn(); + const resolveSelection = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { + platform: "spark", + env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, + nonInteractive: true, + promptFn: vi.fn(), + }, + effects(), + { probeCapability: () => capability, confirmCapability, clearBinding, resolveSelection }, + ); + expect(result).toEqual({ kind: "not-selected" }); + expect(resolveSelection).not.toHaveBeenCalled(); + expect(confirmCapability).not.toHaveBeenCalled(); + expect(clearBinding).not.toHaveBeenCalled(); + }); + + it("falls back only for an ordinary automatic no-match", async () => { + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => ({ + kind: "not-selected", + code: "no-match", + reason: "no exact pair", + }), + }, + ); + expect(result).toEqual({ kind: "not-selected" }); + }); + + it("stops on durable distributed ownership before capability probing or effects", async () => { + const installEffects = effects(); + const probeCapability = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + installEffects, + { + assertNoRuntimeReceipts: () => { + throw new Error("managed runtime receipt already exists"); + }, + probeCapability, + error: vi.fn(), + }, + ); + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(probeCapability).not.toHaveBeenCalled(); + expect(installEffects.pullImage).not.toHaveBeenCalled(); + expect(installEffects.downloadModel).not.toHaveBeenCalled(); + }); + + it("stops before effects when a related runtime is already present", async () => { + const installEffects = effects(); + const error = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + installEffects, + { + probeCapability: () => ({ + kind: "not-selected", + code: "runtime-conflict", + reason: "existing related setup was preserved", + }), + error, + }, + ); + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(error).toHaveBeenCalledWith(expect.stringContaining("preserved")); + expect(installEffects.pullImage).not.toHaveBeenCalled(); + expect(installEffects.downloadModel).not.toHaveBeenCalled(); + }); + + it("revalidates only after consent and stops before effects when the pair changed", async () => { + const capability = readyCapability(); + const installEffects = effects(); + const clearBinding = vi.fn(); + const confirmCapability = vi.fn(() => ({ + kind: "unavailable" as const, + code: "runtime-conflict" as const, + reason: "a related listener appeared after confirmation", + })); + const promptFn = vi.fn(async () => { + expect(confirmCapability).not.toHaveBeenCalled(); + expect(installEffects.prerequisites).not.toHaveBeenCalled(); + return "yes"; + }); + const assertNoRuntimeReceipts = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn }, + installEffects, + { + probeCapability: () => capability, + confirmCapability, + resolveSelection: () => fixtureDualSparkSelection(), + assertNoRuntimeReceipts, + clearBinding, + log: vi.fn(), + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(assertNoRuntimeReceipts).toHaveBeenCalledTimes(2); + expect(confirmCapability).toHaveBeenCalledOnce(); + expect(installEffects.prerequisites).not.toHaveBeenCalled(); + expect(installEffects.pullImage).not.toHaveBeenCalled(); + expect(installEffects.downloadModel).not.toHaveBeenCalled(); + expect(clearBinding).not.toHaveBeenCalled(); + }); + + it("stages both exact nodes, launches, persists ownership, and retires temporary binding state", async () => { + const capability = readyCapability(); + const confirmed = confirmedCapability(capability); + const selection = fixtureDualSparkSelection(); + const installEffects = effects(); + const beforeInstall = vi.fn(); + const clearBinding = vi.fn(); + const persistReceipt = vi.fn(); + let capturedStage: DualSparkExecutorStageNode | undefined; + const executor = {} as DualSparkVllmLifecycleDeps; + const createExecutor = vi.fn((config: CreateDualSparkVllmExecutorOptions) => { + capturedStage = config.stageNode; + return executor; + }); + const start = vi.fn(async (plan) => { + expect(capturedStage).toBeDefined(); + await capturedStage!( + { rolePlan: plan.roles.worker, preparation: plan.roles.worker.preparation }, + { + role: "worker", + dockerEnv: { DOCKER_HOST: "ssh://spark-b" }, + modelCacheRoot: capability.peer.storage.huggingFace.cacheRoot, + peerSshBinding: confirmed.peerSshBinding, + }, + ); + await capturedStage!( + { rolePlan: plan.roles.head, preparation: plan.roles.head.preparation }, + { + role: "head", + dockerEnv: {}, + modelCacheRoot: capability.local.storage.huggingFace.cacheRoot, + }, + ); + return successfulStart(); + }); + + const result = await tryInstallDualSparkManagedVllm( + { + platform: "spark", + env: {}, + nonInteractive: true, + promptFn: vi.fn(), + beforeInstall, + }, + installEffects, + { + probeCapability: () => capability, + confirmCapability: () => confirmed, + resolveSelection: () => selection, + createExecutor: createExecutor as never, + start: start as never, + ensureApiKey: () => API_KEY, + persistReceipt, + clearBinding, + log: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: true } }); + expect(beforeInstall).toHaveBeenCalledWith("deepseek-v4-flash-0731"); + expect(installEffects.pullImage).toHaveBeenCalledTimes(2); + expect(installEffects.downloadModel).toHaveBeenNthCalledWith( + 1, + expect.anything(), + expect.objectContaining({ revision: selection.recipe.spec.model.revision }), + { DOCKER_HOST: "ssh://spark-b" }, + { + hostCacheDir: capability.peer.storage.huggingFace.cacheRoot, + userIdentity: "1001:1001", + }, + ); + expect(start).toHaveBeenCalledWith(expect.anything(), API_KEY, executor); + expect(persistReceipt).toHaveBeenCalledWith( + expect.objectContaining({ + headContainerId: HEAD_ID, + workerContainerId: WORKER_ID, + localCacheRoot: "/home/alice/.cache/huggingface", + peerCacheRoot: "/home/bob/.cache/huggingface", + }), + ); + expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + }); + + it("cleans only a newly-created exact pair when receipt persistence fails", async () => { + const capability = readyCapability(); + const selection = fixtureDualSparkSelection(); + const cleanup = vi.fn(async () => ({ + ok: true as const, + removedContainerIds: [HEAD_ID, WORKER_ID], + })); + const clearBinding = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => capability, + confirmCapability: () => confirmedCapability(capability), + resolveSelection: () => selection, + createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + start: async () => successfulStart(false), + cleanup, + ensureApiKey: () => API_KEY, + persistReceipt: () => { + throw new Error("disk full"); + }, + clearBinding, + log: vi.fn(), + error: vi.fn(), + }, + ); + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(cleanup).toHaveBeenCalledOnce(); + expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + }); + + it("retains the claimed binding when receipt-failure rollback is incomplete", async () => { + const capability = readyCapability(); + const clearBinding = vi.fn(); + const warn = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => capability, + confirmCapability: () => confirmedCapability(capability), + resolveSelection: () => fixtureDualSparkSelection(), + createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + start: async () => successfulStart(false), + cleanup: async () => ({ + ok: false, + reason: "worker cleanup failed", + removedContainerIds: [HEAD_ID], + }), + ensureApiKey: () => API_KEY, + persistReceipt: () => { + throw new Error("disk full"); + }, + clearBinding, + log: vi.fn(), + error: vi.fn(), + warn, + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(clearBinding).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("retained two-Spark SSH ownership")); + }); + + it("retains the claimed binding when lifecycle rollback leaves a container", async () => { + const capability = readyCapability(); + const clearBinding = vi.fn(); + const warn = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => capability, + confirmCapability: () => confirmedCapability(capability), + resolveSelection: () => fixtureDualSparkSelection(), + createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + start: async () => ({ + ok: false, + code: "start-failed", + reason: "head start failed", + rollbackErrors: ["worker cleanup failed"], + }), + ensureApiKey: () => API_KEY, + clearBinding, + log: vi.fn(), + error: vi.fn(), + warn, + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(clearBinding).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("retained two-Spark SSH ownership")); + }); + + it("does not remove an exact reused pair when receipt persistence fails", async () => { + const capability = readyCapability(); + const cleanup = vi.fn(); + const clearBinding = vi.fn(); + await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => capability, + confirmCapability: () => confirmedCapability(capability), + resolveSelection: () => fixtureDualSparkSelection(), + createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + start: async () => successfulStart(true), + cleanup, + ensureApiKey: () => API_KEY, + persistReceipt: () => { + throw new Error("receipt changed"); + }, + clearBinding, + log: vi.fn(), + error: vi.fn(), + }, + ); + expect(cleanup).not.toHaveBeenCalled(); + expect(clearBinding).not.toHaveBeenCalled(); + }); + + it("does not claim or clear binding state when the operator declines", async () => { + const capability = readyCapability(); + const clearBinding = vi.fn(); + const confirmCapability = vi.fn(); + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "no" }, + effects(), + { + probeCapability: () => capability, + confirmCapability, + resolveSelection: () => fixtureDualSparkSelection(), + clearBinding, + log: vi.fn(), + }, + ); + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(confirmCapability).not.toHaveBeenCalled(); + expect(clearBinding).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-installer.ts b/src/lib/inference/serving/dual-spark-installer.ts new file mode 100644 index 00000000000..4b1fe50721d --- /dev/null +++ b/src/lib/inference/serving/dual-spark-installer.ts @@ -0,0 +1,431 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isAffirmativeAnswer } from "../../onboard/prompt-helpers.js"; +import type { VllmProfile } from "../vllm.js"; +import { ensureManagedVllmApiKey } from "../vllm-api-key.js"; +import type { VllmModelDef } from "../vllm-models.js"; +import { VLLM_EXTRA_ARGS_ENV } from "../vllm-models.js"; +import { clearDualStationSshBinding } from "../vllm-station-ssh-binding.js"; +import { + DUAL_SPARK_PRESET_ID, + type ManagedInferenceResolution, + type ManagedInferenceResolverInput, +} from "./catalog-types.js"; +import { + confirmDualSparkManagedServingCapability, + type DualSparkConfirmedManagedServingCapability, + type DualSparkDetectedManagedServingCapability, + NEMOCLAW_DGX_SPARK_PEER_ENV, + NEMOCLAW_SERVING_PRESET_ENV, + probeDualSparkManagedServingCapability, +} from "./dual-spark-discovery.js"; +import { + type CreateDualSparkVllmExecutorOptions, + createDualSparkVllmExecutor, + type DualSparkExecutorStageNode, +} from "./dual-spark-executor.js"; +import { + cleanupDualSparkManagedVllm, + type StartDualSparkVllmResult, + startAutomaticDualSparkVllm, +} from "./dual-spark-lifecycle.js"; +import { + DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, + type DualSparkVllmPlan, + materializeDualSparkVllmPlan, +} from "./dual-spark-materialize.js"; +import type { DualSparkTopologyOutput } from "./dual-spark-topology.js"; +import { assertNoManagedDistributedVllmRuntimeReceipts } from "./managed-runtime-receipts.js"; +import { resolveManagedInferenceServing } from "./resolver.js"; +import { + type PersistDualSparkVllmRuntimeReceiptInput, + persistDualSparkVllmRuntimeReceipt, +} from "./spark-runtime-receipt.js"; + +export interface DualSparkInstallerOptions { + readonly env?: NodeJS.ProcessEnv; + readonly nonInteractive: boolean; + readonly platform: VllmProfile["platform"]; + readonly promptFn: (question: string) => Promise; + readonly beforeInstall?: (modelId: string) => void; +} + +export interface DualSparkInstallerEffects { + readonly prerequisites: () => { ok: boolean; reason?: string }; + readonly pullImage: ( + profile: VllmProfile, + dockerEnv: Record, + ) => Promise<{ ok: boolean; reason?: string }>; + readonly downloadModel: ( + profile: VllmProfile, + model: VllmModelDef, + dockerEnv: Record, + target: { hostCacheDir: string; userIdentity: string }, + ) => Promise<{ ok: boolean; reason?: string }>; + readonly printDownloadAuthentication: (nonInteractive: boolean) => void; +} + +export type DualSparkInstallerResult = + | { readonly kind: "not-selected" } + | { readonly kind: "handled"; readonly result: { readonly ok: boolean } }; + +interface DualSparkInstallerDeps { + readonly probeCapability: typeof probeDualSparkManagedServingCapability; + readonly confirmCapability: typeof confirmDualSparkManagedServingCapability; + readonly resolveSelection: ( + input: ManagedInferenceResolverInput, + ) => ManagedInferenceResolution; + readonly materializePlan: typeof materializeDualSparkVllmPlan; + readonly createExecutor: typeof createDualSparkVllmExecutor; + readonly start: typeof startAutomaticDualSparkVllm; + readonly cleanup: typeof cleanupDualSparkManagedVllm; + readonly persistReceipt: typeof persistDualSparkVllmRuntimeReceipt; + readonly ensureApiKey: typeof ensureManagedVllmApiKey; + readonly assertNoRuntimeReceipts: typeof assertNoManagedDistributedVllmRuntimeReceipts; + readonly clearBinding: typeof clearDualStationSshBinding; + readonly log: (line?: string) => void; + readonly error: (line: string) => void; + readonly warn: (line: string) => void; +} + +const DEFAULT_DEPS: DualSparkInstallerDeps = { + probeCapability: probeDualSparkManagedServingCapability, + confirmCapability: confirmDualSparkManagedServingCapability, + resolveSelection: resolveManagedInferenceServing, + materializePlan: materializeDualSparkVllmPlan, + createExecutor: createDualSparkVllmExecutor, + start: startAutomaticDualSparkVllm, + cleanup: cleanupDualSparkManagedVllm, + persistReceipt: persistDualSparkVllmRuntimeReceipt, + ensureApiKey: ensureManagedVllmApiKey, + assertNoRuntimeReceipts: assertNoManagedDistributedVllmRuntimeReceipts, + clearBinding: clearDualStationSshBinding, + log: (line = "") => console.log(line), + error: (line) => console.error(line), + warn: (line) => console.warn(line), +}; + +function managedProfile(plan: DualSparkVllmPlan): VllmProfile { + return { + name: "Two DGX Sparks", + platform: "spark", + image: plan.roles.head.image, + imageDownloadSizeBytes: plan.roles.head.runtime.imageDownloadSizeBytes, + defaultModel: managedModel(plan), + containerName: DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, + dockerRunFlags: [], + pullTimeoutSec: 12 * 60 * 60, + loadTimeoutSec: Math.ceil(plan.readiness.timeoutMs / 1000), + modelDownloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + }; +} + +function managedModel(plan: DualSparkVllmPlan): VllmModelDef { + return { + id: plan.model.id, + label: "DeepSeek V4 Flash 0731", + envValue: plan.model.servedName, + downloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + maxModelLen: 1_048_576, + revision: plan.model.revision, + servedModelId: plan.model.servedName, + modelArgs: [], + gated: false, + platforms: ["spark"], + installFastSafetensors: false, + }; +} + +function selectionIntent( + capability: DualSparkDetectedManagedServingCapability, + env: NodeJS.ProcessEnv, +) { + const configuredPreset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); + const configuredModel = String(env.NEMOCLAW_VLLM_MODEL ?? "").trim(); + const extraArguments = String(env[VLLM_EXTRA_ARGS_ENV] ?? "").trim(); + return { + ...(configuredPreset || capability.selectionIntent === "explicit" + ? { preset: configuredPreset || DUAL_SPARK_PRESET_ID } + : {}), + ...(configuredModel ? { vllmModel: configuredModel } : {}), + ...(extraArguments ? { vllmExtraArguments: [extraArguments] } : {}), + }; +} + +function automaticIntentDefersToLegacy(env: NodeJS.ProcessEnv): boolean { + const pairIntent = + String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim() || + String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); + if (pairIntent) return false; + return Boolean( + String(env.NEMOCLAW_VLLM_MODEL ?? "").trim() || String(env[VLLM_EXTRA_ARGS_ENV] ?? "").trim(), + ); +} + +function printSummary( + capability: DualSparkDetectedManagedServingCapability, + plan: DualSparkVllmPlan, + deps: DualSparkInstallerDeps, +): void { + const rails = capability.topology.output.rails + .map( + ({ head, worker }) => + `${head.address}/${String(head.prefixLength)} to ${worker.address}/${String(worker.prefixLength)}`, + ) + .join(", "); + deps.log(); + deps.log(" vLLM (two DGX Sparks, experimental):"); + deps.log(` Serving profile: ${plan.presetId}`); + deps.log(` Recipe: ${plan.recipeId}`); + deps.log(` Image: ${plan.roles.head.image}`); + deps.log(` Model: ${plan.model.id}@${plan.model.revision}`); + deps.log(` Served model: ${plan.model.servedName}`); + deps.log(` Topology: ${capability.local.hostname} + ${capability.peer.hostname}`); + deps.log(` Direct rails: ${rails}`); + deps.log( + ` RoCEv2 GIDs: ${capability.topology.output.rails + .map(({ head, worker }) => `${String(head.roceGid.index)}/${String(worker.roceGid.index)}`) + .join(", ")}`, + ); + deps.log( + ` Model caches: ${capability.local.storage.huggingFace.cacheRoot}, ${capability.peer.storage.huggingFace.cacheRoot}`, + ); + deps.log(" Launch order: worker first, then head"); + deps.log(" Restart policy: none; a stopped pair requires explicit cleanup"); + deps.log(" Experimental: physical two-node end-to-end validation is pending"); +} + +function resolutionFailure( + resolution: Exclude, { outcome: "selected" }>, + deps: DualSparkInstallerDeps, +): DualSparkInstallerResult { + deps.error(` Two-Spark managed vLLM setup unavailable: ${resolution.message}`); + return { kind: "handled", result: { ok: false } }; +} + +function receiptInput( + capability: DualSparkConfirmedManagedServingCapability, + plan: DualSparkVllmPlan, + started: Extract, +): PersistDualSparkVllmRuntimeReceiptInput { + return { + plan, + peerSshBinding: capability.peerSshBinding, + localCacheRoot: capability.local.storage.huggingFace.cacheRoot, + peerCacheRoot: capability.peer.storage.huggingFace.cacheRoot, + apiKeyFingerprint: started.apiKeyFingerprint, + headContainerId: started.headContainerId, + workerContainerId: started.workerContainerId, + }; +} + +/** Select and run the automatic two-Spark profile without changing the legacy Spark path. */ +export async function tryInstallDualSparkManagedVllm( + options: DualSparkInstallerOptions, + effects: DualSparkInstallerEffects, + overrides: Partial = {}, +): Promise { + if (options.platform !== "spark") return { kind: "not-selected" }; + const env = options.env ?? process.env; + const deferToLegacy = automaticIntentDefersToLegacy(env); + + const deps = { ...DEFAULT_DEPS, ...overrides }; + const configuredPreset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); + if (configuredPreset && configuredPreset !== DUAL_SPARK_PRESET_ID) { + deps.error( + ` Managed vLLM setup stopped: ${NEMOCLAW_SERVING_PRESET_ENV} selects unsupported profile ${configuredPreset}.`, + ); + return { kind: "handled", result: { ok: false } }; + } + + try { + deps.assertNoRuntimeReceipts(); + } catch (error) { + deps.error(` Managed vLLM setup stopped: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } + + const detected = deps.probeCapability({ env }); + if (detected.kind === "not-selected" && detected.code === "no-match") { + return { kind: "not-selected" }; + } + if (detected.kind !== "ready") { + deps.error(` Two-Spark managed vLLM setup stopped: ${detected.reason}`); + return { kind: "handled", result: { ok: false } }; + } + + let confirmedBinding: DualSparkConfirmedManagedServingCapability | null = null; + let retainBinding = false; + try { + // Explicit legacy model/argument intent keeps the single-Spark path, but + // only after read-only discovery has proved that doing so will not overlap + // a related distributed runtime or ambiguous binding. + if (deferToLegacy) return { kind: "not-selected" }; + + const previewResolution = deps.resolveSelection({ + readinessReports: detected.readiness, + topologyQualifications: [detected.topology], + intent: selectionIntent(detected, env), + }); + if (previewResolution.outcome !== "selected") { + return resolutionFailure(previewResolution, deps); + } + + let previewPlan: DualSparkVllmPlan; + try { + previewPlan = deps.materializePlan(previewResolution); + } catch (error) { + deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } + printSummary(detected, previewPlan, deps); + effects.printDownloadAuthentication(options.nonInteractive); + deps.log(); + + const proceed = + options.nonInteractive || isAffirmativeAnswer(await options.promptFn(" Continue? [y/N]: ")); + if (!proceed) return { kind: "handled", result: { ok: false } }; + + try { + deps.assertNoRuntimeReceipts(); + } catch (error) { + deps.error(` Managed vLLM setup stopped: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } + + const confirmation = deps.confirmCapability(detected, { env }); + if (confirmation.kind !== "ready") { + deps.error(` Two-Spark managed vLLM setup stopped: ${confirmation.reason}`); + return { kind: "handled", result: { ok: false } }; + } + confirmedBinding = confirmation; + + const resolution = deps.resolveSelection({ + readinessReports: confirmation.readiness, + topologyQualifications: [confirmation.topology], + intent: selectionIntent(confirmation, env), + }); + if (resolution.outcome !== "selected") return resolutionFailure(resolution, deps); + + let plan: DualSparkVllmPlan; + try { + plan = deps.materializePlan(resolution); + } catch (error) { + deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } + if ( + plan.presetId !== previewPlan.presetId || + plan.recipeId !== previewPlan.recipeId || + plan.model.id !== previewPlan.model.id || + plan.model.revision !== previewPlan.model.revision || + plan.model.servedName !== previewPlan.model.servedName || + plan.roles.head.image !== previewPlan.roles.head.image + ) { + deps.error(" Two-Spark managed vLLM setup stopped: the presented serving plan changed."); + return { kind: "handled", result: { ok: false } }; + } + + const profile = managedProfile(plan); + const model = managedModel(plan); + options.beforeInstall?.(plan.model.servedName); + + const prerequisites = effects.prerequisites(); + if (!prerequisites.ok) { + deps.error(` vLLM install failed: ${prerequisites.reason ?? "prerequisites unavailable"}`); + return { kind: "handled", result: { ok: false } }; + } + + let apiKey: string; + try { + apiKey = deps.ensureApiKey(); + } catch (error) { + deps.error(` vLLM install failed: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } + + const hosts = { + head: confirmation.local, + worker: confirmation.peer, + } as const; + const stageNode: DualSparkExecutorStageNode = async (_request, target) => { + const host = hosts[target.role]; + deps.log(` ==> Staging pinned vLLM image and model on ${host.hostname}`); + const pull = await effects.pullImage(profile, { ...target.dockerEnv }); + if (!pull.ok) return pull; + return await effects.downloadModel( + profile, + model, + { ...target.dockerEnv }, + { + hostCacheDir: target.modelCacheRoot, + userIdentity: `${String(host.uid)}:${String(host.gid)}`, + }, + ); + }; + const executorOptions: CreateDualSparkVllmExecutorOptions = { + plan, + peerSshBinding: confirmation.peerSshBinding, + localCacheRoot: confirmation.local.storage.huggingFace.cacheRoot, + peerCacheRoot: confirmation.peer.storage.huggingFace.cacheRoot, + stageNode, + }; + const executor = deps.createExecutor(executorOptions); + retainBinding = true; + const started = await deps.start(plan, apiKey, executor); + if (!started.ok) { + retainBinding = started.rollbackErrors.length > 0; + deps.error(` vLLM install failed: ${started.reason}`); + for (const warning of started.rollbackErrors) + deps.warn(` vLLM rollback warning: ${warning}`); + return { kind: "handled", result: { ok: false } }; + } + + try { + deps.persistReceipt(receiptInput(confirmation, plan, started)); + retainBinding = false; + } catch (error) { + if (!started.reusedExisting) { + const cleanup = await deps.cleanup(plan, apiKey, executor); + const expected = new Set([started.headContainerId, started.workerContainerId]); + if ( + cleanup.ok && + cleanup.removedContainerIds.length === expected.size && + new Set(cleanup.removedContainerIds).size === expected.size && + cleanup.removedContainerIds.every((id) => expected.has(id)) + ) { + retainBinding = false; + } else { + deps.warn( + ` vLLM rollback warning: ${cleanup.ok ? "exact pair cleanup was incomplete" : cleanup.reason}`, + ); + } + } + deps.error( + ` vLLM install failed: could not persist managed two-Spark cleanup ownership: ${(error as Error).message}`, + ); + return { kind: "handled", result: { ok: false } }; + } + + deps.log(` ✓ vLLM ready across two DGX Sparks at ${started.baseUrl}`); + return { kind: "handled", result: { ok: true } }; + } catch (error) { + deps.error(` Two-Spark managed vLLM setup failed closed: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } finally { + if (confirmedBinding && retainBinding) { + deps.warn( + ` vLLM rollback warning: retained two-Spark SSH ownership state at ${confirmedBinding.peerSshBindingStatePath} because exact container rollback is incomplete. Resolve the related runtime state before retrying setup or uninstall.`, + ); + } else if (confirmedBinding) { + try { + deps.clearBinding(confirmedBinding.peerSshBindingStatePath); + } catch (error) { + deps.warn( + ` vLLM cleanup warning: temporary two-Spark SSH state could not be retired: ${(error as Error).message}`, + ); + } + } + } +} diff --git a/src/lib/inference/serving/dual-spark-lifecycle.test.ts b/src/lib/inference/serving/dual-spark-lifecycle.test.ts new file mode 100644 index 00000000000..01607f24316 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-lifecycle.test.ts @@ -0,0 +1,458 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { fixtureDualSparkPlan } from "./dual-spark-fixture.test-support.js"; +import { + classifyDualSparkExistingState, + cleanupDualSparkManagedVllm, + type DualSparkContainerStartRequest, + type DualSparkNodeSnapshot, + type DualSparkObservedContainer, + type DualSparkVllmLifecycleDeps, + dualSparkVllmApiKeyFingerprint, + startAutomaticDualSparkVllm, +} from "./dual-spark-lifecycle.js"; +import { + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_MANAGED_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + type DualSparkVllmPlan, + type DualSparkVllmRole, + type DualSparkVllmRolePlan, +} from "./dual-spark-materialize.js"; + +const API_KEY = "a".repeat(64); +const TRANSACTION_ID = "b".repeat(32); +const HEAD_ID = "1".repeat(64); +const WORKER_ID = "2".repeat(64); + +type StoppedForeignContainerFixture = { + readonly signal: string; + readonly name: string; + readonly image: string; + readonly labels: Readonly>; +}; + +const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixture[] = [ + { + signal: "name", + name: "foreign-vllm-server", + image: "example.invalid/inference:latest", + labels: {}, + }, + { + signal: "image", + name: "foreign-inference", + image: "vllm/vllm-openai:latest", + labels: {}, + }, + { + signal: "managed label", + name: "foreign-inference", + image: "example.invalid/inference:latest", + labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + }, +]; + +type Harness = ReturnType; + +function managedContainer( + plan: DualSparkVllmPlan, + role: DualSparkVllmRole, + overrides: Partial = {}, +): DualSparkObservedContainer { + const rolePlan = plan.roles[role]; + return { + id: role === "head" ? HEAD_ID : WORKER_ID, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + healthy: true, + labels: { + ...rolePlan.baseLabels, + [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: dualSparkVllmApiKeyFingerprint(API_KEY), + [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + }, + ...overrides, + }; +} + +function createHarness(plan: DualSparkVllmPlan) { + const events: string[] = []; + const snapshots: Record = { + head: { containers: [], listeningPorts: [] }, + worker: { containers: [], listeningPorts: [] }, + }; + const inspectNode = vi.fn(async (rolePlan: DualSparkVllmRolePlan) => { + events.push(`inspect:${rolePlan.role}`); + return snapshots[rolePlan.role]; + }); + const stageNode = vi.fn(async ({ rolePlan }: { rolePlan: DualSparkVllmRolePlan }) => { + events.push(`stage:${rolePlan.role}`); + return { ok: true }; + }); + const startContainer = vi.fn(async (request: DualSparkContainerStartRequest) => { + const { rolePlan, labels } = request; + events.push(`start:${rolePlan.role}`); + const id = rolePlan.role === "head" ? HEAD_ID : WORKER_ID; + snapshots[rolePlan.role] = { + ...snapshots[rolePlan.role], + containers: [ + { + id, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + healthy: true, + labels, + }, + ], + }; + return { ok: true, containerId: id }; + }); + const waitForContainerReady = vi.fn(async (request) => { + events.push(`wait:${request.rolePlan.role}`); + return true; + }); + const waitForWorkerDistributedReady = vi.fn(async (request) => { + events.push(`distributed:${request.rolePlan.role}`); + return true; + }); + const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + events.push(`remove:${rolePlan.role}:${id}`); + snapshots[rolePlan.role] = { + ...snapshots[rolePlan.role], + containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), + }; + return { ok: true }; + }); + const probeModels = vi.fn(async () => { + events.push("probe:models"); + return true; + }); + const probeChat = vi.fn(async () => { + events.push("probe:chat"); + return true; + }); + const deps: DualSparkVllmLifecycleDeps = { + inspectNode, + stageNode, + startContainer, + waitForContainerReady, + waitForWorkerDistributedReady, + removeContainer, + probeModels, + probeChat, + createTransactionId: () => TRANSACTION_ID, + withLifecycleLock: async (_plan, operation) => await operation(), + }; + return { + deps, + events, + snapshots, + inspectNode, + stageNode, + startContainer, + removeContainer, + probeModels, + probeChat, + }; +} + +describe("automatic dual-DGX-Spark vLLM lifecycle", () => { + let plan: DualSparkVllmPlan; + let harness: Harness; + + beforeEach(() => { + plan = fixtureDualSparkPlan(); + harness = createHarness(plan); + }); + + it("inspects both nodes before staging either node", async () => { + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result.ok).toBe(true); + const firstStage = harness.events.findIndex((event) => event.startsWith("stage:")); + expect(harness.events.slice(0, firstStage)).toEqual( + expect.arrayContaining(["inspect:head", "inspect:worker"]), + ); + }); + + it("preserves singleton, Station, and related external setups", async () => { + harness.snapshots.head = { + containers: [ + { + id: "9".repeat(64), + name: "nemoclaw-vllm", + image: "vllm/vllm-openai:latest", + running: false, + healthy: false, + labels: { "com.nvidia.nemoclaw.managed-vllm": "true" }, + }, + ], + listeningPorts: [], + }; + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "conflict" }); + expect(harness.stageNode).not.toHaveBeenCalled(); + expect(harness.startContainer).not.toHaveBeenCalled(); + expect(harness.removeContainer).not.toHaveBeenCalled(); + }); + + it.each( + STOPPED_FOREIGN_CONTAINER_FIXTURES, + )("preserves a stopped foreign vLLM setup identified by $signal", async (container) => { + harness.snapshots.head = { + containers: [ + { + id: "9".repeat(64), + name: container.name, + image: container.image, + running: false, + healthy: false, + labels: container.labels, + }, + ], + listeningPorts: [], + }; + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "conflict" }); + expect(harness.stageNode).not.toHaveBeenCalled(); + expect(harness.startContainer).not.toHaveBeenCalled(); + expect(harness.removeContainer).not.toHaveBeenCalled(); + }); + + it("does not classify an arbitrary stopped container as a managed vLLM setup", () => { + const snapshots = { + head: { + containers: [ + { + id: "9".repeat(64), + name: "unrelated-service", + image: "example.invalid/worker:latest", + running: false, + healthy: false, + labels: { "example.foreign": "true" }, + }, + ], + listeningPorts: [], + }, + worker: { containers: [], listeningPorts: [] }, + }; + + expect( + classifyDualSparkExistingState(plan, dualSparkVllmApiKeyFingerprint(API_KEY), snapshots), + ).toEqual({ outcome: "clear" }); + }); + + it("reuses only one exact healthy pair with the same transaction", async () => { + harness.snapshots.head = { + containers: [managedContainer(plan, "head")], + listeningPorts: [8000], + }; + harness.snapshots.worker = { + containers: [managedContainer(plan, "worker")], + listeningPorts: [25000], + }; + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ + ok: true, + reusedExisting: true, + headContainerId: HEAD_ID, + workerContainerId: WORKER_ID, + }); + expect(harness.probeModels).toHaveBeenCalledOnce(); + expect(harness.probeChat).toHaveBeenCalledOnce(); + expect(harness.stageNode).not.toHaveBeenCalled(); + expect(harness.startContainer).not.toHaveBeenCalled(); + }); + + it("does not implicitly repair a stopped or partial managed deployment", async () => { + harness.snapshots.head = { + containers: [managedContainer(plan, "head", { running: false, healthy: false })], + listeningPorts: [], + }; + harness.snapshots.worker = { + containers: [managedContainer(plan, "worker")], + listeningPorts: [], + }; + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "conflict" }); + expect(harness.startContainer).not.toHaveBeenCalled(); + expect(harness.removeContainer).not.toHaveBeenCalled(); + }); + + it("starts and prepares rank 1 before rank 0 without exposing its API key", async () => { + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result.ok).toBe(true); + expect(harness.events.indexOf("start:worker")).toBeLessThan( + harness.events.indexOf("distributed:worker"), + ); + expect(harness.events.indexOf("distributed:worker")).toBeLessThan( + harness.events.indexOf("start:head"), + ); + const workerRequest = harness.startContainer.mock.calls[0]![0]; + const headRequest = harness.startContainer.mock.calls[1]![0]; + expect(workerRequest).not.toHaveProperty("bearerApiKey"); + expect(headRequest.bearerApiKey).toBe(API_KEY); + expect(workerRequest.preparation.phase).toBe("container-before-exec"); + expect(headRequest.preparation.phase).toBe("container-before-exec"); + expect(JSON.stringify(workerRequest.labels)).not.toContain(API_KEY); + expect(JSON.stringify(headRequest.labels)).not.toContain(API_KEY); + }); + + it("retains SSH ownership when a failed worker create leaves runtime state", async () => { + harness.startContainer.mockImplementation(async ({ rolePlan, labels }) => { + harness.snapshots.worker = { + containers: [ + { + id: WORKER_ID, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + healthy: true, + labels, + }, + ], + listeningPorts: [], + }; + throw new Error("Docker create outcome was ambiguous"); + }); + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "start-failed" }); + if (result.ok) throw new Error("expected lifecycle failure"); + expect(result.rollbackErrors).toContain( + "dual-Spark post-failure runtime state could not be proven clear; SSH ownership state was retained", + ); + expect(harness.removeContainer).not.toHaveBeenCalled(); + }); + + it("does not retain SSH ownership when a failed create is proven mutation-free", async () => { + harness.startContainer.mockImplementation(async () => { + throw new Error("Docker create failed before mutation"); + }); + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ + ok: false, + code: "start-failed", + rollbackErrors: [], + }); + }); + + it("rolls back only exact transaction-created IDs after API failure", async () => { + harness.probeChat.mockImplementation(async () => { + harness.events.push("probe:chat"); + return false; + }); + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "health-failed", rollbackErrors: [] }); + expect(harness.removeContainer.mock.calls.map((call) => call[1])).toEqual([HEAD_ID, WORKER_ID]); + expect(harness.events).toContain("probe:models"); + expect(harness.events).toContain("probe:chat"); + }); + + it("leaves a container untouched when transaction ownership changes before rollback", async () => { + harness.probeChat.mockImplementation(async () => { + const worker = harness.snapshots.worker.containers[0]!; + harness.snapshots.worker = { + ...harness.snapshots.worker, + containers: [ + { + ...worker, + labels: { + ...worker.labels, + [DUAL_SPARK_TRANSACTION_LABEL]: "c".repeat(32), + }, + }, + ], + }; + return false; + }); + + const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + + expect(result).toMatchObject({ ok: false, code: "health-failed" }); + if (result.ok) throw new Error("expected lifecycle failure"); + expect(result.rollbackErrors).toContain( + "worker rollback ownership changed; container was left untouched", + ); + expect(harness.removeContainer.mock.calls.map((call) => call[1])).toEqual([HEAD_ID]); + expect(harness.snapshots.worker.containers).toHaveLength(1); + }); + + it("classifies port conflicts on either node as nonselectable", () => { + expect( + classifyDualSparkExistingState(plan, dualSparkVllmApiKeyFingerprint(API_KEY), { + head: { containers: [], listeningPorts: [] }, + worker: { containers: [], listeningPorts: [25000] }, + }), + ).toEqual({ outcome: "conflict", reason: "worker port 25000 is already in use" }); + }); + + it("cleans up only a complete exact pair and retains all cache state", async () => { + harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [] }; + harness.snapshots.worker = { + containers: [managedContainer(plan, "worker")], + listeningPorts: [], + }; + + const result = await cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps); + + expect(result).toEqual({ ok: true, removedContainerIds: [HEAD_ID, WORKER_ID] }); + expect(harness.stageNode).not.toHaveBeenCalled(); + }); + + it("retries cleanup after one receipt-owned container was already removed", async () => { + harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [] }; + harness.snapshots.worker = { + containers: [managedContainer(plan, "worker")], + listeningPorts: [], + }; + let workerAttempts = 0; + harness.removeContainer.mockImplementation(async (rolePlan, id) => { + if (rolePlan.role === "worker" && workerAttempts++ === 0) { + return { ok: false, reason: "worker daemon unavailable" }; + } + harness.snapshots[rolePlan.role] = { + ...harness.snapshots[rolePlan.role], + containers: harness.snapshots[rolePlan.role].containers.filter( + (container) => container.id !== id, + ), + }; + return { ok: true }; + }); + const ownership = { headContainerId: HEAD_ID, workerContainerId: WORKER_ID }; + + await expect( + cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps, ownership), + ).resolves.toEqual({ + ok: false, + reason: "worker daemon unavailable", + removedContainerIds: [HEAD_ID], + }); + await expect( + cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps, ownership), + ).resolves.toEqual({ + ok: true, + removedContainerIds: [WORKER_ID], + alreadyAbsentContainerIds: [HEAD_ID], + }); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-lifecycle.ts b/src/lib/inference/serving/dual-spark-lifecycle.ts new file mode 100644 index 00000000000..4ca6a3c606a --- /dev/null +++ b/src/lib/inference/serving/dual-spark-lifecycle.ts @@ -0,0 +1,851 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHmac } from "node:crypto"; + +import { + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_MANAGED_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + DUAL_SPARK_VLLM_API_PORT, + DUAL_SPARK_VLLM_IMAGE, + DUAL_SPARK_VLLM_MASTER_PORT, + DUAL_SPARK_VLLM_PROJECT_ID, + type DualSparkVllmPlan, + type DualSparkVllmRolePlan, +} from "./dual-spark-materialize.js"; + +const API_KEY_PATTERN = /^[a-f0-9]{64}$/; +const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/; +const TRANSACTION_ID_PATTERN = /^[a-f0-9]{32}$/; +const FINGERPRINT_CONTEXT = "nemoclaw-dual-dgx-spark-vllm-api-key\0"; +const STATION_CONTAINER_NAMES = new Set(["nemoclaw-vllm", "nemoclaw-vllm-worker"]); +const STATION_LABEL_PREFIX = "com.nvidia.nemoclaw.vllm-"; +const COMPOSE_PROJECT_LABEL = "com.docker.compose.project"; +const COMPOSE_SERVICE_LABEL = "com.docker.compose.service"; +const VLLM_TOKEN_PATTERN = /(?:^|[./:_-])vllm(?:$|[./:@_-])/i; + +export interface DualSparkObservedContainer { + readonly id: string; + readonly name: string; + readonly image: string; + readonly running: boolean; + /** True only after the executor's bounded role-specific readiness check. */ + readonly healthy: boolean; + readonly labels: Readonly>; +} + +export interface DualSparkNodeSnapshot { + /** All containers visible to the node daemon, including stopped containers. */ + readonly containers: readonly DualSparkObservedContainer[]; + /** Host-network listeners. The executor must inspect both requested ports. */ + readonly listeningPorts: readonly number[]; +} + +export type DualSparkExistingState = + | { readonly outcome: "clear" } + | { + readonly outcome: "reuse"; + readonly headContainerId: string; + readonly workerContainerId: string; + readonly transactionId: string; + } + | { readonly outcome: "conflict"; readonly reason: string } + | { readonly outcome: "unknown"; readonly reason: string }; + +export interface DualSparkStageRequest { + readonly rolePlan: DualSparkVllmRolePlan; + /** Verify or fetch only the pinned model snapshot and immutable image. */ + readonly preparation: DualSparkVllmRolePlan["preparation"]; +} + +export interface DualSparkContainerStartRequest { + readonly rolePlan: DualSparkVllmRolePlan; + readonly labels: Readonly>; + /** + * The executor performs this code-owned preparation inside the newly + * created container, then directly execs the role command. Copy/replace + * operations must match exactly or creation fails before vLLM starts. + */ + readonly preparation: DualSparkVllmRolePlan["preparation"]; + /** Present only for the head. The executor must not persist it in labels or the plan. */ + readonly bearerApiKey?: string; +} + +export interface DualSparkContainerStartResult { + readonly ok: boolean; + readonly containerId?: string; + readonly reason?: string; +} + +export interface DualSparkContainerWaitRequest { + readonly rolePlan: DualSparkVllmRolePlan; + readonly containerId: string; + readonly expectedLabels: Readonly>; + readonly timeoutMs: number; +} + +export interface DualSparkApiProbeRequest { + readonly baseUrl: string; + readonly apiKey: string; + readonly expectedModel: string; + readonly timeoutMs: number; +} + +/** + * Production integration supplies one executor that resolves the opaque SSH + * binding in each worker role plan and performs Docker operations using argv, + * never a caller-built command string. + */ +export interface DualSparkVllmLifecycleDeps { + inspectNode(rolePlan: DualSparkVllmRolePlan): Promise; + stageNode(request: DualSparkStageRequest): Promise<{ ok: boolean; reason?: string }>; + startContainer(request: DualSparkContainerStartRequest): Promise; + waitForContainerReady(request: DualSparkContainerWaitRequest): Promise; + /** Prove the rank-1 process is alive and waiting at the distributed rendezvous. */ + waitForWorkerDistributedReady(request: DualSparkContainerWaitRequest): Promise; + removeContainer( + rolePlan: DualSparkVllmRolePlan, + exactContainerId: string, + ): Promise<{ ok: boolean; reason?: string }>; + probeModels(request: DualSparkApiProbeRequest): Promise; + probeChat(request: DualSparkApiProbeRequest): Promise; + createTransactionId(): string; + withLifecycleLock(plan: DualSparkVllmPlan, operation: () => Promise): Promise; +} + +export interface DualSparkRuntimeInspection { + readonly state: DualSparkExistingState; + readonly snapshots?: { + readonly head: DualSparkNodeSnapshot; + readonly worker: DualSparkNodeSnapshot; + }; +} + +export type CleanupDualSparkVllmResult = + | { + readonly ok: true; + readonly removedContainerIds: readonly string[]; + readonly alreadyAbsentContainerIds?: readonly string[]; + } + | { + readonly ok: false; + readonly reason: string; + readonly removedContainerIds: readonly string[]; + }; + +export interface DualSparkCleanupOwnership { + readonly headContainerId: string; + readonly workerContainerId: string; +} + +export type StartDualSparkVllmResult = + | { + readonly ok: true; + readonly reusedExisting: boolean; + readonly baseUrl: string; + readonly headContainerId: string; + readonly workerContainerId: string; + readonly apiKeyFingerprint: string; + } + | { + readonly ok: false; + readonly code: "conflict" | "unknown" | "staging-failed" | "start-failed" | "health-failed"; + readonly reason: string; + readonly rollbackErrors: readonly string[]; + }; + +interface RoleObservation { + rolePlan: DualSparkVllmRolePlan; + container: DualSparkObservedContainer; + expectedLabels: Readonly>; +} + +interface CreatedContainer { + rolePlan: DualSparkVllmRolePlan; + containerId: string; + expectedLabels: Readonly>; +} + +function labelsMatch( + actual: Readonly>, + expected: Readonly>, +): boolean { + return Object.entries(expected).every(([key, value]) => actual[key] === value); +} + +function exactRoleObservation( + snapshot: DualSparkNodeSnapshot, + rolePlan: DualSparkVllmRolePlan, + apiKeyFingerprint: string, +): RoleObservation | null { + const matches = snapshot.containers.filter(({ name }) => name === rolePlan.containerName); + if (matches.length !== 1) return null; + const container = matches[0]!; + const transactionId = container.labels[DUAL_SPARK_TRANSACTION_LABEL] ?? ""; + const expectedLabels = { + ...rolePlan.baseLabels, + [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, + [DUAL_SPARK_TRANSACTION_LABEL]: transactionId, + }; + if ( + !CONTAINER_ID_PATTERN.test(container.id) || + !TRANSACTION_ID_PATTERN.test(transactionId) || + container.image !== rolePlan.image || + !labelsMatch(container.labels, expectedLabels) + ) { + return null; + } + return { rolePlan, container, expectedLabels }; +} + +/** Recognize only containers that declare or visibly identify a vLLM runtime. */ +export function isRelatedManagedVllmContainer(container: DualSparkObservedContainer): boolean { + if (STATION_CONTAINER_NAMES.has(container.name)) return true; + if (VLLM_TOKEN_PATTERN.test(container.name) || VLLM_TOKEN_PATTERN.test(container.image)) { + return true; + } + if (Object.hasOwn(container.labels, DUAL_SPARK_MANAGED_LABEL)) return true; + if (container.labels[COMPOSE_PROJECT_LABEL] === DUAL_SPARK_VLLM_PROJECT_ID) return true; + if (container.labels[COMPOSE_SERVICE_LABEL] === "vllm-dspark") return true; + return Object.keys(container.labels).some((key) => key.startsWith(STATION_LABEL_PREFIX)); +} + +function invalidSnapshotReason(snapshot: DualSparkNodeSnapshot, node: string): string | null { + if ( + snapshot.listeningPorts.some((port) => !Number.isInteger(port) || port < 1 || port > 65_535) + ) { + return `${node} listener inspection is malformed`; + } + const ids = snapshot.containers.map(({ id }) => id); + if (ids.some((id) => !CONTAINER_ID_PATTERN.test(id)) || new Set(ids).size !== ids.length) { + return `${node} container inspection is malformed or ambiguous`; + } + return null; +} + +/** Pure, fail-closed classification shared by discovery and lifecycle preflight. */ +export function classifyDualSparkExistingState( + plan: DualSparkVllmPlan, + apiKeyFingerprint: string, + snapshots: { + readonly head: DualSparkNodeSnapshot; + readonly worker: DualSparkNodeSnapshot; + }, +): DualSparkExistingState { + if (!/^[a-f0-9]{64}$/.test(apiKeyFingerprint)) { + return { outcome: "unknown", reason: "dual-Spark API key fingerprint is invalid" }; + } + for (const [node, snapshot] of [ + ["head", snapshots.head], + ["worker", snapshots.worker], + ] as const) { + const invalid = invalidSnapshotReason(snapshot, node); + if (invalid) return { outcome: "unknown", reason: invalid }; + } + + const head = exactRoleObservation(snapshots.head, plan.roles.head, apiKeyFingerprint); + const worker = exactRoleObservation(snapshots.worker, plan.roles.worker, apiKeyFingerprint); + const allContainers = [...snapshots.head.containers, ...snapshots.worker.containers]; + const exactIds = new Set([head?.container.id, worker?.container.id].filter(Boolean)); + const unexpectedRelated = allContainers.find( + (container) => isRelatedManagedVllmContainer(container) && !exactIds.has(container.id), + ); + if (unexpectedRelated) { + return { + outcome: "conflict", + reason: `existing related container ${unexpectedRelated.name} is not the exact managed pair`, + }; + } + + if (head || worker) { + if (!head || !worker) { + return { outcome: "conflict", reason: "managed dual-Spark deployment is incomplete" }; + } + const headTransaction = head.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; + const workerTransaction = worker.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; + if (headTransaction !== workerTransaction) { + return { outcome: "conflict", reason: "managed dual-Spark transaction labels do not match" }; + } + if ( + !head.container.running || + !head.container.healthy || + !worker.container.running || + !worker.container.healthy + ) { + return { + outcome: "conflict", + reason: "managed dual-Spark deployment is stopped, incomplete, or unhealthy", + }; + } + return { + outcome: "reuse", + headContainerId: head.container.id, + workerContainerId: worker.container.id, + transactionId: headTransaction, + }; + } + + const dedicatedNameExists = allContainers.some( + ({ name }) => + name === plan.roles.head.containerName || name === plan.roles.worker.containerName, + ); + if (dedicatedNameExists) { + return { outcome: "conflict", reason: "dual-Spark container name ownership is foreign" }; + } + for (const [node, snapshot] of [ + ["head", snapshots.head], + ["worker", snapshots.worker], + ] as const) { + const occupied = snapshot.listeningPorts.find( + (port) => port === DUAL_SPARK_VLLM_API_PORT || port === DUAL_SPARK_VLLM_MASTER_PORT, + ); + if (occupied !== undefined) { + return { outcome: "conflict", reason: `${node} port ${String(occupied)} is already in use` }; + } + } + return { outcome: "clear" }; +} + +/** Domain-separated non-secret ownership binding for the managed endpoint key. */ +export function dualSparkVllmApiKeyFingerprint(apiKey: string): string { + if (!API_KEY_PATTERN.test(apiKey)) { + throw new Error("Dual-Spark vLLM API key must be 64 lowercase hexadecimal characters."); + } + return createHmac("sha256", Buffer.from(apiKey, "hex")).update(FINGERPRINT_CONTEXT).digest("hex"); +} + +async function inspectBoth( + plan: DualSparkVllmPlan, + deps: Pick, +): Promise<{ head: DualSparkNodeSnapshot; worker: DualSparkNodeSnapshot } | null> { + try { + const [head, worker] = await Promise.all([ + deps.inspectNode(plan.roles.head), + deps.inspectNode(plan.roles.worker), + ]); + return { head, worker }; + } catch { + return null; + } +} + +/** Inspect both daemons before any image, cache, or container mutation. */ +export async function preflightDualSparkVllm( + plan: DualSparkVllmPlan, + apiKey: string, + deps: Pick, +): Promise { + let fingerprint: string; + try { + fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + } catch (error) { + return { outcome: "unknown", reason: (error as Error).message }; + } + const snapshots = await inspectBoth(plan, deps); + return snapshots + ? classifyDualSparkExistingState(plan, fingerprint, snapshots) + : { outcome: "unknown", reason: "could not inspect both dual-Spark container daemons" }; +} + +/** Plan- and key-specific read-only inspection for installer/runtime recovery. */ +export async function inspectDualSparkManagedRuntime( + plan: DualSparkVllmPlan, + apiKey: string, + deps: Pick, +): Promise { + let fingerprint: string; + try { + fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + } catch (error) { + return { state: { outcome: "unknown", reason: (error as Error).message } }; + } + const snapshots = await inspectBoth(plan, deps); + return snapshots + ? { state: classifyDualSparkExistingState(plan, fingerprint, snapshots), snapshots } + : { + state: { + outcome: "unknown", + reason: "could not inspect both dual-Spark container daemons", + }, + }; +} + +function labelsForStart( + rolePlan: DualSparkVllmRolePlan, + apiKeyFingerprint: string, + transactionId: string, +): Readonly> { + return { + ...rolePlan.baseLabels, + [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, + [DUAL_SPARK_TRANSACTION_LABEL]: transactionId, + }; +} + +function exactCreatedContainer( + snapshot: DualSparkNodeSnapshot, + created: CreatedContainer, +): DualSparkObservedContainer | null { + const matches = snapshot.containers.filter(({ id }) => id === created.containerId); + if (matches.length !== 1) return null; + const container = matches[0]!; + return container.name === created.rolePlan.containerName && + container.image === created.rolePlan.image && + labelsMatch(container.labels, created.expectedLabels) + ? container + : null; +} + +async function rollbackCreated( + created: readonly CreatedContainer[], + deps: DualSparkVllmLifecycleDeps, +): Promise { + const errors: string[] = []; + for (const item of [...created].reverse()) { + let snapshot: DualSparkNodeSnapshot; + try { + snapshot = await deps.inspectNode(item.rolePlan); + } catch { + errors.push(`${item.rolePlan.role} rollback ownership could not be inspected`); + continue; + } + if (!exactCreatedContainer(snapshot, item)) { + errors.push(`${item.rolePlan.role} rollback ownership changed; container was left untouched`); + continue; + } + try { + const removed = await deps.removeContainer(item.rolePlan, item.containerId); + if (!removed.ok) { + errors.push(removed.reason ?? `${item.rolePlan.role} rollback removal failed`); + } + } catch { + errors.push(`${item.rolePlan.role} rollback removal failed`); + } + } + return errors; +} + +async function rollbackCreatedAndProveClear( + plan: DualSparkVllmPlan, + apiKeyFingerprint: string, + created: readonly CreatedContainer[], + deps: DualSparkVllmLifecycleDeps, +): Promise { + const rollbackErrors = await rollbackCreated(created, deps); + const snapshots = await inspectBoth(plan, deps); + if ( + snapshots && + classifyDualSparkExistingState(plan, apiKeyFingerprint, snapshots).outcome === "clear" + ) { + return []; + } + return [ + ...rollbackErrors, + "dual-Spark post-failure runtime state could not be proven clear; SSH ownership state was retained", + ]; +} + +async function startRole( + rolePlan: DualSparkVllmRolePlan, + apiKey: string, + apiKeyFingerprint: string, + transactionId: string, + timeoutMs: number, + deps: DualSparkVllmLifecycleDeps, +): Promise< + | { ok: true; created: CreatedContainer } + | { ok: false; reason: string; created?: CreatedContainer } +> { + const expectedLabels = labelsForStart(rolePlan, apiKeyFingerprint, transactionId); + let started: DualSparkContainerStartResult; + try { + started = await deps.startContainer({ + rolePlan, + labels: expectedLabels, + preparation: rolePlan.preparation, + ...(rolePlan.role === "head" ? { bearerApiKey: apiKey } : {}), + }); + } catch { + return { ok: false, reason: `${rolePlan.role} container start failed` }; + } + const containerId = started.containerId ?? ""; + if (!CONTAINER_ID_PATTERN.test(containerId)) { + return { + ok: false, + reason: started.reason ?? `${rolePlan.role} container start returned no exact container ID`, + }; + } + const created = { rolePlan, containerId, expectedLabels }; + if (!started.ok) { + return { + ok: false, + reason: started.reason ?? `${rolePlan.role} container start failed`, + created, + }; + } + let ready = false; + try { + const waitRequest = { + rolePlan, + containerId, + expectedLabels, + timeoutMs, + }; + ready = + rolePlan.role === "worker" + ? await deps.waitForWorkerDistributedReady(waitRequest) + : await deps.waitForContainerReady(waitRequest); + } catch { + ready = false; + } + if (!ready) + return { ok: false, reason: `${rolePlan.role} container did not become ready`, created }; + + let snapshot: DualSparkNodeSnapshot; + try { + snapshot = await deps.inspectNode(rolePlan); + } catch { + return { + ok: false, + reason: `${rolePlan.role} container ownership could not be revalidated`, + created, + }; + } + const observed = exactCreatedContainer(snapshot, created); + if (!observed?.running || !observed.healthy) { + return { ok: false, reason: `${rolePlan.role} container ownership or health changed`, created }; + } + return { ok: true, created }; +} + +function failure( + code: Extract["code"], + reason: string, + rollbackErrors: readonly string[] = [], +): StartDualSparkVllmResult { + return { ok: false, code, reason, rollbackErrors }; +} + +async function probeManagedApi( + plan: DualSparkVllmPlan, + apiKey: string, + deps: Pick, +): Promise { + const baseUrl = plan.roles.head.endpoint; + if (!baseUrl) return false; + const request = { + baseUrl, + apiKey, + expectedModel: plan.readiness.expectedModel, + timeoutMs: plan.readiness.timeoutMs, + }; + try { + if (!(await deps.probeModels(request))) return false; + return await deps.probeChat({ ...request, timeoutMs: Math.min(request.timeoutMs, 120_000) }); + } catch { + return false; + } +} + +async function startNewPair( + plan: DualSparkVllmPlan, + apiKey: string, + apiKeyFingerprint: string, + deps: DualSparkVllmLifecycleDeps, +): Promise { + const staged = await Promise.all( + [plan.roles.worker, plan.roles.head].map(async (rolePlan) => { + try { + return await deps.stageNode({ rolePlan, preparation: rolePlan.preparation }); + } catch { + return { ok: false, reason: `${rolePlan.role} staging failed` }; + } + }), + ); + const failedStage = staged.find((result) => !result.ok); + if (failedStage) { + return failure("staging-failed", failedStage.reason ?? "dual-Spark staging failed"); + } + + const afterStageSnapshots = await inspectBoth(plan, deps); + if (!afterStageSnapshots) { + return failure("unknown", "could not re-inspect both daemons after staging"); + } + const afterStage = classifyDualSparkExistingState(plan, apiKeyFingerprint, afterStageSnapshots); + if (afterStage.outcome !== "clear") { + return failure( + afterStage.outcome === "unknown" ? "unknown" : "conflict", + `dual-Spark ownership changed during staging: ${ + "reason" in afterStage ? afterStage.reason : afterStage.outcome + }`, + ); + } + + const transactionId = deps.createTransactionId(); + if (!TRANSACTION_ID_PATTERN.test(transactionId)) { + return failure("unknown", "dual-Spark lifecycle transaction ID is invalid"); + } + + const created: CreatedContainer[] = []; + const worker = await startRole( + plan.roles.worker, + apiKey, + apiKeyFingerprint, + transactionId, + plan.readiness.timeoutMs, + deps, + ); + if (!worker.ok) { + if (worker.created) created.push(worker.created); + return failure( + "start-failed", + worker.reason, + await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + ); + } + created.push(worker.created); + + const head = await startRole( + plan.roles.head, + apiKey, + apiKeyFingerprint, + transactionId, + plan.readiness.timeoutMs, + deps, + ); + if (!head.ok) { + if (head.created) created.push(head.created); + return failure( + "start-failed", + head.reason, + await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + ); + } + created.push(head.created); + + if (!(await probeManagedApi(plan, apiKey, deps))) { + return failure( + "health-failed", + "dual-Spark models or chat health check failed", + await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + ); + } + + const finalSnapshots = await inspectBoth(plan, deps); + const finalState = finalSnapshots + ? classifyDualSparkExistingState(plan, apiKeyFingerprint, finalSnapshots) + : null; + if ( + !finalState || + finalState.outcome !== "reuse" || + finalState.transactionId !== transactionId || + finalState.headContainerId !== head.created.containerId || + finalState.workerContainerId !== worker.created.containerId + ) { + return failure( + "health-failed", + "dual-Spark ownership changed before lifecycle commit", + await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + ); + } + return { + ok: true, + reusedExisting: false, + baseUrl: plan.roles.head.endpoint!, + headContainerId: head.created.containerId, + workerContainerId: worker.created.containerId, + apiKeyFingerprint, + }; +} + +/** + * Automatic lifecycle: exact healthy reuse or clean worker-first creation. + * Stopped, partial, mismatched, Station, singleton, and foreign deployments + * are never repaired or replaced. + */ +export async function startAutomaticDualSparkVllm( + plan: DualSparkVllmPlan, + apiKey: string, + deps: DualSparkVllmLifecycleDeps, +): Promise { + let apiKeyFingerprint: string; + try { + apiKeyFingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + } catch (error) { + return failure("unknown", (error as Error).message); + } + + try { + return await deps.withLifecycleLock(plan, async () => { + const preflight = await preflightDualSparkVllm(plan, apiKey, deps); + if (preflight.outcome === "unknown" || preflight.outcome === "conflict") { + return failure(preflight.outcome, preflight.reason); + } + if (preflight.outcome === "reuse") { + if (!(await probeManagedApi(plan, apiKey, deps))) { + return failure( + "conflict", + "existing managed dual-Spark API is unhealthy; no repair attempted", + ); + } + return { + ok: true, + reusedExisting: true, + baseUrl: plan.roles.head.endpoint!, + headContainerId: preflight.headContainerId, + workerContainerId: preflight.workerContainerId, + apiKeyFingerprint, + }; + } + return await startNewPair(plan, apiKey, apiKeyFingerprint, deps); + }); + } catch (error) { + return failure("unknown", `dual-Spark lifecycle failed: ${(error as Error).message}`); + } +} + +function exactPairForCleanup( + plan: DualSparkVllmPlan, + apiKeyFingerprint: string, + snapshots: { readonly head: DualSparkNodeSnapshot; readonly worker: DualSparkNodeSnapshot }, +): { head: RoleObservation; worker: RoleObservation } | null { + const head = exactRoleObservation(snapshots.head, plan.roles.head, apiKeyFingerprint); + const worker = exactRoleObservation(snapshots.worker, plan.roles.worker, apiKeyFingerprint); + if (!head || !worker) return null; + const transactionId = head.container.labels[DUAL_SPARK_TRANSACTION_LABEL]; + if (!transactionId || transactionId !== worker.container.labels[DUAL_SPARK_TRANSACTION_LABEL]) { + return null; + } + const exactIds = new Set([head.container.id, worker.container.id]); + const related = [...snapshots.head.containers, ...snapshots.worker.containers].find( + (container) => isRelatedManagedVllmContainer(container) && !exactIds.has(container.id), + ); + return related ? null : { head, worker }; +} + +function receiptOwnedTargetsForCleanup( + plan: DualSparkVllmPlan, + apiKeyFingerprint: string, + snapshots: { readonly head: DualSparkNodeSnapshot; readonly worker: DualSparkNodeSnapshot }, + ownership: DualSparkCleanupOwnership, +): + | { + readonly ok: true; + readonly observations: readonly RoleObservation[]; + readonly alreadyAbsentContainerIds: readonly string[]; + } + | { readonly ok: false; readonly reason: string } { + const expectedIds = [ownership.headContainerId, ownership.workerContainerId]; + if ( + expectedIds.some((id) => !CONTAINER_ID_PATTERN.test(id)) || + ownership.headContainerId === ownership.workerContainerId + ) { + return { ok: false, reason: "dual-Spark cleanup receipt identities are invalid" }; + } + + const observations: RoleObservation[] = []; + const alreadyAbsentContainerIds: string[] = []; + let transactionId: string | null = null; + for (const [role, snapshot, expectedId] of [ + ["head", snapshots.head, ownership.headContainerId], + ["worker", snapshots.worker, ownership.workerContainerId], + ] as const) { + const invalid = invalidSnapshotReason(snapshot, role); + if (invalid) return { ok: false, reason: invalid }; + const related = snapshot.containers.filter(isRelatedManagedVllmContainer); + const expected = snapshot.containers.find(({ id }) => id === expectedId); + if (!expected) { + if (related.length > 0) { + return { + ok: false, + reason: `${role} receipt-owned container is absent but related runtime state exists`, + }; + } + alreadyAbsentContainerIds.push(expectedId); + continue; + } + const observation = exactRoleObservation(snapshot, plan.roles[role], apiKeyFingerprint); + if ( + !observation || + observation.container.id !== expectedId || + related.some(({ id }) => id !== expectedId) + ) { + return { ok: false, reason: `${role} receipt-owned container identity changed` }; + } + const observedTransaction = observation.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; + if (transactionId !== null && transactionId !== observedTransaction) { + return { ok: false, reason: "dual-Spark receipt-owned transaction identity changed" }; + } + transactionId = observedTransaction; + observations.push(observation); + } + return { ok: true, observations, alreadyAbsentContainerIds }; +} + +/** Remove only a complete, plan/key/transaction-owned pair. Model caches remain. */ +export async function cleanupDualSparkManagedVllm( + plan: DualSparkVllmPlan, + apiKey: string, + deps: Pick, + ownership?: DualSparkCleanupOwnership, +): Promise { + let fingerprint: string; + try { + fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + } catch (error) { + return { ok: false, reason: (error as Error).message, removedContainerIds: [] }; + } + try { + return await deps.withLifecycleLock(plan, async () => { + const snapshots = await inspectBoth(plan, deps); + if (!snapshots) { + return { + ok: false, + reason: "could not inspect both dual-Spark container daemons", + removedContainerIds: [], + }; + } + const owned = ownership + ? receiptOwnedTargetsForCleanup(plan, fingerprint, snapshots, ownership) + : null; + if (owned && !owned.ok) { + return { ok: false, reason: owned.reason, removedContainerIds: [] }; + } + const pair = ownership ? null : exactPairForCleanup(plan, fingerprint, snapshots); + if (!ownership && !pair) { + return { + ok: false, + reason: "dual-Spark cleanup requires one complete exact owned pair", + removedContainerIds: [], + }; + } + const observations = owned?.ok ? owned.observations : [pair!.head, pair!.worker]; + const removedContainerIds: string[] = []; + for (const observation of observations) { + const removed = await deps.removeContainer(observation.rolePlan, observation.container.id); + if (!removed.ok) { + return { + ok: false, + reason: removed.reason ?? `${observation.rolePlan.role} cleanup failed`, + removedContainerIds, + }; + } + removedContainerIds.push(observation.container.id); + } + return { + ok: true, + removedContainerIds, + ...(owned?.ok && owned.alreadyAbsentContainerIds.length > 0 + ? { alreadyAbsentContainerIds: owned.alreadyAbsentContainerIds } + : {}), + }; + }); + } catch (error) { + return { + ok: false, + reason: `dual-Spark cleanup failed: ${(error as Error).message}`, + removedContainerIds: [], + }; + } +} diff --git a/src/lib/inference/serving/dual-spark-materialize.test.ts b/src/lib/inference/serving/dual-spark-materialize.test.ts new file mode 100644 index 00000000000..a18b5148a2e --- /dev/null +++ b/src/lib/inference/serving/dual-spark-materialize.test.ts @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { + DUAL_SPARK_VLLM_API_PORT, + DUAL_SPARK_VLLM_MASTER_PORT, + materializeDualSparkVllmPlan, +} from "./dual-spark-materialize.js"; +import { dualSparkTopologyOutputDigest } from "./dual-spark-topology.js"; + +describe("dual-DGX-Spark vLLM materializer", () => { + it("creates deterministic head and worker plans from the compiled recipe", () => { + const selection = fixtureDualSparkSelection(); + const plan = materializeDualSparkVllmPlan(selection); + const recipe = selection.recipe.spec; + + expect(materializeDualSparkVllmPlan(selection)).toEqual(plan); + expect(plan.model).toEqual({ + id: recipe.model.id, + revision: recipe.model.revision, + servedName: recipe.model.servedName, + }); + expect(plan.roles.head).toMatchObject({ + image: recipe.runtime.image, + runtime: { + networkMode: recipe.runtime.networkMode, + ipcMode: recipe.runtime.ipcMode, + sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, + devices: recipe.runtime.devices, + imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, + }, + preparation: { + ref: recipe.model.preparationRef, + modelId: recipe.model.id, + modelRevision: recipe.model.revision, + modelDownloadSizeBytes: recipe.model.downloadSizeBytes, + encodingPath: recipe.model.encodingPath, + }, + }); + expect(plan.readiness).toEqual({ + timeoutMs: recipe.readiness.timeoutSeconds * 1000, + expectedModel: recipe.readiness.expectedModel, + }); + expect(plan.apiPort).toBe(DUAL_SPARK_VLLM_API_PORT); + expect(plan.masterPort).toBe(DUAL_SPARK_VLLM_MASTER_PORT); + expect(plan.roles.head.containerName).toBe("nemoclaw-vllm-dspark-head"); + expect(plan.roles.worker.containerName).toBe("nemoclaw-vllm-dspark-worker"); + }); + + it("uses role-local topology values and starts rank 1 headless", () => { + const plan = materializeDualSparkVllmPlan(fixtureDualSparkSelection()); + + expect(plan.roles.head.environment).toMatchObject({ + VLLM_HOST_IP: "192.168.100.10", + NCCL_IB_HCA: "rocep1s0f0:1", + NCCL_SOCKET_IFNAME: "enp1s0f0np0", + NCCL_IB_GID_INDEX: "3", + NODE_RANK: "0", + }); + expect(plan.roles.worker.environment).toMatchObject({ + VLLM_HOST_IP: "192.168.100.11", + NCCL_IB_HCA: "rocep1s0f1:1", + NCCL_SOCKET_IFNAME: "enp1s0f1np1", + NCCL_IB_GID_INDEX: "6", + NODE_RANK: "1", + HEADLESS: "1", + }); + expect(plan.roles.head.command.arguments).toEqual( + expect.arrayContaining(["--host", "192.168.100.10"]), + ); + expect(plan.roles.worker.command.arguments).toEqual( + expect.arrayContaining(["--host", "192.168.100.11"]), + ); + expect(plan.roles.worker.command.arguments).toContain("--headless"); + expect(plan.roles.head.command.arguments).not.toContain("--headless"); + expect(plan.roles.worker.command.arguments).toEqual( + expect.arrayContaining([ + "--tensor-parallel-size", + "2", + "--pipeline-parallel-size", + "1", + "--distributed-executor-backend", + "mp", + "--nnodes", + "2", + "--node-rank", + "1", + "--master-port", + "25000", + ]), + ); + }); + + it("preserves the fixed DSpark serving profile without embedding the API key", () => { + const plan = materializeDualSparkVllmPlan(fixtureDualSparkSelection()); + const headArgs = plan.roles.head.command.arguments; + + expect(headArgs).toEqual( + expect.arrayContaining([ + "--kv-cache-dtype", + "nvfp4_ds_mla", + "--block-size", + "256", + "--max-model-len", + "1048576", + "--max-num-seqs", + "6", + "--max-num-batched-tokens", + "8192", + "--gpu-memory-utilization", + "0.8", + "--moe-backend", + "flashinfer_b12x", + "--async-scheduling", + "--enable-chunked-prefill", + "--generation-config", + "vllm", + ]), + ); + expect(headArgs.join(" ")).toContain('"num_speculative_tokens":5'); + expect(headArgs).not.toContain("--api-key"); + expect(plan.roles.worker.command.arguments).not.toContain("--api-key"); + }); + + it("rejects materializer-owned arguments added after catalog resolution", () => { + const selection = fixtureDualSparkSelection(); + const serve = selection.recipe.spec.serve as unknown as { + arguments: Array<{ name: string; value?: string | number }>; + }; + serve.arguments.push({ name: "--headless" }); + + expect(() => materializeDualSparkVllmPlan(selection)).toThrow( + /not the shipped dual-Spark profile/, + ); + }); + + it("rejects stale topology subject and output digests", () => { + const staleSubject = fixtureDualSparkSelection(); + (staleSubject.topologyQualification as { subjectDigest: string }).subjectDigest = + `sha256:${"f".repeat(64)}`; + expect(() => materializeDualSparkVllmPlan(staleSubject)).toThrow(/subject digest/); + + const staleOutput = fixtureDualSparkSelection(); + (staleOutput.topologyQualification.output.peer as { target: string }).target = + "other-worker.local"; + expect(() => materializeDualSparkVllmPlan(staleOutput)).toThrow(/output digest/); + }); + + it("rejects an inconsistent master address even with a recomputed digest", () => { + const selection = fixtureDualSparkSelection(); + const artifact = selection.topologyQualification; + (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; + (artifact as { outputDigest: string }).outputDigest = dualSparkTopologyOutputDigest( + artifact.output, + ); + + expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/master address/); + }); + + it("requires the code-owned in-container checkpoint compatibility preparation", () => { + const preparation = materializeDualSparkVllmPlan(fixtureDualSparkSelection()).roles.head + .preparation; + + expect(preparation).toMatchObject({ + ref: "deepseek-v4-flash-0731/v1", + phase: "container-before-exec", + encodingPath: "encoding/encoding_dsv4.py", + }); + expect(preparation.encodingSourcePath).toContain(preparation.modelRevision); + expect(preparation.encodingTargetPath).toContain("deepseek_v4_encoding.py"); + expect(preparation.reasoningCompatibility.replacementText).toContain( + 'reasoning_effort = "low"', + ); + }); + + it("rejects a recipe changed after catalog resolution", () => { + const mutableImage = fixtureDualSparkSelection(); + (mutableImage.recipe.spec.runtime as { image: string }).image = + "ghcr.io/anemll/dspark-vllm-gx10:0.1.1"; + expect(() => materializeDualSparkVllmPlan(mutableImage)).toThrow( + /not the shipped dual-Spark profile/, + ); + + const changedRevision = fixtureDualSparkSelection(); + (changedRevision.recipe.spec.model as { revision: string }).revision = "d".repeat(40); + expect(() => materializeDualSparkVllmPlan(changedRevision)).toThrow( + /not the shipped dual-Spark profile/, + ); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-materialize.ts b/src/lib/inference/serving/dual-spark-materialize.ts new file mode 100644 index 00000000000..612883a0fac --- /dev/null +++ b/src/lib/inference/serving/dual-spark-materialize.ts @@ -0,0 +1,422 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { + immutableManagedInferenceCopy, + managedInferenceDigest, + managedInferenceHexDigest, +} from "./catalog-integrity.js"; +import { + DUAL_SPARK_PRESET_ID, + DUAL_SPARK_RECIPE_ID, + isManagedInferenceMaterializerOwnedArgument, + type ResolvedManagedInferenceSelection, +} from "./catalog-types.js"; +import { + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + type DualSparkTopologyOutput, + type DualSparkTopologyRailEndpoint, + getDualSparkTopologyArtifactError, +} from "./dual-spark-topology.js"; + +export const DUAL_SPARK_VLLM_ADAPTER_ID = "vllm.dual-dgx-spark/v1" as const; +const SHIPPED_DUAL_SPARK_RECIPE = loadManagedInferenceCatalog().recipes[0]!.definition; +export const DUAL_SPARK_VLLM_IMAGE = SHIPPED_DUAL_SPARK_RECIPE.spec.runtime.image; +export const DUAL_SPARK_VLLM_MODEL = SHIPPED_DUAL_SPARK_RECIPE.spec.model.id; +export const DUAL_SPARK_VLLM_MODEL_REVISION = SHIPPED_DUAL_SPARK_RECIPE.spec.model.revision; +export const DUAL_SPARK_VLLM_API_PORT = 8000; +export const DUAL_SPARK_VLLM_MASTER_PORT = 25000; +export const DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME = "nemoclaw-vllm-dspark-head"; +export const DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME = "nemoclaw-vllm-dspark-worker"; +export const DUAL_SPARK_VLLM_PROJECT_ID = "nemoclaw-vllm-dspark"; + +export const DUAL_SPARK_MANAGED_LABEL = "com.nvidia.nemoclaw.managed-vllm"; +export const DUAL_SPARK_ADAPTER_LABEL = "com.nvidia.nemoclaw.serving-adapter"; +export const DUAL_SPARK_PRESET_LABEL = "com.nvidia.nemoclaw.serving-preset"; +export const DUAL_SPARK_RECIPE_LABEL = "com.nvidia.nemoclaw.serving-recipe"; +export const DUAL_SPARK_ROLE_LABEL = "com.nvidia.nemoclaw.serving-role"; +export const DUAL_SPARK_CLUSTER_LABEL = "com.nvidia.nemoclaw.serving-cluster"; +export const DUAL_SPARK_PLAN_LABEL = "com.nvidia.nemoclaw.serving-plan"; +export const DUAL_SPARK_GPU_LABEL = "com.nvidia.nemoclaw.serving-gpu"; +export const DUAL_SPARK_IMAGE_LABEL = "com.nvidia.nemoclaw.serving-image"; +export const DUAL_SPARK_MODEL_REVISION_LABEL = "com.nvidia.nemoclaw.serving-model-revision"; +export const DUAL_SPARK_API_KEY_FINGERPRINT_LABEL = + "com.nvidia.nemoclaw.serving-api-key-fingerprint"; +export const DUAL_SPARK_TRANSACTION_LABEL = "com.nvidia.nemoclaw.serving-transaction"; + +const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +export type DualSparkVllmRole = "head" | "worker"; + +export interface DualSparkVllmRolePlan { + readonly role: DualSparkVllmRole; + readonly rank: 0 | 1; + readonly nodeId: string; + readonly gpuId: string; + readonly containerName: string; + readonly execution: + | { readonly kind: "local" } + | { + readonly kind: "ssh"; + readonly expectedTarget: string; + readonly bindingHandle: string; + }; + readonly image: string; + readonly runtime: { + readonly networkMode: "host"; + readonly ipcMode: "host"; + readonly sharedMemoryBytes: number; + readonly gpuRequest: "all"; + readonly devices: readonly string[]; + readonly imageDownloadSizeBytes: number; + readonly ulimits: { + readonly memlock: -1; + readonly stack: 67_108_864; + }; + readonly modelCache: { + readonly source: "huggingface-cache"; + readonly target: "/cache/huggingface"; + }; + }; + readonly preparation: { + readonly ref: string; + /** Code-owned adapter operation executed in the new container before vLLM. */ + readonly phase: "container-before-exec"; + readonly modelId: string; + readonly modelRevision: string; + readonly modelDownloadSizeBytes: number; + readonly encodingPath: string; + readonly encodingSourcePath: string; + readonly encodingTargetPath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py"; + readonly reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py"; + readonly reasoningCompatibility: { + readonly existingText: string; + readonly replacementText: string; + }; + }; + readonly fabric: { + readonly primaryRailIndex: number; + readonly netdev: string; + readonly hcaDevice: string; + readonly hcaPort: number; + readonly address: string; + readonly roceGidIndex: number; + readonly roceGidValue: string; + }; + readonly environment: Readonly>; + readonly command: { + readonly executable: "/usr/local/bin/vllm"; + readonly arguments: readonly string[]; + }; + readonly endpoint: string | null; + readonly baseLabels: Readonly>; +} + +export interface DualSparkVllmPlan { + readonly schemaVersion: 1; + readonly adapterId: typeof DUAL_SPARK_VLLM_ADAPTER_ID; + readonly catalogDigest: string; + readonly presetId: typeof DUAL_SPARK_PRESET_ID; + readonly recipeId: typeof DUAL_SPARK_RECIPE_ID; + readonly topologyId: typeof DUAL_SPARK_TOPOLOGY_ID; + readonly topologySchemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + readonly topologySubjectDigest: string; + readonly topologyOutputDigest: string; + readonly clusterId: string; + readonly planId: string; + readonly model: { + readonly id: string; + readonly revision: string; + readonly servedName: string; + }; + readonly apiPort: typeof DUAL_SPARK_VLLM_API_PORT; + readonly masterAddress: string; + readonly masterPort: typeof DUAL_SPARK_VLLM_MASTER_PORT; + readonly readiness: { + readonly timeoutMs: number; + readonly expectedModel: string; + }; + readonly roles: { + readonly worker: DualSparkVllmRolePlan; + readonly head: DualSparkVllmRolePlan; + }; +} + +function fail(message: string): never { + throw new Error(`Cannot materialize dual-DGX-Spark vLLM: ${message}`); +} + +function commandArguments( + selection: ResolvedManagedInferenceSelection, + rank: 0 | 1, + hostAddress: string, +): string[] { + const recipe = selection.recipe.spec; + const seen = new Set(); + const staticArguments: string[] = []; + for (const argument of recipe.serve.arguments) { + if (!/^--[a-z0-9][a-z0-9-]*$/.test(argument.name)) fail("a serve argument is invalid"); + if (seen.has(argument.name)) fail(`serve argument ${argument.name} is duplicated`); + if (isManagedInferenceMaterializerOwnedArgument(argument.name)) { + fail(`serve argument ${argument.name} is owned by the materializer`); + } + seen.add(argument.name); + staticArguments.push(argument.name); + if (argument.value !== undefined) staticArguments.push(String(argument.value)); + } + + const portIndex = staticArguments.indexOf("--port"); + if (portIndex < 0 || staticArguments[portIndex + 1] !== String(DUAL_SPARK_VLLM_API_PORT)) { + fail(`the shipped recipe must bind API port ${String(DUAL_SPARK_VLLM_API_PORT)}`); + } + + return [ + "serve", + recipe.model.id, + "--served-model-name", + recipe.model.servedName, + "--host", + hostAddress, + ...staticArguments, + "--tensor-parallel-size", + String(recipe.execution.tensorParallelSize), + "--pipeline-parallel-size", + String(recipe.execution.pipelineParallelSize), + "--distributed-executor-backend", + recipe.execution.distributedExecutorBackend, + "--nnodes", + String(recipe.execution.nodeCount), + "--node-rank", + String(rank), + "--master-addr", + selection.topologyQualification.output.masterAddress, + "--master-port", + String(DUAL_SPARK_VLLM_MASTER_PORT), + ...(rank === 1 ? ["--headless"] : []), + ]; +} + +function assertShippedSelection( + selection: ResolvedManagedInferenceSelection, +): void { + const { recipe, preset, topologyQualification: topology } = selection; + const catalog = loadManagedInferenceCatalog(); + const compiledPreset = catalog.presets[0]; + const compiledRecipe = catalog.recipes[0]; + if ( + selection.catalogDigest !== catalog.catalogDigest || + !compiledPreset || + !compiledRecipe || + managedInferenceDigest(preset) !== compiledPreset.definitionDigest || + managedInferenceDigest(recipe) !== compiledRecipe.definitionDigest || + preset.metadata.id !== DUAL_SPARK_PRESET_ID || + recipe.metadata.id !== DUAL_SPARK_RECIPE_ID || + preset.spec.plan.recipeRef !== recipe.metadata.id + ) { + fail("the selected preset and recipe are not the shipped dual-Spark profile"); + } + if ( + recipe.spec.execution.materializerRef !== DUAL_SPARK_VLLM_ADAPTER_ID || + recipe.spec.execution.lifecycleRef !== DUAL_SPARK_VLLM_ADAPTER_ID || + recipe.spec.execution.nodeCount !== 2 || + recipe.spec.execution.tensorParallelSize !== 2 || + recipe.spec.execution.pipelineParallelSize !== 1 || + recipe.spec.execution.distributedExecutorBackend !== "mp" + ) { + fail("recipe execution does not match adapter v1"); + } + if ( + topology.id !== DUAL_SPARK_TOPOLOGY_ID || + topology.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION || + topology.status !== "qualified" + ) { + fail("topology artifact is not the qualified dual-Spark v1 artifact"); + } + const topologyError = getDualSparkTopologyArtifactError(topology); + if (topologyError) fail(topologyError); + if ( + !Number.isSafeInteger(recipe.spec.readiness.timeoutSeconds) || + recipe.spec.readiness.timeoutSeconds <= 0 || + recipe.spec.readiness.timeoutSeconds > 86_400 + ) { + fail("readiness timeout is invalid"); + } +} + +function endpointForRole( + output: DualSparkTopologyOutput, + role: DualSparkVllmRole, +): DualSparkTopologyRailEndpoint { + const endpoint = output.rails[0]?.[role]; + if (!endpoint || endpoint.nodeId !== output[`${role}NodeId`]) { + fail(`primary ${role} fabric endpoint does not match the role node`); + } + if (!SAFE_DEVICE_PATTERN.test(endpoint.hcaDevice) || !SAFE_DEVICE_PATTERN.test(endpoint.netdev)) { + fail(`primary ${role} fabric device identity is invalid`); + } + return endpoint; +} + +function rolePlan( + selection: ResolvedManagedInferenceSelection, + role: DualSparkVllmRole, + clusterId: string, + planId: string, +): DualSparkVllmRolePlan { + const output = selection.topologyQualification.output; + const recipe = selection.recipe.spec; + const rank = role === "head" ? 0 : 1; + const nodeId = role === "head" ? output.headNodeId : output.workerNodeId; + const node = output.nodes.find( + (candidate) => candidate.nodeId === nodeId && candidate.role === role, + ); + if (!node) fail(`${role} node is missing from the topology artifact`); + const endpoint = endpointForRole(output, role); + const baseLabels = { + [DUAL_SPARK_MANAGED_LABEL]: "true", + [DUAL_SPARK_ADAPTER_LABEL]: DUAL_SPARK_VLLM_ADAPTER_ID, + [DUAL_SPARK_PRESET_LABEL]: DUAL_SPARK_PRESET_ID, + [DUAL_SPARK_RECIPE_LABEL]: DUAL_SPARK_RECIPE_ID, + [DUAL_SPARK_ROLE_LABEL]: role, + [DUAL_SPARK_CLUSTER_LABEL]: clusterId, + [DUAL_SPARK_PLAN_LABEL]: planId, + [DUAL_SPARK_GPU_LABEL]: node.gpuId, + [DUAL_SPARK_IMAGE_LABEL]: recipe.runtime.image, + [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.model.revision, + }; + const environment = { + ...recipe.runtime.environment, + VLLM_HOST_IP: endpoint.address, + NCCL_IB_HCA: `${endpoint.hcaDevice}:${String(endpoint.hcaPort)}`, + NCCL_SOCKET_IFNAME: endpoint.netdev, + TP_SOCKET_IFNAME: endpoint.netdev, + GLOO_SOCKET_IFNAME: endpoint.netdev, + NCCL_IB_GID_INDEX: String(endpoint.roceGid.index), + MASTER_ADDR: output.masterAddress, + MASTER_PORT: String(DUAL_SPARK_VLLM_MASTER_PORT), + NODE_RANK: String(rank), + HEADLESS: role === "worker" ? "1" : "", + }; + + return { + role, + rank, + nodeId, + gpuId: node.gpuId, + containerName: + role === "head" ? DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME : DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, + execution: + role === "head" + ? { kind: "local" } + : { + kind: "ssh", + expectedTarget: output.peer.target, + bindingHandle: output.peer.sshBindingHandle, + }, + image: recipe.runtime.image, + runtime: { + networkMode: recipe.runtime.networkMode, + ipcMode: recipe.runtime.ipcMode, + sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, + gpuRequest: "all", + devices: recipe.runtime.devices, + imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, + ulimits: { memlock: -1, stack: 67_108_864 }, + modelCache: { source: "huggingface-cache", target: "/cache/huggingface" }, + }, + preparation: { + ref: recipe.model.preparationRef, + phase: "container-before-exec", + modelId: recipe.model.id, + modelRevision: recipe.model.revision, + modelDownloadSizeBytes: recipe.model.downloadSizeBytes, + encodingPath: recipe.model.encodingPath, + encodingSourcePath: `/cache/huggingface/hub/models--${recipe.model.id.replaceAll( + "/", + "--", + )}/snapshots/${recipe.model.revision}/${recipe.model.encodingPath}`, + encodingTargetPath: + "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py", + reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py", + reasoningCompatibility: { + existingText: + 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n else:\n reasoning_effort = "high"', + replacementText: + 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n elif reasoning_effort == "high":\n reasoning_effort = "high"\n else:\n reasoning_effort = "low"', + }, + }, + fabric: { + primaryRailIndex: output.rails[0].index, + netdev: endpoint.netdev, + hcaDevice: endpoint.hcaDevice, + hcaPort: endpoint.hcaPort, + address: endpoint.address, + roceGidIndex: endpoint.roceGid.index, + roceGidValue: endpoint.roceGid.value, + }, + environment, + command: { + executable: "/usr/local/bin/vllm", + arguments: commandArguments(selection, rank, endpoint.address), + }, + endpoint: + role === "head" ? `http://${output.masterAddress}:${String(DUAL_SPARK_VLLM_API_PORT)}` : null, + baseLabels, + }; +} + +/** Compile one resolved, qualified catalog selection into immutable role-local plans. */ +export function materializeDualSparkVllmPlan( + selection: ResolvedManagedInferenceSelection, +): DualSparkVllmPlan { + let snapshot: ResolvedManagedInferenceSelection; + try { + snapshot = immutableManagedInferenceCopy(selection); + } catch { + fail("the resolved selection is not immutable JSON data"); + } + assertShippedSelection(snapshot); + const output = snapshot.topologyQualification.output; + const clusterId = managedInferenceHexDigest({ + topologyId: snapshot.topologyQualification.id, + subjectDigest: snapshot.topologyQualification.subjectDigest, + outputDigest: snapshot.topologyQualification.outputDigest, + }); + const planId = managedInferenceHexDigest({ + adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + catalogDigest: snapshot.catalogDigest, + preset: snapshot.preset, + recipe: snapshot.recipe, + topology: snapshot.topologyQualification, + }); + return { + schemaVersion: 1, + adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + catalogDigest: snapshot.catalogDigest, + presetId: DUAL_SPARK_PRESET_ID, + recipeId: DUAL_SPARK_RECIPE_ID, + topologyId: DUAL_SPARK_TOPOLOGY_ID, + topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + topologySubjectDigest: snapshot.topologyQualification.subjectDigest, + topologyOutputDigest: snapshot.topologyQualification.outputDigest, + clusterId, + planId, + model: { + id: snapshot.recipe.spec.model.id, + revision: snapshot.recipe.spec.model.revision, + servedName: snapshot.recipe.spec.model.servedName, + }, + apiPort: DUAL_SPARK_VLLM_API_PORT, + masterAddress: output.masterAddress, + masterPort: DUAL_SPARK_VLLM_MASTER_PORT, + readiness: { + timeoutMs: snapshot.recipe.spec.readiness.timeoutSeconds * 1000, + expectedModel: snapshot.recipe.spec.readiness.expectedModel, + }, + roles: { + worker: rolePlan(snapshot, "worker", clusterId, planId), + head: rolePlan(snapshot, "head", clusterId, planId), + }, + }; +} diff --git a/src/lib/inference/serving/dual-spark-topology.test.ts b/src/lib/inference/serving/dual-spark-topology.test.ts new file mode 100644 index 00000000000..20257f7597c --- /dev/null +++ b/src/lib/inference/serving/dual-spark-topology.test.ts @@ -0,0 +1,404 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + type DualSparkNodeObservation, + type DualSparkPeerObservation, + type DualSparkRailObservation, + type DualSparkTopologyQualificationInput, + qualifyDualSparkTopology, +} from "./dual-spark-topology.js"; + +const EVALUATED_AT = "2026-08-02T18:00:00.000Z"; +const READINESS_OBSERVED_AT = "2026-08-02T17:59:30.000Z"; +const REQUIRED_CAPABILITIES = [ + "host.platform.supported", + "host.platform.dgx_spark", + "host.docker.available", + "host.docker.daemon_reachable", + "host.docker.runtime_supported", + "host.docker.storage_compatible", + "host.gpu.nvidia_available", + "host.gpu.container_toolkit_available", + "host.gpu.cdi_healthy", +] as const; + +function readiness(overrides: Partial = {}): SystemReadinessReport { + const base = { + schemaVersion: "1.1.0", + mutated: false, + provenance: { + nemoclawVersion: "0.1.0", + sourceRevision: "1d6948d89b46eab739728215f9a19ef40b8f6121", + observedAt: READINESS_OBSERVED_AT, + }, + observations: [], + capabilities: REQUIRED_CAPABILITIES.map((id) => ({ id, state: "present" as const })), + qualifications: [ + { + id: "host.platform.dgx_spark", + status: "qualified" as const, + capabilityIds: ["host.platform.dgx_spark"], + }, + ], + findings: [], + evidence: [], + status: "supported" as const, + exitCode: 0 as const, + } satisfies SystemReadinessReport; + return { ...base, ...overrides } as SystemReadinessReport; +} + +function rail( + node: "head" | "worker", + index: 0 | 1, + overrides: Partial = {}, +): DualSparkRailObservation { + const headAddress = `192.168.${100 + index}.10`; + const workerAddress = `192.168.${100 + index}.11`; + const isHead = node === "head"; + return { + adapter: "connectx-7", + path: "direct", + physicalPortId: isHead ? "cx7-left-head" : "cx7-left-worker", + netdev: index === 0 ? "enp1s0f0np0" : "enP2p1s0f0np0", + hcaDevice: index === 0 ? "rocep1s0f0" : "roceP2p1s0f0", + hcaPort: 1, + address: isHead ? headAddress : workerAddress, + prefixLength: 24, + peerNodeId: isHead ? "spark-worker" : "spark-head", + peerAddress: isHead ? workerAddress : headAddress, + linkState: "up", + connectivity: "reachable", + roceGid: { + state: "resolved", + index: index === 0 ? 5 : 7, + value: isHead ? `fe80::${10 + index}` : `fe80::${20 + index}`, + }, + ...overrides, + }; +} + +function localNode(): DualSparkNodeObservation { + return { + nodeId: "spark-head", + gpuIds: ["GPU-head"], + readiness: readiness(), + runtimeState: "clear", + rails: [rail("head", 1), rail("head", 0)], + }; +} + +function peerNode(index = 0): DualSparkPeerObservation { + const suffix = index === 0 ? "" : `-${index}`; + return { + nodeId: `spark-worker${suffix}`, + gpuIds: [`GPU-worker${suffix}`], + readiness: readiness(), + runtimeState: "clear", + rails: + index === 0 + ? [rail("worker", 0), rail("worker", 1)] + : [ + rail("worker", 0, { peerNodeId: "spark-head" }), + rail("worker", 1, { peerNodeId: "spark-head" }), + ], + sshBinding: { + state: "pretrusted", + fromNodeId: "spark-head", + toNodeId: `spark-worker${suffix}`, + peerTarget: `spark-worker${suffix}.local`, + handle: `ssh-binding:worker${suffix || "-0"}`, + }, + }; +} + +function qualificationInput( + peers: readonly DualSparkPeerObservation[] = [peerNode()], +): DualSparkTopologyQualificationInput { + return { + intent: "automatic", + evaluatedAt: EVALUATED_AT, + maxReadinessAgeMs: 60_000, + local: localNode(), + peers, + }; +} + +function clone(value: T): T { + return structuredClone(value); +} + +describe("dual DGX Spark topology qualification", () => { + it("returns no match when discovery finds no peer", () => { + expect(qualifyDualSparkTopology(qualificationInput([]))).toMatchObject({ + outcome: "no-match", + code: "peer-count", + }); + }); + + it("qualifies one peer as a two-node direct ConnectX-7 topology", () => { + const result = qualifyDualSparkTopology(qualificationInput()); + + expect(result.outcome).toBe("qualified"); + if (result.outcome !== "qualified") return; + expect(result.artifact).toMatchObject({ + id: DUAL_SPARK_TOPOLOGY_ID, + schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + status: "qualified", + subjectNodeIds: ["spark-head", "spark-worker"], + output: { + headNodeId: "spark-head", + workerNodeId: "spark-worker", + masterAddress: "192.168.100.10", + peer: { + target: "spark-worker.local", + sshBindingHandle: "ssh-binding:worker-0", + }, + }, + }); + expect(result.artifact.subjectDigest).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(result.artifact.outputDigest).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(result.artifact.output.nodes).toEqual([ + { nodeId: "spark-head", gpuId: "GPU-head", role: "head" }, + { nodeId: "spark-worker", gpuId: "GPU-worker", role: "worker" }, + ]); + expect(result.artifact.output.rails).toHaveLength(2); + expect(result.artifact.output.rails.map(({ head }) => head.netdev)).toEqual([ + "enp1s0f0np0", + "enP2p1s0f0np0", + ]); + expect(result.artifact.output.rails[0]).toMatchObject({ + index: 0, + head: { + hcaDevice: "rocep1s0f0", + address: "192.168.100.10", + peerAddress: "192.168.100.11", + roceGid: { index: 5, value: "fe80::10" }, + }, + worker: { + hcaDevice: "rocep1s0f0", + address: "192.168.100.11", + peerAddress: "192.168.100.10", + roceGid: { index: 5, value: "fe80::20" }, + }, + }); + }); + + it("returns no match when discovery finds two peers", () => { + expect(qualifyDualSparkTopology(qualificationInput([peerNode(), peerNode(1)]))).toMatchObject({ + outcome: "no-match", + code: "peer-count", + }); + }); + + it("returns a strict error when discovery finds more than two peers", () => { + const input = qualificationInput([peerNode(), peerNode(1), peerNode(2)]); + input.intent = "explicit"; + + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "error", + code: "peer-count", + }); + }); + + it("returns a strict error for a resume topology mismatch", () => { + const input = qualificationInput([]); + input.intent = "resume"; + + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "error", + code: "peer-count", + }); + }); + + it.each([ + { + name: "an incompatible schema", + mutate: (report: SystemReadinessReport) => { + report.schemaVersion = "2.0.0"; + }, + code: "readiness-schema-incompatible", + }, + { + name: "a stale observation", + mutate: (report: SystemReadinessReport) => { + report.provenance.observedAt = "2026-08-02T17:58:00.000Z"; + }, + code: "readiness-stale", + }, + { + name: "an inconclusive result", + mutate: (report: SystemReadinessReport) => { + Object.assign(report, { status: "inconclusive", exitCode: 3 }); + }, + code: "readiness-inconclusive", + }, + { + name: "an incompatible result", + mutate: (report: SystemReadinessReport) => { + Object.assign(report, { status: "incompatible", exitCode: 2 }); + }, + code: "readiness-incompatible", + }, + { + name: "no Spark qualification", + mutate: (report: SystemReadinessReport) => { + report.qualifications = []; + }, + code: "spark-qualification-unavailable", + }, + { + name: "an unknown Spark qualification", + mutate: (report: SystemReadinessReport) => { + report.qualifications = [ + { id: "host.platform.dgx_spark", status: "unknown", capabilityIds: [] }, + ]; + }, + code: "spark-qualification-unavailable", + }, + { + name: "an unknown runtime capability", + mutate: (report: SystemReadinessReport) => { + report.capabilities = report.capabilities.map((capability) => + capability.id === "host.docker.runtime_supported" + ? { ...capability, state: "unknown" } + : capability, + ); + }, + code: "runtime-qualification-unavailable", + }, + ])("fails closed for $name", ({ mutate, code }) => { + const input = qualificationInput(); + mutate(input.peers[0]!.readiness); + + expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + }); + + it.each([ + { + name: "the same node identity", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.peers[0]!.nodeId = input.local.nodeId; + input.peers[0]!.sshBinding.toNodeId = input.local.nodeId; + }, + code: "duplicate-node-identity", + }, + { + name: "the same GPU identity", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.peers[0]!.gpuIds = input.local.gpuIds; + }, + code: "duplicate-gpu-identity", + }, + { + name: "more than one local GPU identity", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.gpuIds = ["GPU-head", "GPU-extra"]; + }, + code: "gpu-identity-unavailable", + }, + ])("rejects $name", ({ mutate, code }) => { + const input = qualificationInput(); + mutate(input); + + expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + }); + + it.each([ + { state: "conflict" as const, code: "runtime-conflict" }, + { state: "unknown" as const, code: "runtime-state-unknown" }, + ])("does not replace a peer runtime in the $state state", ({ state, code }) => { + const input = qualificationInput(); + input.peers[0]!.runtimeState = state; + + expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + }); + + it.each([ + { + name: "one logical rail", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.rails = input.local.rails.slice(0, 1); + }, + code: "fabric-degraded", + }, + { + name: "three logical rails", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.rails = [...input.local.rails, rail("head", 0, { netdev: "extra0" })]; + }, + code: "fabric-multiple", + }, + { + name: "two physical ports", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.rails[1]!.physicalPortId = "cx7-right-head"; + }, + code: "fabric-multiple", + }, + { + name: "a switched path", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.rails[0]!.path = "switched"; + }, + code: "fabric-degraded", + }, + { + name: "an unreachable peer address", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.peers[0]!.rails[0]!.connectivity = "unreachable"; + }, + code: "fabric-degraded", + }, + { + name: "nonreciprocal addresses", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.peers[0]!.rails[0]!.peerAddress = "192.168.100.99"; + }, + code: "fabric-mismatch", + }, + { + name: "an unresolved RoCE GID", + mutate: (input: DualSparkTopologyQualificationInput) => { + input.local.rails[0]!.roceGid = { state: "unknown" }; + }, + code: "fabric-degraded", + }, + ])("rejects a fabric with $name", ({ mutate, code }) => { + const input = qualificationInput(); + mutate(input); + + expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + }); + + it("rejects a peer without an opaque pretrusted SSH binding", () => { + const input = qualificationInput(); + input.peers[0]!.sshBinding.state = "untrusted"; + input.peers[0]!.sshBinding.handle = "not-an-opaque-binding"; + + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code: "ssh-binding-unavailable", + }); + }); + + it("produces the same artifact for either injected rail order", () => { + const firstInput = qualificationInput(); + const secondInput = clone(firstInput); + secondInput.local.rails = [...secondInput.local.rails].reverse(); + secondInput.peers[0]!.rails = [...secondInput.peers[0]!.rails].reverse(); + + const first = qualifyDualSparkTopology(firstInput); + const second = qualifyDualSparkTopology(secondInput); + expect(first.outcome).toBe("qualified"); + expect(second.outcome).toBe("qualified"); + if (first.outcome !== "qualified" || second.outcome !== "qualified") return; + expect(second.artifact).toEqual(first.artifact); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-topology.ts b/src/lib/inference/serving/dual-spark-topology.ts new file mode 100644 index 00000000000..9679a676924 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-topology.ts @@ -0,0 +1,785 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import net from "node:net"; + +import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { managedInferenceDigest } from "./catalog-integrity.js"; +import { + DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + type ManagedInferenceTopologyQualification, +} from "./catalog-types.js"; + +export const DUAL_SPARK_TOPOLOGY_ID = DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; +export { DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION }; + +const REQUIRED_READINESS_CAPABILITY_IDS = [ + "host.platform.supported", + "host.platform.dgx_spark", + "host.docker.available", + "host.docker.daemon_reachable", + "host.docker.runtime_supported", + "host.docker.storage_compatible", + "host.gpu.nvidia_available", + "host.gpu.container_toolkit_available", + "host.gpu.cdi_healthy", +] as const; +const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +const SAFE_INTERFACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const SAFE_BINDING_HANDLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,8191}$/; +const SSH_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const SSH_HOST_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; + +export type DualSparkQualificationIntent = "automatic" | "explicit" | "resume"; +export type DualSparkRuntimeState = "clear" | "conflict" | "unknown"; +export type DualSparkObservationState = "up" | "down" | "unknown"; +export type DualSparkConnectivityState = "reachable" | "unreachable" | "unknown"; +export type DualSparkRoceGidState = "resolved" | "missing" | "unknown"; + +export interface DualSparkRoceGidObservation { + state: DualSparkRoceGidState; + index?: number; + value?: string; +} + +export interface DualSparkRailObservation { + adapter: "connectx-7" | "other" | "unknown"; + path: "direct" | "switched" | "unknown"; + physicalPortId: string; + netdev: string; + hcaDevice: string; + hcaPort: number; + address: string; + prefixLength: number; + peerNodeId: string; + peerAddress: string; + linkState: DualSparkObservationState; + connectivity: DualSparkConnectivityState; + roceGid: DualSparkRoceGidObservation; +} + +export interface DualSparkNodeObservation { + nodeId: string; + gpuIds: readonly string[]; + readiness: SystemReadinessReport; + runtimeState: DualSparkRuntimeState; + rails: readonly DualSparkRailObservation[]; +} + +export interface DualSparkSshBindingObservation { + state: "pretrusted" | "untrusted" | "unknown"; + fromNodeId: string; + toNodeId: string; + peerTarget: string; + handle: string; +} + +export interface DualSparkPeerObservation extends DualSparkNodeObservation { + sshBinding: DualSparkSshBindingObservation; +} + +export interface DualSparkTopologyQualificationInput { + intent: DualSparkQualificationIntent; + evaluatedAt: string; + maxReadinessAgeMs: number; + local: DualSparkNodeObservation; + peers: readonly DualSparkPeerObservation[]; +} + +export interface DualSparkTopologyNode { + nodeId: string; + gpuId: string; + role: "head" | "worker"; +} + +export interface DualSparkTopologyRoceGid { + index: number; + value: string; +} + +export interface DualSparkTopologyRailEndpoint { + nodeId: string; + netdev: string; + hcaDevice: string; + hcaPort: number; + address: string; + prefixLength: number; + peerAddress: string; + roceGid: DualSparkTopologyRoceGid; +} + +export interface DualSparkTopologyRail { + index: number; + head: DualSparkTopologyRailEndpoint; + worker: DualSparkTopologyRailEndpoint; +} + +export interface DualSparkTopologyOutput { + headNodeId: string; + workerNodeId: string; + nodes: readonly [DualSparkTopologyNode, DualSparkTopologyNode]; + rails: readonly [DualSparkTopologyRail, DualSparkTopologyRail]; + masterAddress: string; + peer: { + target: string; + sshBindingHandle: string; + }; +} + +export type DualSparkTopologyArtifact = + ManagedInferenceTopologyQualification & { + id: typeof DUAL_SPARK_TOPOLOGY_ID; + schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + status: "qualified"; + }; + +export type DualSparkTopologyFailureCode = + | "peer-count" + | "qualification-policy-invalid" + | "readiness-schema-incompatible" + | "readiness-stale" + | "readiness-incompatible" + | "readiness-inconclusive" + | "spark-qualification-unavailable" + | "runtime-qualification-unavailable" + | "node-identity-unavailable" + | "duplicate-node-identity" + | "gpu-identity-unavailable" + | "duplicate-gpu-identity" + | "runtime-conflict" + | "runtime-state-unknown" + | "ssh-binding-unavailable" + | "fabric-degraded" + | "fabric-multiple" + | "fabric-mismatch" + | "artifact-digest-failed"; + +export type DualSparkTopologyQualificationResult = + | { outcome: "qualified"; artifact: DualSparkTopologyArtifact } + | { outcome: "no-match"; code: DualSparkTopologyFailureCode; message: string } + | { outcome: "error"; code: DualSparkTopologyFailureCode; message: string }; + +interface QualificationFailure { + code: DualSparkTopologyFailureCode; + message: string; +} + +interface QualifiedNode { + observation: DualSparkNodeObservation; + gpuId: string; +} + +interface ValidatedRail { + observation: DualSparkRailObservation; + gid: DualSparkTopologyRoceGid; +} + +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function failure( + intent: DualSparkQualificationIntent, + result: QualificationFailure, +): DualSparkTopologyQualificationResult { + return intent === "automatic" + ? { outcome: "no-match", ...result } + : { outcome: "error", ...result }; +} + +function validateQualificationPolicy( + evaluatedAt: string, + maxReadinessAgeMs: number, +): number | QualificationFailure { + const evaluatedAtMs = Date.parse(evaluatedAt); + if ( + !Number.isFinite(evaluatedAtMs) || + !Number.isSafeInteger(maxReadinessAgeMs) || + maxReadinessAgeMs <= 0 + ) { + return { + code: "qualification-policy-invalid", + message: "The topology qualification time or readiness age limit is invalid.", + }; + } + return evaluatedAtMs; +} + +function findUniqueCapability( + report: SystemReadinessReport, + id: string, +): SystemReadinessReport["capabilities"][number] | undefined { + const matches = report.capabilities.filter((capability) => capability.id === id); + return matches.length === 1 ? matches[0] : undefined; +} + +function validateReadiness( + report: SystemReadinessReport, + evaluatedAtMs: number, + maxReadinessAgeMs: number, +): QualificationFailure | undefined { + const compatibility = checkSystemReadinessSchemaVersion(report.schemaVersion); + if (!compatibility.compatible || report.mutated !== false) { + return { + code: "readiness-schema-incompatible", + message: "A node readiness report has an incompatible schema.", + }; + } + + const observedAtMs = Date.parse(report.provenance.observedAt); + const readinessAgeMs = evaluatedAtMs - observedAtMs; + if (!Number.isFinite(observedAtMs) || readinessAgeMs < 0 || readinessAgeMs > maxReadinessAgeMs) { + return { + code: "readiness-stale", + message: "A node readiness report is outside the accepted observation window.", + }; + } + + if (report.status === "inconclusive") { + return { + code: "readiness-inconclusive", + message: "A node readiness report is inconclusive.", + }; + } + if ( + report.status !== "supported" || + report.exitCode !== 0 || + report.findings.some(({ severity }) => severity === "blocking" || severity === "fatal") + ) { + return { + code: "readiness-incompatible", + message: "A node readiness report is incompatible with this topology.", + }; + } + + const sparkQualifications = report.qualifications.filter( + (qualification) => qualification.id === "host.platform.dgx_spark", + ); + if (sparkQualifications.length !== 1 || sparkQualifications[0]?.status !== "qualified") { + return { + code: "spark-qualification-unavailable", + message: "A node does not have one qualified DGX Spark readiness result.", + }; + } + + for (const id of REQUIRED_READINESS_CAPABILITY_IDS) { + if (findUniqueCapability(report, id)?.state !== "present") { + return { + code: "runtime-qualification-unavailable", + message: "A node readiness report does not qualify the required container runtime.", + }; + } + } + return undefined; +} + +function validateNode( + node: DualSparkNodeObservation, + evaluatedAtMs: number, + maxReadinessAgeMs: number, +): QualifiedNode | QualificationFailure { + if (!SAFE_ID_PATTERN.test(node.nodeId)) { + return { + code: "node-identity-unavailable", + message: "A node identity is missing or invalid.", + }; + } + if (node.gpuIds.length !== 1 || !SAFE_ID_PATTERN.test(node.gpuIds[0] ?? "")) { + return { + code: "gpu-identity-unavailable", + message: "Each DGX Spark node must have exactly one valid GPU identity.", + }; + } + const readinessFailure = validateReadiness(node.readiness, evaluatedAtMs, maxReadinessAgeMs); + if (readinessFailure) return readinessFailure; + if (node.runtimeState === "conflict") { + return { + code: "runtime-conflict", + message: "An existing runtime conflicts with automatic dual-node activation.", + }; + } + if (node.runtimeState !== "clear") { + return { + code: "runtime-state-unknown", + message: "The existing runtime state is unknown.", + }; + } + return { observation: node, gpuId: node.gpuIds[0]! }; +} + +function validAddress(address: string, prefixLength: number): boolean { + const version = net.isIP(address); + const maxPrefixLength = version === 4 ? 32 : version === 6 ? 128 : 0; + return ( + maxPrefixLength > 0 && + address !== "0.0.0.0" && + address !== "::" && + Number.isInteger(prefixLength) && + prefixLength > 0 && + prefixLength <= maxPrefixLength + ); +} + +function validateRail( + rail: DualSparkRailObservation, + expectedPeerNodeId: string, +): ValidatedRail | QualificationFailure { + if ( + rail.adapter !== "connectx-7" || + rail.path !== "direct" || + rail.linkState !== "up" || + rail.connectivity !== "reachable" + ) { + return { + code: "fabric-degraded", + message: "The direct ConnectX-7 fabric is incomplete or degraded.", + }; + } + if ( + !SAFE_ID_PATTERN.test(rail.physicalPortId) || + !SAFE_INTERFACE_PATTERN.test(rail.netdev) || + !SAFE_INTERFACE_PATTERN.test(rail.hcaDevice) || + !Number.isInteger(rail.hcaPort) || + rail.hcaPort <= 0 || + rail.hcaPort > 255 || + !validAddress(rail.address, rail.prefixLength) || + net.isIP(rail.peerAddress) === 0 || + rail.address === rail.peerAddress || + rail.peerNodeId !== expectedPeerNodeId + ) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail identity or peer address is invalid.", + }; + } + const gid = rail.roceGid; + if ( + gid.state !== "resolved" || + !Number.isInteger(gid.index) || + (gid.index ?? -1) < 0 || + (gid.index ?? 4096) > 4095 || + typeof gid.value !== "string" || + net.isIP(gid.value) !== 6 || + gid.value === "::" + ) { + return { + code: "fabric-degraded", + message: "A ConnectX-7 rail does not have a resolved RoCE GID.", + }; + } + return { observation: rail, gid: { index: gid.index!, value: gid.value } }; +} + +function validateNodeRails( + node: DualSparkNodeObservation, + expectedPeerNodeId: string, +): readonly [ValidatedRail, ValidatedRail] | QualificationFailure { + if (node.rails.length < 2) { + return { + code: "fabric-degraded", + message: "One direct ConnectX-7 cable must expose two logical rails on each node.", + }; + } + if (node.rails.length > 2) { + return { + code: "fabric-multiple", + message: "More than one candidate ConnectX-7 cable topology was observed.", + }; + } + + const physicalPorts = new Set(node.rails.map(({ physicalPortId }) => physicalPortId)); + if (physicalPorts.size !== 1) { + return { + code: "fabric-multiple", + message: "The candidate logical rails belong to more than one physical port.", + }; + } + + const validated = node.rails.map((rail) => validateRail(rail, expectedPeerNodeId)); + const validationFailure = validated.find((rail): rail is QualificationFailure => "code" in rail); + if (validationFailure) return validationFailure; + const rails = validated as ValidatedRail[]; + const uniqueNetdevs = new Set(rails.map(({ observation }) => observation.netdev)); + const uniqueHcas = new Set( + rails.map(({ observation }) => `${observation.hcaDevice}:${observation.hcaPort}`), + ); + const uniqueAddresses = new Set(rails.map(({ observation }) => observation.address)); + const uniqueGids = new Set( + rails.map(({ gid, observation }) => `${observation.hcaDevice}:${gid.index}:${gid.value}`), + ); + if ( + uniqueNetdevs.size !== 2 || + uniqueHcas.size !== 2 || + uniqueAddresses.size !== 2 || + uniqueGids.size !== 2 + ) { + return { + code: "fabric-mismatch", + message: "The two logical ConnectX-7 rails must have distinct interfaces and addresses.", + }; + } + return [rails[0]!, rails[1]!]; +} + +function endpoint(nodeId: string, rail: ValidatedRail): DualSparkTopologyRailEndpoint { + const observation = rail.observation; + return { + nodeId, + netdev: observation.netdev, + hcaDevice: observation.hcaDevice, + hcaPort: observation.hcaPort, + address: observation.address, + prefixLength: observation.prefixLength, + peerAddress: observation.peerAddress, + roceGid: rail.gid, + }; +} + +function matchRails( + local: DualSparkNodeObservation, + peer: DualSparkNodeObservation, +): readonly [DualSparkTopologyRail, DualSparkTopologyRail] | QualificationFailure { + const localRails = validateNodeRails(local, peer.nodeId); + if ("code" in localRails) return localRails; + const peerRails = validateNodeRails(peer, local.nodeId); + if ("code" in peerRails) return peerRails; + + const remainingPeerRails = [...peerRails]; + const matches: Array<{ head: ValidatedRail; worker: ValidatedRail }> = []; + for (const localRail of localRails) { + const peerIndex = remainingPeerRails.findIndex( + ({ observation }) => + observation.address === localRail.observation.peerAddress && + observation.peerAddress === localRail.observation.address && + observation.prefixLength === localRail.observation.prefixLength && + net.isIP(observation.address) === net.isIP(localRail.observation.address), + ); + if (peerIndex === -1) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail addresses are not reciprocal.", + }; + } + matches.push({ head: localRail, worker: remainingPeerRails[peerIndex]! }); + remainingPeerRails.splice(peerIndex, 1); + } + if (remainingPeerRails.length !== 0) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail pairing is ambiguous.", + }; + } + const endpointAddresses = new Set( + matches.flatMap(({ head, worker }) => [head.observation.address, worker.observation.address]), + ); + if (endpointAddresses.size !== 4) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail endpoints must have four distinct addresses.", + }; + } + + matches.sort((left, right) => { + const leftNetdev = left.head.observation.netdev; + const rightNetdev = right.head.observation.netdev; + return ( + compareStrings(leftNetdev.toLowerCase(), rightNetdev.toLowerCase()) || + compareStrings(leftNetdev, rightNetdev) + ); + }); + const makeRail = ( + match: { head: ValidatedRail; worker: ValidatedRail }, + index: number, + ): DualSparkTopologyRail => ({ + index, + head: endpoint(local.nodeId, match.head), + worker: endpoint(peer.nodeId, match.worker), + }); + return [makeRail(matches[0]!, 0), makeRail(matches[1]!, 1)]; +} + +function validSshTarget(target: string): boolean { + if (target.length === 0 || target.length > 286 || target !== target.trim()) return false; + const parts = target.split("@"); + if (parts.length > 2) return false; + const host = parts.at(-1) ?? ""; + const username = parts.length === 2 ? parts[0] : undefined; + return ( + (username === undefined || SSH_USERNAME_PATTERN.test(username)) && + (net.isIP(host) === 4 || SSH_HOST_PATTERN.test(host)) + ); +} + +function validateSshBinding( + binding: DualSparkSshBindingObservation, + localNodeId: string, + peerNodeId: string, +): QualificationFailure | undefined { + if ( + binding.state !== "pretrusted" || + binding.fromNodeId !== localNodeId || + binding.toNodeId !== peerNodeId || + !validSshTarget(binding.peerTarget) || + !SAFE_BINDING_HANDLE_PATTERN.test(binding.handle) + ) { + return { + code: "ssh-binding-unavailable", + message: "The peer does not have a valid pretrusted SSH binding.", + }; + } + return undefined; +} + +function record(value: unknown): Record | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function artifactEndpointError(value: unknown, expectedNodeId: string): string | undefined { + const candidate = record(value); + const gid = record(candidate?.roceGid); + if ( + !candidate || + candidate.nodeId !== expectedNodeId || + typeof candidate.netdev !== "string" || + !SAFE_INTERFACE_PATTERN.test(candidate.netdev) || + typeof candidate.hcaDevice !== "string" || + !SAFE_INTERFACE_PATTERN.test(candidate.hcaDevice) || + !Number.isInteger(candidate.hcaPort) || + (candidate.hcaPort as number) <= 0 || + (candidate.hcaPort as number) > 255 || + typeof candidate.address !== "string" || + typeof candidate.prefixLength !== "number" || + !validAddress(candidate.address, candidate.prefixLength) || + typeof candidate.peerAddress !== "string" || + net.isIP(candidate.peerAddress) !== net.isIP(candidate.address) || + candidate.peerAddress === candidate.address || + !gid || + !Number.isInteger(gid.index) || + (gid.index as number) < 0 || + (gid.index as number) > 4095 || + typeof gid.value !== "string" || + net.isIP(gid.value) !== 6 || + gid.value === "::" + ) { + return `the ${expectedNodeId} rail endpoint is invalid`; + } + return undefined; +} + +function topologyOutputError( + value: unknown, + subjectNodeIds: readonly string[], +): string | undefined { + const output = record(value); + if (!output) return "topology qualification output is invalid"; + const { headNodeId, workerNodeId } = output; + if ( + typeof headNodeId !== "string" || + typeof workerNodeId !== "string" || + headNodeId === workerNodeId || + !SAFE_ID_PATTERN.test(headNodeId) || + !SAFE_ID_PATTERN.test(workerNodeId) || + [headNodeId, workerNodeId] + .sort(compareStrings) + .some((nodeId, index) => nodeId !== subjectNodeIds[index]) + ) { + return "topology role nodes do not match its subject"; + } + + if (!Array.isArray(output.nodes) || output.nodes.length !== 2) { + return "topology nodes are invalid"; + } + const nodes = output.nodes.map(record); + const head = nodes[0]; + const worker = nodes[1]; + if ( + !head || + !worker || + head.role !== "head" || + head.nodeId !== headNodeId || + worker.role !== "worker" || + worker.nodeId !== workerNodeId || + typeof head.gpuId !== "string" || + !SAFE_ID_PATTERN.test(head.gpuId) || + typeof worker.gpuId !== "string" || + !SAFE_ID_PATTERN.test(worker.gpuId) || + head.gpuId === worker.gpuId + ) { + return "topology node roles or GPU identities are invalid"; + } + + if (!Array.isArray(output.rails) || output.rails.length !== 2) { + return "topology rails are invalid"; + } + const rails: DualSparkTopologyRail[] = []; + for (const [index, value] of output.rails.entries()) { + const rail = record(value); + if (!rail || rail.index !== index) return "topology rail indexes are invalid"; + const headError = artifactEndpointError(rail.head, headNodeId); + const workerError = artifactEndpointError(rail.worker, workerNodeId); + if (headError || workerError) return headError ?? workerError; + const typedRail = rail as unknown as DualSparkTopologyRail; + if ( + typedRail.head.address !== typedRail.worker.peerAddress || + typedRail.worker.address !== typedRail.head.peerAddress || + typedRail.head.prefixLength !== typedRail.worker.prefixLength + ) { + return "topology rail addresses are not reciprocal"; + } + rails.push(typedRail); + } + if ( + new Set(rails.flatMap(({ head, worker }) => [head.address, worker.address])).size !== 4 || + new Set(rails.map(({ head }) => head.netdev)).size !== 2 || + new Set(rails.map(({ worker }) => worker.netdev)).size !== 2 + ) { + return "topology rail identities are not distinct"; + } + if (output.masterAddress !== rails[0]!.head.address) { + return "topology master address does not match the primary head rail"; + } + + const peer = record(output.peer); + if ( + !peer || + typeof peer.target !== "string" || + !validSshTarget(peer.target) || + typeof peer.sshBindingHandle !== "string" || + !SAFE_BINDING_HANDLE_PATTERN.test(peer.sshBindingHandle) + ) { + return "topology peer binding is invalid"; + } + return undefined; +} + +export function dualSparkTopologySubjectDigest(subjectNodeIds: readonly string[]): string { + return managedInferenceDigest([...subjectNodeIds].sort(compareStrings)); +} + +export function dualSparkTopologyOutputDigest(output: DualSparkTopologyOutput): string { + return managedInferenceDigest(output); +} + +export function getDualSparkTopologyArtifactError( + artifact: ManagedInferenceTopologyQualification, + expectedSubjectNodeIds?: readonly string[], +): string | undefined { + if ( + artifact.id !== DUAL_SPARK_TOPOLOGY_ID || + artifact.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION + ) { + return "topology qualification identity is incompatible"; + } + if (artifact.status !== "qualified") return "topology qualification is not qualified"; + if (!Array.isArray(artifact.subjectNodeIds)) return "topology qualification subject is invalid"; + const subjectNodeIds = [...artifact.subjectNodeIds]; + if ( + subjectNodeIds.length !== 2 || + new Set(subjectNodeIds).size !== 2 || + subjectNodeIds.some((nodeId) => !SAFE_ID_PATTERN.test(nodeId)) || + subjectNodeIds.some((nodeId, index) => index > 0 && subjectNodeIds[index - 1]! >= nodeId) + ) { + return "topology qualification subject is invalid"; + } + if ( + expectedSubjectNodeIds && + subjectNodeIds.some((nodeId, index) => nodeId !== expectedSubjectNodeIds[index]) + ) { + return "topology qualification subject does not match the readiness reports"; + } + + const outputError = topologyOutputError(artifact.output, subjectNodeIds); + if (outputError) return outputError; + try { + if (artifact.subjectDigest !== dualSparkTopologySubjectDigest(subjectNodeIds)) { + return "topology qualification subject digest does not match its subject"; + } + if ( + artifact.outputDigest !== + dualSparkTopologyOutputDigest(artifact.output as DualSparkTopologyOutput) + ) { + return "topology qualification output digest does not match its output"; + } + } catch { + return "topology qualification digest is invalid"; + } + return undefined; +} + +export function qualifyDualSparkTopology( + input: Readonly, +): DualSparkTopologyQualificationResult { + if (input.peers.length !== 1) { + return failure(input.intent, { + code: "peer-count", + message: "Automatic dual-node activation requires exactly one discovered DGX Spark peer.", + }); + } + + const evaluatedAtMs = validateQualificationPolicy(input.evaluatedAt, input.maxReadinessAgeMs); + if (typeof evaluatedAtMs !== "number") return failure(input.intent, evaluatedAtMs); + + const peer = input.peers[0]!; + const localNode = validateNode(input.local, evaluatedAtMs, input.maxReadinessAgeMs); + if ("code" in localNode) return failure(input.intent, localNode); + const peerNode = validateNode(peer, evaluatedAtMs, input.maxReadinessAgeMs); + if ("code" in peerNode) return failure(input.intent, peerNode); + + if (input.local.nodeId === peer.nodeId) { + return failure(input.intent, { + code: "duplicate-node-identity", + message: "The two DGX Spark observations refer to the same node identity.", + }); + } + if (localNode.gpuId === peerNode.gpuId) { + return failure(input.intent, { + code: "duplicate-gpu-identity", + message: "The two DGX Spark observations refer to the same GPU identity.", + }); + } + + const sshFailure = validateSshBinding(peer.sshBinding, input.local.nodeId, peer.nodeId); + if (sshFailure) return failure(input.intent, sshFailure); + const rails = matchRails(input.local, peer); + if ("code" in rails) return failure(input.intent, rails); + + const output: DualSparkTopologyOutput = { + headNodeId: input.local.nodeId, + workerNodeId: peer.nodeId, + nodes: [ + { nodeId: input.local.nodeId, gpuId: localNode.gpuId, role: "head" }, + { nodeId: peer.nodeId, gpuId: peerNode.gpuId, role: "worker" }, + ], + rails, + masterAddress: rails[0].head.address, + peer: { + target: peer.sshBinding.peerTarget, + sshBindingHandle: peer.sshBinding.handle, + }, + }; + const subjectNodeIds = [input.local.nodeId, peer.nodeId].sort(); + try { + return { + outcome: "qualified", + artifact: { + id: DUAL_SPARK_TOPOLOGY_ID, + schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + status: "qualified", + subjectNodeIds, + subjectDigest: dualSparkTopologySubjectDigest(subjectNodeIds), + outputDigest: dualSparkTopologyOutputDigest(output), + output, + }, + }; + } catch { + return failure(input.intent, { + code: "artifact-digest-failed", + message: "The qualified topology could not be bound to its subject and output.", + }); + } +} diff --git a/src/lib/inference/serving/generated/catalog.json b/src/lib/inference/serving/generated/catalog.json new file mode 100644 index 00000000000..93c392bdd0a --- /dev/null +++ b/src/lib/inference/serving/generated/catalog.json @@ -0,0 +1,249 @@ +{ + "catalogDigest": "sha256:a3d23879b39b36e3ab80cee6846f4a6e7866bfe3589f650bc72ad92e2b182788", + "compilerVersion": "1.0.0", + "presets": [ + { + "definition": { + "apiVersion": "nemoclaw.nvidia.com/managed-inference/v1", + "kind": "ServingPreset", + "metadata": { + "displayName": "DeepSeek V4 Flash 0731 on two DGX Sparks", + "id": "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731" + }, + "spec": { + "plan": { + "backend": "vllm", + "bindings": { + "sparkTopology": { + "valueFromTopologyQualification": { + "id": "dgx-spark.gb10.dual-cx7", + "output": "topology", + "schemaVersion": 1 + } + } + }, + "recipeRef": "vllm.deepseek-v4-flash-0731.spark-dual.v1" + }, + "requirements": { + "all": [ + { + "readiness": { + "id": "host.platform.dgx_spark", + "kind": "qualification", + "scope": "everyNode", + "status": "qualified" + } + }, + { + "fact": "cluster.nodeCount", + "operator": "equals", + "state": "present", + "value": 2 + }, + { + "topologyQualification": { + "id": "dgx-spark.gb10.dual-cx7", + "schemaVersion": 1, + "status": "qualified" + } + } + ] + }, + "selection": "automatic" + } + }, + "definitionDigest": "sha256:ab115dd1842489f0eb64aa54e26b4ef2d8ff8e5725fa5b3af84398d31ff2f523", + "sourceFile": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" + } + ], + "recipes": [ + { + "definition": { + "apiVersion": "nemoclaw.nvidia.com/managed-inference/v1", + "kind": "ServingRecipe", + "metadata": { + "displayName": "DeepSeek V4 Flash 0731 on two DGX Sparks", + "id": "vllm.deepseek-v4-flash-0731.spark-dual.v1" + }, + "spec": { + "backend": "vllm", + "bindings": { + "sparkTopology": { + "outputSchema": "nemoclaw.nvidia.com/dual-spark-topology/v1", + "qualificationId": "dgx-spark.gb10.dual-cx7", + "schemaVersion": 1, + "type": "topologyQualificationOutput" + } + }, + "execution": { + "distributedExecutorBackend": "mp", + "lifecycleRef": "vllm.dual-dgx-spark/v1", + "materializerRef": "vllm.dual-dgx-spark/v1", + "nodeCount": 2, + "pipelineParallelSize": 1, + "tensorParallelSize": 2, + "topologyBinding": "sparkTopology" + }, + "model": { + "downloadSizeBytes": 166898661074, + "encodingPath": "encoding/encoding_dsv4.py", + "id": "deepseek-ai/DeepSeek-V4-Flash-0731", + "preparationRef": "deepseek-v4-flash-0731/v1", + "revision": "9e165c30e2704aec5d9d593cce3eebd58bbef1cb", + "servedName": "deepseek-v4-flash-0731" + }, + "readiness": { + "expectedModel": "deepseek-v4-flash-0731", + "timeoutSeconds": 3600 + }, + "runtime": { + "architecture": "arm64", + "devices": [ + "/dev/infiniband" + ], + "environment": { + "CUTE_DSL_ARCH": "sm_121a", + "DG_JIT_NVCC_COMPILER": "/usr/local/cuda/bin/nvcc", + "DG_JIT_USE_NVRTC": "0", + "FLASHINFER_CUDA_ARCH_LIST": "12.1a", + "FLASHINFER_DISABLE_VERSION_CHECK": "1", + "FLASHINFER_WORKSPACE_BASE": "/cache/huggingface/flashinfer", + "HF_HOME": "/cache/huggingface", + "HF_HUB_DISABLE_XET": "1", + "HF_HUB_OFFLINE": "1", + "NCCL_CROSS_NIC": "1", + "NCCL_CUMEM_ENABLE": "0", + "NCCL_DEBUG": "WARN", + "NCCL_IB_DISABLE": "0", + "NCCL_IGNORE_CPU_AFFINITY": "1", + "NCCL_NET": "IB", + "NCCL_NVLS_ENABLE": "0", + "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", + "TILELANG_CLEANUP_TEMP_FILES": "1", + "TORCH_CUDA_ARCH_LIST": "12.1a", + "TRANSFORMERS_OFFLINE": "1", + "VLLM_ALLOW_LONG_MAX_MODEL_LEN": "1", + "VLLM_B12X_W4A16_FORCE_BLOCKS_MAX_M": "16", + "VLLM_B12X_W4A16_FORCE_BLOCKS_PER_SM": "0", + "VLLM_CACHE_ROOT": "/cache/huggingface/vllm-cache", + "VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS": "0", + "VLLM_SPARSE_INDEXER_MAX_LOGITS_MB": "256", + "VLLM_USE_B12X_MOE": "1", + "VLLM_USE_BREAKABLE_CUDAGRAPH": "0", + "VLLM_USE_FLASHINFER_SAMPLER": "1" + }, + "image": "ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8", + "imageDownloadSizeBytes": 9787537825, + "ipcMode": "host", + "networkMode": "host", + "sharedMemoryBytes": 68719476736 + }, + "serve": { + "arguments": [ + { + "name": "--port", + "value": 8000 + }, + { + "name": "--trust-remote-code" + }, + { + "name": "--kv-cache-dtype", + "value": "nvfp4_ds_mla" + }, + { + "name": "--block-size", + "value": 256 + }, + { + "name": "--max-model-len", + "value": 1048576 + }, + { + "name": "--max-num-seqs", + "value": 6 + }, + { + "name": "--max-num-batched-tokens", + "value": 8192 + }, + { + "name": "--max-cudagraph-capture-size", + "value": 36 + }, + { + "name": "--gpu-memory-utilization", + "value": 0.8 + }, + { + "name": "--enable-prefix-caching" + }, + { + "name": "--enable-prompt-tokens-details" + }, + { + "name": "--async-scheduling" + }, + { + "name": "--enable-chunked-prefill" + }, + { + "name": "--speculative-config", + "value": "{\"method\":\"dspark\",\"num_speculative_tokens\":5,\"draft_sample_method\":\"probabilistic\"}" + }, + { + "name": "--tokenizer-mode", + "value": "deepseek_v4" + }, + { + "name": "--moe-backend", + "value": "flashinfer_b12x" + }, + { + "name": "--tool-call-parser", + "value": "deepseek_v4" + }, + { + "name": "--enable-auto-tool-choice" + }, + { + "name": "--reasoning-parser", + "value": "deepseek_v4" + }, + { + "name": "--reasoning-config", + "value": "{\"reasoning_parser\":\"deepseek_v4\",\"reasoning_start_str\":\"\",\"reasoning_end_str\":\"\"}" + }, + { + "name": "--default-chat-template-kwargs", + "value": "{\"thinking\":true,\"reasoning_effort\":\"low\"}" + }, + { + "name": "--generation-config", + "value": "vllm" + }, + { + "name": "--enable-flashinfer-autotune" + } + ], + "authentication": "bearer" + } + } + }, + "definitionDigest": "sha256:9ff596013e4e4bb6d22ead3aff23917437239e0bcfbf7f8af79e27f5ec908f0f", + "sourceFile": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" + } + ], + "schemaVersion": "1.0.0", + "sourceFiles": [ + { + "digest": "sha256:e0c4c3a6f175d1ce65bdc1f7d8d4b59247909e884949110628017d7b4adb85a8", + "path": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" + }, + { + "digest": "sha256:1dda2fbb6358718dcb718adfb836d43f4dc7bf446f196794e8f9a2dc95087802", + "path": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" + } + ], + "sourceRevision": "sha256:d7a897e9b3424f44aa0662a0452da2921686ee3f6779fd0b2d0e858b5625b328" +} diff --git a/src/lib/inference/serving/managed-runtime-receipts.ts b/src/lib/inference/serving/managed-runtime-receipts.ts new file mode 100644 index 00000000000..63557f81590 --- /dev/null +++ b/src/lib/inference/serving/managed-runtime-receipts.ts @@ -0,0 +1,86 @@ +// 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 { listGatewayStateRoots } from "../../state/gateway-registry"; +import { managedVllmStateDir } from "../vllm-api-key"; +import { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../vllm-station-runtime-receipt-path"; +import { + DUAL_SPARK_MANAGED_SERVING_STATE_FILE, + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, +} from "./spark-runtime-receipt-path"; + +export { MCP_LIFECYCLE_LOCK_DIRNAME } from "../../state/mcp-lifecycle-lock-storage"; +export { MANAGED_VLLM_API_KEY_FILE } from "../vllm-api-key"; +export { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../vllm-station-runtime-receipt-path"; +export { + DUAL_SPARK_MANAGED_SERVING_STATE_FILE, + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, +} from "./spark-runtime-receipt-path"; + +export interface ManagedDistributedVllmRuntimeReceipts { + readonly sparkBindingPath: string | null; + readonly sparkDiscoveryBindingPaths: readonly string[]; + readonly sparkPath: string | null; + readonly stationBindingPaths: readonly string[]; + readonly stationPaths: readonly string[]; +} + +function pathExistsNoFollow(filePath: string): boolean { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +/** Locate durable distributed-runtime ownership without parsing or following receipt paths. */ +export function findManagedDistributedVllmRuntimeReceipts( + options: { readonly homeDir?: string } = {}, +): ManagedDistributedVllmRuntimeReceipts { + const homeDir = options.homeDir ?? os.homedir(); + const stateRoots = listGatewayStateRoots(homeDir); + const sparkPath = path.join(managedVllmStateDir(homeDir), DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE); + const stationPaths = stateRoots + .map(({ root }) => path.join(root, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE)) + .filter(pathExistsNoFollow); + const sparkBindingPath = `${sparkPath}.ssh-binding`; + const sparkDiscoveryBindingPaths = stateRoots + .map(({ root }) => `${path.join(root, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)}.ssh-binding`) + .filter(pathExistsNoFollow); + const stationBindingPaths = stateRoots + .map(({ root }) => `${path.join(root, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE)}.ssh-binding`) + .filter(pathExistsNoFollow); + return { + sparkBindingPath: pathExistsNoFollow(sparkBindingPath) ? sparkBindingPath : null, + sparkDiscoveryBindingPaths, + sparkPath: pathExistsNoFollow(sparkPath) ? sparkPath : null, + stationBindingPaths, + stationPaths, + }; +} + +/** Stop a new install before it can mutate state already owned by another managed runtime. */ +export function assertNoManagedDistributedVllmRuntimeReceipts( + options: { readonly homeDir?: string } = {}, +): void { + const receipts = findManagedDistributedVllmRuntimeReceipts(options); + const paths = [ + ...(receipts.sparkPath ? [receipts.sparkPath] : []), + ...(receipts.sparkBindingPath ? [receipts.sparkBindingPath] : []), + ...receipts.sparkDiscoveryBindingPaths, + ...receipts.stationPaths, + ...receipts.stationBindingPaths, + ]; + if (paths.length === 0) return; + throw new Error( + `Managed vLLM runtime state already exists at ${paths.join( + ", ", + )}; recover it through Local vLLM or uninstall it before starting a new managed install.`, + ); +} diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts new file mode 100644 index 00000000000..59782fd0275 --- /dev/null +++ b/src/lib/inference/serving/resolver.test.ts @@ -0,0 +1,272 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { + DUAL_SPARK_PRESET_ID, + type ManagedInferenceReadinessSource, + type ManagedInferenceResolverInput, + type ManagedInferenceTopologyQualification, +} from "./catalog-types.js"; +import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { + type DualSparkTopologyOutput, + dualSparkTopologyOutputDigest, +} from "./dual-spark-topology.js"; +import { resolveManagedInferenceServing } from "./resolver.js"; + +const NOW = new Date("2026-08-02T18:00:00.000Z"); +const SOURCE_REVISION = "a".repeat(40); + +function readinessReport(overrides: Partial = {}): SystemReadinessReport { + return { + schemaVersion: "1.1.0", + mutated: false, + provenance: { + nemoclawVersion: "0.1.0", + sourceRevision: SOURCE_REVISION, + observedAt: "2026-08-02T17:59:50.000Z", + }, + observations: [], + capabilities: [{ id: "host.platform.dgx_spark", state: "present" }], + qualifications: [ + { + id: "host.platform.dgx_spark", + status: "qualified", + capabilityIds: ["host.platform.dgx_spark"], + }, + ], + findings: [], + evidence: [], + status: "supported", + exitCode: 0, + ...overrides, + } as SystemReadinessReport; +} + +function readinessSources(): ManagedInferenceReadinessSource[] { + return [ + { nodeId: "spark-head", report: readinessReport() }, + { nodeId: "spark-worker", report: readinessReport() }, + ]; +} + +function topology( + overrides: Partial> = {}, +): ManagedInferenceTopologyQualification { + const artifact = structuredClone(fixtureDualSparkSelection().topologyQualification); + return { + ...artifact, + ...overrides, + }; +} + +function resolverInput( + overrides: Partial> = {}, +): ManagedInferenceResolverInput { + return { + readinessReports: readinessSources(), + topologyQualifications: [topology()], + now: NOW, + ...overrides, + }; +} + +describe("managed inference resolver", () => { + it("selects the automatic preset for two fresh qualified Sparks and their topology", () => { + const result = resolveManagedInferenceServing(resolverInput()); + + expect(result).toMatchObject({ + outcome: "selected", + selection: "automatic", + preset: { metadata: { id: DUAL_SPARK_PRESET_ID } }, + recipe: { spec: { execution: { nodeCount: 2, tensorParallelSize: 2 } } }, + topologyQualification: { output: { masterAddress: "192.168.100.10" } }, + }); + }); + + it("selects the exact explicit preset only when compatible requirements still pass", () => { + const result = resolveManagedInferenceServing( + resolverInput({ + intent: { + preset: DUAL_SPARK_PRESET_ID, + provider: "vllm", + vllmModel: "deepseek-ai/DeepSeek-V4-Flash-0731", + }, + }), + ); + + expect(result).toMatchObject({ outcome: "selected", selection: "explicit" }); + }); + + it("returns an immutable topology snapshot", () => { + const artifact = topology(); + const result = resolveManagedInferenceServing( + resolverInput({ topologyQualifications: [artifact] }), + ); + + expect(result.outcome).toBe("selected"); + if (result.outcome !== "selected") return; + (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; + expect(result.topologyQualification.output.masterAddress).toBe("192.168.100.10"); + expect(Object.isFrozen(result.topologyQualification.output)).toBe(true); + }); + + it.each([ + { provider: "vllm" }, + { vllmModel: "another/model" }, + { vllmExtraArguments: ["--another-option"] }, + ])("leaves existing inference intent authoritative for automatic selection", (intent) => { + expect( + resolveManagedInferenceServing({ + readinessReports: [], + topologyQualifications: [], + intent, + now: NOW, + }), + ).toMatchObject({ outcome: "no-match", code: "explicit-intent" }); + }); + + it("rejects an unknown explicit preset", () => { + expect( + resolveManagedInferenceServing(resolverInput({ intent: { preset: "vllm.unknown" } })), + ).toMatchObject({ outcome: "rejected", code: "unknown-preset" }); + }); + + it("rejects explicit preset intent that conflicts with its immutable recipe", () => { + expect( + resolveManagedInferenceServing( + resolverInput({ + intent: { preset: DUAL_SPARK_PRESET_ID, vllmExtraArguments: ["--max-model-len", "1"] }, + }), + ), + ).toMatchObject({ outcome: "rejected", code: "incompatible-intent" }); + }); + + it.each([ + { + name: "stale provenance", + report: readinessReport({ + provenance: { + nemoclawVersion: "0.1.0", + sourceRevision: SOURCE_REVISION, + observedAt: "2026-08-02T17:00:00.000Z", + }, + }), + }, + { + name: "incompatible report", + report: readinessReport({ status: "incompatible", exitCode: 2 }), + }, + { + name: "blocking finding", + report: readinessReport({ + findings: [{ id: "host.blocked", severity: "blocking", summary: "Blocked." }], + }), + }, + { + name: "unknown Spark qualification", + report: readinessReport({ + qualifications: [ + { + id: "host.platform.dgx_spark", + status: "unknown", + capabilityIds: ["host.platform.dgx_spark"], + }, + ], + }), + }, + ])("rejects $name before selecting a recipe", ({ report }) => { + const sources = readinessSources(); + sources[1] = { nodeId: "spark-worker", report }; + + expect( + resolveManagedInferenceServing(resolverInput({ readinessReports: sources })), + ).toMatchObject({ outcome: "rejected", code: "invalid-readiness" }); + }); + + it("rejects a non-finite resolution time", () => { + expect( + resolveManagedInferenceServing(resolverInput({ now: new Date(Number.NaN) })), + ).toMatchObject({ outcome: "rejected", code: "invalid-readiness" }); + }); + + it.each([1, 3])("does not activate automatically for %i readiness reports", (count) => { + const reports = [ + ...readinessSources(), + { nodeId: "spark-third", report: readinessReport() }, + ].slice(0, count); + + expect( + resolveManagedInferenceServing(resolverInput({ readinessReports: reports })), + ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); + }); + + it("does not activate automatically without the qualified topology artifact", () => { + expect( + resolveManagedInferenceServing(resolverInput({ topologyQualifications: [] })), + ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); + }); + + it("rejects a topology artifact for different physical subjects", () => { + expect( + resolveManagedInferenceServing( + resolverInput({ + topologyQualifications: [topology({ subjectNodeIds: ["spark-head", "spark-third"] })], + }), + ), + ).toMatchObject({ outcome: "rejected", code: "invalid-topology" }); + }); + + it("rejects topology output mutated without a new digest", () => { + const artifact = topology(); + (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; + + expect( + resolveManagedInferenceServing(resolverInput({ topologyQualifications: [artifact] })), + ).toMatchObject({ outcome: "rejected", code: "invalid-topology" }); + }); + + it("rejects a stale topology subject digest", () => { + expect( + resolveManagedInferenceServing( + resolverInput({ + topologyQualifications: [topology({ subjectDigest: `sha256:${"f".repeat(64)}` })], + }), + ), + ).toMatchObject({ outcome: "rejected", code: "invalid-topology" }); + }); + + it("rejects an internally inconsistent topology with a recomputed output digest", () => { + const artifact = topology(); + (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; + (artifact as { outputDigest: string }).outputDigest = dualSparkTopologyOutputDigest( + artifact.output, + ); + + expect( + resolveManagedInferenceServing(resolverInput({ topologyQualifications: [artifact] })), + ).toMatchObject({ outcome: "rejected", code: "invalid-topology" }); + }); + + it("rejects ambiguous topology artifacts", () => { + expect( + resolveManagedInferenceServing( + resolverInput({ topologyQualifications: [topology(), topology()] }), + ), + ).toMatchObject({ outcome: "rejected", code: "invalid-topology" }); + }); + + it("rejects missing requirements for an explicit preset instead of falling back", () => { + expect( + resolveManagedInferenceServing( + resolverInput({ + readinessReports: readinessSources().slice(0, 1), + intent: { preset: DUAL_SPARK_PRESET_ID }, + }), + ), + ).toMatchObject({ outcome: "rejected", code: "requirements-not-met" }); + }); +}); diff --git a/src/lib/inference/serving/resolver.ts b/src/lib/inference/serving/resolver.ts new file mode 100644 index 00000000000..611759a2ca5 --- /dev/null +++ b/src/lib/inference/serving/resolver.ts @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; +import { getSystemReadinessReferenceErrors } from "../../readiness/references.js"; +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; +import { + DUAL_SPARK_PRESET_ID, + DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + type ManagedInferenceReadinessSource, + type ManagedInferenceResolution, + type ManagedInferenceResolverInput, + type ManagedInferenceSelectionIntent, + type ManagedInferenceServingPreset, + type ManagedInferenceServingRecipe, + type ManagedInferenceTopologyQualification, +} from "./catalog-types.js"; +import { getDualSparkTopologyArtifactError } from "./dual-spark-topology.js"; + +export const MANAGED_INFERENCE_READINESS_MAX_AGE_MS = 30_000; +const MAX_FUTURE_CLOCK_SKEW_MS = 5_000; +const SOURCE_REVISION = /^[0-9a-f]{40,64}$/u; +const PUBLIC_VERSION = + /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u; + +function hasText(value: string | undefined): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +function explicitIntentWithoutPreset(intent: ManagedInferenceSelectionIntent): boolean { + return ( + hasText(intent.provider) || + hasText(intent.vllmModel) || + (intent.vllmExtraArguments?.length ?? 0) > 0 + ); +} + +function readinessError( + source: ManagedInferenceReadinessSource, + nowMs: number, + maxAgeMs: number, +): string | undefined { + const { nodeId, report } = source; + if (!hasText(nodeId)) return "readiness node ID is empty"; + const compatibility = checkSystemReadinessSchemaVersion(report.schemaVersion); + if (!compatibility.compatible) return `${nodeId}: ${compatibility.reason}`; + if (report.mutated !== false) return `${nodeId}: readiness report is not read-only`; + if (!PUBLIC_VERSION.test(report.provenance.nemoclawVersion)) { + return `${nodeId}: readiness producer version is invalid`; + } + if (!SOURCE_REVISION.test(report.provenance.sourceRevision)) { + return `${nodeId}: readiness source revision is invalid`; + } + const observedAt = Date.parse(report.provenance.observedAt); + const ageMs = nowMs - observedAt; + if (!Number.isFinite(observedAt) || ageMs > maxAgeMs || ageMs < -MAX_FUTURE_CLOCK_SKEW_MS) { + return `${nodeId}: readiness report is stale or has an invalid observation time`; + } + const referenceErrors = getSystemReadinessReferenceErrors(report); + if (referenceErrors.length > 0) return `${nodeId}: ${referenceErrors[0]}`; + if (report.status !== "supported" || report.exitCode !== 0) { + return `${nodeId}: readiness status is ${report.status}`; + } + if (report.findings.some(({ severity }) => severity === "fatal" || severity === "blocking")) { + return `${nodeId}: readiness report contains a blocking finding`; + } + const sparkQualifications = report.qualifications.filter( + ({ id }) => id === "host.platform.dgx_spark", + ); + if (sparkQualifications.length !== 1 || sparkQualifications[0]?.status !== "qualified") { + return `${nodeId}: DGX Spark qualification is not qualified`; + } + return undefined; +} + +function readinessReportsError( + sources: readonly ManagedInferenceReadinessSource[], + nowMs: number, + maxAgeMs: number, +): string | undefined { + const nodeIds = sources.map(({ nodeId }) => nodeId); + if (new Set(nodeIds).size !== nodeIds.length) + return "readiness reports contain duplicate node IDs"; + for (const source of sources) { + const error = readinessError(source, nowMs, maxAgeMs); + if (error) return error; + } + return undefined; +} + +function requirementsError( + preset: ManagedInferenceServingPreset, + reports: readonly ManagedInferenceReadinessSource[], + topology: ManagedInferenceTopologyQualification, +): string | undefined { + for (const requirement of preset.spec.requirements.all) { + if ("readiness" in requirement) { + const matches = reports.every(({ report }) => + report.qualifications.some( + ({ id, status }) => + id === requirement.readiness.id && status === requirement.readiness.status, + ), + ); + if (!matches) return `readiness requirement ${requirement.readiness.id} did not match`; + } else if ("fact" in requirement) { + if ( + requirement.state !== "present" || + requirement.operator !== "equals" || + reports.length !== requirement.value + ) { + return `selection fact ${requirement.fact} did not match`; + } + } else if ( + topology.id !== requirement.topologyQualification.id || + topology.schemaVersion !== requirement.topologyQualification.schemaVersion || + topology.status !== requirement.topologyQualification.status + ) { + return `topology requirement ${requirement.topologyQualification.id} did not match`; + } + } + return undefined; +} + +function intentCompatibilityError( + intent: ManagedInferenceSelectionIntent, + recipe: ManagedInferenceServingRecipe, +): string | undefined { + if (hasText(intent.provider) && intent.provider !== recipe.spec.backend) { + return `provider ${intent.provider} conflicts with preset ${DUAL_SPARK_PRESET_ID}`; + } + if ( + hasText(intent.vllmModel) && + intent.vllmModel !== recipe.spec.model.id && + intent.vllmModel !== recipe.spec.model.servedName + ) { + return `model ${intent.vllmModel} conflicts with preset ${DUAL_SPARK_PRESET_ID}`; + } + if ((intent.vllmExtraArguments?.length ?? 0) > 0) { + return `extra vLLM arguments conflict with preset ${DUAL_SPARK_PRESET_ID}`; + } + return undefined; +} + +function rejectOrSkip(explicit: boolean, message: string): ManagedInferenceResolution { + return explicit + ? { outcome: "rejected", code: "requirements-not-met", message } + : { outcome: "no-match", code: "requirements-not-met", message }; +} + +export function resolveManagedInferenceServing( + input: ManagedInferenceResolverInput, +): ManagedInferenceResolution { + const catalog = loadManagedInferenceCatalog(); + const intent = input.intent ?? {}; + const explicitPreset = hasText(intent.preset) ? intent.preset : undefined; + if (!explicitPreset && explicitIntentWithoutPreset(intent)) { + return { + outcome: "no-match", + code: "explicit-intent", + message: "Existing inference intent remains authoritative.", + }; + } + if (explicitPreset && explicitPreset !== DUAL_SPARK_PRESET_ID) { + return { + outcome: "rejected", + code: "unknown-preset", + message: `Unknown managed inference preset ${explicitPreset}.`, + }; + } + + const explicit = explicitPreset !== undefined; + const preset = catalog.presets[0]?.definition; + const recipe = catalog.recipes[0]?.definition; + if (!preset || !recipe) throw new Error("compiled managed inference catalog is incomplete"); + const intentError = intentCompatibilityError(intent, recipe); + if (intentError) + return { outcome: "rejected", code: "incompatible-intent", message: intentError }; + if (input.readinessReports.length !== recipe.spec.execution.nodeCount) { + return rejectOrSkip(explicit, "The preset requires exactly two readiness reports."); + } + const maxAgeMs = input.maxReadinessAgeMs ?? MANAGED_INFERENCE_READINESS_MAX_AGE_MS; + const nowMs = (input.now ?? new Date()).getTime(); + if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0 || !Number.isFinite(nowMs)) { + return { + outcome: "rejected", + code: "invalid-readiness", + message: "Readiness freshness policy is invalid.", + }; + } + const reportsError = readinessReportsError(input.readinessReports, nowMs, maxAgeMs); + if (reportsError) { + return { outcome: "rejected", code: "invalid-readiness", message: reportsError }; + } + + const matchingTopologies = input.topologyQualifications.filter( + ({ id, schemaVersion }) => + id === DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID && + schemaVersion === DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + ); + if (matchingTopologies.length === 0) { + return rejectOrSkip(explicit, "The qualified two-Spark topology is unavailable."); + } + if (matchingTopologies.length !== 1) { + return { + outcome: "rejected", + code: "invalid-topology", + message: "Topology qualifications contain more than one candidate for the same subject.", + }; + } + let topology: ManagedInferenceTopologyQualification; + try { + topology = immutableManagedInferenceCopy(matchingTopologies[0]!); + } catch { + return { + outcome: "rejected", + code: "invalid-topology", + message: "Topology qualification is not immutable JSON data.", + }; + } + const expectedNodeIds = input.readinessReports.map(({ nodeId }) => nodeId).sort(); + const invalidTopology = getDualSparkTopologyArtifactError(topology, expectedNodeIds); + if (invalidTopology) { + return { outcome: "rejected", code: "invalid-topology", message: invalidTopology }; + } + const unmetRequirement = requirementsError(preset, input.readinessReports, topology); + if (unmetRequirement) return rejectOrSkip(explicit, unmetRequirement); + + return { + outcome: "selected", + selection: explicit ? "explicit" : "automatic", + catalogDigest: catalog.catalogDigest, + preset, + recipe, + topologyQualification: topology as ManagedInferenceTopologyQualification, + }; +} diff --git a/src/lib/inference/serving/spark-runtime-receipt-path.ts b/src/lib/inference/serving/spark-runtime-receipt-path.ts new file mode 100644 index 00000000000..ca99cb91d89 --- /dev/null +++ b/src/lib/inference/serving/spark-runtime-receipt-path.ts @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE = "dual-spark-vllm-runtime.json"; +export const DUAL_SPARK_MANAGED_SERVING_STATE_FILE = "dual-spark-managed-serving.json"; diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts new file mode 100644 index 00000000000..368b6529d99 --- /dev/null +++ b/src/lib/inference/serving/spark-runtime-receipt.ts @@ -0,0 +1,523 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { ensureLocalAdapterStateDir } from "../local-adapter-lifecycle"; +import { loadManagedVllmApiKey, managedVllmStateDir } from "../vllm-api-key"; +import { + clearDualStationSshBinding, + copyDualStationSshBinding, + type DualStationSshBinding, + encodeDualStationSshBindingHandoff, + loadDualStationSshBindingHandoff, +} from "../vllm-station-ssh-binding"; +import { loadManagedInferenceCatalog } from "./catalog"; +import { managedInferenceHexDigest } from "./catalog-integrity"; +import { + assertDualSparkVllmExecutorConfig, + createDualSparkVllmExecutor, + type DualSparkVllmNodeSnapshots, + inspectDualSparkVllmNodesSync, +} from "./dual-spark-executor"; +import { + classifyDualSparkExistingState, + cleanupDualSparkManagedVllm, + type DualSparkVllmLifecycleDeps, + dualSparkVllmApiKeyFingerprint, +} from "./dual-spark-lifecycle"; +import type { DualSparkVllmPlan } from "./dual-spark-materialize"; +import { DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE } from "./spark-runtime-receipt-path"; + +const MAX_RECEIPT_BYTES = 128 * 1024; +const SHA256 = /^[a-f0-9]{64}$/; +const CONTAINER_ID = /^[a-f0-9]{64}$/; +const BINDING_HANDLE = /^[A-Za-z0-9_-]{1,8192}$/; +const RECEIPT_KEYS = [ + "apiKeyFingerprint", + "headContainerId", + "localCacheRoot", + "peerCacheRoot", + "plan", + "planDigest", + "schemaVersion", + "sshBinding", + "workerContainerId", +] as const; + +interface PersistedReceipt { + readonly schemaVersion: 1; + readonly plan: DualSparkVllmPlan; + readonly planDigest: string; + readonly sshBinding: string; + readonly localCacheRoot: string; + readonly peerCacheRoot: string; + readonly apiKeyFingerprint: string; + readonly headContainerId: string; + readonly workerContainerId: string; +} + +export interface PersistDualSparkVllmRuntimeReceiptInput { + readonly plan: DualSparkVllmPlan; + readonly peerSshBinding: DualStationSshBinding; + readonly localCacheRoot: string; + readonly peerCacheRoot: string; + readonly apiKeyFingerprint: string; + readonly headContainerId: string; + readonly workerContainerId: string; +} + +export interface LoadedDualSparkVllmRuntime { + readonly plan: DualSparkVllmPlan; + readonly peerSshBinding: DualStationSshBinding; + readonly sshBinding: string; + readonly localCacheRoot: string; + readonly peerCacheRoot: string; + readonly apiKeyFingerprint: string; + readonly headContainerId: string; + readonly workerContainerId: string; +} + +type CleanupDeps = Pick< + DualSparkVllmLifecycleDeps, + "inspectNode" | "removeContainer" | "withLifecycleLock" +>; + +export interface DualSparkVllmRuntimeReceiptOptions { + readonly stateDir?: string; + /** @internal Test seam. */ + readonly loadApiKey?: () => string | null; + /** @internal Test seam. */ + readonly createLifecycleDeps?: (runtime: LoadedDualSparkVllmRuntime) => CleanupDeps; + /** @internal Test seam. */ + readonly inspectNodesSync?: (runtime: LoadedDualSparkVllmRuntime) => DualSparkVllmNodeSnapshots; +} + +export interface RecoveredDualSparkVllmEndpoint { + readonly baseUrl: string; + readonly apiKey: string; + readonly apiKeyFingerprint: string; + readonly plan: DualSparkVllmPlan; +} + +export type DualSparkVllmRuntimeCleanupResult = + | { readonly kind: "not-installed" } + | { readonly kind: "removed"; readonly removedContainerIds: readonly string[] }; + +export function dualSparkVllmRuntimeReceiptPath(stateDir = managedVllmStateDir()): string { + return path.join(stateDir, DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function exactKeys( + value: Record, + expected: readonly string[], + label: string, +): void { + const actual = Object.keys(value).sort(); + const sorted = [...expected].sort(); + if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) { + throw new Error(`${label} fields are invalid`); + } +} + +function requireString(value: unknown, label: string, pattern: RegExp, maximum = 8192): string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > maximum || + value !== value.trim() || + !pattern.test(value) + ) { + throw new Error(`${label} is invalid`); + } + return value; +} + +function requireAbsolutePath(value: unknown, label: string): string { + const candidate = requireString(value, label, /^[^\u0000-\u001f\u007f]+$/, 4096); + if (!path.posix.isAbsolute(candidate) || path.posix.normalize(candidate) !== candidate) { + throw new Error(`${label} must be a normalized absolute POSIX path`); + } + return candidate; +} + +function planDigest(plan: DualSparkVllmPlan): string { + return managedInferenceHexDigest(plan); +} + +function workerTarget(plan: DualSparkVllmPlan): string { + const roles = isRecord(plan.roles) ? plan.roles : null; + const worker = roles && isRecord(roles.worker) ? roles.worker : null; + const execution = worker && isRecord(worker.execution) ? worker.execution : null; + if (!execution || execution.kind !== "ssh") { + throw new Error("Dual-Spark worker SSH execution is invalid"); + } + return requireString( + execution.expectedTarget, + "dual-Spark worker SSH target", + /^(?:[A-Za-z_][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/, + 286, + ); +} + +function assertExecutorContract( + plan: DualSparkVllmPlan, + peerSshBinding: DualStationSshBinding, + localCacheRoot: string, + peerCacheRoot: string, +): void { + if (plan.catalogDigest !== loadManagedInferenceCatalog().catalogDigest) { + throw new Error("Dual-Spark runtime plan does not match the shipped catalog"); + } + assertDualSparkVllmExecutorConfig({ + plan, + peerSshBinding, + localCacheRoot, + peerCacheRoot, + }); +} + +function parseReceipt(value: unknown): PersistedReceipt { + if (!isRecord(value)) throw new Error("Dual-Spark vLLM runtime receipt is invalid"); + exactKeys(value, RECEIPT_KEYS, "Dual-Spark vLLM runtime receipt"); + if (value.schemaVersion !== 1 || !isRecord(value.plan)) { + throw new Error("Dual-Spark vLLM runtime receipt schema is unsupported"); + } + const plan = value.plan as unknown as DualSparkVllmPlan; + const digest = requireString(value.planDigest, "dual-Spark plan digest", SHA256, 64); + if (planDigest(plan) !== digest) throw new Error("Dual-Spark vLLM runtime plan digest changed"); + const headContainerId = requireString( + value.headContainerId, + "dual-Spark head container ID", + CONTAINER_ID, + 64, + ); + const workerContainerId = requireString( + value.workerContainerId, + "dual-Spark worker container ID", + CONTAINER_ID, + 64, + ); + if (headContainerId === workerContainerId) { + throw new Error("Dual-Spark container identities are ambiguous"); + } + return { + schemaVersion: 1, + plan, + planDigest: digest, + sshBinding: requireString(value.sshBinding, "dual-Spark SSH binding", BINDING_HANDLE), + localCacheRoot: requireAbsolutePath(value.localCacheRoot, "dual-Spark local cache root"), + peerCacheRoot: requireAbsolutePath(value.peerCacheRoot, "dual-Spark peer cache root"), + apiKeyFingerprint: requireString( + value.apiKeyFingerprint, + "dual-Spark API key fingerprint", + SHA256, + 64, + ), + headContainerId, + workerContainerId, + }; +} + +function assertPrivateReceipt(stat: fs.Stats, filePath: string): void { + if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) { + throw new Error(`Dual-Spark vLLM runtime receipt must be a private regular file: ${filePath}`); + } + if (typeof process.getuid === "function" && stat.uid !== process.getuid()) { + throw new Error(`Dual-Spark vLLM runtime receipt has the wrong owner: ${filePath}`); + } +} + +function loadPersistedReceipt(stateDir: string): PersistedReceipt | null { + const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); + if (typeof fs.constants.O_NOFOLLOW !== "number") { + throw new Error("Secure no-follow file opens are unavailable on this platform"); + } + let fd: number | undefined; + try { + try { + fd = fs.openSync( + filePath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | (fs.constants.O_NONBLOCK ?? 0), + ); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT") return null; + if (code === "ELOOP") { + throw new Error(`Refusing to read dual-Spark runtime receipt through a symbolic link`); + } + throw error; + } + const stat = fs.fstatSync(fd); + assertPrivateReceipt(stat, filePath); + if (stat.size < 2 || stat.size > MAX_RECEIPT_BYTES) { + throw new Error(`Dual-Spark vLLM runtime receipt is malformed: ${filePath}`); + } + return parseReceipt(JSON.parse(fs.readFileSync(fd, "utf8"))); + } catch (error) { + if (error instanceof SyntaxError) { + throw new Error(`Dual-Spark vLLM runtime receipt is malformed: ${filePath}`); + } + throw error; + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + +function fsyncDirectory(directory: string): void { + const fd = fs.openSync(directory, fs.constants.O_RDONLY); + try { + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } +} + +function writeReceipt(receipt: PersistedReceipt, stateDir: string): void { + ensureLocalAdapterStateDir(stateDir); + const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); + const temporary = `${filePath}.tmp-${String(process.pid)}-${Date.now().toString(16)}`; + let fd: number | undefined; + try { + fd = fs.openSync( + temporary, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, + 0o600, + ); + assertPrivateReceipt(fs.fstatSync(fd), temporary); + fs.writeFileSync(fd, `${JSON.stringify(receipt)}\n`, "utf8"); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = undefined; + fs.renameSync(temporary, filePath); + fsyncDirectory(stateDir); + } finally { + if (fd !== undefined) fs.closeSync(fd); + try { + fs.unlinkSync(temporary); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + } +} + +function durablePlan(plan: DualSparkVllmPlan, sshBinding: string): DualSparkVllmPlan { + if (plan.roles.worker.execution.kind !== "ssh") { + throw new Error("Dual-Spark worker SSH execution is invalid"); + } + return { + ...plan, + roles: { + ...plan.roles, + worker: { + ...plan.roles.worker, + execution: { ...plan.roles.worker.execution, bindingHandle: sshBinding }, + }, + }, + }; +} + +function loadedRuntime(receipt: PersistedReceipt): LoadedDualSparkVllmRuntime { + const binding = loadDualStationSshBindingHandoff(receipt.sshBinding, workerTarget(receipt.plan)); + if (encodeDualStationSshBindingHandoff(binding) !== receipt.sshBinding) { + throw new Error("Dual-Spark runtime SSH binding identity changed"); + } + assertExecutorContract(receipt.plan, binding, receipt.localCacheRoot, receipt.peerCacheRoot); + return { ...receipt, peerSshBinding: binding }; +} + +export function loadDualSparkVllmRuntimeReceipt( + options: Pick = {}, +): LoadedDualSparkVllmRuntime | null { + const receipt = loadPersistedReceipt(options.stateDir ?? managedVllmStateDir()); + return receipt ? loadedRuntime(receipt) : null; +} + +function sameInput( + existing: LoadedDualSparkVllmRuntime, + input: PersistDualSparkVllmRuntimeReceiptInput, +): boolean { + return ( + planDigest(durablePlan(input.plan, existing.sshBinding)) === planDigest(existing.plan) && + input.peerSshBinding.peerTarget === existing.peerSshBinding.peerTarget && + input.peerSshBinding.hostKeyDigest === existing.peerSshBinding.hostKeyDigest && + input.peerSshBinding.resolvedHost === existing.peerSshBinding.resolvedHost && + input.peerSshBinding.sshUser === existing.peerSshBinding.sshUser && + input.peerSshBinding.port === existing.peerSshBinding.port && + input.localCacheRoot === existing.localCacheRoot && + input.peerCacheRoot === existing.peerCacheRoot && + input.apiKeyFingerprint === existing.apiKeyFingerprint && + input.headContainerId === existing.headContainerId && + input.workerContainerId === existing.workerContainerId + ); +} + +/** Persist immutable ownership and pinned transport state for recovery/uninstall. */ +export function persistDualSparkVllmRuntimeReceipt( + input: PersistDualSparkVllmRuntimeReceiptInput, + options: Pick = {}, +): LoadedDualSparkVllmRuntime { + const stateDir = options.stateDir ?? managedVllmStateDir(); + ensureLocalAdapterStateDir(stateDir); + requireString(input.apiKeyFingerprint, "dual-Spark API key fingerprint", SHA256, 64); + requireString(input.headContainerId, "dual-Spark head container ID", CONTAINER_ID, 64); + requireString(input.workerContainerId, "dual-Spark worker container ID", CONTAINER_ID, 64); + if (input.headContainerId === input.workerContainerId) { + throw new Error("Dual-Spark container identities are ambiguous"); + } + assertExecutorContract( + input.plan, + input.peerSshBinding, + input.localCacheRoot, + input.peerCacheRoot, + ); + + const existing = loadDualSparkVllmRuntimeReceipt({ stateDir }); + if (existing) { + if (!sameInput(existing, input)) { + throw new Error("A different managed dual-Spark runtime receipt already owns recovery state"); + } + return existing; + } + + const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const bindingPath = `${receiptPath}.ssh-binding`; + try { + fs.mkdirSync(bindingPath, { mode: 0o700 }); + fsyncDirectory(stateDir); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") { + throw new Error(`Managed dual-Spark SSH binding state already exists: ${bindingPath}`); + } + throw error; + } + try { + const runtimeBinding = copyDualStationSshBinding(receiptPath, input.peerSshBinding); + const sshBinding = encodeDualStationSshBindingHandoff(runtimeBinding); + const plan = durablePlan(input.plan, sshBinding); + assertExecutorContract(plan, runtimeBinding, input.localCacheRoot, input.peerCacheRoot); + const receipt: PersistedReceipt = { + schemaVersion: 1, + plan, + planDigest: planDigest(plan), + sshBinding, + localCacheRoot: input.localCacheRoot, + peerCacheRoot: input.peerCacheRoot, + apiKeyFingerprint: input.apiKeyFingerprint, + headContainerId: input.headContainerId, + workerContainerId: input.workerContainerId, + }; + writeReceipt(receipt, stateDir); + return loadedRuntime(receipt); + } catch (error) { + try { + clearDualStationSshBinding(receiptPath); + } catch { + // Preserve the receipt persistence error. + } + throw error; + } +} + +function clearReceipt(stateDir: string): void { + const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); + fs.unlinkSync(filePath); + clearDualStationSshBinding(filePath); + fsyncDirectory(stateDir); +} + +function defaultCreateLifecycleDeps(runtime: LoadedDualSparkVllmRuntime): CleanupDeps { + return createDualSparkVllmExecutor({ + plan: runtime.plan, + peerSshBinding: runtime.peerSshBinding, + localCacheRoot: runtime.localCacheRoot, + peerCacheRoot: runtime.peerCacheRoot, + }); +} + +function defaultInspectNodesSync(runtime: LoadedDualSparkVllmRuntime): DualSparkVllmNodeSnapshots { + return inspectDualSparkVllmNodesSync({ + plan: runtime.plan, + peerSshBinding: runtime.peerSshBinding, + localCacheRoot: runtime.localCacheRoot, + peerCacheRoot: runtime.peerCacheRoot, + }); +} + +/** Recover only the exact healthy receipt-owned pair; unsafe managed state is explicit. */ +export function recoverInstalledDualSparkVllmEndpoint( + options: Pick< + DualSparkVllmRuntimeReceiptOptions, + "inspectNodesSync" | "loadApiKey" | "stateDir" + > = {}, +): RecoveredDualSparkVllmEndpoint | null { + const runtime = loadDualSparkVllmRuntimeReceipt({ stateDir: options.stateDir }); + if (!runtime) return null; + const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); + if (!apiKey || dualSparkVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { + throw new Error("Managed dual-Spark API key no longer matches the runtime receipt"); + } + let snapshots: DualSparkVllmNodeSnapshots; + try { + snapshots = (options.inspectNodesSync ?? defaultInspectNodesSync)(runtime); + } catch (error) { + throw new Error( + `Could not inspect the managed dual-Spark pair: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + const state = classifyDualSparkExistingState(runtime.plan, runtime.apiKeyFingerprint, snapshots); + if ( + state.outcome !== "reuse" || + state.headContainerId !== runtime.headContainerId || + state.workerContainerId !== runtime.workerContainerId + ) { + const reason = "reason" in state ? state.reason : "receipt-owned container IDs changed"; + throw new Error(`Managed dual-Spark runtime is not recoverable: ${reason}`); + } + const baseUrl = runtime.plan.roles.head.endpoint; + if (!baseUrl) throw new Error("Managed dual-Spark head endpoint is invalid"); + return { + baseUrl, + apiKey, + apiKeyFingerprint: runtime.apiKeyFingerprint, + plan: runtime.plan, + }; +} + +/** Remove only receipt-ID-owned containers, then retire fully accounted ownership state. */ +export async function cleanupInstalledDualSparkVllmRuntime( + options: DualSparkVllmRuntimeReceiptOptions = {}, +): Promise { + const stateDir = options.stateDir ?? managedVllmStateDir(); + const runtime = loadDualSparkVllmRuntimeReceipt({ stateDir }); + if (!runtime) return { kind: "not-installed" }; + + const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); + if (!apiKey || dualSparkVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { + throw new Error("Managed dual-Spark API key no longer matches the runtime receipt"); + } + const deps = (options.createLifecycleDeps ?? defaultCreateLifecycleDeps)(runtime); + const cleanup = await cleanupDualSparkManagedVllm(runtime.plan, apiKey, deps, { + headContainerId: runtime.headContainerId, + workerContainerId: runtime.workerContainerId, + }); + if (!cleanup.ok) throw new Error(cleanup.reason); + const expected = new Set([runtime.headContainerId, runtime.workerContainerId]); + const accounted = [...cleanup.removedContainerIds, ...(cleanup.alreadyAbsentContainerIds ?? [])]; + if ( + accounted.length !== expected.size || + new Set(accounted).size !== expected.size || + accounted.some((id) => !expected.has(id)) + ) { + throw new Error("Managed dual-Spark cleanup returned unexpected container identities"); + } + clearReceipt(stateDir); + return { kind: "removed", removedContainerIds: cleanup.removedContainerIds }; +} diff --git a/src/lib/inference/serving/vllm-managed-support.ts b/src/lib/inference/serving/vllm-managed-support.ts new file mode 100644 index 00000000000..7e26c4f70a2 --- /dev/null +++ b/src/lib/inference/serving/vllm-managed-support.ts @@ -0,0 +1,12 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { ensureDualStationVllmApiKey, loadDualStationVllmApiKey } from "../vllm-api-key.js"; +export { + buildLocalDualStationDockerEnv, + buildRemoteVllmDockerEnv, + buildVllmDockerEnv, +} from "../vllm-docker-env.js"; +export { resolveVllmInstallModel } from "../vllm-prompt.js"; +export { tryInstallDualSparkManagedVllm } from "./dual-spark-installer.js"; +export { recoverInstalledDualSparkVllmEndpoint } from "./spark-runtime-receipt.js"; diff --git a/src/lib/inference/vllm-api-key.ts b/src/lib/inference/vllm-api-key.ts index 0eda887c52b..b600b17729d 100644 --- a/src/lib/inference/vllm-api-key.ts +++ b/src/lib/inference/vllm-api-key.ts @@ -12,34 +12,41 @@ import { ensureLocalAdapterStateDir } from "./local-adapter-lifecycle"; export const DUAL_STATION_VLLM_API_KEY_FILE = "dual-station-vllm-api-key"; export const DUAL_STATION_VLLM_API_KEY_PATTERN = /^[a-f0-9]{64}$/; +// The original managed endpoint key was introduced with dual-Station serving. +// Keep its path stable while exposing topology-neutral names for later managed +// serving profiles such as dual Spark. +export const MANAGED_VLLM_API_KEY_FILE = DUAL_STATION_VLLM_API_KEY_FILE; +export const MANAGED_VLLM_API_KEY_PATTERN = DUAL_STATION_VLLM_API_KEY_PATTERN; export interface DualStationVllmApiKeyOptions { stateDir?: string; randomBytes?: (size: number) => Buffer; } -function defaultStateDir(): string { +export function managedVllmStateDir(homeDir = os.homedir()): string { // The managed vLLM service is host-global rather than gateway-scoped. Every // gateway therefore reads the same key even when NEMOCLAW_GATEWAY_PORT is // changed for a second sandbox. - return nemoclawStateRoot(os.homedir(), DEFAULT_GATEWAY_PORT); + return nemoclawStateRoot(homeDir, DEFAULT_GATEWAY_PORT); } -export function dualStationVllmApiKeyPath(stateDir = defaultStateDir()): string { +export function dualStationVllmApiKeyPath(stateDir = managedVllmStateDir()): string { return path.join(stateDir, DUAL_STATION_VLLM_API_KEY_FILE); } +export const managedVllmApiKeyPath = dualStationVllmApiKeyPath; + function assertPrivateRegularFile(stat: fs.Stats, filePath: string): void { if (!stat.isFile()) { - throw new Error(`Refusing to read dual-Station vLLM API key from non-file path: ${filePath}`); + throw new Error(`Refusing to read managed vLLM API key from non-file path: ${filePath}`); } if ((stat.mode & 0o077) !== 0) { throw new Error( - `Dual-Station vLLM API key file must not be accessible by group or others: ${filePath}`, + `Managed vLLM API key file must not be accessible by group or others: ${filePath}`, ); } if (typeof process.getuid === "function" && stat.uid !== process.getuid()) { - throw new Error(`Dual-Station vLLM API key file is not owned by the current user: ${filePath}`); + throw new Error(`Managed vLLM API key file is not owned by the current user: ${filePath}`); } } @@ -47,7 +54,7 @@ function assertPrivateRegularFile(stat: fs.Stats, filePath: string): void { export function loadDualStationVllmApiKey( options: Pick = {}, ): string | null { - const filePath = dualStationVllmApiKeyPath(options.stateDir ?? defaultStateDir()); + const filePath = dualStationVllmApiKeyPath(options.stateDir ?? managedVllmStateDir()); const noFollow = fs.constants.O_NOFOLLOW; if (typeof noFollow !== "number") { throw new Error("Secure no-follow file opens are unavailable on this platform"); @@ -62,7 +69,7 @@ export function loadDualStationVllmApiKey( if (code === "ENOENT") return null; if (code === "ELOOP") { throw new Error( - `Refusing to read dual-Station vLLM API key through a symbolic link: ${filePath}`, + `Refusing to read managed vLLM API key through a symbolic link: ${filePath}`, ); } throw error; @@ -70,11 +77,11 @@ export function loadDualStationVllmApiKey( const opened = fs.fstatSync(fd); assertPrivateRegularFile(opened, filePath); if (opened.size < 64 || opened.size > 65) { - throw new Error(`Dual-Station vLLM API key file is malformed: ${filePath}`); + throw new Error(`Managed vLLM API key file is malformed: ${filePath}`); } const value = fs.readFileSync(fd, "utf8").trim(); if (!DUAL_STATION_VLLM_API_KEY_PATTERN.test(value)) { - throw new Error(`Dual-Station vLLM API key file is malformed: ${filePath}`); + throw new Error(`Managed vLLM API key file is malformed: ${filePath}`); } return value; } finally { @@ -84,7 +91,7 @@ export function loadDualStationVllmApiKey( /** Create the managed endpoint key once, or reuse the existing private key. */ export function ensureDualStationVllmApiKey(options: DualStationVllmApiKeyOptions = {}): string { - const stateDir = options.stateDir ?? defaultStateDir(); + const stateDir = options.stateDir ?? managedVllmStateDir(); ensureLocalAdapterStateDir(stateDir); const existing = loadDualStationVllmApiKey({ stateDir }); if (existing) return existing; @@ -92,7 +99,7 @@ export function ensureDualStationVllmApiKey(options: DualStationVllmApiKeyOption const randomBytes = options.randomBytes ?? crypto.randomBytes; const value = randomBytes(32).toString("hex"); if (!DUAL_STATION_VLLM_API_KEY_PATTERN.test(value)) { - throw new Error("Could not generate a valid dual-Station vLLM API key"); + throw new Error("Could not generate a valid managed vLLM API key"); } const filePath = dualStationVllmApiKeyPath(stateDir); @@ -123,7 +130,10 @@ export function ensureDualStationVllmApiKey(options: DualStationVllmApiKeyOption const persisted = loadDualStationVllmApiKey({ stateDir }); if (persisted !== value) { - throw new Error("Could not verify the persisted dual-Station vLLM API key"); + throw new Error("Could not verify the persisted managed vLLM API key"); } return value; } + +export const loadManagedVllmApiKey = loadDualStationVllmApiKey; +export const ensureManagedVllmApiKey = ensureDualStationVllmApiKey; diff --git a/src/lib/inference/vllm-docker-env.ts b/src/lib/inference/vllm-docker-env.ts index 6dcf3f14f9b..70e76c56c31 100644 --- a/src/lib/inference/vllm-docker-env.ts +++ b/src/lib/inference/vllm-docker-env.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import { isIP } from "node:net"; import { buildSubprocessEnv } from "../subprocess-env"; @@ -8,6 +9,7 @@ import { assertDualStationSshBindingFiles, type DualStationSshBinding, dualStationDockerSshUri, + dualStationPinnedSshArgs, } from "./vllm-station-ssh-binding"; const DOCKER_CLIENT_ENV_NAMES = [ @@ -43,6 +45,30 @@ const SSH_TRANSPORT_ENV_NAMES = [ const CANONICAL_SSH_HOST_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; const CANONICAL_SSH_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const LISTENER_PROBE_MAX_BUFFER_BYTES = 1024 * 1024; + +function captureListenerCommand( + argv: readonly [string, ...string[]], + env: Readonly>, + timeoutMs: number, +): string { + const [file, ...args] = argv; + const result = spawnSync(file, args, { + encoding: "utf8", + env, + killSignal: "SIGKILL", + maxBuffer: LISTENER_PROBE_MAX_BUFFER_BYTES, + shell: false, + stdio: ["ignore", "pipe", "pipe"], + timeout: timeoutMs, + windowsHide: true, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error(`managed vLLM listener probe exited with status ${String(result.status)}`); + } + return (result.stdout ?? "").trim(); +} function validateRemoteDockerSshUri(value: string): string { const invalid = () => @@ -135,6 +161,35 @@ export function buildVllmSshTransportEnv( return { ...env, ...extra }; } +/** Capture the listening TCP sockets from one side of a pinned managed-vLLM pair. */ +export function captureManagedVllmTcpListeners( + role: "head" | "worker", + binding: DualStationSshBinding, + timeoutMs: number, +): string { + if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) { + throw new Error("managed vLLM listener probe timeout must be a positive integer"); + } + if (role === "head") { + return captureListenerCommand( + ["ss", "-H", "-lnt"], + buildSubprocessEnv({ LC_ALL: "C" }), + timeoutMs, + ); + } + return captureListenerCommand( + [ + "/usr/bin/ssh", + ...dualStationPinnedSshArgs(binding), + "--", + binding.peerTarget, + "LC_ALL=C ss -H -lnt", + ], + buildVllmSshTransportEnv({ LC_ALL: "C" }), + timeoutMs, + ); +} + /** * Select one explicitly configured Docker-over-SSH daemon without allowing an * ambient context, client config, API pin, or TCP/TLS settings to influence it. diff --git a/src/lib/inference/vllm-dual-station.test.ts b/src/lib/inference/vllm-dual-station.test.ts index 82f04bfff98..b735ff30d17 100644 --- a/src/lib/inference/vllm-dual-station.test.ts +++ b/src/lib/inference/vllm-dual-station.test.ts @@ -97,7 +97,10 @@ vi.mock("./vllm-station-runtime-receipt", () => ({ vi.mock("./vllm-api-key", () => ({ ensureDualStationVllmApiKey: mocks.ensureApiKey, + ensureManagedVllmApiKey: mocks.ensureApiKey, loadDualStationVllmApiKey: mocks.loadApiKey, + loadManagedVllmApiKey: mocks.loadApiKey, + managedVllmStateDir: () => path.join(os.homedir(), ".nemoclaw"), })); import { diff --git a/src/lib/inference/vllm-managed-recovery.test.ts b/src/lib/inference/vllm-managed-recovery.test.ts new file mode 100644 index 00000000000..1129f06b4af --- /dev/null +++ b/src/lib/inference/vllm-managed-recovery.test.ts @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const sparkRecovery = vi.hoisted(() => ({ endpoint: vi.fn() })); + +vi.mock("./serving/spark-runtime-receipt", async (importOriginal) => ({ + ...(await importOriginal()), + recoverInstalledDualSparkVllmEndpoint: sparkRecovery.endpoint, +})); + +import { + isNemoClawManagedVllmRunning, + persistConfiguredDualStationVllmRuntimeReceipt, + persistConfiguredManagedVllmRuntimeReceipt, +} from "./vllm"; + +describe("managed vLLM Spark recovery", () => { + beforeEach(() => { + sparkRecovery.endpoint.mockReset(); + }); + + it("recognizes and confirms an installer-owned Spark receipt", async () => { + sparkRecovery.endpoint.mockReturnValue({ + baseUrl: "http://10.40.0.1:8000", + apiKey: "a".repeat(64), + }); + + expect(isNemoClawManagedVllmRunning()).toBe(true); + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ + ok: true, + persisted: true, + }); + await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + ok: true, + persisted: true, + }); + }); + + it("fails closed instead of falling through when Spark receipt recovery is unsafe", async () => { + sparkRecovery.endpoint.mockImplementation(() => { + throw new Error("receipt-owned container IDs changed"); + }); + + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ + ok: false, + reason: "managed vLLM recovery failed: receipt-owned container IDs changed", + }); + }); +}); diff --git a/src/lib/inference/vllm-managed-runtime-receipts.test.ts b/src/lib/inference/vllm-managed-runtime-receipts.test.ts new file mode 100644 index 00000000000..42678780fd4 --- /dev/null +++ b/src/lib/inference/vllm-managed-runtime-receipts.test.ts @@ -0,0 +1,126 @@ +// 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 { DEFAULT_GATEWAY_PORT } from "../core/ports"; +import { nemoclawStateRoot } from "../state/state-root"; +import { createProductionDualSparkDiscoveryDeps } from "./serving/dual-spark-discovery-production"; +import { + assertNoManagedDistributedVllmRuntimeReceipts, + findManagedDistributedVllmRuntimeReceipts, +} from "./serving/managed-runtime-receipts"; +import { dualSparkVllmRuntimeReceiptPath } from "./serving/spark-runtime-receipt"; +import { dualStationVllmRuntimeReceiptPath } from "./vllm-station-runtime-receipt"; + +const temporaryHomes: string[] = []; + +function temporaryHome(): string { + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-receipts-")); + temporaryHomes.push(homeDir); + return homeDir; +} + +function touch(filePath: string): void { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, "stale\n", { mode: 0o600 }); +} + +afterEach(() => { + vi.unstubAllEnvs(); + for (const homeDir of temporaryHomes.splice(0)) fs.rmSync(homeDir, { recursive: true }); +}); + +describe("managed distributed vLLM receipt preflight", () => { + it("allows installation when no durable distributed receipt exists", () => { + expect(() => + assertNoManagedDistributedVllmRuntimeReceipts({ homeDir: temporaryHome() }), + ).not.toThrow(); + }); + + it("blocks a host-global Spark receipt without parsing stale contents", () => { + const homeDir = temporaryHome(); + const receiptPath = dualSparkVllmRuntimeReceiptPath( + nemoclawStateRoot(homeDir, DEFAULT_GATEWAY_PORT), + ); + touch(receiptPath); + + expect(findManagedDistributedVllmRuntimeReceipts({ homeDir })).toEqual({ + sparkBindingPath: null, + sparkDiscoveryBindingPaths: [], + sparkPath: receiptPath, + stationBindingPaths: [], + stationPaths: [], + }); + expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow( + "recover it through Local vLLM", + ); + }); + + it("blocks Station receipts across safely enumerated gateway roots", () => { + const homeDir = temporaryHome(); + const receiptPath = dualStationVllmRuntimeReceiptPath(nemoclawStateRoot(homeDir, 18080)); + touch(receiptPath); + + expect(findManagedDistributedVllmRuntimeReceipts({ homeDir }).stationPaths).toEqual([ + receiptPath, + ]); + }); + + it.each([ + { topology: "Spark", gatewayPort: DEFAULT_GATEWAY_PORT }, + { topology: "Station", gatewayPort: 18080 }, + ])("blocks an orphaned $topology SSH binding tree", ({ topology, gatewayPort }) => { + const homeDir = temporaryHome(); + const stateRoot = nemoclawStateRoot(homeDir, gatewayPort); + const receiptPath = + topology === "Spark" + ? dualSparkVllmRuntimeReceiptPath(stateRoot) + : dualStationVllmRuntimeReceiptPath(stateRoot); + const bindingPath = `${receiptPath}.ssh-binding`; + fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); + + expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow(bindingPath); + }); + + it("blocks an orphaned Spark discovery binding claim", () => { + const homeDir = temporaryHome(); + const bindingPath = path.join( + nemoclawStateRoot(homeDir), + "dual-spark-managed-serving.json.ssh-binding", + ); + fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); + + expect( + findManagedDistributedVllmRuntimeReceipts({ homeDir }).sparkDiscoveryBindingPaths, + ).toEqual([bindingPath]); + expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow(bindingPath); + }); + + it("places the production Spark discovery claim in the scanner-visible gateway root", () => { + const homeDir = temporaryHome(); + vi.stubEnv("HOME", homeDir); + const deps = createProductionDualSparkDiscoveryDeps(() => { + throw new Error("unexpected host probe"); + }); + + expect(deps.resolveBindingStatePath()).toBe( + path.join(nemoclawStateRoot(homeDir), "dual-spark-managed-serving.json"), + ); + }); + + it("treats a receipt symlink as existing without following it", () => { + const homeDir = temporaryHome(); + const receiptPath = dualSparkVllmRuntimeReceiptPath(nemoclawStateRoot(homeDir)); + fs.mkdirSync(path.dirname(receiptPath), { recursive: true }); + fs.symlinkSync(path.join(homeDir, "missing-target"), receiptPath); + + expect(findManagedDistributedVllmRuntimeReceipts({ homeDir }).sparkPath).toBe(receiptPath); + expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow( + "Managed vLLM runtime state already exists", + ); + }); +}); diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts new file mode 100644 index 00000000000..adbbb1ec685 --- /dev/null +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -0,0 +1,364 @@ +// 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, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadManagedInferenceCatalog } from "./serving/catalog"; +import { fixtureDualSparkSelection } from "./serving/dual-spark-fixture.test-support"; +import { + type DualSparkNodeSnapshot, + type DualSparkVllmLifecycleDeps, + dualSparkVllmApiKeyFingerprint, +} from "./serving/dual-spark-lifecycle"; +import { + DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, + DUAL_SPARK_TRANSACTION_LABEL, + type DualSparkVllmPlan, + type DualSparkVllmRolePlan, + materializeDualSparkVllmPlan, +} from "./serving/dual-spark-materialize"; +import { dualSparkTopologyOutputDigest } from "./serving/dual-spark-topology"; +import { + cleanupInstalledDualSparkVllmRuntime, + dualSparkVllmRuntimeReceiptPath, + loadDualSparkVllmRuntimeReceipt, + type PersistDualSparkVllmRuntimeReceiptInput, + persistDualSparkVllmRuntimeReceipt, + recoverInstalledDualSparkVllmEndpoint, +} from "./serving/spark-runtime-receipt"; +import { + createDualStationSshBindingFixture, + type DualStationSshBindingFixture, +} from "./vllm-station-ssh-binding.test-support"; + +const API_KEY = "a".repeat(64); +const HEAD_ID = "b".repeat(64); +const WORKER_ID = "c".repeat(64); +const TRANSACTION_ID = "d".repeat(32); + +let root: string; +let stateDir: string; +let sshFixture: DualStationSshBindingFixture; + +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-spark-runtime-receipt-")); + stateDir = path.join(root, ".nemoclaw"); + sshFixture = createDualStationSshBindingFixture("nvidia@spark-worker.local"); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + sshFixture.cleanup(); + fs.rmSync(root, { recursive: true, force: true }); +}); + +function plan(): DualSparkVllmPlan { + const selection = fixtureDualSparkSelection(); + const catalog = loadManagedInferenceCatalog(); + const sourceTopology = selection.topologyQualification; + const output = { + ...sourceTopology.output, + peer: { + target: sshFixture.binding.peerTarget, + sshBindingHandle: sshFixture.token, + }, + }; + return materializeDualSparkVllmPlan({ + ...selection, + catalogDigest: catalog.catalogDigest, + preset: catalog.presets[0]!.definition, + recipe: catalog.recipes[0]!.definition, + topologyQualification: { + ...sourceTopology, + outputDigest: dualSparkTopologyOutputDigest(output), + output, + }, + }); +} + +function input(): PersistDualSparkVllmRuntimeReceiptInput { + return { + plan: plan(), + peerSshBinding: sshFixture.binding, + localCacheRoot: "/home/nvidia/.cache/huggingface", + peerCacheRoot: "/home/nvidia/.cache/huggingface", + apiKeyFingerprint: dualSparkVllmApiKeyFingerprint(API_KEY), + headContainerId: HEAD_ID, + workerContainerId: WORKER_ID, + }; +} + +function snapshot(rolePlan: DualSparkVllmRolePlan, containerId: string): DualSparkNodeSnapshot { + return { + containers: [ + { + id: containerId, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + healthy: true, + labels: { + ...rolePlan.baseLabels, + [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: dualSparkVllmApiKeyFingerprint(API_KEY), + [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + }, + }, + ], + listeningPorts: + rolePlan.role === "head" ? [rolePlan.endpoint ? 8000 : 0, 25000].filter(Boolean) : [25000], + }; +} + +function cleanupDeps( + runtimePlan: DualSparkVllmPlan, + ids: { head: string; worker: string } = { head: HEAD_ID, worker: WORKER_ID }, +): { + deps: Pick; + removeContainer: ReturnType; +} { + const removeContainer = vi.fn(async () => ({ ok: true as const })); + return { + deps: { + inspectNode: async (rolePlan) => + rolePlan.role === "head" + ? snapshot(runtimePlan.roles.head, ids.head) + : snapshot(runtimePlan.roles.worker, ids.worker), + removeContainer, + withLifecycleLock: async (_plan, operation) => await operation(), + }, + removeContainer, + }; +} + +describe("dual-Spark vLLM runtime receipt", () => { + it("uses the host-global default gateway state root", async () => { + vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); + vi.resetModules(); + const { dualSparkVllmRuntimeReceiptPath: selectedReceiptPath } = await import( + "./serving/spark-runtime-receipt" + ); + expect(selectedReceiptPath()).toBe( + path.join(os.homedir(), ".nemoclaw", "dual-spark-vllm-runtime.json"), + ); + }); + + it("persists a private exact runtime plan with a promoted SSH binding and no bearer key", () => { + const source = input(); + const runtime = persistDualSparkVllmRuntimeReceipt(source, { stateDir }); + const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const raw = fs.readFileSync(receiptPath, "utf8"); + + expect(fs.statSync(receiptPath).mode & 0o777).toBe(0o600); + expect(fs.lstatSync(`${receiptPath}.ssh-binding`).isDirectory()).toBe(true); + expect(raw).not.toContain(API_KEY); + expect(runtime.sshBinding).not.toBe(sshFixture.token); + expect(runtime.plan.roles.worker.execution).toMatchObject({ + kind: "ssh", + expectedTarget: sshFixture.binding.peerTarget, + bindingHandle: runtime.sshBinding, + }); + expect(runtime.peerSshBinding.bindingFile).toContain(`${receiptPath}.ssh-binding/`); + expect(loadDualSparkVllmRuntimeReceipt({ stateDir })).toEqual(runtime); + }); + + it("is idempotent only for the same committed runtime", () => { + const source = input(); + const first = persistDualSparkVllmRuntimeReceipt(source, { stateDir }); + const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const original = fs.readFileSync(receiptPath, "utf8"); + + expect(persistDualSparkVllmRuntimeReceipt(source, { stateDir })).toEqual(first); + expect(() => + persistDualSparkVllmRuntimeReceipt( + { ...source, workerContainerId: "e".repeat(64) }, + { stateDir }, + ), + ).toThrow("different managed dual-Spark runtime receipt"); + expect(fs.readFileSync(receiptPath, "utf8")).toBe(original); + }); + + it("refuses a pre-existing SSH binding tree without mutating it", () => { + fs.mkdirSync(stateDir, { mode: 0o700 }); + const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const bindingPath = `${receiptPath}.ssh-binding`; + const markerPath = path.join(bindingPath, "foreign-state"); + fs.mkdirSync(bindingPath, { mode: 0o700 }); + fs.writeFileSync(markerPath, "leave intact\n", { mode: 0o600 }); + + expect(() => persistDualSparkVllmRuntimeReceipt(input(), { stateDir })).toThrow( + "Managed dual-Spark SSH binding state already exists", + ); + expect(fs.readFileSync(markerPath, "utf8")).toBe("leave intact\n"); + expect(fs.existsSync(receiptPath)).toBe(false); + }); + + it("refuses a symbolic-link receipt", () => { + fs.mkdirSync(stateDir, { mode: 0o700 }); + const target = path.join(root, "redirected.json"); + fs.writeFileSync(target, "{}\n", { mode: 0o600 }); + fs.symlinkSync(target, dualSparkVllmRuntimeReceiptPath(stateDir)); + + expect(() => loadDualSparkVllmRuntimeReceipt({ stateDir })).toThrow("symbolic link"); + }); + + it("rejects changed plan contents before using the persisted binding", () => { + persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf8")); + receipt.plan.model.id = "foreign/model"; + fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { mode: 0o600 }); + + expect(() => loadDualSparkVllmRuntimeReceipt({ stateDir })).toThrow("plan digest changed"); + }); + + it("recovers only the exact healthy receipt-owned endpoint synchronously", () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + expect( + recoverInstalledDualSparkVllmEndpoint({ + stateDir, + loadApiKey: () => API_KEY, + inspectNodesSync: () => ({ + head: snapshot(runtime.plan.roles.head, HEAD_ID), + worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + }), + }), + ).toEqual({ + baseUrl: runtime.plan.roles.head.endpoint, + apiKey: API_KEY, + apiKeyFingerprint: runtime.apiKeyFingerprint, + plan: runtime.plan, + }); + }); + + it("signals a managed endpoint whose exact receipt-owned IDs changed", () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + expect(() => + recoverInstalledDualSparkVllmEndpoint({ + stateDir, + loadApiKey: () => API_KEY, + inspectNodesSync: () => ({ + head: snapshot(runtime.plan.roles.head, "e".repeat(64)), + worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + }), + }), + ).toThrow("not recoverable"); + }); + + it("signals a persisted managed endpoint whose key no longer matches", () => { + persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + expect(() => + recoverInstalledDualSparkVllmEndpoint({ + stateDir, + loadApiKey: () => "f".repeat(64), + inspectNodesSync: vi.fn(), + }), + ).toThrow("API key no longer matches"); + }); + + it("removes only both exact receipt-owned containers before retiring state", async () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const { deps, removeContainer } = cleanupDeps(runtime.plan); + await expect( + cleanupInstalledDualSparkVllmRuntime({ + stateDir, + loadApiKey: () => API_KEY, + createLifecycleDeps: () => deps, + }), + ).resolves.toEqual({ kind: "removed", removedContainerIds: [HEAD_ID, WORKER_ID] }); + expect(removeContainer).toHaveBeenNthCalledWith(1, runtime.plan.roles.head, HEAD_ID); + expect(removeContainer).toHaveBeenNthCalledWith(2, runtime.plan.roles.worker, WORKER_ID); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); + expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); + }); + + it("retains the receipt and resumes after one exact container removal fails", async () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { + head: snapshot(runtime.plan.roles.head, HEAD_ID), + worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + }; + let workerAttempts = 0; + const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + if (rolePlan.role === "worker" && workerAttempts++ === 0) { + return { ok: false as const, reason: "worker daemon unavailable" }; + } + snapshots[rolePlan.role] = { + ...snapshots[rolePlan.role], + containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), + }; + return { ok: true as const }; + }); + const deps = { + inspectNode: async (rolePlan: DualSparkVllmRolePlan) => snapshots[rolePlan.role], + removeContainer, + withLifecycleLock: async (_plan: DualSparkVllmPlan, operation: () => Promise) => + await operation(), + }; + const options = { + stateDir, + loadApiKey: () => API_KEY, + createLifecycleDeps: () => deps, + }; + + await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow( + "worker daemon unavailable", + ); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + await expect(cleanupInstalledDualSparkVllmRuntime(options)).resolves.toEqual({ + kind: "removed", + removedContainerIds: [WORKER_ID], + }); + expect(removeContainer.mock.calls.map((call) => call[1])).toEqual([ + HEAD_ID, + WORKER_ID, + WORKER_ID, + ]); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); + }); + + it("preserves recovery state when the observed container IDs changed", async () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const { deps, removeContainer } = cleanupDeps(runtime.plan, { + head: "e".repeat(64), + worker: WORKER_ID, + }); + await expect( + cleanupInstalledDualSparkVllmRuntime({ + stateDir, + loadApiKey: () => API_KEY, + createLifecycleDeps: () => deps, + }), + ).rejects.toThrow("head receipt-owned container is absent but related runtime state exists"); + expect(removeContainer).not.toHaveBeenCalled(); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + }); + + it("preserves recovery state when the managed API key changed", async () => { + persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const createLifecycleDeps = vi.fn(); + await expect( + cleanupInstalledDualSparkVllmRuntime({ + stateDir, + loadApiKey: () => "f".repeat(64), + createLifecycleDeps, + }), + ).rejects.toThrow("API key no longer matches"); + expect(createLifecycleDeps).not.toHaveBeenCalled(); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + }); + + it("does nothing when no runtime receipt exists", async () => { + await expect( + cleanupInstalledDualSparkVllmRuntime({ + stateDir, + loadApiKey: vi.fn(), + createLifecycleDeps: vi.fn(), + }), + ).resolves.toEqual({ kind: "not-installed" }); + }); +}); diff --git a/src/lib/inference/vllm-station-lifecycle-lock.test.ts b/src/lib/inference/vllm-station-lifecycle-lock.test.ts index f654e12cef2..56d3765db38 100644 --- a/src/lib/inference/vllm-station-lifecycle-lock.test.ts +++ b/src/lib/inference/vllm-station-lifecycle-lock.test.ts @@ -10,6 +10,7 @@ import { type DualStationControllerUidFileStat, readDualStationControllerUid, withDualStationVllmLifecycleLock, + withHostGlobalVllmLifecycleLock, } from "./vllm-station-lifecycle-lock"; function controllerUidStat( @@ -113,4 +114,29 @@ describe("dual-Station controller UID binding", () => { fs.rmSync(root, { recursive: true, force: true }); } }); + + it("shares the host-global vLLM lock without requiring Station host preparation", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-vllm-lock-")); + const accountHome = path.join(root, "account-home"); + fs.mkdirSync(accountHome, { mode: 0o700 }); + const userInfo = os.userInfo(); + const userInfoSpy = vi.spyOn(os, "userInfo").mockReturnValue({ + ...userInfo, + homedir: accountHome, + }); + + try { + await withHostGlobalVllmLifecycleLock( + () => { + expect( + fs.existsSync(path.join(accountHome, ".nemoclaw", "state", "mcp-lifecycle-locks")), + ).toBe(true); + }, + { pollIntervalMs: 5, timeoutMs: 250, corruptLockGraceMs: 5 }, + ); + } finally { + userInfoSpy.mockRestore(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/inference/vllm-station-lifecycle-lock.ts b/src/lib/inference/vllm-station-lifecycle-lock.ts index 1db4076f21d..b706c11d912 100644 --- a/src/lib/inference/vllm-station-lifecycle-lock.ts +++ b/src/lib/inference/vllm-station-lifecycle-lock.ts @@ -8,7 +8,7 @@ import path from "node:path"; import { type McpLifecycleLockOptions, withMcpLifecycleLock } from "../state/mcp-lifecycle-lock"; import { STATE_DIR_NAME } from "../state/state-root"; -const DUAL_STATION_VLLM_LIFECYCLE_LOCK = "dual-station-vllm:host-global"; +const HOST_GLOBAL_VLLM_LIFECYCLE_LOCK = "dual-station-vllm:host-global"; const DUAL_STATION_CONTROLLER_CONFIG_DIR = "/etc/nemoclaw"; export const DUAL_STATION_CONTROLLER_UID_FILE = path.join( DUAL_STATION_CONTROLLER_CONFIG_DIR, @@ -125,6 +125,18 @@ export function assertDualStationControllerAccount( return controllerUid; } +/** Serialize every host-managed vLLM profile under the effective account home. */ +export function withHostGlobalVllmLifecycleLock( + operation: () => Promise | T, + options: McpLifecycleLockOptions = {}, +): Promise { + const stateDir = options.stateDir ?? path.join(os.userInfo().homedir, STATE_DIR_NAME, "state"); + return withMcpLifecycleLock(HOST_GLOBAL_VLLM_LIFECYCLE_LOCK, operation, { + ...options, + stateDir, + }); +} + /** * Serialize the host-managed dual-Station service across gateway instances. * @@ -146,9 +158,5 @@ export function withDualStationVllmLifecycleLock( identityDeps.readControllerUid, identityDeps.effectiveControllerUid, ); - const stateDir = options.stateDir ?? path.join(os.userInfo().homedir, STATE_DIR_NAME, "state"); - return withMcpLifecycleLock(DUAL_STATION_VLLM_LIFECYCLE_LOCK, operation, { - ...options, - stateDir, - }); + return withHostGlobalVllmLifecycleLock(operation, options); } diff --git a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts index c0f0821b418..6950706e47d 100644 --- a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts +++ b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts @@ -1,19 +1,89 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { cleanupInstalledDualStationVllmRuntime } from "./vllm-station-runtime-receipt"; +import fs from "node:fs"; +import path from "node:path"; + +import { + cleanupInstalledDualSparkVllmRuntime, + dualSparkVllmRuntimeReceiptPath, +} from "./serving/spark-runtime-receipt"; +import { + cleanupInstalledDualStationVllmRuntime, + dualStationVllmRuntimeReceiptPath, +} from "./vllm-station-runtime-receipt"; + +function pathExistsNoFollow(filePath: string): boolean { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +function requestedReceipt(): { + readonly filePath: string; + readonly stateDir: string; + readonly topology: "spark" | "station"; +} { + const args = process.argv.slice(2); + if (args.length !== 1) { + throw new Error("managed distributed vLLM cleanup requires one exact receipt path"); + } + const filePath = args[0]!; + if (!path.isAbsolute(filePath) || path.normalize(filePath) !== filePath) { + throw new Error("managed distributed vLLM cleanup receipt path is invalid"); + } + const stateDir = path.dirname(filePath); + if (filePath === dualSparkVllmRuntimeReceiptPath(stateDir)) { + return { filePath, stateDir, topology: "spark" }; + } + if (filePath === dualStationVllmRuntimeReceiptPath(stateDir)) { + return { filePath, stateDir, topology: "station" }; + } + throw new Error("managed distributed vLLM cleanup receipt name is unsupported"); +} async function main(): Promise { - const result = await cleanupInstalledDualStationVllmRuntime(); - if (result.kind === "not-installed") return; + const receipt = requestedReceipt(); + if (!pathExistsNoFollow(receipt.filePath)) { + throw new Error(`managed distributed vLLM receipt disappeared: ${receipt.filePath}`); + } + const otherReceipt = + receipt.topology === "spark" + ? dualStationVllmRuntimeReceiptPath(receipt.stateDir) + : dualSparkVllmRuntimeReceiptPath(receipt.stateDir); + if (pathExistsNoFollow(otherReceipt)) { + throw new Error( + "both dual-Spark and dual-Station runtime receipts exist; refusing ambiguous cleanup", + ); + } + + if (receipt.topology === "spark") { + const spark = await cleanupInstalledDualSparkVllmRuntime({ stateDir: receipt.stateDir }); + if (spark.kind !== "removed" || pathExistsNoFollow(receipt.filePath)) { + throw new Error("the requested dual-Spark runtime receipt was not removed"); + } + console.log( + `Removed managed dual-Spark vLLM containers: ${spark.removedContainerIds.join(", ")}`, + ); + return; + } + + const station = await cleanupInstalledDualStationVllmRuntime({ stateDir: receipt.stateDir }); + if (station.kind !== "removed" || pathExistsNoFollow(receipt.filePath)) { + throw new Error("the requested dual-Station runtime receipt was not removed"); + } console.log( - `Removed managed dual-Station vLLM containers: ${result.removedContainerIds.join(", ")}`, + `Removed managed dual-Station vLLM containers: ${station.removedContainerIds.join(", ")}`, ); } main().catch((error: unknown) => { console.error( - `Refusing uninstall before managed dual-Station cleanup: ${ + `Refusing uninstall before managed distributed vLLM cleanup: ${ error instanceof Error ? error.message : String(error) }`, ); diff --git a/src/lib/inference/vllm.ts b/src/lib/inference/vllm.ts index 4a6b74b8f24..e4869c295e7 100644 --- a/src/lib/inference/vllm.ts +++ b/src/lib/inference/vllm.ts @@ -32,12 +32,16 @@ import { runCapture } from "../runner"; import { redactFull } from "../security/redact"; import { isSafeModelId } from "../validation"; import { getGpuIndicesByName } from "./nim"; -import { ensureDualStationVllmApiKey, loadDualStationVllmApiKey } from "./vllm-api-key"; import { buildLocalDualStationDockerEnv, buildRemoteVllmDockerEnv, buildVllmDockerEnv, -} from "./vllm-docker-env"; + ensureDualStationVllmApiKey, + loadDualStationVllmApiKey, + recoverInstalledDualSparkVllmEndpoint, + resolveVllmInstallModel, + tryInstallDualSparkManagedVllm, +} from "./serving/vllm-managed-support"; import { buildVllmServeCommand, NEMOTRON_ULTRA_DUAL_STATION_IMAGE, @@ -48,7 +52,6 @@ import { type VllmModelDef, type VllmPlatform, } from "./vllm-models"; -import { resolveVllmInstallModel } from "./vllm-prompt"; import { type DualStationVllmPlan, NEMOCLAW_DGX_STATION_PEER_ENV, @@ -196,8 +199,16 @@ function hfCacheMount(): string { return `${hostHfCacheDir()}:${HF_CACHE_CONTAINER_DIR}`; } -function hfDownloadCacheMount(): string { - return `${hostHfCacheDir()}:${HF_DOWNLOAD_CACHE_CONTAINER_DIR}`; +function hfDownloadCacheMount(hostCacheDir = hostHfCacheDir()): string { + const normalized = path.posix.normalize(hostCacheDir); + if ( + !path.posix.isAbsolute(hostCacheDir) || + normalized !== hostCacheDir || + hostCacheDir.includes(":") + ) { + throw new Error("vLLM model cache must be a normalized absolute path without ':'"); + } + return `${normalized}:${HF_DOWNLOAD_CACHE_CONTAINER_DIR}`; } function hfModelCacheKey(model: VllmModelDef): string | null { @@ -206,7 +217,7 @@ function hfModelCacheKey(model: VllmModelDef): string | null { return `models--${modelParts.join("--")}`; } -function hfModelSnapshotDir(model: VllmModelDef): string | null { +export function hfModelSnapshotDir(model: VllmModelDef): string | null { const revision = model.revision; const modelCacheKey = hfModelCacheKey(model); if (!revision || !modelCacheKey || !HF_CACHE_COMPONENT_PATTERN.test(revision)) { @@ -228,8 +239,10 @@ function hostUserIdentity(): string | null { return `${String(process.getuid())}:${String(process.getgid())}`; } -function hostUserDockerArgs(): string[] { - const identity = hostUserIdentity(); +function hostUserDockerArgs(identity = hostUserIdentity()): string[] { + if (identity !== null && !/^[1-9][0-9]*:(?:0|[1-9][0-9]*)$/.test(identity)) { + throw new Error("vLLM model download user must be one non-root numeric uid and numeric gid"); + } return identity ? ["--user", identity] : []; } @@ -511,10 +524,11 @@ export async function pullImage( } // Run `hf download ` inside a one-shot container of the same image. -function downloadModel( +export function downloadModel( profile: VllmProfile, model: VllmModelDef, dockerEnv: Record = buildVllmDockerEnv(), + target: { hostCacheDir?: string; userIdentity?: string } = {}, ): Promise<{ ok: boolean; reason?: string }> { emit(`Pre-downloading model with hf: ${model.id}`); return new Promise((resolve) => { @@ -525,11 +539,11 @@ function downloadModel( "-t", "--rm", "--pull=never", - ...hostUserDockerArgs(), + ...hostUserDockerArgs(target.userIdentity), "--entrypoint", "hf", "-v", - hfDownloadCacheMount(), + hfDownloadCacheMount(target.hostCacheDir), "-e", `HF_HOME=${HF_DOWNLOAD_CACHE_CONTAINER_DIR}`, ...buildHfTokenDockerArgs(), @@ -880,19 +894,29 @@ function vllmContainerReplacementTarget( } export function isNemoClawManagedVllmRunning(): boolean { + if (recoverInstalledDualSparkVllmEndpoint()) return true; const ownership = inspectVllmContainerOwnership(NEMOCLAW_VLLM_CONTAINER_NAME); return (ownership.kind === "managed" || ownership.kind === "dual-managed") && ownership.running; } -export type PersistConfiguredDualStationVllmRuntimeResult = +export type PersistConfiguredManagedVllmRuntimeResult = | { ok: true; persisted: boolean } | { ok: false; reason: string }; +export type PersistConfiguredDualStationVllmRuntimeResult = + PersistConfiguredManagedVllmRuntimeResult; + /** - * Adopt an already-running installer-qualified pair into durable uninstall - * ownership after onboarding has authenticated and validated its endpoint. + * Confirm an installer-owned receipt or adopt an already-running Station pair + * after onboarding has authenticated and validated its endpoint. */ -export async function persistConfiguredDualStationVllmRuntimeReceipt(): Promise { +export async function persistConfiguredManagedVllmRuntimeReceipt(): Promise { + try { + if (recoverInstalledDualSparkVllmEndpoint()) return { ok: true, persisted: true }; + } catch (error) { + return { ok: false, reason: `managed vLLM recovery failed: ${(error as Error).message}` }; + } + const configuredPeer = String(process.env[NEMOCLAW_DGX_STATION_PEER_ENV] ?? "").trim(); if (!configuredPeer) { return { @@ -935,6 +959,10 @@ export async function persistConfiguredDualStationVllmRuntimeReceipt(): Promise< } } +/** @deprecated Use persistConfiguredManagedVllmRuntimeReceipt. */ +export const persistConfiguredDualStationVllmRuntimeReceipt = + persistConfiguredManagedVllmRuntimeReceipt; + function startContainer( profile: VllmProfile, model: VllmModelDef, @@ -1497,7 +1525,7 @@ interface InstallVllmOptions { beforeInstall?: (modelId: string) => void; } -function imageIsCached( +export function imageIsCached( profile: VllmProfile, dockerEnv: Record = buildVllmDockerEnv(), ): boolean { @@ -1552,6 +1580,22 @@ async function runVllmInstall( profile: VllmProfile, opts: InstallVllmOptions, ): Promise<{ ok: boolean }> { + const dualSpark = await tryInstallDualSparkManagedVllm( + { + platform: profile.platform, + nonInteractive: opts.nonInteractive, + promptFn: opts.promptFn, + beforeInstall: opts.beforeInstall, + }, + { + prerequisites: dockerPrereqsOk, + pullImage, + downloadModel, + printDownloadAuthentication: printHfDownloadAuthentication, + }, + ); + if (dualSpark.kind === "handled") return dualSpark.result; + let dualStationPlan: DualStationVllmPlan | null = null; let peerModelSnapshot: "ready" | "staging-required" | null = null; const explicitModel = String(process.env.NEMOCLAW_VLLM_MODEL ?? "").trim(); diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 15d49e79c2b..704ed090c8b 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -1085,8 +1085,8 @@ const { // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. const handleVllmSelection = createSetupNimVllmHandler({ VLLM_PORT, runCapture, getLocalProviderBaseUrl, getLocalProviderValidationBaseUrl, - getManagedVllmProviderBinding: localInference.getManagedDualStationVllmProviderBinding, queryVllmModels: (baseUrl, apiKey) => { const result = localInference.probeVllmModels(baseUrl, apiKey); return result.ok ? result.body : ""; }, isSafeModelId, requireValue, validateOpenAiLikeSelection, - applyVllmRuntimeContextWindow: localInference.applyVllmRuntimeContextWindow, isDgxSparkHost: () => nim.detectNvidiaPlatform() === "spark", isNemoClawManagedVllmRunning: vllmInference.isNemoClawManagedVllmRunning, persistConfiguredDualStationVllmRuntimeReceipt: vllmInference.persistConfiguredDualStationVllmRuntimeReceipt, + getManagedVllmProviderBinding: localInference.getManagedVllmProviderBinding, queryVllmModels: (baseUrl, apiKey) => { const result = localInference.probeVllmModels(baseUrl, apiKey); return result.ok ? result.body : ""; }, isSafeModelId, requireValue, validateOpenAiLikeSelection, + applyVllmRuntimeContextWindow: localInference.applyVllmRuntimeContextWindow, isDgxSparkHost: () => nim.detectNvidiaPlatform() === "spark", isNemoClawManagedVllmRunning: vllmInference.isNemoClawManagedVllmRunning, persistConfiguredManagedVllmRuntimeReceipt: vllmInference.persistConfiguredManagedVllmRuntimeReceipt, exitProcess: (code) => process.exit(code), }); const ollamaModelSize: typeof import("./inference/ollama/model-size") = require("./inference/ollama/model-size"); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index ca0fffb653f..28abd052896 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; import { canonicalEndpoint } from "../core/url-utils"; +import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; import { assertEndpointResolvesPublic, type EndpointDnsLookupFn, @@ -15,7 +15,7 @@ import { isAdvisoryGatewayRouteConflict, } from "../inference/gateway-route-compatibility"; import { withGatewayRouteMutationLock } from "../inference/gateway-route-mutation-lock"; -import { getManagedDualStationVllmProviderBinding } from "../inference/local"; +import { getManagedVllmProviderBinding } from "../inference/local"; import { assertNoExplicitOpenShellGatewayEndpoint, assertNoOpenShellGatewayEndpointOverride, @@ -37,6 +37,7 @@ function matchesOnboardEndpoint( const selected = canonicalEndpoint(endpointUrl, flavor); return selected !== null && selected === canonicalEndpoint(onboardEndpointUrl, flavor); } + import type { CommonDeps, HermesDeps, @@ -442,7 +443,7 @@ export function createSetupInference( run: deps.run, VLLM_LOCAL_CREDENTIAL_ENV: deps.vllmLocalCredentialEnv, getManagedVllmProviderBinding: - deps.getManagedVllmProviderBinding ?? getManagedDualStationVllmProviderBinding, + deps.getManagedVllmProviderBinding ?? getManagedVllmProviderBinding, }, ); if (outcome.done) return outcome.result; diff --git a/src/lib/onboard/setup-nim-vllm.test.ts b/src/lib/onboard/setup-nim-vllm.test.ts index 822e0a2cf0d..5041cfe56b8 100644 --- a/src/lib/onboard/setup-nim-vllm.test.ts +++ b/src/lib/onboard/setup-nim-vllm.test.ts @@ -40,7 +40,7 @@ function deps(overrides: Partial = {}): SetupNimVllmDeps { applyVllmRuntimeContextWindow: vi.fn(), isDgxSparkHost: () => false, isNemoClawManagedVllmRunning: () => false, - persistConfiguredDualStationVllmRuntimeReceipt: async () => ({ + persistConfiguredManagedVllmRuntimeReceipt: async () => ({ ok: true, persisted: true, }), @@ -130,7 +130,7 @@ describe("setupNim vLLM route containment", () => { .flat() .join("\n"); expect(renderedOutput).not.toContain(apiKey); - expect(renderedOutput).toContain("Using managed dual-Station vLLM endpoint"); + expect(renderedOutput).toContain("Using managed vLLM endpoint"); expect(renderedOutput).not.toContain("localhost:8000"); }); @@ -154,7 +154,7 @@ describe("setupNim vLLM route containment", () => { await expect(handler(selection)).rejects.toThrow("exit 1"); expect(validateOpenAiLikeSelection).not.toHaveBeenCalled(); expect(console.error).toHaveBeenCalledWith( - " To install 'required/model', stop the managed dual-Station vLLM deployment, then rerun the original install/onboard command.", + " To install 'required/model', stop the managed vLLM deployment, then rerun the original install/onboard command.", ); expect(vi.mocked(console.error).mock.calls.flat().join("\n")).not.toContain("localhost"); }); @@ -166,7 +166,7 @@ describe("setupNim vLLM route containment", () => { deps({ runCapture, getManagedVllmProviderBinding: () => { - throw new Error("Managed dual-Station vLLM authentication is missing."); + throw new Error("Managed vLLM authentication is missing."); }, queryVllmModels, }), @@ -181,7 +181,7 @@ describe("setupNim vLLM route containment", () => { }); it("persists cleanup ownership after validating a managed dual endpoint", async () => { - const persistConfiguredDualStationVllmRuntimeReceipt = vi.fn(async () => ({ + const persistConfiguredManagedVllmRuntimeReceipt = vi.fn(async () => ({ ok: true as const, persisted: true, })); @@ -192,12 +192,12 @@ describe("setupNim vLLM route containment", () => { apiKey: "a".repeat(64), }), queryVllmModels: () => JSON.stringify({ data: [{ id: "served/model" }] }), - persistConfiguredDualStationVllmRuntimeReceipt, + persistConfiguredManagedVllmRuntimeReceipt, }), ); await expect(handler(state(null))).resolves.toBe("selected"); - expect(persistConfiguredDualStationVllmRuntimeReceipt).toHaveBeenCalledOnce(); + expect(persistConfiguredManagedVllmRuntimeReceipt).toHaveBeenCalledOnce(); }); it("fails closed when managed dual cleanup ownership cannot be persisted", async () => { @@ -208,7 +208,7 @@ describe("setupNim vLLM route containment", () => { apiKey: "a".repeat(64), }), queryVllmModels: () => JSON.stringify({ data: [{ id: "served/model" }] }), - persistConfiguredDualStationVllmRuntimeReceipt: async () => ({ + persistConfiguredManagedVllmRuntimeReceipt: async () => ({ ok: false, reason: "pair identity changed", }), @@ -217,7 +217,7 @@ describe("setupNim vLLM route containment", () => { await expect(handler(state(null))).rejects.toThrow("exit 1"); expect(console.error).toHaveBeenCalledWith( - " Managed dual-Station cleanup ownership could not be persisted: pair identity changed", + " Managed vLLM cleanup ownership could not be persisted: pair identity changed", ); }); @@ -229,7 +229,7 @@ describe("setupNim vLLM route containment", () => { apiKey: "a".repeat(64), }), queryVllmModels: () => JSON.stringify({ data: [{ id: "served/model" }] }), - persistConfiguredDualStationVllmRuntimeReceipt: async () => ({ + persistConfiguredManagedVllmRuntimeReceipt: async () => ({ ok: true, persisted: false, }), @@ -238,7 +238,7 @@ describe("setupNim vLLM route containment", () => { await expect(handler(state(null))).rejects.toThrow("exit 1"); expect(console.error).toHaveBeenCalledWith( - " Managed dual-Station cleanup ownership could not be persisted: the managed dual-Station cleanup receipt was not written", + " Managed vLLM cleanup ownership could not be persisted: the managed cleanup receipt was not written", ); }); diff --git a/src/lib/onboard/setup-nim-vllm.ts b/src/lib/onboard/setup-nim-vllm.ts index 58fbce3c5de..4459c252146 100644 --- a/src/lib/onboard/setup-nim-vllm.ts +++ b/src/lib/onboard/setup-nim-vllm.ts @@ -50,7 +50,7 @@ export interface SetupNimVllmDeps { applyVllmRuntimeContextWindow(models: VllmModels, model: string): void; isDgxSparkHost?: () => boolean; isNemoClawManagedVllmRunning?: () => boolean; - persistConfiguredDualStationVllmRuntimeReceipt(): Promise< + persistConfiguredManagedVllmRuntimeReceipt(): Promise< | { ok: true; persisted: boolean; @@ -78,7 +78,7 @@ async function managedVllmValidationOptions(baseUrl: string, apiKey: string) { trustedPrivateHosts: [hostname], }); if (!preflight.ok || !preflight.trustedPrivateCapability) { - throw new Error("Managed dual-Station vLLM endpoint authorization failed."); + throw new Error("Managed vLLM endpoint authorization failed."); } return { apiKey, @@ -257,10 +257,10 @@ export function createSetupNimVllmHandler( } const apiKey = managedBinding?.apiKey ?? null; - const managedDualEndpoint = managedBinding != null; + const managedEndpoint = managedBinding != null; console.log( - managedDualEndpoint - ? " ✓ Using managed dual-Station vLLM endpoint" + managedEndpoint + ? " ✓ Using managed vLLM endpoint" : ` ✓ Using existing vLLM on localhost:${deps.VLLM_PORT}`, ); const raw = apiKey @@ -273,8 +273,8 @@ export function createSetupNimVllmHandler( models = JSON.parse(raw); } catch { console.error( - managedDualEndpoint - ? " Could not query the managed dual-Station vLLM models endpoint. Is the deployment running and reachable?" + managedEndpoint + ? " Could not query the managed vLLM models endpoint. Is the deployment running and reachable?" : ` Could not query vLLM models endpoint. Is vLLM running on localhost:${deps.VLLM_PORT}?`, ); deps.exitProcess(1); @@ -295,15 +295,15 @@ export function createSetupNimVllmHandler( requiredModel && detectedModel !== requiredModel && (options.managedInstall === true || - managedDualEndpoint || + managedEndpoint || !reportedModelMatchesRequest(models, detectedModel, requiredModel)) ) { console.error( ` Detected vLLM model '${detectedModel}' does not match the shared gateway route '${requiredModel}'.`, ); console.error( - managedDualEndpoint - ? ` To install '${requiredModel}', stop the managed dual-Station vLLM deployment, then rerun the original install/onboard command.` + managedEndpoint + ? ` To install '${requiredModel}', stop the managed vLLM deployment, then rerun the original install/onboard command.` : ` To install '${requiredModel}', stop the existing vLLM server on localhost:${deps.VLLM_PORT}, then rerun the original install/onboard command.`, ); console.error(` To keep '${detectedModel}' instead, start detailed setup:`); @@ -363,13 +363,11 @@ export function createSetupNimVllmHandler( return "retry-selection"; } - if (managedDualEndpoint) { - const receipt = await deps.persistConfiguredDualStationVllmRuntimeReceipt(); + if (managedEndpoint) { + const receipt = await deps.persistConfiguredManagedVllmRuntimeReceipt(); if (!receipt.ok || !receipt.persisted) { - const reason = receipt.ok - ? "the managed dual-Station cleanup receipt was not written" - : receipt.reason; - console.error(` Managed dual-Station cleanup ownership could not be persisted: ${reason}`); + const reason = receipt.ok ? "the managed cleanup receipt was not written" : receipt.reason; + console.error(` Managed vLLM cleanup ownership could not be persisted: ${reason}`); deps.exitProcess(1); } } diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index 86390a961a1..e38c21df53e 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -46,6 +46,14 @@ function runTests(...tests: string[]): () => string[] { } export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ + { + pattern: /(?:^|\/)managed-inference\/(?:presets|recipes|schemas)\/[^/]+\.(?:json|yaml)$/, + testsToRun: runTests( + "src/lib/inference/serving/catalog.test.ts", + "src/lib/inference/serving/resolver.test.ts", + "test/managed-inference-catalog-compiler.test.ts", + ), + }, { pattern: /(?:^|\/)(?:Dockerfile|agents\/(?:hermes|langchain-deepagents-code)\/Dockerfile)$/, testsToRun: runTests("src/lib/onboard/managed-startup-profile.test.ts"), diff --git a/test/install-express-prompt.test.ts b/test/install-express-prompt.test.ts index b93454393a0..53a9350afa6 100644 --- a/test/install-express-prompt.test.ts +++ b/test/install-express-prompt.test.ts @@ -293,11 +293,11 @@ DGX_COMMIT_ID="d0e99cc"\nDGX_PLATFORM="DGX Server for GALAXY-GB300" expect(result.status, output).toBe(0); expect(output).toMatch(/Detected DGX Spark/); expect(output).toMatch( - /Express install will configure managed local vLLM using the DGX Spark profile default model/, - ); - expect(output).toMatch( - /Managed vLLM pulls the configured vLLM image\/model and runs a local vLLM inference container/, + /Express install will configure managed vLLM with automatic DGX Spark serving-profile selection/, ); + expect(output).toMatch(/one exactly qualified pretrusted two-Spark topology/); + expect(output).toMatch(/related or ambiguous setup remains untouched and stops installation/); + expect(output).toMatch(/experimental pending physical end-to-end validation/); expect(output).toMatch(/Sandbox name: my-assistant/); expect(output).toMatch(/Sandbox policy: suggested mode, tier 'balanced'/); expect(output).toMatch(/Run express install/); @@ -318,9 +318,8 @@ DGX_COMMIT_ID="d0e99cc"\nDGX_PLATFORM="DGX Server for GALAXY-GB300" expect(output).toMatch( /Express install will configure managed local vLLM with model custom-qwen3\.6/, ); - expect(output).toMatch( - /Managed vLLM pulls the configured vLLM image\/model and runs a local vLLM inference container/, - ); + expect(output).toMatch(/The explicit model remains authoritative/); + expect(output).toMatch(/keeps the existing single-Spark profile/); expect(output).toMatch( /RESULT NON_INTERACTIVE=1 SUDO_MODE=prompt PROVIDER=install-vllm MODEL= VLLM_MODEL=custom-qwen3\.6 POLICY=suggested YES=1 SANDBOX=my-assistant/, ); diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts new file mode 100644 index 00000000000..4383526b43e --- /dev/null +++ b/test/managed-inference-catalog-compiler.test.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { + compileManagedInferenceCatalogSources, + type ManagedInferenceCatalogSource, +} from "../scripts/managed-inference/compile-catalog.mts"; + +const REPOSITORY_ROOT = fileURLToPath(new URL("..", import.meta.url)); +const PRESET_PATH = + "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml"; +const RECIPE_PATH = "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml"; +function source(sourcePath: string): ManagedInferenceCatalogSource { + return { + path: sourcePath, + contents: fs.readFileSync(path.join(REPOSITORY_ROOT, sourcePath), "utf8"), + }; +} + +function catalogSources(): ManagedInferenceCatalogSource[] { + return [source(PRESET_PATH), source(RECIPE_PATH)]; +} + +function replaceSource( + sources: readonly ManagedInferenceCatalogSource[], + sourcePath: string, + replace: (contents: string) => string, +): ManagedInferenceCatalogSource[] { + return sources.map((item) => + item.path === sourcePath ? { ...item, contents: replace(item.contents) } : item, + ); +} + +describe("managed inference catalog compiler", () => { + it("produces identical canonical JSON regardless of source enumeration order", () => { + const sources = catalogSources(); + + expect(compileManagedInferenceCatalogSources(sources).json).toBe( + compileManagedInferenceCatalogSources(sources.reverse()).json, + ); + }); + + it("rejects an unknown recipe field", () => { + const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => + contents.replace(" backend: vllm", " backend: vllm\n unsupportedField: true"), + ); + + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/additional properties/u); + }); + + it("rejects a mutable runtime image reference", () => { + const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => + contents.replace( + /ghcr\.io\/anemll\/dspark-vllm-gx10@sha256:[0-9a-f]{64}/u, + "ghcr.io/anemll/dspark-vllm-gx10:0.1.1", + ), + ); + + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/schema validation/u); + }); + + it("requires a new recipe ID for any material contract change", () => { + const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => + contents.replace(" NCCL_DEBUG: WARN", " NCCL_DEBUG: INFO"), + ); + + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( + /contract changed without a new recipe ID/u, + ); + }); + + it.each([ + "--node-rank", + "--headless", + "--host", + ])("rejects materializer-owned serving argument %s", (argument) => { + const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => + contents.replace(" - name: --port", ` - name: ${argument}\n - name: --port`), + ); + + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( + new RegExp(`materializer-owned argument ${argument}`), + ); + }); + + it("rejects an unresolved preset recipe reference", () => { + const sources = replaceSource(catalogSources(), PRESET_PATH, (contents) => + contents.replace( + "recipeRef: vllm.deepseek-v4-flash-0731.spark-dual.v1", + "recipeRef: vllm.missing.recipe", + ), + ); + + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( + /references unknown recipe/u, + ); + }); +}); diff --git a/test/vitest-watch-triggers.test.ts b/test/vitest-watch-triggers.test.ts index 599426fe744..d5232efe5bf 100644 --- a/test/vitest-watch-triggers.test.ts +++ b/test/vitest-watch-triggers.test.ts @@ -48,6 +48,7 @@ const E2E_WORKFLOW_CONTRACTS = [ ] as const; const OPAQUE_INPUTS = [ + "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml", "Dockerfile", "agents/hermes/Dockerfile", "agents/langchain-deepagents-code/Dockerfile", @@ -86,6 +87,13 @@ describe("Vitest opaque-input watch triggers", () => { }); it("maps current opaque inputs to their direct contract tests (#6692)", () => { + expect( + triggeredBy("managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml"), + ).toEqual([ + "src/lib/inference/serving/catalog.test.ts", + "src/lib/inference/serving/resolver.test.ts", + "test/managed-inference-catalog-compiler.test.ts", + ]); expect(triggeredBy("Dockerfile")).toEqual(["src/lib/onboard/managed-startup-profile.test.ts"]); expect(triggeredBy("agents/hermes/Dockerfile")).toEqual([ "src/lib/onboard/managed-startup-profile.test.ts", From ad4daa52bd2409cbf933a4d4cb2bac41f2c63b3b Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 07:39:22 -0700 Subject: [PATCH 02/27] refactor(inference): make serving profiles catalog-driven Signed-off-by: Aaron Erickson --- .../set-up-vllm-on-two-dgx-sparks.mdx | 10 +- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 3 +- docs/reference/host-files-and-state.mdx | 2 +- ...park-gb10.dual.deepseek-v4-flash-0731.yaml | 46 ++ ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 42 +- managed-inference/schemas/catalog.schema.json | 3 + managed-inference/schemas/preset.schema.json | 121 ++-- managed-inference/schemas/recipe.schema.json | 215 ++++-- package.json | 2 +- scripts/managed-inference/compile-catalog.mts | 187 ++++-- src/lib/actions/uninstall/run-plan.ts | 16 +- .../serving/adapter-registry.test.ts | 267 ++++++++ src/lib/inference/serving/adapter-registry.ts | 464 +++++++++++++ src/lib/inference/serving/catalog-types.ts | 161 +++-- src/lib/inference/serving/catalog.test.ts | 69 +- src/lib/inference/serving/catalog.ts | 185 +++++- .../dual-spark-discovery-production.ts | 59 +- .../serving/dual-spark-discovery.test.ts | 178 +++-- .../inference/serving/dual-spark-discovery.ts | 117 ++-- .../serving/dual-spark-executor.test.ts | 326 +++++++--- .../inference/serving/dual-spark-executor.ts | 216 +++--- .../dual-spark-fixture.test-support.ts | 18 +- .../serving/dual-spark-installer.test.ts | 262 +++++++- .../inference/serving/dual-spark-installer.ts | 265 ++++++-- .../serving/dual-spark-lifecycle.test.ts | 61 +- .../inference/serving/dual-spark-lifecycle.ts | 5 +- .../serving/dual-spark-materialize.test.ts | 403 +++++++++--- .../serving/dual-spark-materialize.ts | 613 +++++++++++++----- .../serving/dual-spark-preparation.test.ts | 112 ++++ .../serving/dual-spark-preparation.ts | 200 ++++++ .../serving/dual-spark-topology.test.ts | 77 ++- .../inference/serving/dual-spark-topology.ts | 41 +- .../inference/serving/generated/catalog.json | 141 +++- src/lib/inference/serving/resolver.test.ts | 462 +++++++++++-- src/lib/inference/serving/resolver.ts | 478 +++++++++++--- .../serving/spark-runtime-receipt.ts | 4 - .../vllm-spark-runtime-receipt.test.ts | 56 +- ...managed-inference-catalog-compiler.test.ts | 468 +++++++++++-- 38 files changed, 5091 insertions(+), 1264 deletions(-) create mode 100644 src/lib/inference/serving/adapter-registry.test.ts create mode 100644 src/lib/inference/serving/adapter-registry.ts create mode 100644 src/lib/inference/serving/dual-spark-preparation.test.ts create mode 100644 src/lib/inference/serving/dual-spark-preparation.ts diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx index 6130456437d..148492b470e 100644 --- a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -28,8 +28,8 @@ It does not scan a subnet, add SSH host keys, add authorized keys, or change SSH Both derived addresses must already have strict public-key SSH trust. They must identify the same physical peer and the same SSH host key. The detector performs read-only host probes only through that pinned identity. -After you confirm setup, NemoClaw repeats the read-only pair qualification and then writes an owner-only temporary SSH binding at `/dual-spark-managed-serving.json.ssh-binding/` for the install transaction. -The selected state root is `~/.nemoclaw/` for the default gateway or `~/.nemoclaw/gateways//` for a non-default gateway. +After you confirm setup, NemoClaw repeats the read-only pair qualification and then writes an owner-only temporary SSH binding at `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` for the install transaction. +This claim is host-global and shared by every gateway on the host. Declining setup creates no binding. After confirmation, NemoClaw attempts to remove the binding when setup fails or the durable runtime receipt is committed. If cleanup cannot be confirmed and the claim remains without a durable runtime receipt, a new managed-vLLM install stops before mutation and preserves the claim for explicit recovery or removal. @@ -80,7 +80,7 @@ For a cold cache, each system needs these approximate capacities: | Docker storage | `32.584 GB` | Three times the `9.788 GB` compressed image size plus a `3.221 GB` staging reserve. | | Shared filesystem | `203.520 GB` | The combined cold-cache requirement when both paths share one filesystem. | -An exact cached image or exact pinned model snapshot removes its corresponding download requirement. +NemoClaw reserves the selected recipe's full declared image and model download sizes, staging capacity, and writable allowance even when the exact artifacts are cached. An unavailable capacity, ownership, directory, writability, or inode result leaves the two-node profile unqualified. ## Restrict Network Access @@ -163,6 +163,10 @@ The explicit target still must match the exact reciprocal rail topology. ## Understand the Distributed Runtime +The compiled managed inference catalog reads profile selection, artifacts, runtime resources, serving arguments, preparation, and readiness checks from preset and recipe YAML. +Maintainers can add another profile that uses the registered dual-Spark topology, materializer, lifecycle, and preparation adapters by adding preset and recipe YAML without TypeScript changes. +A profile that needs a different execution contract requires a registered adapter. + The compiled profile pins these artifacts: - The image is `ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8`. diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index efcf75e2af2..547c080763e 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -44,7 +44,8 @@ During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first r It then removes only both exact receipt-owned containers. The dual-DGX Spark receipt is host-global under `~/.nemoclaw/`, while a dual-DGX Station receipt uses the selected gateway state root. Only after that pair cleanup succeeds does NemoClaw start the remaining full-uninstall steps. -If an interrupted dual-DGX Spark transaction leaves `/dual-spark-managed-serving.json.ssh-binding/` without a durable runtime receipt, full uninstall fails closed before cleanup or other mutation and preserves the claim for explicit recovery or removal. +If an interrupted dual-DGX Spark transaction leaves `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` without a durable runtime receipt, full uninstall fails closed before cleanup or other mutation and preserves the claim for explicit recovery or removal. +This temporary claim is host-global regardless of the selected gateway. If validation or pair cleanup fails, uninstall exits nonzero and keeps the receipt so you can resolve the reported SSH, Docker, or peer-host error and retry. Pair cleanup can partially complete before an error, so inspect both systems before retrying. When sibling gateways remain, it removes only the selected gateway's resources and port-scoped state and preserves those shared host resources. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index 708fc26a3a4..874d526e185 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -37,7 +37,7 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by NemoClaw-managed distributed vLLM profiles. | No while a managed distributed runtime exists. Full uninstall removes it only after managed runtime cleanup succeeds and no sibling gateway remains. | | `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, and container identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | | `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded DGX Spark worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds. | -| `/dual-spark-managed-serving.json.ssh-binding/` | Owner-only temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. Gateway-scoped uninstall preserves it. | +| `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. Gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | diff --git a/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml index 7cf41c71891..cdd31be7006 100644 --- a/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml +++ b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml @@ -10,6 +10,7 @@ metadata: spec: selection: automatic + priority: 400 requirements: all: @@ -18,6 +19,51 @@ spec: kind: qualification id: host.platform.dgx_spark status: qualified + - readiness: + scope: everyNode + kind: capability + id: host.platform.supported + state: present + - readiness: + scope: everyNode + kind: capability + id: host.platform.dgx_spark + state: present + - readiness: + scope: everyNode + kind: capability + id: host.docker.available + state: present + - readiness: + scope: everyNode + kind: capability + id: host.docker.daemon_reachable + state: present + - readiness: + scope: everyNode + kind: capability + id: host.docker.runtime_supported + state: present + - readiness: + scope: everyNode + kind: capability + id: host.docker.storage_compatible + state: present + - readiness: + scope: everyNode + kind: capability + id: host.gpu.nvidia_available + state: present + - readiness: + scope: everyNode + kind: capability + id: host.gpu.container_toolkit_available + state: present + - readiness: + scope: everyNode + kind: capability + id: host.gpu.cdi_healthy + state: present - fact: cluster.nodeCount state: present operator: equals diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml index 46b2f783590..1e5c008c380 100644 --- a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -23,8 +23,27 @@ spec: revision: 9e165c30e2704aec5d9d593cce3eebd58bbef1cb servedName: deepseek-v4-flash-0731 downloadSizeBytes: 166898661074 - preparationRef: deepseek-v4-flash-0731/v1 - encodingPath: encoding/encoding_dsv4.py + gated: false + installFastSafetensors: false + preparation: + ref: snapshot-copy-and-exact-text-replacement/v1 + snapshotCopy: + sourcePath: encoding/encoding_dsv4.py + targetPath: /usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py + exactTextReplacement: + targetPath: /usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py + expectedText: |- + elif reasoning_effort in ("max", "xhigh"): + reasoning_effort = "max" + else: + reasoning_effort = "high" + replacementText: |- + elif reasoning_effort in ("max", "xhigh"): + reasoning_effort = "max" + elif reasoning_effort == "high": + reasoning_effort = "high" + else: + reasoning_effort = "low" runtime: image: ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8 @@ -32,9 +51,26 @@ spec: architecture: arm64 networkMode: host ipcMode: host + gpuRequest: all sharedMemoryBytes: 68719476736 + pullTimeoutSeconds: 43200 devices: - /dev/infiniband + ulimits: + memlock: -1 + stackBytes: 67108864 + modelCache: + source: huggingface-cache + target: /cache/huggingface + temporaryFilesystems: + - target: /cache/huggingface + sizeBytes: 17179869184 + mode: "0700" + options: [rw, nosuid, nodev, exec] + - target: /tmp + sizeBytes: 17179869184 + mode: "1777" + options: [rw, nosuid, nodev, exec] environment: CUTE_DSL_ARCH: sm_121a DG_JIT_NVCC_COMPILER: /usr/local/cuda/bin/nvcc @@ -42,7 +78,6 @@ spec: FLASHINFER_CUDA_ARCH_LIST: 12.1a FLASHINFER_DISABLE_VERSION_CHECK: "1" FLASHINFER_WORKSPACE_BASE: /cache/huggingface/flashinfer - HF_HOME: /cache/huggingface HF_HUB_DISABLE_XET: "1" HF_HUB_OFFLINE: "1" NCCL_CROSS_NIC: "1" @@ -77,6 +112,7 @@ spec: serve: authentication: bearer + executable: /usr/local/bin/vllm arguments: - name: --port value: 8000 diff --git a/managed-inference/schemas/catalog.schema.json b/managed-inference/schemas/catalog.schema.json index 49c9178f856..d3a51fac651 100644 --- a/managed-inference/schemas/catalog.schema.json +++ b/managed-inference/schemas/catalog.schema.json @@ -9,6 +9,7 @@ "compilerVersion": { "const": "1.0.0" }, "presets": { "type": "array", + "minItems": 1, "items": { "allOf": [ { "$ref": "#/$defs/compiledDefinition" }, @@ -23,6 +24,7 @@ }, "recipes": { "type": "array", + "minItems": 1, "items": { "allOf": [ { "$ref": "#/$defs/compiledDefinition" }, @@ -38,6 +40,7 @@ "schemaVersion": { "const": "1.0.0" }, "sourceFiles": { "type": "array", + "minItems": 2, "items": { "type": "object", "required": ["digest", "path"], diff --git a/managed-inference/schemas/preset.schema.json b/managed-inference/schemas/preset.schema.json index 4618248dd6c..c49b8d0e1bd 100644 --- a/managed-inference/schemas/preset.schema.json +++ b/managed-inference/schemas/preset.schema.json @@ -10,9 +10,10 @@ "metadata": { "$ref": "#/$defs/metadata" }, "spec": { "type": "object", - "required": ["selection", "requirements", "plan"], + "required": ["selection", "priority", "requirements", "plan"], "properties": { - "selection": { "const": "automatic" }, + "selection": { "enum": ["automatic", "explicit-only", "disabled"] }, + "priority": { "type": "integer", "minimum": -1000000, "maximum": 1000000 }, "requirements": { "type": "object", "required": ["all"], @@ -20,9 +21,11 @@ "all": { "type": "array", "minItems": 1, + "maxItems": 128, "items": { "oneOf": [ - { "$ref": "#/$defs/readinessRequirement" }, + { "$ref": "#/$defs/readinessQualificationRequirement" }, + { "$ref": "#/$defs/readinessStateRequirement" }, { "$ref": "#/$defs/factRequirement" }, { "$ref": "#/$defs/topologyRequirement" } ] @@ -35,31 +38,14 @@ "type": "object", "required": ["backend", "recipeRef", "bindings"], "properties": { - "backend": { "const": "vllm" }, + "backend": { "$ref": "#/$defs/token" }, "recipeRef": { "$ref": "#/$defs/stableId" }, "bindings": { "type": "object", - "required": ["sparkTopology"], - "properties": { - "sparkTopology": { - "type": "object", - "required": ["valueFromTopologyQualification"], - "properties": { - "valueFromTopologyQualification": { - "type": "object", - "required": ["id", "schemaVersion", "output"], - "properties": { - "id": { "const": "dgx-spark.gb10.dual-cx7" }, - "schemaVersion": { "const": 1 }, - "output": { "const": "topology" } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false + "minProperties": 1, + "maxProperties": 16, + "propertyNames": { "$ref": "#/$defs/bindingName" }, + "additionalProperties": { "$ref": "#/$defs/presetTopologyBinding" } } }, "additionalProperties": false @@ -81,10 +67,24 @@ }, "stableId": { "type": "string", - "pattern": "^[a-z][a-z0-9]*(?:[._/-][a-z0-9]+)+$", - "maxLength": 160 + "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]{0,159}$" }, - "readinessRequirement": { + "bindingName": { + "type": "string", + "pattern": "^[a-z][A-Za-z0-9]{0,63}$" + }, + "token": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" + }, + "scope": { + "enum": ["everyNode", "anyNode"] + }, + "state": { + "type": "string", + "pattern": "^[a-z][a-z0-9._-]{0,63}$" + }, + "readinessQualificationRequirement": { "type": "object", "required": ["readiness"], "properties": { @@ -92,10 +92,28 @@ "type": "object", "required": ["scope", "kind", "id", "status"], "properties": { - "scope": { "const": "everyNode" }, + "scope": { "$ref": "#/$defs/scope" }, "kind": { "const": "qualification" }, - "id": { "const": "host.platform.dgx_spark" }, - "status": { "const": "qualified" } + "id": { "$ref": "#/$defs/stableId" }, + "status": { "$ref": "#/$defs/state" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "readinessStateRequirement": { + "type": "object", + "required": ["readiness"], + "properties": { + "readiness": { + "type": "object", + "required": ["scope", "kind", "id", "state"], + "properties": { + "scope": { "$ref": "#/$defs/scope" }, + "kind": { "enum": ["observation", "capability"] }, + "id": { "$ref": "#/$defs/stableId" }, + "state": { "$ref": "#/$defs/state" } }, "additionalProperties": false } @@ -106,10 +124,20 @@ "type": "object", "required": ["fact", "state", "operator", "value"], "properties": { - "fact": { "const": "cluster.nodeCount" }, - "state": { "const": "present" }, - "operator": { "const": "equals" }, - "value": { "type": "integer", "minimum": 1 } + "fact": { "$ref": "#/$defs/stableId" }, + "state": { "enum": ["present", "absent"] }, + "operator": { "enum": ["equals", "oneOf", "atLeast", "atMost", "between"] }, + "value": { + "oneOf": [ + { "type": ["string", "number", "boolean"] }, + { + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": { "type": ["string", "number", "boolean"] } + } + ] + } }, "additionalProperties": false }, @@ -121,9 +149,26 @@ "type": "object", "required": ["id", "schemaVersion", "status"], "properties": { - "id": { "const": "dgx-spark.gb10.dual-cx7" }, - "schemaVersion": { "const": 1 }, - "status": { "const": "qualified" } + "id": { "$ref": "#/$defs/stableId" }, + "schemaVersion": { "type": "integer", "minimum": 1 }, + "status": { "$ref": "#/$defs/state" } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "presetTopologyBinding": { + "type": "object", + "required": ["valueFromTopologyQualification"], + "properties": { + "valueFromTopologyQualification": { + "type": "object", + "required": ["id", "schemaVersion", "output"], + "properties": { + "id": { "$ref": "#/$defs/stableId" }, + "schemaVersion": { "type": "integer", "minimum": 1 }, + "output": { "$ref": "#/$defs/token" } }, "additionalProperties": false } diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json index a8ae01dd7ac..a1d2abcc2f9 100644 --- a/managed-inference/schemas/recipe.schema.json +++ b/managed-inference/schemas/recipe.schema.json @@ -12,59 +12,79 @@ "type": "object", "required": ["backend", "bindings", "model", "runtime", "execution", "serve", "readiness"], "properties": { - "backend": { "const": "vllm" }, + "backend": { "$ref": "#/$defs/token" }, "bindings": { "type": "object", - "required": ["sparkTopology"], - "properties": { - "sparkTopology": { - "type": "object", - "required": ["type", "qualificationId", "schemaVersion", "outputSchema"], - "properties": { - "type": { "const": "topologyQualificationOutput" }, - "qualificationId": { "const": "dgx-spark.gb10.dual-cx7" }, - "schemaVersion": { "const": 1 }, - "outputSchema": { "const": "nemoclaw.nvidia.com/dual-spark-topology/v1" } - }, - "additionalProperties": false - } - }, - "additionalProperties": false + "minProperties": 1, + "maxProperties": 16, + "propertyNames": { "$ref": "#/$defs/bindingName" }, + "additionalProperties": { "$ref": "#/$defs/topologyBinding" } }, "model": { "type": "object", - "required": ["id", "revision", "servedName", "downloadSizeBytes", "preparationRef", "encodingPath"], + "required": ["id", "revision", "servedName", "downloadSizeBytes", "gated", "installFastSafetensors", "preparation"], "properties": { - "id": { "type": "string", "pattern": "^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$" }, - "revision": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "id": { "type": "string", "pattern": "^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$", "maxLength": 256 }, + "revision": { "type": "string", "pattern": "^[0-9a-f]{40,64}$" }, "servedName": { "$ref": "#/$defs/stableId" }, - "downloadSizeBytes": { "type": "integer", "minimum": 1 }, - "preparationRef": { "const": "deepseek-v4-flash-0731/v1" }, - "encodingPath": { "const": "encoding/encoding_dsv4.py" } + "downloadSizeBytes": { "$ref": "#/$defs/positiveSafeInteger" }, + "gated": { "type": "boolean" }, + "installFastSafetensors": { "type": "boolean" }, + "preparation": { "$ref": "#/$defs/modelPreparation" } }, "additionalProperties": false }, "runtime": { "type": "object", - "required": ["image", "imageDownloadSizeBytes", "architecture", "networkMode", "ipcMode", "sharedMemoryBytes", "devices", "environment"], + "required": ["image", "imageDownloadSizeBytes", "pullTimeoutSeconds", "architecture", "networkMode", "ipcMode", "sharedMemoryBytes", "gpuRequest", "devices", "ulimits", "modelCache", "temporaryFilesystems", "environment"], "properties": { - "image": { "type": "string", "pattern": "^[a-z0-9.-]+(?:/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$" }, - "imageDownloadSizeBytes": { "type": "integer", "minimum": 1 }, - "architecture": { "const": "arm64" }, - "networkMode": { "const": "host" }, - "ipcMode": { "const": "host" }, - "sharedMemoryBytes": { "type": "integer", "minimum": 1 }, + "image": { "type": "string", "pattern": "^[a-z0-9.-]+(?::[0-9]+)?(?:/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$", "maxLength": 1024 }, + "imageDownloadSizeBytes": { "$ref": "#/$defs/positiveSafeInteger" }, + "pullTimeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 86400 }, + "architecture": { "$ref": "#/$defs/token" }, + "networkMode": { "$ref": "#/$defs/token" }, + "ipcMode": { "$ref": "#/$defs/token" }, + "sharedMemoryBytes": { "$ref": "#/$defs/positiveSafeInteger" }, + "gpuRequest": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._,:=-]{0,255}$" }, "devices": { "type": "array", - "minItems": 1, + "maxItems": 32, "uniqueItems": true, - "items": { "type": "string", "pattern": "^/dev/[A-Za-z0-9._/-]+$" } + "items": { "$ref": "#/$defs/absolutePath" } + }, + "ulimits": { + "type": "object", + "required": ["memlock", "stackBytes"], + "properties": { + "memlock": { + "oneOf": [ + { "type": "integer", "minimum": -1, "maximum": 9007199254740991 }, + { "type": "string", "enum": ["unlimited"] } + ] + }, + "stackBytes": { "$ref": "#/$defs/positiveSafeInteger" } + }, + "additionalProperties": false + }, + "modelCache": { + "type": "object", + "required": ["source", "target"], + "properties": { + "source": { "$ref": "#/$defs/stableId" }, + "target": { "$ref": "#/$defs/absolutePath" } + }, + "additionalProperties": false + }, + "temporaryFilesystems": { + "type": "array", + "maxItems": 16, + "items": { "$ref": "#/$defs/temporaryFilesystem" } }, "environment": { "type": "object", - "minProperties": 1, - "propertyNames": { "pattern": "^[A-Z][A-Z0-9_]*$" }, - "additionalProperties": { "type": "string", "maxLength": 1024 } + "maxProperties": 128, + "propertyNames": { "pattern": "^[A-Z][A-Z0-9_]{0,127}$" }, + "additionalProperties": { "type": "string", "maxLength": 4096 } } }, "additionalProperties": false @@ -73,30 +93,37 @@ "type": "object", "required": ["materializerRef", "lifecycleRef", "topologyBinding", "nodeCount", "tensorParallelSize", "pipelineParallelSize", "distributedExecutorBackend"], "properties": { - "materializerRef": { "const": "vllm.dual-dgx-spark/v1" }, - "lifecycleRef": { "const": "vllm.dual-dgx-spark/v1" }, - "topologyBinding": { "const": "sparkTopology" }, - "nodeCount": { "const": 2 }, - "tensorParallelSize": { "const": 2 }, - "pipelineParallelSize": { "const": 1 }, - "distributedExecutorBackend": { "const": "mp" } + "materializerRef": { "$ref": "#/$defs/stableId" }, + "lifecycleRef": { "$ref": "#/$defs/stableId" }, + "topologyBinding": { "$ref": "#/$defs/bindingName" }, + "nodeCount": { "type": "integer", "minimum": 1, "maximum": 1024 }, + "tensorParallelSize": { "type": "integer", "minimum": 1, "maximum": 1024 }, + "pipelineParallelSize": { "type": "integer", "minimum": 1, "maximum": 1024 }, + "distributedExecutorBackend": { "$ref": "#/$defs/token" } }, "additionalProperties": false }, "serve": { "type": "object", - "required": ["authentication", "arguments"], + "required": ["authentication", "executable", "arguments"], "properties": { - "authentication": { "const": "bearer" }, + "authentication": { "$ref": "#/$defs/token" }, + "executable": { "$ref": "#/$defs/absolutePath" }, "arguments": { "type": "array", - "minItems": 1, + "maxItems": 128, "items": { "type": "object", "required": ["name"], "properties": { - "name": { "type": "string", "pattern": "^--[a-z0-9]+(?:-[a-z0-9]+)*$" }, - "value": { "type": ["string", "number", "boolean"] } + "name": { "type": "string", "pattern": "^--[a-z0-9]+(?:-[a-z0-9]+)*$", "maxLength": 128 }, + "value": { + "oneOf": [ + { "type": "string", "maxLength": 16384 }, + { "type": "number", "minimum": -9007199254740991, "maximum": 9007199254740991 }, + { "type": "boolean" } + ] + } }, "additionalProperties": false } @@ -108,7 +135,7 @@ "type": "object", "required": ["timeoutSeconds", "expectedModel"], "properties": { - "timeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 7200 }, + "timeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 86400 }, "expectedModel": { "$ref": "#/$defs/stableId" } }, "additionalProperties": false @@ -123,15 +150,103 @@ "type": "object", "required": ["id", "displayName"], "properties": { - "id": { "const": "vllm.deepseek-v4-flash-0731.spark-dual.v1" }, + "id": { "$ref": "#/$defs/stableId" }, "displayName": { "type": "string", "minLength": 1, "maxLength": 128 } }, "additionalProperties": false }, "stableId": { "type": "string", - "pattern": "^[a-z][a-z0-9]*(?:[._/-][a-z0-9]+)+$", - "maxLength": 160 + "pattern": "^[A-Za-z0-9][A-Za-z0-9._/-]{0,159}$" + }, + "bindingName": { + "type": "string", + "pattern": "^[a-z][A-Za-z0-9]{0,63}$" + }, + "token": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" + }, + "positiveSafeInteger": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "absolutePath": { + "type": "string", + "pattern": "^/(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._+/-]+$", + "maxLength": 4096 + }, + "relativePath": { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._+/-]+$", + "maxLength": 4096 + }, + "topologyBinding": { + "type": "object", + "required": ["type", "qualificationId", "schemaVersion", "outputSchema"], + "properties": { + "type": { "const": "topologyQualificationOutput" }, + "qualificationId": { "$ref": "#/$defs/stableId" }, + "schemaVersion": { "type": "integer", "minimum": 1 }, + "outputSchema": { "$ref": "#/$defs/stableId" } + }, + "additionalProperties": false + }, + "modelPreparation": { + "oneOf": [ + { + "type": "object", + "required": ["ref"], + "properties": { + "ref": { "const": "none/v1" } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["ref", "snapshotCopy", "exactTextReplacement"], + "properties": { + "ref": { "const": "snapshot-copy-and-exact-text-replacement/v1" }, + "snapshotCopy": { + "type": "object", + "required": ["sourcePath", "targetPath"], + "properties": { + "sourcePath": { "$ref": "#/$defs/relativePath" }, + "targetPath": { "$ref": "#/$defs/absolutePath" } + }, + "additionalProperties": false + }, + "exactTextReplacement": { + "type": "object", + "required": ["targetPath", "expectedText", "replacementText"], + "properties": { + "targetPath": { "$ref": "#/$defs/absolutePath" }, + "expectedText": { "type": "string", "minLength": 1, "maxLength": 16384 }, + "replacementText": { "type": "string", "minLength": 1, "maxLength": 16384 } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] + }, + "temporaryFilesystem": { + "type": "object", + "required": ["target", "sizeBytes", "mode", "options"], + "properties": { + "target": { "$ref": "#/$defs/absolutePath" }, + "sizeBytes": { "$ref": "#/$defs/positiveSafeInteger" }, + "mode": { "type": "string", "pattern": "^[0-7]{4}$" }, + "options": { + "type": "array", + "maxItems": 8, + "uniqueItems": true, + "items": { "enum": ["rw", "ro", "nosuid", "nodev", "noexec", "exec", "noatime", "relatime"] } + } + }, + "additionalProperties": false } } } diff --git a/package.json b/package.json index 434e74223de..7f75f88f976 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "build:policy-boundary": "tsc -p nemoclaw/tsconfig.shared.json", "catalog:compile": "tsx scripts/managed-inference/compile-catalog.mts --write", "catalog:check": "tsx scripts/managed-inference/compile-catalog.mts", - "build:cli": "npm run catalog:check && npm run build:policy-boundary && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", + "build:cli": "npm run build:policy-boundary && tsc -p tsconfig.src.json && npm run catalog:check && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", "clean:cli": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", "typecheck:cli": "tsc -p tsconfig.cli.json", "validate:configs": "tsx scripts/validate-configs.mts", diff --git a/scripts/managed-inference/compile-catalog.mts b/scripts/managed-inference/compile-catalog.mts index 763b4b9862f..fb833087c80 100644 --- a/scripts/managed-inference/compile-catalog.mts +++ b/scripts/managed-inference/compile-catalog.mts @@ -13,14 +13,23 @@ import catalogSchema from "../../managed-inference/schemas/catalog.schema.json" }; import presetSchema from "../../managed-inference/schemas/preset.schema.json" with { type: "json" }; import recipeSchema from "../../managed-inference/schemas/recipe.schema.json" with { type: "json" }; +import * as adapterRegistryModule from "../../src/lib/inference/serving/adapter-registry.ts"; import * as catalogIntegrityModule from "../../src/lib/inference/serving/catalog-integrity.ts"; import type { CompiledManagedInferenceCatalog, + ManagedInferenceFactRequirement, ManagedInferenceServingPreset, ManagedInferenceServingRecipe, } from "../../src/lib/inference/serving/catalog-types.ts"; import * as catalogTypesModule from "../../src/lib/inference/serving/catalog-types.ts"; +const compatibleAdapterRegistryModule = adapterRegistryModule as unknown as { + default?: typeof adapterRegistryModule; +}; +const { + getManagedInferenceRecipeRegistrationError, + getManagedInferenceTopologyQualificationDescriptor, +} = compatibleAdapterRegistryModule.default ?? adapterRegistryModule; const compatibleCatalogIntegrityModule = catalogIntegrityModule as unknown as { default?: typeof catalogIntegrityModule; }; @@ -30,9 +39,6 @@ const compatibleCatalogTypesModule = catalogTypesModule as unknown as { default?: typeof catalogTypesModule; }; const { - DUAL_SPARK_PRESET_ID, - DUAL_SPARK_RECIPE_ID, - DUAL_SPARK_RECIPE_SPEC_DIGEST, isManagedInferenceMaterializerOwnedArgument, MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, @@ -104,13 +110,38 @@ function createValidators(): { }; } -function validateRecipeSemantics(recipe: ManagedInferenceServingRecipe): void { - if (recipe.metadata.id !== DUAL_SPARK_RECIPE_ID) { - throw new Error(`unsupported serving recipe ${recipe.metadata.id}`); +function factRequirementError(requirement: ManagedInferenceFactRequirement): string | undefined { + if (requirement.fact !== "cluster.nodeCount") { + return "unsupported selection fact"; + } + const { operator, value } = requirement; + const arrayValue = Array.isArray(value) ? value : null; + if (operator === "oneOf") { + return arrayValue && arrayValue.length > 0 + ? undefined + : "oneOf requires a non-empty value array"; + } + if (operator === "between") { + return arrayValue?.length === 2 && arrayValue.every((item) => typeof item === "number") + ? undefined + : "between requires exactly two numeric values"; + } + if (arrayValue) return `${operator} requires one scalar value`; + if ((operator === "atLeast" || operator === "atMost") && typeof value !== "number") { + return `${operator} requires one numeric value`; } + return undefined; +} + +function validateRecipeSemantics(recipe: ManagedInferenceServingRecipe): void { if (!SHA256.test(recipe.spec.runtime.image.slice(recipe.spec.runtime.image.indexOf("@") + 1))) { throw new Error(`${recipe.metadata.id} must pin its runtime image by sha256 digest`); } + if (!Object.hasOwn(recipe.spec.bindings, recipe.spec.execution.topologyBinding)) { + throw new Error( + `${recipe.metadata.id} references unknown topology binding ${recipe.spec.execution.topologyBinding}`, + ); + } const seenArguments = new Set(); for (const argument of recipe.spec.serve.arguments) { if (seenArguments.has(argument.name)) { @@ -121,63 +152,121 @@ function validateRecipeSemantics(recipe: ManagedInferenceServingRecipe): void { } seenArguments.add(argument.name); } - if (managedInferenceDigest(recipe.spec) !== DUAL_SPARK_RECIPE_SPEC_DIGEST) { - throw new Error(`${recipe.metadata.id} contract changed without a new recipe ID`); + const temporaryTargets = recipe.spec.runtime.temporaryFilesystems.map(({ target }) => target); + if (new Set(temporaryTargets).size !== temporaryTargets.length) { + throw new Error(`${recipe.metadata.id} contains duplicate temporary filesystem targets`); + } + for (const filesystem of recipe.spec.runtime.temporaryFilesystems) { + const options = new Set(filesystem.options); + if ( + (options.has("rw") && options.has("ro")) || + (options.has("exec") && options.has("noexec")) + ) { + throw new Error(`${recipe.metadata.id} contains conflicting temporary filesystem options`); + } + } + const registrationError = getManagedInferenceRecipeRegistrationError(recipe); + if (registrationError) { + throw new Error( + `${recipe.metadata.id} is incompatible with its registered adapters: ${registrationError}`, + ); } } +function sortedKeys(value: object): string[] { + return Object.keys(value).sort(compareStrings); +} + function validatePresetSemantics( preset: ManagedInferenceServingPreset, recipes: ReadonlyMap, ): void { - if (preset.metadata.id !== DUAL_SPARK_PRESET_ID) { - throw new Error(`unsupported serving preset ${preset.metadata.id}`); - } - if (preset.spec.selection !== "automatic") { - throw new Error(`${preset.metadata.id} must remain an automatic preset`); - } const recipe = recipes.get(preset.spec.plan.recipeRef); - if (!recipe) + if (!recipe) { throw new Error( `${preset.metadata.id} references unknown recipe ${preset.spec.plan.recipeRef}`, ); + } if (recipe.spec.backend !== preset.spec.plan.backend) { throw new Error(`${preset.metadata.id} backend does not match its recipe`); } - const readinessRequirements = preset.spec.requirements.all.filter( - (requirement) => "readiness" in requirement, - ); - const nodeCountRequirements = preset.spec.requirements.all.filter( - (requirement) => "fact" in requirement, - ); - const topologyRequirements = preset.spec.requirements.all.filter( - (requirement) => "topologyQualification" in requirement, - ); + const recipeBindingNames = sortedKeys(recipe.spec.bindings); + const presetBindingNames = sortedKeys(preset.spec.plan.bindings); if ( - readinessRequirements.length !== 1 || - readinessRequirements[0]?.readiness.status !== "qualified" + recipeBindingNames.length !== presetBindingNames.length || + recipeBindingNames.some((name, index) => name !== presetBindingNames[index]) ) { + throw new Error(`${preset.metadata.id} bindings do not exactly satisfy its recipe`); + } + const topologyRequirements = preset.spec.requirements.all + .filter((requirement) => "topologyQualification" in requirement) + .map(({ topologyQualification }) => topologyQualification); + if (topologyRequirements.length !== recipeBindingNames.length) { throw new Error( - `${preset.metadata.id} must require qualified DGX Spark readiness on every node`, + `${preset.metadata.id} topology requirements do not exactly satisfy its recipe bindings`, ); } - if ( - nodeCountRequirements.length !== 1 || - nodeCountRequirements[0]?.state !== "present" || - nodeCountRequirements[0]?.value !== recipe.spec.execution.nodeCount - ) { - throw new Error(`${preset.metadata.id} must require the recipe's exact node count`); + for (const name of recipeBindingNames) { + const recipeBinding = recipe.spec.bindings[name]!; + const presetBinding = preset.spec.plan.bindings[name]!.valueFromTopologyQualification; + const descriptor = getManagedInferenceTopologyQualificationDescriptor( + recipeBinding.qualificationId, + recipeBinding.schemaVersion, + ); + if ( + !descriptor || + presetBinding.id !== recipeBinding.qualificationId || + presetBinding.schemaVersion !== recipeBinding.schemaVersion || + presetBinding.output !== descriptor.bindingOutput + ) { + throw new Error(`${preset.metadata.id} binding ${name} does not match its recipe`); + } + const matchingRequirements = topologyRequirements.filter( + ({ id, schemaVersion, status }) => + id === presetBinding.id && + schemaVersion === presetBinding.schemaVersion && + status === "qualified", + ); + if (matchingRequirements.length !== 1) { + throw new Error( + `${preset.metadata.id} binding ${name} requires one matching qualified topology requirement`, + ); + } } - const topology = topologyRequirements[0]?.topologyQualification; - const recipeTopology = recipe.spec.bindings.sparkTopology; - if ( - topologyRequirements.length !== 1 || - topology?.status !== "qualified" || - topology.id !== recipeTopology.qualificationId || - topology.schemaVersion !== recipeTopology.schemaVersion - ) { - throw new Error(`${preset.metadata.id} topology requirement does not match its recipe binding`); + for (const requirement of preset.spec.requirements.all) { + if (!("fact" in requirement)) continue; + const error = factRequirementError(requirement); + if (error) throw new Error(`${preset.metadata.id} fact ${requirement.fact}: ${error}`); + if ( + requirement.fact === "cluster.nodeCount" && + requirement.state === "present" && + requirement.operator === "equals" && + requirement.value !== recipe.spec.execution.nodeCount + ) { + throw new Error(`${preset.metadata.id} node-count requirement does not match its recipe`); + } + } +} + +function assertUniqueDefinitionIds( + presets: readonly { readonly definition: ManagedInferenceServingPreset }[], + recipes: readonly { readonly definition: ManagedInferenceServingRecipe }[], +): void { + const seen = new Map(); + for (const [kind, definitions] of [ + ["preset", presets], + ["recipe", recipes], + ] as const) { + for (const { definition } of definitions) { + const existing = seen.get(definition.metadata.id); + if (existing) { + throw new Error( + `managed inference definition ID ${definition.metadata.id} is duplicated by ${existing} and ${kind}`, + ); + } + seen.set(definition.metadata.id, kind); + } } } @@ -236,14 +325,21 @@ export function compileManagedInferenceCatalogSources( } } - if (recipes.length !== 1 || presets.length !== 1) { - throw new Error("managed inference catalog v1 requires exactly one recipe and one preset"); + if (recipes.length === 0 || presets.length === 0) { + throw new Error("managed inference catalog requires at least one recipe and one preset"); } + assertUniqueDefinitionIds(presets, recipes); for (const { definition } of recipes) validateRecipeSemantics(definition); const recipesById = new Map( recipes.map(({ definition }) => [definition.metadata.id, definition]), ); for (const { definition } of presets) validatePresetSemantics(definition, recipesById); + recipes.sort((left, right) => + compareStrings(left.definition.metadata.id, right.definition.metadata.id), + ); + presets.sort((left, right) => + compareStrings(left.definition.metadata.id, right.definition.metadata.id), + ); const sourceFiles = sortedSources.map((source) => ({ digest: managedInferenceTextDigest(source.contents), @@ -261,8 +357,9 @@ export function compileManagedInferenceCatalogSources( ...withoutDigest, catalogDigest: managedInferenceDigest(withoutDigest), }) as CompiledManagedInferenceCatalog; - if (!validateCatalog(catalog)) + if (!validateCatalog(catalog)) { throw validationError("compiled managed inference catalog", validateCatalog); + } return { catalog, json: `${JSON.stringify(catalog, null, 2)}\n` }; } diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 2b4e00b7a8f..445d8b34451 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -1233,7 +1233,19 @@ function dockerIsAvailable(runtime: UninstallRuntime): boolean { return true; } -function removeManagedDistributedVllmRuntime(runtime: UninstallRuntime): boolean { +function removeManagedDistributedVllmRuntime( + paths: UninstallPaths, + runtime: UninstallRuntime, +): boolean { + const sharedRoot = path.dirname(paths.managedSwapMarkerPath); + try { + const root = fs.lstatSync(sharedRoot); + if (root.isSymbolicLink() || !root.isDirectory()) return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; + runtime.error(`Could not inspect managed distributed vLLM state root: ${formatError(error)}`); + return false; + } let state: ReturnType; try { state = findManagedDistributedVllmRuntimeReceipts({ @@ -1616,7 +1628,7 @@ function executePlan( for (const [index, step] of plan.steps.entries()) { runtime.log(`[${index + 1}/${plan.steps.length}] ${planStepDisplayName(step.name, branding)}`); if (step.name === "Stopping services") { - if (!scopedToSelectedGateway && !removeManagedDistributedVllmRuntime(runtime)) { + if (!scopedToSelectedGateway && !removeManagedDistributedVllmRuntime(paths, runtime)) { return { ok: false }; } if ( diff --git a/src/lib/inference/serving/adapter-registry.test.ts b/src/lib/inference/serving/adapter-registry.test.ts new file mode 100644 index 00000000000..b2e6149843c --- /dev/null +++ b/src/lib/inference/serving/adapter-registry.test.ts @@ -0,0 +1,267 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { + DUAL_SPARK_VLLM_LIFECYCLE_REF, + DUAL_SPARK_VLLM_MATERIALIZER_REF, + getManagedInferenceLifecycleDescriptor, + getManagedInferenceMaterializerDescriptor, + getManagedInferencePreparationDescriptor, + getManagedInferenceRecipeRegistrationError, + getManagedInferenceTopologyQualificationDescriptor, + listManagedInferenceLifecycleDescriptors, + listManagedInferenceMaterializerDescriptors, + listManagedInferencePreparationDescriptors, + listManagedInferenceTopologyQualificationDescriptors, + NO_PREPARATION_REF, + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, +} from "./adapter-registry.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; +import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, +} from "./dual-spark-topology.js"; + +function shippedRecipe(): ManagedInferenceServingRecipe { + const recipe = loadManagedInferenceCatalog().recipes.find( + ({ definition }) => + definition.spec.execution.materializerRef === DUAL_SPARK_VLLM_MATERIALIZER_REF, + )?.definition; + expect(recipe).toBeDefined(); + return structuredClone(recipe as ManagedInferenceServingRecipe); +} + +describe("managed inference adapter registries", () => { + it("registers one versioned descriptor for each shipped dual-Spark mechanic", () => { + expect(listManagedInferenceTopologyQualificationDescriptors()).toMatchObject([ + { + id: DUAL_SPARK_TOPOLOGY_ID, + schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + bindingOutput: "topology", + }, + ]); + expect(listManagedInferenceMaterializerDescriptors()).toMatchObject([ + { ref: DUAL_SPARK_VLLM_MATERIALIZER_REF, backend: "vllm" }, + ]); + expect(listManagedInferenceLifecycleDescriptors()).toMatchObject([ + { ref: DUAL_SPARK_VLLM_LIFECYCLE_REF, backend: "vllm" }, + ]); + expect(listManagedInferencePreparationDescriptors()).toEqual( + expect.arrayContaining([ + expect.objectContaining({ ref: NO_PREPARATION_REF, backend: "vllm" }), + expect.objectContaining({ + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + backend: "vllm", + }), + ]), + ); + }); + + it("looks up mechanics only by their stable registry references", () => { + expect( + getManagedInferenceTopologyQualificationDescriptor( + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + ), + ).toBeDefined(); + expect( + getManagedInferenceTopologyQualificationDescriptor("unknown.topology", 1), + ).toBeUndefined(); + expect( + getManagedInferenceMaterializerDescriptor(DUAL_SPARK_VLLM_MATERIALIZER_REF), + ).toBeDefined(); + expect(getManagedInferenceMaterializerDescriptor("unknown.materializer/v1")).toBeUndefined(); + expect(getManagedInferenceLifecycleDescriptor(DUAL_SPARK_VLLM_LIFECYCLE_REF)).toBeDefined(); + expect(getManagedInferenceLifecycleDescriptor("unknown.lifecycle/v1")).toBeUndefined(); + expect( + getManagedInferencePreparationDescriptor( + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + ), + ).toBeDefined(); + expect(getManagedInferencePreparationDescriptor(NO_PREPARATION_REF)).toBeDefined(); + expect(getManagedInferencePreparationDescriptor("unknown.preparation/v1")).toBeUndefined(); + }); + + it("validates the current recipe by adapter shape without pinning its profile or model identity", () => { + const recipe = shippedRecipe(); + const changedIdentity = { + ...recipe, + metadata: { ...recipe.metadata, id: "vllm.synthetic.second-recipe" }, + spec: { + ...recipe.spec, + model: { + ...recipe.spec.model, + id: "example/AnotherModel", + revision: "b".repeat(40), + servedName: "another-model", + }, + runtime: { + ...recipe.spec.runtime, + image: `registry.example/vllm@sha256:${"c".repeat(64)}`, + }, + readiness: { ...recipe.spec.readiness, expectedModel: "another-model" }, + }, + } as ManagedInferenceServingRecipe; + + expect(getManagedInferenceRecipeRegistrationError(recipe)).toBeUndefined(); + expect(getManagedInferenceRecipeRegistrationError(changedIdentity)).toBeUndefined(); + }); + + it("rejects an unregistered or incompatible recipe mechanic", () => { + const recipe = shippedRecipe(); + const unregistered = { + ...recipe, + spec: { + ...recipe.spec, + execution: { ...recipe.spec.execution, materializerRef: "vllm.unknown/v1" }, + }, + } as ManagedInferenceServingRecipe; + const wrongShape = { + ...recipe, + spec: { + ...recipe.spec, + execution: { ...recipe.spec.execution, nodeCount: 3 }, + }, + } as ManagedInferenceServingRecipe; + + expect(getManagedInferenceRecipeRegistrationError(unregistered)).toMatch( + /unknown materializer/u, + ); + expect(getManagedInferenceRecipeRegistrationError(wrongShape)).toMatch(/two-node/u); + }); + + it("rejects schema-valid values that the registered adapter cannot execute", () => { + const recipe = shippedRecipe(); + const unsupportedCache = { + ...recipe, + spec: { + ...recipe.spec, + runtime: { + ...recipe.spec.runtime, + modelCache: { ...recipe.spec.runtime.modelCache, source: "synthetic-cache" }, + }, + }, + } as ManagedInferenceServingRecipe; + const rendezvousCollision = { + ...recipe, + spec: { + ...recipe.spec, + serve: { + ...recipe.spec.serve, + arguments: recipe.spec.serve.arguments.map((argument) => + argument.name === "--port" ? { ...argument, value: 25_000 } : argument, + ), + }, + }, + } as ManagedInferenceServingRecipe; + const mutableLaunchImage = { + ...recipe, + spec: { + ...recipe.spec, + model: { ...recipe.spec.model, installFastSafetensors: true }, + }, + } as ManagedInferenceServingRecipe; + const redundantPath = { + ...recipe, + spec: { + ...recipe.spec, + runtime: { + ...recipe.spec.runtime, + modelCache: { ...recipe.spec.runtime.modelCache, target: "/models//cache" }, + }, + }, + } as ManagedInferenceServingRecipe; + + expect(getManagedInferenceRecipeRegistrationError(unsupportedCache)).toMatch( + /Hugging Face cache source/u, + ); + expect(getManagedInferenceRecipeRegistrationError(rendezvousCollision)).toMatch( + /rendezvous port/u, + ); + expect(getManagedInferenceRecipeRegistrationError(mutableLaunchImage)).toMatch( + /cannot install fastsafetensors/u, + ); + expect(getManagedInferenceRecipeRegistrationError(redundantPath)).toMatch( + /normalized absolute/u, + ); + }); + + it("dispatches topology artifact validation through the registered descriptor", () => { + const artifact = fixtureDualSparkSelection().topologyQualification; + const descriptor = getManagedInferenceTopologyQualificationDescriptor( + artifact.id, + artifact.schemaVersion, + ); + expect(descriptor?.validateArtifact(artifact, artifact.subjectNodeIds)).toBeUndefined(); + + const changed = structuredClone(artifact); + (changed as { outputDigest: string }).outputDigest = `sha256:${"f".repeat(64)}`; + expect(descriptor?.validateArtifact(changed, artifact.subjectNodeIds)).toMatch(/digest/u); + }); + + it("keeps preparation inputs bounded without coupling them to a model ID", () => { + const recipe = shippedRecipe(); + const preparation = (recipe.spec.model as unknown as { preparation: { ref: string } }) + .preparation; + const descriptor = getManagedInferencePreparationDescriptor(preparation.ref); + const differentModel = { + ...recipe, + spec: { + ...recipe.spec, + model: { ...recipe.spec.model, id: "example/AnotherModel" }, + }, + } as ManagedInferenceServingRecipe; + const unsafePath = { + ...recipe, + spec: { + ...recipe.spec, + model: { + ...recipe.spec.model, + preparation: { + ...(recipe.spec.model as unknown as { preparation: object }).preparation, + snapshotCopy: { + ...( + recipe.spec.model as unknown as { + preparation: { snapshotCopy: object }; + } + ).preparation.snapshotCopy, + sourcePath: "../encoding.py", + }, + }, + }, + }, + } as ManagedInferenceServingRecipe; + + expect(descriptor?.validateRecipe(differentModel)).toBeUndefined(); + expect(descriptor?.validateRecipe(unsafePath)).toMatch(/copy paths/u); + }); + + it("accepts only the exact no-op preparation shape", () => { + const recipe = shippedRecipe(); + const descriptor = getManagedInferencePreparationDescriptor(NO_PREPARATION_REF); + const noPreparation = { + ...recipe, + spec: { + ...recipe.spec, + model: { ...recipe.spec.model, preparation: { ref: NO_PREPARATION_REF } }, + }, + } as ManagedInferenceServingRecipe; + const extraInput = { + ...noPreparation, + spec: { + ...noPreparation.spec, + model: { + ...noPreparation.spec.model, + preparation: { ref: NO_PREPARATION_REF, command: "true" }, + }, + }, + } as ManagedInferenceServingRecipe; + + expect(descriptor?.validateRecipe(noPreparation)).toBeUndefined(); + expect(descriptor?.validateRecipe(extraInput)).toMatch(/empty preparation/u); + }); +}); diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts new file mode 100644 index 00000000000..209814db5e6 --- /dev/null +++ b/src/lib/inference/serving/adapter-registry.ts @@ -0,0 +1,464 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { + ManagedInferenceServingRecipe, + ManagedInferenceTopologyQualification, +} from "./catalog-types.js"; +import { + DUAL_SPARK_TOPOLOGY_ID, + DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + getDualSparkTopologyArtifactError, +} from "./dual-spark-topology.js"; + +export const DUAL_SPARK_VLLM_MATERIALIZER_REF = "vllm.dual-dgx-spark/v1" as const; +export const DUAL_SPARK_VLLM_LIFECYCLE_REF = "vllm.dual-dgx-spark/v1" as const; +export const SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF = + "snapshot-copy-and-exact-text-replacement/v1" as const; +export const NO_PREPARATION_REF = "none/v1" as const; +export const DUAL_SPARK_HUGGING_FACE_CACHE_SOURCE = "huggingface-cache" as const; +export const DUAL_SPARK_VLLM_MASTER_PORT = 25_000 as const; + +export interface ManagedInferenceTopologyQualificationDescriptor { + readonly id: string; + readonly schemaVersion: number; + readonly outputSchema: string; + readonly bindingOutput: string; + validateArtifact( + artifact: ManagedInferenceTopologyQualification, + expectedSubjectNodeIds?: readonly string[], + ): string | undefined; +} + +export interface ManagedInferenceMaterializerDescriptor { + readonly ref: string; + readonly backend: string; + readonly outputPlanSchema: string; + readonly topology: { + readonly qualificationId: string; + readonly schemaVersion: number; + readonly outputSchema: string; + }; + validateRecipe(recipe: ManagedInferenceServingRecipe): string | undefined; +} + +export interface ManagedInferenceLifecycleDescriptor { + readonly ref: string; + readonly backend: string; + readonly acceptedMaterializerRefs: readonly string[]; + readonly acceptedPlanSchemas: readonly string[]; + readonly secretHandlePermissions: readonly string[]; + validateRecipe(recipe: ManagedInferenceServingRecipe): string | undefined; +} + +export interface ManagedInferencePreparationDescriptor { + readonly ref: string; + readonly backend: string; + readonly phase: "container-before-exec"; + validateRecipe(recipe: ManagedInferenceServingRecipe): string | undefined; +} + +const DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA = "nemoclaw.nvidia.com/dual-spark-topology/v1" as const; +const DUAL_SPARK_PLAN_SCHEMA = "nemoclaw.nvidia.com/dual-spark-vllm-plan/v1" as const; +const LOWERCASE_STABLE_ID = /^[a-z0-9][a-z0-9._/-]{0,159}$/u; +const DUAL_SPARK_MATERIALIZER_OWNED_ENVIRONMENT = new Set([ + "GLOO_SOCKET_IFNAME", + "HEADLESS", + "HF_HOME", + "MASTER_ADDR", + "MASTER_PORT", + "NCCL_IB_GID_INDEX", + "NCCL_IB_HCA", + "NCCL_SOCKET_IFNAME", + "NODE_RANK", + "TP_SOCKET_IFNAME", + "VLLM_API_KEY", + "VLLM_HOST_IP", +]); + +export function isDualSparkMaterializerOwnedEnvironment(name: string): boolean { + return DUAL_SPARK_MATERIALIZER_OWNED_ENVIRONMENT.has(name); +} + +function dualSparkTopologyBinding( + recipe: ManagedInferenceServingRecipe, +): ManagedInferenceServingRecipe["spec"]["bindings"][string] | undefined { + return recipe.spec.bindings[recipe.spec.execution.topologyBinding]; +} + +function positiveIntegerArgument( + recipe: ManagedInferenceServingRecipe, + name: string, + maximum = Number.MAX_SAFE_INTEGER, +): number | undefined { + const matches = recipe.spec.serve.arguments.filter((argument) => argument.name === name); + if (matches.length !== 1) return undefined; + const value = matches[0]!.value; + const parsed = + typeof value === "number" + ? value + : typeof value === "string" && /^\d+$/u.test(value) + ? Number(value) + : Number.NaN; + return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= maximum ? parsed : undefined; +} + +function validateDualSparkMaterializerRecipe( + recipe: ManagedInferenceServingRecipe, +): string | undefined { + if (recipe.spec.backend !== "vllm") return "dual-Spark materializer requires backend vllm"; + if (recipe.spec.execution.materializerRef !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { + return "recipe does not select the dual-Spark materializer"; + } + if ( + recipe.spec.execution.nodeCount !== 2 || + recipe.spec.execution.tensorParallelSize !== 2 || + recipe.spec.execution.pipelineParallelSize !== 1 || + recipe.spec.execution.distributedExecutorBackend !== "mp" + ) { + return "dual-Spark materializer requires its two-node TP=2, PP=1, mp execution shape"; + } + if (Object.keys(recipe.spec.bindings).length !== 1) { + return "dual-Spark materializer requires exactly one topology binding"; + } + if ( + recipe.spec.runtime.architecture !== "arm64" || + recipe.spec.runtime.networkMode !== "host" || + recipe.spec.runtime.ipcMode !== "host" || + recipe.spec.serve.authentication !== "bearer" + ) { + return "dual-Spark materializer requires arm64 host networking, host IPC, and bearer authentication"; + } + const apiPort = positiveIntegerArgument(recipe, "--port", 65_535); + if (apiPort === undefined || positiveIntegerArgument(recipe, "--max-model-len") === undefined) { + return "dual-Spark materializer requires one valid --port and one positive --max-model-len"; + } + if (apiPort === DUAL_SPARK_VLLM_MASTER_PORT) { + return "dual-Spark API port conflicts with the materializer rendezvous port"; + } + if (recipe.spec.readiness.expectedModel !== recipe.spec.model.servedName) { + return "dual-Spark readiness must expect the recipe served model"; + } + if (!LOWERCASE_STABLE_ID.test(recipe.spec.model.servedName)) { + return "dual-Spark served model name must be a lowercase stable ID"; + } + if (recipe.spec.model.installFastSafetensors) { + return "dual-Spark immutable-image materializer cannot install fastsafetensors at launch"; + } + if (recipe.spec.runtime.modelCache.source !== DUAL_SPARK_HUGGING_FACE_CACHE_SOURCE) { + return "dual-Spark materializer requires the Hugging Face cache source"; + } + if ( + !safeAbsoluteContainerPath(recipe.spec.serve.executable) || + !safeAbsoluteContainerPath(recipe.spec.runtime.modelCache.target) || + recipe.spec.runtime.devices.some((device) => !safeAbsoluteContainerPath(device)) || + recipe.spec.runtime.temporaryFilesystems.some( + ({ target }) => !safeAbsoluteContainerPath(target), + ) + ) { + return "dual-Spark runtime paths must be normalized absolute container paths"; + } + const resourceValues = [ + recipe.spec.model.downloadSizeBytes, + recipe.spec.runtime.imageDownloadSizeBytes, + recipe.spec.runtime.sharedMemoryBytes, + recipe.spec.runtime.ulimits.stackBytes, + ...recipe.spec.runtime.temporaryFilesystems.map(({ sizeBytes }) => sizeBytes), + ]; + if (resourceValues.some((value) => !Number.isSafeInteger(value) || value <= 0)) { + return "dual-Spark recipe resource values must be positive safe integers"; + } + const memlock = recipe.spec.runtime.ulimits.memlock; + if (typeof memlock === "number" && (!Number.isSafeInteger(memlock) || memlock < -1)) { + return "dual-Spark memlock value must be -1 or a non-negative safe integer"; + } + if ( + recipe.spec.serve.arguments.some( + ({ value }) => + typeof value === "string" && + (Buffer.byteLength(value, "utf8") > 16_384 || value.includes("\0")), + ) + ) { + return "dual-Spark serving argument values must be bounded text without NUL bytes"; + } + if ( + Object.values(recipe.spec.runtime.environment).some( + (value) => Buffer.byteLength(value, "utf8") > 4_096 || value.includes("\0"), + ) + ) { + return "dual-Spark environment values must be bounded text without NUL bytes"; + } + if ( + Object.keys(recipe.spec.runtime.environment).some((name) => + isDualSparkMaterializerOwnedEnvironment(name), + ) + ) { + return "dual-Spark recipe environment overrides a materializer-owned value"; + } + const binding = dualSparkTopologyBinding(recipe); + if ( + !binding || + binding.type !== "topologyQualificationOutput" || + binding.qualificationId !== DUAL_SPARK_TOPOLOGY_ID || + binding.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION || + binding.outputSchema !== DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA + ) { + return "dual-Spark materializer topology binding is incompatible"; + } + return undefined; +} + +function validateDualSparkLifecycleRecipe( + recipe: ManagedInferenceServingRecipe, +): string | undefined { + const materializerError = validateDualSparkMaterializerRecipe(recipe); + if (materializerError) return materializerError; + return recipe.spec.execution.lifecycleRef === DUAL_SPARK_VLLM_LIFECYCLE_REF + ? undefined + : "recipe does not select the dual-Spark lifecycle"; +} + +interface SnapshotPreparationInput { + readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; + readonly snapshotCopy: { + readonly sourcePath: string; + readonly targetPath: string; + }; + readonly exactTextReplacement: { + readonly targetPath: string; + readonly expectedText: string; + readonly replacementText: string; + }; +} + +interface NoPreparationInput { + readonly ref: typeof NO_PREPARATION_REF; +} + +type ManagedInferencePreparationInput = SnapshotPreparationInput | NoPreparationInput; + +function recipePreparation( + recipe: ManagedInferenceServingRecipe, +): ManagedInferencePreparationInput | undefined { + const preparation = (recipe.spec.model as unknown as { readonly preparation?: unknown }) + .preparation; + return typeof preparation === "object" && preparation !== null + ? (preparation as ManagedInferencePreparationInput) + : undefined; +} + +function hasExactKeys(value: object, expected: readonly string[]): boolean { + const keys = Object.keys(value).sort(); + const sortedExpected = [...expected].sort(); + return ( + keys.length === sortedExpected.length && + keys.every((key, index) => key === sortedExpected[index]) + ); +} + +function safeRelativeSnapshotPath(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 4096 && + !value.startsWith("/") && + value.split("/").every((component) => component && component !== "." && component !== "..") && + !/[\u0000-\u001f\u007f]/u.test(value) + ); +} + +function safeAbsoluteContainerPath(value: unknown): value is string { + return ( + typeof value === "string" && + value.startsWith("/") && + value.length <= 4096 && + value + .split("/") + .slice(1) + .every((component) => component && component !== "." && component !== "..") && + !/[\u0000-\u001f\u007f]/u.test(value) + ); +} + +function validateSnapshotPreparationRecipe( + recipe: ManagedInferenceServingRecipe, +): string | undefined { + if (recipe.spec.backend !== "vllm") return "snapshot preparation requires backend vllm"; + const preparation = recipePreparation(recipe); + if ( + preparation?.ref !== SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF || + !hasExactKeys(preparation, ["exactTextReplacement", "ref", "snapshotCopy"]) + ) { + return "recipe does not select the snapshot preparation operation"; + } + if ( + !preparation.snapshotCopy || + !hasExactKeys(preparation.snapshotCopy, ["sourcePath", "targetPath"]) || + !safeRelativeSnapshotPath(preparation.snapshotCopy.sourcePath) || + !safeAbsoluteContainerPath(preparation.snapshotCopy.targetPath) + ) { + return "snapshot preparation copy paths are invalid"; + } + const replacement = preparation.exactTextReplacement; + if ( + !replacement || + !hasExactKeys(replacement, ["expectedText", "replacementText", "targetPath"]) || + !safeAbsoluteContainerPath(replacement.targetPath) || + typeof replacement.expectedText !== "string" || + typeof replacement.replacementText !== "string" || + replacement.expectedText.length === 0 || + replacement.expectedText.length > 65_536 || + replacement.replacementText.length === 0 || + replacement.replacementText.length > 65_536 || + replacement.expectedText === replacement.replacementText || + replacement.expectedText.includes("\0") || + replacement.replacementText.includes("\0") + ) { + return "snapshot preparation exact-text replacement is invalid"; + } + return undefined; +} + +function validateNoPreparationRecipe(recipe: ManagedInferenceServingRecipe): string | undefined { + if (recipe.spec.backend !== "vllm") return "empty preparation requires backend vllm"; + const preparation = recipePreparation(recipe); + return preparation?.ref === NO_PREPARATION_REF && hasExactKeys(preparation, ["ref"]) + ? undefined + : "recipe does not select the empty preparation operation"; +} + +const TOPOLOGY_DESCRIPTORS = [ + { + id: DUAL_SPARK_TOPOLOGY_ID, + schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + outputSchema: DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA, + bindingOutput: "topology", + validateArtifact: getDualSparkTopologyArtifactError, + }, +] as const satisfies readonly ManagedInferenceTopologyQualificationDescriptor[]; + +const MATERIALIZER_DESCRIPTORS = [ + { + ref: DUAL_SPARK_VLLM_MATERIALIZER_REF, + backend: "vllm", + outputPlanSchema: DUAL_SPARK_PLAN_SCHEMA, + topology: { + qualificationId: DUAL_SPARK_TOPOLOGY_ID, + schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + outputSchema: DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA, + }, + validateRecipe: validateDualSparkMaterializerRecipe, + }, +] as const satisfies readonly ManagedInferenceMaterializerDescriptor[]; + +const LIFECYCLE_DESCRIPTORS = [ + { + ref: DUAL_SPARK_VLLM_LIFECYCLE_REF, + backend: "vllm", + acceptedMaterializerRefs: [DUAL_SPARK_VLLM_MATERIALIZER_REF], + acceptedPlanSchemas: [DUAL_SPARK_PLAN_SCHEMA], + secretHandlePermissions: ["sshBinding"], + validateRecipe: validateDualSparkLifecycleRecipe, + }, +] as const satisfies readonly ManagedInferenceLifecycleDescriptor[]; + +const PREPARATION_DESCRIPTORS = [ + { + ref: NO_PREPARATION_REF, + backend: "vllm", + phase: "container-before-exec", + validateRecipe: validateNoPreparationRecipe, + }, + { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + backend: "vllm", + phase: "container-before-exec", + validateRecipe: validateSnapshotPreparationRecipe, + }, +] as const satisfies readonly ManagedInferencePreparationDescriptor[]; + +function registry( + entries: readonly T[], + key: (entry: T) => string, + label: string, +): ReadonlyMap { + const result = new Map(); + for (const entry of entries) { + const id = key(entry); + if (result.has(id)) + throw new Error(`duplicate managed inference ${label} registry entry ${id}`); + result.set(id, entry); + } + return result; +} + +const TOPOLOGY_REGISTRY = registry( + TOPOLOGY_DESCRIPTORS, + ({ id, schemaVersion }) => `${id}@${String(schemaVersion)}`, + "topology qualification", +); +const MATERIALIZER_REGISTRY = registry(MATERIALIZER_DESCRIPTORS, ({ ref }) => ref, "materializer"); +const LIFECYCLE_REGISTRY = registry(LIFECYCLE_DESCRIPTORS, ({ ref }) => ref, "lifecycle"); +const PREPARATION_REGISTRY = registry(PREPARATION_DESCRIPTORS, ({ ref }) => ref, "preparation"); + +export function listManagedInferenceTopologyQualificationDescriptors(): readonly ManagedInferenceTopologyQualificationDescriptor[] { + return [...TOPOLOGY_DESCRIPTORS]; +} + +export function getManagedInferenceTopologyQualificationDescriptor( + id: string, + schemaVersion: number, +): ManagedInferenceTopologyQualificationDescriptor | undefined { + return TOPOLOGY_REGISTRY.get(`${id}@${String(schemaVersion)}`); +} + +export function listManagedInferenceMaterializerDescriptors(): readonly ManagedInferenceMaterializerDescriptor[] { + return [...MATERIALIZER_DESCRIPTORS]; +} + +export function getManagedInferenceMaterializerDescriptor( + ref: string, +): ManagedInferenceMaterializerDescriptor | undefined { + return MATERIALIZER_REGISTRY.get(ref); +} + +export function listManagedInferenceLifecycleDescriptors(): readonly ManagedInferenceLifecycleDescriptor[] { + return [...LIFECYCLE_DESCRIPTORS]; +} + +export function getManagedInferenceLifecycleDescriptor( + ref: string, +): ManagedInferenceLifecycleDescriptor | undefined { + return LIFECYCLE_REGISTRY.get(ref); +} + +export function listManagedInferencePreparationDescriptors(): readonly ManagedInferencePreparationDescriptor[] { + return [...PREPARATION_DESCRIPTORS]; +} + +export function getManagedInferencePreparationDescriptor( + ref: string, +): ManagedInferencePreparationDescriptor | undefined { + return PREPARATION_REGISTRY.get(ref); +} + +export function getManagedInferenceRecipeRegistrationError( + recipe: ManagedInferenceServingRecipe, +): string | undefined { + const materializer = getManagedInferenceMaterializerDescriptor( + recipe.spec.execution.materializerRef, + ); + if (!materializer) { + return `unknown materializer ${recipe.spec.execution.materializerRef}`; + } + const lifecycle = getManagedInferenceLifecycleDescriptor(recipe.spec.execution.lifecycleRef); + if (!lifecycle) return `unknown lifecycle ${recipe.spec.execution.lifecycleRef}`; + const preparationRef = recipePreparation(recipe)?.ref ?? ""; + const preparation = getManagedInferencePreparationDescriptor(preparationRef); + if (!preparation) return `unknown preparation ${preparationRef || "(missing)"}`; + return ( + materializer.validateRecipe(recipe) ?? + lifecycle.validateRecipe(recipe) ?? + preparation.validateRecipe(recipe) + ); +} diff --git a/src/lib/inference/serving/catalog-types.ts b/src/lib/inference/serving/catalog-types.ts index 4712a2385a9..d97664a51fb 100644 --- a/src/lib/inference/serving/catalog-types.ts +++ b/src/lib/inference/serving/catalog-types.ts @@ -5,12 +5,6 @@ import type { SystemReadinessReport } from "../../readiness/types.js"; export const MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION = "1.0.0" as const; export const MANAGED_INFERENCE_CATALOG_COMPILER_VERSION = "1.0.0" as const; -export const DUAL_SPARK_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731" as const; -export const DUAL_SPARK_RECIPE_ID = "vllm.deepseek-v4-flash-0731.spark-dual.v1" as const; -export const DUAL_SPARK_RECIPE_SPEC_DIGEST = - "sha256:32d4233427cc9fe99a143a52887b66232aeaf650712ad1b8b6ff673743fe9637" as const; -export const DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID = "dgx-spark.gb10.dual-cx7" as const; -export const DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION = 1 as const; const MATERIALIZER_OWNED_SERVE_ARGUMENTS = new Set([ "--api-key", @@ -22,6 +16,7 @@ const MATERIALIZER_OWNED_SERVE_ARGUMENTS = new Set([ "--nnodes", "--node-rank", "--pipeline-parallel-size", + "--revision", "--served-model-name", "--tensor-parallel-size", ]); @@ -40,49 +35,84 @@ export interface ManagedInferenceServingArgument { readonly value?: string | number | boolean; } +export interface ManagedInferenceTopologyBinding { + readonly type: "topologyQualificationOutput"; + readonly qualificationId: string; + readonly schemaVersion: number; + readonly outputSchema: string; +} + +export type ManagedInferenceModelPreparation = + | { readonly ref: "none/v1" } + | { + readonly ref: "snapshot-copy-and-exact-text-replacement/v1"; + readonly snapshotCopy: { + readonly sourcePath: string; + readonly targetPath: string; + }; + readonly exactTextReplacement: { + readonly targetPath: string; + readonly expectedText: string; + readonly replacementText: string; + }; + }; + +export interface ManagedInferenceTemporaryFilesystem { + readonly target: string; + readonly sizeBytes: number; + readonly mode: string; + readonly options: readonly string[]; +} + export interface ManagedInferenceServingRecipe { readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; readonly kind: "ServingRecipe"; readonly metadata: ManagedInferenceMetadata; readonly spec: { - readonly backend: "vllm"; - readonly bindings: { - readonly sparkTopology: { - readonly type: "topologyQualificationOutput"; - readonly qualificationId: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; - readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; - readonly outputSchema: "nemoclaw.nvidia.com/dual-spark-topology/v1"; - }; - }; + readonly backend: string; + readonly bindings: Readonly>; readonly model: { readonly id: string; readonly revision: string; readonly servedName: string; readonly downloadSizeBytes: number; - readonly preparationRef: "deepseek-v4-flash-0731/v1"; - readonly encodingPath: "encoding/encoding_dsv4.py"; + readonly gated: boolean; + readonly installFastSafetensors: boolean; + readonly preparation: ManagedInferenceModelPreparation; }; readonly runtime: { readonly image: string; readonly imageDownloadSizeBytes: number; - readonly architecture: "arm64"; - readonly networkMode: "host"; - readonly ipcMode: "host"; + readonly pullTimeoutSeconds: number; + readonly architecture: string; + readonly networkMode: string; + readonly ipcMode: string; readonly sharedMemoryBytes: number; + readonly gpuRequest: string; readonly devices: readonly string[]; + readonly ulimits: { + readonly memlock: number | string; + readonly stackBytes: number; + }; + readonly modelCache: { + readonly source: string; + readonly target: string; + }; + readonly temporaryFilesystems: readonly ManagedInferenceTemporaryFilesystem[]; readonly environment: Readonly>; }; readonly execution: { - readonly materializerRef: "vllm.dual-dgx-spark/v1"; - readonly lifecycleRef: "vllm.dual-dgx-spark/v1"; - readonly topologyBinding: "sparkTopology"; - readonly nodeCount: 2; - readonly tensorParallelSize: 2; - readonly pipelineParallelSize: 1; - readonly distributedExecutorBackend: "mp"; + readonly materializerRef: string; + readonly lifecycleRef: string; + readonly topologyBinding: string; + readonly nodeCount: number; + readonly tensorParallelSize: number; + readonly pipelineParallelSize: number; + readonly distributedExecutorBackend: string; }; readonly serve: { - readonly authentication: "bearer"; + readonly authentication: string; + readonly executable: string; readonly arguments: readonly ManagedInferenceServingArgument[]; }; readonly readiness: { @@ -92,50 +122,72 @@ export interface ManagedInferenceServingRecipe { }; } -export type ManagedInferencePresetRequirement = +export type ManagedInferenceReadinessRequirement = | { readonly readiness: { - readonly scope: "everyNode"; + readonly scope: "everyNode" | "anyNode"; readonly kind: "qualification"; - readonly id: "host.platform.dgx_spark"; - readonly status: "qualified"; + readonly id: string; + readonly status: string; }; } | { - readonly fact: "cluster.nodeCount"; - readonly state: "present"; - readonly operator: "equals"; - readonly value: number; - } - | { - readonly topologyQualification: { - readonly id: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; - readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; - readonly status: "qualified"; + readonly readiness: { + readonly scope: "everyNode" | "anyNode"; + readonly kind: "observation" | "capability"; + readonly id: string; + readonly state: string; }; }; +export type ManagedInferenceFactValue = + | string + | number + | boolean + | readonly (string | number | boolean)[]; + +export interface ManagedInferenceFactRequirement { + readonly fact: string; + readonly state: "present" | "absent"; + readonly operator: "equals" | "oneOf" | "atLeast" | "atMost" | "between"; + readonly value: ManagedInferenceFactValue; +} + +export interface ManagedInferenceTopologyRequirement { + readonly topologyQualification: { + readonly id: string; + readonly schemaVersion: number; + readonly status: string; + }; +} + +export type ManagedInferencePresetRequirement = + | ManagedInferenceReadinessRequirement + | ManagedInferenceFactRequirement + | ManagedInferenceTopologyRequirement; + +export interface ManagedInferencePresetTopologyBinding { + readonly valueFromTopologyQualification: { + readonly id: string; + readonly schemaVersion: number; + readonly output: string; + }; +} + export interface ManagedInferenceServingPreset { readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; readonly kind: "ServingPreset"; readonly metadata: ManagedInferenceMetadata; readonly spec: { - readonly selection: "automatic"; + readonly selection: "automatic" | "explicit-only" | "disabled"; + readonly priority: number; readonly requirements: { readonly all: readonly ManagedInferencePresetRequirement[]; }; readonly plan: { - readonly backend: "vllm"; + readonly backend: string; readonly recipeRef: string; - readonly bindings: { - readonly sparkTopology: { - readonly valueFromTopologyQualification: { - readonly id: typeof DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; - readonly schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; - readonly output: "topology"; - }; - }; - }; + readonly bindings: Readonly>; }; }; } @@ -193,6 +245,8 @@ export interface ResolvedManagedInferenceSelection { readonly outcome: "selected"; readonly selection: "automatic" | "explicit"; readonly catalogDigest: string; + readonly presetDigest: string; + readonly recipeDigest: string; readonly preset: ManagedInferenceServingPreset; readonly recipe: ManagedInferenceServingRecipe; readonly topologyQualification: ManagedInferenceTopologyQualification; @@ -212,6 +266,7 @@ export type ManagedInferenceResolution = | "incompatible-intent" | "invalid-readiness" | "invalid-topology" + | "ambiguous-selection" | "requirements-not-met"; readonly message: string; }; diff --git a/src/lib/inference/serving/catalog.test.ts b/src/lib/inference/serving/catalog.test.ts index 61e4db678be..86b9460611e 100644 --- a/src/lib/inference/serving/catalog.test.ts +++ b/src/lib/inference/serving/catalog.test.ts @@ -3,46 +3,41 @@ import { describe, expect, it } from "vitest"; -import { loadManagedInferenceCatalog } from "./catalog.js"; import { - DUAL_SPARK_PRESET_ID, - DUAL_SPARK_RECIPE_ID, - DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, -} from "./catalog-types.js"; + getManagedInferenceCompiledPreset, + getManagedInferenceCompiledRecipe, + loadManagedInferenceCatalog, +} from "./catalog.js"; describe("managed inference catalog", () => { - it("loads the immutable two-Spark recipe from compiled JSON", () => { + it("loads every compiled YAML definition with unique IDs and resolvable references", () => { const catalog = loadManagedInferenceCatalog(); - const recipe = catalog.recipes[0]?.definition; - const preset = catalog.presets[0]?.definition; - expect(catalog.catalogDigest).toMatch(/^sha256:[0-9a-f]{64}$/u); - expect(recipe?.metadata.id).toBe(DUAL_SPARK_RECIPE_ID); - expect(recipe?.spec.model).toMatchObject({ - id: "deepseek-ai/DeepSeek-V4-Flash-0731", - revision: "9e165c30e2704aec5d9d593cce3eebd58bbef1cb", - downloadSizeBytes: 166_898_661_074, - preparationRef: "deepseek-v4-flash-0731/v1", - }); - expect(recipe?.spec.runtime).toMatchObject({ - image: - "ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8", - imageDownloadSizeBytes: 9_787_537_825, - }); - expect(recipe?.spec.execution).toMatchObject({ - materializerRef: "vllm.dual-dgx-spark/v1", - lifecycleRef: "vllm.dual-dgx-spark/v1", - nodeCount: 2, - tensorParallelSize: 2, - }); - expect(preset?.metadata.id).toBe(DUAL_SPARK_PRESET_ID); - expect(preset?.spec.requirements.all).toContainEqual({ - topologyQualification: { - id: DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, - schemaVersion: 1, - status: "qualified", - }, - }); + expect(catalog.presets.length).toBeGreaterThan(0); + expect(catalog.recipes.length).toBeGreaterThan(0); + + const ids = [ + ...catalog.presets.map(({ definition }) => definition.metadata.id), + ...catalog.recipes.map(({ definition }) => definition.metadata.id), + ]; + expect(new Set(ids).size).toBe(ids.length); + for (const compiledPreset of catalog.presets) { + expect(getManagedInferenceCompiledPreset(compiledPreset.definition.metadata.id)).toBe( + compiledPreset, + ); + const compiledRecipe = getManagedInferenceCompiledRecipe( + compiledPreset.definition.spec.plan.recipeRef, + ); + expect(compiledRecipe?.definition.spec.backend).toBe( + compiledPreset.definition.spec.plan.backend, + ); + } + for (const compiledRecipe of catalog.recipes) { + expect(getManagedInferenceCompiledRecipe(compiledRecipe.definition.metadata.id)).toBe( + compiledRecipe, + ); + expect(compiledRecipe.definitionDigest).toMatch(/^sha256:[0-9a-f]{64}$/u); + } }); it("returns one deeply frozen catalog instance", () => { @@ -51,6 +46,8 @@ describe("managed inference catalog", () => { expect(second).toBe(first); expect(Object.isFrozen(first)).toBe(true); - expect(Object.isFrozen(first.recipes[0]?.definition.spec.runtime.environment)).toBe(true); + for (const { definition } of first.recipes) { + expect(Object.isFrozen(definition.spec.runtime.environment)).toBe(true); + } }); }); diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts index 96c041db129..583a4ef110e 100644 --- a/src/lib/inference/serving/catalog.ts +++ b/src/lib/inference/serving/catalog.ts @@ -1,24 +1,119 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + getManagedInferenceRecipeRegistrationError, + getManagedInferenceTopologyQualificationDescriptor, +} from "./adapter-registry.js"; import { immutableManagedInferenceCopy, managedInferenceDigest } from "./catalog-integrity.js"; import { type CompiledManagedInferenceCatalog, - DUAL_SPARK_PRESET_ID, - DUAL_SPARK_RECIPE_ID, - DUAL_SPARK_RECIPE_SPEC_DIGEST, MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, + type ManagedInferenceServingPreset, + type ManagedInferenceServingRecipe, } from "./catalog-types.js"; import generatedCatalog from "./generated/catalog.json"; const SHA256 = /^sha256:[0-9a-f]{64}$/u; +const SOURCE_PATH = /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u; -function assertCatalogIntegrity(value: unknown): asserts value is CompiledManagedInferenceCatalog { - if (typeof value !== "object" || value === null || Array.isArray(value)) { - throw new Error("managed inference catalog must be an object"); +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function definitionId(value: unknown): string | undefined { + if (!isRecord(value)) return undefined; + const metadata = value.metadata; + if (!isRecord(metadata)) return undefined; + return typeof metadata.id === "string" && metadata.id.length > 0 ? metadata.id : undefined; +} + +function assertCompiledDefinitions( + definitions: + | CompiledManagedInferenceCatalog["presets"] + | CompiledManagedInferenceCatalog["recipes"], + kind: "ServingPreset" | "ServingRecipe", + sourceDirectory: "presets" | "recipes", + sourcePaths: ReadonlySet, + seenIds: Set, + seenSources: Set, +): void { + for (const compiled of definitions) { + const id = definitionId(compiled.definition); + if ( + !id || + !isRecord(compiled.definition) || + compiled.definition.kind !== kind || + seenIds.has(id) || + !SHA256.test(compiled.definitionDigest) || + compiled.definitionDigest !== managedInferenceDigest(compiled.definition) || + typeof compiled.sourceFile !== "string" || + !compiled.sourceFile.startsWith(`managed-inference/${sourceDirectory}/`) || + !sourcePaths.has(compiled.sourceFile) || + seenSources.has(compiled.sourceFile) + ) { + throw new Error(`managed inference ${kind} definition is invalid`); + } + seenIds.add(id); + seenSources.add(compiled.sourceFile); + } +} + +function assertReferences( + presets: readonly { readonly definition: ManagedInferenceServingPreset }[], + recipes: readonly { readonly definition: ManagedInferenceServingRecipe }[], +): void { + const recipesById = new Map( + recipes.map(({ definition }) => [definition.metadata.id, definition]), + ); + for (const { definition: recipe } of recipes) { + const registrationError = getManagedInferenceRecipeRegistrationError(recipe); + if (registrationError) { + throw new Error( + `managed inference recipe ${recipe.metadata.id} is incompatible with its registered adapters: ${registrationError}`, + ); + } } - const catalog = value as Partial; + for (const { definition: preset } of presets) { + const recipe = recipesById.get(preset.spec.plan.recipeRef); + if (!recipe || recipe.spec.backend !== preset.spec.plan.backend) { + throw new Error( + `managed inference preset ${preset.metadata.id} has an invalid recipe reference`, + ); + } + const recipeBindings = Object.keys(recipe.spec.bindings).sort(); + const presetBindings = Object.keys(preset.spec.plan.bindings).sort(); + if ( + recipeBindings.length !== presetBindings.length || + recipeBindings.some((name, index) => name !== presetBindings[index]) + ) { + throw new Error(`managed inference preset ${preset.metadata.id} has invalid bindings`); + } + for (const name of recipeBindings) { + const expected = recipe.spec.bindings[name]!; + const actual = preset.spec.plan.bindings[name]!.valueFromTopologyQualification; + const descriptor = getManagedInferenceTopologyQualificationDescriptor( + expected.qualificationId, + expected.schemaVersion, + ); + if ( + !descriptor || + actual.id !== expected.qualificationId || + actual.schemaVersion !== expected.schemaVersion || + actual.output !== descriptor.bindingOutput + ) { + throw new Error( + `managed inference preset ${preset.metadata.id} has invalid binding ${name}`, + ); + } + } + } +} + +function assertCatalogIntegrity(value: unknown): asserts value is CompiledManagedInferenceCatalog { + if (!isRecord(value)) throw new Error("managed inference catalog must be an object"); + const catalog = value as unknown as Partial; if ( catalog.schemaVersion !== MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION || catalog.compilerVersion !== MANAGED_INFERENCE_CATALOG_COMPILER_VERSION @@ -31,7 +126,9 @@ function assertCatalogIntegrity(value: unknown): asserts value is CompiledManage if ( !Array.isArray(catalog.sourceFiles) || !Array.isArray(catalog.recipes) || - !Array.isArray(catalog.presets) + !Array.isArray(catalog.presets) || + catalog.recipes.length === 0 || + catalog.presets.length === 0 ) { throw new Error("managed inference catalog definitions are invalid"); } @@ -43,35 +140,43 @@ function assertCatalogIntegrity(value: unknown): asserts value is CompiledManage if (managedInferenceDigest(catalog.sourceFiles) !== catalog.sourceRevision) { throw new Error("managed inference catalog source revision does not match its provenance"); } - if (catalog.recipes.length !== 1 || catalog.presets.length !== 1) { - throw new Error("managed inference catalog must contain the supported recipe and preset"); - } - - const recipe = catalog.recipes[0]; - const preset = catalog.presets[0]; - if ( - !recipe || - !preset || - recipe.definition.metadata.id !== DUAL_SPARK_RECIPE_ID || - preset.definition.metadata.id !== DUAL_SPARK_PRESET_ID - ) { - throw new Error("managed inference catalog contains an unsupported definition"); - } - if (managedInferenceDigest(recipe.definition.spec) !== DUAL_SPARK_RECIPE_SPEC_DIGEST) { - throw new Error("managed inference recipe ID does not match its immutable contract"); - } - for (const compiled of [recipe, preset]) { + const sourcePaths = new Set(); + for (const source of catalog.sourceFiles) { if ( - !SHA256.test(compiled.definitionDigest) || - compiled.definitionDigest !== managedInferenceDigest(compiled.definition) || - !catalog.sourceFiles.some(({ path }) => path === compiled.sourceFile) + !isRecord(source) || + typeof source.path !== "string" || + !SOURCE_PATH.test(source.path) || + sourcePaths.has(source.path) || + typeof source.digest !== "string" || + !SHA256.test(source.digest) ) { - throw new Error(`managed inference definition ${compiled.definition.metadata.id} is invalid`); + throw new Error("managed inference catalog source provenance is invalid"); } + sourcePaths.add(source.path); } - if (preset.definition.spec.plan.recipeRef !== recipe.definition.metadata.id) { - throw new Error("managed inference preset references an unknown recipe"); + if (sourcePaths.size !== catalog.recipes.length + catalog.presets.length) { + throw new Error("managed inference catalog source provenance is incomplete"); } + + const seenIds = new Set(); + const seenSources = new Set(); + assertCompiledDefinitions( + catalog.recipes, + "ServingRecipe", + "recipes", + sourcePaths, + seenIds, + seenSources, + ); + assertCompiledDefinitions( + catalog.presets, + "ServingPreset", + "presets", + sourcePaths, + seenIds, + seenSources, + ); + assertReferences(catalog.presets, catalog.recipes); } let loadedCatalog: CompiledManagedInferenceCatalog | undefined; @@ -82,3 +187,19 @@ export function loadManagedInferenceCatalog(): CompiledManagedInferenceCatalog { loadedCatalog = immutableManagedInferenceCopy(generatedCatalog); return loadedCatalog; } + +export function getManagedInferenceCompiledPreset( + id: string, +): CompiledManagedInferenceCatalog["presets"][number] | undefined { + return loadManagedInferenceCatalog().presets.find( + ({ definition }) => definition.metadata.id === id, + ); +} + +export function getManagedInferenceCompiledRecipe( + id: string, +): CompiledManagedInferenceCatalog["recipes"][number] | undefined { + return loadManagedInferenceCatalog().recipes.find( + ({ definition }) => definition.metadata.id === id, + ); +} diff --git a/src/lib/inference/serving/dual-spark-discovery-production.ts b/src/lib/inference/serving/dual-spark-discovery-production.ts index 7ef4910408e..947603b2bad 100644 --- a/src/lib/inference/serving/dual-spark-discovery-production.ts +++ b/src/lib/inference/serving/dual-spark-discovery-production.ts @@ -24,7 +24,6 @@ import { strictStationSshTransportArgs, writeDualStationSshBinding, } from "../vllm-station-ssh-binding.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; import type { DualSparkCommandResult, DualSparkConnectivityRequest, @@ -33,11 +32,6 @@ import type { DualSparkPinnedPeerTransport, DualSparkReadOnlyHostTransport, } from "./dual-spark-discovery.js"; -import { - DUAL_SPARK_VLLM_IMAGE, - DUAL_SPARK_VLLM_MODEL, - DUAL_SPARK_VLLM_MODEL_REVISION, -} from "./dual-spark-materialize.js"; import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./spark-runtime-receipt-path.js"; const COMMAND_TIMEOUT_MS = 20_000; @@ -171,10 +165,7 @@ import re import shutil import socket import subprocess -import sys -MODEL_ID, MODEL_REVISION, IMAGE_REF, MODEL_BYTES_TEXT = sys.argv[1:5] -MODEL_BYTES = int(MODEL_BYTES_TEXT) DOCKER_ENV_NAMES = ( "DOCKER_API_VERSION", "DOCKER_CERT_PATH", @@ -433,44 +424,11 @@ def nearest_capacity(requested): "writableByUser": False, } -def snapshot_state(snapshot, cache_root): - if not snapshot.is_dir(): - return 0, False - total = 0 - seen = set() - count = 0 - try: - cache_real = cache_root.resolve(strict=True) - for root, dirs, files in os.walk(snapshot, followlinks=False): - dirs.sort() - files.sort() - for name in files: - count += 1 - if count > 100000 or name.endswith(".incomplete"): - return None, False - file_path = Path(root) / name - real = file_path.resolve(strict=True) - if os.path.commonpath([str(cache_real), str(real)]) != str(cache_real): - return None, False - stats = real.stat() - identity = (stats.st_dev, stats.st_ino) - if identity not in seen: - seen.add(identity) - total += stats.st_size - required = [snapshot / "config.json", snapshot / "encoding" / "encoding_dsv4.py"] - complete = total >= MODEL_BYTES and all(item.is_file() for item in required) - return total, complete - except Exception: - return None, False - uid = os.getuid() gid = os.getgid() account = pwd.getpwuid(uid) home = Path(account.pw_dir).resolve() hf_home = home / ".cache" / "huggingface" -hub = hf_home / "hub" -snapshot = hub / ("models--" + MODEL_ID.replace("/", "--")) / "snapshots" / MODEL_REVISION -snapshot_bytes, snapshot_cached = snapshot_state(snapshot, hub) hf_capacity = nearest_capacity(hf_home) docker_root = None @@ -481,7 +439,6 @@ if docker_info_code == 0: except Exception: docker_root = None docker_capacity = nearest_capacity(docker_root or "/var/lib/docker") -image_code, _ = run(["docker", "image", "inspect", IMAGE_REF]) observed_containers, containers_complete = containers() ports, ports_complete = listening_ports() @@ -530,14 +487,10 @@ result = { "huggingFace": { **hf_capacity, "cacheRoot": str(hf_home), - "snapshotPath": str(snapshot), - "snapshotBytes": snapshot_bytes, - "exactSnapshotCached": snapshot_cached, }, "docker": { **docker_capacity, "dockerRootDir": docker_root, - "exactImageCached": image_code == 0, }, }, } @@ -662,17 +615,7 @@ function probeHostWithTransport( transport: DualSparkReadOnlyHostTransport, parseHost: DualSparkHostParser, ): DualSparkHostObservation { - const recipe = loadManagedInferenceCatalog().recipes[0]?.definition; - if (!recipe) throw new Error("Managed inference recipe is unavailable"); - const result = transport.execute([ - "python3", - "-c", - HOST_PROBE_SCRIPT, - DUAL_SPARK_VLLM_MODEL, - DUAL_SPARK_VLLM_MODEL_REVISION, - DUAL_SPARK_VLLM_IMAGE, - String(recipe.spec.model.downloadSizeBytes), - ]); + const result = transport.execute(["python3", "-c", HOST_PROBE_SCRIPT]); return parseHost(parseJsonCommandResult(result, "DGX Spark host probe")); } diff --git a/src/lib/inference/serving/dual-spark-discovery.test.ts b/src/lib/inference/serving/dual-spark-discovery.test.ts index 3b03a389b01..0589093779b 100644 --- a/src/lib/inference/serving/dual-spark-discovery.test.ts +++ b/src/lib/inference/serving/dual-spark-discovery.test.ts @@ -14,10 +14,10 @@ import { type QualifiedStationSshIdentity, stationKnownHostsDigest, } from "../vllm-station-ssh-binding.js"; -import { DUAL_SPARK_PRESET_ID } from "./catalog-types.js"; import { confirmDualSparkManagedServingCapability, createDualSparkDiscoveryDeps, + type DualSparkDetectedManagedServingCapability, type DualSparkDiscoveryDeps, type DualSparkHostObservation, type DualSparkReadOnlyHostTransport, @@ -27,7 +27,8 @@ import { parseDualSparkHostObservation, probeDualSparkManagedServingCapability, } from "./dual-spark-discovery.js"; -import { DUAL_SPARK_MANAGED_LABEL } from "./dual-spark-materialize.js"; +import { FIXTURE_DUAL_SPARK_PRESET_ID } from "./dual-spark-fixture.test-support.js"; +import { DUAL_SPARK_MANAGED_LABEL, DUAL_SPARK_VLLM_MASTER_PORT } from "./dual-spark-materialize.js"; const NOW = new Date("2026-08-02T20:00:00.000Z"); const SOURCE_REVISION = "1d6948d89b46eab739728215f9a19ef40b8f6121"; @@ -71,6 +72,13 @@ const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixtur }, ]; +function expectDetectedPair( + detected: ReturnType, +): DualSparkDetectedManagedServingCapability { + expect(detected.kind).toBe("ready"); + return detected as DualSparkDetectedManagedServingCapability; +} + function readiness(overrides: Partial = {}): SystemReadinessReport { return { schemaVersion: "1.1.0", @@ -83,7 +91,10 @@ function readiness(overrides: Partial = {}): SystemReadin observedAt: NOW.toISOString(), }, observations: [], - capabilities: REQUIRED_CAPABILITIES.map((id) => ({ id, state: "present" as const })), + capabilities: REQUIRED_CAPABILITIES.map((id) => ({ + id, + state: "present" as const, + })), qualifications: [ { id: "host.platform.dgx_spark", @@ -182,14 +193,10 @@ function host( huggingFace: { ...capacity(cacheRoot, uid, gid), cacheRoot, - snapshotPath: `${cacheRoot}/hub/models--deepseek/snapshots/revision`, - snapshotBytes: 0, - exactSnapshotCached: false, }, docker: { ...capacity("/var/lib/docker", 0, 0), dockerRootDir: "/var/lib/docker", - exactImageCached: false, }, }, ...overrides, @@ -248,7 +255,10 @@ function fixture(overrides: Partial = {}) { const deps: DualSparkDiscoveryDeps = { now: () => NOW, currentUid: () => 1000, - getBuildIdentity: () => ({ nemoclawVersion: "0.1.0", sourceRevision: SOURCE_REVISION }), + getBuildIdentity: () => ({ + nemoclawVersion: "0.1.0", + sourceRevision: SOURCE_REVISION, + }), localTransport: () => localTransport, probeHost: (candidate) => (candidate === localTransport ? host("local") : host("peer")), inspectPretrustedTarget: (target) => identity(target), @@ -317,10 +327,30 @@ describe("dual DGX Spark managed-serving discovery", () => { expect(bindingWrites()).toBe(0); }); + it("rejects an explicit dual-Spark peer combined with another serving preset", () => { + const { deps, events, bindingWrites } = fixture({ + localTransport: () => { + throw new Error("must not probe"); + }, + }); + + expect( + probeDualSparkManagedServingCapability({ + env: { + [NEMOCLAW_SERVING_PRESET_ENV]: "another-preset", + [NEMOCLAW_DGX_SPARK_PEER_ENV]: "spark-worker.local", + }, + deps, + }), + ).toMatchObject({ kind: "unavailable", code: "incompatible-selection" }); + expect(events).toEqual([]); + expect(bindingWrites()).toBe(0); + }); + it("persists one binding only after the detected pair is confirmed and revalidated", () => { const { deps, events, bindingWrites } = fixture(); - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); expect(detected).toMatchObject({ kind: "ready", @@ -332,9 +362,10 @@ describe("dual DGX Spark managed-serving discovery", () => { }); expect(bindingWrites()).toBe(0); expect(events).not.toContain("write-binding"); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); - - const confirmed = confirmDualSparkManagedServingCapability(detected, { env: {}, deps }); + const confirmed = confirmDualSparkManagedServingCapability(detected, { + env: {}, + deps, + }); expect(confirmed).toMatchObject({ kind: "ready", @@ -357,7 +388,9 @@ describe("dual DGX Spark managed-serving discovery", () => { }); it("returns an ordinary automatic no-match when both rails are not pretrusted", () => { - const { deps, bindingWrites } = fixture({ inspectPretrustedTarget: () => null }); + const { deps, bindingWrites } = fixture({ + inspectPretrustedTarget: () => null, + }); expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", @@ -371,7 +404,7 @@ describe("dual DGX Spark managed-serving discovery", () => { expect( probeDualSparkManagedServingCapability({ - env: { [NEMOCLAW_SERVING_PRESET_ENV]: DUAL_SPARK_PRESET_ID }, + env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_DUAL_SPARK_PRESET_ID }, deps, }), ).toMatchObject({ kind: "unavailable", code: "peer-trust-unavailable" }); @@ -472,7 +505,11 @@ describe("dual DGX Spark managed-serving discovery", () => { name: "an active earlyoom service", mutate: (value: DualSparkHostObservation) => ({ ...value, - earlyoom: { installed: true, active: "active" as const, enabled: "enabled" as const }, + earlyoom: { + installed: true, + active: "active" as const, + enabled: "enabled" as const, + }, }), code: "no-match", }, @@ -482,14 +519,17 @@ describe("dual DGX Spark managed-serving discovery", () => { ...value, runtimeSnapshot: { containers: [], - listeningPorts: [8000], + listeningPorts: [DUAL_SPARK_VLLM_MASTER_PORT], }, }), code: "runtime-conflict", }, { name: "an inconclusive runtime inspection", - mutate: (value: DualSparkHostObservation) => ({ ...value, runtimeInspectionComplete: false }), + mutate: (value: DualSparkHostObservation) => ({ + ...value, + runtimeInspectionComplete: false, + }), code: "runtime-unknown", }, { @@ -528,7 +568,11 @@ describe("dual DGX Spark managed-serving discovery", () => { inspections += 1; const observed = identity(target); return inspections > 2 - ? { ...observed, sshTarget: "spark-worker.local", resolvedHost: "spark-worker.local" } + ? { + ...observed, + sshTarget: "spark-worker.local", + resolvedHost: "spark-worker.local", + } : observed; }, claimBinding: () => { @@ -536,8 +580,7 @@ describe("dual DGX Spark managed-serving discovery", () => { return true; }, }; - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ kind: "unavailable", @@ -554,7 +597,12 @@ describe("dual DGX Spark managed-serving discovery", () => { ...base.deps, probeHost: (candidate) => candidate === base.localTransport && runtimeAppeared - ? host("local", { runtimeSnapshot: { containers: [], listeningPorts: [8000] } }) + ? host("local", { + runtimeSnapshot: { + containers: [], + listeningPorts: [DUAL_SPARK_VLLM_MASTER_PORT], + }, + }) : candidate === base.localTransport ? host("local") : host("peer"), @@ -563,8 +611,7 @@ describe("dual DGX Spark managed-serving discovery", () => { return true; }, }; - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); runtimeAppeared = true; expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ @@ -576,9 +623,10 @@ describe("dual DGX Spark managed-serving discovery", () => { }); it("preserves an existing binding as a hard automatic conflict", () => { - const { deps, events, bindingWrites } = fixture({ claimBinding: () => false }); - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); + const { deps, events, bindingWrites } = fixture({ + claimBinding: () => false, + }); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ kind: "unavailable", @@ -595,8 +643,7 @@ describe("dual DGX Spark managed-serving discovery", () => { throw new Error("partial write"); }, }); - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ kind: "unavailable", @@ -615,8 +662,7 @@ describe("dual DGX Spark managed-serving discovery", () => { throw new Error("encode failed"); }, }; - const detected = probeDualSparkManagedServingCapability({ env: {}, deps }); - if (detected.kind !== "ready") throw new Error("expected a detected pair"); + const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ kind: "unavailable", @@ -645,11 +691,17 @@ describe("production pinned peer transport", () => { fs.chmodSync(parent, 0o700); const statePath = path.join(parent, "dual-spark.json"); const bindingRoot = `${statePath}.ssh-binding`; - const deps = createDualSparkDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "" })); + const deps = createDualSparkDiscoveryDeps(() => ({ + status: 0, + stdout: "", + stderr: "", + })); try { expect(deps.claimBinding(statePath)).toBe(true); - fs.writeFileSync(path.join(bindingRoot, "owner"), "first\n", { mode: 0o600 }); + fs.writeFileSync(path.join(bindingRoot, "owner"), "first\n", { + mode: 0o600, + }); expect(deps.claimBinding(statePath)).toBe(false); expect(fs.readFileSync(path.join(bindingRoot, "owner"), "utf8")).toBe("first\n"); } finally { @@ -690,14 +742,16 @@ describe("production pinned peer transport", () => { } finally { for (const name of dockerNames) { const value = previous.get(name); - if (value === undefined) delete process.env[name]; - else process.env[name] = value; + value === undefined + ? Reflect.deleteProperty(process.env, name) + : Reflect.set(process.env, name, value); } } expect(calls).toHaveLength(2); const local = calls[0]!; expect(local.file).toBe("python3"); + expect(local.args).toHaveLength(2); expect(local.options.env).toMatchObject({ DOCKER_CONTEXT: "default" }); expect(local.options.env).not.toHaveProperty("DOCKER_HOST"); expect(local.options.env).not.toHaveProperty("DOCKER_CONFIG"); @@ -708,13 +762,20 @@ describe("production pinned peer transport", () => { expect(remote.options.env).not.toHaveProperty("DOCKER_CONTEXT"); expect(remote.options.env).not.toHaveProperty("DOCKER_CONFIG"); const request = JSON.parse(Buffer.from(remote.args.at(-1)!, "base64url").toString("utf8")); + expect(request.argv).toHaveLength(3); const script = request.argv[2] as string; expect(script).toContain("env.pop(name, None)"); expect(script).toContain('env["DOCKER_CONTEXT"] = "default"'); + expect(script).not.toContain("MODEL_ID"); + expect(script).not.toContain("IMAGE_REF"); }); it("requires direct routes, exact neighbors, and jumbo reachability on both rails", () => { - const deps = createDualSparkDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "" })); + const deps = createDualSparkDiscoveryDeps(() => ({ + status: 0, + stdout: "", + stderr: "", + })); const requests = [ { netdev: "enp1s0f0np0", @@ -732,34 +793,39 @@ describe("production pinned peer transport", () => { let routedThroughGateway = false; const directTransport: DualSparkReadOnlyHostTransport = { execute: (argv) => { - if (argv[1] === "-j" && argv[2] === "route") { + const routeResponse = () => ({ + status: 0, + stdout: JSON.stringify([ + { + dev: argv.at(-1), + prefsrc: argv[6], + scope: "link", + ...(routedThroughGateway ? { gateway: "192.168.100.254" } : {}), + }, + ]), + stderr: "", + }); + const pingResponse = () => ({ status: 0, stdout: "", stderr: "" }); + const neighborResponse = () => { + const request = requests.find(({ peerAddress }) => peerAddress === argv[5])!; return { status: 0, stdout: JSON.stringify([ { - dev: argv.at(-1), - prefsrc: argv[6], - scope: "link", - ...(routedThroughGateway ? { gateway: "192.168.100.254" } : {}), + dst: request.peerAddress, + dev: request.netdev, + lladdr: request.expectedPeerMac, + state: ["REACHABLE"], }, ]), stderr: "", }; - } - if (argv[0] === "ping") return { status: 0, stdout: "", stderr: "" }; - const request = requests.find(({ peerAddress }) => peerAddress === argv[5])!; - return { - status: 0, - stdout: JSON.stringify([ - { - dst: request.peerAddress, - dev: request.netdev, - lladdr: request.expectedPeerMac, - state: ["REACHABLE"], - }, - ]), - stderr: "", }; + return argv[1] === "-j" && argv[2] === "route" + ? routeResponse() + : argv[0] === "ping" + ? pingResponse() + : neighborResponse(); }, readFile: () => "", readdir: () => [], @@ -784,7 +850,9 @@ describe("production pinned peer transport", () => { const pinned = deps.openPinnedPeerTransport(identity("192.168.100.2")); try { - expect(pinned.transport.execute(["uname", "-m"])).toMatchObject({ status: 0 }); + expect(pinned.transport.execute(["uname", "-m"])).toMatchObject({ + status: 0, + }); } finally { pinned.close(); } diff --git a/src/lib/inference/serving/dual-spark-discovery.ts b/src/lib/inference/serving/dual-spark-discovery.ts index 6cff0448627..9bfac524b9c 100644 --- a/src/lib/inference/serving/dual-spark-discovery.ts +++ b/src/lib/inference/serving/dual-spark-discovery.ts @@ -10,17 +10,18 @@ import { type DualStationSshBinding, type QualifiedStationSshIdentity, } from "../vllm-station-ssh-binding.js"; -import { imageStorageRequirementBytes, modelStorageRequirementBytes } from "../vllm-storage.js"; +import { + DUAL_SPARK_VLLM_MASTER_PORT, + DUAL_SPARK_VLLM_MATERIALIZER_REF, +} from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; -import { DUAL_SPARK_PRESET_ID } from "./catalog-types.js"; import { createProductionDualSparkDiscoveryDeps } from "./dual-spark-discovery-production.js"; import { type DualSparkNodeSnapshot, type DualSparkObservedContainer, isRelatedManagedVllmContainer, } from "./dual-spark-lifecycle.js"; -import { DUAL_SPARK_VLLM_API_PORT, DUAL_SPARK_VLLM_MASTER_PORT } from "./dual-spark-materialize.js"; import { type DualSparkNodeObservation, type DualSparkPeerObservation, @@ -39,7 +40,6 @@ const HOST_PROBE_SCHEMA_VERSION = 1; const DIRECT_RAIL_PREFIX_LENGTH = 30; const EXPECTED_CX7_SPEED_MBPS = 200_000; const MINIMUM_CX7_MTU = 9_000; -const VLLM_WRITABLE_ALLOWANCE_BYTES = 816_000_000n; const MINIMUM_AVAILABLE_INODES = 1_024; const SAFE_TARGET_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; @@ -120,13 +120,9 @@ export interface DualSparkStorageCapacityObservation { export interface DualSparkStorageObservation { readonly huggingFace: DualSparkStorageCapacityObservation & { readonly cacheRoot: string; - readonly snapshotPath: string; - readonly snapshotBytes: number | null; - readonly exactSnapshotCached: boolean; }; readonly docker: DualSparkStorageCapacityObservation & { readonly dockerRootDir: string | null; - readonly exactImageCached: boolean; }; } @@ -351,24 +347,40 @@ function selectionFromEnvironment( ): Selection | DualSparkManagedServingCapability { const preset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); const peer = String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim(); - if (preset && preset !== DUAL_SPARK_PRESET_ID) { - return peer - ? unavailable( - "incompatible-selection", - `${NEMOCLAW_DGX_SPARK_PEER_ENV} cannot be combined with another serving preset.`, - ) - : notSelected("no-match", "Another managed inference preset is selected."); + if (preset) { + const catalog = loadManagedInferenceCatalog(); + const compiledPreset = catalog.presets.find( + ({ definition }) => definition.metadata.id === preset, + ); + const recipe = compiledPreset + ? catalog.recipes.find( + ({ definition }) => + definition.metadata.id === compiledPreset.definition.spec.plan.recipeRef, + )?.definition + : undefined; + if (recipe?.spec.execution.materializerRef !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { + return peer + ? unavailable( + "incompatible-selection", + `${NEMOCLAW_DGX_SPARK_PEER_ENV} cannot be combined with another serving preset.`, + ) + : notSelected("no-match", "Another managed inference preset is selected."); + } } if (peer) { try { - return { strict: true, intent: "explicit", explicitPeer: validatePeerTarget(peer) }; + return { + strict: true, + intent: "explicit", + explicitPeer: validatePeerTarget(peer), + }; } catch (error) { return unavailable("invalid-peer", (error as Error).message); } } return { - strict: preset === DUAL_SPARK_PRESET_ID, - intent: preset === DUAL_SPARK_PRESET_ID ? "explicit" : "automatic", + strict: Boolean(preset), + intent: preset ? "explicit" : "automatic", explicitPeer: null, }; } @@ -569,17 +581,11 @@ export function parseDualSparkHostObservation(value: unknown): DualSparkHostObse !validStorageCapacity(value.storage.huggingFace) || !isSafeText(value.storage.huggingFace.cacheRoot) || !path.isAbsolute(value.storage.huggingFace.cacheRoot) || - !isSafeText(value.storage.huggingFace.snapshotPath) || - !path.isAbsolute(value.storage.huggingFace.snapshotPath) || - (value.storage.huggingFace.snapshotBytes !== null && - !isSafeInteger(value.storage.huggingFace.snapshotBytes)) || - typeof value.storage.huggingFace.exactSnapshotCached !== "boolean" || !isRecord(value.storage.docker) || !validStorageCapacity(value.storage.docker) || (value.storage.docker.dockerRootDir !== null && (!isSafeText(value.storage.docker.dockerRootDir) || - !path.isAbsolute(value.storage.docker.dockerRootDir))) || - typeof value.storage.docker.exactImageCached !== "boolean" + !path.isAbsolute(value.storage.docker.dockerRootDir))) ) { throw new Error("DGX Spark host observation is invalid"); } @@ -678,7 +684,7 @@ function runtimeFailure(host: DualSparkHostObservation, label: string): Discover }; } const port = host.runtimeSnapshot.listeningPorts.find( - (entry) => entry === DUAL_SPARK_VLLM_API_PORT || entry === DUAL_SPARK_VLLM_MASTER_PORT, + (entry) => entry === DUAL_SPARK_VLLM_MASTER_PORT, ); return port === undefined ? null @@ -715,10 +721,6 @@ function validCapacity(capacity: DualSparkStorageCapacityObservation): boolean { } function storageFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { - const catalog = loadManagedInferenceCatalog(); - const recipe = catalog.recipes[0]?.definition; - if (!recipe) - return { code: "storage-unavailable", reason: "Managed inference recipe is unavailable." }; const huggingFace = host.storage.huggingFace; const docker = host.storage.docker; if (!validCapacity(huggingFace) || !validCapacity(docker)) { @@ -750,36 +752,6 @@ function storageFailure(host: DualSparkHostObservation, label: string): Discover }; } - const requirements = new Map(); - const available = new Map(); - const add = (capacity: DualSparkStorageCapacityObservation, required: bigint): void => { - const filesystemId = capacity.filesystemId!; - requirements.set(filesystemId, (requirements.get(filesystemId) ?? 0n) + required); - const bytes = BigInt(capacity.availableBytes!); - const prior = available.get(filesystemId); - available.set(filesystemId, prior === undefined || bytes < prior ? bytes : prior); - }; - add( - huggingFace, - (huggingFace.exactSnapshotCached - ? 0n - : modelStorageRequirementBytes(recipe.spec.model.downloadSizeBytes)) + - VLLM_WRITABLE_ALLOWANCE_BYTES, - ); - add( - docker, - docker.exactImageCached - ? 0n - : imageStorageRequirementBytes(recipe.spec.runtime.imageDownloadSizeBytes), - ); - for (const [filesystemId, required] of requirements) { - if ((available.get(filesystemId) ?? -1n) < required) { - return { - code: "storage-insufficient", - reason: `${label} filesystem ${filesystemId} lacks capacity for the pinned image, model, staging, and writable allowance.`, - }; - } - } return null; } @@ -1151,11 +1123,11 @@ export function probeDualSparkManagedServingCapability( } } -/** Revalidate the detected pair, then claim and persist its SSH binding after confirmation. */ -export function confirmDualSparkManagedServingCapability( +/** Revalidate the detected pair without claiming or writing its SSH binding. */ +export function revalidateDualSparkManagedServingCapability( detected: DualSparkDetectedManagedServingCapability, options: ProbeDualSparkManagedServingOptions = {}, -): DualSparkManagedServingConfirmation { +): DualSparkManagedServingCapability { const deps = options.deps ?? defaultDualSparkDiscoveryDeps; const revalidated = probeDualSparkManagedServingCapability({ ...options, @@ -1174,7 +1146,15 @@ export function confirmDualSparkManagedServingCapability( "The confirmed DGX Spark pair or its exact pretrusted SSH identity changed after selection.", ); } + return revalidated; +} +/** Atomically claim and persist a previously revalidated pair's SSH binding. */ +export function claimDualSparkManagedServingCapability( + revalidated: DualSparkDetectedManagedServingCapability, + options: Pick = {}, +): DualSparkManagedServingConfirmation { + const deps = options.deps ?? defaultDualSparkDiscoveryDeps; const statePath = revalidated.peerSshBindingStatePath; if (!deps.claimBinding(statePath)) { return confirmationUnavailable( @@ -1207,6 +1187,17 @@ export function confirmDualSparkManagedServingCapability( } } +/** Revalidate the detected pair, then claim and persist its SSH binding after confirmation. */ +export function confirmDualSparkManagedServingCapability( + detected: DualSparkDetectedManagedServingCapability, + options: ProbeDualSparkManagedServingOptions = {}, +): DualSparkManagedServingConfirmation { + const revalidated = revalidateDualSparkManagedServingCapability(detected, options); + return revalidated.kind === "ready" + ? claimDualSparkManagedServingCapability(revalidated, options) + : revalidated; +} + export type { DualSparkSpawnSync } from "./dual-spark-discovery-production.js"; export function createDualSparkDiscoveryDeps( diff --git a/src/lib/inference/serving/dual-spark-executor.test.ts b/src/lib/inference/serving/dual-spark-executor.test.ts index 4e3ebe7392b..25b711fb8fe 100644 --- a/src/lib/inference/serving/dual-spark-executor.test.ts +++ b/src/lib/inference/serving/dual-spark-executor.test.ts @@ -7,6 +7,7 @@ import { createDualStationSshBindingFixture, type DualStationSshBindingFixture, } from "../vllm-station-ssh-binding.test-support.js"; +import { NO_PREPARATION_REF } from "./adapter-registry.js"; import { assertDualSparkVllmExecutorConfig, buildDualSparkVllmRunArgs, @@ -129,6 +130,36 @@ function runtimeOverrides( }; } +type DockerCaptureHandler = (args: readonly string[], options?: DockerCaptureOptions) => string; + +function fixedDockerCapture(value: string): DockerCaptureHandler { + return () => value; +} + +function unexpectedDockerCapture(args: readonly string[]): never { + throw new Error(`unexpected Docker argv: ${args.join(" ")}`); +} + +function routeDockerCapture( + args: readonly string[], + options: DockerCaptureOptions | undefined, + handlers: { + readonly quiet: DockerCaptureHandler; + readonly inspect: DockerCaptureHandler; + readonly exec: DockerCaptureHandler; + readonly fallback: DockerCaptureHandler; + }, +): string { + const handler = args.includes("--quiet") + ? handlers.quiet + : args.includes("inspect") + ? handlers.inspect + : args[0] === "exec" + ? handlers.exec + : handlers.fallback; + return handler(args, options); +} + describe("dual-DGX-Spark vLLM executor", () => { let bindingFixture: DualStationSshBindingFixture; let plan: DualSparkVllmPlan; @@ -143,7 +174,7 @@ describe("dual-DGX-Spark vLLM executor", () => { vi.restoreAllMocks(); }); - it("builds the pinned host-network role launch without a restart policy or bearer value", () => { + it("builds the YAML-backed role launch without a restart policy or bearer value", () => { const head = plan.roles.head; const args = buildDualSparkVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)); const command = args.at(-1)!; @@ -153,38 +184,72 @@ describe("dual-DGX-Spark vLLM executor", () => { "--pull=never", "--init", "--network", - "host", + head.runtime.networkMode, "--ipc", - "host", + head.runtime.ipcMode, "--shm-size", - "64g", + String(head.runtime.sharedMemoryBytes), "--gpus", - "all", + head.runtime.gpuRequest, "--device", - "/dev/infiniband", + head.runtime.devices[0], "--ulimit", - "memlock=-1", - "stack=67108864", + `memlock=${String(head.runtime.ulimits.memlock)}`, + `stack=${String(head.runtime.ulimits.stack)}`, "--tmpfs", - "/cache/huggingface:rw,nosuid,nodev,exec,size=17179869184,mode=0700", - "/tmp:rw,nosuid,nodev,exec,size=17179869184,mode=1777", + ...head.runtime.temporaryFilesystems.map( + (filesystem) => + `${filesystem.target}:${[ + ...filesystem.options, + `size=${String(filesystem.sizeBytes)}`, + `mode=${filesystem.mode}`, + ].join(",")}`, + ), "--volume", - `${LOCAL_CACHE_ROOT}/hub:/cache/huggingface/hub:ro`, + `${LOCAL_CACHE_ROOT}/hub:${head.runtime.modelCache.target}/hub:ro`, "--env", "VLLM_API_KEY", head.image, ]), ); expect(args).not.toContain("--restart"); - expect(args).not.toContain(`${LOCAL_CACHE_ROOT}:/cache/huggingface`); + expect(args).not.toContain(`${LOCAL_CACHE_ROOT}:${head.runtime.modelCache.target}`); expect(JSON.stringify(args)).not.toContain(API_KEY); expect(command).toContain("install -m 0644 --"); - expect(command).toContain("deepseek_v4_encoding.py"); - expect(command).toContain("reasoning compatibility source text did not match exactly once"); + expect(head.preparation.ref).not.toBe(NO_PREPARATION_REF); + const boundedPreparation = head.preparation as Exclude< + typeof head.preparation, + { ref: typeof NO_PREPARATION_REF } + >; + expect(command).toContain(boundedPreparation.snapshotCopy.targetPath); + expect(command).toContain("preparation source text did not match exactly once"); expect(command).not.toContain("--api-key"); expect(command).not.toContain("$VLLM_API_KEY"); expect(command).toContain("'--host' '192.168.100.10'"); - expect(command).toContain("exec '/usr/local/bin/vllm'"); + expect(command).toContain(`exec '${head.command.executable}'`); + }); + + it("dispatches the no-op preparation and YAML-backed executable without patch steps", () => { + const head: DualSparkVllmRolePlan = { + ...plan.roles.head, + preparation: { + ref: NO_PREPARATION_REF, + phase: "container-before-exec", + modelId: plan.model.id, + modelRevision: plan.model.revision, + modelDownloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + }, + command: { + executable: "/opt/vllm/bin/vllm", + arguments: ["serve", "synthetic/model"], + }, + }; + + const command = buildDualSparkVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)).at(-1)!; + + expect(command).toContain("exec '/opt/vllm/bin/vllm' 'serve' 'synthetic/model'"); + expect(command).not.toContain("install -m"); + expect(command).not.toContain("python3 -c"); }); it("keeps the worker launch headless and free of the bearer environment key", () => { @@ -257,34 +322,63 @@ describe("dual-DGX-Spark vLLM executor", () => { ); }); + it("validates selected definition digests without pinning the aggregate catalog", () => { + const config = { + plan, + peerSshBinding: bindingFixture.binding, + localCacheRoot: LOCAL_CACHE_ROOT, + peerCacheRoot: PEER_CACHE_ROOT, + }; + const catalogExpandedElsewhere: DualSparkVllmPlan = { + ...plan, + catalogDigest: `sha256:${"e".repeat(64)}`, + }; + + expect(() => + assertDualSparkVllmExecutorConfig({ + ...config, + plan: catalogExpandedElsewhere, + }), + ).not.toThrow(); + expect(() => + assertDualSparkVllmExecutorConfig({ + ...config, + plan: { ...plan, recipeDigest: `sha256:${"f".repeat(64)}` }, + }), + ).toThrow(/selected definition digests/u); + }); + it("inspects every container plus host listeners and marks only the exact live role healthy", async () => { const headLabels = launchLabels(plan.roles.head); const foreignLabels = { "example.foreign": "true" }; - const dockerCapture = vi.fn((args: readonly string[]) => { - if (args.includes("--quiet")) return `${HEAD_ID}\n${FOREIGN_ID}\n`; - if (args.includes("inspect")) { - return [ - inspectionRow({ - id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, - running: true, - labels: headLabels, - }), - inspectionRow({ - id: FOREIGN_ID, - name: "unrelated-service", - image: "example.invalid/foreign:latest", - running: true, - labels: foreignLabels, - }), - ].join("\n"); - } - if (args[0] === "exec") return "ready"; - throw new Error(`unexpected Docker argv: ${args.join(" ")}`); - }); + const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => + routeDockerCapture(args, options, { + quiet: fixedDockerCapture(`${HEAD_ID}\n${FOREIGN_ID}\n`), + inspect: fixedDockerCapture( + [ + inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: true, + labels: headLabels, + }), + inspectionRow({ + id: FOREIGN_ID, + name: "unrelated-service", + image: "example.invalid/foreign:latest", + running: true, + labels: foreignLabels, + }), + ].join("\n"), + ), + exec: fixedDockerCapture("ready"), + fallback: unexpectedDockerCapture, + }), + ); const captureListeners = vi.fn( - () => "LISTEN 0 4096 0.0.0.0:8000 0.0.0.0:*\nLISTEN 0 128 [::]:25000 [::]:*\n", + () => + `LISTEN 0 4096 0.0.0.0:${String(plan.apiPort)} 0.0.0.0:*\nLISTEN 0 128 [::]:${String(plan.masterPort)} [::]:*\n`, ); const executor = createDualSparkVllmExecutor( { @@ -298,10 +392,16 @@ describe("dual-DGX-Spark vLLM executor", () => { const snapshot = await executor.inspectNode(plan.roles.head); - expect(snapshot.listeningPorts).toEqual([8000, 25000]); + expect(snapshot.listeningPorts).toEqual([plan.apiPort, plan.masterPort].sort((a, b) => a - b)); expect(snapshot.containers).toHaveLength(2); - expect(snapshot.containers[0]).toMatchObject({ id: HEAD_ID, healthy: true }); - expect(snapshot.containers[1]).toMatchObject({ id: FOREIGN_ID, healthy: false }); + expect(snapshot.containers[0]).toMatchObject({ + id: HEAD_ID, + healthy: true, + }); + expect(snapshot.containers[1]).toMatchObject({ + id: FOREIGN_ID, + healthy: false, + }); expect(dockerCapture).toHaveBeenCalledWith( expect.arrayContaining(["container", "inspect", HEAD_ID, FOREIGN_ID]), expect.any(Object), @@ -327,18 +427,20 @@ describe("dual-DGX-Spark vLLM executor", () => { const role = options?.env?.DOCKER_HOST ? "worker" : "head"; const rolePlan = plan.roles[role]; const id = role === "worker" ? WORKER_ID : HEAD_ID; - if (args.includes("--quiet")) return id; - if (args.includes("inspect")) { - return inspectionRow({ - id, - name: rolePlan.containerName, - image: rolePlan.image, - running: true, - labels: launchLabels(rolePlan), - }); - } - if (args[0] === "exec") return "ready"; - throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + return routeDockerCapture(args, options, { + quiet: fixedDockerCapture(id), + inspect: fixedDockerCapture( + inspectionRow({ + id, + name: rolePlan.containerName, + image: rolePlan.image, + running: true, + labels: launchLabels(rolePlan), + }), + ), + exec: fixedDockerCapture("ready"), + fallback: unexpectedDockerCapture, + }); }); let tick = 0; const executor = createDualSparkVllmExecutor( @@ -370,26 +472,28 @@ describe("dual-DGX-Spark vLLM executor", () => { const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => { const role = options?.env?.DOCKER_HOST ? "worker" : "head"; const id = role === "worker" ? WORKER_ID : FOREIGN_ID; - if (args.includes("--quiet")) return id; - if (args.includes("inspect")) { - return role === "worker" - ? inspectionRow({ - id, - name: plan.roles.worker.containerName, - image: plan.roles.worker.image, - running: true, - labels: launchLabels(plan.roles.worker), - }) - : inspectionRow({ - id, - name: foreign.name, - image: foreign.image, - running: false, - labels: foreign.labels, - }); - } - if (args[0] === "exec") return "ready"; - throw new Error(`unexpected Docker argv: ${args.join(" ")}`); + return routeDockerCapture(args, options, { + quiet: fixedDockerCapture(id), + inspect: fixedDockerCapture( + role === "worker" + ? inspectionRow({ + id, + name: plan.roles.worker.containerName, + image: plan.roles.worker.image, + running: true, + labels: launchLabels(plan.roles.worker), + }) + : inspectionRow({ + id, + name: foreign.name, + image: foreign.image, + running: false, + labels: foreign.labels, + }), + ), + exec: fixedDockerCapture("ready"), + fallback: unexpectedDockerCapture, + }); }); let tick = 0; const executor = createDualSparkVllmExecutor( @@ -417,20 +521,22 @@ describe("dual-DGX-Spark vLLM executor", () => { it("starts one exact head with the bearer only in the Docker subprocess environment", async () => { const labels = launchLabels(plan.roles.head); - const dockerCapture = vi.fn((args: readonly string[]) => { - if (args.includes("--quiet")) return HEAD_ID; - if (args.includes("inspect")) { - return inspectionRow({ - id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, - running: true, - labels, - }); - } - if (args[0] === "exec") return "ready"; - throw new Error(`unexpected Docker argv: ${args.join(" ")}`); - }); + const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => + routeDockerCapture(args, options, { + quiet: fixedDockerCapture(HEAD_ID), + inspect: fixedDockerCapture( + inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: true, + labels, + }), + ), + exec: fixedDockerCapture("ready"), + fallback: unexpectedDockerCapture, + }), + ); const dockerRunDetached = vi.fn(() => successfulDockerResult(`${HEAD_ID}\n`), ); @@ -503,24 +609,30 @@ describe("dual-DGX-Spark vLLM executor", () => { rolePlan: plan.roles.head, preparation: plan.roles.head.preparation, }), - ).resolves.toMatchObject({ ok: false, reason: expect.stringContaining("not configured") }); + ).resolves.toMatchObject({ + ok: false, + reason: expect.stringContaining("not configured"), + }); }); it("removes only the revalidated exact container ID", async () => { const labels = launchLabels(plan.roles.head); - const dockerCapture = vi.fn((args: readonly string[]) => { - if (args.includes("--quiet")) return HEAD_ID; - if (args.includes("inspect")) { - return inspectionRow({ - id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, - running: false, - labels, - }); - } - return ""; - }); + const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => + routeDockerCapture(args, options, { + quiet: fixedDockerCapture(HEAD_ID), + inspect: fixedDockerCapture( + inspectionRow({ + id: HEAD_ID, + name: plan.roles.head.containerName, + image: plan.roles.head.image, + running: false, + labels, + }), + ), + exec: fixedDockerCapture(""), + fallback: fixedDockerCapture(""), + }), + ); const dockerForceRm = vi.fn(() => successfulDockerResult()); const executor = createDualSparkVllmExecutor( { @@ -561,7 +673,10 @@ describe("dual-DGX-Spark vLLM executor", () => { ok: true, httpStatus: 200, curlStatus: 0, - body: JSON.stringify({ model: plan.model.servedName, choices: [{ message: {} }] }), + body: JSON.stringify({ + model: plan.model.servedName, + choices: [{ message: {} }], + }), stderr: "", message: "", }); @@ -584,7 +699,10 @@ describe("dual-DGX-Spark vLLM executor", () => { await expect(executor.probeModels(request)).resolves.toBe(true); await expect(executor.probeChat(request)).resolves.toBe(true); await expect( - executor.probeModels({ ...request, baseUrl: "http://attacker.invalid:8000" }), + executor.probeModels({ + ...request, + baseUrl: `http://attacker.invalid:${String(plan.apiPort)}`, + }), ).resolves.toBe(false); for (const [argv, options] of runCurlProbe.mock.calls) { expect(JSON.stringify(argv)).not.toContain(API_KEY); diff --git a/src/lib/inference/serving/dual-spark-executor.ts b/src/lib/inference/serving/dual-spark-executor.ts index f08b80b336a..46f64274783 100644 --- a/src/lib/inference/serving/dual-spark-executor.ts +++ b/src/lib/inference/serving/dual-spark-executor.ts @@ -20,7 +20,13 @@ import { type DualStationSshBinding, encodeDualStationSshBindingHandoff, } from "../vllm-station-ssh-binding.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; +import { + NO_PREPARATION_REF, + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, +} from "./adapter-registry.js"; +import { getManagedInferenceCompiledPreset, getManagedInferenceCompiledRecipe } from "./catalog.js"; +import { managedInferenceHexDigest } from "./catalog-integrity.js"; +import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; import { type DualSparkApiProbeRequest, type DualSparkContainerStartRequest, @@ -45,7 +51,6 @@ import { DUAL_SPARK_ROLE_LABEL, DUAL_SPARK_TRANSACTION_LABEL, DUAL_SPARK_VLLM_ADAPTER_ID, - DUAL_SPARK_VLLM_API_PORT, DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, DUAL_SPARK_VLLM_MASTER_PORT, DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, @@ -53,6 +58,7 @@ import { type DualSparkVllmRole, type DualSparkVllmRolePlan, } from "./dual-spark-materialize.js"; +import { materializeDualSparkVllmPreparation } from "./dual-spark-preparation.js"; import { DUAL_SPARK_TOPOLOGY_ID, DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, @@ -72,7 +78,7 @@ const PROCESS_PROBE_TIMEOUT_MS = 10_000; const PROCESS_PROBE_INTERVAL_MS = 1_000; const MAX_PROCESS_WAIT_MS = 120_000; const API_PROBE_INTERVAL_MS = 2_000; -const MAX_MODELS_PROBE_MS = 3_600_000; +const MAX_MODELS_PROBE_MS = 86_400_000; const MAX_CHAT_PROBE_MS = 120_000; const CONTAINER_INSPECTION_FORMAT = @@ -87,28 +93,21 @@ for item in glob.glob("/proc/[0-9]*/cmdline"): argv = [part.decode("utf-8") for part in raw.split(b"\0") if part] except (OSError, UnicodeDecodeError): continue - try: - index = argv.index("/usr/local/bin/vllm") - except ValueError: - continue - actual = argv[index:] - if actual[:len(expected)] != expected: - continue - tail = actual[len(expected):] - if not tail: - print("ready") - raise SystemExit(0) + for index, value in enumerate(argv): + if value == expected[0] and argv[index:] == expected: + print("ready") + raise SystemExit(0) raise SystemExit(1) `.trim(); -const REASONING_REPLACEMENT_SCRIPT = String.raw` +const EXACT_TEXT_REPLACEMENT_SCRIPT = String.raw` import base64, pathlib, sys target = pathlib.Path(sys.argv[1]) existing = base64.urlsafe_b64decode(sys.argv[2] + "==").decode("utf-8") replacement = base64.urlsafe_b64decode(sys.argv[3] + "==").decode("utf-8") content = target.read_text(encoding="utf-8") if content.count(existing) != 1: - raise SystemExit("reasoning compatibility source text did not match exactly once") + raise SystemExit("preparation source text did not match exactly once") target.write_text(content.replace(existing, replacement), encoding="utf-8") `.trim(); @@ -145,9 +144,7 @@ export interface DualSparkVllmExecutorRuntimeDeps { withLifecycleLock(operation: () => Promise): Promise; } -type ShippedRecipe = ReturnType< - typeof loadManagedInferenceCatalog ->["recipes"][number]["definition"]["spec"]; +type SelectedRecipe = ManagedInferenceServingRecipe["spec"]; const DEFAULT_DEPS: DualSparkVllmExecutorRuntimeDeps = { dockerCapture, @@ -188,7 +185,7 @@ function exactKeys(actual: object, expected: readonly string[], label: string): function recipeCommandArguments( rolePlan: DualSparkVllmRolePlan, plan: DualSparkVllmPlan, - recipe: ShippedRecipe, + recipe: SelectedRecipe, ): string[] { const staticArguments = recipe.serve.arguments.flatMap(({ name, value }) => value === undefined ? [name] : [name, String(value)], @@ -196,6 +193,8 @@ function recipeCommandArguments( return [ "serve", recipe.model.id, + "--revision", + recipe.model.revision, "--served-model-name", recipe.model.servedName, "--host", @@ -222,11 +221,12 @@ function recipeCommandArguments( function assertRolePlan( rolePlan: DualSparkVllmRolePlan, plan: DualSparkVllmPlan, - recipe: ShippedRecipe, + recipe: SelectedRecipe, ): void { const isHead = rolePlan.role === "head"; const environment = { ...recipe.runtime.environment, + HF_HOME: recipe.runtime.modelCache.target, VLLM_HOST_IP: rolePlan.fabric.address, NCCL_IB_HCA: `${rolePlan.fabric.hcaDevice}:${String(rolePlan.fabric.hcaPort)}`, NCCL_SOCKET_IFNAME: rolePlan.fabric.netdev, @@ -250,24 +250,10 @@ function assertRolePlan( [DUAL_SPARK_IMAGE_LABEL]: recipe.runtime.image, [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.model.revision, }; - const preparation = { - ref: recipe.model.preparationRef, - phase: "container-before-exec", - modelId: recipe.model.id, - modelRevision: recipe.model.revision, - modelDownloadSizeBytes: recipe.model.downloadSizeBytes, - encodingPath: recipe.model.encodingPath, - encodingSourcePath: `/cache/huggingface/hub/models--${recipe.model.id.replaceAll("/", "--")}/snapshots/${recipe.model.revision}/${recipe.model.encodingPath}`, - encodingTargetPath: - "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py", - reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py", - reasoningCompatibility: { - existingText: - 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n else:\n reasoning_effort = "high"', - replacementText: - 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n elif reasoning_effort == "high":\n reasoning_effort = "high"\n else:\n reasoning_effort = "low"', - }, - }; + const preparation = materializeDualSparkVllmPreparation({ + ...recipe.model, + modelCacheTarget: recipe.runtime.modelCache.target, + }); const fabric = { primaryRailIndex: rolePlan.fabric.primaryRailIndex, netdev: rolePlan.fabric.netdev, @@ -288,23 +274,29 @@ function assertRolePlan( execution: rolePlan.execution, image: recipe.runtime.image, runtime: { + architecture: recipe.runtime.architecture, networkMode: recipe.runtime.networkMode, ipcMode: recipe.runtime.ipcMode, sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, - gpuRequest: "all", + gpuRequest: recipe.runtime.gpuRequest, devices: recipe.runtime.devices, imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, - ulimits: { memlock: -1, stack: 67_108_864 }, - modelCache: { source: "huggingface-cache", target: "/cache/huggingface" }, + pullTimeoutSeconds: recipe.runtime.pullTimeoutSeconds, + ulimits: { + memlock: recipe.runtime.ulimits.memlock, + stack: recipe.runtime.ulimits.stackBytes, + }, + modelCache: recipe.runtime.modelCache, + temporaryFilesystems: recipe.runtime.temporaryFilesystems, }, preparation, fabric, environment, command: { - executable: "/usr/local/bin/vllm", + executable: recipe.serve.executable, arguments: recipeCommandArguments(rolePlan, plan, recipe), }, - endpoint: isHead ? `http://${plan.masterAddress}:${String(DUAL_SPARK_VLLM_API_PORT)}` : null, + endpoint: isHead ? `http://${plan.masterAddress}:${String(plan.apiPort)}` : null, baseLabels, }; if ( @@ -324,6 +316,19 @@ function assertRolePlan( } } +function recipeApiPort(recipe: SelectedRecipe): number | undefined { + const ports = recipe.serve.arguments + .filter(({ name }) => name === "--port") + .map(({ value }) => + typeof value === "number" + ? value + : typeof value === "string" && /^\d{1,5}$/u.test(value) + ? Number(value) + : Number.NaN, + ); + return ports.length === 1 && Number.isInteger(ports[0]) ? ports[0] : undefined; +} + /** Read-only validation shared by installer, receipt, recovery, and cleanup. */ export function assertDualSparkVllmExecutorConfig( config: CreateDualSparkVllmExecutorOptions, @@ -342,26 +347,53 @@ export function assertDualSparkVllmExecutorConfig( normalizedAbsoluteHostPath(config.localCacheRoot, "Local model cache root"); normalizedAbsoluteHostPath(config.peerCacheRoot, "Peer model cache root"); const { plan, peerSshBinding: binding } = config; - const catalog = loadManagedInferenceCatalog(); - const recipe = catalog.recipes[0]!.definition.spec; + const compiledPreset = getManagedInferenceCompiledPreset(plan.presetId); + const compiledRecipe = getManagedInferenceCompiledRecipe(plan.recipeId); + if ( + !compiledPreset || + !compiledRecipe || + compiledPreset.definitionDigest !== plan.presetDigest || + compiledRecipe.definitionDigest !== plan.recipeDigest || + compiledPreset.definition.spec.plan.recipeRef !== compiledRecipe.definition.metadata.id || + compiledPreset.definition.spec.plan.backend !== compiledRecipe.definition.spec.backend + ) { + throw new Error("Dual-Spark executor input does not match its selected definition digests"); + } + const recipe = compiledRecipe.definition.spec; + const topologyIdentity = { + id: plan.topologyId, + schemaVersion: plan.topologySchemaVersion, + subjectDigest: plan.topologySubjectDigest, + outputDigest: plan.topologyOutputDigest, + }; + const expectedClusterId = managedInferenceHexDigest(topologyIdentity); + const expectedPlanId = managedInferenceHexDigest({ + adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + preset: { id: plan.presetId, digest: plan.presetDigest }, + recipe: { id: plan.recipeId, digest: plan.recipeDigest }, + topology: topologyIdentity, + }); const expectedPlan = { schemaVersion: 1, adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, - catalogDigest: catalog.catalogDigest, - presetId: catalog.presets[0]!.definition.metadata.id, - recipeId: catalog.recipes[0]!.definition.metadata.id, + catalogDigest: plan.catalogDigest, + presetId: compiledPreset.definition.metadata.id, + presetDigest: compiledPreset.definitionDigest, + recipeId: compiledRecipe.definition.metadata.id, + recipeDigest: compiledRecipe.definitionDigest, topologyId: DUAL_SPARK_TOPOLOGY_ID, topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, topologySubjectDigest: plan.topologySubjectDigest, topologyOutputDigest: plan.topologyOutputDigest, - clusterId: plan.clusterId, - planId: plan.planId, + clusterId: expectedClusterId, + planId: expectedPlanId, model: { id: recipe.model.id, revision: recipe.model.revision, servedName: recipe.model.servedName, }, - apiPort: DUAL_SPARK_VLLM_API_PORT, + authentication: recipe.serve.authentication, + apiPort: recipeApiPort(recipe), masterAddress: plan.masterAddress, masterPort: DUAL_SPARK_VLLM_MASTER_PORT, readiness: { @@ -372,6 +404,9 @@ export function assertDualSparkVllmExecutorConfig( }; if ( !isDeepStrictEqual(plan, expectedPlan) || + !SHA256_PATTERN.test(plan.catalogDigest) || + !SHA256_PATTERN.test(plan.presetDigest) || + !SHA256_PATTERN.test(plan.recipeDigest) || plan.masterAddress !== plan.roles.head.fabric.address || !HEX64_PATTERN.test(plan.clusterId) || !HEX64_PATTERN.test(plan.planId) || @@ -401,19 +436,23 @@ function base64url(value: string): string { function preparationCommand(rolePlan: DualSparkVllmRolePlan): string { const preparation = rolePlan.preparation; - const command = [ - "set -Eeuo pipefail", - `test -f ${shellQuote(preparation.encodingSourcePath)}`, - `install -m 0644 -- ${shellQuote(preparation.encodingSourcePath)} ${shellQuote(preparation.encodingTargetPath)}`, - [ - "python3", - "-c", - shellQuote(REASONING_REPLACEMENT_SCRIPT), - shellQuote(preparation.reasoningModulePath), - shellQuote(base64url(preparation.reasoningCompatibility.existingText)), - shellQuote(base64url(preparation.reasoningCompatibility.replacementText)), - ].join(" "), - ]; + const command = ["set -Eeuo pipefail"]; + if (preparation.ref === SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF) { + command.push( + `test -f ${shellQuote(preparation.snapshotCopy.sourcePath)}`, + `install -m 0644 -- ${shellQuote(preparation.snapshotCopy.sourcePath)} ${shellQuote(preparation.snapshotCopy.targetPath)}`, + [ + "python3", + "-c", + shellQuote(EXACT_TEXT_REPLACEMENT_SCRIPT), + shellQuote(preparation.exactTextReplacement.targetPath), + shellQuote(base64url(preparation.exactTextReplacement.expectedText)), + shellQuote(base64url(preparation.exactTextReplacement.replacementText)), + ].join(" "), + ); + } else if (preparation.ref !== NO_PREPARATION_REF) { + throw new Error("Unsupported dual-Spark preparation"); + } const executable = shellQuote(rolePlan.command.executable); const commandArguments = rolePlan.command.arguments.map(shellQuote).join(" "); command.push(`exec ${executable} ${commandArguments}`); @@ -462,26 +501,30 @@ export function buildDualSparkVllmRunArgs( "--pull=never", "--init", "--network", - "host", + rolePlan.runtime.networkMode, "--ipc", - "host", + rolePlan.runtime.ipcMode, "--shm-size", - "64g", + String(rolePlan.runtime.sharedMemoryBytes), "--gpus", - "all", - "--device", - "/dev/infiniband", + rolePlan.runtime.gpuRequest, "--ulimit", - "memlock=-1", + `memlock=${rolePlan.runtime.ulimits.memlock === "unlimited" ? "-1" : String(rolePlan.runtime.ulimits.memlock)}`, "--ulimit", - "stack=67108864", - "--tmpfs", - "/cache/huggingface:rw,nosuid,nodev,exec,size=17179869184,mode=0700", - "--tmpfs", - "/tmp:rw,nosuid,nodev,exec,size=17179869184,mode=1777", - "--volume", - `${cacheRoot}/hub:${rolePlan.runtime.modelCache.target}/hub:ro`, + `stack=${String(rolePlan.runtime.ulimits.stack)}`, ]; + for (const device of rolePlan.runtime.devices) args.push("--device", device); + for (const temporaryFilesystem of rolePlan.runtime.temporaryFilesystems) { + args.push( + "--tmpfs", + `${temporaryFilesystem.target}:${[ + ...temporaryFilesystem.options, + `size=${String(temporaryFilesystem.sizeBytes)}`, + `mode=${temporaryFilesystem.mode}`, + ].join(",")}`, + ); + } + args.push("--volume", `${cacheRoot}/hub:${rolePlan.runtime.modelCache.target}/hub:ro`); for (const [name, value] of Object.entries(rolePlan.environment).sort(([left], [right]) => left.localeCompare(right), )) { @@ -722,11 +765,13 @@ function exactWaitObservation( : null; } -function workerFirstBoundaryIsClear(snapshot: DualSparkNodeSnapshot): boolean { +function workerFirstBoundaryIsClear( + snapshot: DualSparkNodeSnapshot, + plan: DualSparkVllmPlan, +): boolean { return ( - !snapshot.listeningPorts.some( - (port) => port === DUAL_SPARK_VLLM_API_PORT || port === DUAL_SPARK_VLLM_MASTER_PORT, - ) && !snapshot.containers.some(isRelatedManagedVllmContainer) + !snapshot.listeningPorts.some((port) => port === plan.apiPort || port === plan.masterPort) && + !snapshot.containers.some(isRelatedManagedVllmContainer) ); } @@ -747,7 +792,10 @@ async function waitForRoleProcess( ); const headAbsent = !requireHeadAbsent || - workerFirstBoundaryIsClear(inspectRoleNode(config.plan.roles.head, config, deps)); + workerFirstBoundaryIsClear( + inspectRoleNode(config.plan.roles.head, config, deps), + config.plan, + ); consecutive = observed?.running && observed.healthy && headAbsent ? consecutive + 1 : 0; if (consecutive >= stableChecks) return true; } catch { diff --git a/src/lib/inference/serving/dual-spark-fixture.test-support.ts b/src/lib/inference/serving/dual-spark-fixture.test-support.ts index 5f454308fe8..bb4b6480637 100644 --- a/src/lib/inference/serving/dual-spark-fixture.test-support.ts +++ b/src/lib/inference/serving/dual-spark-fixture.test-support.ts @@ -10,11 +10,21 @@ import { dualSparkTopologySubjectDigest, } from "./dual-spark-topology.js"; +export const FIXTURE_DUAL_SPARK_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731"; + export function fixtureDualSparkSelection(): ResolvedManagedInferenceSelection { const catalog = loadManagedInferenceCatalog(); - const preset = structuredClone(catalog.presets[0]?.definition); - const recipe = structuredClone(catalog.recipes[0]?.definition); - if (!preset || !recipe) throw new Error("managed inference fixture catalog is incomplete"); + const compiledPreset = catalog.presets.find( + ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, + ); + const compiledRecipe = catalog.recipes.find( + ({ definition }) => definition.metadata.id === compiledPreset?.definition.spec.plan.recipeRef, + ); + if (!compiledPreset || !compiledRecipe) { + throw new Error("managed inference fixture catalog is incomplete"); + } + const preset = structuredClone(compiledPreset.definition); + const recipe = structuredClone(compiledRecipe.definition); const subjectNodeIds = ["spark-head", "spark-worker"] as const; const output: DualSparkTopologyOutput = { headNodeId: "spark-head", @@ -78,6 +88,8 @@ export function fixtureDualSparkSelection(): ResolvedManagedInferenceSelection { it("defers qualified explicit legacy intent without claiming binding state", async () => { const capability = readyCapability(); const clearBinding = vi.fn(); - const confirmCapability = vi.fn(); + const revalidateCapability = vi.fn(); + const claimCapability = vi.fn(); const resolveSelection = vi.fn(); const result = await tryInstallDualSparkManagedVllm( { @@ -143,11 +155,18 @@ describe("two-Spark managed vLLM installer selection", () => { promptFn: vi.fn(), }, effects(), - { probeCapability: () => capability, confirmCapability, clearBinding, resolveSelection }, + { + probeCapability: () => capability, + revalidateCapability, + claimCapability, + clearBinding, + resolveSelection, + }, ); expect(result).toEqual({ kind: "not-selected" }); expect(resolveSelection).not.toHaveBeenCalled(); - expect(confirmCapability).not.toHaveBeenCalled(); + expect(revalidateCapability).not.toHaveBeenCalled(); + expect(claimCapability).not.toHaveBeenCalled(); expect(clearBinding).not.toHaveBeenCalled(); }); @@ -207,17 +226,184 @@ describe("two-Spark managed vLLM installer selection", () => { expect(installEffects.downloadModel).not.toHaveBeenCalled(); }); + it("admits the selected recipe port before prompting or claiming binding state", async () => { + const selection = fixtureDualSparkSelection(); + const port = Number( + selection.recipe.spec.serve.arguments.find(({ name }) => name === "--port")?.value, + ); + const base = readyCapability(); + const capability = { + ...base, + local: { + ...base.local, + runtimeSnapshot: { ...base.local.runtimeSnapshot, listeningPorts: [port] }, + }, + } as DualSparkDetectedManagedServingCapability; + const promptFn = vi.fn(async () => "yes"); + const revalidateCapability = vi.fn(); + const claimCapability = vi.fn(); + const installEffects = effects(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn }, + installEffects, + { + probeCapability: () => capability, + resolveSelection: () => selection, + revalidateCapability, + claimCapability, + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(promptFn).not.toHaveBeenCalled(); + expect(revalidateCapability).not.toHaveBeenCalled(); + expect(claimCapability).not.toHaveBeenCalled(); + expect(installEffects.prerequisites).not.toHaveBeenCalled(); + }); + + it("budgets the selected model and image at full size before prompting", async () => { + const selection = fixtureDualSparkSelection(); + const base = readyCapability(); + const capability = { + ...base, + selectionIntent: "explicit", + local: { + ...base.local, + storage: { + ...base.local.storage, + huggingFace: { ...base.local.storage.huggingFace, availableBytes: 1 }, + }, + }, + } as DualSparkDetectedManagedServingCapability; + const promptFn = vi.fn(async () => "yes"); + const claimCapability = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn }, + effects(), + { + probeCapability: () => capability, + resolveSelection: () => selection, + claimCapability, + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(promptFn).not.toHaveBeenCalled(); + expect(claimCapability).not.toHaveBeenCalled(); + }); + + it("rechecks the selected port after consent and before claiming binding state", async () => { + const capability = readyCapability(); + const selection = fixtureDualSparkSelection(); + const port = Number( + selection.recipe.spec.serve.arguments.find(({ name }) => name === "--port")?.value, + ); + const revalidated = { + ...capability, + peer: { + ...capability.peer, + runtimeSnapshot: { ...capability.peer.runtimeSnapshot, listeningPorts: [port] }, + }, + } as DualSparkDetectedManagedServingCapability; + const claimCapability = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, + effects(), + { + probeCapability: () => capability, + revalidateCapability: () => revalidated, + claimCapability, + resolveSelection: () => selection, + assertNoRuntimeReceipts: vi.fn(), + log: vi.fn(), + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(claimCapability).not.toHaveBeenCalled(); + }); + + it("does not fall through to legacy setup when storage changes after consent", async () => { + const capability = readyCapability(); + const revalidated = { + ...capability, + local: { + ...capability.local, + storage: { + ...capability.local.storage, + huggingFace: { ...capability.local.storage.huggingFace, availableBytes: 1 }, + }, + }, + } as DualSparkDetectedManagedServingCapability; + const claimCapability = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, + effects(), + { + probeCapability: () => capability, + revalidateCapability: () => revalidated, + claimCapability, + resolveSelection: () => fixtureDualSparkSelection(), + assertNoRuntimeReceipts: vi.fn(), + log: vi.fn(), + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(claimCapability).not.toHaveBeenCalled(); + }); + + it("does not fall through to legacy setup when selection changes after consent", async () => { + const capability = readyCapability(); + const resolveSelection = vi + .fn() + .mockReturnValueOnce(fixtureDualSparkSelection()) + .mockReturnValueOnce({ + outcome: "no-match", + code: "requirements-not-met", + message: "selected requirements changed", + }); + const claimCapability = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, + effects(), + { + probeCapability: () => capability, + revalidateCapability: () => capability, + claimCapability, + resolveSelection, + assertNoRuntimeReceipts: vi.fn(), + log: vi.fn(), + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(resolveSelection).toHaveBeenCalledTimes(2); + expect(claimCapability).not.toHaveBeenCalled(); + }); + it("revalidates only after consent and stops before effects when the pair changed", async () => { const capability = readyCapability(); const installEffects = effects(); const clearBinding = vi.fn(); - const confirmCapability = vi.fn(() => ({ + const revalidateCapability = vi.fn(() => ({ kind: "unavailable" as const, code: "runtime-conflict" as const, reason: "a related listener appeared after confirmation", })); + const claimCapability = vi.fn(); const promptFn = vi.fn(async () => { - expect(confirmCapability).not.toHaveBeenCalled(); + expect(revalidateCapability).not.toHaveBeenCalled(); expect(installEffects.prerequisites).not.toHaveBeenCalled(); return "yes"; }); @@ -228,7 +414,8 @@ describe("two-Spark managed vLLM installer selection", () => { installEffects, { probeCapability: () => capability, - confirmCapability, + revalidateCapability, + claimCapability, resolveSelection: () => fixtureDualSparkSelection(), assertNoRuntimeReceipts, clearBinding, @@ -239,13 +426,48 @@ describe("two-Spark managed vLLM installer selection", () => { expect(result).toEqual({ kind: "handled", result: { ok: false } }); expect(assertNoRuntimeReceipts).toHaveBeenCalledTimes(2); - expect(confirmCapability).toHaveBeenCalledOnce(); + expect(revalidateCapability).toHaveBeenCalledOnce(); + expect(claimCapability).not.toHaveBeenCalled(); expect(installEffects.prerequisites).not.toHaveBeenCalled(); expect(installEffects.pullImage).not.toHaveBeenCalled(); expect(installEffects.downloadModel).not.toHaveBeenCalled(); expect(clearBinding).not.toHaveBeenCalled(); }); + it("applies selected-model access preflight before prompting or effects", async () => { + const capability = readyCapability(); + const installEffects = effects(); + const promptFn = vi.fn(async () => "yes"); + const assertGatedModelAccess = vi.fn(() => { + throw new Error("selected model access is unavailable"); + }); + const revalidateCapability = vi.fn(); + const claimCapability = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: false, promptFn }, + installEffects, + { + probeCapability: () => capability, + resolveSelection: () => fixtureDualSparkSelection(), + assertGatedModelAccess, + revalidateCapability, + claimCapability, + log: vi.fn(), + error: vi.fn(), + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: false } }); + expect(assertGatedModelAccess).toHaveBeenCalledOnce(); + expect(promptFn).not.toHaveBeenCalled(); + expect(revalidateCapability).not.toHaveBeenCalled(); + expect(claimCapability).not.toHaveBeenCalled(); + expect(installEffects.prerequisites).not.toHaveBeenCalled(); + expect(installEffects.pullImage).not.toHaveBeenCalled(); + expect(installEffects.downloadModel).not.toHaveBeenCalled(); + }); + it("stages both exact nodes, launches, persists ownership, and retires temporary binding state", async () => { const capability = readyCapability(); const confirmed = confirmedCapability(capability); @@ -293,7 +515,8 @@ describe("two-Spark managed vLLM installer selection", () => { installEffects, { probeCapability: () => capability, - confirmCapability: () => confirmed, + revalidateCapability: () => capability, + claimCapability: () => confirmed, resolveSelection: () => selection, createExecutor: createExecutor as never, start: start as never, @@ -342,7 +565,8 @@ describe("two-Spark managed vLLM installer selection", () => { effects(), { probeCapability: () => capability, - confirmCapability: () => confirmedCapability(capability), + revalidateCapability: () => capability, + claimCapability: () => confirmedCapability(capability), resolveSelection: () => selection, createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, start: async () => successfulStart(false), @@ -370,7 +594,8 @@ describe("two-Spark managed vLLM installer selection", () => { effects(), { probeCapability: () => capability, - confirmCapability: () => confirmedCapability(capability), + revalidateCapability: () => capability, + claimCapability: () => confirmedCapability(capability), resolveSelection: () => fixtureDualSparkSelection(), createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, start: async () => successfulStart(false), @@ -404,7 +629,8 @@ describe("two-Spark managed vLLM installer selection", () => { effects(), { probeCapability: () => capability, - confirmCapability: () => confirmedCapability(capability), + revalidateCapability: () => capability, + claimCapability: () => confirmedCapability(capability), resolveSelection: () => fixtureDualSparkSelection(), createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, start: async () => ({ @@ -435,7 +661,8 @@ describe("two-Spark managed vLLM installer selection", () => { effects(), { probeCapability: () => capability, - confirmCapability: () => confirmedCapability(capability), + revalidateCapability: () => capability, + claimCapability: () => confirmedCapability(capability), resolveSelection: () => fixtureDualSparkSelection(), createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, start: async () => successfulStart(true), @@ -456,20 +683,23 @@ describe("two-Spark managed vLLM installer selection", () => { it("does not claim or clear binding state when the operator declines", async () => { const capability = readyCapability(); const clearBinding = vi.fn(); - const confirmCapability = vi.fn(); + const revalidateCapability = vi.fn(); + const claimCapability = vi.fn(); const result = await tryInstallDualSparkManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "no" }, effects(), { probeCapability: () => capability, - confirmCapability, + revalidateCapability, + claimCapability, resolveSelection: () => fixtureDualSparkSelection(), clearBinding, log: vi.fn(), }, ); expect(result).toEqual({ kind: "handled", result: { ok: false } }); - expect(confirmCapability).not.toHaveBeenCalled(); + expect(revalidateCapability).not.toHaveBeenCalled(); + expect(claimCapability).not.toHaveBeenCalled(); expect(clearBinding).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/inference/serving/dual-spark-installer.ts b/src/lib/inference/serving/dual-spark-installer.ts index 4b1fe50721d..82792a9bde2 100644 --- a/src/lib/inference/serving/dual-spark-installer.ts +++ b/src/lib/inference/serving/dual-spark-installer.ts @@ -4,21 +4,24 @@ import { isAffirmativeAnswer } from "../../onboard/prompt-helpers.js"; import type { VllmProfile } from "../vllm.js"; import { ensureManagedVllmApiKey } from "../vllm-api-key.js"; -import type { VllmModelDef } from "../vllm-models.js"; -import { VLLM_EXTRA_ARGS_ENV } from "../vllm-models.js"; +import { assertGatedModelAccess, type VllmModelDef, VLLM_EXTRA_ARGS_ENV } from "../vllm-models.js"; import { clearDualStationSshBinding } from "../vllm-station-ssh-binding.js"; +import { imageStorageRequirementBytes, modelStorageRequirementBytes } from "../vllm-storage.js"; import { - DUAL_SPARK_PRESET_ID, type ManagedInferenceResolution, type ManagedInferenceResolverInput, + type ManagedInferenceServingRecipe, } from "./catalog-types.js"; import { - confirmDualSparkManagedServingCapability, + claimDualSparkManagedServingCapability, type DualSparkConfirmedManagedServingCapability, type DualSparkDetectedManagedServingCapability, + type DualSparkHostObservation, + type DualSparkStorageCapacityObservation, NEMOCLAW_DGX_SPARK_PEER_ENV, NEMOCLAW_SERVING_PRESET_ENV, probeDualSparkManagedServingCapability, + revalidateDualSparkManagedServingCapability, } from "./dual-spark-discovery.js"; import { type CreateDualSparkVllmExecutorOptions, @@ -31,7 +34,7 @@ import { startAutomaticDualSparkVllm, } from "./dual-spark-lifecycle.js"; import { - DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, + DUAL_SPARK_VLLM_MASTER_PORT, type DualSparkVllmPlan, materializeDualSparkVllmPlan, } from "./dual-spark-materialize.js"; @@ -72,7 +75,8 @@ export type DualSparkInstallerResult = interface DualSparkInstallerDeps { readonly probeCapability: typeof probeDualSparkManagedServingCapability; - readonly confirmCapability: typeof confirmDualSparkManagedServingCapability; + readonly revalidateCapability: typeof revalidateDualSparkManagedServingCapability; + readonly claimCapability: typeof claimDualSparkManagedServingCapability; readonly resolveSelection: ( input: ManagedInferenceResolverInput, ) => ManagedInferenceResolution; @@ -84,6 +88,7 @@ interface DualSparkInstallerDeps { readonly ensureApiKey: typeof ensureManagedVllmApiKey; readonly assertNoRuntimeReceipts: typeof assertNoManagedDistributedVllmRuntimeReceipts; readonly clearBinding: typeof clearDualStationSshBinding; + readonly assertGatedModelAccess: typeof assertGatedModelAccess; readonly log: (line?: string) => void; readonly error: (line: string) => void; readonly warn: (line: string) => void; @@ -91,7 +96,8 @@ interface DualSparkInstallerDeps { const DEFAULT_DEPS: DualSparkInstallerDeps = { probeCapability: probeDualSparkManagedServingCapability, - confirmCapability: confirmDualSparkManagedServingCapability, + revalidateCapability: revalidateDualSparkManagedServingCapability, + claimCapability: claimDualSparkManagedServingCapability, resolveSelection: resolveManagedInferenceServing, materializePlan: materializeDualSparkVllmPlan, createExecutor: createDualSparkVllmExecutor, @@ -101,53 +107,168 @@ const DEFAULT_DEPS: DualSparkInstallerDeps = { ensureApiKey: ensureManagedVllmApiKey, assertNoRuntimeReceipts: assertNoManagedDistributedVllmRuntimeReceipts, clearBinding: clearDualStationSshBinding, + assertGatedModelAccess, log: (line = "") => console.log(line), error: (line) => console.error(line), warn: (line) => console.warn(line), }; -function managedProfile(plan: DualSparkVllmPlan): VllmProfile { +const VLLM_WRITABLE_ALLOWANCE_BYTES = 816_000_000n; + +type SelectedRecipeAdmissionFailure = { + readonly code: + | "runtime-conflict" + | "runtime-unknown" + | "storage-unavailable" + | "storage-insufficient"; + readonly reason: string; +}; + +function recipeApiPort(recipe: ManagedInferenceServingRecipe): number | null { + const ports = recipe.spec.serve.arguments + .filter(({ name }) => name === "--port") + .map(({ value }) => Number(value)); + return ports.length === 1 && + Number.isSafeInteger(ports[0]) && + ports[0]! > 0 && + ports[0]! <= 65_535 + ? ports[0]! + : null; +} + +function selectedHostStorageFailure( + host: DualSparkHostObservation, + label: string, + recipe: ManagedInferenceServingRecipe, +): SelectedRecipeAdmissionFailure | null { + const requirements = new Map(); + const available = new Map(); + const add = (capacity: DualSparkStorageCapacityObservation, required: bigint): boolean => { + if (capacity.filesystemId === null || capacity.availableBytes === null) return false; + requirements.set( + capacity.filesystemId, + (requirements.get(capacity.filesystemId) ?? 0n) + required, + ); + const bytes = BigInt(capacity.availableBytes); + const prior = available.get(capacity.filesystemId); + available.set(capacity.filesystemId, prior === undefined || bytes < prior ? bytes : prior); + return true; + }; + if ( + !add( + host.storage.huggingFace, + modelStorageRequirementBytes(recipe.spec.model.downloadSizeBytes) + + VLLM_WRITABLE_ALLOWANCE_BYTES, + ) || + !add( + host.storage.docker, + imageStorageRequirementBytes(recipe.spec.runtime.imageDownloadSizeBytes), + ) + ) { + return { + code: "storage-unavailable", + reason: `${label} cache or Docker filesystem capacity could not be proven.`, + }; + } + for (const [filesystemId, required] of requirements) { + if ((available.get(filesystemId) ?? -1n) < required) { + return { + code: "storage-insufficient", + reason: `${label} filesystem ${filesystemId} lacks capacity for the selected image, model, staging, and writable allowance.`, + }; + } + } + return null; +} + +function selectedRecipeAdmissionFailure( + capability: DualSparkDetectedManagedServingCapability, + recipe: ManagedInferenceServingRecipe, +): SelectedRecipeAdmissionFailure | null { + const apiPort = recipeApiPort(recipe); + if (apiPort === null) { + return { code: "runtime-unknown", reason: "The selected recipe serving port is invalid." }; + } + for (const [host, label] of [ + [capability.local, "Local DGX Spark"], + [capability.peer, "Peer DGX Spark"], + ] as const) { + const occupied = host.runtimeSnapshot.listeningPorts.find( + (port) => port === apiPort || port === DUAL_SPARK_VLLM_MASTER_PORT, + ); + if (occupied !== undefined) { + return { + code: "runtime-conflict", + reason: `${label} port ${String(occupied)} is already in use; its listener was not changed.`, + }; + } + const storage = selectedHostStorageFailure(host, label, recipe); + if (storage) return storage; + } + return null; +} + +function structuredArguments(recipe: ManagedInferenceServingRecipe): string[] { + return recipe.spec.serve.arguments.flatMap(({ name, value }) => + value === undefined ? [name] : [name, String(value)], + ); +} + +function requiredPositiveIntegerArgument( + recipe: ManagedInferenceServingRecipe, + name: string, +): number { + const matches = recipe.spec.serve.arguments.filter((argument) => argument.name === name); + const value = matches.length === 1 ? Number(matches[0]?.value) : Number.NaN; + if (!Number.isSafeInteger(value) || value <= 0) { + throw new Error(`Selected serving recipe must define one positive ${name} argument.`); + } + return value; +} + +function managedProfile( + plan: DualSparkVllmPlan, + recipe: ManagedInferenceServingRecipe, +): VllmProfile { return { - name: "Two DGX Sparks", + name: recipe.metadata.displayName, platform: "spark", image: plan.roles.head.image, imageDownloadSizeBytes: plan.roles.head.runtime.imageDownloadSizeBytes, - defaultModel: managedModel(plan), - containerName: DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, + defaultModel: managedModel(plan, recipe), + containerName: plan.roles.head.containerName, dockerRunFlags: [], - pullTimeoutSec: 12 * 60 * 60, + pullTimeoutSec: recipe.spec.runtime.pullTimeoutSeconds, loadTimeoutSec: Math.ceil(plan.readiness.timeoutMs / 1000), modelDownloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, }; } -function managedModel(plan: DualSparkVllmPlan): VllmModelDef { +function managedModel( + plan: DualSparkVllmPlan, + recipe: ManagedInferenceServingRecipe, +): VllmModelDef { return { id: plan.model.id, - label: "DeepSeek V4 Flash 0731", + label: recipe.metadata.displayName, envValue: plan.model.servedName, downloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, - maxModelLen: 1_048_576, + maxModelLen: requiredPositiveIntegerArgument(recipe, "--max-model-len"), revision: plan.model.revision, servedModelId: plan.model.servedName, - modelArgs: [], - gated: false, + modelArgs: structuredArguments(recipe), + gated: recipe.spec.model.gated, platforms: ["spark"], - installFastSafetensors: false, + installFastSafetensors: recipe.spec.model.installFastSafetensors, }; } -function selectionIntent( - capability: DualSparkDetectedManagedServingCapability, - env: NodeJS.ProcessEnv, -) { +function selectionIntent(env: NodeJS.ProcessEnv) { const configuredPreset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); const configuredModel = String(env.NEMOCLAW_VLLM_MODEL ?? "").trim(); const extraArguments = String(env[VLLM_EXTRA_ARGS_ENV] ?? "").trim(); return { - ...(configuredPreset || capability.selectionIntent === "explicit" - ? { preset: configuredPreset || DUAL_SPARK_PRESET_ID } - : {}), + ...(configuredPreset ? { preset: configuredPreset } : {}), ...(configuredModel ? { vllmModel: configuredModel } : {}), ...(extraArguments ? { vllmExtraArguments: [extraArguments] } : {}), }; @@ -198,12 +319,38 @@ function printSummary( function resolutionFailure( resolution: Exclude, { outcome: "selected" }>, + selectionIntent: DualSparkDetectedManagedServingCapability["selectionIntent"], + allowAutomaticFallback: boolean, deps: DualSparkInstallerDeps, ): DualSparkInstallerResult { + if ( + allowAutomaticFallback && + selectionIntent === "automatic" && + resolution.outcome === "no-match" + ) { + return { kind: "not-selected" }; + } deps.error(` Two-Spark managed vLLM setup unavailable: ${resolution.message}`); return { kind: "handled", result: { ok: false } }; } +function admissionFailure( + failure: SelectedRecipeAdmissionFailure, + selectionIntent: DualSparkDetectedManagedServingCapability["selectionIntent"], + allowAutomaticFallback: boolean, + deps: DualSparkInstallerDeps, +): DualSparkInstallerResult { + if ( + allowAutomaticFallback && + selectionIntent === "automatic" && + (failure.code === "storage-unavailable" || failure.code === "storage-insufficient") + ) { + return { kind: "not-selected" }; + } + deps.error(` Two-Spark managed vLLM setup stopped: ${failure.reason}`); + return { kind: "handled", result: { ok: false } }; +} + function receiptInput( capability: DualSparkConfirmedManagedServingCapability, plan: DualSparkVllmPlan, @@ -231,14 +378,6 @@ export async function tryInstallDualSparkManagedVllm( const deferToLegacy = automaticIntentDefersToLegacy(env); const deps = { ...DEFAULT_DEPS, ...overrides }; - const configuredPreset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); - if (configuredPreset && configuredPreset !== DUAL_SPARK_PRESET_ID) { - deps.error( - ` Managed vLLM setup stopped: ${NEMOCLAW_SERVING_PRESET_ENV} selects unsupported profile ${configuredPreset}.`, - ); - return { kind: "handled", result: { ok: false } }; - } - try { deps.assertNoRuntimeReceipts(); } catch (error) { @@ -266,10 +405,14 @@ export async function tryInstallDualSparkManagedVllm( const previewResolution = deps.resolveSelection({ readinessReports: detected.readiness, topologyQualifications: [detected.topology], - intent: selectionIntent(detected, env), + intent: selectionIntent(env), }); if (previewResolution.outcome !== "selected") { - return resolutionFailure(previewResolution, deps); + return resolutionFailure(previewResolution, detected.selectionIntent, true, deps); + } + const previewAdmission = selectedRecipeAdmissionFailure(detected, previewResolution.recipe); + if (previewAdmission) { + return admissionFailure(previewAdmission, detected.selectionIntent, true, deps); } let previewPlan: DualSparkVllmPlan; @@ -279,6 +422,12 @@ export async function tryInstallDualSparkManagedVllm( deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); return { kind: "handled", result: { ok: false } }; } + try { + deps.assertGatedModelAccess(managedModel(previewPlan, previewResolution.recipe), env); + } catch (error) { + deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + return { kind: "handled", result: { ok: false } }; + } printSummary(detected, previewPlan, deps); effects.printDownloadAuthentication(options.nonInteractive); deps.log(); @@ -294,19 +443,45 @@ export async function tryInstallDualSparkManagedVllm( return { kind: "handled", result: { ok: false } }; } - const confirmation = deps.confirmCapability(detected, { env }); + const revalidated = deps.revalidateCapability(detected, { env }); + if (revalidated.kind !== "ready") { + deps.error(` Two-Spark managed vLLM setup stopped: ${revalidated.reason}`); + return { kind: "handled", result: { ok: false } }; + } + + const revalidatedResolution = deps.resolveSelection({ + readinessReports: revalidated.readiness, + topologyQualifications: [revalidated.topology], + intent: selectionIntent(env), + }); + if (revalidatedResolution.outcome !== "selected") { + return resolutionFailure(revalidatedResolution, revalidated.selectionIntent, false, deps); + } + const revalidatedAdmission = selectedRecipeAdmissionFailure( + revalidated, + revalidatedResolution.recipe, + ); + if (revalidatedAdmission) { + return admissionFailure(revalidatedAdmission, revalidated.selectionIntent, false, deps); + } + if ( + revalidatedResolution.presetDigest !== previewResolution.presetDigest || + revalidatedResolution.recipeDigest !== previewResolution.recipeDigest + ) { + deps.error(" Two-Spark managed vLLM setup stopped: the selected profile changed."); + return { kind: "handled", result: { ok: false } }; + } + + const confirmation = deps.claimCapability(revalidated); if (confirmation.kind !== "ready") { deps.error(` Two-Spark managed vLLM setup stopped: ${confirmation.reason}`); return { kind: "handled", result: { ok: false } }; } confirmedBinding = confirmation; - - const resolution = deps.resolveSelection({ - readinessReports: confirmation.readiness, - topologyQualifications: [confirmation.topology], - intent: selectionIntent(confirmation, env), - }); - if (resolution.outcome !== "selected") return resolutionFailure(resolution, deps); + const resolution = { + ...revalidatedResolution, + topologyQualification: confirmation.topology, + }; let plan: DualSparkVllmPlan; try { @@ -327,8 +502,8 @@ export async function tryInstallDualSparkManagedVllm( return { kind: "handled", result: { ok: false } }; } - const profile = managedProfile(plan); - const model = managedModel(plan); + const profile = managedProfile(plan, resolution.recipe); + const model = managedModel(plan, resolution.recipe); options.beforeInstall?.(plan.model.servedName); const prerequisites = effects.prerequisites(); diff --git a/src/lib/inference/serving/dual-spark-lifecycle.test.ts b/src/lib/inference/serving/dual-spark-lifecycle.test.ts index 01607f24316..c3b7cbd64ef 100644 --- a/src/lib/inference/serving/dual-spark-lifecycle.test.ts +++ b/src/lib/inference/serving/dual-spark-lifecycle.test.ts @@ -333,8 +333,8 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "start-failed" }); - if (result.ok) throw new Error("expected lifecycle failure"); - expect(result.rollbackErrors).toContain( + const failed = result as Extract; + expect(failed.rollbackErrors).toContain( "dual-Spark post-failure runtime state could not be proven clear; SSH ownership state was retained", ); expect(harness.removeContainer).not.toHaveBeenCalled(); @@ -362,7 +362,11 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); - expect(result).toMatchObject({ ok: false, code: "health-failed", rollbackErrors: [] }); + expect(result).toMatchObject({ + ok: false, + code: "health-failed", + rollbackErrors: [], + }); expect(harness.removeContainer.mock.calls.map((call) => call[1])).toEqual([HEAD_ID, WORKER_ID]); expect(harness.events).toContain("probe:models"); expect(harness.events).toContain("probe:chat"); @@ -389,8 +393,8 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "health-failed" }); - if (result.ok) throw new Error("expected lifecycle failure"); - expect(result.rollbackErrors).toContain( + const failed = result as Extract; + expect(failed.rollbackErrors).toContain( "worker rollback ownership changed; container was left untouched", ); expect(harness.removeContainer.mock.calls.map((call) => call[1])).toEqual([HEAD_ID]); @@ -403,11 +407,17 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { head: { containers: [], listeningPorts: [] }, worker: { containers: [], listeningPorts: [25000] }, }), - ).toEqual({ outcome: "conflict", reason: "worker port 25000 is already in use" }); + ).toEqual({ + outcome: "conflict", + reason: "worker port 25000 is already in use", + }); }); it("cleans up only a complete exact pair and retains all cache state", async () => { - harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [] }; + harness.snapshots.head = { + containers: [managedContainer(plan, "head")], + listeningPorts: [], + }; harness.snapshots.worker = { containers: [managedContainer(plan, "worker")], listeningPorts: [], @@ -415,30 +425,43 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { const result = await cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps); - expect(result).toEqual({ ok: true, removedContainerIds: [HEAD_ID, WORKER_ID] }); + expect(result).toEqual({ + ok: true, + removedContainerIds: [HEAD_ID, WORKER_ID], + }); expect(harness.stageNode).not.toHaveBeenCalled(); }); it("retries cleanup after one receipt-owned container was already removed", async () => { - harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [] }; + harness.snapshots.head = { + containers: [managedContainer(plan, "head")], + listeningPorts: [], + }; harness.snapshots.worker = { containers: [managedContainer(plan, "worker")], listeningPorts: [], }; let workerAttempts = 0; harness.removeContainer.mockImplementation(async (rolePlan, id) => { - if (rolePlan.role === "worker" && workerAttempts++ === 0) { - return { ok: false, reason: "worker daemon unavailable" }; - } - harness.snapshots[rolePlan.role] = { - ...harness.snapshots[rolePlan.role], - containers: harness.snapshots[rolePlan.role].containers.filter( - (container) => container.id !== id, - ), + const shouldFailWorker = rolePlan.role === "worker" && workerAttempts === 0; + workerAttempts += Number(rolePlan.role === "worker"); + const removeOwnedContainer = () => { + harness.snapshots[rolePlan.role] = { + ...harness.snapshots[rolePlan.role], + containers: harness.snapshots[rolePlan.role].containers.filter( + (container) => container.id !== id, + ), + }; + return { ok: true } as const; }; - return { ok: true }; + return shouldFailWorker + ? ({ ok: false, reason: "worker daemon unavailable" } as const) + : removeOwnedContainer(); }); - const ownership = { headContainerId: HEAD_ID, workerContainerId: WORKER_ID }; + const ownership = { + headContainerId: HEAD_ID, + workerContainerId: WORKER_ID, + }; await expect( cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps, ownership), diff --git a/src/lib/inference/serving/dual-spark-lifecycle.ts b/src/lib/inference/serving/dual-spark-lifecycle.ts index 4ca6a3c606a..2afd09ea218 100644 --- a/src/lib/inference/serving/dual-spark-lifecycle.ts +++ b/src/lib/inference/serving/dual-spark-lifecycle.ts @@ -7,9 +7,6 @@ import { DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, DUAL_SPARK_MANAGED_LABEL, DUAL_SPARK_TRANSACTION_LABEL, - DUAL_SPARK_VLLM_API_PORT, - DUAL_SPARK_VLLM_IMAGE, - DUAL_SPARK_VLLM_MASTER_PORT, DUAL_SPARK_VLLM_PROJECT_ID, type DualSparkVllmPlan, type DualSparkVllmRolePlan, @@ -298,7 +295,7 @@ export function classifyDualSparkExistingState( ["worker", snapshots.worker], ] as const) { const occupied = snapshot.listeningPorts.find( - (port) => port === DUAL_SPARK_VLLM_API_PORT || port === DUAL_SPARK_VLLM_MASTER_PORT, + (port) => port === plan.apiPort || port === plan.masterPort, ); if (occupied !== undefined) { return { outcome: "conflict", reason: `${node} port ${String(occupied)} is already in use` }; diff --git a/src/lib/inference/serving/dual-spark-materialize.test.ts b/src/lib/inference/serving/dual-spark-materialize.test.ts index a18b5148a2e..598a3b5448e 100644 --- a/src/lib/inference/serving/dual-spark-materialize.test.ts +++ b/src/lib/inference/serving/dual-spark-materialize.test.ts @@ -3,55 +3,238 @@ import { describe, expect, it } from "vitest"; +import { + NO_PREPARATION_REF, + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, +} from "./adapter-registry.js"; +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { managedInferenceDigest, managedInferenceTextDigest } from "./catalog-integrity.js"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ResolvedManagedInferenceSelection, +} from "./catalog-types.js"; import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; import { - DUAL_SPARK_VLLM_API_PORT, + DUAL_SPARK_PRESET_LABEL, + DUAL_SPARK_RECIPE_LABEL, DUAL_SPARK_VLLM_MASTER_PORT, materializeDualSparkVllmPlan, } from "./dual-spark-materialize.js"; -import { dualSparkTopologyOutputDigest } from "./dual-spark-topology.js"; +import { + type DualSparkTopologyOutput, + dualSparkTopologyOutputDigest, +} from "./dual-spark-topology.js"; + +interface SyntheticProfile { + readonly catalog: CompiledManagedInferenceCatalog; + readonly selection: ResolvedManagedInferenceSelection; +} + +function selectionWithDigests(): ResolvedManagedInferenceSelection { + const selection = fixtureDualSparkSelection(); + return { + ...selection, + presetDigest: managedInferenceDigest(selection.preset), + recipeDigest: managedInferenceDigest(selection.recipe), + }; +} + +function syntheticSecondProfile(): SyntheticProfile { + const baseCatalog = loadManagedInferenceCatalog(); + const baseSelection = selectionWithDigests(); + const topology = baseSelection.topologyQualification; + const basePreset = baseCatalog.presets.find( + ({ definition }) => definition.metadata.id === baseSelection.preset.metadata.id, + )?.definition; + const baseRecipe = baseCatalog.recipes.find( + ({ definition }) => definition.metadata.id === baseSelection.recipe.metadata.id, + )?.definition; + expect(basePreset).toBeDefined(); + expect(baseRecipe).toBeDefined(); + const presetTemplate = basePreset as ManagedInferenceServingPreset; + const recipeTemplate = baseRecipe as ManagedInferenceServingRecipe; + + const recipe: ManagedInferenceServingRecipe = { + ...recipeTemplate, + metadata: { + id: "vllm.synthetic-model.spark-dual.v1", + displayName: "Synthetic model on two compatible nodes", + }, + spec: { + ...recipeTemplate.spec, + model: { + ...recipeTemplate.spec.model, + id: "example-org/Synthetic-Model", + revision: "b".repeat(40), + servedName: "synthetic-model", + downloadSizeBytes: 1_234_567, + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { + sourcePath: "assets/synthetic_tokenizer.py", + targetPath: "/opt/synthetic-vllm/tokenizers/copied.py", + }, + exactTextReplacement: { + targetPath: "/opt/synthetic-vllm/parsers/reasoning.py", + expectedText: "MODE = 'legacy'", + replacementText: "MODE = 'compatible'", + }, + }, + }, + runtime: { + ...recipeTemplate.spec.runtime, + image: `registry.example.test/inference/vllm@sha256:${"c".repeat(64)}`, + imageDownloadSizeBytes: 7_654_321, + pullTimeoutSeconds: 7_200, + sharedMemoryBytes: 8_589_934_592, + gpuRequest: "device=all", + devices: ["/dev/infiniband", "/dev/synthetic"], + ulimits: { memlock: "unlimited", stackBytes: 33_554_432 }, + modelCache: { source: "huggingface-cache", target: "/models/cache" }, + temporaryFilesystems: [ + { + target: "/models/cache", + sizeBytes: 4_294_967_296, + mode: "0700", + options: ["rw", "nosuid", "nodev"], + }, + ], + environment: { SYNTHETIC_PROFILE: "enabled" }, + }, + serve: { + ...recipeTemplate.spec.serve, + executable: "/opt/vllm/bin/vllm", + arguments: [ + { name: "--port", value: 9_001 }, + { name: "--max-model-len", value: 4_096 }, + { name: "--generation-config", value: "auto" }, + ], + }, + readiness: { timeoutSeconds: 900, expectedModel: "synthetic-model" }, + }, + }; + const preset: ManagedInferenceServingPreset = { + ...presetTemplate, + metadata: { + id: "vllm.synthetic-profile.spark-dual", + displayName: "Synthetic profile on two compatible nodes", + }, + spec: { + ...presetTemplate.spec, + priority: 399, + plan: { ...presetTemplate.spec.plan, recipeRef: recipe.metadata.id }, + }, + }; + const recipeDigest = managedInferenceDigest(recipe); + const presetDigest = managedInferenceDigest(preset); + const recipeSourceFile = "managed-inference/recipes/vllm.synthetic-model.spark-dual.v1.yaml"; + const presetSourceFile = "managed-inference/presets/vllm.synthetic-profile.spark-dual.yaml"; + const sourceFiles = [ + ...baseCatalog.sourceFiles, + { + path: presetSourceFile, + digest: managedInferenceTextDigest("synthetic preset"), + }, + { + path: recipeSourceFile, + digest: managedInferenceTextDigest("synthetic recipe"), + }, + ]; + const catalogContents = { + compilerVersion: baseCatalog.compilerVersion, + presets: [ + ...baseCatalog.presets, + { + definition: preset, + definitionDigest: presetDigest, + sourceFile: presetSourceFile, + }, + ], + recipes: [ + ...baseCatalog.recipes, + { + definition: recipe, + definitionDigest: recipeDigest, + sourceFile: recipeSourceFile, + }, + ], + schemaVersion: baseCatalog.schemaVersion, + sourceFiles, + sourceRevision: managedInferenceDigest(sourceFiles), + } as const; + const catalog: CompiledManagedInferenceCatalog = { + ...catalogContents, + catalogDigest: managedInferenceDigest(catalogContents), + }; + return { + catalog, + selection: { + outcome: "selected", + selection: "automatic", + catalogDigest: catalog.catalogDigest, + presetDigest, + recipeDigest, + preset, + recipe, + topologyQualification: topology, + }, + }; +} describe("dual-DGX-Spark vLLM materializer", () => { - it("creates deterministic head and worker plans from the compiled recipe", () => { - const selection = fixtureDualSparkSelection(); + it("creates deterministic plans entirely from the selected catalog definitions", () => { + const selection = selectionWithDigests(); const plan = materializeDualSparkVllmPlan(selection); const recipe = selection.recipe.spec; expect(materializeDualSparkVllmPlan(selection)).toEqual(plan); - expect(plan.model).toEqual({ - id: recipe.model.id, - revision: recipe.model.revision, - servedName: recipe.model.servedName, + expect(Object.isFrozen(plan)).toBe(true); + expect(plan).toMatchObject({ + catalogDigest: selection.catalogDigest, + presetId: selection.preset.metadata.id, + presetDigest: selection.presetDigest, + recipeId: selection.recipe.metadata.id, + recipeDigest: selection.recipeDigest, + model: { + id: recipe.model.id, + revision: recipe.model.revision, + servedName: recipe.model.servedName, + }, + authentication: recipe.serve.authentication, + readiness: { + timeoutMs: recipe.readiness.timeoutSeconds * 1_000, + expectedModel: recipe.readiness.expectedModel, + }, }); expect(plan.roles.head).toMatchObject({ image: recipe.runtime.image, runtime: { + architecture: recipe.runtime.architecture, networkMode: recipe.runtime.networkMode, ipcMode: recipe.runtime.ipcMode, sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, + gpuRequest: recipe.runtime.gpuRequest, devices: recipe.runtime.devices, imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, + pullTimeoutSeconds: recipe.runtime.pullTimeoutSeconds, + ulimits: { + memlock: recipe.runtime.ulimits.memlock, + stack: recipe.runtime.ulimits.stackBytes, + }, + modelCache: recipe.runtime.modelCache, + temporaryFilesystems: recipe.runtime.temporaryFilesystems, }, - preparation: { - ref: recipe.model.preparationRef, - modelId: recipe.model.id, - modelRevision: recipe.model.revision, - modelDownloadSizeBytes: recipe.model.downloadSizeBytes, - encodingPath: recipe.model.encodingPath, - }, + command: { executable: recipe.serve.executable }, }); - expect(plan.readiness).toEqual({ - timeoutMs: recipe.readiness.timeoutSeconds * 1000, - expectedModel: recipe.readiness.expectedModel, - }); - expect(plan.apiPort).toBe(DUAL_SPARK_VLLM_API_PORT); - expect(plan.masterPort).toBe(DUAL_SPARK_VLLM_MASTER_PORT); - expect(plan.roles.head.containerName).toBe("nemoclaw-vllm-dspark-head"); - expect(plan.roles.worker.containerName).toBe("nemoclaw-vllm-dspark-worker"); + const configuredPort = recipe.serve.arguments.find(({ name }) => name === "--port")?.value; + expect(plan.apiPort).toBe(configuredPort); + expect(plan.roles.head.endpoint).toBe(`http://${plan.masterAddress}:${String(configuredPort)}`); }); it("uses role-local topology values and starts rank 1 headless", () => { - const plan = materializeDualSparkVllmPlan(fixtureDualSparkSelection()); + const plan = materializeDualSparkVllmPlan(selectionWithDigests()); expect(plan.roles.head.environment).toMatchObject({ VLLM_HOST_IP: "192.168.100.10", @@ -72,9 +255,8 @@ describe("dual-DGX-Spark vLLM materializer", () => { expect.arrayContaining(["--host", "192.168.100.10"]), ); expect(plan.roles.worker.command.arguments).toEqual( - expect.arrayContaining(["--host", "192.168.100.11"]), + expect.arrayContaining(["--host", "192.168.100.11", "--headless"]), ); - expect(plan.roles.worker.command.arguments).toContain("--headless"); expect(plan.roles.head.command.arguments).not.toContain("--headless"); expect(plan.roles.worker.command.arguments).toEqual( expect.arrayContaining([ @@ -89,105 +271,150 @@ describe("dual-DGX-Spark vLLM materializer", () => { "--node-rank", "1", "--master-port", - "25000", + String(DUAL_SPARK_VLLM_MASTER_PORT), ]), ); }); - it("preserves the fixed DSpark serving profile without embedding the API key", () => { - const plan = materializeDualSparkVllmPlan(fixtureDualSparkSelection()); - const headArgs = plan.roles.head.command.arguments; + it("passes every recipe serving argument without embedding an API key", () => { + const selection = selectionWithDigests(); + const plan = materializeDualSparkVllmPlan(selection); + const headArguments = plan.roles.head.command.arguments; - expect(headArgs).toEqual( - expect.arrayContaining([ - "--kv-cache-dtype", - "nvfp4_ds_mla", - "--block-size", - "256", - "--max-model-len", - "1048576", - "--max-num-seqs", - "6", - "--max-num-batched-tokens", - "8192", - "--gpu-memory-utilization", - "0.8", - "--moe-backend", - "flashinfer_b12x", - "--async-scheduling", - "--enable-chunked-prefill", - "--generation-config", - "vllm", - ]), - ); - expect(headArgs.join(" ")).toContain('"num_speculative_tokens":5'); - expect(headArgs).not.toContain("--api-key"); + for (const argument of selection.recipe.spec.serve.arguments) { + const index = headArguments.indexOf(argument.name); + expect(index).toBeGreaterThan(-1); + } + for (const argument of selection.recipe.spec.serve.arguments.filter( + ({ value }) => value !== undefined, + )) { + const index = headArguments.indexOf(argument.name); + expect(headArguments[index + 1]).toBe(String(argument.value)); + } + expect(headArguments).not.toContain("--api-key"); expect(plan.roles.worker.command.arguments).not.toContain("--api-key"); }); - it("rejects materializer-owned arguments added after catalog resolution", () => { - const selection = fixtureDualSparkSelection(); - const serve = selection.recipe.spec.serve as unknown as { - arguments: Array<{ name: string; value?: string | number }>; - }; - serve.arguments.push({ name: "--headless" }); + it("rejects a selected definition changed after catalog resolution", () => { + const selection = selectionWithDigests(); + (selection.recipe.spec.runtime as { image: string }).image = + `registry.example.test/vllm@sha256:${"d".repeat(64)}`; - expect(() => materializeDualSparkVllmPlan(selection)).toThrow( - /not the shipped dual-Spark profile/, - ); + expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/definition digest/u); }); it("rejects stale topology subject and output digests", () => { - const staleSubject = fixtureDualSparkSelection(); + const staleSubject = selectionWithDigests(); (staleSubject.topologyQualification as { subjectDigest: string }).subjectDigest = `sha256:${"f".repeat(64)}`; - expect(() => materializeDualSparkVllmPlan(staleSubject)).toThrow(/subject digest/); + expect(() => materializeDualSparkVllmPlan(staleSubject)).toThrow(/subject digest/u); - const staleOutput = fixtureDualSparkSelection(); + const staleOutput = selectionWithDigests(); (staleOutput.topologyQualification.output.peer as { target: string }).target = "other-worker.local"; - expect(() => materializeDualSparkVllmPlan(staleOutput)).toThrow(/output digest/); + expect(() => materializeDualSparkVllmPlan(staleOutput)).toThrow(/output digest/u); }); it("rejects an inconsistent master address even with a recomputed digest", () => { - const selection = fixtureDualSparkSelection(); + const selection = selectionWithDigests(); const artifact = selection.topologyQualification; (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; (artifact as { outputDigest: string }).outputDigest = dualSparkTopologyOutputDigest( artifact.output, ); - expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/master address/); + expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/master address/u); }); - it("requires the code-owned in-container checkpoint compatibility preparation", () => { - const preparation = materializeDualSparkVllmPlan(fixtureDualSparkSelection()).roles.head - .preparation; + it("materializes bounded preparation operations from recipe data", () => { + const selection = selectionWithDigests(); + const preparation = materializeDualSparkVllmPlan(selection).roles.head.preparation; + const configured = selection.recipe.spec.model.preparation; + expect(configured.ref).not.toBe(NO_PREPARATION_REF); + const boundedConfigured = configured as Extract< + typeof configured, + { ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF } + >; expect(preparation).toMatchObject({ - ref: "deepseek-v4-flash-0731/v1", + ref: boundedConfigured.ref, phase: "container-before-exec", - encodingPath: "encoding/encoding_dsv4.py", + modelId: selection.recipe.spec.model.id, + modelRevision: selection.recipe.spec.model.revision, + modelDownloadSizeBytes: selection.recipe.spec.model.downloadSizeBytes, + snapshotCopy: { + targetPath: boundedConfigured.snapshotCopy.targetPath, + }, + exactTextReplacement: boundedConfigured.exactTextReplacement, }); - expect(preparation.encodingSourcePath).toContain(preparation.modelRevision); - expect(preparation.encodingTargetPath).toContain("deepseek_v4_encoding.py"); - expect(preparation.reasoningCompatibility.replacementText).toContain( - 'reasoning_effort = "low"', + expect(preparation.ref).not.toBe(NO_PREPARATION_REF); + const boundedPreparation = preparation as Extract< + typeof preparation, + { ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF } + >; + expect(boundedPreparation.snapshotCopy.sourcePath).toContain(boundedPreparation.modelRevision); + expect(boundedPreparation.snapshotCopy.sourcePath).toContain( + boundedConfigured.snapshotCopy.sourcePath, ); }); - it("rejects a recipe changed after catalog resolution", () => { - const mutableImage = fixtureDualSparkSelection(); - (mutableImage.recipe.spec.runtime as { image: string }).image = - "ghcr.io/anemll/dspark-vllm-gx10:0.1.1"; - expect(() => materializeDualSparkVllmPlan(mutableImage)).toThrow( - /not the shipped dual-Spark profile/, + it("materializes a synthetic second profile without materializer code changes", () => { + const { catalog, selection } = syntheticSecondProfile(); + const plan = materializeDualSparkVllmPlan(selection, { catalog }); + + expect(plan).toMatchObject({ + presetId: selection.preset.metadata.id, + recipeId: selection.recipe.metadata.id, + model: { + id: "example-org/Synthetic-Model", + servedName: "synthetic-model", + }, + apiPort: 9_001, + readiness: { timeoutMs: 900_000, expectedModel: "synthetic-model" }, + }); + expect(plan.roles.head).toMatchObject({ + image: selection.recipe.spec.runtime.image, + runtime: { + sharedMemoryBytes: 8_589_934_592, + gpuRequest: "device=all", + pullTimeoutSeconds: 7_200, + ulimits: { memlock: "unlimited", stack: 33_554_432 }, + modelCache: { source: "huggingface-cache", target: "/models/cache" }, + }, + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { + sourcePath: expect.stringContaining( + "/models/cache/hub/models--example-org--Synthetic-Model/", + ), + targetPath: "/opt/synthetic-vllm/tokenizers/copied.py", + }, + exactTextReplacement: { + targetPath: "/opt/synthetic-vllm/parsers/reasoning.py", + expectedText: "MODE = 'legacy'", + replacementText: "MODE = 'compatible'", + }, + }, + command: { executable: "/opt/vllm/bin/vllm" }, + baseLabels: { + [DUAL_SPARK_PRESET_LABEL]: selection.preset.metadata.id, + [DUAL_SPARK_RECIPE_LABEL]: selection.recipe.metadata.id, + }, + }); + expect(plan.roles.head.environment).toMatchObject({ + HF_HOME: "/models/cache", + SYNTHETIC_PROFILE: "enabled", + }); + expect(plan.roles.head.command.arguments).toEqual( + expect.arrayContaining(["--port", "9001", "--max-model-len", "4096"]), ); - const changedRevision = fixtureDualSparkSelection(); - (changedRevision.recipe.spec.model as { revision: string }).revision = "d".repeat(40); - expect(() => materializeDualSparkVllmPlan(changedRevision)).toThrow( - /not the shipped dual-Spark profile/, + const originalSelection = selectionWithDigests(); + const originalPlan = materializeDualSparkVllmPlan(originalSelection); + const originalFromExpandedCatalog = materializeDualSparkVllmPlan( + { ...originalSelection, catalogDigest: catalog.catalogDigest }, + { catalog }, ); + expect(originalFromExpandedCatalog.planId).toBe(originalPlan.planId); }); }); diff --git a/src/lib/inference/serving/dual-spark-materialize.ts b/src/lib/inference/serving/dual-spark-materialize.ts index 612883a0fac..e79ae7e56e8 100644 --- a/src/lib/inference/serving/dual-spark-materialize.ts +++ b/src/lib/inference/serving/dual-spark-materialize.ts @@ -1,6 +1,17 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import path from "node:path"; + +import { + DUAL_SPARK_VLLM_MASTER_PORT, + DUAL_SPARK_VLLM_MATERIALIZER_REF, + getManagedInferenceLifecycleDescriptor, + getManagedInferenceMaterializerDescriptor, + getManagedInferenceRecipeRegistrationError, + getManagedInferenceTopologyQualificationDescriptor, + isDualSparkMaterializerOwnedEnvironment, +} from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { immutableManagedInferenceCopy, @@ -8,26 +19,27 @@ import { managedInferenceHexDigest, } from "./catalog-integrity.js"; import { - DUAL_SPARK_PRESET_ID, - DUAL_SPARK_RECIPE_ID, isManagedInferenceMaterializerOwnedArgument, + type CompiledManagedInferenceCatalog, + type CompiledManagedInferenceDefinition, + type ManagedInferenceServingPreset, + type ManagedInferenceServingRecipe, type ResolvedManagedInferenceSelection, } from "./catalog-types.js"; +import { + materializeDualSparkVllmPreparation, + type DualSparkVllmPreparationPlan, +} from "./dual-spark-preparation.js"; import { DUAL_SPARK_TOPOLOGY_ID, DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, type DualSparkTopologyOutput, type DualSparkTopologyRailEndpoint, - getDualSparkTopologyArtifactError, } from "./dual-spark-topology.js"; -export const DUAL_SPARK_VLLM_ADAPTER_ID = "vllm.dual-dgx-spark/v1" as const; -const SHIPPED_DUAL_SPARK_RECIPE = loadManagedInferenceCatalog().recipes[0]!.definition; -export const DUAL_SPARK_VLLM_IMAGE = SHIPPED_DUAL_SPARK_RECIPE.spec.runtime.image; -export const DUAL_SPARK_VLLM_MODEL = SHIPPED_DUAL_SPARK_RECIPE.spec.model.id; -export const DUAL_SPARK_VLLM_MODEL_REVISION = SHIPPED_DUAL_SPARK_RECIPE.spec.model.revision; -export const DUAL_SPARK_VLLM_API_PORT = 8000; -export const DUAL_SPARK_VLLM_MASTER_PORT = 25000; +/** Stable adapter identity; profile identities and values come from the selected catalog entries. */ +export const DUAL_SPARK_VLLM_ADAPTER_ID = DUAL_SPARK_VLLM_MATERIALIZER_REF; +export { DUAL_SPARK_VLLM_MASTER_PORT }; export const DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME = "nemoclaw-vllm-dspark-head"; export const DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME = "nemoclaw-vllm-dspark-worker"; export const DUAL_SPARK_VLLM_PROJECT_ID = "nemoclaw-vllm-dspark"; @@ -46,7 +58,25 @@ export const DUAL_SPARK_API_KEY_FINGERPRINT_LABEL = "com.nvidia.nemoclaw.serving-api-key-fingerprint"; export const DUAL_SPARK_TRANSACTION_LABEL = "com.nvidia.nemoclaw.serving-transaction"; -const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/u; +const SAFE_ABSOLUTE_PATH_PATTERN = /^\/(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9._+/-]+$/u; +const SAFE_GPU_REQUEST_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._,:=-]{0,255}$/u; +const SAFE_ENVIRONMENT_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/u; +const SAFE_MODEL_ID_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/u; +const SAFE_MODEL_REVISION_PATTERN = /^[0-9a-f]{40,64}$/u; +const SAFE_STABLE_ID_PATTERN = /^[a-z0-9][a-z0-9._/-]{0,159}$/u; +const PINNED_IMAGE_PATTERN = /^[a-z0-9.-]+(?::[0-9]+)?(?:\/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$/u; +const SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u; +const TMPFS_OPTIONS = new Set([ + "rw", + "ro", + "nosuid", + "nodev", + "noexec", + "exec", + "noatime", + "relatime", +]); export type DualSparkVllmRole = "head" | "worker"; export interface DualSparkVllmRolePlan { @@ -64,37 +94,30 @@ export interface DualSparkVllmRolePlan { }; readonly image: string; readonly runtime: { - readonly networkMode: "host"; - readonly ipcMode: "host"; + readonly architecture: string; + readonly networkMode: string; + readonly ipcMode: string; readonly sharedMemoryBytes: number; - readonly gpuRequest: "all"; + readonly gpuRequest: string; readonly devices: readonly string[]; readonly imageDownloadSizeBytes: number; + readonly pullTimeoutSeconds: number; readonly ulimits: { - readonly memlock: -1; - readonly stack: 67_108_864; + readonly memlock: number | string; + readonly stack: number; }; readonly modelCache: { - readonly source: "huggingface-cache"; - readonly target: "/cache/huggingface"; - }; - }; - readonly preparation: { - readonly ref: string; - /** Code-owned adapter operation executed in the new container before vLLM. */ - readonly phase: "container-before-exec"; - readonly modelId: string; - readonly modelRevision: string; - readonly modelDownloadSizeBytes: number; - readonly encodingPath: string; - readonly encodingSourcePath: string; - readonly encodingTargetPath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py"; - readonly reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py"; - readonly reasoningCompatibility: { - readonly existingText: string; - readonly replacementText: string; + readonly source: string; + readonly target: string; }; + readonly temporaryFilesystems: readonly { + readonly target: string; + readonly sizeBytes: number; + readonly mode: string; + readonly options: readonly string[]; + }[]; }; + readonly preparation: DualSparkVllmPreparationPlan; readonly fabric: { readonly primaryRailIndex: number; readonly netdev: string; @@ -106,7 +129,7 @@ export interface DualSparkVllmRolePlan { }; readonly environment: Readonly>; readonly command: { - readonly executable: "/usr/local/bin/vllm"; + readonly executable: string; readonly arguments: readonly string[]; }; readonly endpoint: string | null; @@ -117,8 +140,10 @@ export interface DualSparkVllmPlan { readonly schemaVersion: 1; readonly adapterId: typeof DUAL_SPARK_VLLM_ADAPTER_ID; readonly catalogDigest: string; - readonly presetId: typeof DUAL_SPARK_PRESET_ID; - readonly recipeId: typeof DUAL_SPARK_RECIPE_ID; + readonly presetId: string; + readonly presetDigest: string; + readonly recipeId: string; + readonly recipeDigest: string; readonly topologyId: typeof DUAL_SPARK_TOPOLOGY_ID; readonly topologySchemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; readonly topologySubjectDigest: string; @@ -130,7 +155,8 @@ export interface DualSparkVllmPlan { readonly revision: string; readonly servedName: string; }; - readonly apiPort: typeof DUAL_SPARK_VLLM_API_PORT; + readonly authentication: string; + readonly apiPort: number; readonly masterAddress: string; readonly masterPort: typeof DUAL_SPARK_VLLM_MASTER_PORT; readonly readiness: { @@ -143,107 +169,311 @@ export interface DualSparkVllmPlan { }; } +export interface DualSparkVllmMaterializeOptions { + /** Explicit catalog input keeps the materializer testable with additional YAML-compiled profiles. */ + readonly catalog?: CompiledManagedInferenceCatalog; +} + +interface CatalogSelection { + readonly preset: ManagedInferenceServingPreset; + readonly recipe: ManagedInferenceServingRecipe; +} + +interface ParsedServingArguments { + readonly apiPort: number; + readonly arguments: readonly string[]; +} + function fail(message: string): never { throw new Error(`Cannot materialize dual-DGX-Spark vLLM: ${message}`); } -function commandArguments( +function positiveSafeInteger(value: number, maximum = Number.MAX_SAFE_INTEGER): boolean { + return Number.isSafeInteger(value) && value > 0 && value <= maximum; +} + +function safeAbsolutePath(value: string): boolean { + return ( + value.length <= 4_096 && + SAFE_ABSOLUTE_PATH_PATTERN.test(value) && + path.posix.normalize(value) === value + ); +} + +function selectedDefinition( + definitions: readonly CompiledManagedInferenceDefinition[], + selected: TDefinition, + selectedDigest: string, + label: string, +): TDefinition { + const matches = definitions.filter( + ({ definition }) => definition.metadata.id === selected.metadata.id, + ); + if (matches.length !== 1) { + fail(`selected ${label} ${selected.metadata.id} is not unique in the compiled catalog`); + } + const compiled = matches[0]!; + if ( + !SHA256_PATTERN.test(selectedDigest) || + compiled.definitionDigest !== selectedDigest || + managedInferenceDigest(compiled.definition) !== selectedDigest || + managedInferenceDigest(selected) !== selectedDigest + ) { + fail(`selected ${label} ${selected.metadata.id} does not match its definition digest`); + } + return compiled.definition; +} + +function assertCatalogSelection( selection: ResolvedManagedInferenceSelection, - rank: 0 | 1, - hostAddress: string, -): string[] { - const recipe = selection.recipe.spec; + catalog: CompiledManagedInferenceCatalog, +): CatalogSelection { + const { catalogDigest, ...catalogContents } = catalog; + if ( + selection.catalogDigest !== catalogDigest || + !SHA256_PATTERN.test(catalogDigest) || + managedInferenceDigest(catalogContents) !== catalogDigest + ) { + fail("the resolved selection does not match the compiled catalog digest"); + } + if ( + !SHA256_PATTERN.test(catalog.sourceRevision) || + managedInferenceDigest(catalog.sourceFiles) !== catalog.sourceRevision + ) { + fail("the compiled catalog provenance is invalid"); + } + + const preset = selectedDefinition( + catalog.presets, + selection.preset, + selection.presetDigest, + "preset", + ); + const recipe = selectedDefinition( + catalog.recipes, + selection.recipe, + selection.recipeDigest, + "recipe", + ); + const bindingName = recipe.spec.execution.topologyBinding; + const recipeBinding = recipe.spec.bindings[bindingName]; + const presetBinding = preset.spec.plan.bindings[bindingName]?.valueFromTopologyQualification; + const topologyDescriptor = recipeBinding + ? getManagedInferenceTopologyQualificationDescriptor( + recipeBinding.qualificationId, + recipeBinding.schemaVersion, + ) + : undefined; + + if ( + preset.spec.plan.recipeRef !== recipe.metadata.id || + preset.spec.plan.backend !== recipe.spec.backend + ) { + fail("the selected preset does not reference the selected recipe and backend"); + } + if ( + !recipeBinding || + !presetBinding || + !topologyDescriptor || + presetBinding.output !== topologyDescriptor.bindingOutput || + presetBinding.id !== recipeBinding.qualificationId || + presetBinding.schemaVersion !== recipeBinding.schemaVersion + ) { + fail(`preset and recipe topology binding ${bindingName} is incompatible`); + } + + const materializer = getManagedInferenceMaterializerDescriptor( + recipe.spec.execution.materializerRef, + ); + if (!materializer || materializer.ref !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { + fail(`recipe selects unsupported materializer ${recipe.spec.execution.materializerRef}`); + } + const lifecycle = getManagedInferenceLifecycleDescriptor(recipe.spec.execution.lifecycleRef); + if ( + !lifecycle || + lifecycle.backend !== recipe.spec.backend || + !lifecycle.acceptedMaterializerRefs.includes(materializer.ref) || + !lifecycle.acceptedPlanSchemas.includes(materializer.outputPlanSchema) + ) { + fail(`recipe selects incompatible lifecycle ${recipe.spec.execution.lifecycleRef}`); + } + const registrationError = getManagedInferenceRecipeRegistrationError(recipe); + if (registrationError) fail(registrationError); + + const topology = selection.topologyQualification; + if ( + topology.status !== "qualified" || + topology.id !== recipeBinding.qualificationId || + topology.schemaVersion !== recipeBinding.schemaVersion || + topology.id !== materializer.topology.qualificationId || + topology.schemaVersion !== materializer.topology.schemaVersion || + recipeBinding.outputSchema !== materializer.topology.outputSchema + ) { + fail("topology artifact is incompatible with the selected recipe binding"); + } + if (topologyDescriptor.outputSchema !== recipeBinding.outputSchema) { + fail("topology artifact has no compatible registered validator"); + } + const topologyError = topologyDescriptor.validateArtifact(topology); + if (topologyError) fail(topologyError); + + return { preset, recipe }; +} + +function assertRecipeValues(recipe: ManagedInferenceServingRecipe): void { + const { model, readiness, runtime, serve } = recipe.spec; + if ( + runtime.architecture !== "arm64" || + runtime.networkMode !== "host" || + runtime.ipcMode !== "host" || + serve.authentication !== "bearer" + ) { + fail("recipe runtime and authentication do not match adapter v1"); + } + if ( + !PINNED_IMAGE_PATTERN.test(runtime.image) || + !positiveSafeInteger(runtime.imageDownloadSizeBytes) || + !positiveSafeInteger(runtime.pullTimeoutSeconds, 86_400) || + !positiveSafeInteger(runtime.sharedMemoryBytes) || + !SAFE_GPU_REQUEST_PATTERN.test(runtime.gpuRequest) || + !safeAbsolutePath(serve.executable) + ) { + fail("recipe runtime contains an invalid executable or resource value"); + } + if ( + runtime.devices.length > 32 || + new Set(runtime.devices).size !== runtime.devices.length || + runtime.devices.some((device) => !safeAbsolutePath(device)) + ) { + fail("recipe runtime device bindings are invalid"); + } + const { memlock, stackBytes } = runtime.ulimits; + if ( + !( + (typeof memlock === "number" && Number.isSafeInteger(memlock) && memlock >= -1) || + memlock === "unlimited" + ) || + !positiveSafeInteger(stackBytes) + ) { + fail("recipe runtime ulimits are invalid"); + } + if ( + !SAFE_STABLE_ID_PATTERN.test(runtime.modelCache.source) || + !safeAbsolutePath(runtime.modelCache.target) + ) { + fail("recipe model-cache binding is invalid"); + } + const temporaryTargets = new Set(); + for (const temporaryFilesystem of runtime.temporaryFilesystems) { + if ( + temporaryTargets.has(temporaryFilesystem.target) || + !safeAbsolutePath(temporaryFilesystem.target) || + !positiveSafeInteger(temporaryFilesystem.sizeBytes) || + !/^[0-7]{4}$/u.test(temporaryFilesystem.mode) || + temporaryFilesystem.options.length > 8 || + new Set(temporaryFilesystem.options).size !== temporaryFilesystem.options.length || + temporaryFilesystem.options.some((option) => !TMPFS_OPTIONS.has(option)) + ) { + fail("recipe temporary-filesystem configuration is invalid"); + } + temporaryTargets.add(temporaryFilesystem.target); + } + const environmentEntries = Object.entries(runtime.environment); + if ( + environmentEntries.length > 128 || + environmentEntries.some( + ([name, value]) => + !SAFE_ENVIRONMENT_NAME_PATTERN.test(name) || + isDualSparkMaterializerOwnedEnvironment(name) || + Buffer.byteLength(value, "utf8") > 4_096 || + value.includes("\0"), + ) + ) { + fail("recipe runtime environment is invalid or overrides adapter-owned values"); + } + if ( + !SAFE_MODEL_ID_PATTERN.test(model.id) || + !SAFE_MODEL_REVISION_PATTERN.test(model.revision) || + !SAFE_STABLE_ID_PATTERN.test(model.servedName) || + !positiveSafeInteger(model.downloadSizeBytes) || + !positiveSafeInteger(readiness.timeoutSeconds, 86_400) || + readiness.expectedModel !== model.servedName + ) { + fail("recipe model identity or readiness contract is invalid"); + } +} + +function servingArguments(recipe: ManagedInferenceServingRecipe): ParsedServingArguments { const seen = new Set(); const staticArguments: string[] = []; - for (const argument of recipe.serve.arguments) { - if (!/^--[a-z0-9][a-z0-9-]*$/.test(argument.name)) fail("a serve argument is invalid"); + let apiPort: number | undefined; + for (const argument of recipe.spec.serve.arguments) { + if (!/^--[a-z0-9][a-z0-9-]*$/u.test(argument.name)) fail("a serve argument is invalid"); if (seen.has(argument.name)) fail(`serve argument ${argument.name} is duplicated`); if (isManagedInferenceMaterializerOwnedArgument(argument.name)) { fail(`serve argument ${argument.name} is owned by the materializer`); } seen.add(argument.name); staticArguments.push(argument.name); - if (argument.value !== undefined) staticArguments.push(String(argument.value)); - } - - const portIndex = staticArguments.indexOf("--port"); - if (portIndex < 0 || staticArguments[portIndex + 1] !== String(DUAL_SPARK_VLLM_API_PORT)) { - fail(`the shipped recipe must bind API port ${String(DUAL_SPARK_VLLM_API_PORT)}`); + if (argument.value !== undefined) { + const value = String(argument.value); + if (Buffer.byteLength(value, "utf8") > 16_384 || value.includes("\0")) { + fail(`serve argument ${argument.name} has an invalid value`); + } + staticArguments.push(value); + } + if (argument.name === "--port") { + const parsed = + typeof argument.value === "number" + ? argument.value + : typeof argument.value === "string" && /^\d{1,5}$/u.test(argument.value) + ? Number(argument.value) + : Number.NaN; + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 65_535) { + fail("serve argument --port must contain a valid TCP port"); + } + apiPort = parsed; + } } + if (apiPort === undefined) fail("recipe must define one --port serve argument"); + return { apiPort, arguments: staticArguments }; +} +function commandArguments( + recipe: ManagedInferenceServingRecipe, + topology: ResolvedManagedInferenceSelection["topologyQualification"], + staticArguments: readonly string[], + rank: 0 | 1, + hostAddress: string, +): string[] { return [ "serve", - recipe.model.id, + recipe.spec.model.id, + "--revision", + recipe.spec.model.revision, "--served-model-name", - recipe.model.servedName, + recipe.spec.model.servedName, "--host", hostAddress, ...staticArguments, "--tensor-parallel-size", - String(recipe.execution.tensorParallelSize), + String(recipe.spec.execution.tensorParallelSize), "--pipeline-parallel-size", - String(recipe.execution.pipelineParallelSize), + String(recipe.spec.execution.pipelineParallelSize), "--distributed-executor-backend", - recipe.execution.distributedExecutorBackend, + recipe.spec.execution.distributedExecutorBackend, "--nnodes", - String(recipe.execution.nodeCount), + String(recipe.spec.execution.nodeCount), "--node-rank", String(rank), "--master-addr", - selection.topologyQualification.output.masterAddress, + topology.output.masterAddress, "--master-port", String(DUAL_SPARK_VLLM_MASTER_PORT), ...(rank === 1 ? ["--headless"] : []), ]; } -function assertShippedSelection( - selection: ResolvedManagedInferenceSelection, -): void { - const { recipe, preset, topologyQualification: topology } = selection; - const catalog = loadManagedInferenceCatalog(); - const compiledPreset = catalog.presets[0]; - const compiledRecipe = catalog.recipes[0]; - if ( - selection.catalogDigest !== catalog.catalogDigest || - !compiledPreset || - !compiledRecipe || - managedInferenceDigest(preset) !== compiledPreset.definitionDigest || - managedInferenceDigest(recipe) !== compiledRecipe.definitionDigest || - preset.metadata.id !== DUAL_SPARK_PRESET_ID || - recipe.metadata.id !== DUAL_SPARK_RECIPE_ID || - preset.spec.plan.recipeRef !== recipe.metadata.id - ) { - fail("the selected preset and recipe are not the shipped dual-Spark profile"); - } - if ( - recipe.spec.execution.materializerRef !== DUAL_SPARK_VLLM_ADAPTER_ID || - recipe.spec.execution.lifecycleRef !== DUAL_SPARK_VLLM_ADAPTER_ID || - recipe.spec.execution.nodeCount !== 2 || - recipe.spec.execution.tensorParallelSize !== 2 || - recipe.spec.execution.pipelineParallelSize !== 1 || - recipe.spec.execution.distributedExecutorBackend !== "mp" - ) { - fail("recipe execution does not match adapter v1"); - } - if ( - topology.id !== DUAL_SPARK_TOPOLOGY_ID || - topology.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION || - topology.status !== "qualified" - ) { - fail("topology artifact is not the qualified dual-Spark v1 artifact"); - } - const topologyError = getDualSparkTopologyArtifactError(topology); - if (topologyError) fail(topologyError); - if ( - !Number.isSafeInteger(recipe.spec.readiness.timeoutSeconds) || - recipe.spec.readiness.timeoutSeconds <= 0 || - recipe.spec.readiness.timeoutSeconds > 86_400 - ) { - fail("readiness timeout is invalid"); - } -} - function endpointForRole( output: DualSparkTopologyOutput, role: DualSparkVllmRole, @@ -258,14 +488,20 @@ function endpointForRole( return endpoint; } -function rolePlan( - selection: ResolvedManagedInferenceSelection, - role: DualSparkVllmRole, - clusterId: string, - planId: string, -): DualSparkVllmRolePlan { +interface RolePlanInput { + readonly selection: ResolvedManagedInferenceSelection; + readonly preset: ManagedInferenceServingPreset; + readonly recipe: ManagedInferenceServingRecipe; + readonly serving: ParsedServingArguments; + readonly preparation: DualSparkVllmPreparationPlan; + readonly role: DualSparkVllmRole; + readonly clusterId: string; + readonly planId: string; +} + +function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { + const { clusterId, planId, preparation, preset, recipe, role, selection, serving } = input; const output = selection.topologyQualification.output; - const recipe = selection.recipe.spec; const rank = role === "head" ? 0 : 1; const nodeId = role === "head" ? output.headNodeId : output.workerNodeId; const node = output.nodes.find( @@ -276,17 +512,18 @@ function rolePlan( const baseLabels = { [DUAL_SPARK_MANAGED_LABEL]: "true", [DUAL_SPARK_ADAPTER_LABEL]: DUAL_SPARK_VLLM_ADAPTER_ID, - [DUAL_SPARK_PRESET_LABEL]: DUAL_SPARK_PRESET_ID, - [DUAL_SPARK_RECIPE_LABEL]: DUAL_SPARK_RECIPE_ID, + [DUAL_SPARK_PRESET_LABEL]: preset.metadata.id, + [DUAL_SPARK_RECIPE_LABEL]: recipe.metadata.id, [DUAL_SPARK_ROLE_LABEL]: role, [DUAL_SPARK_CLUSTER_LABEL]: clusterId, [DUAL_SPARK_PLAN_LABEL]: planId, [DUAL_SPARK_GPU_LABEL]: node.gpuId, - [DUAL_SPARK_IMAGE_LABEL]: recipe.runtime.image, - [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.model.revision, + [DUAL_SPARK_IMAGE_LABEL]: recipe.spec.runtime.image, + [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.spec.model.revision, }; const environment = { - ...recipe.runtime.environment, + ...recipe.spec.runtime.environment, + HF_HOME: recipe.spec.runtime.modelCache.target, VLLM_HOST_IP: endpoint.address, NCCL_IB_HCA: `${endpoint.hcaDevice}:${String(endpoint.hcaPort)}`, NCCL_SOCKET_IFNAME: endpoint.netdev, @@ -298,6 +535,7 @@ function rolePlan( NODE_RANK: String(rank), HEADLESS: role === "worker" ? "1" : "", }; + const runtime = recipe.spec.runtime; return { role, @@ -314,38 +552,21 @@ function rolePlan( expectedTarget: output.peer.target, bindingHandle: output.peer.sshBindingHandle, }, - image: recipe.runtime.image, + image: runtime.image, runtime: { - networkMode: recipe.runtime.networkMode, - ipcMode: recipe.runtime.ipcMode, - sharedMemoryBytes: recipe.runtime.sharedMemoryBytes, - gpuRequest: "all", - devices: recipe.runtime.devices, - imageDownloadSizeBytes: recipe.runtime.imageDownloadSizeBytes, - ulimits: { memlock: -1, stack: 67_108_864 }, - modelCache: { source: "huggingface-cache", target: "/cache/huggingface" }, - }, - preparation: { - ref: recipe.model.preparationRef, - phase: "container-before-exec", - modelId: recipe.model.id, - modelRevision: recipe.model.revision, - modelDownloadSizeBytes: recipe.model.downloadSizeBytes, - encodingPath: recipe.model.encodingPath, - encodingSourcePath: `/cache/huggingface/hub/models--${recipe.model.id.replaceAll( - "/", - "--", - )}/snapshots/${recipe.model.revision}/${recipe.model.encodingPath}`, - encodingTargetPath: - "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py", - reasoningModulePath: "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py", - reasoningCompatibility: { - existingText: - 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n else:\n reasoning_effort = "high"', - replacementText: - 'elif reasoning_effort in ("max", "xhigh"):\n reasoning_effort = "max"\n elif reasoning_effort == "high":\n reasoning_effort = "high"\n else:\n reasoning_effort = "low"', - }, + architecture: runtime.architecture, + networkMode: runtime.networkMode, + ipcMode: runtime.ipcMode, + sharedMemoryBytes: runtime.sharedMemoryBytes, + gpuRequest: runtime.gpuRequest, + devices: runtime.devices, + imageDownloadSizeBytes: runtime.imageDownloadSizeBytes, + pullTimeoutSeconds: runtime.pullTimeoutSeconds, + ulimits: { memlock: runtime.ulimits.memlock, stack: runtime.ulimits.stackBytes }, + modelCache: runtime.modelCache, + temporaryFilesystems: runtime.temporaryFilesystems, }, + preparation, fabric: { primaryRailIndex: output.rails[0].index, netdev: endpoint.netdev, @@ -357,11 +578,16 @@ function rolePlan( }, environment, command: { - executable: "/usr/local/bin/vllm", - arguments: commandArguments(selection, rank, endpoint.address), + executable: recipe.spec.serve.executable, + arguments: commandArguments( + recipe, + selection.topologyQualification, + serving.arguments, + rank, + endpoint.address, + ), }, - endpoint: - role === "head" ? `http://${output.masterAddress}:${String(DUAL_SPARK_VLLM_API_PORT)}` : null, + endpoint: role === "head" ? `http://${output.masterAddress}:${String(serving.apiPort)}` : null, baseLabels, }; } @@ -369,33 +595,55 @@ function rolePlan( /** Compile one resolved, qualified catalog selection into immutable role-local plans. */ export function materializeDualSparkVllmPlan( selection: ResolvedManagedInferenceSelection, + options: DualSparkVllmMaterializeOptions = {}, ): DualSparkVllmPlan { let snapshot: ResolvedManagedInferenceSelection; + let catalog: CompiledManagedInferenceCatalog; try { snapshot = immutableManagedInferenceCopy(selection); + catalog = options.catalog + ? immutableManagedInferenceCopy(options.catalog) + : loadManagedInferenceCatalog(); } catch { - fail("the resolved selection is not immutable JSON data"); + fail("the resolved selection or catalog is not immutable JSON data"); } - assertShippedSelection(snapshot); - const output = snapshot.topologyQualification.output; - const clusterId = managedInferenceHexDigest({ - topologyId: snapshot.topologyQualification.id, + + const selected = assertCatalogSelection(snapshot, catalog); + const catalogSelection = { ...snapshot, ...selected }; + assertRecipeValues(selected.recipe); + const serving = servingArguments(selected.recipe); + let preparation: DualSparkVllmPreparationPlan; + try { + preparation = materializeDualSparkVllmPreparation({ + ...selected.recipe.spec.model, + modelCacheTarget: selected.recipe.spec.runtime.modelCache.target, + }); + } catch (error) { + fail(error instanceof Error ? error.message : "model preparation is invalid"); + } + + const topologyIdentity = { + id: snapshot.topologyQualification.id, + schemaVersion: snapshot.topologyQualification.schemaVersion, subjectDigest: snapshot.topologyQualification.subjectDigest, outputDigest: snapshot.topologyQualification.outputDigest, - }); + }; + const clusterId = managedInferenceHexDigest(topologyIdentity); const planId = managedInferenceHexDigest({ adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, - catalogDigest: snapshot.catalogDigest, - preset: snapshot.preset, - recipe: snapshot.recipe, - topology: snapshot.topologyQualification, + preset: { id: selected.preset.metadata.id, digest: snapshot.presetDigest }, + recipe: { id: selected.recipe.metadata.id, digest: snapshot.recipeDigest }, + topology: topologyIdentity, }); - return { + const output = snapshot.topologyQualification.output; + return immutableManagedInferenceCopy({ schemaVersion: 1, adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, catalogDigest: snapshot.catalogDigest, - presetId: DUAL_SPARK_PRESET_ID, - recipeId: DUAL_SPARK_RECIPE_ID, + presetId: selected.preset.metadata.id, + presetDigest: snapshot.presetDigest, + recipeId: selected.recipe.metadata.id, + recipeDigest: snapshot.recipeDigest, topologyId: DUAL_SPARK_TOPOLOGY_ID, topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, topologySubjectDigest: snapshot.topologyQualification.subjectDigest, @@ -403,20 +651,39 @@ export function materializeDualSparkVllmPlan( clusterId, planId, model: { - id: snapshot.recipe.spec.model.id, - revision: snapshot.recipe.spec.model.revision, - servedName: snapshot.recipe.spec.model.servedName, + id: selected.recipe.spec.model.id, + revision: selected.recipe.spec.model.revision, + servedName: selected.recipe.spec.model.servedName, }, - apiPort: DUAL_SPARK_VLLM_API_PORT, + authentication: selected.recipe.spec.serve.authentication, + apiPort: serving.apiPort, masterAddress: output.masterAddress, masterPort: DUAL_SPARK_VLLM_MASTER_PORT, readiness: { - timeoutMs: snapshot.recipe.spec.readiness.timeoutSeconds * 1000, - expectedModel: snapshot.recipe.spec.readiness.expectedModel, + timeoutMs: selected.recipe.spec.readiness.timeoutSeconds * 1000, + expectedModel: selected.recipe.spec.readiness.expectedModel, }, roles: { - worker: rolePlan(snapshot, "worker", clusterId, planId), - head: rolePlan(snapshot, "head", clusterId, planId), + worker: rolePlan({ + selection: catalogSelection, + preset: selected.preset, + recipe: selected.recipe, + serving, + preparation, + role: "worker", + clusterId, + planId, + }), + head: rolePlan({ + selection: catalogSelection, + preset: selected.preset, + recipe: selected.recipe, + serving, + preparation, + role: "head", + clusterId, + planId, + }), }, - }; + }); } diff --git a/src/lib/inference/serving/dual-spark-preparation.test.ts b/src/lib/inference/serving/dual-spark-preparation.test.ts new file mode 100644 index 00000000000..7088f6a6da9 --- /dev/null +++ b/src/lib/inference/serving/dual-spark-preparation.test.ts @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { + NO_PREPARATION_REF, + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, +} from "./adapter-registry.js"; +import { materializeDualSparkVllmPreparation } from "./dual-spark-preparation.js"; + +const MODEL = { + id: "example-org/Synthetic-Model", + revision: "a".repeat(64), + downloadSizeBytes: 1_234_567, + modelCacheTarget: "/models/alternate-cache", +} as const; + +describe("dual-DGX-Spark vLLM preparation materializer", () => { + it("materializes the registered no-op without executable input", () => { + const preparation = materializeDualSparkVllmPreparation({ + ...MODEL, + preparation: { ref: NO_PREPARATION_REF }, + }); + + expect(preparation).toEqual({ + ref: NO_PREPARATION_REF, + phase: "container-before-exec", + modelId: MODEL.id, + modelRevision: MODEL.revision, + modelDownloadSizeBytes: MODEL.downloadSizeBytes, + }); + expect(preparation).not.toHaveProperty("command"); + }); + + it("derives the snapshot root and opaque target paths from recipe data", () => { + const preparation = materializeDualSparkVllmPreparation({ + ...MODEL, + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { + sourcePath: "artifacts/tokenizer.py", + targetPath: "/opt/alternate-vllm/tokenizers/model.py", + }, + exactTextReplacement: { + targetPath: "/opt/alternate-vllm/parsers/reasoning.py", + expectedText: "MODE = 'before'", + replacementText: "MODE = 'after'", + }, + }, + }); + + expect(preparation).toEqual({ + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + phase: "container-before-exec", + modelId: MODEL.id, + modelRevision: MODEL.revision, + modelDownloadSizeBytes: MODEL.downloadSizeBytes, + snapshotCopy: { + sourcePath: `/models/alternate-cache/hub/models--example-org--Synthetic-Model/snapshots/${MODEL.revision}/artifacts/tokenizer.py`, + targetPath: "/opt/alternate-vllm/tokenizers/model.py", + }, + exactTextReplacement: { + targetPath: "/opt/alternate-vllm/parsers/reasoning.py", + expectedText: "MODE = 'before'", + replacementText: "MODE = 'after'", + }, + }); + expect(preparation).not.toHaveProperty("command"); + }); + + it.each([ + { + label: "snapshot traversal", + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { sourcePath: "../escape.py", targetPath: "/opt/vllm/copied.py" }, + exactTextReplacement: { + targetPath: "/opt/vllm/reasoning.py", + expectedText: "before", + replacementText: "after", + }, + }, + }, + { + label: "relative container target", + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { sourcePath: "safe.py", targetPath: "relative/copied.py" }, + exactTextReplacement: { + targetPath: "/opt/vllm/reasoning.py", + expectedText: "before", + replacementText: "after", + }, + }, + }, + { + label: "unchanged replacement", + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { sourcePath: "safe.py", targetPath: "/opt/vllm/copied.py" }, + exactTextReplacement: { + targetPath: "/opt/vllm/reasoning.py", + expectedText: "same", + replacementText: "same", + }, + }, + }, + ])("rejects bounded operation input with $label", ({ preparation }) => { + expect(() => materializeDualSparkVllmPreparation({ ...MODEL, preparation })).toThrow(); + }); +}); diff --git a/src/lib/inference/serving/dual-spark-preparation.ts b/src/lib/inference/serving/dual-spark-preparation.ts new file mode 100644 index 00000000000..db475a4d67e --- /dev/null +++ b/src/lib/inference/serving/dual-spark-preparation.ts @@ -0,0 +1,200 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import { + NO_PREPARATION_REF, + SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, +} from "./adapter-registry.js"; + +const MODEL_ID = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/u; +const MODEL_REVISION = /^[0-9a-f]{40,64}$/u; +const MAX_PATH_BYTES = 4_096; +const MAX_REPLACEMENT_BYTES = 64 * 1_024; + +export type DualSparkVllmPreparationRecipe = + | { readonly ref: typeof NO_PREPARATION_REF } + | { + readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; + readonly snapshotCopy: { + /** Normalized path relative to the immutable model snapshot. */ + readonly sourcePath: string; + /** Normalized absolute destination inside the pinned vLLM image. */ + readonly targetPath: string; + }; + readonly exactTextReplacement: { + /** Normalized absolute file inside the pinned vLLM package. */ + readonly targetPath: string; + readonly expectedText: string; + readonly replacementText: string; + }; + }; + +interface DualSparkVllmPreparationPlanBase { + readonly phase: "container-before-exec"; + readonly modelId: string; + readonly modelRevision: string; + readonly modelDownloadSizeBytes: number; +} + +export type DualSparkVllmPreparationPlan = + | (DualSparkVllmPreparationPlanBase & { readonly ref: typeof NO_PREPARATION_REF }) + | (DualSparkVllmPreparationPlanBase & { + readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; + readonly snapshotCopy: { + readonly sourcePath: string; + readonly targetPath: string; + }; + readonly exactTextReplacement: { + readonly targetPath: string; + readonly expectedText: string; + readonly replacementText: string; + }; + }); + +interface PreparationModel { + readonly id: string; + readonly revision: string; + readonly downloadSizeBytes: number; + readonly preparation: unknown; + readonly modelCacheTarget: string; +} + +function isRecord(value: unknown): value is Readonly> { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function exactKeys( + value: Readonly>, + expected: readonly string[], + label: string, +): void { + const actual = Object.keys(value).sort(); + const sorted = [...expected].sort(); + if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) { + throw new Error(`${label} fields are invalid`); + } +} + +function boundedText(value: unknown, label: string, maximum = MAX_REPLACEMENT_BYTES): string { + if ( + typeof value !== "string" || + value.length === 0 || + Buffer.byteLength(value, "utf8") > maximum || + value.includes("\0") + ) { + throw new Error(`${label} is invalid`); + } + return value; +} + +function snapshotRelativePath(value: unknown): string { + const candidate = boundedText(value, "snapshot copy source path", MAX_PATH_BYTES); + if ( + path.posix.isAbsolute(candidate) || + path.posix.normalize(candidate) !== candidate || + candidate === "." || + candidate.startsWith("../") || + candidate.includes(":") + ) { + throw new Error("snapshot copy source path must be a normalized relative POSIX path"); + } + return candidate; +} + +function containerPath(value: unknown, label: string): string { + const candidate = boundedText(value, label, MAX_PATH_BYTES); + if ( + !path.posix.isAbsolute(candidate) || + path.posix.normalize(candidate) !== candidate || + candidate === "/" + ) { + throw new Error(`${label} must be a normalized absolute container path`); + } + return candidate; +} + +function preparationRecipe(value: unknown): DualSparkVllmPreparationRecipe { + if (!isRecord(value)) throw new Error("model preparation must be an object"); + if (value.ref === NO_PREPARATION_REF) { + exactKeys(value, ["ref"], "model preparation"); + return { ref: NO_PREPARATION_REF }; + } + exactKeys(value, ["exactTextReplacement", "ref", "snapshotCopy"], "model preparation"); + if (value.ref !== SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF) { + throw new Error(`unsupported model preparation ${String(value.ref)}`); + } + if (!isRecord(value.snapshotCopy)) throw new Error("snapshot copy preparation is invalid"); + exactKeys(value.snapshotCopy, ["sourcePath", "targetPath"], "snapshot copy preparation"); + if (!isRecord(value.exactTextReplacement)) { + throw new Error("exact-text replacement preparation is invalid"); + } + exactKeys( + value.exactTextReplacement, + ["expectedText", "replacementText", "targetPath"], + "exact-text replacement preparation", + ); + const expectedText = boundedText( + value.exactTextReplacement.expectedText, + "exact-text replacement expected text", + ); + const replacementText = boundedText( + value.exactTextReplacement.replacementText, + "exact-text replacement replacement text", + ); + if (expectedText === replacementText) { + throw new Error("exact-text replacement must change the matched text"); + } + return { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { + sourcePath: snapshotRelativePath(value.snapshotCopy.sourcePath), + targetPath: containerPath(value.snapshotCopy.targetPath, "snapshot copy target path"), + }, + exactTextReplacement: { + targetPath: containerPath( + value.exactTextReplacement.targetPath, + "exact-text replacement target path", + ), + expectedText, + replacementText, + }, + }; +} + +/** Materialize one allowlisted, non-executable preparation operation from recipe data. */ +export function materializeDualSparkVllmPreparation( + model: PreparationModel, +): DualSparkVllmPreparationPlan { + if (!MODEL_ID.test(model.id) || !MODEL_REVISION.test(model.revision)) { + throw new Error("model preparation identity is invalid"); + } + if (!Number.isSafeInteger(model.downloadSizeBytes) || model.downloadSizeBytes <= 0) { + throw new Error("model preparation download size is invalid"); + } + const modelCacheTarget = containerPath(model.modelCacheTarget, "model cache target"); + const preparation = preparationRecipe(model.preparation); + const base = { + phase: "container-before-exec" as const, + modelId: model.id, + modelRevision: model.revision, + modelDownloadSizeBytes: model.downloadSizeBytes, + }; + if (preparation.ref === NO_PREPARATION_REF) { + return { ...base, ref: NO_PREPARATION_REF }; + } + const snapshotRoot = `${modelCacheTarget}/hub/models--${model.id.replaceAll( + "/", + "--", + )}/snapshots/${model.revision}`; + return { + ...base, + ref: preparation.ref, + snapshotCopy: { + sourcePath: `${snapshotRoot}/${preparation.snapshotCopy.sourcePath}`, + targetPath: preparation.snapshotCopy.targetPath, + }, + exactTextReplacement: preparation.exactTextReplacement, + }; +} diff --git a/src/lib/inference/serving/dual-spark-topology.test.ts b/src/lib/inference/serving/dual-spark-topology.test.ts index 20257f7597c..f7269809e67 100644 --- a/src/lib/inference/serving/dual-spark-topology.test.ts +++ b/src/lib/inference/serving/dual-spark-topology.test.ts @@ -38,7 +38,10 @@ function readiness(overrides: Partial = {}): SystemReadin observedAt: READINESS_OBSERVED_AT, }, observations: [], - capabilities: REQUIRED_CAPABILITIES.map((id) => ({ id, state: "present" as const })), + capabilities: REQUIRED_CAPABILITIES.map((id) => ({ + id, + state: "present" as const, + })), qualifications: [ { id: "host.platform.dgx_spark", @@ -146,8 +149,8 @@ describe("dual DGX Spark topology qualification", () => { const result = qualifyDualSparkTopology(qualificationInput()); expect(result.outcome).toBe("qualified"); - if (result.outcome !== "qualified") return; - expect(result.artifact).toMatchObject({ + const qualified = result as Extract; + expect(qualified.artifact).toMatchObject({ id: DUAL_SPARK_TOPOLOGY_ID, schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, status: "qualified", @@ -162,18 +165,18 @@ describe("dual DGX Spark topology qualification", () => { }, }, }); - expect(result.artifact.subjectDigest).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(result.artifact.outputDigest).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(result.artifact.output.nodes).toEqual([ + expect(qualified.artifact.subjectDigest).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(qualified.artifact.outputDigest).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(qualified.artifact.output.nodes).toEqual([ { nodeId: "spark-head", gpuId: "GPU-head", role: "head" }, { nodeId: "spark-worker", gpuId: "GPU-worker", role: "worker" }, ]); - expect(result.artifact.output.rails).toHaveLength(2); - expect(result.artifact.output.rails.map(({ head }) => head.netdev)).toEqual([ + expect(qualified.artifact.output.rails).toHaveLength(2); + expect(qualified.artifact.output.rails.map(({ head }) => head.netdev)).toEqual([ "enp1s0f0np0", "enP2p1s0f0np0", ]); - expect(result.artifact.output.rails[0]).toMatchObject({ + expect(qualified.artifact.output.rails[0]).toMatchObject({ index: 0, head: { hcaDevice: "rocep1s0f0", @@ -257,27 +260,37 @@ describe("dual DGX Spark topology qualification", () => { name: "an unknown Spark qualification", mutate: (report: SystemReadinessReport) => { report.qualifications = [ - { id: "host.platform.dgx_spark", status: "unknown", capabilityIds: [] }, + { + id: "host.platform.dgx_spark", + status: "unknown", + capabilityIds: [], + }, ]; }, code: "spark-qualification-unavailable", }, - { - name: "an unknown runtime capability", - mutate: (report: SystemReadinessReport) => { - report.capabilities = report.capabilities.map((capability) => - capability.id === "host.docker.runtime_supported" - ? { ...capability, state: "unknown" } - : capability, - ); - }, - code: "runtime-qualification-unavailable", - }, ])("fails closed for $name", ({ mutate, code }) => { const input = qualificationInput(); mutate(input.peers[0]!.readiness); - expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code, + }); + }); + + it("leaves serving runtime capability policy to preset resolution", () => { + const input = qualificationInput(); + input.peers[0]!.readiness.capabilities = input.peers[0]!.readiness.capabilities.map( + (capability) => + capability.id === "host.docker.runtime_supported" + ? { ...capability, state: "unknown" } + : capability, + ); + + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "qualified", + }); }); it.each([ @@ -307,7 +320,10 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); mutate(input); - expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code, + }); }); it.each([ @@ -317,7 +333,10 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); input.peers[0]!.runtimeState = state; - expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code, + }); }); it.each([ @@ -374,7 +393,10 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); mutate(input); - expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", code }); + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code, + }); }); it("rejects a peer without an opaque pretrusted SSH binding", () => { @@ -398,7 +420,8 @@ describe("dual DGX Spark topology qualification", () => { const second = qualifyDualSparkTopology(secondInput); expect(first.outcome).toBe("qualified"); expect(second.outcome).toBe("qualified"); - if (first.outcome !== "qualified" || second.outcome !== "qualified") return; - expect(second.artifact).toEqual(first.artifact); + const firstQualified = first as Extract; + const secondQualified = second as Extract; + expect(secondQualified.artifact).toEqual(firstQualified.artifact); }); }); diff --git a/src/lib/inference/serving/dual-spark-topology.ts b/src/lib/inference/serving/dual-spark-topology.ts index 9679a676924..f3397403c0e 100644 --- a/src/lib/inference/serving/dual-spark-topology.ts +++ b/src/lib/inference/serving/dual-spark-topology.ts @@ -6,26 +6,11 @@ import net from "node:net"; import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; import type { SystemReadinessReport } from "../../readiness/types.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; -import { - DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - type ManagedInferenceTopologyQualification, -} from "./catalog-types.js"; - -export const DUAL_SPARK_TOPOLOGY_ID = DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID; -export { DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION }; - -const REQUIRED_READINESS_CAPABILITY_IDS = [ - "host.platform.supported", - "host.platform.dgx_spark", - "host.docker.available", - "host.docker.daemon_reachable", - "host.docker.runtime_supported", - "host.docker.storage_compatible", - "host.gpu.nvidia_available", - "host.gpu.container_toolkit_available", - "host.gpu.cdi_healthy", -] as const; +import type { ManagedInferenceTopologyQualification } from "./catalog-types.js"; + +export const DUAL_SPARK_TOPOLOGY_ID = "dgx-spark.gb10.dual-cx7" as const; +export const DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION = 1 as const; + const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const SAFE_INTERFACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; const SAFE_BINDING_HANDLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,8191}$/; @@ -208,14 +193,6 @@ function validateQualificationPolicy( return evaluatedAtMs; } -function findUniqueCapability( - report: SystemReadinessReport, - id: string, -): SystemReadinessReport["capabilities"][number] | undefined { - const matches = report.capabilities.filter((capability) => capability.id === id); - return matches.length === 1 ? matches[0] : undefined; -} - function validateReadiness( report: SystemReadinessReport, evaluatedAtMs: number, @@ -265,14 +242,6 @@ function validateReadiness( }; } - for (const id of REQUIRED_READINESS_CAPABILITY_IDS) { - if (findUniqueCapability(report, id)?.state !== "present") { - return { - code: "runtime-qualification-unavailable", - message: "A node readiness report does not qualify the required container runtime.", - }; - } - } return undefined; } diff --git a/src/lib/inference/serving/generated/catalog.json b/src/lib/inference/serving/generated/catalog.json index 93c392bdd0a..3cec1feeef5 100644 --- a/src/lib/inference/serving/generated/catalog.json +++ b/src/lib/inference/serving/generated/catalog.json @@ -1,5 +1,5 @@ { - "catalogDigest": "sha256:a3d23879b39b36e3ab80cee6846f4a6e7866bfe3589f650bc72ad92e2b182788", + "catalogDigest": "sha256:a38d1e4e861f412ddaaa603b1ae4c7521e10c3d4ec80f102eee950fb28acb4a8", "compilerVersion": "1.0.0", "presets": [ { @@ -24,6 +24,7 @@ }, "recipeRef": "vllm.deepseek-v4-flash-0731.spark-dual.v1" }, + "priority": 400, "requirements": { "all": [ { @@ -34,6 +35,78 @@ "status": "qualified" } }, + { + "readiness": { + "id": "host.platform.supported", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.platform.dgx_spark", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.docker.available", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.docker.daemon_reachable", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.docker.runtime_supported", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.docker.storage_compatible", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.gpu.nvidia_available", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.gpu.container_toolkit_available", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, + { + "readiness": { + "id": "host.gpu.cdi_healthy", + "kind": "capability", + "scope": "everyNode", + "state": "present" + } + }, { "fact": "cluster.nodeCount", "operator": "equals", @@ -52,7 +125,7 @@ "selection": "automatic" } }, - "definitionDigest": "sha256:ab115dd1842489f0eb64aa54e26b4ef2d8ff8e5725fa5b3af84398d31ff2f523", + "definitionDigest": "sha256:a49aa9a24b28b9b5b077d9b9e14f94cd38b328a45e6129704a1a7fb9def72262", "sourceFile": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" } ], @@ -86,9 +159,21 @@ }, "model": { "downloadSizeBytes": 166898661074, - "encodingPath": "encoding/encoding_dsv4.py", + "gated": false, "id": "deepseek-ai/DeepSeek-V4-Flash-0731", - "preparationRef": "deepseek-v4-flash-0731/v1", + "installFastSafetensors": false, + "preparation": { + "exactTextReplacement": { + "expectedText": "elif reasoning_effort in (\"max\", \"xhigh\"):\n reasoning_effort = \"max\"\n else:\n reasoning_effort = \"high\"", + "replacementText": "elif reasoning_effort in (\"max\", \"xhigh\"):\n reasoning_effort = \"max\"\n elif reasoning_effort == \"high\":\n reasoning_effort = \"high\"\n else:\n reasoning_effort = \"low\"", + "targetPath": "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py" + }, + "ref": "snapshot-copy-and-exact-text-replacement/v1", + "snapshotCopy": { + "sourcePath": "encoding/encoding_dsv4.py", + "targetPath": "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py" + } + }, "revision": "9e165c30e2704aec5d9d593cce3eebd58bbef1cb", "servedName": "deepseek-v4-flash-0731" }, @@ -108,7 +193,6 @@ "FLASHINFER_CUDA_ARCH_LIST": "12.1a", "FLASHINFER_DISABLE_VERSION_CHECK": "1", "FLASHINFER_WORKSPACE_BASE": "/cache/huggingface/flashinfer", - "HF_HOME": "/cache/huggingface", "HF_HUB_DISABLE_XET": "1", "HF_HUB_OFFLINE": "1", "NCCL_CROSS_NIC": "1", @@ -132,11 +216,45 @@ "VLLM_USE_BREAKABLE_CUDAGRAPH": "0", "VLLM_USE_FLASHINFER_SAMPLER": "1" }, + "gpuRequest": "all", "image": "ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8", "imageDownloadSizeBytes": 9787537825, "ipcMode": "host", + "modelCache": { + "source": "huggingface-cache", + "target": "/cache/huggingface" + }, "networkMode": "host", - "sharedMemoryBytes": 68719476736 + "pullTimeoutSeconds": 43200, + "sharedMemoryBytes": 68719476736, + "temporaryFilesystems": [ + { + "mode": "0700", + "options": [ + "rw", + "nosuid", + "nodev", + "exec" + ], + "sizeBytes": 17179869184, + "target": "/cache/huggingface" + }, + { + "mode": "1777", + "options": [ + "rw", + "nosuid", + "nodev", + "exec" + ], + "sizeBytes": 17179869184, + "target": "/tmp" + } + ], + "ulimits": { + "memlock": -1, + "stackBytes": 67108864 + } }, "serve": { "arguments": [ @@ -226,24 +344,25 @@ "name": "--enable-flashinfer-autotune" } ], - "authentication": "bearer" + "authentication": "bearer", + "executable": "/usr/local/bin/vllm" } } }, - "definitionDigest": "sha256:9ff596013e4e4bb6d22ead3aff23917437239e0bcfbf7f8af79e27f5ec908f0f", + "definitionDigest": "sha256:47d72d6065cf9cf942034dcd7eb32199c800bb56a046950cf2c79de2a4796fa5", "sourceFile": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" } ], "schemaVersion": "1.0.0", "sourceFiles": [ { - "digest": "sha256:e0c4c3a6f175d1ce65bdc1f7d8d4b59247909e884949110628017d7b4adb85a8", + "digest": "sha256:3ec369485750277058344be345187cdac9318d5b1ea2eef55ce78c33c62891ba", "path": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" }, { - "digest": "sha256:1dda2fbb6358718dcb718adfb836d43f4dc7bf446f196794e8f9a2dc95087802", + "digest": "sha256:f59a45f2661f2ce072b3888802b8d081fb8d747c322c74e1d660a4d969ef0cf9", "path": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" } ], - "sourceRevision": "sha256:d7a897e9b3424f44aa0662a0452da2921686ee3f6779fd0b2d0e858b5625b328" + "sourceRevision": "sha256:1602dfca0d1166579893c17a34fd41d39c8a7da99c903f40d3a1fb0466df3584" } diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 59782fd0275..496912aa00c 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -2,13 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; - import type { SystemReadinessReport } from "../../readiness/types.js"; -import { - DUAL_SPARK_PRESET_ID, - type ManagedInferenceReadinessSource, - type ManagedInferenceResolverInput, - type ManagedInferenceTopologyQualification, +import { loadManagedInferenceCatalog } from "./catalog.js"; +import { managedInferenceDigest } from "./catalog-integrity.js"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferencePresetRequirement, + ManagedInferenceReadinessSource, + ManagedInferenceResolverInput, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ManagedInferenceTopologyQualification, } from "./catalog-types.js"; import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; import { @@ -20,7 +24,65 @@ import { resolveManagedInferenceServing } from "./resolver.js"; const NOW = new Date("2026-08-02T18:00:00.000Z"); const SOURCE_REVISION = "a".repeat(40); +function shippedCatalog(): CompiledManagedInferenceCatalog { + return structuredClone(loadManagedInferenceCatalog()); +} + +function shippedPreset(catalog = shippedCatalog()): ManagedInferenceServingPreset { + const preset = catalog.presets[0]?.definition; + expect(preset).toBeDefined(); + return preset as ManagedInferenceServingPreset; +} + +function shippedRecipe(catalog = shippedCatalog()): ManagedInferenceServingRecipe { + const recipe = catalog.recipes[0]?.definition; + expect(recipe).toBeDefined(); + return recipe as ManagedInferenceServingRecipe; +} + +function catalogReadinessEntities(): Pick< + SystemReadinessReport, + "observations" | "capabilities" | "qualifications" +> { + const readinessRequirements = shippedPreset().spec.requirements.all.flatMap((requirement) => + "readiness" in requirement ? [requirement.readiness] : [], + ); + return { + observations: readinessRequirements.flatMap((readiness) => + readiness.kind === "observation" + ? [ + { + id: readiness.id, + state: readiness.state as SystemReadinessReport["observations"][number]["state"], + }, + ] + : [], + ), + capabilities: readinessRequirements.flatMap((readiness) => + readiness.kind === "capability" + ? [ + { + id: readiness.id, + state: readiness.state as SystemReadinessReport["capabilities"][number]["state"], + }, + ] + : [], + ), + qualifications: readinessRequirements.flatMap((readiness) => + readiness.kind === "qualification" + ? [ + { + id: readiness.id, + status: readiness.status as SystemReadinessReport["qualifications"][number]["status"], + }, + ] + : [], + ), + }; +} + function readinessReport(overrides: Partial = {}): SystemReadinessReport { + const entities = catalogReadinessEntities(); return { schemaVersion: "1.1.0", mutated: false, @@ -29,15 +91,7 @@ function readinessReport(overrides: Partial = {}): System sourceRevision: SOURCE_REVISION, observedAt: "2026-08-02T17:59:50.000Z", }, - observations: [], - capabilities: [{ id: "host.platform.dgx_spark", state: "present" }], - qualifications: [ - { - id: "host.platform.dgx_spark", - status: "qualified", - capabilityIds: ["host.platform.dgx_spark"], - }, - ], + ...entities, findings: [], evidence: [], status: "supported", @@ -57,10 +111,7 @@ function topology( overrides: Partial> = {}, ): ManagedInferenceTopologyQualification { const artifact = structuredClone(fixtureDualSparkSelection().topologyQualification); - return { - ...artifact, - ...overrides, - }; + return { ...artifact, ...overrides }; } function resolverInput( @@ -74,31 +125,340 @@ function resolverInput( }; } +function catalogWithSecondProfile(options: { + readonly firstPriority: number; + readonly secondPriority: number; + readonly secondSelection?: "automatic" | "explicit-only" | "disabled"; +}): { + readonly catalog: CompiledManagedInferenceCatalog; + readonly secondPresetId: string; + readonly secondRecipeId: string; +} { + const catalog = shippedCatalog(); + const firstPreset = shippedPreset(catalog); + const firstRecipe = shippedRecipe(catalog); + const secondPresetId = "vllm.synthetic.dual-second"; + const secondRecipeId = "vllm.synthetic.second-recipe"; + const normalizedFirst = { + ...firstPreset, + spec: { ...firstPreset.spec, priority: options.firstPriority }, + } as ManagedInferenceServingPreset; + const secondRecipe = { + ...firstRecipe, + metadata: { + ...firstRecipe.metadata, + id: secondRecipeId, + displayName: "Synthetic model", + }, + spec: { + ...firstRecipe.spec, + model: { + ...firstRecipe.spec.model, + id: "example/AnotherModel", + revision: "b".repeat(40), + servedName: "another-model", + }, + readiness: { + ...firstRecipe.spec.readiness, + expectedModel: "another-model", + }, + }, + } as ManagedInferenceServingRecipe; + const secondPreset = { + ...firstPreset, + metadata: { + ...firstPreset.metadata, + id: secondPresetId, + displayName: "Synthetic preset", + }, + spec: { + ...firstPreset.spec, + selection: options.secondSelection ?? "automatic", + priority: options.secondPriority, + plan: { ...firstPreset.spec.plan, recipeRef: secondRecipeId }, + }, + } as ManagedInferenceServingPreset; + return { + catalog: { + ...catalog, + presets: [ + { + ...catalog.presets[0]!, + definition: normalizedFirst, + definitionDigest: managedInferenceDigest(normalizedFirst), + }, + { + ...catalog.presets[0]!, + definition: secondPreset, + definitionDigest: managedInferenceDigest(secondPreset), + sourceFile: "managed-inference/presets/vllm.synthetic.dual-second.yaml", + }, + ], + recipes: [ + catalog.recipes[0]!, + { + ...catalog.recipes[0]!, + definition: secondRecipe, + definitionDigest: managedInferenceDigest(secondRecipe), + sourceFile: "managed-inference/recipes/vllm.synthetic.second-recipe.yaml", + }, + ], + }, + secondPresetId, + secondRecipeId, + }; +} + describe("managed inference resolver", () => { - it("selects the automatic preset for two fresh qualified Sparks and their topology", () => { - const result = resolveManagedInferenceServing(resolverInput()); + it("selects the shipped automatic preset from catalog data", () => { + const catalog = shippedCatalog(); + const result = resolveManagedInferenceServing(resolverInput(), catalog); expect(result).toMatchObject({ outcome: "selected", selection: "automatic", - preset: { metadata: { id: DUAL_SPARK_PRESET_ID } }, - recipe: { spec: { execution: { nodeCount: 2, tensorParallelSize: 2 } } }, + presetDigest: catalog.presets[0]!.definitionDigest, + recipeDigest: catalog.recipes[0]!.definitionDigest, + preset: { metadata: { id: shippedPreset(catalog).metadata.id } }, + recipe: { metadata: { id: shippedRecipe(catalog).metadata.id } }, topologyQualification: { output: { masterAddress: "192.168.100.10" } }, }); }); - it("selects the exact explicit preset only when compatible requirements still pass", () => { + it("looks up and resolves an arbitrary explicit-only preset by ID", () => { + const { catalog, secondPresetId, secondRecipeId } = catalogWithSecondProfile({ + firstPriority: 100, + secondPriority: 1, + secondSelection: "explicit-only", + }); const result = resolveManagedInferenceServing( resolverInput({ - intent: { - preset: DUAL_SPARK_PRESET_ID, - provider: "vllm", - vllmModel: "deepseek-ai/DeepSeek-V4-Flash-0731", + intent: { preset: secondPresetId, vllmModel: "another-model" }, + }), + catalog, + ); + + expect(result).toMatchObject({ + outcome: "selected", + selection: "explicit", + preset: { metadata: { id: secondPresetId } }, + recipe: { metadata: { id: secondRecipeId } }, + }); + }); + + it("selects the highest-priority matching automatic preset", () => { + const { catalog, secondPresetId, secondRecipeId } = catalogWithSecondProfile({ + firstPriority: 100, + secondPriority: 200, + }); + const result = resolveManagedInferenceServing(resolverInput(), catalog); + + expect(result).toMatchObject({ + outcome: "selected", + preset: { metadata: { id: secondPresetId } }, + recipe: { metadata: { id: secondRecipeId } }, + }); + }); + + it("selects a lower-priority profile when higher-priority requirements do not match", () => { + const { + catalog: baseCatalog, + secondPresetId, + secondRecipeId, + } = catalogWithSecondProfile({ + firstPriority: 200, + secondPriority: 100, + }); + const highPreset = baseCatalog.presets[0]!.definition; + const unavailableHighPreset = { + ...highPreset, + spec: { + ...highPreset.spec, + requirements: { + all: [ + { + readiness: { + scope: "everyNode", + kind: "capability", + id: "host.synthetic.unavailable", + state: "present", + }, + }, + ...highPreset.spec.requirements.all, + ], }, + }, + } as ManagedInferenceServingPreset; + const catalog: CompiledManagedInferenceCatalog = { + ...baseCatalog, + presets: [ + { + ...baseCatalog.presets[0]!, + definition: unavailableHighPreset, + definitionDigest: managedInferenceDigest(unavailableHighPreset), + }, + baseCatalog.presets[1]!, + ], + }; + + expect(resolveManagedInferenceServing(resolverInput(), catalog)).toMatchObject({ + outcome: "selected", + preset: { metadata: { id: secondPresetId } }, + recipe: { metadata: { id: secondRecipeId } }, + }); + }); + + it("rejects equal-priority automatic matches as ambiguous", () => { + const { catalog, secondPresetId } = catalogWithSecondProfile({ + firstPriority: 100, + secondPriority: 100, + }); + const result = resolveManagedInferenceServing(resolverInput(), catalog); + + expect(result).toMatchObject({ + outcome: "rejected", + code: "ambiguous-selection", + }); + const rejected = result as Extract; + expect(rejected.message).toContain(shippedPreset(catalog).metadata.id); + expect(rejected.message).toContain(secondPresetId); + }); + + it("evaluates registered readiness entities and numeric facts without profile branches", () => { + const catalog = shippedCatalog(); + const preset = shippedPreset(catalog); + const topologyRequirement = preset.spec.requirements.all.find( + (requirement) => "topologyQualification" in requirement, + ); + expect(topologyRequirement).toBeDefined(); + const genericRequirements: ManagedInferencePresetRequirement[] = [ + { + readiness: { + scope: "everyNode", + kind: "capability", + id: "host.docker.available", + state: "present", + }, + }, + { + fact: "cluster.nodeCount", + state: "present", + operator: "between", + value: [2, 2], + }, + topologyRequirement as ManagedInferencePresetRequirement, + ]; + const customizedPreset = { + ...preset, + spec: { + ...preset.spec, + requirements: { all: genericRequirements }, + }, + } as ManagedInferenceServingPreset; + const customizedCatalog: CompiledManagedInferenceCatalog = { + ...catalog, + presets: [ + { + ...catalog.presets[0]!, + definition: customizedPreset, + definitionDigest: managedInferenceDigest(customizedPreset), + }, + ], + }; + + expect(resolveManagedInferenceServing(resolverInput(), customizedCatalog)).toMatchObject({ + outcome: "selected", + }); + const missingCapability = readinessSources(); + missingCapability[1] = { + nodeId: "spark-worker", + report: readinessReport({ + capabilities: readinessReport().capabilities.map((capability) => + capability.id === "host.docker.available" + ? { ...capability, state: "absent" } + : capability, + ), }), + }; + expect( + resolveManagedInferenceServing( + resolverInput({ readinessReports: missingCapability }), + customizedCatalog, + ), + ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); + }); + + it("applies any-node readiness requirements as an existential match", () => { + const catalog = shippedCatalog(); + const preset = shippedPreset(catalog); + const topologyRequirement = preset.spec.requirements.all.find( + (requirement) => "topologyQualification" in requirement, ); + expect(topologyRequirement).toBeDefined(); + const customizedPreset = { + ...preset, + spec: { + ...preset.spec, + requirements: { + all: [ + { + readiness: { + scope: "anyNode", + kind: "capability", + id: "host.docker.available", + state: "present", + }, + }, + topologyRequirement as ManagedInferencePresetRequirement, + ], + }, + }, + } as ManagedInferenceServingPreset; + const customizedCatalog: CompiledManagedInferenceCatalog = { + ...catalog, + presets: [ + { + ...catalog.presets[0]!, + definition: customizedPreset, + definitionDigest: managedInferenceDigest(customizedPreset), + }, + ], + }; + const reports = readinessSources(); + reports[1] = { + nodeId: "spark-worker", + report: readinessReport({ + capabilities: readinessReport().capabilities.map((capability) => + capability.id === "host.docker.available" + ? { ...capability, state: "absent" } + : capability, + ), + }), + }; + + expect( + resolveManagedInferenceServing( + resolverInput({ readinessReports: reports }), + customizedCatalog, + ), + ).toMatchObject({ outcome: "selected" }); - expect(result).toMatchObject({ outcome: "selected", selection: "explicit" }); + reports[0] = { + nodeId: "spark-head", + report: readinessReport({ + capabilities: readinessReport().capabilities.map((capability) => + capability.id === "host.docker.available" + ? { ...capability, state: "absent" } + : capability, + ), + }), + }; + expect( + resolveManagedInferenceServing( + resolverInput({ readinessReports: reports }), + customizedCatalog, + ), + ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); }); it("returns an immutable topology snapshot", () => { @@ -108,10 +468,10 @@ describe("managed inference resolver", () => { ); expect(result.outcome).toBe("selected"); - if (result.outcome !== "selected") return; + const selected = result as Extract; (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; - expect(result.topologyQualification.output.masterAddress).toBe("192.168.100.10"); - expect(Object.isFrozen(result.topologyQualification.output)).toBe(true); + expect(selected.topologyQualification.output.masterAddress).toBe("192.168.100.10"); + expect(Object.isFrozen(selected.topologyQualification.output)).toBe(true); }); it.each([ @@ -135,11 +495,29 @@ describe("managed inference resolver", () => { ).toMatchObject({ outcome: "rejected", code: "unknown-preset" }); }); - it("rejects explicit preset intent that conflicts with its immutable recipe", () => { + it("rejects a disabled explicit preset", () => { + const { catalog, secondPresetId } = catalogWithSecondProfile({ + firstPriority: 100, + secondPriority: 200, + secondSelection: "disabled", + }); + expect( + resolveManagedInferenceServing( + resolverInput({ intent: { preset: secondPresetId } }), + catalog, + ), + ).toMatchObject({ outcome: "rejected", code: "requirements-not-met" }); + }); + + it("rejects explicit preset intent that conflicts with its recipe", () => { + const presetId = shippedPreset().metadata.id; expect( resolveManagedInferenceServing( resolverInput({ - intent: { preset: DUAL_SPARK_PRESET_ID, vllmExtraArguments: ["--max-model-len", "1"] }, + intent: { + preset: presetId, + vllmExtraArguments: ["--max-model-len", "1"], + }, }), ), ).toMatchObject({ outcome: "rejected", code: "incompatible-intent" }); @@ -166,18 +544,6 @@ describe("managed inference resolver", () => { findings: [{ id: "host.blocked", severity: "blocking", summary: "Blocked." }], }), }, - { - name: "unknown Spark qualification", - report: readinessReport({ - qualifications: [ - { - id: "host.platform.dgx_spark", - status: "unknown", - capabilityIds: ["host.platform.dgx_spark"], - }, - ], - }), - }, ])("rejects $name before selecting a recipe", ({ report }) => { const sources = readinessSources(); sources[1] = { nodeId: "spark-worker", report }; @@ -204,7 +570,7 @@ describe("managed inference resolver", () => { ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); }); - it("does not activate automatically without the qualified topology artifact", () => { + it("does not activate automatically without the required topology artifact", () => { expect( resolveManagedInferenceServing(resolverInput({ topologyQualifications: [] })), ).toMatchObject({ outcome: "no-match", code: "requirements-not-met" }); @@ -264,7 +630,7 @@ describe("managed inference resolver", () => { resolveManagedInferenceServing( resolverInput({ readinessReports: readinessSources().slice(0, 1), - intent: { preset: DUAL_SPARK_PRESET_ID }, + intent: { preset: shippedPreset().metadata.id }, }), ), ).toMatchObject({ outcome: "rejected", code: "requirements-not-met" }); diff --git a/src/lib/inference/serving/resolver.ts b/src/lib/inference/serving/resolver.ts index 611759a2ca5..1dff1932c5d 100644 --- a/src/lib/inference/serving/resolver.ts +++ b/src/lib/inference/serving/resolver.ts @@ -3,22 +3,26 @@ import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; import { getSystemReadinessReferenceErrors } from "../../readiness/references.js"; -import type { SystemReadinessReport } from "../../readiness/types.js"; +import { + getManagedInferenceRecipeRegistrationError, + getManagedInferenceTopologyQualificationDescriptor, +} from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; -import { - DUAL_SPARK_PRESET_ID, - DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - type ManagedInferenceReadinessSource, - type ManagedInferenceResolution, - type ManagedInferenceResolverInput, - type ManagedInferenceSelectionIntent, - type ManagedInferenceServingPreset, - type ManagedInferenceServingRecipe, - type ManagedInferenceTopologyQualification, +import type { + CompiledManagedInferenceCatalog, + ManagedInferenceFactRequirement, + ManagedInferencePresetRequirement, + ManagedInferenceReadinessRequirement, + ManagedInferenceReadinessSource, + ManagedInferenceResolution, + ManagedInferenceResolverInput, + ManagedInferenceSelectionIntent, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ManagedInferenceTopologyQualification, + ManagedInferenceTopologyRequirement, } from "./catalog-types.js"; -import { getDualSparkTopologyArtifactError } from "./dual-spark-topology.js"; export const MANAGED_INFERENCE_READINESS_MAX_AGE_MS = 30_000; const MAX_FUTURE_CLOCK_SKEW_MS = 5_000; @@ -26,10 +30,33 @@ const SOURCE_REVISION = /^[0-9a-f]{40,64}$/u; const PUBLIC_VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u; +type SelectionOperator = ManagedInferenceFactRequirement["operator"]; + +type RequirementEvaluation = + | { + readonly outcome: "matched"; + readonly topologyQualifications: readonly ManagedInferenceTopologyQualification[]; + } + | { readonly outcome: "unmet"; readonly message: string } + | { readonly outcome: "invalid-topology"; readonly message: string }; + +interface MatchingCandidate { + readonly preset: ManagedInferenceServingPreset; + readonly presetDigest: string; + readonly recipe: ManagedInferenceServingRecipe; + readonly recipeDigest: string; + readonly priority: number; + readonly topologyQualification: ManagedInferenceTopologyQualification; +} + function hasText(value: string | undefined): value is string { return typeof value === "string" && value.trim().length > 0; } +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + function explicitIntentWithoutPreset(intent: ManagedInferenceSelectionIntent): boolean { return ( hasText(intent.provider) || @@ -67,12 +94,6 @@ function readinessError( if (report.findings.some(({ severity }) => severity === "fatal" || severity === "blocking")) { return `${nodeId}: readiness report contains a blocking finding`; } - const sparkQualifications = report.qualifications.filter( - ({ id }) => id === "host.platform.dgx_spark", - ); - if (sparkQualifications.length !== 1 || sparkQualifications[0]?.status !== "qualified") { - return `${nodeId}: DGX Spark qualification is not qualified`; - } return undefined; } @@ -82,8 +103,9 @@ function readinessReportsError( maxAgeMs: number, ): string | undefined { const nodeIds = sources.map(({ nodeId }) => nodeId); - if (new Set(nodeIds).size !== nodeIds.length) + if (new Set(nodeIds).size !== nodeIds.length) { return "readiness reports contain duplicate node IDs"; + } for (const source of sources) { const error = readinessError(source, nowMs, maxAgeMs); if (error) return error; @@ -91,96 +113,309 @@ function readinessReportsError( return undefined; } -function requirementsError( +function scalarEquals(actual: unknown, expected: unknown): boolean { + return ( + (actual === null || ["string", "number", "boolean"].includes(typeof actual)) && + actual === expected + ); +} + +function matchesOperator(actual: unknown, operator: SelectionOperator, expected: unknown): boolean { + switch (operator) { + case "equals": + return scalarEquals(actual, expected); + case "oneOf": + return ( + Array.isArray(expected) && expected.some((candidate) => scalarEquals(actual, candidate)) + ); + case "atLeast": + return typeof actual === "number" && typeof expected === "number" && actual >= expected; + case "atMost": + return typeof actual === "number" && typeof expected === "number" && actual <= expected; + case "between": + return ( + typeof actual === "number" && + Array.isArray(expected) && + expected.length === 2 && + typeof expected[0] === "number" && + typeof expected[1] === "number" && + actual >= expected[0] && + actual <= expected[1] + ); + } +} + +function readinessScopeMatches( + scope: string, + reports: readonly ManagedInferenceReadinessSource[], + predicate: (source: ManagedInferenceReadinessSource) => boolean, +): boolean { + if (reports.length === 0) return false; + if (scope === "everyNode") return reports.every(predicate); + if (scope === "anyNode") return reports.some(predicate); + return false; +} + +function readinessRequirementMatches( + requirement: ManagedInferenceReadinessRequirement["readiness"], + reports: readonly ManagedInferenceReadinessSource[], +): boolean { + return readinessScopeMatches(requirement.scope, reports, ({ report }) => { + if (requirement.kind === "qualification") { + const matches = report.qualifications.filter(({ id }) => id === requirement.id); + return matches.length === 1 && matches[0]!.status === requirement.status; + } + const collection = + requirement.kind === "observation" ? report.observations : report.capabilities; + const matches = collection.filter(({ id }) => id === requirement.id); + return matches.length === 1 && matches[0]!.state === requirement.state; + }); +} + +function selectionFact( + path: string, + reports: readonly ManagedInferenceReadinessSource[], +): + | { + readonly state: "present"; + readonly value: ManagedInferenceFactRequirement["value"]; + } + | undefined { + if (path === "cluster.nodeCount") return { state: "present", value: reports.length }; + return undefined; +} + +function factRequirementMatches( + requirement: ManagedInferenceFactRequirement, + reports: readonly ManagedInferenceReadinessSource[], +): boolean { + const fact = selectionFact(requirement.fact, reports); + if (!fact) return false; + return ( + requirement.state === fact.state && + matchesOperator(fact.value, requirement.operator, requirement.value) + ); +} + +function evaluateTopologyRequirement( + requirement: ManagedInferenceTopologyRequirement["topologyQualification"], + artifacts: readonly ManagedInferenceTopologyQualification[], + expectedSubjectNodeIds: readonly string[], +): + | { + readonly outcome: "matched"; + readonly artifact: ManagedInferenceTopologyQualification; + } + | { readonly outcome: "unmet"; readonly message: string } + | { readonly outcome: "invalid-topology"; readonly message: string } { + const descriptor = getManagedInferenceTopologyQualificationDescriptor( + requirement.id, + requirement.schemaVersion, + ); + if (!descriptor) { + return { + outcome: "invalid-topology", + message: `Topology qualification ${requirement.id}@${String(requirement.schemaVersion)} is not registered.`, + }; + } + const matching = artifacts.filter( + ({ id, schemaVersion }) => id === requirement.id && schemaVersion === requirement.schemaVersion, + ); + if (matching.length === 0) { + return { + outcome: "unmet", + message: `Topology requirement ${requirement.id} did not match.`, + }; + } + if (matching.length !== 1) { + return { + outcome: "invalid-topology", + message: `Topology qualification ${requirement.id} has more than one candidate.`, + }; + } + const artifact = matching[0]!; + if (artifact.status !== requirement.status) { + return { + outcome: "unmet", + message: `Topology requirement ${requirement.id} did not match.`, + }; + } + const error = descriptor.validateArtifact(artifact, expectedSubjectNodeIds); + return error ? { outcome: "invalid-topology", message: error } : { outcome: "matched", artifact }; +} + +function evaluateRequirements( preset: ManagedInferenceServingPreset, reports: readonly ManagedInferenceReadinessSource[], - topology: ManagedInferenceTopologyQualification, -): string | undefined { + topologyQualifications: readonly ManagedInferenceTopologyQualification[], +): RequirementEvaluation { + const matchedTopologies: ManagedInferenceTopologyQualification[] = []; + const expectedSubjectNodeIds = reports.map(({ nodeId }) => nodeId).sort(compareStrings); for (const requirement of preset.spec.requirements.all) { if ("readiness" in requirement) { - const matches = reports.every(({ report }) => - report.qualifications.some( - ({ id, status }) => - id === requirement.readiness.id && status === requirement.readiness.status, - ), - ); - if (!matches) return `readiness requirement ${requirement.readiness.id} did not match`; - } else if ("fact" in requirement) { - if ( - requirement.state !== "present" || - requirement.operator !== "equals" || - reports.length !== requirement.value - ) { - return `selection fact ${requirement.fact} did not match`; + if (!readinessRequirementMatches(requirement.readiness, reports)) { + return { + outcome: "unmet", + message: `Readiness requirement ${requirement.readiness.id} did not match.`, + }; } - } else if ( - topology.id !== requirement.topologyQualification.id || - topology.schemaVersion !== requirement.topologyQualification.schemaVersion || - topology.status !== requirement.topologyQualification.status - ) { - return `topology requirement ${requirement.topologyQualification.id} did not match`; + continue; } + if ("fact" in requirement) { + if (!factRequirementMatches(requirement, reports)) { + return { + outcome: "unmet", + message: `Selection fact ${requirement.fact} did not match.`, + }; + } + continue; + } + const topology = evaluateTopologyRequirement( + requirement.topologyQualification, + topologyQualifications, + expectedSubjectNodeIds, + ); + if (topology.outcome !== "matched") return topology; + matchedTopologies.push(topology.artifact); } - return undefined; + return { outcome: "matched", topologyQualifications: matchedTopologies }; } function intentCompatibilityError( intent: ManagedInferenceSelectionIntent, + preset: ManagedInferenceServingPreset, recipe: ManagedInferenceServingRecipe, ): string | undefined { if (hasText(intent.provider) && intent.provider !== recipe.spec.backend) { - return `provider ${intent.provider} conflicts with preset ${DUAL_SPARK_PRESET_ID}`; + return `provider ${intent.provider} conflicts with preset ${preset.metadata.id}`; } if ( hasText(intent.vllmModel) && intent.vllmModel !== recipe.spec.model.id && intent.vllmModel !== recipe.spec.model.servedName ) { - return `model ${intent.vllmModel} conflicts with preset ${DUAL_SPARK_PRESET_ID}`; + return `model ${intent.vllmModel} conflicts with preset ${preset.metadata.id}`; } if ((intent.vllmExtraArguments?.length ?? 0) > 0) { - return `extra vLLM arguments conflict with preset ${DUAL_SPARK_PRESET_ID}`; + return `extra vLLM arguments conflict with preset ${preset.metadata.id}`; } return undefined; } -function rejectOrSkip(explicit: boolean, message: string): ManagedInferenceResolution { - return explicit - ? { outcome: "rejected", code: "requirements-not-met", message } - : { outcome: "no-match", code: "requirements-not-met", message }; +function presetPriority(preset: ManagedInferenceServingPreset): number { + const priority = (preset.spec as { readonly priority?: unknown }).priority; + if (!Number.isSafeInteger(priority)) { + throw new Error(`managed inference preset ${preset.metadata.id} has an invalid priority`); + } + return priority as number; } -export function resolveManagedInferenceServing( - input: ManagedInferenceResolverInput, -): ManagedInferenceResolution { - const catalog = loadManagedInferenceCatalog(); - const intent = input.intent ?? {}; - const explicitPreset = hasText(intent.preset) ? intent.preset : undefined; - if (!explicitPreset && explicitIntentWithoutPreset(intent)) { +function recipeForPreset( + catalog: CompiledManagedInferenceCatalog, + preset: ManagedInferenceServingPreset, +): CompiledManagedInferenceCatalog["recipes"][number] { + const matches = catalog.recipes.filter( + ({ definition }) => definition.metadata.id === preset.spec.plan.recipeRef, + ); + if (matches.length !== 1) { + throw new Error( + `managed inference preset ${preset.metadata.id} does not resolve exactly one recipe ${preset.spec.plan.recipeRef}`, + ); + } + const compiledRecipe = matches[0]!; + const recipe = compiledRecipe.definition; + if (recipe.spec.backend !== preset.spec.plan.backend) { + throw new Error( + `managed inference preset ${preset.metadata.id} backend does not match its recipe`, + ); + } + const registrationError = getManagedInferenceRecipeRegistrationError(recipe); + if (registrationError) { + throw new Error(`managed inference recipe ${recipe.metadata.id}: ${registrationError}`); + } + return compiledRecipe; +} + +function matchingCandidate( + catalog: CompiledManagedInferenceCatalog, + compiledPreset: CompiledManagedInferenceCatalog["presets"][number], + input: ManagedInferenceResolverInput, +): + | { readonly outcome: "matched"; readonly candidate: MatchingCandidate } + | { readonly outcome: "unmet"; readonly message: string } + | { readonly outcome: "invalid-topology"; readonly message: string } + | { readonly outcome: "incompatible-intent"; readonly message: string } { + const preset = compiledPreset.definition; + const compiledRecipe = recipeForPreset(catalog, preset); + const recipe = compiledRecipe.definition; + const intentError = intentCompatibilityError(input.intent ?? {}, preset, recipe); + if (intentError) return { outcome: "incompatible-intent", message: intentError }; + const requirements = evaluateRequirements( + preset, + input.readinessReports, + input.topologyQualifications, + ); + if (requirements.outcome !== "matched") return requirements; + if (requirements.topologyQualifications.length !== 1) { return { - outcome: "no-match", - code: "explicit-intent", - message: "Existing inference intent remains authoritative.", + outcome: "invalid-topology", + message: `Preset ${preset.metadata.id} must resolve exactly one topology qualification.`, }; } - if (explicitPreset && explicitPreset !== DUAL_SPARK_PRESET_ID) { + return { + outcome: "matched", + candidate: { + preset, + presetDigest: compiledPreset.definitionDigest, + recipe, + recipeDigest: compiledRecipe.definitionDigest, + priority: presetPriority(preset), + topologyQualification: requirements.topologyQualifications[0]!, + }, + }; +} + +function selectedResolution( + catalog: CompiledManagedInferenceCatalog, + candidate: MatchingCandidate, + selection: "automatic" | "explicit", +): ManagedInferenceResolution { + let topologyQualification: ManagedInferenceTopologyQualification; + try { + topologyQualification = immutableManagedInferenceCopy(candidate.topologyQualification); + } catch { return { outcome: "rejected", - code: "unknown-preset", - message: `Unknown managed inference preset ${explicitPreset}.`, + code: "invalid-topology", + message: "Topology qualification is not immutable JSON data.", }; } + return { + outcome: "selected", + selection, + catalogDigest: catalog.catalogDigest, + presetDigest: candidate.presetDigest, + recipeDigest: candidate.recipeDigest, + preset: candidate.preset, + recipe: candidate.recipe, + topologyQualification, + }; +} - const explicit = explicitPreset !== undefined; - const preset = catalog.presets[0]?.definition; - const recipe = catalog.recipes[0]?.definition; - if (!preset || !recipe) throw new Error("compiled managed inference catalog is incomplete"); - const intentError = intentCompatibilityError(intent, recipe); - if (intentError) - return { outcome: "rejected", code: "incompatible-intent", message: intentError }; - if (input.readinessReports.length !== recipe.spec.execution.nodeCount) { - return rejectOrSkip(explicit, "The preset requires exactly two readiness reports."); +export function resolveManagedInferenceServing( + input: ManagedInferenceResolverInput, + catalog: CompiledManagedInferenceCatalog = loadManagedInferenceCatalog(), +): ManagedInferenceResolution { + const intent = input.intent ?? {}; + const explicitPresetId = hasText(intent.preset) ? intent.preset : undefined; + if (!explicitPresetId && explicitIntentWithoutPreset(intent)) { + return { + outcome: "no-match", + code: "explicit-intent", + message: "Existing inference intent remains authoritative.", + }; } + const maxAgeMs = input.maxReadinessAgeMs ?? MANAGED_INFERENCE_READINESS_MAX_AGE_MS; const nowMs = (input.now ?? new Date()).getTime(); if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0 || !Number.isFinite(nowMs)) { @@ -195,45 +430,80 @@ export function resolveManagedInferenceServing( return { outcome: "rejected", code: "invalid-readiness", message: reportsError }; } - const matchingTopologies = input.topologyQualifications.filter( - ({ id, schemaVersion }) => - id === DUAL_SPARK_TOPOLOGY_QUALIFICATION_ID && - schemaVersion === DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - ); - if (matchingTopologies.length === 0) { - return rejectOrSkip(explicit, "The qualified two-Spark topology is unavailable."); - } - if (matchingTopologies.length !== 1) { + if (explicitPresetId) { + const matches = catalog.presets.filter( + ({ definition }) => definition.metadata.id === explicitPresetId, + ); + if (matches.length !== 1) { + return { + outcome: "rejected", + code: "unknown-preset", + message: `Unknown managed inference preset ${explicitPresetId}.`, + }; + } + const compiledPreset = matches[0]!; + const preset = compiledPreset.definition; + if (preset.spec.selection === "disabled") { + return { + outcome: "rejected", + code: "requirements-not-met", + message: `Managed inference preset ${explicitPresetId} is disabled.`, + }; + } + const evaluated = matchingCandidate(catalog, compiledPreset, input); + if (evaluated.outcome === "matched") { + return selectedResolution(catalog, evaluated.candidate, "explicit"); + } return { outcome: "rejected", - code: "invalid-topology", - message: "Topology qualifications contain more than one candidate for the same subject.", + code: + evaluated.outcome === "invalid-topology" + ? "invalid-topology" + : evaluated.outcome === "incompatible-intent" + ? "incompatible-intent" + : "requirements-not-met", + message: evaluated.message, }; } - let topology: ManagedInferenceTopologyQualification; - try { - topology = immutableManagedInferenceCopy(matchingTopologies[0]!); - } catch { + + const matching: MatchingCandidate[] = []; + let firstInvalidTopology: string | undefined; + for (const compiledPreset of catalog.presets) { + const preset = compiledPreset.definition; + if (preset.spec.selection !== "automatic") continue; + const evaluated = matchingCandidate(catalog, compiledPreset, input); + if (evaluated.outcome === "matched") matching.push(evaluated.candidate); + else if (evaluated.outcome === "invalid-topology") firstInvalidTopology ??= evaluated.message; + } + if (firstInvalidTopology) { return { outcome: "rejected", code: "invalid-topology", - message: "Topology qualification is not immutable JSON data.", + message: firstInvalidTopology, }; } - const expectedNodeIds = input.readinessReports.map(({ nodeId }) => nodeId).sort(); - const invalidTopology = getDualSparkTopologyArtifactError(topology, expectedNodeIds); - if (invalidTopology) { - return { outcome: "rejected", code: "invalid-topology", message: invalidTopology }; + if (matching.length === 0) { + return { + outcome: "no-match", + code: "requirements-not-met", + message: "No automatic managed inference preset matched.", + }; } - const unmetRequirement = requirementsError(preset, input.readinessReports, topology); - if (unmetRequirement) return rejectOrSkip(explicit, unmetRequirement); - - return { - outcome: "selected", - selection: explicit ? "explicit" : "automatic", - catalogDigest: catalog.catalogDigest, - preset, - recipe, - topologyQualification: topology as ManagedInferenceTopologyQualification, - }; + matching.sort( + (left, right) => + right.priority - left.priority || + compareStrings(left.preset.metadata.id, right.preset.metadata.id), + ); + const highestPriority = matching[0]!.priority; + const tied = matching.filter(({ priority }) => priority === highestPriority); + if (tied.length !== 1) { + return { + outcome: "rejected", + code: "ambiguous-selection", + message: `Automatic managed inference selection is ambiguous at priority ${String( + highestPriority, + )}: ${tied.map(({ preset }) => preset.metadata.id).join(", ")}.`, + }; + } + return selectedResolution(catalog, tied[0]!, "automatic"); } diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts index 368b6529d99..5c9888bd380 100644 --- a/src/lib/inference/serving/spark-runtime-receipt.ts +++ b/src/lib/inference/serving/spark-runtime-receipt.ts @@ -13,7 +13,6 @@ import { encodeDualStationSshBindingHandoff, loadDualStationSshBindingHandoff, } from "../vllm-station-ssh-binding"; -import { loadManagedInferenceCatalog } from "./catalog"; import { managedInferenceHexDigest } from "./catalog-integrity"; import { assertDualSparkVllmExecutorConfig, @@ -171,9 +170,6 @@ function assertExecutorContract( localCacheRoot: string, peerCacheRoot: string, ): void { - if (plan.catalogDigest !== loadManagedInferenceCatalog().catalogDigest) { - throw new Error("Dual-Spark runtime plan does not match the shipped catalog"); - } assertDualSparkVllmExecutorConfig({ plan, peerSshBinding, diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts index adbbb1ec685..6e0a093c369 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -6,7 +6,6 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadManagedInferenceCatalog } from "./serving/catalog"; import { fixtureDualSparkSelection } from "./serving/dual-spark-fixture.test-support"; import { type DualSparkNodeSnapshot, @@ -58,7 +57,6 @@ afterEach(() => { function plan(): DualSparkVllmPlan { const selection = fixtureDualSparkSelection(); - const catalog = loadManagedInferenceCatalog(); const sourceTopology = selection.topologyQualification; const output = { ...sourceTopology.output, @@ -69,9 +67,6 @@ function plan(): DualSparkVllmPlan { }; return materializeDualSparkVllmPlan({ ...selection, - catalogDigest: catalog.catalogDigest, - preset: catalog.presets[0]!.definition, - recipe: catalog.recipes[0]!.definition, topologyQualification: { ...sourceTopology, outputDigest: dualSparkTopologyOutputDigest(output), @@ -181,6 +176,25 @@ describe("dual-Spark vLLM runtime receipt", () => { expect(fs.readFileSync(receiptPath, "utf8")).toBe(original); }); + it("keeps a selected profile receipt valid when unrelated catalog entries change", () => { + const source = input(); + const previousCatalogPlan = { + ...source.plan, + catalogDigest: `sha256:${"e".repeat(64)}`, + }; + + const runtime = persistDualSparkVllmRuntimeReceipt( + { ...source, plan: previousCatalogPlan }, + { stateDir }, + ); + const loaded = loadDualSparkVllmRuntimeReceipt({ stateDir }); + + expect(loaded?.plan.catalogDigest).toBe(previousCatalogPlan.catalogDigest); + expect(loaded?.plan.planId).toBe(previousCatalogPlan.planId); + expect(runtime.plan.presetDigest).toBe(source.plan.presetDigest); + expect(runtime.plan.recipeDigest).toBe(source.plan.recipeDigest); + }); + it("refuses a pre-existing SSH binding tree without mutating it", () => { fs.mkdirSync(stateDir, { mode: 0o700 }); const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); @@ -210,7 +224,9 @@ describe("dual-Spark vLLM runtime receipt", () => { const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf8")); receipt.plan.model.id = "foreign/model"; - fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { mode: 0o600 }); + fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { + mode: 0o600, + }); expect(() => loadDualSparkVllmRuntimeReceipt({ stateDir })).toThrow("plan digest changed"); }); @@ -268,7 +284,10 @@ describe("dual-Spark vLLM runtime receipt", () => { loadApiKey: () => API_KEY, createLifecycleDeps: () => deps, }), - ).resolves.toEqual({ kind: "removed", removedContainerIds: [HEAD_ID, WORKER_ID] }); + ).resolves.toEqual({ + kind: "removed", + removedContainerIds: [HEAD_ID, WORKER_ID], + }); expect(removeContainer).toHaveBeenNthCalledWith(1, runtime.plan.roles.head, HEAD_ID); expect(removeContainer).toHaveBeenNthCalledWith(2, runtime.plan.roles.worker, WORKER_ID); expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); @@ -283,14 +302,23 @@ describe("dual-Spark vLLM runtime receipt", () => { }; let workerAttempts = 0; const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { - if (rolePlan.role === "worker" && workerAttempts++ === 0) { - return { ok: false as const, reason: "worker daemon unavailable" }; - } - snapshots[rolePlan.role] = { - ...snapshots[rolePlan.role], - containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), + const shouldFailWorker = rolePlan.role === "worker" && workerAttempts === 0; + workerAttempts += Number(rolePlan.role === "worker"); + const removeOwnedContainer = () => { + snapshots[rolePlan.role] = { + ...snapshots[rolePlan.role], + containers: snapshots[rolePlan.role].containers.filter( + (container) => container.id !== id, + ), + }; + return { ok: true as const }; }; - return { ok: true as const }; + return shouldFailWorker + ? ({ + ok: false as const, + reason: "worker daemon unavailable", + } as const) + : removeOwnedContainer(); }); const deps = { inspectNode: async (rolePlan: DualSparkVllmRolePlan) => snapshots[rolePlan.role], diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index 4383526b43e..200fc83284c 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -4,101 +4,483 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; - import { describe, expect, it } from "vitest"; +import { parse, stringify } from "yaml"; import { compileManagedInferenceCatalogSources, type ManagedInferenceCatalogSource, } from "../scripts/managed-inference/compile-catalog.mts"; +import type { SystemReadinessReport } from "../src/lib/readiness/types.js"; +import type { + ManagedInferenceReadinessSource, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ResolvedManagedInferenceSelection, +} from "../src/lib/inference/serving/catalog-types.js"; +import { fixtureDualSparkSelection } from "../src/lib/inference/serving/dual-spark-fixture.test-support.js"; +import { materializeDualSparkVllmPlan } from "../src/lib/inference/serving/dual-spark-materialize.js"; +import type { DualSparkTopologyOutput } from "../src/lib/inference/serving/dual-spark-topology.js"; +import { resolveManagedInferenceServing } from "../src/lib/inference/serving/resolver.js"; const REPOSITORY_ROOT = fileURLToPath(new URL("..", import.meta.url)); -const PRESET_PATH = - "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml"; -const RECIPE_PATH = "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml"; -function source(sourcePath: string): ManagedInferenceCatalogSource { - return { - path: sourcePath, - contents: fs.readFileSync(path.join(REPOSITORY_ROOT, sourcePath), "utf8"), - }; -} +const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; function catalogSources(): ManagedInferenceCatalogSource[] { - return [source(PRESET_PATH), source(RECIPE_PATH)]; + return SOURCE_DIRECTORIES.flatMap((directory) => + fs + .readdirSync(path.join(REPOSITORY_ROOT, directory), { + withFileTypes: true, + }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".yaml")) + .map((entry) => { + const sourcePath = `${directory}/${entry.name}`; + return { + path: sourcePath, + contents: fs.readFileSync(path.join(REPOSITORY_ROOT, sourcePath), "utf8"), + }; + }), + ); } -function replaceSource( +function replaceDefinition( sources: readonly ManagedInferenceCatalogSource[], - sourcePath: string, - replace: (contents: string) => string, + kind: "ServingPreset" | "ServingRecipe", + replace: (definition: TDefinition) => TDefinition, ): ManagedInferenceCatalogSource[] { - return sources.map((item) => - item.path === sourcePath ? { ...item, contents: replace(item.contents) } : item, + const replacementIndex = sources.findIndex( + (source) => (parse(source.contents) as { readonly kind?: unknown }).kind === kind, ); + expect(replacementIndex).toBeGreaterThanOrEqual(0); + return sources.map((source, index) => + index === replacementIndex + ? { + ...source, + contents: stringify(replace(parse(source.contents) as TDefinition)), + } + : source, + ); +} + +function syntheticProfileSources( + sources: readonly ManagedInferenceCatalogSource[], +): ManagedInferenceCatalogSource[] { + const compiled = compileManagedInferenceCatalogSources(sources).catalog; + const sourceRecipe = compiled.recipes[0]?.definition; + const sourcePreset = compiled.presets.find( + ({ definition }) => definition.spec.plan.recipeRef === sourceRecipe?.metadata.id, + )?.definition; + expect(sourceRecipe).toBeDefined(); + expect(sourcePreset).toBeDefined(); + const recipeTemplate = sourceRecipe as ManagedInferenceServingRecipe; + const presetTemplate = sourcePreset as ManagedInferenceServingPreset; + + const recipe: ManagedInferenceServingRecipe = { + ...recipeTemplate, + metadata: { + id: "vllm.synthetic-model.generic-topology.v1", + displayName: "Synthetic model on a registered topology", + }, + spec: { + ...recipeTemplate.spec, + model: { + ...recipeTemplate.spec.model, + id: "example/Synthetic-Model", + revision: "1111111111111111111111111111111111111111", + servedName: "synthetic-model", + downloadSizeBytes: 12_345_678_901, + preparation: { ref: "none/v1" }, + }, + runtime: { + ...recipeTemplate.spec.runtime, + image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, + imageDownloadSizeBytes: 2_345_678_901, + sharedMemoryBytes: 34_359_738_368, + modelCache: { + ...recipeTemplate.spec.runtime.modelCache, + target: "/models/synthetic-cache", + }, + temporaryFilesystems: recipeTemplate.spec.runtime.temporaryFilesystems.map((filesystem) => + filesystem.target === recipeTemplate.spec.runtime.modelCache.target + ? { ...filesystem, target: "/models/synthetic-cache", sizeBytes: 8_589_934_592 } + : filesystem, + ), + environment: { + ...recipeTemplate.spec.runtime.environment, + FLASHINFER_WORKSPACE_BASE: "/models/synthetic-cache/flashinfer", + VLLM_CACHE_ROOT: "/models/synthetic-cache/vllm-cache", + SYNTHETIC_PROFILE: "enabled", + }, + }, + serve: { + ...recipeTemplate.spec.serve, + executable: "/opt/vllm/bin/vllm", + arguments: recipeTemplate.spec.serve.arguments.map((argument) => + argument.name === "--port" + ? { ...argument, value: 8_101 } + : argument.name === "--max-model-len" + ? { ...argument, value: 131_072 } + : argument, + ), + }, + readiness: { + ...sourceRecipe.spec.readiness, + timeoutSeconds: 900, + expectedModel: "synthetic-model", + }, + }, + }; + const preset: ManagedInferenceServingPreset = { + ...presetTemplate, + metadata: { + id: "vllm.synthetic-model.generic-topology", + displayName: "Synthetic model on a registered topology", + }, + spec: { + ...presetTemplate.spec, + priority: presetTemplate.spec.priority + 1, + plan: { ...presetTemplate.spec.plan, recipeRef: recipe.metadata.id }, + }, + }; + return [ + ...sources, + { + path: "managed-inference/recipes/vllm.synthetic-model.generic-topology.v1.yaml", + contents: stringify(recipe), + }, + { + path: "managed-inference/presets/vllm.synthetic-model.generic-topology.yaml", + contents: stringify(preset), + }, + ]; +} + +function matchingReadinessSources( + preset: ManagedInferenceServingPreset, +): ManagedInferenceReadinessSource[] { + const requirements = preset.spec.requirements.all.flatMap((requirement) => + "readiness" in requirement ? [requirement.readiness] : [], + ); + const report: SystemReadinessReport = { + schemaVersion: "1.1.0", + mutated: false, + provenance: { + nemoclawVersion: "0.1.0", + sourceRevision: "a".repeat(40), + observedAt: "2026-08-03T12:00:00.000Z", + }, + observations: requirements.flatMap((requirement) => + requirement.kind === "observation" + ? [ + { + id: requirement.id, + state: requirement.state as SystemReadinessReport["observations"][number]["state"], + }, + ] + : [], + ), + capabilities: requirements.flatMap((requirement) => + requirement.kind === "capability" + ? [ + { + id: requirement.id, + state: requirement.state as SystemReadinessReport["capabilities"][number]["state"], + }, + ] + : [], + ), + qualifications: requirements.flatMap((requirement) => + requirement.kind === "qualification" + ? [ + { + id: requirement.id, + status: + requirement.status as SystemReadinessReport["qualifications"][number]["status"], + }, + ] + : [], + ), + findings: [], + evidence: [], + status: "supported", + exitCode: 0, + }; + return ["spark-head", "spark-worker"].map((nodeId) => ({ + nodeId, + report: structuredClone(report), + })); } describe("managed inference catalog compiler", () => { it("produces identical canonical JSON regardless of source enumeration order", () => { const sources = catalogSources(); - expect(compileManagedInferenceCatalogSources(sources).json).toBe( - compileManagedInferenceCatalogSources(sources.reverse()).json, + compileManagedInferenceCatalogSources([...sources].reverse()).json, ); }); - it("rejects an unknown recipe field", () => { - const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => - contents.replace(" backend: vllm", " backend: vllm\n unsupportedField: true"), + it("compiles a synthetic second YAML-only profile without schema or TypeScript changes", () => { + const compiled = compileManagedInferenceCatalogSources( + syntheticProfileSources(catalogSources()), ); + expect(compiled.catalog.presets).toHaveLength(2); + expect(compiled.catalog.recipes).toHaveLength(2); + expect(compiled.catalog.presets.map(({ definition }) => definition.metadata.id)).toContain( + "vllm.synthetic-model.generic-topology", + ); + expect(compiled.catalog.recipes.map(({ definition }) => definition.metadata.id)).toContain( + "vllm.synthetic-model.generic-topology.v1", + ); + }); + it("resolves and materializes the second YAML-only profile without profile-specific code", () => { + const catalog = compileManagedInferenceCatalogSources( + syntheticProfileSources(catalogSources()), + ).catalog; + const preset = catalog.presets.find( + ({ definition }) => definition.metadata.id === "vllm.synthetic-model.generic-topology", + )?.definition; + expect(preset).toBeDefined(); + const topologyQualification = fixtureDualSparkSelection().topologyQualification; + const resolution = resolveManagedInferenceServing( + { + readinessReports: matchingReadinessSources(preset as ManagedInferenceServingPreset), + topologyQualifications: [topologyQualification], + now: new Date("2026-08-03T12:00:10.000Z"), + }, + catalog, + ); + expect(resolution).toMatchObject({ + outcome: "selected", + selection: "automatic", + preset: { metadata: { id: "vllm.synthetic-model.generic-topology" } }, + recipe: { metadata: { id: "vllm.synthetic-model.generic-topology.v1" } }, + }); + const plan = materializeDualSparkVllmPlan( + resolution as ResolvedManagedInferenceSelection, + { catalog }, + ); + const revisionIndex = plan.roles.head.command.arguments.indexOf("--revision"); + + expect(plan).toMatchObject({ + model: { + id: "example/Synthetic-Model", + revision: "1111111111111111111111111111111111111111", + servedName: "synthetic-model", + }, + apiPort: 8_101, + readiness: { timeoutMs: 900_000, expectedModel: "synthetic-model" }, + roles: { + head: { + image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, + runtime: { + sharedMemoryBytes: 34_359_738_368, + imageDownloadSizeBytes: 2_345_678_901, + modelCache: { source: "huggingface-cache", target: "/models/synthetic-cache" }, + }, + preparation: { + ref: "none/v1", + modelDownloadSizeBytes: 12_345_678_901, + }, + environment: { + HF_HOME: "/models/synthetic-cache", + SYNTHETIC_PROFILE: "enabled", + }, + command: { executable: "/opt/vllm/bin/vllm" }, + }, + }, + }); + expect(plan.roles.head.command.arguments[revisionIndex + 1]).toBe( + "1111111111111111111111111111111111111111", + ); + expect(plan.roles.head.command.arguments).toEqual( + expect.arrayContaining(["--port", "8101", "--max-model-len", "131072"]), + ); + }); + + it("rejects duplicate definition IDs across YAML files", () => { + const sources = catalogSources(); + const recipeSource = sources.find((source) => source.path.includes("/recipes/")); + expect(recipeSource).toBeDefined(); + expect(() => + compileManagedInferenceCatalogSources([ + ...sources, + { + ...(recipeSource as ManagedInferenceCatalogSource), + path: "managed-inference/recipes/duplicate.yaml", + }, + ]), + ).toThrow(/definition ID .* duplicated/u); + }); + + it("rejects an unknown recipe field", () => { + const sources = replaceDefinition( + catalogSources(), + "ServingRecipe", + (recipe) => ({ + ...recipe, + spec: { ...recipe.spec, unsupportedField: true }, + }), + ); expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/additional properties/u); }); it("rejects a mutable runtime image reference", () => { - const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => - contents.replace( - /ghcr\.io\/anemll\/dspark-vllm-gx10@sha256:[0-9a-f]{64}/u, - "ghcr.io/anemll/dspark-vllm-gx10:0.1.1", - ), + const sources = replaceDefinition( + catalogSources(), + "ServingRecipe", + (recipe) => ({ + ...recipe, + spec: { + ...recipe.spec, + runtime: { + ...recipe.spec.runtime, + image: "registry.example.test/runtime:latest", + }, + }, + }), ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/schema validation/u); }); - it("requires a new recipe ID for any material contract change", () => { - const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => - contents.replace(" NCCL_DEBUG: WARN", " NCCL_DEBUG: INFO"), - ); - - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( - /contract changed without a new recipe ID/u, + it("derives a new definition digest when YAML profile data changes", () => { + const sources = catalogSources(); + const before = compileManagedInferenceCatalogSources(sources).catalog.recipes[0]; + const changed = replaceDefinition( + sources, + "ServingRecipe", + (recipe) => ({ + ...recipe, + spec: { + ...recipe.spec, + runtime: { + ...recipe.spec.runtime, + environment: { + ...recipe.spec.runtime.environment, + SYNTHETIC_SETTING: "enabled", + }, + }, + }, + }), ); + const after = compileManagedInferenceCatalogSources(changed).catalog.recipes[0]; + expect(after?.definitionDigest).not.toBe(before?.definitionDigest); }); it.each([ "--node-rank", "--headless", "--host", + "--revision", ])("rejects materializer-owned serving argument %s", (argument) => { - const sources = replaceSource(catalogSources(), RECIPE_PATH, (contents) => - contents.replace(" - name: --port", ` - name: ${argument}\n - name: --port`), + const sources = replaceDefinition( + catalogSources(), + "ServingRecipe", + (recipe) => ({ + ...recipe, + spec: { + ...recipe.spec, + serve: { + ...recipe.spec.serve, + arguments: [{ name: argument }, ...recipe.spec.serve.arguments], + }, + }, + }), ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( new RegExp(`materializer-owned argument ${argument}`), ); }); it("rejects an unresolved preset recipe reference", () => { - const sources = replaceSource(catalogSources(), PRESET_PATH, (contents) => - contents.replace( - "recipeRef: vllm.deepseek-v4-flash-0731.spark-dual.v1", - "recipeRef: vllm.missing.recipe", - ), + const sources = replaceDefinition( + catalogSources(), + "ServingPreset", + (preset) => ({ + ...preset, + spec: { + ...preset.spec, + plan: { ...preset.spec.plan, recipeRef: "vllm.missing.recipe" }, + }, + }), ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( /references unknown recipe/u, ); }); + + it("rejects an unsupported selection fact even when it requests absence", () => { + const sources = replaceDefinition( + catalogSources(), + "ServingPreset", + (preset) => ({ + ...preset, + spec: { + ...preset.spec, + requirements: { + all: [ + ...preset.spec.requirements.all, + { + fact: "cluster.unknown", + state: "absent", + operator: "equals", + value: true, + }, + ], + }, + }, + }), + ); + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( + /unsupported selection fact/u, + ); + }); + + it("rejects a preset topology output not declared by the registered adapter", () => { + const sources = replaceDefinition( + catalogSources(), + "ServingPreset", + (preset) => ({ + ...preset, + spec: { + ...preset.spec, + plan: { + ...preset.spec.plan, + bindings: Object.fromEntries( + Object.entries(preset.spec.plan.bindings).map(([name, binding]) => [ + name, + { + valueFromTopologyQualification: { + ...binding.valueFromTopologyQualification, + output: "unsupported-output", + }, + }, + ]), + ), + }, + }, + }), + ); + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( + /binding .* does not match its recipe/u, + ); + }); + + it("rejects a recipe whose adapter reference is not registered", () => { + const sources = replaceDefinition( + catalogSources(), + "ServingRecipe", + (recipe) => ({ + ...recipe, + spec: { + ...recipe.spec, + execution: { + ...recipe.spec.execution, + materializerRef: "vllm.missing-adapter/v1", + }, + }, + }), + ); + expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/unknown materializer/u); + }); }); From 1365605dcdcf5377358c566ad0e6a68859a26893 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 08:10:50 -0700 Subject: [PATCH 03/27] fix(inference): harden Spark binding claim Signed-off-by: Aaron Erickson --- .../dual-spark-discovery-production.ts | 55 ++++++++++--------- .../serving/dual-spark-discovery.test.ts | 21 +++++++ 2 files changed, 50 insertions(+), 26 deletions(-) diff --git a/src/lib/inference/serving/dual-spark-discovery-production.ts b/src/lib/inference/serving/dual-spark-discovery-production.ts index 947603b2bad..158c34c90e7 100644 --- a/src/lib/inference/serving/dual-spark-discovery-production.ts +++ b/src/lib/inference/serving/dual-spark-discovery-production.ts @@ -1112,38 +1112,41 @@ function claimBinding(statePath: string): boolean { const parent = path.dirname(bindingDirectory); const uid = process.getuid?.(); if (uid === undefined) throw new Error("DGX Spark binding claim requires a POSIX user identity"); - const parentMetadata = fs.lstatSync(parent); - if ( - parentMetadata.isSymbolicLink() || - !parentMetadata.isDirectory() || - parentMetadata.uid !== uid || - (parentMetadata.mode & 0o777) !== 0o700 - ) { - throw new Error("DGX Spark binding parent is unsafe"); - } - try { - fs.mkdirSync(bindingDirectory, { mode: 0o700 }); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "EEXIST") return false; - throw error; - } + const directoryFlags = fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW; + const parentDescriptor = fs.openSync(parent, directoryFlags); try { - fs.chmodSync(bindingDirectory, 0o700); - const descriptor = fs.openSync(parent, fs.constants.O_RDONLY); + const parentMetadata = fs.fstatSync(parentDescriptor); + if ( + !parentMetadata.isDirectory() || + parentMetadata.uid !== uid || + (parentMetadata.mode & 0o777) !== 0o700 + ) { + throw new Error("DGX Spark binding parent is unsafe"); + } try { - fs.fsyncSync(descriptor); - } finally { - fs.closeSync(descriptor); + fs.mkdirSync(bindingDirectory, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") return false; + throw error; } - } catch (error) { + + const bindingDescriptor = fs.openSync(bindingDirectory, directoryFlags); try { - fs.rmdirSync(bindingDirectory); - } catch { - // Retain the exclusive claim if its safe cleanup cannot be completed. + const bindingMetadata = fs.fstatSync(bindingDescriptor); + if (!bindingMetadata.isDirectory() || bindingMetadata.uid !== uid) { + throw new Error("DGX Spark binding claim is unsafe"); + } + fs.fchmodSync(bindingDescriptor, 0o700); + fs.fsyncSync(bindingDescriptor); + } finally { + fs.closeSync(bindingDescriptor); } - throw error; + + fs.fsyncSync(parentDescriptor); + return true; + } finally { + fs.closeSync(parentDescriptor); } - return true; } /** diff --git a/src/lib/inference/serving/dual-spark-discovery.test.ts b/src/lib/inference/serving/dual-spark-discovery.test.ts index 0589093779b..503dea136c6 100644 --- a/src/lib/inference/serving/dual-spark-discovery.test.ts +++ b/src/lib/inference/serving/dual-spark-discovery.test.ts @@ -710,6 +710,27 @@ describe("production pinned peer transport", () => { } }); + it("rejects a symlinked binding parent before creating a claim", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-spark-binding-link-")); + const parent = path.join(root, "parent"); + const alias = path.join(root, "alias"); + fs.mkdirSync(parent, { mode: 0o700 }); + fs.symlinkSync(parent, alias, "dir"); + const statePath = path.join(alias, "dual-spark.json"); + const deps = createDualSparkDiscoveryDeps(() => ({ + status: 0, + stdout: "", + stderr: "", + })); + + try { + expect(() => deps.claimBinding(statePath)).toThrow(); + expect(fs.existsSync(`${path.join(parent, "dual-spark.json")}.ssh-binding`)).toBe(false); + } finally { + fs.rmSync(root, { force: true, recursive: true }); + } + }); + it("pins local and remote host probes to the physical default Docker daemon", () => { const calls: Array<{ file: string; From 8c9a9ec7a8718b4f07f12d9f6705f3e68fd24c8d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 08:55:55 -0700 Subject: [PATCH 04/27] fix(inference): retire Spark discovery claims on uninstall Signed-off-by: Aaron Erickson --- .../uninstall/run-plan-dual-station.test.ts | 92 +++++++++++++++++++ src/lib/actions/uninstall/run-plan.ts | 5 + .../serving/dual-spark-installer.test.ts | 37 ++++++++ .../serving/spark-runtime-receipt.ts | 6 +- .../vllm-spark-runtime-receipt.test.ts | 57 ++++++++++++ 5 files changed, 196 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index 20ed99298fc..81d433f1807 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -82,6 +82,98 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); + it("associates the canonical leftover Spark discovery binding with its durable receipt", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-")); + const stateDir = path.join(home, ".nemoclaw"); + const receiptPath = path.join(stateDir, "dual-spark-vllm-runtime.json"); + const discoveryBindingPath = path.join(stateDir, "dual-spark-managed-serving.json.ssh-binding"); + fs.mkdirSync(stateDir, { mode: 0o700 }); + fs.writeFileSync(receiptPath, "{}\n", { mode: 0o600 }); + fs.mkdirSync(`${receiptPath}.ssh-binding`, { mode: 0o700 }); + fs.mkdirSync(discoveryBindingPath, { mode: 0o700 }); + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync: vi.fn(), + run: okWithKnownGatewayList, + runDocker: () => ok(), + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(0); + expect(runDualStationRuntimeCleanup).toHaveBeenCalledWith( + receiptPath, + expect.objectContaining({ stdio: "inherit" }), + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + it.each([ + { + title: "a noncanonical gateway Spark claim despite a host-global Spark receipt", + receiptFile: "dual-spark-vllm-runtime.json", + bindingSegments: ["gateways", "18080", "dual-spark-managed-serving.json.ssh-binding"], + }, + { + title: "a canonical Spark claim when only a Station receipt exists", + receiptFile: "dual-station-vllm-runtime.json", + bindingSegments: ["dual-spark-managed-serving.json.ssh-binding"], + }, + ])("refuses $title", ({ receiptFile, bindingSegments }) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-other-")); + const stateDir = path.join(home, ".nemoclaw"); + const receiptPath = path.join(stateDir, receiptFile); + const discoveryBindingPath = path.join(stateDir, ...bindingSegments); + fs.mkdirSync(stateDir, { mode: 0o700 }); + fs.writeFileSync(receiptPath, "{}\n", { mode: 0o600 }); + fs.mkdirSync(`${receiptPath}.ssh-binding`, { mode: 0o700 }); + fs.mkdirSync(discoveryBindingPath, { recursive: true, mode: 0o700 }); + const errors: string[] = []; + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + const rmSync = vi.fn(); + const runDocker = vi.fn(() => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + error: (message) => errors.push(message), + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync, + run: okWithKnownGatewayList, + runDocker, + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(1); + expect(runDualStationRuntimeCleanup).not.toHaveBeenCalled(); + expect(runDocker).not.toHaveBeenCalled(); + expect(rmSync).not.toHaveBeenCalled(); + expect(errors.join("\n")).toContain( + "Managed distributed vLLM SSH binding exists without its ownership receipt", + ); + expect(fs.existsSync(discoveryBindingPath)).toBe(true); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + it("targets the exact Station receipt found under a stale non-default gateway root", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-stale-station-")); const receiptPath = path.join( diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index d812427f433..3bc2e74bbec 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -1264,6 +1264,11 @@ function removeManagedDistributedVllmRuntime( ...state.stationBindingPaths, ]; const expectedBindingPaths = new Set(receipts.map((receiptPath) => `${receiptPath}.ssh-binding`)); + if (state.sparkPath) { + expectedBindingPaths.add( + `${path.join(path.dirname(state.sparkPath), DUAL_SPARK_MANAGED_SERVING_STATE_FILE)}.ssh-binding`, + ); + } const orphanBinding = bindingPaths.find((bindingPath) => !expectedBindingPaths.has(bindingPath)); if (orphanBinding) { runtime.error( diff --git a/src/lib/inference/serving/dual-spark-installer.test.ts b/src/lib/inference/serving/dual-spark-installer.test.ts index 1923892f81e..1413c8f2638 100644 --- a/src/lib/inference/serving/dual-spark-installer.test.ts +++ b/src/lib/inference/serving/dual-spark-installer.test.ts @@ -552,6 +552,43 @@ describe("two-Spark managed vLLM installer selection", () => { expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); }); + it("keeps a successful receipt-owned install when temporary binding retirement fails", async () => { + const capability = readyCapability(); + const persistReceipt = vi.fn(); + const clearBinding = vi.fn(() => { + throw new Error("temporary binding busy"); + }); + const warn = vi.fn(); + + const result = await tryInstallDualSparkManagedVllm( + { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, + effects(), + { + probeCapability: () => capability, + revalidateCapability: () => capability, + claimCapability: () => confirmedCapability(capability), + resolveSelection: () => fixtureDualSparkSelection(), + createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + start: async () => successfulStart(), + ensureApiKey: () => API_KEY, + persistReceipt, + clearBinding, + log: vi.fn(), + warn, + }, + ); + + expect(result).toEqual({ kind: "handled", result: { ok: true } }); + expect(persistReceipt).toHaveBeenCalledOnce(); + expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + expect(persistReceipt.mock.invocationCallOrder[0]).toBeLessThan( + clearBinding.mock.invocationCallOrder[0]!, + ); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("temporary two-Spark SSH state could not be retired"), + ); + }); + it("cleans only a newly-created exact pair when receipt persistence fails", async () => { const capability = readyCapability(); const selection = fixtureDualSparkSelection(); diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts index 5c9888bd380..c50db070916 100644 --- a/src/lib/inference/serving/spark-runtime-receipt.ts +++ b/src/lib/inference/serving/spark-runtime-receipt.ts @@ -27,7 +27,10 @@ import { dualSparkVllmApiKeyFingerprint, } from "./dual-spark-lifecycle"; import type { DualSparkVllmPlan } from "./dual-spark-materialize"; -import { DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE } from "./spark-runtime-receipt-path"; +import { + DUAL_SPARK_MANAGED_SERVING_STATE_FILE, + DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, +} from "./spark-runtime-receipt-path"; const MAX_RECEIPT_BYTES = 128 * 1024; const SHA256 = /^[a-f0-9]{64}$/; @@ -514,6 +517,7 @@ export async function cleanupInstalledDualSparkVllmRuntime( ) { throw new Error("Managed dual-Spark cleanup returned unexpected container identities"); } + clearDualStationSshBinding(path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)); clearReceipt(stateDir); return { kind: "removed", removedContainerIds: cleanup.removedContainerIds }; } diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts index 6e0a093c369..1b3d948a847 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -28,6 +28,8 @@ import { persistDualSparkVllmRuntimeReceipt, recoverInstalledDualSparkVllmEndpoint, } from "./serving/spark-runtime-receipt"; +import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./serving/spark-runtime-receipt-path"; +import { copyDualStationSshBinding } from "./vllm-station-ssh-binding"; import { createDualStationSshBindingFixture, type DualStationSshBindingFixture, @@ -277,6 +279,8 @@ describe("dual-Spark vLLM runtime receipt", () => { it("removes only both exact receipt-owned containers before retiring state", async () => { const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); + copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); const { deps, removeContainer } = cleanupDeps(runtime.plan); await expect( cleanupInstalledDualSparkVllmRuntime({ @@ -290,12 +294,63 @@ describe("dual-Spark vLLM runtime receipt", () => { }); expect(removeContainer).toHaveBeenNthCalledWith(1, runtime.plan.roles.head, HEAD_ID); expect(removeContainer).toHaveBeenNthCalledWith(2, runtime.plan.roles.worker, WORKER_ID); + expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(false); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); + expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); + }); + + it("retains durable ownership when a leftover discovery binding is unsafe to retire", async () => { + const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const discoveryBindingPath = `${path.join( + stateDir, + DUAL_SPARK_MANAGED_SERVING_STATE_FILE, + )}.ssh-binding`; + fs.mkdirSync(discoveryBindingPath, { mode: 0o755 }); + fs.chmodSync(discoveryBindingPath, 0o755); + const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { + head: snapshot(runtime.plan.roles.head, HEAD_ID), + worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + }; + const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + snapshots[rolePlan.role] = { + ...snapshots[rolePlan.role], + containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), + }; + return { ok: true as const }; + }); + const options = { + stateDir, + loadApiKey: () => API_KEY, + createLifecycleDeps: () => ({ + inspectNode: async (rolePlan: DualSparkVllmRolePlan) => snapshots[rolePlan.role], + removeContainer, + withLifecycleLock: async (_plan: DualSparkVllmPlan, operation: () => Promise) => + await operation(), + }), + }; + + await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow("unsafe to remove"); + + expect(removeContainer).toHaveBeenCalledTimes(2); + expect(fs.existsSync(discoveryBindingPath)).toBe(true); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + + fs.chmodSync(discoveryBindingPath, 0o700); + await expect(cleanupInstalledDualSparkVllmRuntime(options)).resolves.toEqual({ + kind: "removed", + removedContainerIds: [], + }); + expect(removeContainer).toHaveBeenCalledTimes(2); + expect(fs.existsSync(discoveryBindingPath)).toBe(false); expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); }); it("retains the receipt and resumes after one exact container removal fails", async () => { const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); + copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { head: snapshot(runtime.plan.roles.head, HEAD_ID), worker: snapshot(runtime.plan.roles.worker, WORKER_ID), @@ -335,6 +390,7 @@ describe("dual-Spark vLLM runtime receipt", () => { await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow( "worker daemon unavailable", ); + expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(true); expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); await expect(cleanupInstalledDualSparkVllmRuntime(options)).resolves.toEqual({ kind: "removed", @@ -345,6 +401,7 @@ describe("dual-Spark vLLM runtime receipt", () => { WORKER_ID, WORKER_ID, ]); + expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(false); expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); }); From ff7c59bcb2df21bb3558ae010960a004ad93f6db Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 09:00:22 -0700 Subject: [PATCH 05/27] docs(inference): clarify Spark claim cleanup Signed-off-by: Aaron Erickson --- docs/inference/set-up-vllm-on-two-dgx-sparks.mdx | 4 ++-- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 3 ++- docs/reference/host-files-and-state.mdx | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx index 148492b470e..84a824bf8a8 100644 --- a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -222,8 +222,8 @@ Run a full uninstall to remove the exact receipt-owned pair. $$nemoclaw uninstall ``` -Full uninstall revalidates both exact container IDs before it removes them and retires the receipt and copied SSH binding. -If revalidation or removal fails, uninstall stops before other cleanup and preserves the receipt for a retry. +Full uninstall revalidates both exact container IDs before it removes them and retires the receipt, copied SSH binding, and any leftover temporary discovery claim associated with that receipt. +If revalidation, removal, or safe claim retirement fails, uninstall stops before other cleanup and preserves the receipt for a retry. A gateway-scoped uninstall preserves the host-global pair, receipt, SSH binding, and API key while another gateway remains. Pair cleanup does not delete the Hugging Face model cache. diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 547c080763e..1a7e8644e50 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -44,9 +44,10 @@ During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first r It then removes only both exact receipt-owned containers. The dual-DGX Spark receipt is host-global under `~/.nemoclaw/`, while a dual-DGX Station receipt uses the selected gateway state root. Only after that pair cleanup succeeds does NemoClaw start the remaining full-uninstall steps. +For a host-global dual-DGX Spark receipt, successful pair cleanup also retires any canonical temporary discovery claim associated with that receipt. If an interrupted dual-DGX Spark transaction leaves `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` without a durable runtime receipt, full uninstall fails closed before cleanup or other mutation and preserves the claim for explicit recovery or removal. This temporary claim is host-global regardless of the selected gateway. -If validation or pair cleanup fails, uninstall exits nonzero and keeps the receipt so you can resolve the reported SSH, Docker, or peer-host error and retry. +If validation, pair cleanup, or safe temporary-claim retirement fails, uninstall exits nonzero and keeps the receipt so you can resolve the reported SSH, Docker, peer-host, or claim error and retry. Pair cleanup can partially complete before an error, so inspect both systems before retrying. When sibling gateways remain, it removes only the selected gateway's resources and port-scoped state and preserves those shared host resources. This gateway-scoped path leaves a managed distributed pair running and preserves its cleanup receipt, copied SSH binding, any temporary dual-Spark discovery claim, and host-global API key. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index 874d526e185..c647a7c92c2 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -37,7 +37,7 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by NemoClaw-managed distributed vLLM profiles. | No while a managed distributed runtime exists. Full uninstall removes it only after managed runtime cleanup succeeds and no sibling gateway remains. | | `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, and container identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | | `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded DGX Spark worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds. | -| `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. Gateway-scoped uninstall preserves it. | +| `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. With the matching host-global dual-Spark receipt, full uninstall retires the claim after it removes both exact containers; if safe retirement fails, it preserves the receipt for a retry. Gateway-scoped uninstall preserves the claim. | | `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | From 4af798880fece2042057cbf79a0137e123e5244d Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 09:35:19 -0700 Subject: [PATCH 06/27] refactor(inference): make serving profiles YAML-only Signed-off-by: Aaron Erickson --- .gitignore | 1 + .pre-commit-config.yaml | 8 + .../set-up-vllm-on-two-dgx-sparks.mdx | 5 +- package.json | 14 +- scripts/managed-inference/compile-catalog.mts | 35 +- src/lib/inference/serving/catalog.ts | 2 +- .../inference/serving/generated/catalog.json | 368 ------------------ src/lib/inference/serving/resolver.test.ts | 74 +++- ...managed-inference-catalog-compiler.test.ts | 62 ++- 9 files changed, 143 insertions(+), 426 deletions(-) delete mode 100644 src/lib/inference/serving/generated/catalog.json diff --git a/.gitignore b/.gitignore index bb4d9305487..49c15e03c59 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ coverage/ dist/ docs/_build/ node_modules/ +src/lib/inference/serving/generated/catalog.ts # OS metadata .DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ab4ec7b9f1f..90119417586 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -167,6 +167,14 @@ repos: files: ^(nemoclaw-blueprint/.*\.yaml$|nemoclaw/openclaw\.plugin\.json$|schemas/.*\.json$) priority: 10 + - id: validate-managed-inference-catalog + name: Validate managed inference catalog + entry: npm run catalog:check + language: system + pass_filenames: false + files: ^(managed-inference/(?:presets|recipes)/.*\.yaml$|managed-inference/schemas/.*\.json$|scripts/managed-inference/compile-catalog\.mts$|src/lib/inference/serving/(?:adapter-registry|catalog-integrity|catalog-types)\.ts$) + priority: 10 + - id: repository-checks name: Repository checks entry: npm run checks:repository diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx index 84a824bf8a8..348247be7bc 100644 --- a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -164,7 +164,8 @@ The explicit target still must match the exact reciprocal rail topology. ## Understand the Distributed Runtime The compiled managed inference catalog reads profile selection, artifacts, runtime resources, serving arguments, preparation, and readiness checks from preset and recipe YAML. -Maintainers can add another profile that uses the registered dual-Spark topology, materializer, lifecycle, and preparation adapters by adding preset and recipe YAML without TypeScript changes. +Maintainers can add another profile that uses the registered dual-Spark topology, materializer, lifecycle, and preparation adapters by adding preset and recipe YAML without TypeScript changes or a committed generated artifact. +The build compiles those YAML definitions into the packaged runtime catalog automatically. A profile that needs a different execution contract requires a registered adapter. The compiled profile pins these artifacts: @@ -222,7 +223,7 @@ Run a full uninstall to remove the exact receipt-owned pair. $$nemoclaw uninstall ``` -Full uninstall revalidates both exact container IDs before it removes them and retires the receipt, copied SSH binding, and any leftover temporary discovery claim associated with that receipt. +Full uninstall revalidates both exact container IDs before it removes them and retires the receipt, copied SSH binding, and only the exact leftover temporary discovery claim recorded by that receipt. If revalidation, removal, or safe claim retirement fails, uninstall stops before other cleanup and preserves the receipt for a retry. A gateway-scoped uninstall preserves the host-global pair, receipt, SSH binding, and API key while another gateway remains. Pair cleanup does not delete the Hugging Face model cache. diff --git a/package.json b/package.json index 7f75f88f976..b2a8887ecd8 100644 --- a/package.json +++ b/package.json @@ -25,11 +25,11 @@ "agent": "pi", "test": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project cli --project integration --project installer-integration --project package-contract --project plugin --project e2e-support", "test:spec": "npm test -- --reporter=tree", - "test:fast": "npm run clean:cli && vitest run --project cli --project plugin --project e2e-support", - "test:changed": "vitest run --changed --project cli --project plugin --project e2e-support", - "test:watch": "vitest watch --project cli --project plugin --project e2e-support", - "test:shuffle": "vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", - "test:diagnose:leaks": "vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", + "test:fast": "npm run clean:cli && npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support", + "test:changed": "npm run catalog:compile && vitest run --changed --project cli --project plugin --project e2e-support", + "test:watch": "npm run catalog:compile && vitest watch --project cli --project plugin --project e2e-support", + "test:shuffle": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", + "test:diagnose:leaks": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", "test:e2e-phases:check": "npm run build:policy-boundary && node --experimental-strip-types --no-warnings tools/e2e/check-semantic-phases.mts", "test:runtime-audit": "tsx scripts/audit-test-runtime.mts", "test:integration": "npm run clean:cli && npm run build:cli && vitest run --project integration --project installer-integration", @@ -57,9 +57,9 @@ "build:policy-boundary": "tsc -p nemoclaw/tsconfig.shared.json", "catalog:compile": "tsx scripts/managed-inference/compile-catalog.mts --write", "catalog:check": "tsx scripts/managed-inference/compile-catalog.mts", - "build:cli": "npm run build:policy-boundary && tsc -p tsconfig.src.json && npm run catalog:check && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", + "build:cli": "npm run build:policy-boundary && npm run catalog:compile && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", "clean:cli": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", - "typecheck:cli": "tsc -p tsconfig.cli.json", + "typecheck:cli": "npm run catalog:compile && tsc -p tsconfig.cli.json", "validate:configs": "tsx scripts/validate-configs.mts", "type-safety:hotspots": "tsx scripts/type-safety-hotspots.mts", "source-shape:scan": "tsx scripts/find-source-shape-tests.mts --metrics", diff --git a/scripts/managed-inference/compile-catalog.mts b/scripts/managed-inference/compile-catalog.mts index fb833087c80..9ce479dee8f 100644 --- a/scripts/managed-inference/compile-catalog.mts +++ b/scripts/managed-inference/compile-catalog.mts @@ -46,7 +46,7 @@ const { const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; -const GENERATED_CATALOG_PATH = "src/lib/inference/serving/generated/catalog.json"; +const GENERATED_CATALOG_MODULE_PATH = "src/lib/inference/serving/generated/catalog.ts"; const RECIPE_SCHEMA_ID = recipeSchema.$id; const PRESET_SCHEMA_ID = presetSchema.$id; const SHA256 = /^sha256:[0-9a-f]{64}$/u; @@ -58,7 +58,24 @@ export interface ManagedInferenceCatalogSource { export interface CompiledManagedInferenceCatalogResult { readonly catalog: CompiledManagedInferenceCatalog; - readonly json: string; + readonly module: string; +} + +export function renderManagedInferenceCatalogModule( + catalog: CompiledManagedInferenceCatalog, +): string { + return `// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Generated by scripts/managed-inference/compile-catalog.mts from managed-inference YAML. +// Do not edit this file directly. + +import type { CompiledManagedInferenceCatalog } from "../catalog-types.js"; + +const generatedCatalog: CompiledManagedInferenceCatalog = ${JSON.stringify(catalog, null, 2)}; + +export default generatedCatalog; +`; } function compareStrings(left: string, right: string): number { @@ -360,7 +377,10 @@ export function compileManagedInferenceCatalogSources( if (!validateCatalog(catalog)) { throw validationError("compiled managed inference catalog", validateCatalog); } - return { catalog, json: `${JSON.stringify(catalog, null, 2)}\n` }; + return { + catalog, + module: renderManagedInferenceCatalogModule(catalog), + }; } function readCatalogSources(repositoryRoot: string): ManagedInferenceCatalogSource[] { @@ -388,15 +408,12 @@ export function compileManagedInferenceCatalog( function main(): void { const unknownArguments = process.argv.slice(2).filter((argument) => argument !== "--write"); if (unknownArguments.length > 0) throw new Error(`unknown argument ${unknownArguments[0]}`); - const { json } = compileManagedInferenceCatalog(); - const outputPath = path.join(REPOSITORY_ROOT, GENERATED_CATALOG_PATH); + const { module } = compileManagedInferenceCatalog(); if (process.argv.includes("--write")) { + const outputPath = path.join(REPOSITORY_ROOT, GENERATED_CATALOG_MODULE_PATH); fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - fs.writeFileSync(outputPath, json, "utf8"); - return; + fs.writeFileSync(outputPath, module, "utf8"); } - const current = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : ""; - if (current !== json) throw new Error(`${GENERATED_CATALOG_PATH} is stale; rerun with --write`); } if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) { diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts index 583a4ef110e..e91e755fe9d 100644 --- a/src/lib/inference/serving/catalog.ts +++ b/src/lib/inference/serving/catalog.ts @@ -13,7 +13,7 @@ import { type ManagedInferenceServingPreset, type ManagedInferenceServingRecipe, } from "./catalog-types.js"; -import generatedCatalog from "./generated/catalog.json"; +import generatedCatalog from "./generated/catalog.js"; const SHA256 = /^sha256:[0-9a-f]{64}$/u; const SOURCE_PATH = /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u; diff --git a/src/lib/inference/serving/generated/catalog.json b/src/lib/inference/serving/generated/catalog.json deleted file mode 100644 index 3cec1feeef5..00000000000 --- a/src/lib/inference/serving/generated/catalog.json +++ /dev/null @@ -1,368 +0,0 @@ -{ - "catalogDigest": "sha256:a38d1e4e861f412ddaaa603b1ae4c7521e10c3d4ec80f102eee950fb28acb4a8", - "compilerVersion": "1.0.0", - "presets": [ - { - "definition": { - "apiVersion": "nemoclaw.nvidia.com/managed-inference/v1", - "kind": "ServingPreset", - "metadata": { - "displayName": "DeepSeek V4 Flash 0731 on two DGX Sparks", - "id": "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731" - }, - "spec": { - "plan": { - "backend": "vllm", - "bindings": { - "sparkTopology": { - "valueFromTopologyQualification": { - "id": "dgx-spark.gb10.dual-cx7", - "output": "topology", - "schemaVersion": 1 - } - } - }, - "recipeRef": "vllm.deepseek-v4-flash-0731.spark-dual.v1" - }, - "priority": 400, - "requirements": { - "all": [ - { - "readiness": { - "id": "host.platform.dgx_spark", - "kind": "qualification", - "scope": "everyNode", - "status": "qualified" - } - }, - { - "readiness": { - "id": "host.platform.supported", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.platform.dgx_spark", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.docker.available", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.docker.daemon_reachable", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.docker.runtime_supported", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.docker.storage_compatible", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.gpu.nvidia_available", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.gpu.container_toolkit_available", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "readiness": { - "id": "host.gpu.cdi_healthy", - "kind": "capability", - "scope": "everyNode", - "state": "present" - } - }, - { - "fact": "cluster.nodeCount", - "operator": "equals", - "state": "present", - "value": 2 - }, - { - "topologyQualification": { - "id": "dgx-spark.gb10.dual-cx7", - "schemaVersion": 1, - "status": "qualified" - } - } - ] - }, - "selection": "automatic" - } - }, - "definitionDigest": "sha256:a49aa9a24b28b9b5b077d9b9e14f94cd38b328a45e6129704a1a7fb9def72262", - "sourceFile": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" - } - ], - "recipes": [ - { - "definition": { - "apiVersion": "nemoclaw.nvidia.com/managed-inference/v1", - "kind": "ServingRecipe", - "metadata": { - "displayName": "DeepSeek V4 Flash 0731 on two DGX Sparks", - "id": "vllm.deepseek-v4-flash-0731.spark-dual.v1" - }, - "spec": { - "backend": "vllm", - "bindings": { - "sparkTopology": { - "outputSchema": "nemoclaw.nvidia.com/dual-spark-topology/v1", - "qualificationId": "dgx-spark.gb10.dual-cx7", - "schemaVersion": 1, - "type": "topologyQualificationOutput" - } - }, - "execution": { - "distributedExecutorBackend": "mp", - "lifecycleRef": "vllm.dual-dgx-spark/v1", - "materializerRef": "vllm.dual-dgx-spark/v1", - "nodeCount": 2, - "pipelineParallelSize": 1, - "tensorParallelSize": 2, - "topologyBinding": "sparkTopology" - }, - "model": { - "downloadSizeBytes": 166898661074, - "gated": false, - "id": "deepseek-ai/DeepSeek-V4-Flash-0731", - "installFastSafetensors": false, - "preparation": { - "exactTextReplacement": { - "expectedText": "elif reasoning_effort in (\"max\", \"xhigh\"):\n reasoning_effort = \"max\"\n else:\n reasoning_effort = \"high\"", - "replacementText": "elif reasoning_effort in (\"max\", \"xhigh\"):\n reasoning_effort = \"max\"\n elif reasoning_effort == \"high\":\n reasoning_effort = \"high\"\n else:\n reasoning_effort = \"low\"", - "targetPath": "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py" - }, - "ref": "snapshot-copy-and-exact-text-replacement/v1", - "snapshotCopy": { - "sourcePath": "encoding/encoding_dsv4.py", - "targetPath": "/usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py" - } - }, - "revision": "9e165c30e2704aec5d9d593cce3eebd58bbef1cb", - "servedName": "deepseek-v4-flash-0731" - }, - "readiness": { - "expectedModel": "deepseek-v4-flash-0731", - "timeoutSeconds": 3600 - }, - "runtime": { - "architecture": "arm64", - "devices": [ - "/dev/infiniband" - ], - "environment": { - "CUTE_DSL_ARCH": "sm_121a", - "DG_JIT_NVCC_COMPILER": "/usr/local/cuda/bin/nvcc", - "DG_JIT_USE_NVRTC": "0", - "FLASHINFER_CUDA_ARCH_LIST": "12.1a", - "FLASHINFER_DISABLE_VERSION_CHECK": "1", - "FLASHINFER_WORKSPACE_BASE": "/cache/huggingface/flashinfer", - "HF_HUB_DISABLE_XET": "1", - "HF_HUB_OFFLINE": "1", - "NCCL_CROSS_NIC": "1", - "NCCL_CUMEM_ENABLE": "0", - "NCCL_DEBUG": "WARN", - "NCCL_IB_DISABLE": "0", - "NCCL_IGNORE_CPU_AFFINITY": "1", - "NCCL_NET": "IB", - "NCCL_NVLS_ENABLE": "0", - "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", - "TILELANG_CLEANUP_TEMP_FILES": "1", - "TORCH_CUDA_ARCH_LIST": "12.1a", - "TRANSFORMERS_OFFLINE": "1", - "VLLM_ALLOW_LONG_MAX_MODEL_LEN": "1", - "VLLM_B12X_W4A16_FORCE_BLOCKS_MAX_M": "16", - "VLLM_B12X_W4A16_FORCE_BLOCKS_PER_SM": "0", - "VLLM_CACHE_ROOT": "/cache/huggingface/vllm-cache", - "VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS": "0", - "VLLM_SPARSE_INDEXER_MAX_LOGITS_MB": "256", - "VLLM_USE_B12X_MOE": "1", - "VLLM_USE_BREAKABLE_CUDAGRAPH": "0", - "VLLM_USE_FLASHINFER_SAMPLER": "1" - }, - "gpuRequest": "all", - "image": "ghcr.io/anemll/dspark-vllm-gx10@sha256:a83948492cf13df455170fb42885f5ef4db54fefe0feff0f841ecbff464ac9d8", - "imageDownloadSizeBytes": 9787537825, - "ipcMode": "host", - "modelCache": { - "source": "huggingface-cache", - "target": "/cache/huggingface" - }, - "networkMode": "host", - "pullTimeoutSeconds": 43200, - "sharedMemoryBytes": 68719476736, - "temporaryFilesystems": [ - { - "mode": "0700", - "options": [ - "rw", - "nosuid", - "nodev", - "exec" - ], - "sizeBytes": 17179869184, - "target": "/cache/huggingface" - }, - { - "mode": "1777", - "options": [ - "rw", - "nosuid", - "nodev", - "exec" - ], - "sizeBytes": 17179869184, - "target": "/tmp" - } - ], - "ulimits": { - "memlock": -1, - "stackBytes": 67108864 - } - }, - "serve": { - "arguments": [ - { - "name": "--port", - "value": 8000 - }, - { - "name": "--trust-remote-code" - }, - { - "name": "--kv-cache-dtype", - "value": "nvfp4_ds_mla" - }, - { - "name": "--block-size", - "value": 256 - }, - { - "name": "--max-model-len", - "value": 1048576 - }, - { - "name": "--max-num-seqs", - "value": 6 - }, - { - "name": "--max-num-batched-tokens", - "value": 8192 - }, - { - "name": "--max-cudagraph-capture-size", - "value": 36 - }, - { - "name": "--gpu-memory-utilization", - "value": 0.8 - }, - { - "name": "--enable-prefix-caching" - }, - { - "name": "--enable-prompt-tokens-details" - }, - { - "name": "--async-scheduling" - }, - { - "name": "--enable-chunked-prefill" - }, - { - "name": "--speculative-config", - "value": "{\"method\":\"dspark\",\"num_speculative_tokens\":5,\"draft_sample_method\":\"probabilistic\"}" - }, - { - "name": "--tokenizer-mode", - "value": "deepseek_v4" - }, - { - "name": "--moe-backend", - "value": "flashinfer_b12x" - }, - { - "name": "--tool-call-parser", - "value": "deepseek_v4" - }, - { - "name": "--enable-auto-tool-choice" - }, - { - "name": "--reasoning-parser", - "value": "deepseek_v4" - }, - { - "name": "--reasoning-config", - "value": "{\"reasoning_parser\":\"deepseek_v4\",\"reasoning_start_str\":\"\",\"reasoning_end_str\":\"\"}" - }, - { - "name": "--default-chat-template-kwargs", - "value": "{\"thinking\":true,\"reasoning_effort\":\"low\"}" - }, - { - "name": "--generation-config", - "value": "vllm" - }, - { - "name": "--enable-flashinfer-autotune" - } - ], - "authentication": "bearer", - "executable": "/usr/local/bin/vllm" - } - } - }, - "definitionDigest": "sha256:47d72d6065cf9cf942034dcd7eb32199c800bb56a046950cf2c79de2a4796fa5", - "sourceFile": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" - } - ], - "schemaVersion": "1.0.0", - "sourceFiles": [ - { - "digest": "sha256:3ec369485750277058344be345187cdac9318d5b1ea2eef55ce78c33c62891ba", - "path": "managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml" - }, - { - "digest": "sha256:f59a45f2661f2ce072b3888802b8d081fb8d747c322c74e1d660a4d969ef0cf9", - "path": "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml" - } - ], - "sourceRevision": "sha256:1602dfca0d1166579893c17a34fd41d39c8a7da99c903f40d3a1fb0466df3584" -} diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 496912aa00c..b4cf2633e3a 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -14,7 +14,10 @@ import type { ManagedInferenceServingRecipe, ManagedInferenceTopologyQualification, } from "./catalog-types.js"; -import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { + FIXTURE_DUAL_SPARK_PRESET_ID, + fixtureDualSparkSelection, +} from "./dual-spark-fixture.test-support.js"; import { type DualSparkTopologyOutput, dualSparkTopologyOutputDigest, @@ -28,16 +31,40 @@ function shippedCatalog(): CompiledManagedInferenceCatalog { return structuredClone(loadManagedInferenceCatalog()); } -function shippedPreset(catalog = shippedCatalog()): ManagedInferenceServingPreset { - const preset = catalog.presets[0]?.definition; +function shippedCompiledPreset( + catalog = shippedCatalog(), +): CompiledManagedInferenceCatalog["presets"][number] { + const preset = catalog.presets.find( + ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, + ); expect(preset).toBeDefined(); - return preset as ManagedInferenceServingPreset; + return preset as CompiledManagedInferenceCatalog["presets"][number]; } -function shippedRecipe(catalog = shippedCatalog()): ManagedInferenceServingRecipe { - const recipe = catalog.recipes[0]?.definition; +function shippedPreset(catalog = shippedCatalog()): ManagedInferenceServingPreset { + return shippedCompiledPreset(catalog).definition; +} + +function shippedCompiledRecipe( + catalog = shippedCatalog(), +): CompiledManagedInferenceCatalog["recipes"][number] { + const recipeRef = shippedCompiledPreset(catalog).definition.spec.plan.recipeRef; + const recipe = catalog.recipes.find(({ definition }) => definition.metadata.id === recipeRef); expect(recipe).toBeDefined(); - return recipe as ManagedInferenceServingRecipe; + return recipe as CompiledManagedInferenceCatalog["recipes"][number]; +} + +function shippedRecipe(catalog = shippedCatalog()): ManagedInferenceServingRecipe { + return shippedCompiledRecipe(catalog).definition; +} + +function shippedFixtureCatalog(): CompiledManagedInferenceCatalog { + const catalog = shippedCatalog(); + return { + ...catalog, + presets: [shippedCompiledPreset(catalog)], + recipes: [shippedCompiledRecipe(catalog)], + }; } function catalogReadinessEntities(): Pick< @@ -135,6 +162,8 @@ function catalogWithSecondProfile(options: { readonly secondRecipeId: string; } { const catalog = shippedCatalog(); + const firstCompiledPreset = shippedCompiledPreset(catalog); + const firstCompiledRecipe = shippedCompiledRecipe(catalog); const firstPreset = shippedPreset(catalog); const firstRecipe = shippedRecipe(catalog); const secondPresetId = "vllm.synthetic.dual-second"; @@ -183,21 +212,21 @@ function catalogWithSecondProfile(options: { ...catalog, presets: [ { - ...catalog.presets[0]!, + ...firstCompiledPreset, definition: normalizedFirst, definitionDigest: managedInferenceDigest(normalizedFirst), }, { - ...catalog.presets[0]!, + ...firstCompiledPreset, definition: secondPreset, definitionDigest: managedInferenceDigest(secondPreset), sourceFile: "managed-inference/presets/vllm.synthetic.dual-second.yaml", }, ], recipes: [ - catalog.recipes[0]!, + firstCompiledRecipe, { - ...catalog.recipes[0]!, + ...firstCompiledRecipe, definition: secondRecipe, definitionDigest: managedInferenceDigest(secondRecipe), sourceFile: "managed-inference/recipes/vllm.synthetic.second-recipe.yaml", @@ -211,14 +240,16 @@ function catalogWithSecondProfile(options: { describe("managed inference resolver", () => { it("selects the shipped automatic preset from catalog data", () => { - const catalog = shippedCatalog(); + const catalog = shippedFixtureCatalog(); + const compiledPreset = shippedCompiledPreset(catalog); + const compiledRecipe = shippedCompiledRecipe(catalog); const result = resolveManagedInferenceServing(resolverInput(), catalog); expect(result).toMatchObject({ outcome: "selected", selection: "automatic", - presetDigest: catalog.presets[0]!.definitionDigest, - recipeDigest: catalog.recipes[0]!.definitionDigest, + presetDigest: compiledPreset.definitionDigest, + recipeDigest: compiledRecipe.definitionDigest, preset: { metadata: { id: shippedPreset(catalog).metadata.id } }, recipe: { metadata: { id: shippedRecipe(catalog).metadata.id } }, topologyQualification: { output: { masterAddress: "192.168.100.10" } }, @@ -269,7 +300,12 @@ describe("managed inference resolver", () => { firstPriority: 200, secondPriority: 100, }); - const highPreset = baseCatalog.presets[0]!.definition; + const highCompiledPreset = shippedCompiledPreset(baseCatalog); + const secondCompiledPreset = baseCatalog.presets.find( + ({ definition }) => definition.metadata.id === secondPresetId, + ); + expect(secondCompiledPreset).toBeDefined(); + const highPreset = highCompiledPreset.definition; const unavailableHighPreset = { ...highPreset, spec: { @@ -293,11 +329,11 @@ describe("managed inference resolver", () => { ...baseCatalog, presets: [ { - ...baseCatalog.presets[0]!, + ...highCompiledPreset, definition: unavailableHighPreset, definitionDigest: managedInferenceDigest(unavailableHighPreset), }, - baseCatalog.presets[1]!, + secondCompiledPreset as CompiledManagedInferenceCatalog["presets"][number], ], }; @@ -359,7 +395,7 @@ describe("managed inference resolver", () => { ...catalog, presets: [ { - ...catalog.presets[0]!, + ...shippedCompiledPreset(catalog), definition: customizedPreset, definitionDigest: managedInferenceDigest(customizedPreset), }, @@ -418,7 +454,7 @@ describe("managed inference resolver", () => { ...catalog, presets: [ { - ...catalog.presets[0]!, + ...shippedCompiledPreset(catalog), definition: customizedPreset, definitionDigest: managedInferenceDigest(customizedPreset), }, diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index 200fc83284c..f4e23fe4ef3 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -11,20 +11,24 @@ import { compileManagedInferenceCatalogSources, type ManagedInferenceCatalogSource, } from "../scripts/managed-inference/compile-catalog.mts"; -import type { SystemReadinessReport } from "../src/lib/readiness/types.js"; import type { ManagedInferenceReadinessSource, ManagedInferenceServingPreset, ManagedInferenceServingRecipe, ResolvedManagedInferenceSelection, } from "../src/lib/inference/serving/catalog-types.js"; -import { fixtureDualSparkSelection } from "../src/lib/inference/serving/dual-spark-fixture.test-support.js"; +import { + FIXTURE_DUAL_SPARK_PRESET_ID, + fixtureDualSparkSelection, +} from "../src/lib/inference/serving/dual-spark-fixture.test-support.js"; import { materializeDualSparkVllmPlan } from "../src/lib/inference/serving/dual-spark-materialize.js"; import type { DualSparkTopologyOutput } from "../src/lib/inference/serving/dual-spark-topology.js"; import { resolveManagedInferenceServing } from "../src/lib/inference/serving/resolver.js"; +import type { SystemReadinessReport } from "../src/lib/readiness/types.js"; const REPOSITORY_ROOT = fileURLToPath(new URL("..", import.meta.url)); const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; +const FIXTURE_DUAL_SPARK_RECIPE_ID = fixtureDualSparkSelection().recipe.metadata.id; function catalogSources(): ManagedInferenceCatalogSource[] { return SOURCE_DIRECTORIES.flatMap((directory) => @@ -48,9 +52,15 @@ function replaceDefinition( kind: "ServingPreset" | "ServingRecipe", replace: (definition: TDefinition) => TDefinition, ): ManagedInferenceCatalogSource[] { - const replacementIndex = sources.findIndex( - (source) => (parse(source.contents) as { readonly kind?: unknown }).kind === kind, - ); + const fixtureId = + kind === "ServingPreset" ? FIXTURE_DUAL_SPARK_PRESET_ID : FIXTURE_DUAL_SPARK_RECIPE_ID; + const replacementIndex = sources.findIndex((source) => { + const definition = parse(source.contents) as { + readonly kind?: unknown; + readonly metadata?: { readonly id?: unknown }; + }; + return definition.kind === kind && definition.metadata?.id === fixtureId; + }); expect(replacementIndex).toBeGreaterThanOrEqual(0); return sources.map((source, index) => index === replacementIndex @@ -66,14 +76,16 @@ function syntheticProfileSources( sources: readonly ManagedInferenceCatalogSource[], ): ManagedInferenceCatalogSource[] { const compiled = compileManagedInferenceCatalogSources(sources).catalog; - const sourceRecipe = compiled.recipes[0]?.definition; const sourcePreset = compiled.presets.find( - ({ definition }) => definition.spec.plan.recipeRef === sourceRecipe?.metadata.id, + ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, )?.definition; - expect(sourceRecipe).toBeDefined(); expect(sourcePreset).toBeDefined(); - const recipeTemplate = sourceRecipe as ManagedInferenceServingRecipe; const presetTemplate = sourcePreset as ManagedInferenceServingPreset; + const sourceRecipe = compiled.recipes.find( + ({ definition }) => definition.metadata.id === presetTemplate.spec.plan.recipeRef, + )?.definition; + expect(sourceRecipe).toBeDefined(); + const recipeTemplate = sourceRecipe as ManagedInferenceServingRecipe; const recipe: ManagedInferenceServingRecipe = { ...recipeTemplate, @@ -124,7 +136,7 @@ function syntheticProfileSources( ), }, readiness: { - ...sourceRecipe.spec.readiness, + ...recipeTemplate.spec.readiness, timeoutSeconds: 900, expectedModel: "synthetic-model", }, @@ -212,25 +224,29 @@ function matchingReadinessSources( } describe("managed inference catalog compiler", () => { - it("produces identical canonical JSON regardless of source enumeration order", () => { + it("produces an identical generated TypeScript module regardless of source enumeration order", () => { const sources = catalogSources(); - expect(compileManagedInferenceCatalogSources(sources).json).toBe( - compileManagedInferenceCatalogSources([...sources].reverse()).json, + const generated = compileManagedInferenceCatalogSources(sources).module; + expect(generated).toBe(compileManagedInferenceCatalogSources([...sources].reverse()).module); + expect(generated).toMatch( + /const generatedCatalog: CompiledManagedInferenceCatalog = \{[\s\S]+\};\n\nexport default generatedCatalog;\n$/u, ); }); it("compiles a synthetic second YAML-only profile without schema or TypeScript changes", () => { - const compiled = compileManagedInferenceCatalogSources( - syntheticProfileSources(catalogSources()), - ); - expect(compiled.catalog.presets).toHaveLength(2); - expect(compiled.catalog.recipes).toHaveLength(2); + const sources = catalogSources(); + const base = compileManagedInferenceCatalogSources(sources).catalog; + const compiled = compileManagedInferenceCatalogSources(syntheticProfileSources(sources)); + expect(compiled.catalog.presets).toHaveLength(base.presets.length + 1); + expect(compiled.catalog.recipes).toHaveLength(base.recipes.length + 1); expect(compiled.catalog.presets.map(({ definition }) => definition.metadata.id)).toContain( "vllm.synthetic-model.generic-topology", ); expect(compiled.catalog.recipes.map(({ definition }) => definition.metadata.id)).toContain( "vllm.synthetic-model.generic-topology.v1", ); + expect(compiled.module).toContain("vllm.synthetic-model.generic-topology"); + expect(compiled.module).toContain("vllm.synthetic-model.generic-topology.v1"); }); it("resolves and materializes the second YAML-only profile without profile-specific code", () => { @@ -345,7 +361,9 @@ describe("managed inference catalog compiler", () => { it("derives a new definition digest when YAML profile data changes", () => { const sources = catalogSources(); - const before = compileManagedInferenceCatalogSources(sources).catalog.recipes[0]; + const before = compileManagedInferenceCatalogSources(sources).catalog.recipes.find( + ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_RECIPE_ID, + ); const changed = replaceDefinition( sources, "ServingRecipe", @@ -363,7 +381,11 @@ describe("managed inference catalog compiler", () => { }, }), ); - const after = compileManagedInferenceCatalogSources(changed).catalog.recipes[0]; + const after = compileManagedInferenceCatalogSources(changed).catalog.recipes.find( + ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_RECIPE_ID, + ); + expect(before).toBeDefined(); + expect(after).toBeDefined(); expect(after?.definitionDigest).not.toBe(before?.definitionDigest); }); From b461955d06afc1fa17c096de5730eb6a927050fe Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 09:40:27 -0700 Subject: [PATCH 07/27] fix(inference): bind Spark claim cleanup to receipt Signed-off-by: Aaron Erickson --- docs/reference/host-files-and-state.mdx | 2 +- .../serving/spark-runtime-receipt.ts | 60 +++++++++++++- .../vllm-spark-runtime-receipt.test.ts | 79 ++++++++++++++----- src/lib/inference/vllm-station-ssh-binding.ts | 28 +++++++ 4 files changed, 146 insertions(+), 23 deletions(-) diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index c647a7c92c2..f267297ff08 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -35,7 +35,7 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/usage-notice.json` | Records the third-party software notice version in `acceptedVersion` and the acceptance time in `acceptedAt`. Install, onboarding, and rebuild flows consult this file and prompt again when its recorded version differs from the current notice or the file is absent. | Yes; deleting it makes the next applicable install, onboarding, or rebuild flow prompt for acceptance again. | | `~/.nemoclaw/ollama-proxy-token` | Local auth token used by the host-side Ollama auth proxy. | Yes, but re-run onboarding afterward so NemoClaw recreates and registers the proxy token. | | `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by NemoClaw-managed distributed vLLM profiles. | No while a managed distributed runtime exists. Full uninstall removes it only after managed runtime cleanup succeeds and no sibling gateway remains. | -| `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, and container identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | +| `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, container, and temporary discovery-claim identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | | `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded DGX Spark worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds. | | `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. With the matching host-global dual-Spark receipt, full uninstall retires the claim after it removes both exact containers; if safe retirement fails, it preserves the receipt for a retry. Gateway-scoped uninstall preserves the claim. | | `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts index c50db070916..a1a74ef0bf8 100644 --- a/src/lib/inference/serving/spark-runtime-receipt.ts +++ b/src/lib/inference/serving/spark-runtime-receipt.ts @@ -11,6 +11,7 @@ import { copyDualStationSshBinding, type DualStationSshBinding, encodeDualStationSshBindingHandoff, + loadDualStationSshBindingForStatePath, loadDualStationSshBindingHandoff, } from "../vllm-station-ssh-binding"; import { managedInferenceHexDigest } from "./catalog-integrity"; @@ -38,6 +39,7 @@ const CONTAINER_ID = /^[a-f0-9]{64}$/; const BINDING_HANDLE = /^[A-Za-z0-9_-]{1,8192}$/; const RECEIPT_KEYS = [ "apiKeyFingerprint", + "discoveryBindingDigest", "headContainerId", "localCacheRoot", "peerCacheRoot", @@ -47,12 +49,31 @@ const RECEIPT_KEYS = [ "sshBinding", "workerContainerId", ] as const; +const EXACT_BINDING_KEYS = [ + "schemaVersion", + "peerTarget", + "resolvedHost", + "sshUser", + "port", + "lookupHost", + "hostKeyDigest", + "dockerCliFile", + "dockerShimFile", + "dockerShimSha256", + "knownHostsFile", + "knownHostsSha256", + "bindingFile", + "sshWrapperDirectory", + "sshWrapperFile", + "sshWrapperSha256", +] as const satisfies readonly (keyof DualStationSshBinding)[]; interface PersistedReceipt { readonly schemaVersion: 1; readonly plan: DualSparkVllmPlan; readonly planDigest: string; readonly sshBinding: string; + readonly discoveryBindingDigest: string; readonly localCacheRoot: string; readonly peerCacheRoot: string; readonly apiKeyFingerprint: string; @@ -74,6 +95,7 @@ export interface LoadedDualSparkVllmRuntime { readonly plan: DualSparkVllmPlan; readonly peerSshBinding: DualStationSshBinding; readonly sshBinding: string; + readonly discoveryBindingDigest: string; readonly localCacheRoot: string; readonly peerCacheRoot: string; readonly apiKeyFingerprint: string; @@ -210,6 +232,12 @@ function parseReceipt(value: unknown): PersistedReceipt { plan, planDigest: digest, sshBinding: requireString(value.sshBinding, "dual-Spark SSH binding", BINDING_HANDLE), + discoveryBindingDigest: requireString( + value.discoveryBindingDigest, + "dual-Spark discovery SSH binding digest", + SHA256, + 64, + ), localCacheRoot: requireAbsolutePath(value.localCacheRoot, "dual-Spark local cache root"), peerCacheRoot: requireAbsolutePath(value.peerCacheRoot, "dual-Spark peer cache root"), apiKeyFingerprint: requireString( @@ -330,6 +358,27 @@ function loadedRuntime(receipt: PersistedReceipt): LoadedDualSparkVllmRuntime { return { ...receipt, peerSshBinding: binding }; } +function bindingDigest(binding: DualStationSshBinding): string { + return managedInferenceHexDigest( + Object.fromEntries(EXACT_BINDING_KEYS.map((field) => [field, binding[field]])), + ); +} + +function loadReceiptOwnedDiscoveryBinding( + stateDir: string, + runtime: LoadedDualSparkVllmRuntime, +): DualStationSshBinding | null { + const binding = loadDualStationSshBindingForStatePath( + path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE), + runtime.peerSshBinding.peerTarget, + runtime.peerSshBinding.hostKeyDigest, + ); + if (binding && bindingDigest(binding) !== runtime.discoveryBindingDigest) { + throw new Error("Dual-Spark discovery SSH binding does not match the runtime receipt identity"); + } + return binding; +} + export function loadDualSparkVllmRuntimeReceipt( options: Pick = {}, ): LoadedDualSparkVllmRuntime | null { @@ -348,6 +397,7 @@ function sameInput( input.peerSshBinding.resolvedHost === existing.peerSshBinding.resolvedHost && input.peerSshBinding.sshUser === existing.peerSshBinding.sshUser && input.peerSshBinding.port === existing.peerSshBinding.port && + bindingDigest(input.peerSshBinding) === existing.discoveryBindingDigest && input.localCacheRoot === existing.localCacheRoot && input.peerCacheRoot === existing.peerCacheRoot && input.apiKeyFingerprint === existing.apiKeyFingerprint && @@ -405,6 +455,7 @@ export function persistDualSparkVllmRuntimeReceipt( plan, planDigest: planDigest(plan), sshBinding, + discoveryBindingDigest: bindingDigest(input.peerSshBinding), localCacheRoot: input.localCacheRoot, peerCacheRoot: input.peerCacheRoot, apiKeyFingerprint: input.apiKeyFingerprint, @@ -502,6 +553,7 @@ export async function cleanupInstalledDualSparkVllmRuntime( if (!apiKey || dualSparkVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { throw new Error("Managed dual-Spark API key no longer matches the runtime receipt"); } + const discoveryBinding = loadReceiptOwnedDiscoveryBinding(stateDir, runtime); const deps = (options.createLifecycleDeps ?? defaultCreateLifecycleDeps)(runtime); const cleanup = await cleanupDualSparkManagedVllm(runtime.plan, apiKey, deps, { headContainerId: runtime.headContainerId, @@ -517,7 +569,13 @@ export async function cleanupInstalledDualSparkVllmRuntime( ) { throw new Error("Managed dual-Spark cleanup returned unexpected container identities"); } - clearDualStationSshBinding(path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)); + const currentDiscoveryBinding = loadReceiptOwnedDiscoveryBinding(stateDir, runtime); + if ((discoveryBinding === null) !== (currentDiscoveryBinding === null)) { + throw new Error("Dual-Spark discovery SSH binding changed during runtime cleanup"); + } + if (currentDiscoveryBinding) { + clearDualStationSshBinding(path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)); + } clearReceipt(stateDir); return { kind: "removed", removedContainerIds: cleanup.removedContainerIds }; } diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts index 1b3d948a847..d81effb2706 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -29,7 +29,12 @@ import { recoverInstalledDualSparkVllmEndpoint, } from "./serving/spark-runtime-receipt"; import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./serving/spark-runtime-receipt-path"; -import { copyDualStationSshBinding } from "./vllm-station-ssh-binding"; +import { + clearDualStationSshBinding, + copyDualStationSshBinding, + type DualStationSshBinding, + encodeDualStationSshBindingHandoff, +} from "./vllm-station-ssh-binding"; import { createDualStationSshBindingFixture, type DualStationSshBindingFixture, @@ -57,14 +62,14 @@ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); -function plan(): DualSparkVllmPlan { +function plan(peerSshBinding: DualStationSshBinding = sshFixture.binding): DualSparkVllmPlan { const selection = fixtureDualSparkSelection(); const sourceTopology = selection.topologyQualification; const output = { ...sourceTopology.output, peer: { - target: sshFixture.binding.peerTarget, - sshBindingHandle: sshFixture.token, + target: peerSshBinding.peerTarget, + sshBindingHandle: encodeDualStationSshBindingHandoff(peerSshBinding), }, }; return materializeDualSparkVllmPlan({ @@ -77,10 +82,12 @@ function plan(): DualSparkVllmPlan { }); } -function input(): PersistDualSparkVllmRuntimeReceiptInput { +function input( + peerSshBinding: DualStationSshBinding = sshFixture.binding, +): PersistDualSparkVllmRuntimeReceiptInput { return { - plan: plan(), - peerSshBinding: sshFixture.binding, + plan: plan(peerSshBinding), + peerSshBinding, localCacheRoot: "/home/nvidia/.cache/huggingface", peerCacheRoot: "/home/nvidia/.cache/huggingface", apiKeyFingerprint: dualSparkVllmApiKeyFingerprint(API_KEY), @@ -89,6 +96,21 @@ function input(): PersistDualSparkVllmRuntimeReceiptInput { }; } +function persistWithDiscoveryBinding(): { + discoveryBindingPath: string; + discoveryStatePath: string; + runtime: ReturnType; +} { + fs.mkdirSync(stateDir, { mode: 0o700 }); + const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); + const binding = copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + return { + discoveryBindingPath: `${discoveryStatePath}.ssh-binding`, + discoveryStatePath, + runtime: persistDualSparkVllmRuntimeReceipt(input(binding), { stateDir }), + }; +} + function snapshot(rolePlan: DualSparkVllmRolePlan, containerId: string): DualSparkNodeSnapshot { return { containers: [ @@ -278,9 +300,7 @@ describe("dual-Spark vLLM runtime receipt", () => { }); it("removes only both exact receipt-owned containers before retiring state", async () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); - const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); - copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + const { discoveryStatePath, runtime } = persistWithDiscoveryBinding(); const { deps, removeContainer } = cleanupDeps(runtime.plan); await expect( cleanupInstalledDualSparkVllmRuntime({ @@ -299,14 +319,30 @@ describe("dual-Spark vLLM runtime receipt", () => { expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); }); + it("preserves a replaced canonical discovery binding before container cleanup", async () => { + const { discoveryBindingPath, discoveryStatePath, runtime } = persistWithDiscoveryBinding(); + clearDualStationSshBinding(discoveryStatePath); + copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + const { deps, removeContainer } = cleanupDeps(runtime.plan); + const createLifecycleDeps = vi.fn(() => deps); + + await expect( + cleanupInstalledDualSparkVllmRuntime({ + stateDir, + loadApiKey: () => API_KEY, + createLifecycleDeps, + }), + ).rejects.toThrow("does not match the runtime receipt identity"); + + expect(createLifecycleDeps).not.toHaveBeenCalled(); + expect(removeContainer).not.toHaveBeenCalled(); + expect(fs.existsSync(discoveryBindingPath)).toBe(true); + expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + }); + it("retains durable ownership when a leftover discovery binding is unsafe to retire", async () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); - const discoveryBindingPath = `${path.join( - stateDir, - DUAL_SPARK_MANAGED_SERVING_STATE_FILE, - )}.ssh-binding`; - fs.mkdirSync(discoveryBindingPath, { mode: 0o755 }); - fs.chmodSync(discoveryBindingPath, 0o755); + const { discoveryBindingPath, runtime } = persistWithDiscoveryBinding(); const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { head: snapshot(runtime.plan.roles.head, HEAD_ID), worker: snapshot(runtime.plan.roles.worker, WORKER_ID), @@ -316,6 +352,7 @@ describe("dual-Spark vLLM runtime receipt", () => { ...snapshots[rolePlan.role], containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), }; + if (rolePlan.role === "worker") fs.chmodSync(discoveryBindingPath, 0o755); return { ok: true as const }; }); const options = { @@ -329,7 +366,9 @@ describe("dual-Spark vLLM runtime receipt", () => { }), }; - await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow("unsafe to remove"); + await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow( + "must be an owner-only directory", + ); expect(removeContainer).toHaveBeenCalledTimes(2); expect(fs.existsSync(discoveryBindingPath)).toBe(true); @@ -348,9 +387,7 @@ describe("dual-Spark vLLM runtime receipt", () => { }); it("retains the receipt and resumes after one exact container removal fails", async () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); - const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); - copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + const { discoveryStatePath, runtime } = persistWithDiscoveryBinding(); const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { head: snapshot(runtime.plan.roles.head, HEAD_ID), worker: snapshot(runtime.plan.roles.worker, WORKER_ID), diff --git a/src/lib/inference/vllm-station-ssh-binding.ts b/src/lib/inference/vllm-station-ssh-binding.ts index bfce00f32c8..8b98c8abb62 100644 --- a/src/lib/inference/vllm-station-ssh-binding.ts +++ b/src/lib/inference/vllm-station-ssh-binding.ts @@ -728,6 +728,34 @@ export function loadDualStationSshBinding( return validateDualStationSshBindingFiles(binding); } +/** Load the sole validated binding owned by one resume-state path, if present. */ +export function loadDualStationSshBindingForStatePath( + statePath: string, + expectedPeerTarget: string, + expectedHostKeyDigest: string, +): DualStationSshBinding | null { + const runtimeDirectory = dualStationSshBindingDirectory(statePath); + try { + assertDirectory(runtimeDirectory, 0o700, "Station SSH binding root"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw error; + } + const entries = fs.readdirSync(runtimeDirectory, { withFileTypes: true }); + if ( + entries.length !== 1 || + !entries[0]?.isDirectory() || + !VERSION_DIRECTORY_PATTERN.test(entries[0].name) + ) { + throw new Error("Station SSH binding root does not contain one exact binding"); + } + return loadDualStationSshBinding( + path.join(runtimeDirectory, entries[0].name, "binding.json"), + expectedPeerTarget, + expectedHostKeyDigest, + ); +} + export function encodeDualStationSshBindingHandoff(binding: DualStationSshBinding): string { const canonical = validateDualStationSshBindingFiles(binding); const handoff: BindingHandoff = { From a263b939d8962749b67b810dbc9de65c5ef50825 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 10:13:08 -0700 Subject: [PATCH 08/27] fix(inference): generate catalog for semantic checks Signed-off-by: Aaron Erickson --- package.json | 2 +- test/e2e/support/e2e-semantic-phase-check.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index b2a8887ecd8..5619ffe3f7c 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "test:watch": "npm run catalog:compile && vitest watch --project cli --project plugin --project e2e-support", "test:shuffle": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", "test:diagnose:leaks": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", - "test:e2e-phases:check": "npm run build:policy-boundary && node --experimental-strip-types --no-warnings tools/e2e/check-semantic-phases.mts", + "test:e2e-phases:check": "npm run catalog:compile && npm run build:policy-boundary && node --experimental-strip-types --no-warnings tools/e2e/check-semantic-phases.mts", "test:runtime-audit": "tsx scripts/audit-test-runtime.mts", "test:integration": "npm run clean:cli && npm run build:cli && vitest run --project integration --project installer-integration", "test:package": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project package-contract", diff --git a/test/e2e/support/e2e-semantic-phase-check.test.ts b/test/e2e/support/e2e-semantic-phase-check.test.ts index 4e3b2066041..43b40995d15 100644 --- a/test/e2e/support/e2e-semantic-phase-check.test.ts +++ b/test/e2e/support/e2e-semantic-phase-check.test.ts @@ -31,7 +31,7 @@ const TEST_PROGRESS_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/progress.ts const FAKE_OPENAI_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/fake-openai-compatible.ts"); describe("semantic E2E phase checker", () => { - // source-shape-contract: compatibility -- Generated policy output must precede semantic collection and remain shared with the canonical CLI build + // source-shape-contract: compatibility -- Generated catalog and policy output must precede semantic collection and remain shared with the canonical CLI build test("builds the policy boundary before semantic collection and CLI compilation", () => { const scripts = ( JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8")) as { @@ -41,10 +41,10 @@ describe("semantic E2E phase checker", () => { expect(scripts["build:policy-boundary"]).toBe("tsc -p nemoclaw/tsconfig.shared.json"); expect(scripts["test:e2e-phases:check"]).toMatch( - /^npm run build:policy-boundary && node .*tools\/e2e\/check-semantic-phases\.mts$/u, + /^npm run catalog:compile && npm run build:policy-boundary && node .*tools\/e2e\/check-semantic-phases\.mts$/u, ); expect(scripts["build:cli"]).toMatch( - /^npm run build:policy-boundary && tsc -p tsconfig\.src\.json &&/u, + /^npm run build:policy-boundary && npm run catalog:compile && tsc -p tsconfig\.src\.json &&/u, ); }); From 00eb5796d4d99bfa8586f0d1008df7166dd29eef Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 10:38:03 -0700 Subject: [PATCH 09/27] test(inference): keep receipt cleanup setup linear Signed-off-by: Aaron Erickson --- src/lib/inference/vllm-spark-runtime-receipt.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts index d81effb2706..cb2dc5b399a 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -347,12 +347,16 @@ describe("dual-Spark vLLM runtime receipt", () => { head: snapshot(runtime.plan.roles.head, HEAD_ID), worker: snapshot(runtime.plan.roles.worker, WORKER_ID), }; + const discoveryBindingModeByRole: Record = { + head: 0o700, + worker: 0o755, + }; const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { snapshots[rolePlan.role] = { ...snapshots[rolePlan.role], containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), }; - if (rolePlan.role === "worker") fs.chmodSync(discoveryBindingPath, 0o755); + fs.chmodSync(discoveryBindingPath, discoveryBindingModeByRole[rolePlan.role]); return { ok: true as const }; }); const options = { From 16afe65e39b2eec39eb7d56b1d9ba793d0e27829 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 11:02:38 -0700 Subject: [PATCH 10/27] test(vitest): stub catalog compiler in script harness Signed-off-by: Aaron Erickson --- test/helpers/vitest-npm-script.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/helpers/vitest-npm-script.ts b/test/helpers/vitest-npm-script.ts index 3e983d256a0..0b984df17ff 100644 --- a/test/helpers/vitest-npm-script.ts +++ b/test/helpers/vitest-npm-script.ts @@ -24,6 +24,7 @@ export function runVitestNpmScript( '#!/bin/sh\nprintf \'vitest %s\\n\' "$*" > "$COMMAND_LOG"\n', { mode: 0o755 }, ); + fs.writeFileSync(path.join(fakeBin, "tsx"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); fs.writeFileSync( scriptShell, `#!/bin/sh\nPATH="$FAKE_BIN:${path.dirname(process.execPath)}:/usr/bin:/bin"\nexport PATH\nexec /bin/sh "$@"\n`, From f6674ae7b702d8932604c95f36c0625ebac332be Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 11:52:30 -0700 Subject: [PATCH 11/27] fix(inference): package generated catalog as data Signed-off-by: Aaron Erickson --- .gitignore | 2 + scripts/managed-inference/compile-catalog.mts | 48 ++++++++++-------- src/lib/inference/serving/catalog.ts | 2 +- ...managed-inference-catalog-compiler.test.ts | 50 ++++++++++++++++--- .../managed-inference-catalog.test.ts | 47 +++++++++++++++++ 5 files changed, 121 insertions(+), 28 deletions(-) create mode 100644 test/package-contract/managed-inference-catalog.test.ts diff --git a/.gitignore b/.gitignore index 49c15e03c59..e1548b6b329 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,9 @@ coverage/ dist/ docs/_build/ node_modules/ +# Managed inference compiler output and its pre-JSON legacy path. src/lib/inference/serving/generated/catalog.ts +src/lib/inference/serving/generated/catalog.json # OS metadata .DS_Store diff --git a/scripts/managed-inference/compile-catalog.mts b/scripts/managed-inference/compile-catalog.mts index 9ce479dee8f..c8ce7051bae 100644 --- a/scripts/managed-inference/compile-catalog.mts +++ b/scripts/managed-inference/compile-catalog.mts @@ -46,7 +46,14 @@ const { const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; -const GENERATED_CATALOG_MODULE_PATH = "src/lib/inference/serving/generated/catalog.ts"; +const GENERATED_CATALOG_DOCUMENT_PATH = "src/lib/inference/serving/generated/catalog.json"; +const LEGACY_GENERATED_CATALOG_PATHS = [ + "src/lib/inference/serving/generated/catalog.ts", + "dist/lib/inference/serving/generated/catalog.js", + "dist/lib/inference/serving/generated/catalog.js.map", + "dist/lib/inference/serving/generated/catalog.d.ts", + "dist/lib/inference/serving/generated/catalog.d.ts.map", +] as const; const RECIPE_SCHEMA_ID = recipeSchema.$id; const PRESET_SCHEMA_ID = presetSchema.$id; const SHA256 = /^sha256:[0-9a-f]{64}$/u; @@ -58,24 +65,13 @@ export interface ManagedInferenceCatalogSource { export interface CompiledManagedInferenceCatalogResult { readonly catalog: CompiledManagedInferenceCatalog; - readonly module: string; + readonly document: string; } -export function renderManagedInferenceCatalogModule( +export function renderManagedInferenceCatalogDocument( catalog: CompiledManagedInferenceCatalog, ): string { - return `// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -// Generated by scripts/managed-inference/compile-catalog.mts from managed-inference YAML. -// Do not edit this file directly. - -import type { CompiledManagedInferenceCatalog } from "../catalog-types.js"; - -const generatedCatalog: CompiledManagedInferenceCatalog = ${JSON.stringify(catalog, null, 2)}; - -export default generatedCatalog; -`; + return `${JSON.stringify(catalog, null, 2)}\n`; } function compareStrings(left: string, right: string): number { @@ -379,7 +375,7 @@ export function compileManagedInferenceCatalogSources( } return { catalog, - module: renderManagedInferenceCatalogModule(catalog), + document: renderManagedInferenceCatalogDocument(catalog), }; } @@ -405,14 +401,26 @@ export function compileManagedInferenceCatalog( return compileManagedInferenceCatalogSources(readCatalogSources(repositoryRoot)); } +export function writeManagedInferenceCatalog( + repositoryRoot = REPOSITORY_ROOT, +): CompiledManagedInferenceCatalogResult { + const compiled = compileManagedInferenceCatalog(repositoryRoot); + const outputPath = path.join(repositoryRoot, GENERATED_CATALOG_DOCUMENT_PATH); + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, compiled.document, "utf8"); + for (const legacyPath of LEGACY_GENERATED_CATALOG_PATHS) { + fs.rmSync(path.join(repositoryRoot, legacyPath), { force: true }); + } + return compiled; +} + function main(): void { const unknownArguments = process.argv.slice(2).filter((argument) => argument !== "--write"); if (unknownArguments.length > 0) throw new Error(`unknown argument ${unknownArguments[0]}`); - const { module } = compileManagedInferenceCatalog(); if (process.argv.includes("--write")) { - const outputPath = path.join(REPOSITORY_ROOT, GENERATED_CATALOG_MODULE_PATH); - fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - fs.writeFileSync(outputPath, module, "utf8"); + writeManagedInferenceCatalog(); + } else { + compileManagedInferenceCatalog(); } } diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts index e91e755fe9d..583a4ef110e 100644 --- a/src/lib/inference/serving/catalog.ts +++ b/src/lib/inference/serving/catalog.ts @@ -13,7 +13,7 @@ import { type ManagedInferenceServingPreset, type ManagedInferenceServingRecipe, } from "./catalog-types.js"; -import generatedCatalog from "./generated/catalog.js"; +import generatedCatalog from "./generated/catalog.json"; const SHA256 = /^sha256:[0-9a-f]{64}$/u; const SOURCE_PATH = /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u; diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index f4e23fe4ef3..b121c4ae414 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; @@ -10,6 +11,7 @@ import { parse, stringify } from "yaml"; import { compileManagedInferenceCatalogSources, type ManagedInferenceCatalogSource, + writeManagedInferenceCatalog, } from "../scripts/managed-inference/compile-catalog.mts"; import type { ManagedInferenceReadinessSource, @@ -224,13 +226,47 @@ function matchingReadinessSources( } describe("managed inference catalog compiler", () => { - it("produces an identical generated TypeScript module regardless of source enumeration order", () => { + it("produces an identical generated JSON document regardless of source enumeration order", () => { const sources = catalogSources(); - const generated = compileManagedInferenceCatalogSources(sources).module; - expect(generated).toBe(compileManagedInferenceCatalogSources([...sources].reverse()).module); - expect(generated).toMatch( - /const generatedCatalog: CompiledManagedInferenceCatalog = \{[\s\S]+\};\n\nexport default generatedCatalog;\n$/u, + const compiled = compileManagedInferenceCatalogSources(sources); + expect(compiled.document).toBe( + compileManagedInferenceCatalogSources([...sources].reverse()).document, ); + expect(JSON.parse(compiled.document)).toEqual(compiled.catalog); + expect(compiled.document.endsWith("\n")).toBe(true); + }); + + it("writes the JSON artifact and removes legacy generated TypeScript outputs", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-catalog-compiler-")); + const sources = catalogSources(); + const legacyPaths = [ + "src/lib/inference/serving/generated/catalog.ts", + "dist/lib/inference/serving/generated/catalog.js", + "dist/lib/inference/serving/generated/catalog.js.map", + "dist/lib/inference/serving/generated/catalog.d.ts", + "dist/lib/inference/serving/generated/catalog.d.ts.map", + ]; + try { + for (const source of sources) { + const sourcePath = path.join(root, source.path); + fs.mkdirSync(path.dirname(sourcePath), { recursive: true }); + fs.writeFileSync(sourcePath, source.contents, "utf8"); + } + for (const legacyPath of legacyPaths) { + const artifactPath = path.join(root, legacyPath); + fs.mkdirSync(path.dirname(artifactPath), { recursive: true }); + fs.writeFileSync(artifactPath, "legacy generated artifact\n", "utf8"); + } + + const compiled = writeManagedInferenceCatalog(root); + const documentPath = path.join(root, "src/lib/inference/serving/generated/catalog.json"); + expect(JSON.parse(fs.readFileSync(documentPath, "utf8"))).toEqual(compiled.catalog); + expect(legacyPaths.every((legacyPath) => !fs.existsSync(path.join(root, legacyPath)))).toBe( + true, + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } }); it("compiles a synthetic second YAML-only profile without schema or TypeScript changes", () => { @@ -245,8 +281,8 @@ describe("managed inference catalog compiler", () => { expect(compiled.catalog.recipes.map(({ definition }) => definition.metadata.id)).toContain( "vllm.synthetic-model.generic-topology.v1", ); - expect(compiled.module).toContain("vllm.synthetic-model.generic-topology"); - expect(compiled.module).toContain("vllm.synthetic-model.generic-topology.v1"); + expect(compiled.document).toContain("vllm.synthetic-model.generic-topology"); + expect(compiled.document).toContain("vllm.synthetic-model.generic-topology.v1"); }); it("resolves and materializes the second YAML-only profile without profile-specific code", () => { diff --git a/test/package-contract/managed-inference-catalog.test.ts b/test/package-contract/managed-inference-catalog.test.ts new file mode 100644 index 00000000000..62f9fe63232 --- /dev/null +++ b/test/package-contract/managed-inference-catalog.test.ts @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +const require = createRequire(import.meta.url); +const REPOSITORY_ROOT = fileURLToPath(new URL("../..", import.meta.url)); +const GENERATED_CATALOG_DIRECTORY = path.join( + REPOSITORY_ROOT, + "dist/lib/inference/serving/generated", +); + +describe("managed inference catalog package contract", () => { + it("does not ship legacy generated TypeScript outputs", () => { + expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.js"))).toBe(false); + expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.js.map"))).toBe(false); + expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.d.ts"))).toBe(false); + expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.d.ts.map"))).toBe(false); + }); + + it("loads and validates the compiled catalog through the packaged runtime", () => { + const catalogModule = require( + path.join(REPOSITORY_ROOT, "dist/lib/inference/serving/catalog.js"), + ) as { + loadManagedInferenceCatalog(): { + readonly presets: readonly unknown[]; + readonly recipes: readonly unknown[]; + readonly sourceFiles: readonly { readonly path: string }[]; + }; + }; + + const catalog = catalogModule.loadManagedInferenceCatalog(); + expect(catalog.presets.length).toBeGreaterThan(0); + expect(catalog.recipes.length).toBeGreaterThan(0); + expect(catalog.sourceFiles).toHaveLength(catalog.presets.length + catalog.recipes.length); + expect( + catalog.sourceFiles.every(({ path: sourcePath }) => + /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u.test(sourcePath), + ), + ).toBe(true); + }); +}); From aec892aad10cc2f5dc106bde2521913d6228e9c6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 14:45:02 -0700 Subject: [PATCH 12/27] fix(inference): address dual Spark review feedback Signed-off-by: Aaron Erickson --- ci/source-architecture-budget.json | 2 +- ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 4 - .../uninstall/run-plan-dual-station.test.ts | 56 ++++++++- src/lib/actions/uninstall/run-plan.test.ts | 13 ++- src/lib/actions/uninstall/run-plan.ts | 29 ++++- src/lib/inference/local-vllm-auth.test.ts | 19 ++++ src/lib/inference/local.ts | 79 ++++++++----- .../serving/adapter-registry.test.ts | 26 ++++- src/lib/inference/serving/adapter-registry.ts | 11 ++ .../serving/dual-spark-discovery.test.ts | 22 +++- .../inference/serving/dual-spark-discovery.ts | 18 ++- .../serving/dual-spark-installer.test.ts | 16 ++- .../serving/dual-spark-materialize.test.ts | 12 +- .../serving/dual-spark-materialize.ts | 2 + .../serving/dual-spark-topology.test.ts | 13 ++- src/lib/inference/serving/resolver.test.ts | 8 +- .../serving/spark-runtime-receipt.ts | 15 ++- src/lib/inference/vllm-dual-station.test.ts | 12 +- .../inference/vllm-managed-recovery.test.ts | 11 +- .../vllm-spark-runtime-receipt.test.ts | 106 +++++++++++++++--- .../vllm-station-cluster-lifecycle.test.ts | 10 +- .../vllm-station-lifecycle-lock.test.ts | 17 ++- .../inference/vllm-station-lifecycle-lock.ts | 11 +- .../vllm-station-runtime-cleanup-entry.ts | 8 +- src/lib/inference/vllm.ts | 13 +-- src/lib/onboard/provider-host-state.test.ts | 19 ++++ src/lib/onboard/provider-host-state.ts | 16 ++- ...managed-inference-catalog-compiler.test.ts | 1 + 28 files changed, 437 insertions(+), 132 deletions(-) diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index de561b85725..b3e3e96514e 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -28,7 +28,7 @@ "src/lib/security/redact.ts": 51, "src/lib/state/onboard-session.ts": 36, "src/lib/state/registry.ts": 101, - "src/lib/state/state-root.ts": 23, + "src/lib/state/state-root.ts": 22, "src/lib/subprocess-env.ts": 24, "src/lib/validation.ts": 25 } diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml index 1e5c008c380..7411b1880a6 100644 --- a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -63,10 +63,6 @@ spec: source: huggingface-cache target: /cache/huggingface temporaryFilesystems: - - target: /cache/huggingface - sizeBytes: 17179869184 - mode: "0700" - options: [rw, nosuid, nodev, exec] - target: /tmp sizeBytes: 17179869184 mode: "1777" diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index 81d433f1807..a4cc771a7c8 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -341,14 +341,17 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("finds the host-global Spark receipt from a non-default gateway selection", async () => { - const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-global-")); + it.each([ + ["Spark", "dual-spark-vllm-runtime.json"], + ["Station", "dual-station-vllm-runtime.json"], + ])("finds the host-global %s receipt from a non-default gateway selection", async (_topology, receiptFile) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-managed-global-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); - fs.writeFileSync(path.join(stateDir, "dual-spark-vllm-runtime.json"), "{}\n", { + fs.writeFileSync(path.join(stateDir, receiptFile), "{}\n", { mode: 0o600, }); - fs.mkdirSync(path.join(stateDir, "dual-spark-vllm-runtime.json.ssh-binding"), { + fs.mkdirSync(path.join(stateDir, `${receiptFile}.ssh-binding`), { mode: 0o700, }); fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${"a".repeat(64)}\n`, { @@ -400,4 +403,49 @@ describe("managed distributed vLLM runtime uninstall", () => { fs.rmSync(home, { recursive: true, force: true }); } }); + + it.each([ + "symbolic link", + "regular file", + ])("fails closed when the host-global managed state root is a %s", (shape) => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-unsafe-root-")); + const stateDir = path.join(home, ".nemoclaw"); + if (shape === "symbolic link") { + const target = path.join(home, "redirected-state"); + fs.mkdirSync(target, { mode: 0o700 }); + fs.symlinkSync(target, stateDir, "dir"); + } else { + fs.writeFileSync(stateDir, "not a directory\n", { mode: 0o600 }); + } + const errors: string[] = []; + const runDualStationRuntimeCleanup = vi.fn(() => ok()); + const runDocker = vi.fn(() => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: home, TMPDIR: home } as NodeJS.ProcessEnv, + error: (message) => errors.push(message), + existsSync: () => false, + isTty: false, + log: vi.fn(), + rmSync: vi.fn(), + run: okWithKnownGatewayList, + runDocker, + runDualStationRuntimeCleanup, + }, + ); + + expect(result.exitCode).toBe(1); + expect(runDualStationRuntimeCleanup).not.toHaveBeenCalled(); + expect(runDocker).not.toHaveBeenCalled(); + expect(errors.join("\n")).toContain( + "Managed distributed vLLM state root is not a real directory", + ); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/actions/uninstall/run-plan.test.ts b/src/lib/actions/uninstall/run-plan.test.ts index 1eb4a92fc20..fd17027e974 100644 --- a/src/lib/actions/uninstall/run-plan.test.ts +++ b/src/lib/actions/uninstall/run-plan.test.ts @@ -1367,7 +1367,7 @@ describe("uninstall run plan", () => { } }); - it("removes ~/.nemoclaw wholesale when it is a symlink rather than a real directory", () => { + it("refuses to follow or remove ~/.nemoclaw when it is a symlink", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-preserve-")); const realTarget = fs.mkdtempSync( path.join(os.tmpdir(), "nemoclaw-uninstall-preserve-target-"), @@ -1379,12 +1379,14 @@ describe("uninstall run plan", () => { fs.writeFileSync(path.join(realTarget, "rebuild-backups"), "should not be followed"); try { const logs: string[] = []; + const errors: string[] = []; const result = runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: (command) => command === "openshell", env: { HOME: tmpHome } as NodeJS.ProcessEnv, existsSync: (target: string) => target.startsWith(tmpHome) && fs.existsSync(target), + error: (line) => errors.push(line), isTty: false, log: (line) => logs.push(line), run: vi.fn(okWithKnownGatewayList), @@ -1392,10 +1394,13 @@ describe("uninstall run plan", () => { }, ); - expect(result.exitCode).toBe(0); - expect(fs.existsSync(stateDir)).toBe(false); + expect(result.exitCode).toBe(1); + expect(fs.lstatSync(stateDir).isSymbolicLink()).toBe(true); expect(fs.existsSync(realTarget)).toBe(true); - expect(logs).toContain(`Removed ${stateDir}`); + expect(errors.join("\n")).toContain( + "Managed distributed vLLM state root is not a real directory", + ); + expect(logs).not.toContain(`Removed ${stateDir}`); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); fs.rmSync(realTarget, { recursive: true, force: true }); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 3bc2e74bbec..4f1a29f3ff9 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -261,6 +261,8 @@ const SHARED_HOST_STATE_ENTRIES = new Set([ DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, `${DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, `${DUAL_SPARK_MANAGED_SERVING_STATE_FILE}.ssh-binding`, + DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, + `${DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, MANAGED_VLLM_API_KEY_FILE, ...HTTPS_PIN_RUNTIME_ADAPTER_STATE_ENTRIES, ]); @@ -1233,19 +1235,31 @@ function dockerIsAvailable(runtime: UninstallRuntime): boolean { return true; } -function removeManagedDistributedVllmRuntime( +function managedDistributedVllmStateRootStatus( paths: UninstallPaths, - runtime: UninstallRuntime, -): boolean { + runtime: Pick, +): "absent" | "directory" | "unsafe" { const sharedRoot = path.dirname(paths.managedSwapMarkerPath); try { const root = fs.lstatSync(sharedRoot); - if (root.isSymbolicLink() || !root.isDirectory()) return true; + if (root.isSymbolicLink() || !root.isDirectory()) { + runtime.error(`Managed distributed vLLM state root is not a real directory: ${sharedRoot}`); + return "unsafe"; + } + return "directory"; } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; + if ((error as NodeJS.ErrnoException).code === "ENOENT") return "absent"; runtime.error(`Could not inspect managed distributed vLLM state root: ${formatError(error)}`); - return false; + return "unsafe"; } +} + +function removeManagedDistributedVllmRuntime( + paths: UninstallPaths, + runtime: UninstallRuntime, +): boolean { + const rootStatus = managedDistributedVllmStateRootStatus(paths, runtime); + if (rootStatus !== "directory") return rootStatus === "absent"; let state: ReturnType; try { state = findManagedDistributedVllmRuntimeReceipts({ @@ -1925,6 +1939,9 @@ export function runUninstallPlan( } const resolvedOptions = { ...options, gatewayName: expectedGatewayName }; const { paths, plan } = buildRunPlan(resolvedOptions, { ...deps, env: runtime.env }); + if (managedDistributedVllmStateRootStatus(paths, runtime) === "unsafe") { + return { exitCode: 1, plan }; + } let externallySupervised: boolean; try { externallySupervised = isExternallySupervised( diff --git a/src/lib/inference/local-vllm-auth.test.ts b/src/lib/inference/local-vllm-auth.test.ts index 39d25e8004f..8e559060c0d 100644 --- a/src/lib/inference/local-vllm-auth.test.ts +++ b/src/lib/inference/local-vllm-auth.test.ts @@ -155,6 +155,25 @@ describe("managed vLLM authentication", () => { expect(getManagedBaseUrlImpl).not.toHaveBeenCalled(); }); + it("fails URL and validation boundaries closed when managed recovery is unsafe", () => { + sparkRecovery.endpoint.mockImplementation(() => { + throw new Error("Spark receipt identity changed"); + }); + const capture = vi.fn(() => "200"); + + expect(getLocalProviderBaseUrl("vllm-local")).toBeNull(); + expect(getLocalProviderHealthEndpoint("vllm-local")).toBeNull(); + expect(getLocalProviderHealthCheck("vllm-local")).toBeNull(); + expect(getLocalProviderContainerReachabilityCheck("vllm-local")).toBeNull(); + expect(validateLocalProvider("vllm-local", capture)).toEqual({ + ok: false, + message: + "Managed vLLM state could not be inspected safely. Re-run `nemoclaw onboard` to repair the provider.", + }); + expect(capture).not.toHaveBeenCalled(); + expect(lifecycle.baseUrl).not.toHaveBeenCalled(); + }); + it("stops when Spark and Station managed state are both present", () => { expect(() => getManagedVllmProviderBinding({ diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index 478f9d5168a..baa111ac772 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -414,9 +414,20 @@ function configuredLocalInferenceHostUrl(hostUrl?: string | null): string | null ); } -function recoveredManagedVllmBaseUrl(): string | null { - if (configuredLocalInferenceHostUrl()) return null; - return getManagedVllmProviderBinding()?.baseUrl.replace(/\/v1\/?$/, "") ?? null; +type RecoveredManagedVllmBaseUrl = + | { readonly kind: "available"; readonly baseUrl: string | null } + | { readonly kind: "unavailable" }; + +function recoveredManagedVllmBaseUrl(): RecoveredManagedVllmBaseUrl { + if (configuredLocalInferenceHostUrl()) return { kind: "available", baseUrl: null }; + try { + return { + kind: "available", + baseUrl: getManagedVllmProviderBinding()?.baseUrl.replace(/\/v1\/?$/, "") ?? null, + }; + } catch { + return { kind: "unavailable" }; + } } export interface ManagedVllmProviderBinding { @@ -548,15 +559,6 @@ export function getManagedVllmProviderBinding( return { baseUrl: state.baseUrl, apiKey: state.apiKey }; } -export type ManagedDualStationVllmProviderBinding = ManagedVllmProviderBinding; -export type ManagedDualStationVllmProviderState = ManagedVllmProviderState; -export type ManagedDualStationVllmProviderBindingOptions = ManagedVllmProviderBindingOptions; - -/** @deprecated Use getManagedVllmProviderState. */ -export const getManagedDualStationVllmProviderState = getManagedVllmProviderState; -/** @deprecated Use getManagedVllmProviderBinding. */ -export const getManagedDualStationVllmProviderBinding = getManagedVllmProviderBinding; - export function getLocalProviderBaseUrl( provider: string, options: { hostUrl?: string | null } = {}, @@ -566,8 +568,9 @@ export function getLocalProviderBaseUrl( switch (provider) { case "vllm-local": { if (!configuredHostUrl) { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); - if (managedBaseUrl) return `${managedBaseUrl}/v1`; + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + if (managed.baseUrl) return `${managed.baseUrl}/v1`; } return `${hostUrl}:${VLLM_PORT}/v1`; } @@ -582,8 +585,9 @@ export function getLocalProviderBaseUrl( export function getLocalProviderValidationBaseUrl(provider: string): string | null { switch (provider) { case "vllm-local": { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); - return managedBaseUrl ? `${managedBaseUrl}/v1` : `http://127.0.0.1:${VLLM_PORT}/v1`; + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + return managed.baseUrl ? `${managed.baseUrl}/v1` : `http://127.0.0.1:${VLLM_PORT}/v1`; } case "ollama-local": return `http://${getResolvedOllamaHost()}:${OLLAMA_PORT}/v1`; @@ -595,9 +599,10 @@ export function getLocalProviderValidationBaseUrl(provider: string): string | nu export function getLocalProviderHealthEndpoint(provider: string): string | null { switch (provider) { case "vllm-local": { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); - return managedBaseUrl - ? `${managedBaseUrl}/v1/models` + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + return managed.baseUrl + ? `${managed.baseUrl}/v1/models` : `http://127.0.0.1:${VLLM_PORT}/v1/models`; } case "ollama-local": @@ -610,8 +615,10 @@ export function getLocalProviderHealthEndpoint(provider: string): string | null /** Lightweight endpoint used only to prove that the local service is reachable. */ export function getLocalProviderAvailabilityEndpoint(provider: string): string | null { if (provider === "vllm-local") { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); - if (managedBaseUrl) return `${managedBaseUrl}/health`; + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + if (managed.baseUrl) return `${managed.baseUrl}/health`; + return `http://127.0.0.1:${VLLM_PORT}/v1/models`; } return getLocalProviderHealthEndpoint(provider); } @@ -950,7 +957,9 @@ export function probeLocalProviderHealth( export function getLocalProviderContainerReachabilityCheck(provider: string): string[] | null { switch (provider) { case "vllm-local": { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + const managedBaseUrl = managed.baseUrl; return [ ...(managedBaseUrl ? ["docker", "--context", "default"] : ["docker"]), "run", @@ -1020,6 +1029,13 @@ export function validateLocalProvider( const sleep = sleepFn ?? sleepSeconds; const command = getLocalProviderHealthCheck(provider); if (!command) { + if (provider === "vllm-local") { + return { + ok: false, + message: + "Managed vLLM state could not be inspected safely. Re-run `nemoclaw onboard` to repair the provider.", + }; + } return { ok: true }; } @@ -1043,6 +1059,13 @@ export function validateLocalProvider( const containerCommand = getLocalProviderContainerReachabilityCheck(provider); if (!containerCommand) { + if (provider === "vllm-local") { + return { + ok: false, + message: + "Managed vLLM state could not be inspected safely. Re-run `nemoclaw onboard` to repair the provider.", + }; + } return { ok: true }; } @@ -1082,12 +1105,13 @@ export function validateLocalProvider( } } -function getContainerCheckUrl(provider: string): string { +function getContainerCheckUrl(provider: string): string | null { switch (provider) { case "vllm-local": { - const managedBaseUrl = recoveredManagedVllmBaseUrl(); - return managedBaseUrl - ? `${managedBaseUrl}/health` + const managed = recoveredManagedVllmBaseUrl(); + if (managed.kind === "unavailable") return null; + return managed.baseUrl + ? `${managed.baseUrl}/health` : `http://host.openshell.internal:${VLLM_PORT}/v1/models`; } case "ollama-local": @@ -1099,8 +1123,9 @@ function getContainerCheckUrl(provider: string): string { function collectContainerDiagnostic(provider: string, capture: RunCaptureFn): string { const url = getContainerCheckUrl(provider); + if (!url) return "Managed vLLM state could not be inspected safely."; const dockerCommand = - provider === "vllm-local" && recoveredManagedVllmBaseUrl() + provider === "vllm-local" && url.endsWith("/health") ? ["docker", "--context", "default"] : ["docker"]; try { diff --git a/src/lib/inference/serving/adapter-registry.test.ts b/src/lib/inference/serving/adapter-registry.test.ts index b2e6149843c..f5a9e799dfa 100644 --- a/src/lib/inference/serving/adapter-registry.test.ts +++ b/src/lib/inference/serving/adapter-registry.test.ts @@ -175,6 +175,24 @@ describe("managed inference adapter registries", () => { }, }, } as ManagedInferenceServingRecipe; + const shadowedCache = { + ...recipe, + spec: { + ...recipe.spec, + runtime: { + ...recipe.spec.runtime, + temporaryFilesystems: [ + ...recipe.spec.runtime.temporaryFilesystems, + { + target: "/cache", + sizeBytes: 1_073_741_824, + mode: "0700", + options: ["rw", "nosuid", "nodev"], + }, + ], + }, + }, + } as ManagedInferenceServingRecipe; expect(getManagedInferenceRecipeRegistrationError(unsupportedCache)).toMatch( /Hugging Face cache source/u, @@ -188,6 +206,9 @@ describe("managed inference adapter registries", () => { expect(getManagedInferenceRecipeRegistrationError(redundantPath)).toMatch( /normalized absolute/u, ); + expect(getManagedInferenceRecipeRegistrationError(shadowedCache)).toMatch( + /cannot shadow the model cache/u, + ); }); it("dispatches topology artifact validation through the registered descriptor", () => { @@ -196,11 +217,12 @@ describe("managed inference adapter registries", () => { artifact.id, artifact.schemaVersion, ); - expect(descriptor?.validateArtifact(artifact, artifact.subjectNodeIds)).toBeUndefined(); + expect(descriptor).toBeDefined(); + expect(descriptor!.validateArtifact(artifact, artifact.subjectNodeIds)).toBeUndefined(); const changed = structuredClone(artifact); (changed as { outputDigest: string }).outputDigest = `sha256:${"f".repeat(64)}`; - expect(descriptor?.validateArtifact(changed, artifact.subjectNodeIds)).toMatch(/digest/u); + expect(descriptor!.validateArtifact(changed, artifact.subjectNodeIds)).toMatch(/digest/u); }); it("keeps preparation inputs bounded without coupling them to a model ID", () => { diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index 209814db5e6..d9d34ed3395 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -19,6 +19,10 @@ export const NO_PREPARATION_REF = "none/v1" as const; export const DUAL_SPARK_HUGGING_FACE_CACHE_SOURCE = "huggingface-cache" as const; export const DUAL_SPARK_VLLM_MASTER_PORT = 25_000 as const; +export function containerPathContains(parent: string, child: string): boolean { + return child === parent || child.startsWith(`${parent}/`); +} + export interface ManagedInferenceTopologyQualificationDescriptor { readonly id: string; readonly schemaVersion: number; @@ -158,6 +162,13 @@ function validateDualSparkMaterializerRecipe( ) { return "dual-Spark runtime paths must be normalized absolute container paths"; } + if ( + recipe.spec.runtime.temporaryFilesystems.some(({ target }) => + containerPathContains(target, recipe.spec.runtime.modelCache.target), + ) + ) { + return "dual-Spark temporary filesystem cannot shadow the model cache"; + } const resourceValues = [ recipe.spec.model.downloadSizeBytes, recipe.spec.runtime.imageDownloadSizeBytes, diff --git a/src/lib/inference/serving/dual-spark-discovery.test.ts b/src/lib/inference/serving/dual-spark-discovery.test.ts index 503dea136c6..e9f04ba17b3 100644 --- a/src/lib/inference/serving/dual-spark-discovery.test.ts +++ b/src/lib/inference/serving/dual-spark-discovery.test.ts @@ -347,6 +347,26 @@ describe("dual DGX Spark managed-serving discovery", () => { expect(bindingWrites()).toBe(0); }); + it("fails closed when an explicit preset catalog cannot be loaded", () => { + const { deps, events, bindingWrites } = fixture({ + localTransport: () => { + throw new Error("must not probe"); + }, + }); + + expect( + probeDualSparkManagedServingCapability({ + env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_DUAL_SPARK_PRESET_ID }, + deps, + loadCatalog: () => { + throw new Error("catalog unavailable"); + }, + }), + ).toMatchObject({ kind: "unavailable", code: "incompatible-selection" }); + expect(events).toEqual([]); + expect(bindingWrites()).toBe(0); + }); + it("persists one binding only after the detected pair is confirmed and revalidated", () => { const { deps, events, bindingWrites } = fixture(); @@ -706,7 +726,7 @@ describe("production pinned peer transport", () => { expect(fs.readFileSync(path.join(bindingRoot, "owner"), "utf8")).toBe("first\n"); } finally { deps.clearBinding(statePath); - fs.rmdirSync(parent); + fs.rmSync(parent, { force: true, recursive: true }); } }); diff --git a/src/lib/inference/serving/dual-spark-discovery.ts b/src/lib/inference/serving/dual-spark-discovery.ts index 9bfac524b9c..4e8dfd56f72 100644 --- a/src/lib/inference/serving/dual-spark-discovery.ts +++ b/src/lib/inference/serving/dual-spark-discovery.ts @@ -245,6 +245,8 @@ export type DualSparkManagedServingConfirmation = export interface ProbeDualSparkManagedServingOptions { readonly env?: NodeJS.ProcessEnv; readonly deps?: DualSparkDiscoveryDeps; + /** @internal Catalog loader seam for fail-closed tests. */ + readonly loadCatalog?: typeof loadManagedInferenceCatalog; readonly bindingStatePath?: string; readonly maxReadinessAgeMs?: number; } @@ -344,11 +346,20 @@ function validatePeerTarget(raw: string): string { function selectionFromEnvironment( env: NodeJS.ProcessEnv, + loadCatalog: typeof loadManagedInferenceCatalog, ): Selection | DualSparkManagedServingCapability { const preset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); const peer = String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim(); if (preset) { - const catalog = loadManagedInferenceCatalog(); + let catalog; + try { + catalog = loadCatalog(); + } catch { + return unavailable( + "incompatible-selection", + "The selected managed inference preset catalog is unavailable.", + ); + } const compiledPreset = catalog.presets.find( ({ definition }) => definition.metadata.id === preset, ); @@ -956,7 +967,10 @@ function confirmationUnavailable( export function probeDualSparkManagedServingCapability( options: ProbeDualSparkManagedServingOptions = {}, ): DualSparkManagedServingCapability { - const selection = selectionFromEnvironment(options.env ?? process.env); + const selection = selectionFromEnvironment( + options.env ?? process.env, + options.loadCatalog ?? loadManagedInferenceCatalog, + ); if (!("strict" in selection)) return selection; const deps = options.deps ?? defaultDualSparkDiscoveryDeps; const opened: DualSparkPinnedPeerTransport[] = []; diff --git a/src/lib/inference/serving/dual-spark-installer.test.ts b/src/lib/inference/serving/dual-spark-installer.test.ts index 1413c8f2638..4fdf803a078 100644 --- a/src/lib/inference/serving/dual-spark-installer.test.ts +++ b/src/lib/inference/serving/dual-spark-installer.test.ts @@ -88,7 +88,11 @@ describe("two-Spark managed vLLM installer selection", () => { beforeEach(() => vi.restoreAllMocks()); it("leaves non-Spark and conflict-free explicit legacy vLLM intent untouched", async () => { - const probeCapability = vi.fn(); + const probeCapability = vi.fn(() => ({ + kind: "not-selected" as const, + code: "no-match" as const, + reason: "no related distributed runtime", + })); await expect( tryInstallDualSparkManagedVllm( { platform: "station", nonInteractive: true, promptFn: vi.fn() }, @@ -105,16 +109,10 @@ describe("two-Spark managed vLLM installer selection", () => { promptFn: vi.fn(), }, effects(), - { - probeCapability: () => ({ - kind: "not-selected", - code: "no-match", - reason: "no related distributed runtime", - }), - }, + { probeCapability }, ), ).resolves.toEqual({ kind: "not-selected" }); - expect(probeCapability).not.toHaveBeenCalled(); + expect(probeCapability).toHaveBeenCalledOnce(); }); it("does not let explicit legacy intent bypass a related-runtime conflict", async () => { diff --git a/src/lib/inference/serving/dual-spark-materialize.test.ts b/src/lib/inference/serving/dual-spark-materialize.test.ts index 598a3b5448e..a5dcd7cad3c 100644 --- a/src/lib/inference/serving/dual-spark-materialize.test.ts +++ b/src/lib/inference/serving/dual-spark-materialize.test.ts @@ -41,7 +41,7 @@ function selectionWithDigests(): ResolvedManagedInferenceSelection { ); expect(originalFromExpandedCatalog.planId).toBe(originalPlan.planId); }); + + it("rejects a temporary filesystem that shadows the model cache", () => { + const { catalog, selection } = syntheticSecondProfile("/models"); + + expect(() => materializeDualSparkVllmPlan(selection, { catalog })).toThrow( + /temporary filesystem cannot shadow the model cache/u, + ); + }); }); diff --git a/src/lib/inference/serving/dual-spark-materialize.ts b/src/lib/inference/serving/dual-spark-materialize.ts index e79ae7e56e8..8339c57f7ab 100644 --- a/src/lib/inference/serving/dual-spark-materialize.ts +++ b/src/lib/inference/serving/dual-spark-materialize.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { + containerPathContains, DUAL_SPARK_VLLM_MASTER_PORT, DUAL_SPARK_VLLM_MATERIALIZER_REF, getManagedInferenceLifecycleDescriptor, @@ -368,6 +369,7 @@ function assertRecipeValues(recipe: ManagedInferenceServingRecipe): void { if ( temporaryTargets.has(temporaryFilesystem.target) || !safeAbsolutePath(temporaryFilesystem.target) || + containerPathContains(temporaryFilesystem.target, runtime.modelCache.target) || !positiveSafeInteger(temporaryFilesystem.sizeBytes) || !/^[0-7]{4}$/u.test(temporaryFilesystem.mode) || temporaryFilesystem.options.length > 8 || diff --git a/src/lib/inference/serving/dual-spark-topology.test.ts b/src/lib/inference/serving/dual-spark-topology.test.ts index f7269809e67..f81267f6a88 100644 --- a/src/lib/inference/serving/dual-spark-topology.test.ts +++ b/src/lib/inference/serving/dual-spark-topology.test.ts @@ -399,10 +399,19 @@ describe("dual DGX Spark topology qualification", () => { }); }); - it("rejects a peer without an opaque pretrusted SSH binding", () => { + it("rejects a peer whose SSH binding state is not trusted", () => { const input = qualificationInput(); input.peers[0]!.sshBinding.state = "untrusted"; - input.peers[0]!.sshBinding.handle = "not-an-opaque-binding"; + + expect(qualifyDualSparkTopology(input)).toMatchObject({ + outcome: "no-match", + code: "ssh-binding-unavailable", + }); + }); + + it("rejects a peer whose trusted SSH binding handle is empty", () => { + const input = qualificationInput(); + input.peers[0]!.sshBinding.handle = " "; expect(qualifyDualSparkTopology(input)).toMatchObject({ outcome: "no-match", diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index b4cf2633e3a..15811557221 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -511,10 +511,10 @@ describe("managed inference resolver", () => { }); it.each([ - { provider: "vllm" }, - { vllmModel: "another/model" }, - { vllmExtraArguments: ["--another-option"] }, - ])("leaves existing inference intent authoritative for automatic selection", (intent) => { + { name: "provider", intent: { provider: "vllm" } }, + { name: "model", intent: { vllmModel: "another/model" } }, + { name: "extra arguments", intent: { vllmExtraArguments: ["--another-option"] } }, + ])("leaves existing $name intent authoritative for automatic selection", ({ intent }) => { expect( resolveManagedInferenceServing({ readinessReports: [], diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts index a1a74ef0bf8..86db3a53be3 100644 --- a/src/lib/inference/serving/spark-runtime-receipt.ts +++ b/src/lib/inference/serving/spark-runtime-receipt.ts @@ -323,13 +323,20 @@ function writeReceipt(receipt: PersistedReceipt, stateDir: string): void { fd = undefined; fs.renameSync(temporary, filePath); fsyncDirectory(stateDir); - } finally { - if (fd !== undefined) fs.closeSync(fd); + } catch (error) { + if (fd !== undefined) { + try { + fs.closeSync(fd); + } catch { + // Preserve the receipt-write failure. + } + } try { fs.unlinkSync(temporary); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } catch { + // A leftover unique temporary file must not mask the receipt-write failure. } + throw error; } } diff --git a/src/lib/inference/vllm-dual-station.test.ts b/src/lib/inference/vllm-dual-station.test.ts index b735ff30d17..3ac7a00c2b5 100644 --- a/src/lib/inference/vllm-dual-station.test.ts +++ b/src/lib/inference/vllm-dual-station.test.ts @@ -103,11 +103,7 @@ vi.mock("./vllm-api-key", () => ({ managedVllmStateDir: () => path.join(os.homedir(), ".nemoclaw"), })); -import { - detectVllmProfile, - installVllm, - persistConfiguredDualStationVllmRuntimeReceipt, -} from "./vllm"; +import { detectVllmProfile, installVllm, persistConfiguredManagedVllmRuntimeReceipt } from "./vllm"; import { DUAL_STATION_VLLM_RUNTIME, type DualStationVllmPlan } from "./vllm-station-cluster"; import { createDualStationSshBindingFixture, @@ -307,7 +303,7 @@ afterEach(() => { describe("dual DGX Station running-runtime receipt adoption", () => { it("persists cleanup ownership for the exact configured running pair", async () => { - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: true, persisted: true, }); @@ -324,7 +320,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { reason: "worker ownership changed", }); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "worker ownership changed", }); @@ -334,7 +330,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { it("fails closed when the managed peer configuration is missing", async () => { delete process.env.NEMOCLAW_DGX_STATION_PEER; - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "the managed dual-Station peer configuration is missing", }); diff --git a/src/lib/inference/vllm-managed-recovery.test.ts b/src/lib/inference/vllm-managed-recovery.test.ts index 1129f06b4af..709620c7bd9 100644 --- a/src/lib/inference/vllm-managed-recovery.test.ts +++ b/src/lib/inference/vllm-managed-recovery.test.ts @@ -10,11 +10,7 @@ vi.mock("./serving/spark-runtime-receipt", async (importOriginal) => ({ recoverInstalledDualSparkVllmEndpoint: sparkRecovery.endpoint, })); -import { - isNemoClawManagedVllmRunning, - persistConfiguredDualStationVllmRuntimeReceipt, - persistConfiguredManagedVllmRuntimeReceipt, -} from "./vllm"; +import { isNemoClawManagedVllmRunning, persistConfiguredManagedVllmRuntimeReceipt } from "./vllm"; describe("managed vLLM Spark recovery", () => { beforeEach(() => { @@ -32,10 +28,6 @@ describe("managed vLLM Spark recovery", () => { ok: true, persisted: true, }); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ - ok: true, - persisted: true, - }); }); it("fails closed instead of falling through when Spark receipt recovery is unsafe", async () => { @@ -43,6 +35,7 @@ describe("managed vLLM Spark recovery", () => { throw new Error("receipt-owned container IDs changed"); }); + expect(isNemoClawManagedVllmRunning()).toBe(false); await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "managed vLLM recovery failed: receipt-owned container IDs changed", diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-spark-runtime-receipt.test.ts index cb2dc5b399a..d4f3f745a22 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-spark-runtime-receipt.test.ts @@ -7,6 +7,9 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { fixtureDualSparkSelection } from "./serving/dual-spark-fixture.test-support"; +import { loadManagedInferenceCatalog } from "./serving/catalog"; +import { managedInferenceDigest } from "./serving/catalog-integrity"; +import type { CompiledManagedInferenceCatalog } from "./serving/catalog-types"; import { type DualSparkNodeSnapshot, type DualSparkVllmLifecycleDeps, @@ -57,6 +60,7 @@ beforeEach(() => { afterEach(() => { vi.unstubAllEnvs(); + vi.doUnmock("./serving/generated/catalog.json"); vi.resetModules(); sshFixture.cleanup(); fs.rmSync(root, { recursive: true, force: true }); @@ -96,6 +100,61 @@ function input( }; } +function catalogWithUnrelatedProfile(): CompiledManagedInferenceCatalog { + const current = loadManagedInferenceCatalog(); + const selectedPreset = current.presets[0]!; + const selectedRecipe = current.recipes[0]!; + const unrelatedRecipe = { + ...selectedRecipe.definition, + metadata: { ...selectedRecipe.definition.metadata, id: "vllm.unrelated.spark-dual.v1" }, + }; + const unrelatedPreset = { + ...selectedPreset.definition, + metadata: { ...selectedPreset.definition.metadata, id: "vllm.unrelated.spark-dual" }, + spec: { + ...selectedPreset.definition.spec, + plan: { + ...selectedPreset.definition.spec.plan, + recipeRef: unrelatedRecipe.metadata.id, + }, + }, + }; + const sourceFiles = [ + ...current.sourceFiles, + { + path: "managed-inference/presets/vllm.unrelated.spark-dual.yaml", + digest: `sha256:${"1".repeat(64)}`, + }, + { + path: "managed-inference/recipes/vllm.unrelated.spark-dual.v1.yaml", + digest: `sha256:${"2".repeat(64)}`, + }, + ] as const; + const contents = { + compilerVersion: current.compilerVersion, + presets: [ + ...current.presets, + { + definition: unrelatedPreset, + definitionDigest: managedInferenceDigest(unrelatedPreset), + sourceFile: sourceFiles.at(-2)!.path, + }, + ], + recipes: [ + ...current.recipes, + { + definition: unrelatedRecipe, + definitionDigest: managedInferenceDigest(unrelatedRecipe), + sourceFile: sourceFiles.at(-1)!.path, + }, + ], + schemaVersion: current.schemaVersion, + sourceFiles, + sourceRevision: managedInferenceDigest(sourceFiles), + } as const; + return { ...contents, catalogDigest: managedInferenceDigest(contents) }; +} + function persistWithDiscoveryBinding(): { discoveryBindingPath: string; discoveryStatePath: string; @@ -200,23 +259,44 @@ describe("dual-Spark vLLM runtime receipt", () => { expect(fs.readFileSync(receiptPath, "utf8")).toBe(original); }); - it("keeps a selected profile receipt valid when unrelated catalog entries change", () => { + it("keeps a selected profile receipt valid when unrelated catalog entries change", async () => { const source = input(); - const previousCatalogPlan = { - ...source.plan, - catalogDigest: `sha256:${"e".repeat(64)}`, - }; + const currentCatalog = loadManagedInferenceCatalog(); + const changedCatalog = catalogWithUnrelatedProfile(); + persistDualSparkVllmRuntimeReceipt(source, { stateDir }); - const runtime = persistDualSparkVllmRuntimeReceipt( - { ...source, plan: previousCatalogPlan }, - { stateDir }, + expect(changedCatalog.catalogDigest).not.toBe(currentCatalog.catalogDigest); + vi.doMock("./serving/generated/catalog.json", () => ({ default: changedCatalog })); + vi.resetModules(); + const { loadDualSparkVllmRuntimeReceipt: loadAgainstChangedCatalog } = await import( + "./serving/spark-runtime-receipt" + ); + const loaded = loadAgainstChangedCatalog({ stateDir }); + const currentPreset = changedCatalog.presets.find( + ({ definition }) => definition.metadata.id === source.plan.presetId, + ); + const currentRecipe = changedCatalog.recipes.find( + ({ definition }) => definition.metadata.id === source.plan.recipeId, ); - const loaded = loadDualSparkVllmRuntimeReceipt({ stateDir }); - expect(loaded?.plan.catalogDigest).toBe(previousCatalogPlan.catalogDigest); - expect(loaded?.plan.planId).toBe(previousCatalogPlan.planId); - expect(runtime.plan.presetDigest).toBe(source.plan.presetDigest); - expect(runtime.plan.recipeDigest).toBe(source.plan.recipeDigest); + expect(loaded?.plan.catalogDigest).toBe(currentCatalog.catalogDigest); + expect(loaded?.plan.presetDigest).toBe(currentPreset?.definitionDigest); + expect(loaded?.plan.recipeDigest).toBe(currentRecipe?.definitionDigest); + }); + + it("preserves a receipt-write failure when temporary-file cleanup also fails", () => { + const rename = vi.spyOn(fs, "renameSync").mockImplementationOnce(() => { + throw new Error("receipt rename failed"); + }); + const unlink = vi.spyOn(fs, "unlinkSync").mockImplementationOnce(() => { + throw new Error("temporary cleanup failed"); + }); + + expect(() => persistDualSparkVllmRuntimeReceipt(input(), { stateDir })).toThrow( + "receipt rename failed", + ); + expect(rename).toHaveBeenCalledOnce(); + expect(unlink).toHaveBeenCalledOnce(); }); it("refuses a pre-existing SSH binding tree without mutating it", () => { diff --git a/src/lib/inference/vllm-station-cluster-lifecycle.test.ts b/src/lib/inference/vllm-station-cluster-lifecycle.test.ts index 97d7ea907a0..32433e579de 100644 --- a/src/lib/inference/vllm-station-cluster-lifecycle.test.ts +++ b/src/lib/inference/vllm-station-cluster-lifecycle.test.ts @@ -469,24 +469,24 @@ describe("dual-Station managed vLLM lifecycle", () => { expect(fake.operations).toEqual([]); }); - it("anchors the default lock under the effective account home instead of mutable HOME", async () => { + it("anchors the default lock under the host-global managed state home", async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-station-lock-home-")); const accountHome = path.join(root, "account-home"); - const ambientHome = path.join(root, "ambient-home"); + const managedHome = path.join(root, "managed-home"); fs.mkdirSync(accountHome, { mode: 0o700 }); const userInfo = os.userInfo(); const userInfoSpy = vi.spyOn(os, "userInfo").mockReturnValue({ ...userInfo, homedir: accountHome, }); - vi.stubEnv("HOME", ambientHome); + vi.stubEnv("HOME", managedHome); try { await withDualStationVllmLifecycleLock( () => { expect( - fs.existsSync(path.join(accountHome, ".nemoclaw", "state", "mcp-lifecycle-locks")), + fs.existsSync(path.join(managedHome, ".nemoclaw", "state", "mcp-lifecycle-locks")), ).toBe(true); - expect(fs.existsSync(ambientHome)).toBe(false); + expect(fs.existsSync(path.join(accountHome, ".nemoclaw"))).toBe(false); }, { pollIntervalMs: 5, timeoutMs: 250, corruptLockGraceMs: 5 }, { diff --git a/src/lib/inference/vllm-station-lifecycle-lock.test.ts b/src/lib/inference/vllm-station-lifecycle-lock.test.ts index 56d3765db38..0b2120a79ea 100644 --- a/src/lib/inference/vllm-station-lifecycle-lock.test.ts +++ b/src/lib/inference/vllm-station-lifecycle-lock.test.ts @@ -12,6 +12,7 @@ import { withDualStationVllmLifecycleLock, withHostGlobalVllmLifecycleLock, } from "./vllm-station-lifecycle-lock"; +import { managedVllmStateDir } from "./vllm-api-key"; function controllerUidStat( kind: "directory" | "file", @@ -115,26 +116,32 @@ describe("dual-Station controller UID binding", () => { } }); - it("shares the host-global vLLM lock without requiring Station host preparation", async () => { + it("shares the managed-state home even when passwd and HOME directories differ", async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-vllm-lock-")); - const accountHome = path.join(root, "account-home"); - fs.mkdirSync(accountHome, { mode: 0o700 }); + const passwdHome = path.join(root, "passwd-home"); + const managedHome = path.join(root, "managed-home"); + fs.mkdirSync(passwdHome, { mode: 0o700 }); + fs.mkdirSync(managedHome, { mode: 0o700 }); const userInfo = os.userInfo(); const userInfoSpy = vi.spyOn(os, "userInfo").mockReturnValue({ ...userInfo, - homedir: accountHome, + homedir: passwdHome, }); + vi.stubEnv("HOME", managedHome); try { + expect(managedVllmStateDir()).toBe(path.join(managedHome, ".nemoclaw")); await withHostGlobalVllmLifecycleLock( () => { expect( - fs.existsSync(path.join(accountHome, ".nemoclaw", "state", "mcp-lifecycle-locks")), + fs.existsSync(path.join(managedHome, ".nemoclaw", "state", "mcp-lifecycle-locks")), ).toBe(true); + expect(fs.existsSync(path.join(passwdHome, ".nemoclaw"))).toBe(false); }, { pollIntervalMs: 5, timeoutMs: 250, corruptLockGraceMs: 5 }, ); } finally { + vi.unstubAllEnvs(); userInfoSpy.mockRestore(); fs.rmSync(root, { recursive: true, force: true }); } diff --git a/src/lib/inference/vllm-station-lifecycle-lock.ts b/src/lib/inference/vllm-station-lifecycle-lock.ts index b706c11d912..ab25ec9120e 100644 --- a/src/lib/inference/vllm-station-lifecycle-lock.ts +++ b/src/lib/inference/vllm-station-lifecycle-lock.ts @@ -2,11 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { type McpLifecycleLockOptions, withMcpLifecycleLock } from "../state/mcp-lifecycle-lock"; -import { STATE_DIR_NAME } from "../state/state-root"; +import { managedVllmStateDir } from "./vllm-api-key"; const HOST_GLOBAL_VLLM_LIFECYCLE_LOCK = "dual-station-vllm:host-global"; const DUAL_STATION_CONTROLLER_CONFIG_DIR = "/etc/nemoclaw"; @@ -130,7 +129,7 @@ export function withHostGlobalVllmLifecycleLock( operation: () => Promise | T, options: McpLifecycleLockOptions = {}, ): Promise { - const stateDir = options.stateDir ?? path.join(os.userInfo().homedir, STATE_DIR_NAME, "state"); + const stateDir = options.stateDir ?? path.join(managedVllmStateDir(), "state"); return withMcpLifecycleLock(HOST_GLOBAL_VLLM_LIFECYCLE_LOCK, operation, { ...options, stateDir, @@ -141,9 +140,9 @@ export function withHostGlobalVllmLifecycleLock( * Serialize the host-managed dual-Station service across gateway instances. * * Dual-Station lifecycle supports one effective controller account per host. - * This anchors every supported caller at that account's passwd home instead of - * mutable HOME or a gateway-specific root. Host preparation binds that account - * in root-owned state before the lease can be acquired. + * This anchors every supported caller at the same host-global state root used + * by managed vLLM receipts and credentials. Host preparation binds the + * controller account in root-owned state before the lease can be acquired. */ export function withDualStationVllmLifecycleLock( operation: () => Promise | T, diff --git a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts index 6950706e47d..39d5a03939e 100644 --- a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts +++ b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts @@ -67,7 +67,9 @@ async function main(): Promise { throw new Error("the requested dual-Spark runtime receipt was not removed"); } console.log( - `Removed managed dual-Spark vLLM containers: ${spark.removedContainerIds.join(", ")}`, + spark.removedContainerIds.length > 0 + ? `Removed managed dual-Spark vLLM containers: ${spark.removedContainerIds.join(", ")}` + : "Removed managed dual-Spark vLLM state; no receipt-owned containers remained.", ); return; } @@ -77,7 +79,9 @@ async function main(): Promise { throw new Error("the requested dual-Station runtime receipt was not removed"); } console.log( - `Removed managed dual-Station vLLM containers: ${station.removedContainerIds.join(", ")}`, + station.removedContainerIds.length > 0 + ? `Removed managed dual-Station vLLM containers: ${station.removedContainerIds.join(", ")}` + : "Removed managed dual-Station vLLM state; no receipt-owned containers remained.", ); } diff --git a/src/lib/inference/vllm.ts b/src/lib/inference/vllm.ts index e4869c295e7..bc5403fa3c3 100644 --- a/src/lib/inference/vllm.ts +++ b/src/lib/inference/vllm.ts @@ -894,7 +894,11 @@ function vllmContainerReplacementTarget( } export function isNemoClawManagedVllmRunning(): boolean { - if (recoverInstalledDualSparkVllmEndpoint()) return true; + try { + if (recoverInstalledDualSparkVllmEndpoint()) return true; + } catch { + return false; + } const ownership = inspectVllmContainerOwnership(NEMOCLAW_VLLM_CONTAINER_NAME); return (ownership.kind === "managed" || ownership.kind === "dual-managed") && ownership.running; } @@ -903,9 +907,6 @@ export type PersistConfiguredManagedVllmRuntimeResult = | { ok: true; persisted: boolean } | { ok: false; reason: string }; -export type PersistConfiguredDualStationVllmRuntimeResult = - PersistConfiguredManagedVllmRuntimeResult; - /** * Confirm an installer-owned receipt or adopt an already-running Station pair * after onboarding has authenticated and validated its endpoint. @@ -959,10 +960,6 @@ export async function persistConfiguredManagedVllmRuntimeReceipt(): Promise SUPPORTED_WINDOWS_OLLAMA), detectVllmProfile: vi.fn(() => null), + getLocalProviderAvailabilityEndpoint: vi.fn(() => "http://127.0.0.1:8000/v1/models"), ...overrides, }; } @@ -160,6 +161,24 @@ describe("detectInferenceProviderHostState", () => { expect(state.vllmRunning).toBe(false); }); + it("fails the vLLM running probe closed when managed endpoint resolution fails", () => { + const runCapture = vi.fn(() => "200"); + const state = detectWithDeps( + buildDeps({ + runCapture, + getLocalProviderAvailabilityEndpoint: () => { + throw new Error("managed state unavailable"); + }, + }), + ); + + expect(state.vllmRunning).toBe(false); + expect(runCapture).not.toHaveBeenCalledWith( + expect.arrayContaining([expect.stringContaining("8000")]), + expect.anything(), + ); + }); + it("detects a reachable Windows-host Ollama beside WSL-local Ollama and warns outside mirrored networking", () => { const logs: string[] = []; const deps = buildDeps({ diff --git a/src/lib/onboard/provider-host-state.ts b/src/lib/onboard/provider-host-state.ts index 4a41d5a8f8d..5134774bb4e 100644 --- a/src/lib/onboard/provider-host-state.ts +++ b/src/lib/onboard/provider-host-state.ts @@ -85,6 +85,7 @@ export interface DetectInferenceProviderHostStateDeps { runtime: ContainerRuntime | null, ) => WindowsHostOllamaDockerRequirement; detectVllmProfile: (gpu: InferenceProviderHostGpu | null | undefined) => VllmProfile | null; + getLocalProviderAvailabilityEndpoint: (provider: string) => string | null; } const LOCAL_PROVIDER_PROBE_CURL_ARGS = ["--connect-timeout", "2", "--max-time", "5"] as const; @@ -113,16 +114,23 @@ function buildDeps( detectVllmProfile: overrides.detectVllmProfile ?? ((gpu) => detectVllmProfile(gpu as Parameters[0])), + getLocalProviderAvailabilityEndpoint: + overrides.getLocalProviderAvailabilityEndpoint ?? getLocalProviderAvailabilityEndpoint, }; } -function probeVllmRunning(runCapture: RunCapture): boolean { - const endpoint = getLocalProviderAvailabilityEndpoint("vllm-local"); +function probeVllmRunning(deps: DetectInferenceProviderHostStateDeps): boolean { + let endpoint: string | null; + try { + endpoint = deps.getLocalProviderAvailabilityEndpoint("vllm-local"); + } catch { + return false; + } if (!endpoint) return false; const writeOut = endpoint.endsWith("/health") ? ["--noproxy", "*", "--write-out", "%{http_code}"] : []; - const output = runCapture( + const output = deps.runCapture( ["curl", "-sf", ...LOCAL_PROVIDER_PROBE_CURL_ARGS, ...writeOut, endpoint], { ignoreError: true, @@ -179,7 +187,7 @@ export function detectInferenceProviderHostState( const ollamaHost = input.probeOllama === false ? null : deps.findReachableOllamaHost(); const ollamaRunning = ollamaHost !== null; const isWindowsHostOllama = ollamaHost === OLLAMA_HOST_DOCKER_INTERNAL; - const vllmRunning = input.probeVllm === false ? false : probeVllmRunning(deps.runCapture); + const vllmRunning = input.probeVllm === false ? false : probeVllmRunning(deps); const vllmProfile = deps.detectVllmProfile(input.gpu); const hasVllmImage = !!( vllmProfile && diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index b121c4ae414..3b06ac20ee3 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -342,6 +342,7 @@ describe("managed inference catalog compiler", () => { }, }, }); + expect(revisionIndex).toBeGreaterThanOrEqual(0); expect(plan.roles.head.command.arguments[revisionIndex + 1]).toBe( "1111111111111111111111111111111111111111", ); From 7013fc8fb88bcc9cf61e1cc72e732c5ab84ff019 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 14:57:29 -0700 Subject: [PATCH 13/27] test(uninstall): keep unsafe-root cases linear Signed-off-by: Aaron Erickson --- .../uninstall/run-plan-dual-station.test.ts | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index a4cc771a7c8..b70424a454d 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -405,18 +405,24 @@ describe("managed distributed vLLM runtime uninstall", () => { }); it.each([ - "symbolic link", - "regular file", - ])("fails closed when the host-global managed state root is a %s", (shape) => { + { + shape: "symbolic link", + arrange: (stateDir: string, home: string) => { + const target = path.join(home, "redirected-state"); + fs.mkdirSync(target, { mode: 0o700 }); + fs.symlinkSync(target, stateDir, "dir"); + }, + }, + { + shape: "regular file", + arrange: (stateDir: string) => { + fs.writeFileSync(stateDir, "not a directory\n", { mode: 0o600 }); + }, + }, + ])("fails closed when the host-global managed state root is a $shape", ({ arrange }) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-unsafe-root-")); const stateDir = path.join(home, ".nemoclaw"); - if (shape === "symbolic link") { - const target = path.join(home, "redirected-state"); - fs.mkdirSync(target, { mode: 0o700 }); - fs.symlinkSync(target, stateDir, "dir"); - } else { - fs.writeFileSync(stateDir, "not a directory\n", { mode: 0o600 }); - } + arrange(stateDir, home); const errors: string[] = []; const runDualStationRuntimeCleanup = vi.fn(() => ok()); const runDocker = vi.fn(() => ok()); From 5c7161418bd5791a10d0c4207eae39ab3d5a01b4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 15:03:21 -0700 Subject: [PATCH 14/27] fix(mcp): refresh reviewed runtime audit pins Signed-off-by: Aaron Erickson --- .../package-lock.json | 18 +++++++++--------- tools/mcp-tool-discovery-runtime/package.json | 4 +++- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/tools/mcp-tool-discovery-runtime/package-lock.json b/tools/mcp-tool-discovery-runtime/package-lock.json index f5cc6c8aea8..192c1694a38 100644 --- a/tools/mcp-tool-discovery-runtime/package-lock.json +++ b/tools/mcp-tool-discovery-runtime/package-lock.json @@ -947,9 +947,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", - "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", + "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", "funding": [ { "type": "github", @@ -1084,9 +1084,9 @@ } }, "node_modules/hono": { - "version": "4.12.30", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.30.tgz", - "integrity": "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==", + "version": "4.12.34", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.34.tgz", + "integrity": "sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -1135,9 +1135,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", - "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz", + "integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==", "license": "MIT", "engines": { "node": ">= 12" diff --git a/tools/mcp-tool-discovery-runtime/package.json b/tools/mcp-tool-discovery-runtime/package.json index 73aa3261835..d8e5569f426 100644 --- a/tools/mcp-tool-discovery-runtime/package.json +++ b/tools/mcp-tool-discovery-runtime/package.json @@ -16,7 +16,9 @@ }, "overrides": { "@hono/node-server": "2.0.11", - "fast-uri": "3.1.4" + "fast-uri": "3.1.5", + "hono": "4.12.34", + "ip-address": "10.4.0" }, "engines": { "node": ">=22.19.0" From 475f5bdaaa5a352e04364281d23edb950611fde6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 16:34:48 -0700 Subject: [PATCH 15/27] refactor(inference): make managed clusters cardinality-driven Signed-off-by: Aaron Erickson --- .../set-up-vllm-on-two-dgx-sparks.mdx | 50 +- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 26 +- docs/reference/host-files-and-state.mdx | 6 +- ...park-gb10.dual.deepseek-v4-flash-0731.yaml | 4 +- ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 9 +- managed-inference/schemas/recipe.schema.json | 5 +- scripts/install.sh | 4 +- .../uninstall/run-plan-dual-station.test.ts | 55 +- .../run-plan-gateway-segregation.test.ts | 9 +- src/lib/actions/uninstall/run-plan.ts | 68 +- src/lib/inference/local-vllm-auth.test.ts | 40 +- src/lib/inference/local.ts | 63 +- .../serving/adapter-registry.test.ts | 38 +- src/lib/inference/serving/adapter-registry.ts | 141 +-- src/lib/inference/serving/catalog-types.ts | 1 + .../dual-spark-fixture.test-support.ts | 109 --- .../inference/serving/dual-spark-topology.ts | 754 --------------- ...> managed-cluster-discovery-production.ts} | 76 +- ...t.ts => managed-cluster-discovery.test.ts} | 208 +++-- ...covery.ts => managed-cluster-discovery.ts} | 823 ++++++++-------- ...st.ts => managed-cluster-executor.test.ts} | 358 ++++--- ...xecutor.ts => managed-cluster-executor.ts} | 380 ++++---- .../managed-cluster-fixture.test-support.ts | 121 +++ ...t.ts => managed-cluster-installer.test.ts} | 225 +++-- ...taller.ts => managed-cluster-installer.ts} | 317 ++++--- ...t.ts => managed-cluster-lifecycle.test.ts} | 146 +-- ...ecycle.ts => managed-cluster-lifecycle.ts} | 561 +++++------ ...ts => managed-cluster-materialize.test.ts} | 193 ++-- ...lize.ts => managed-cluster-materialize.ts} | 266 +++--- ...ts => managed-cluster-preparation.test.ts} | 10 +- ...tion.ts => managed-cluster-preparation.ts} | 16 +- .../managed-cluster-runtime-receipt-path.ts | 22 + .../managed-cluster-runtime-receipt.ts | 723 ++++++++++++++ ...st.ts => managed-cluster-topology.test.ts} | 229 +++-- .../serving/managed-cluster-topology.ts | 880 ++++++++++++++++++ .../serving/managed-runtime-receipts.ts | 70 +- src/lib/inference/serving/resolver.test.ts | 26 +- .../serving/spark-runtime-receipt-path.ts | 5 - .../serving/spark-runtime-receipt.ts | 588 ------------ .../inference/serving/vllm-managed-support.ts | 4 +- src/lib/inference/vllm-api-key.ts | 2 +- ...m-managed-cluster-runtime-receipt.test.ts} | 294 +++--- .../inference/vllm-managed-recovery.test.ts | 20 +- .../vllm-managed-runtime-receipts.test.ts | 59 +- .../vllm-station-runtime-cleanup-entry.ts | 34 +- src/lib/inference/vllm.ts | 12 +- test/install-express-prompt.test.ts | 2 +- ...managed-inference-catalog-compiler.test.ts | 68 +- 48 files changed, 4543 insertions(+), 3577 deletions(-) delete mode 100644 src/lib/inference/serving/dual-spark-fixture.test-support.ts delete mode 100644 src/lib/inference/serving/dual-spark-topology.ts rename src/lib/inference/serving/{dual-spark-discovery-production.ts => managed-cluster-discovery-production.ts} (95%) rename src/lib/inference/serving/{dual-spark-discovery.test.ts => managed-cluster-discovery.test.ts} (79%) rename src/lib/inference/serving/{dual-spark-discovery.ts => managed-cluster-discovery.ts} (56%) rename src/lib/inference/serving/{dual-spark-executor.test.ts => managed-cluster-executor.test.ts} (66%) rename src/lib/inference/serving/{dual-spark-executor.ts => managed-cluster-executor.ts} (75%) create mode 100644 src/lib/inference/serving/managed-cluster-fixture.test-support.ts rename src/lib/inference/serving/{dual-spark-installer.test.ts => managed-cluster-installer.test.ts} (76%) rename src/lib/inference/serving/{dual-spark-installer.ts => managed-cluster-installer.ts} (62%) rename src/lib/inference/serving/{dual-spark-lifecycle.test.ts => managed-cluster-lifecycle.test.ts} (73%) rename src/lib/inference/serving/{dual-spark-lifecycle.ts => managed-cluster-lifecycle.ts} (51%) rename src/lib/inference/serving/{dual-spark-materialize.test.ts => managed-cluster-materialize.test.ts} (67%) rename src/lib/inference/serving/{dual-spark-materialize.ts => managed-cluster-materialize.ts} (73%) rename src/lib/inference/serving/{dual-spark-preparation.test.ts => managed-cluster-preparation.test.ts} (90%) rename src/lib/inference/serving/{dual-spark-preparation.ts => managed-cluster-preparation.ts} (93%) create mode 100644 src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts create mode 100644 src/lib/inference/serving/managed-cluster-runtime-receipt.ts rename src/lib/inference/serving/{dual-spark-topology.test.ts => managed-cluster-topology.test.ts} (61%) create mode 100644 src/lib/inference/serving/managed-cluster-topology.ts delete mode 100644 src/lib/inference/serving/spark-runtime-receipt-path.ts delete mode 100644 src/lib/inference/serving/spark-runtime-receipt.ts rename src/lib/inference/{vllm-spark-runtime-receipt.test.ts => vllm-managed-cluster-runtime-receipt.test.ts} (59%) diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx index 348247be7bc..b4a41c5d905 100644 --- a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -4,7 +4,7 @@ title: "Set Up vLLM on Two DGX Sparks" sidebar-title: "Set Up vLLM on Two DGX Sparks" description: "Qualify two trusted DGX Spark systems and start NemoClaw's Experimental distributed DeepSeek V4 Flash vLLM profile." -description-agent: "Sets up the Experimental managed vLLM profile for two DGX Spark systems, including selection, qualification, runtime ownership, and cleanup. Use when configuring NEMOCLAW_DGX_SPARK_PEER or NEMOCLAW_SERVING_PRESET." +description-agent: "Sets up the Experimental managed vLLM profile for two DGX Spark systems, including selection, qualification, runtime ownership, and cleanup. Use when configuring NEMOCLAW_MANAGED_CLUSTER_PEERS or NEMOCLAW_SERVING_PRESET." keywords: ["nemoclaw dual dgx spark", "two dgx spark vllm", "deepseek v4 flash"] content: type: "how_to" @@ -28,20 +28,24 @@ It does not scan a subnet, add SSH host keys, add authorized keys, or change SSH Both derived addresses must already have strict public-key SSH trust. They must identify the same physical peer and the same SSH host key. The detector performs read-only host probes only through that pinned identity. -After you confirm setup, NemoClaw repeats the read-only pair qualification and then writes an owner-only temporary SSH binding at `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` for the install transaction. -This claim is host-global and shared by every gateway on the host. -Declining setup creates no binding. After confirmation, NemoClaw attempts to remove the binding when setup fails or the durable runtime receipt is committed. -If cleanup cannot be confirmed and the claim remains without a durable runtime receipt, a new managed-vLLM install stops before mutation and preserves the claim for explicit recovery or removal. - -When no pair qualifies during automatic selection, NemoClaw retains the existing single-DGX Spark managed vLLM path. +After you confirm setup, NemoClaw repeats the read-only topology qualification. +It then writes an owner-only temporary SSH binding for each peer at `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/`. +These claims are host-global and shared by every gateway on the host. +Declining setup creates no binding. +After confirmation, NemoClaw attempts to remove every binding when setup fails or the durable runtime receipt is committed. +If cleanup cannot be confirmed, a new managed-vLLM install stops before mutation and preserves the claims for explicit recovery or removal. + +When no matching cluster qualifies during automatic selection, NemoClaw retains the existing single-DGX Spark managed vLLM path. This ordinary no-match result occurs before the distributed image or model download starts. Existing related runtime state is not an ordinary no-match result. NemoClaw stops when either host has a related vLLM or DGX Station container, an ambiguous runtime inspection, or a listener on port `8000` or `25000`. -An existing durable dual-Spark or dual-Station runtime receipt, either receipt's copied SSH binding, an orphaned temporary dual-Spark discovery claim, or an SSH binding that conflicts with the new transaction also stops setup. +An existing durable managed-cluster or dual-Station runtime receipt also stops setup. +A copied runtime binding, an orphaned discovery claim, or an SSH binding conflict also stops setup. NemoClaw leaves the existing files, containers, and listeners untouched instead of replacing, repairing, adopting, or removing them. -Set `NEMOCLAW_DGX_SPARK_PEER` to request one exact pretrusted peer. +Set `NEMOCLAW_MANAGED_CLUSTER_PEERS` to a comma-separated list of exact pretrusted peers. +The current profile declares `nodeCount: 2`, so its strict selection requires one peer. Set `NEMOCLAW_SERVING_PRESET=vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731` to request the exact serving profile. Either setting makes qualification strict, so a missed requirement stops setup instead of selecting the single-DGX Spark profile. @@ -152,7 +156,7 @@ curl -fsSL https://www.nvidia.com/nemoclaw.sh | \ NEMOCLAW_NON_INTERACTIVE=1 \ NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 \ NEMOCLAW_PROVIDER=install-vllm \ - NEMOCLAW_DGX_SPARK_PEER="" \ + NEMOCLAW_MANAGED_CLUSTER_PEERS="" \ NEMOCLAW_SERVING_PRESET=vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731 \ NEMOCLAW_SANDBOX_NAME=my-assistant \ bash @@ -163,8 +167,10 @@ The explicit target still must match the exact reciprocal rail topology. ## Understand the Distributed Runtime -The compiled managed inference catalog reads profile selection, artifacts, runtime resources, serving arguments, preparation, and readiness checks from preset and recipe YAML. -Maintainers can add another profile that uses the registered dual-Spark topology, materializer, lifecycle, and preparation adapters by adding preset and recipe YAML without TypeScript changes or a committed generated artifact. +The compiled managed inference catalog reads cluster size, profile selection, artifacts, runtime resources, serving arguments, preparation, and readiness checks from preset and recipe YAML. +Maintainers can add another compatible profile that uses the registered managed-cluster adapters by adding preset and recipe YAML. +The YAML `nodeCount` declares the required cardinality. +The TypeScript adapters validate the qualified topology against it and materialize every ranked topology node. The build compiles those YAML definitions into the packaged runtime catalog automatically. A profile that needs a different execution contract requires a registered adapter. @@ -202,31 +208,33 @@ It does not establish physical two-node E2E validation or product support. ## Preserve Ownership and Uninstall State -After runtime validation, NemoClaw writes the owner-only host-global receipt `~/.nemoclaw/dual-spark-vllm-runtime.json`. -It copies the pinned SSH binding to `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/`. -The receipt contains the exact plan, container IDs, peer identity, and API key fingerprint, but not the API key. +After runtime validation, NemoClaw writes the owner-only host-global receipt `~/.nemoclaw/managed-cluster-vllm-runtime.json`. +It copies each pinned peer SSH binding to `~/.nemoclaw/managed-cluster-vllm-runtime.json.rank-.ssh-binding/`. +The receipt contains the exact plan, ranked node identities, container IDs, peer identities, and API key fingerprint. +It does not contain the API key. NemoClaw stores the host-global bearer API key in the owner-only `~/.nemoclaw/dual-station-vllm-api-key` file. The filename remains stable for managed vLLM compatibility across distributed profiles. Users with Docker control can inspect the head container environment, so restrict Docker access to trusted administrators. If receipt persistence fails, NemoClaw attempts to remove only the exact containers created by that attempt and reports any rollback removal it cannot confirm. -It does not remove an exact pair that existed before the attempt. +It does not remove an exact cluster that existed before the attempt. The containers have no Docker restart policy. NemoClaw does not provide automatic runtime persistence across a Docker daemon restart or host reboot. -A stopped, partial, mismatched, or unhealthy pair remains a conflict and is not repaired automatically. +A stopped, partial, mismatched, or unhealthy cluster remains a conflict and is not repaired automatically. -Run a full uninstall to remove the exact receipt-owned pair. +Run a full uninstall to remove the exact receipt-owned cluster. ```bash $$nemoclaw uninstall ``` -Full uninstall revalidates both exact container IDs before it removes them and retires the receipt, copied SSH binding, and only the exact leftover temporary discovery claim recorded by that receipt. +Full uninstall revalidates every exact container ID before it removes the containers. +It then retires the receipt, copied SSH bindings, and exact temporary discovery claims recorded by that receipt. If revalidation, removal, or safe claim retirement fails, uninstall stops before other cleanup and preserves the receipt for a retry. -A gateway-scoped uninstall preserves the host-global pair, receipt, SSH binding, and API key while another gateway remains. -Pair cleanup does not delete the Hugging Face model cache. +A gateway-scoped uninstall preserves the host-global cluster, receipt, SSH bindings, and API key while another gateway remains. +Cluster cleanup does not delete the Hugging Face model cache. ## Related Topics diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 1a7e8644e50..36a11be1a67 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -40,22 +40,26 @@ In this section, `` is `~/.nemoclaw/` for the default gatew For the default gateway, the uninstall command preserves `~/.nemoclaw/rebuild-backups/`, `~/.nemoclaw/backups/`, and `~/.nemoclaw/sandboxes.json` by default. A non-default gateway uses the corresponding entries under `~/.nemoclaw/gateways//`. When uninstall confirms that no sibling gateways remain, it also removes the shared CLI, services, images, providers, configuration, models, and swap. -During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first revalidate the recorded peer, plan, cluster, GPU, and container identities. -It then removes only both exact receipt-owned containers. -The dual-DGX Spark receipt is host-global under `~/.nemoclaw/`, while a dual-DGX Station receipt uses the selected gateway state root. -Only after that pair cleanup succeeds does NemoClaw start the remaining full-uninstall steps. -For a host-global dual-DGX Spark receipt, successful pair cleanup also retires any canonical temporary discovery claim associated with that receipt. -If an interrupted dual-DGX Spark transaction leaves `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` without a durable runtime receipt, full uninstall fails closed before cleanup or other mutation and preserves the claim for explicit recovery or removal. -This temporary claim is host-global regardless of the selected gateway. -If validation, pair cleanup, or safe temporary-claim retirement fails, uninstall exits nonzero and keeps the receipt so you can resolve the reported SSH, Docker, peer-host, or claim error and retry. -Pair cleanup can partially complete before an error, so inspect both systems before retrying. +During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first revalidate the recorded plan and every cluster node, GPU, container, and SSH peer identity. +It then removes only the exact receipt-owned containers. +The managed-cluster receipt is host-global under `~/.nemoclaw/`. +A dual-DGX Station receipt uses the selected gateway state root. +NemoClaw starts the remaining full-uninstall steps only after distributed runtime cleanup succeeds. +For a host-global managed-cluster receipt, successful cleanup also retires every recorded temporary discovery claim. +An interrupted transaction can leave `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/` without a durable runtime receipt. +In that state, full uninstall fails closed before mutation and preserves every claim for explicit recovery or removal. +These temporary claims are host-global regardless of the selected gateway. +If validation, runtime cleanup, or temporary-claim retirement fails, uninstall exits nonzero and keeps the receipt. +Resolve the reported SSH, Docker, peer-host, or claim error before you retry. +Runtime cleanup can partially complete before an error, so inspect every cluster node before retrying. When sibling gateways remain, it removes only the selected gateway's resources and port-scoped state and preserves those shared host resources. -This gateway-scoped path leaves a managed distributed pair running and preserves its cleanup receipt, copied SSH binding, any temporary dual-Spark discovery claim, and host-global API key. +This gateway-scoped path leaves a managed distributed runtime running. +It preserves the cleanup receipt, copied SSH bindings, temporary discovery claims, and host-global API key. This preservation also applies when you pass `--destroy-user-data`. If the OpenShell command is unavailable or its gateway list cannot be read, uninstall cannot confirm that the selected gateway is the last one, so it uses the same scoped path and preserves the shared resources. When the command itself is unavailable, uninstall exits nonzero before OpenShell cleanup so you can restore the command and retry. The preserved `rebuild-backups/`, `backups/`, and `sandboxes.json` entries stay unless you pass `--destroy-user-data`. -That flag does not override gateway-scoped preservation of the managed pair receipt, its copied SSH binding, or a temporary dual-Spark discovery claim. +That flag does not override gateway-scoped preservation of the managed runtime receipt, copied SSH bindings, or temporary discovery claims. Interactive runs prompt before they remove the preserved entries, and the default answer keeps them. For non-interactive runs using `--yes`, `NEMOCLAW_NON_INTERACTIVE=1`, or a non-TTY shell, pass `--destroy-user-data` or set `NEMOCLAW_UNINSTALL_DESTROY_USER_DATA=1` to acknowledge data loss and remove the preserved entries. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index f267297ff08..cc575edf17c 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -35,9 +35,9 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/usage-notice.json` | Records the third-party software notice version in `acceptedVersion` and the acceptance time in `acceptedAt`. Install, onboarding, and rebuild flows consult this file and prompt again when its recorded version differs from the current notice or the file is absent. | Yes; deleting it makes the next applicable install, onboarding, or rebuild flow prompt for acceptance again. | | `~/.nemoclaw/ollama-proxy-token` | Local auth token used by the host-side Ollama auth proxy. | Yes, but re-run onboarding afterward so NemoClaw recreates and registers the proxy token. | | `~/.nemoclaw/dual-station-vllm-api-key` | Owner-only host-global bearer API key shared by NemoClaw-managed distributed vLLM profiles. | No while a managed distributed runtime exists. Full uninstall removes it only after managed runtime cleanup succeeds and no sibling gateway remains. | -| `~/.nemoclaw/dual-spark-vllm-runtime.json` | Owner-only host-global dual-DGX Spark cleanup receipt. It contains no serving API key and binds the exact peer, plan, container, and temporary discovery-claim identities. | No while the managed pair exists. Full uninstall removes it after both exact containers are removed. | -| `~/.nemoclaw/dual-spark-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded DGX Spark worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds. | -| `~/.nemoclaw/dual-spark-managed-serving.json.ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written after setup confirmation and repeated dual-DGX Spark pair qualification for the install transaction. It is distinct from the durable runtime receipt binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. With the matching host-global dual-Spark receipt, full uninstall retires the claim after it removes both exact containers; if safe retirement fails, it preserves the receipt for a retry. Gateway-scoped uninstall preserves the claim. | +| `~/.nemoclaw/managed-cluster-vllm-runtime.json` | Owner-only host-global managed-cluster cleanup receipt. It contains no serving API key and binds the exact plan, ranked nodes, containers, and temporary discovery-claim identities. | No while the managed cluster exists. Full uninstall removes it after every exact container is removed. | +| `~/.nemoclaw/managed-cluster-vllm-runtime.json.rank-.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach one recorded worker rank during full uninstall. | No while the managed cluster exists. Full uninstall removes every rank binding with the cleanup receipt after cluster cleanup succeeds. | +| `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written for one peer after setup confirmation and repeated topology qualification. Each claim is distinct from its durable runtime binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. With the matching host-global managed-cluster receipt, full uninstall retires every recorded claim after it removes every exact container. If claim retirement fails, it preserves the receipt for a retry. Gateway-scoped uninstall preserves each claim. | | `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | | `/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | diff --git a/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml index cdd31be7006..5186b79d960 100644 --- a/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml +++ b/managed-inference/presets/vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731.yaml @@ -69,7 +69,7 @@ spec: operator: equals value: 2 - topologyQualification: - id: dgx-spark.gb10.dual-cx7 + id: host-cluster.direct-cx7 schemaVersion: 1 status: qualified @@ -79,6 +79,6 @@ spec: bindings: sparkTopology: valueFromTopologyQualification: - id: dgx-spark.gb10.dual-cx7 + id: host-cluster.direct-cx7 schemaVersion: 1 output: topology diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml index 7411b1880a6..651f3adb37c 100644 --- a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -14,9 +14,9 @@ spec: bindings: sparkTopology: type: topologyQualificationOutput - qualificationId: dgx-spark.gb10.dual-cx7 + qualificationId: host-cluster.direct-cx7 schemaVersion: 1 - outputSchema: nemoclaw.nvidia.com/dual-spark-topology/v1 + outputSchema: nemoclaw.nvidia.com/managed-cluster-topology/v1 model: id: deepseek-ai/DeepSeek-V4-Flash-0731 @@ -98,13 +98,14 @@ spec: VLLM_USE_FLASHINFER_SAMPLER: "1" execution: - materializerRef: vllm.dual-dgx-spark/v1 - lifecycleRef: vllm.dual-dgx-spark/v1 + materializerRef: vllm.managed-cluster/v1 + lifecycleRef: vllm.managed-cluster/v1 topologyBinding: sparkTopology nodeCount: 2 tensorParallelSize: 2 pipelineParallelSize: 1 distributedExecutorBackend: mp + rendezvousPort: 25000 serve: authentication: bearer diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json index a1d2abcc2f9..9a56b71f063 100644 --- a/managed-inference/schemas/recipe.schema.json +++ b/managed-inference/schemas/recipe.schema.json @@ -91,7 +91,7 @@ }, "execution": { "type": "object", - "required": ["materializerRef", "lifecycleRef", "topologyBinding", "nodeCount", "tensorParallelSize", "pipelineParallelSize", "distributedExecutorBackend"], + "required": ["materializerRef", "lifecycleRef", "topologyBinding", "nodeCount", "tensorParallelSize", "pipelineParallelSize", "distributedExecutorBackend", "rendezvousPort"], "properties": { "materializerRef": { "$ref": "#/$defs/stableId" }, "lifecycleRef": { "$ref": "#/$defs/stableId" }, @@ -99,7 +99,8 @@ "nodeCount": { "type": "integer", "minimum": 1, "maximum": 1024 }, "tensorParallelSize": { "type": "integer", "minimum": 1, "maximum": 1024 }, "pipelineParallelSize": { "type": "integer", "minimum": 1, "maximum": 1024 }, - "distributedExecutorBackend": { "$ref": "#/$defs/token" } + "distributedExecutorBackend": { "$ref": "#/$defs/token" }, + "rendezvousPort": { "type": "integer", "minimum": 1, "maximum": 65535 } }, "additionalProperties": false }, diff --git a/scripts/install.sh b/scripts/install.sh index 23b415f48d9..0a9f93fa171 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -4512,10 +4512,10 @@ describe_express_install() { "DGX Spark") if [ -n "${NEMOCLAW_VLLM_MODEL:-}" ]; then inference_summary="managed local vLLM with model ${NEMOCLAW_VLLM_MODEL}" - inference_disclosure="The explicit model remains authoritative, so this run keeps the existing single-Spark profile. Managed vLLM pulls the configured image/model and runs only its dedicated container." + inference_disclosure="The explicit model remains authoritative, so this run keeps the existing single-host DGX Spark profile. Managed vLLM pulls the configured image/model and runs only its dedicated container." else inference_summary="managed vLLM with automatic DGX Spark serving-profile selection" - inference_disclosure="With no explicit inference intent or related runtime, one exactly qualified pretrusted two-Spark topology selects the pinned distributed profile. An ordinary no-match keeps the existing single-Spark profile; any related or ambiguous setup remains untouched and stops installation. Managed vLLM pulls the selected image/model and runs only its dedicated containers. The two-Spark profile is experimental pending physical end-to-end validation." + inference_disclosure="With no explicit inference intent or related runtime, one exactly qualified pretrusted managed cluster topology selects a matching pinned distributed profile. An ordinary no-match keeps the existing single-host DGX Spark profile; any related or ambiguous setup remains untouched and stops installation. Managed vLLM pulls the selected image/model and runs only its dedicated containers. The selected distributed profile is experimental pending physical end-to-end validation." fi sandbox_summary="${NEMOCLAW_SANDBOX_NAME:-my-assistant}" ;; diff --git a/src/lib/actions/uninstall/run-plan-dual-station.test.ts b/src/lib/actions/uninstall/run-plan-dual-station.test.ts index b70424a454d..38978a87105 100644 --- a/src/lib/actions/uninstall/run-plan-dual-station.test.ts +++ b/src/lib/actions/uninstall/run-plan-dual-station.test.ts @@ -40,11 +40,17 @@ function okWithKnownGatewayList(command: string, args: readonly string[]): RunRe : ok(); } +function managedRuntimeBindingPath(receiptPath: string): string { + return receiptPath.endsWith("managed-cluster-vllm-runtime.json") + ? `${receiptPath}.rank-1.ssh-binding` + : `${receiptPath}.ssh-binding`; +} + describe("managed distributed vLLM runtime uninstall", () => { it.each([ "dual-station-vllm-runtime.json", - "dual-spark-vllm-runtime.json", - ])("removes the pair owned by %s before the remaining full-uninstall steps", (receiptFile) => { + "managed-cluster-vllm-runtime.json", + ])("removes the runtime owned by %s before the remaining full-uninstall steps", (receiptFile) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-pair-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); @@ -82,14 +88,17 @@ describe("managed distributed vLLM runtime uninstall", () => { } }); - it("associates the canonical leftover Spark discovery binding with its durable receipt", () => { + it("associates a canonical cluster discovery binding with its durable receipt", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-")); const stateDir = path.join(home, ".nemoclaw"); - const receiptPath = path.join(stateDir, "dual-spark-vllm-runtime.json"); - const discoveryBindingPath = path.join(stateDir, "dual-spark-managed-serving.json.ssh-binding"); + const receiptPath = path.join(stateDir, "managed-cluster-vllm-runtime.json"); + const discoveryBindingPath = path.join( + stateDir, + "managed-cluster-managed-serving.json.spark-worker.ssh-binding", + ); fs.mkdirSync(stateDir, { mode: 0o700 }); fs.writeFileSync(receiptPath, "{}\n", { mode: 0o600 }); - fs.mkdirSync(`${receiptPath}.ssh-binding`, { mode: 0o700 }); + fs.mkdirSync(managedRuntimeBindingPath(receiptPath), { mode: 0o700 }); fs.mkdirSync(discoveryBindingPath, { mode: 0o700 }); const runDualStationRuntimeCleanup = vi.fn(() => ok()); @@ -121,14 +130,18 @@ describe("managed distributed vLLM runtime uninstall", () => { it.each([ { - title: "a noncanonical gateway Spark claim despite a host-global Spark receipt", - receiptFile: "dual-spark-vllm-runtime.json", - bindingSegments: ["gateways", "18080", "dual-spark-managed-serving.json.ssh-binding"], + title: "a noncanonical gateway cluster claim despite a host-global cluster receipt", + receiptFile: "managed-cluster-vllm-runtime.json", + bindingSegments: [ + "gateways", + "18080", + "managed-cluster-managed-serving.json.spark-worker.ssh-binding", + ], }, { - title: "a canonical Spark claim when only a Station receipt exists", + title: "a canonical cluster claim when only a Station receipt exists", receiptFile: "dual-station-vllm-runtime.json", - bindingSegments: ["dual-spark-managed-serving.json.ssh-binding"], + bindingSegments: ["managed-cluster-managed-serving.json.spark-worker.ssh-binding"], }, ])("refuses $title", ({ receiptFile, bindingSegments }) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-spark-claim-other-")); @@ -137,7 +150,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const discoveryBindingPath = path.join(stateDir, ...bindingSegments); fs.mkdirSync(stateDir, { mode: 0o700 }); fs.writeFileSync(receiptPath, "{}\n", { mode: 0o600 }); - fs.mkdirSync(`${receiptPath}.ssh-binding`, { mode: 0o700 }); + fs.mkdirSync(managedRuntimeBindingPath(receiptPath), { mode: 0o700 }); fs.mkdirSync(discoveryBindingPath, { recursive: true, mode: 0o700 }); const errors: string[] = []; const runDualStationRuntimeCleanup = vi.fn(() => ok()); @@ -260,7 +273,7 @@ describe("managed distributed vLLM runtime uninstall", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-dual-conflict-")); const stateDir = path.join(home, ".nemoclaw"); fs.mkdirSync(stateDir, { mode: 0o700 }); - for (const name of ["dual-spark-vllm-runtime.json", "dual-station-vllm-runtime.json"]) { + for (const name of ["managed-cluster-vllm-runtime.json", "dual-station-vllm-runtime.json"]) { fs.writeFileSync(path.join(stateDir, name), "{}\n", { mode: 0o600 }); } const errors: string[] = []; @@ -290,7 +303,7 @@ describe("managed distributed vLLM runtime uninstall", () => { expect(runDocker).not.toHaveBeenCalled(); expect(rmSync).not.toHaveBeenCalled(); expect(errors).toContain( - "Both dual-Spark and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", + "Both managed cluster and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", ); } finally { fs.rmSync(home, { recursive: true, force: true }); @@ -298,13 +311,13 @@ describe("managed distributed vLLM runtime uninstall", () => { }); it.each([ - "dual-spark-vllm-runtime.json", - "dual-spark-managed-serving.json", - "dual-station-vllm-runtime.json", - ])("refuses an orphaned %s SSH binding before cleanup or other mutation", (receiptFile) => { + "managed-cluster-vllm-runtime.json.rank-1.ssh-binding", + "managed-cluster-managed-serving.json.spark-worker.ssh-binding", + "dual-station-vllm-runtime.json.ssh-binding", + ])("refuses an orphaned %s before cleanup or other mutation", (bindingEntry) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-binding-orphan-")); const stateDir = path.join(home, ".nemoclaw"); - const bindingPath = path.join(stateDir, `${receiptFile}.ssh-binding`); + const bindingPath = path.join(stateDir, bindingEntry); fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); const errors: string[] = []; const runDualStationRuntimeCleanup = vi.fn(() => ok()); @@ -342,7 +355,7 @@ describe("managed distributed vLLM runtime uninstall", () => { }); it.each([ - ["Spark", "dual-spark-vllm-runtime.json"], + ["Spark", "managed-cluster-vllm-runtime.json"], ["Station", "dual-station-vllm-runtime.json"], ])("finds the host-global %s receipt from a non-default gateway selection", async (_topology, receiptFile) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-managed-global-")); @@ -351,7 +364,7 @@ describe("managed distributed vLLM runtime uninstall", () => { fs.writeFileSync(path.join(stateDir, receiptFile), "{}\n", { mode: 0o600, }); - fs.mkdirSync(path.join(stateDir, `${receiptFile}.ssh-binding`), { + fs.mkdirSync(managedRuntimeBindingPath(path.join(stateDir, receiptFile)), { mode: 0o700, }); fs.writeFileSync(path.join(stateDir, "dual-station-vllm-api-key"), `${"a".repeat(64)}\n`, { diff --git a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts index e378f67f319..48cddd87208 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-segregation.test.ts @@ -1072,9 +1072,12 @@ describe("uninstall gateway-port segregation (#3053)", () => { }, }), ); - const runtimeReceipt = path.join(stateDir, "dual-spark-vllm-runtime.json"); - const runtimeBinding = `${runtimeReceipt}.ssh-binding`; - const discoveryBinding = path.join(stateDir, "dual-spark-managed-serving.json.ssh-binding"); + const runtimeReceipt = path.join(stateDir, "managed-cluster-vllm-runtime.json"); + const runtimeBinding = `${runtimeReceipt}.rank-1.ssh-binding`; + const discoveryBinding = path.join( + stateDir, + "managed-cluster-managed-serving.json.spark-worker.ssh-binding", + ); const managedApiKey = path.join(stateDir, "dual-station-vllm-api-key"); fs.writeFileSync(runtimeReceipt, "{}\n", { mode: 0o600 }); fs.mkdirSync(runtimeBinding, { mode: 0o700 }); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 4f1a29f3ff9..9fb8fb53574 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -28,10 +28,11 @@ import { import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { isOllamaAuthProxyCommandLine } from "../../inference/ollama/process"; import { - DUAL_SPARK_MANAGED_SERVING_STATE_FILE, - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, findManagedDistributedVllmRuntimeReceipts, + isManagedClusterDiscoveryBindingStateEntry, + isManagedClusterRuntimeBindingStateEntry, + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, MANAGED_VLLM_API_KEY_FILE, MCP_LIFECYCLE_LOCK_DIRNAME, } from "../../inference/serving/managed-runtime-receipts"; @@ -258,15 +259,36 @@ const SHARED_HOST_STATE_ENTRIES = new Set([ "source", GATEWAYS_SUBDIR, "managed_swap", - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, - `${DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, - `${DUAL_SPARK_MANAGED_SERVING_STATE_FILE}.ssh-binding`, + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, `${DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, MANAGED_VLLM_API_KEY_FILE, ...HTTPS_PIN_RUNTIME_ADAPTER_STATE_ENTRIES, ]); +function isSharedHostStateEntry(entry: string): boolean { + return ( + SHARED_HOST_STATE_ENTRIES.has(entry) || + isManagedClusterRuntimeBindingStateEntry(entry) || + isManagedClusterDiscoveryBindingStateEntry(entry) + ); +} + +function managedClusterBindingStateEntries(stateDir: string): readonly string[] { + try { + return fs + .readdirSync(stateDir) + .filter( + (entry) => + isManagedClusterRuntimeBindingStateEntry(entry) || + isManagedClusterDiscoveryBindingStateEntry(entry), + ); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + function dormantHostGlobalLifecycleState(sharedRoot: string): boolean { const stateDir = path.join(sharedRoot, "state"); try { @@ -1271,17 +1293,26 @@ function removeManagedDistributedVllmRuntime( ); return false; } - const receipts = [...(state.sparkPath ? [state.sparkPath] : []), ...state.stationPaths]; + const receipts = [ + ...(state.managedClusterPath ? [state.managedClusterPath] : []), + ...state.stationPaths, + ]; const bindingPaths = [ - ...(state.sparkBindingPath ? [state.sparkBindingPath] : []), - ...state.sparkDiscoveryBindingPaths, + ...state.managedClusterBindingPaths, + ...state.managedClusterDiscoveryBindingPaths, ...state.stationBindingPaths, ]; - const expectedBindingPaths = new Set(receipts.map((receiptPath) => `${receiptPath}.ssh-binding`)); - if (state.sparkPath) { - expectedBindingPaths.add( - `${path.join(path.dirname(state.sparkPath), DUAL_SPARK_MANAGED_SERVING_STATE_FILE)}.ssh-binding`, - ); + const expectedBindingPaths = new Set( + state.stationPaths.map((receiptPath) => `${receiptPath}.ssh-binding`), + ); + if (state.managedClusterPath) { + const stateDir = path.dirname(state.managedClusterPath); + for (const bindingPath of [ + ...state.managedClusterBindingPaths, + ...state.managedClusterDiscoveryBindingPaths, + ]) { + if (path.dirname(bindingPath) === stateDir) expectedBindingPaths.add(bindingPath); + } } const orphanBinding = bindingPaths.find((bindingPath) => !expectedBindingPaths.has(bindingPath)); if (orphanBinding) { @@ -1291,9 +1322,9 @@ function removeManagedDistributedVllmRuntime( return false; } if (receipts.length === 0) return true; - if (state.sparkPath && state.stationPaths.length > 0) { + if (state.managedClusterPath && state.stationPaths.length > 0) { runtime.error( - "Both dual-Spark and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", + "Both managed cluster and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", ); return false; } @@ -1469,7 +1500,7 @@ function inspectOtherGatewayEnvironments( .readdirSync(sharedRoot) .some( (entry) => - !SHARED_HOST_STATE_ENTRIES.has(entry) && + !isSharedHostStateEntry(entry) && !(entry === "state" && dormantHostGlobalLifecycleState(sharedRoot)), ) ) { @@ -1847,9 +1878,8 @@ function executePlan( ...(scopedToSelectedGateway ? [ ...HTTPS_PIN_RUNTIME_ADAPTER_STATE_ENTRIES, - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, - `${DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, - `${DUAL_SPARK_MANAGED_SERVING_STATE_FILE}.ssh-binding`, + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, + ...managedClusterBindingStateEntries(paths.nemoclawStateDir), DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE, `${DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE}.ssh-binding`, MANAGED_VLLM_API_KEY_FILE, diff --git a/src/lib/inference/local-vllm-auth.test.ts b/src/lib/inference/local-vllm-auth.test.ts index 8e559060c0d..ec77707a1ba 100644 --- a/src/lib/inference/local-vllm-auth.test.ts +++ b/src/lib/inference/local-vllm-auth.test.ts @@ -14,7 +14,7 @@ interface ManagedBaseUrlOverrides { const lifecycle = vi.hoisted(() => ({ baseUrl: vi.fn<(overrides?: ManagedBaseUrlOverrides) => string | null>(), })); -const sparkRecovery = vi.hoisted(() => ({ +const managedClusterRecovery = vi.hoisted(() => ({ endpoint: vi.fn(), })); const managedKey = vi.hoisted(() => ({ @@ -24,8 +24,8 @@ const managedKey = vi.hoisted(() => ({ vi.mock("./vllm-station-cluster-lifecycle", () => ({ getDualStationManagedVllmBaseUrl: lifecycle.baseUrl, })); -vi.mock("./serving/spark-runtime-receipt", () => ({ - recoverInstalledDualSparkVllmEndpoint: sparkRecovery.endpoint, +vi.mock("./serving/managed-cluster-runtime-receipt", () => ({ + recoverInstalledManagedClusterVllmEndpoint: managedClusterRecovery.endpoint, })); vi.mock("./vllm-api-key", async (importOriginal) => ({ ...(await importOriginal()), @@ -93,8 +93,8 @@ function productionManagedBaseUrlResolver( beforeEach(() => { vi.stubEnv(LOCAL_INFERENCE_SANDBOX_HOST_URL_ENV, undefined); - sparkRecovery.endpoint.mockReset(); - sparkRecovery.endpoint.mockReturnValue(null); + managedClusterRecovery.endpoint.mockReset(); + managedClusterRecovery.endpoint.mockReturnValue(null); managedKey.load.mockReset(); managedKey.load.mockReturnValue(API_KEY); lifecycle.baseUrl.mockReset(); @@ -118,13 +118,13 @@ describe("managed vLLM authentication", () => { }), ).toBeNull(); expect(loadApiKeyImpl).not.toHaveBeenCalled(); - expect(sparkRecovery.endpoint).not.toHaveBeenCalled(); + expect(managedClusterRecovery.endpoint).not.toHaveBeenCalled(); }); - it("recovers a receipt-owned Spark endpoint before checking Station state", () => { + it("recovers a receipt-owned managed cluster endpoint before checking Station state", () => { const events: string[] = []; - const recoverSparkVllmEndpointImpl = vi.fn(() => { - events.push("spark"); + const recoverManagedClusterVllmEndpointImpl = vi.fn(() => { + events.push("managed-cluster"); return { baseUrl: BASE_URL, apiKey: API_KEY }; }); const getManagedBaseUrlImpl = vi.fn(() => { @@ -135,29 +135,29 @@ describe("managed vLLM authentication", () => { expect( getManagedVllmProviderBinding({ getManagedBaseUrlImpl, - recoverSparkVllmEndpointImpl, + recoverManagedClusterVllmEndpointImpl, }), ).toEqual({ baseUrl: `${BASE_URL}/v1`, apiKey: API_KEY }); - expect(events).toEqual(["spark", "station"]); + expect(events).toEqual(["managed-cluster", "station"]); }); - it("does not fall through to Station when Spark recovery is unsafe", () => { + it("does not fall through to Station when managed cluster recovery is unsafe", () => { const getManagedBaseUrlImpl = vi.fn(() => BASE_URL); expect(() => getManagedVllmProviderBinding({ getManagedBaseUrlImpl, - recoverSparkVllmEndpointImpl: () => { - throw new Error("Spark receipt identity changed"); + recoverManagedClusterVllmEndpointImpl: () => { + throw new Error("managed cluster receipt identity changed"); }, }), - ).toThrow("Spark receipt identity changed"); + ).toThrow("managed cluster receipt identity changed"); expect(getManagedBaseUrlImpl).not.toHaveBeenCalled(); }); it("fails URL and validation boundaries closed when managed recovery is unsafe", () => { - sparkRecovery.endpoint.mockImplementation(() => { - throw new Error("Spark receipt identity changed"); + managedClusterRecovery.endpoint.mockImplementation(() => { + throw new Error("managed cluster receipt identity changed"); }); const capture = vi.fn(() => "200"); @@ -174,18 +174,18 @@ describe("managed vLLM authentication", () => { expect(lifecycle.baseUrl).not.toHaveBeenCalled(); }); - it("stops when Spark and Station managed state are both present", () => { + it("stops when managed cluster and Station state are both present", () => { expect(() => getManagedVllmProviderBinding({ loadApiKeyImpl: () => API_KEY, - recoverSparkVllmEndpointImpl: () => ({ baseUrl: BASE_URL, apiKey: API_KEY }), + recoverManagedClusterVllmEndpointImpl: () => ({ baseUrl: BASE_URL, apiKey: API_KEY }), getManagedBaseUrlImpl: (overrides) => { overrides?.onManagedHeadObserved?.(); overrides?.loadApiKey?.(); return BASE_URL; }, }), - ).toThrow("Both managed Spark and Station vLLM state are present"); + ).toThrow("Both managed cluster and Station vLLM state are present"); }); it("does not load a stale or unsafe key without a recovered managed endpoint", () => { diff --git a/src/lib/inference/local.ts b/src/lib/inference/local.ts index baa111ac772..1ace4bc2316 100644 --- a/src/lib/inference/local.ts +++ b/src/lib/inference/local.ts @@ -46,9 +46,9 @@ import { resolveOllamaRuntimeContextWindow as resolveOllamaRuntimeContextWindowWithHost, } from "./ollama-runtime-context"; import { - type RecoveredDualSparkVllmEndpoint, - recoverInstalledDualSparkVllmEndpoint, -} from "./serving/spark-runtime-receipt"; + type RecoveredManagedClusterVllmEndpoint, + recoverInstalledManagedClusterVllmEndpoint, +} from "./serving/managed-cluster-runtime-receipt"; import { loadManagedVllmApiKey } from "./vllm-api-key"; import { applyVllmRuntimeContextWindow as applyVllmRuntimeContextWindowFromModels } from "./vllm-runtime-context"; import { getDualStationManagedVllmBaseUrl } from "./vllm-station-cluster-lifecycle"; @@ -260,8 +260,8 @@ export interface LocalProviderHealthProbeOptions { loadVllmApiKeyImpl?: () => string | null; /** Recovers a managed Station endpoint while validating the injected key. */ getManagedVllmBaseUrlImpl?: ManagedStationVllmBaseUrlResolver; - /** Recovers a receipt-owned managed Spark endpoint. */ - recoverSparkVllmEndpointImpl?: ManagedSparkVllmEndpointResolver; + /** Recovers a receipt-owned managed cluster endpoint. */ + recoverManagedClusterVllmEndpointImpl?: ManagedClusterVllmEndpointResolver; } function defaultLoadOllamaProxyToken(): string | null { @@ -440,9 +440,9 @@ type ManagedStationVllmBaseUrlResolver = (overrides?: { onManagedHeadObserved?: () => void; }) => string | null; -type ManagedSparkVllmEndpointResolver = (options?: { +type ManagedClusterVllmEndpointResolver = (options?: { loadApiKey?: () => string | null; -}) => Pick | null; +}) => Pick | null; export type ManagedVllmProviderState = | { kind: "absent" } @@ -454,7 +454,7 @@ export interface ManagedVllmProviderBindingOptions { /** Compatibility seam for the Station lifecycle resolver. */ getManagedBaseUrlImpl?: ManagedStationVllmBaseUrlResolver; loadApiKeyImpl?: () => string | null; - recoverSparkVllmEndpointImpl?: ManagedSparkVllmEndpointResolver; + recoverManagedClusterVllmEndpointImpl?: ManagedClusterVllmEndpointResolver; } function getManagedStationVllmProviderState( @@ -509,39 +509,44 @@ export function getManagedVllmProviderState( if (configuredLocalInferenceHostUrl(options.hostUrl)) return { kind: "absent" }; const loadApiKey = options.loadApiKeyImpl ?? loadManagedVllmApiKey; - let sparkAuthFailure: "missing" | "unsafe" | null = null; - let sparkEndpoint: Pick | null; + let managedClusterAuthFailure: "missing" | "unsafe" | null = null; + let managedClusterEndpoint: Pick< + RecoveredManagedClusterVllmEndpoint, + "baseUrl" | "apiKey" + > | null; try { - sparkEndpoint = (options.recoverSparkVllmEndpointImpl ?? recoverInstalledDualSparkVllmEndpoint)( - { - loadApiKey: () => { - try { - const apiKey = loadApiKey(); - if (!apiKey) sparkAuthFailure = "missing"; - return apiKey; - } catch { - sparkAuthFailure = "unsafe"; - return null; - } - }, + managedClusterEndpoint = ( + options.recoverManagedClusterVllmEndpointImpl ?? recoverInstalledManagedClusterVllmEndpoint + )({ + loadApiKey: () => { + try { + const apiKey = loadApiKey(); + if (!apiKey) managedClusterAuthFailure = "missing"; + return apiKey; + } catch { + managedClusterAuthFailure = "unsafe"; + return null; + } }, - ); + }); } catch (error) { - if (sparkAuthFailure) return { kind: "invalid-auth", reason: sparkAuthFailure }; + if (managedClusterAuthFailure) { + return { kind: "invalid-auth", reason: managedClusterAuthFailure }; + } throw error; } const stationState = getManagedStationVllmProviderState(options, loadApiKey); - if (!sparkEndpoint) return stationState; + if (!managedClusterEndpoint) return stationState; if (stationState.kind !== "absent") { throw new Error( - "Both managed Spark and Station vLLM state are present; refusing to select either endpoint.", + "Both managed cluster and Station vLLM state are present; refusing to select either endpoint.", ); } return { kind: "ready", - baseUrl: `${sparkEndpoint.baseUrl.replace(/\/+$/, "")}/v1`, - apiKey: sparkEndpoint.apiKey, + baseUrl: `${managedClusterEndpoint.baseUrl.replace(/\/+$/, "")}/v1`, + apiKey: managedClusterEndpoint.apiKey, }; } @@ -815,7 +820,7 @@ export function probeLocalProviderHealth( managedState = getManagedVllmProviderState({ getManagedBaseUrlImpl: options.getManagedVllmBaseUrlImpl, loadApiKeyImpl: options.loadVllmApiKeyImpl, - recoverSparkVllmEndpointImpl: options.recoverSparkVllmEndpointImpl, + recoverManagedClusterVllmEndpointImpl: options.recoverManagedClusterVllmEndpointImpl, }); } catch { return { diff --git a/src/lib/inference/serving/adapter-registry.test.ts b/src/lib/inference/serving/adapter-registry.test.ts index f5a9e799dfa..8a14666a361 100644 --- a/src/lib/inference/serving/adapter-registry.test.ts +++ b/src/lib/inference/serving/adapter-registry.test.ts @@ -4,8 +4,6 @@ import { describe, expect, it } from "vitest"; import { - DUAL_SPARK_VLLM_LIFECYCLE_REF, - DUAL_SPARK_VLLM_MATERIALIZER_REF, getManagedInferenceLifecycleDescriptor, getManagedInferenceMaterializerDescriptor, getManagedInferencePreparationDescriptor, @@ -15,40 +13,42 @@ import { listManagedInferenceMaterializerDescriptors, listManagedInferencePreparationDescriptors, listManagedInferenceTopologyQualificationDescriptors, + MANAGED_CLUSTER_VLLM_LIFECYCLE_REF, + MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; -import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, -} from "./dual-spark-topology.js"; + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, +} from "./managed-cluster-topology.js"; function shippedRecipe(): ManagedInferenceServingRecipe { const recipe = loadManagedInferenceCatalog().recipes.find( ({ definition }) => - definition.spec.execution.materializerRef === DUAL_SPARK_VLLM_MATERIALIZER_REF, + definition.spec.execution.materializerRef === MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, )?.definition; expect(recipe).toBeDefined(); return structuredClone(recipe as ManagedInferenceServingRecipe); } describe("managed inference adapter registries", () => { - it("registers one versioned descriptor for each shipped dual-Spark mechanic", () => { + it("registers one versioned descriptor for each shipped managed cluster mechanic", () => { expect(listManagedInferenceTopologyQualificationDescriptors()).toMatchObject([ { - id: DUAL_SPARK_TOPOLOGY_ID, - schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, bindingOutput: "topology", }, ]); expect(listManagedInferenceMaterializerDescriptors()).toMatchObject([ - { ref: DUAL_SPARK_VLLM_MATERIALIZER_REF, backend: "vllm" }, + { ref: MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, backend: "vllm" }, ]); expect(listManagedInferenceLifecycleDescriptors()).toMatchObject([ - { ref: DUAL_SPARK_VLLM_LIFECYCLE_REF, backend: "vllm" }, + { ref: MANAGED_CLUSTER_VLLM_LIFECYCLE_REF, backend: "vllm" }, ]); expect(listManagedInferencePreparationDescriptors()).toEqual( expect.arrayContaining([ @@ -64,18 +64,20 @@ describe("managed inference adapter registries", () => { it("looks up mechanics only by their stable registry references", () => { expect( getManagedInferenceTopologyQualificationDescriptor( - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, ), ).toBeDefined(); expect( getManagedInferenceTopologyQualificationDescriptor("unknown.topology", 1), ).toBeUndefined(); expect( - getManagedInferenceMaterializerDescriptor(DUAL_SPARK_VLLM_MATERIALIZER_REF), + getManagedInferenceMaterializerDescriptor(MANAGED_CLUSTER_VLLM_MATERIALIZER_REF), ).toBeDefined(); expect(getManagedInferenceMaterializerDescriptor("unknown.materializer/v1")).toBeUndefined(); - expect(getManagedInferenceLifecycleDescriptor(DUAL_SPARK_VLLM_LIFECYCLE_REF)).toBeDefined(); + expect( + getManagedInferenceLifecycleDescriptor(MANAGED_CLUSTER_VLLM_LIFECYCLE_REF), + ).toBeDefined(); expect(getManagedInferenceLifecycleDescriptor("unknown.lifecycle/v1")).toBeUndefined(); expect( getManagedInferencePreparationDescriptor( @@ -131,7 +133,7 @@ describe("managed inference adapter registries", () => { expect(getManagedInferenceRecipeRegistrationError(unregistered)).toMatch( /unknown materializer/u, ); - expect(getManagedInferenceRecipeRegistrationError(wrongShape)).toMatch(/two-node/u); + expect(getManagedInferenceRecipeRegistrationError(wrongShape)).toMatch(/TP times PP/u); }); it("rejects schema-valid values that the registered adapter cannot execute", () => { @@ -212,7 +214,7 @@ describe("managed inference adapter registries", () => { }); it("dispatches topology artifact validation through the registered descriptor", () => { - const artifact = fixtureDualSparkSelection().topologyQualification; + const artifact = fixtureManagedClusterSelection().topologyQualification; const descriptor = getManagedInferenceTopologyQualificationDescriptor( artifact.id, artifact.schemaVersion, diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index d9d34ed3395..7c1c845ad3f 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -6,18 +6,17 @@ import type { ManagedInferenceTopologyQualification, } from "./catalog-types.js"; import { - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - getDualSparkTopologyArtifactError, -} from "./dual-spark-topology.js"; + getManagedClusterTopologyArtifactError, + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, +} from "./managed-cluster-topology.js"; -export const DUAL_SPARK_VLLM_MATERIALIZER_REF = "vllm.dual-dgx-spark/v1" as const; -export const DUAL_SPARK_VLLM_LIFECYCLE_REF = "vllm.dual-dgx-spark/v1" as const; +export const MANAGED_CLUSTER_VLLM_MATERIALIZER_REF = "vllm.managed-cluster/v1" as const; +export const MANAGED_CLUSTER_VLLM_LIFECYCLE_REF = "vllm.managed-cluster/v1" as const; export const SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF = "snapshot-copy-and-exact-text-replacement/v1" as const; export const NO_PREPARATION_REF = "none/v1" as const; -export const DUAL_SPARK_HUGGING_FACE_CACHE_SOURCE = "huggingface-cache" as const; -export const DUAL_SPARK_VLLM_MASTER_PORT = 25_000 as const; +export const MANAGED_CLUSTER_HUGGING_FACE_CACHE_SOURCE = "huggingface-cache" as const; export function containerPathContains(parent: string, child: string): boolean { return child === parent || child.startsWith(`${parent}/`); @@ -62,10 +61,11 @@ export interface ManagedInferencePreparationDescriptor { validateRecipe(recipe: ManagedInferenceServingRecipe): string | undefined; } -const DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA = "nemoclaw.nvidia.com/dual-spark-topology/v1" as const; -const DUAL_SPARK_PLAN_SCHEMA = "nemoclaw.nvidia.com/dual-spark-vllm-plan/v1" as const; +const MANAGED_CLUSTER_TOPOLOGY_OUTPUT_SCHEMA = + "nemoclaw.nvidia.com/managed-cluster-topology/v1" as const; +const MANAGED_CLUSTER_PLAN_SCHEMA = "nemoclaw.nvidia.com/managed-cluster-vllm-plan/v1" as const; const LOWERCASE_STABLE_ID = /^[a-z0-9][a-z0-9._/-]{0,159}$/u; -const DUAL_SPARK_MATERIALIZER_OWNED_ENVIRONMENT = new Set([ +const MANAGED_CLUSTER_MATERIALIZER_OWNED_ENVIRONMENT = new Set([ "GLOO_SOCKET_IFNAME", "HEADLESS", "HF_HOME", @@ -80,11 +80,11 @@ const DUAL_SPARK_MATERIALIZER_OWNED_ENVIRONMENT = new Set([ "VLLM_HOST_IP", ]); -export function isDualSparkMaterializerOwnedEnvironment(name: string): boolean { - return DUAL_SPARK_MATERIALIZER_OWNED_ENVIRONMENT.has(name); +export function isManagedClusterMaterializerOwnedEnvironment(name: string): boolean { + return MANAGED_CLUSTER_MATERIALIZER_OWNED_ENVIRONMENT.has(name); } -function dualSparkTopologyBinding( +function managedClusterTopologyBinding( recipe: ManagedInferenceServingRecipe, ): ManagedInferenceServingRecipe["spec"]["bindings"][string] | undefined { return recipe.spec.bindings[recipe.spec.execution.topologyBinding]; @@ -107,23 +107,29 @@ function positiveIntegerArgument( return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= maximum ? parsed : undefined; } -function validateDualSparkMaterializerRecipe( +function validateManagedClusterMaterializerRecipe( recipe: ManagedInferenceServingRecipe, ): string | undefined { - if (recipe.spec.backend !== "vllm") return "dual-Spark materializer requires backend vllm"; - if (recipe.spec.execution.materializerRef !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { - return "recipe does not select the dual-Spark materializer"; + if (recipe.spec.backend !== "vllm") return "managed cluster materializer requires backend vllm"; + if (recipe.spec.execution.materializerRef !== MANAGED_CLUSTER_VLLM_MATERIALIZER_REF) { + return "recipe does not select the managed cluster materializer"; } + const { execution } = recipe.spec; if ( - recipe.spec.execution.nodeCount !== 2 || - recipe.spec.execution.tensorParallelSize !== 2 || - recipe.spec.execution.pipelineParallelSize !== 1 || - recipe.spec.execution.distributedExecutorBackend !== "mp" + !Number.isSafeInteger(execution.nodeCount) || + execution.nodeCount < 2 || + execution.nodeCount > 1_024 || + !Number.isSafeInteger(execution.tensorParallelSize) || + execution.tensorParallelSize < 1 || + !Number.isSafeInteger(execution.pipelineParallelSize) || + execution.pipelineParallelSize < 1 || + execution.tensorParallelSize * execution.pipelineParallelSize !== execution.nodeCount || + execution.distributedExecutorBackend !== "mp" ) { - return "dual-Spark materializer requires its two-node TP=2, PP=1, mp execution shape"; + return "managed cluster materializer requires a bounded node count equal to TP times PP with the mp backend"; } if (Object.keys(recipe.spec.bindings).length !== 1) { - return "dual-Spark materializer requires exactly one topology binding"; + return "managed cluster materializer requires exactly one topology binding"; } if ( recipe.spec.runtime.architecture !== "arm64" || @@ -131,26 +137,33 @@ function validateDualSparkMaterializerRecipe( recipe.spec.runtime.ipcMode !== "host" || recipe.spec.serve.authentication !== "bearer" ) { - return "dual-Spark materializer requires arm64 host networking, host IPC, and bearer authentication"; + return "managed cluster materializer requires arm64 host networking, host IPC, and bearer authentication"; } const apiPort = positiveIntegerArgument(recipe, "--port", 65_535); if (apiPort === undefined || positiveIntegerArgument(recipe, "--max-model-len") === undefined) { - return "dual-Spark materializer requires one valid --port and one positive --max-model-len"; + return "managed cluster materializer requires one valid --port and one positive --max-model-len"; } - if (apiPort === DUAL_SPARK_VLLM_MASTER_PORT) { - return "dual-Spark API port conflicts with the materializer rendezvous port"; + if ( + !Number.isSafeInteger(execution.rendezvousPort) || + execution.rendezvousPort < 1 || + execution.rendezvousPort > 65_535 + ) { + return "managed cluster materializer requires a valid rendezvous port"; + } + if (apiPort === execution.rendezvousPort) { + return "managed cluster API port conflicts with the materializer rendezvous port"; } if (recipe.spec.readiness.expectedModel !== recipe.spec.model.servedName) { - return "dual-Spark readiness must expect the recipe served model"; + return "managed cluster readiness must expect the recipe served model"; } if (!LOWERCASE_STABLE_ID.test(recipe.spec.model.servedName)) { - return "dual-Spark served model name must be a lowercase stable ID"; + return "managed cluster served model name must be a lowercase stable ID"; } if (recipe.spec.model.installFastSafetensors) { - return "dual-Spark immutable-image materializer cannot install fastsafetensors at launch"; + return "managed cluster immutable-image materializer cannot install fastsafetensors at launch"; } - if (recipe.spec.runtime.modelCache.source !== DUAL_SPARK_HUGGING_FACE_CACHE_SOURCE) { - return "dual-Spark materializer requires the Hugging Face cache source"; + if (recipe.spec.runtime.modelCache.source !== MANAGED_CLUSTER_HUGGING_FACE_CACHE_SOURCE) { + return "managed cluster materializer requires the Hugging Face cache source"; } if ( !safeAbsoluteContainerPath(recipe.spec.serve.executable) || @@ -160,14 +173,14 @@ function validateDualSparkMaterializerRecipe( ({ target }) => !safeAbsoluteContainerPath(target), ) ) { - return "dual-Spark runtime paths must be normalized absolute container paths"; + return "managed cluster runtime paths must be normalized absolute container paths"; } if ( recipe.spec.runtime.temporaryFilesystems.some(({ target }) => containerPathContains(target, recipe.spec.runtime.modelCache.target), ) ) { - return "dual-Spark temporary filesystem cannot shadow the model cache"; + return "managed cluster temporary filesystem cannot shadow the model cache"; } const resourceValues = [ recipe.spec.model.downloadSizeBytes, @@ -177,11 +190,11 @@ function validateDualSparkMaterializerRecipe( ...recipe.spec.runtime.temporaryFilesystems.map(({ sizeBytes }) => sizeBytes), ]; if (resourceValues.some((value) => !Number.isSafeInteger(value) || value <= 0)) { - return "dual-Spark recipe resource values must be positive safe integers"; + return "managed cluster recipe resource values must be positive safe integers"; } const memlock = recipe.spec.runtime.ulimits.memlock; if (typeof memlock === "number" && (!Number.isSafeInteger(memlock) || memlock < -1)) { - return "dual-Spark memlock value must be -1 or a non-negative safe integer"; + return "managed cluster memlock value must be -1 or a non-negative safe integer"; } if ( recipe.spec.serve.arguments.some( @@ -190,43 +203,43 @@ function validateDualSparkMaterializerRecipe( (Buffer.byteLength(value, "utf8") > 16_384 || value.includes("\0")), ) ) { - return "dual-Spark serving argument values must be bounded text without NUL bytes"; + return "managed cluster serving argument values must be bounded text without NUL bytes"; } if ( Object.values(recipe.spec.runtime.environment).some( (value) => Buffer.byteLength(value, "utf8") > 4_096 || value.includes("\0"), ) ) { - return "dual-Spark environment values must be bounded text without NUL bytes"; + return "managed cluster environment values must be bounded text without NUL bytes"; } if ( Object.keys(recipe.spec.runtime.environment).some((name) => - isDualSparkMaterializerOwnedEnvironment(name), + isManagedClusterMaterializerOwnedEnvironment(name), ) ) { - return "dual-Spark recipe environment overrides a materializer-owned value"; + return "managed cluster recipe environment overrides a materializer-owned value"; } - const binding = dualSparkTopologyBinding(recipe); + const binding = managedClusterTopologyBinding(recipe); if ( !binding || binding.type !== "topologyQualificationOutput" || - binding.qualificationId !== DUAL_SPARK_TOPOLOGY_ID || - binding.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION || - binding.outputSchema !== DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA + binding.qualificationId !== MANAGED_CLUSTER_TOPOLOGY_ID || + binding.schemaVersion !== MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION || + binding.outputSchema !== MANAGED_CLUSTER_TOPOLOGY_OUTPUT_SCHEMA ) { - return "dual-Spark materializer topology binding is incompatible"; + return "managed cluster materializer topology binding is incompatible"; } return undefined; } -function validateDualSparkLifecycleRecipe( +function validateManagedClusterLifecycleRecipe( recipe: ManagedInferenceServingRecipe, ): string | undefined { - const materializerError = validateDualSparkMaterializerRecipe(recipe); + const materializerError = validateManagedClusterMaterializerRecipe(recipe); if (materializerError) return materializerError; - return recipe.spec.execution.lifecycleRef === DUAL_SPARK_VLLM_LIFECYCLE_REF + return recipe.spec.execution.lifecycleRef === MANAGED_CLUSTER_VLLM_LIFECYCLE_REF ? undefined - : "recipe does not select the dual-Spark lifecycle"; + : "recipe does not select the managed cluster lifecycle"; } interface SnapshotPreparationInput { @@ -340,36 +353,36 @@ function validateNoPreparationRecipe(recipe: ManagedInferenceServingRecipe): str const TOPOLOGY_DESCRIPTORS = [ { - id: DUAL_SPARK_TOPOLOGY_ID, - schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - outputSchema: DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA, + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + outputSchema: MANAGED_CLUSTER_TOPOLOGY_OUTPUT_SCHEMA, bindingOutput: "topology", - validateArtifact: getDualSparkTopologyArtifactError, + validateArtifact: getManagedClusterTopologyArtifactError, }, ] as const satisfies readonly ManagedInferenceTopologyQualificationDescriptor[]; const MATERIALIZER_DESCRIPTORS = [ { - ref: DUAL_SPARK_VLLM_MATERIALIZER_REF, + ref: MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, backend: "vllm", - outputPlanSchema: DUAL_SPARK_PLAN_SCHEMA, + outputPlanSchema: MANAGED_CLUSTER_PLAN_SCHEMA, topology: { - qualificationId: DUAL_SPARK_TOPOLOGY_ID, - schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - outputSchema: DUAL_SPARK_TOPOLOGY_OUTPUT_SCHEMA, + qualificationId: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + outputSchema: MANAGED_CLUSTER_TOPOLOGY_OUTPUT_SCHEMA, }, - validateRecipe: validateDualSparkMaterializerRecipe, + validateRecipe: validateManagedClusterMaterializerRecipe, }, ] as const satisfies readonly ManagedInferenceMaterializerDescriptor[]; const LIFECYCLE_DESCRIPTORS = [ { - ref: DUAL_SPARK_VLLM_LIFECYCLE_REF, + ref: MANAGED_CLUSTER_VLLM_LIFECYCLE_REF, backend: "vllm", - acceptedMaterializerRefs: [DUAL_SPARK_VLLM_MATERIALIZER_REF], - acceptedPlanSchemas: [DUAL_SPARK_PLAN_SCHEMA], + acceptedMaterializerRefs: [MANAGED_CLUSTER_VLLM_MATERIALIZER_REF], + acceptedPlanSchemas: [MANAGED_CLUSTER_PLAN_SCHEMA], secretHandlePermissions: ["sshBinding"], - validateRecipe: validateDualSparkLifecycleRecipe, + validateRecipe: validateManagedClusterLifecycleRecipe, }, ] as const satisfies readonly ManagedInferenceLifecycleDescriptor[]; diff --git a/src/lib/inference/serving/catalog-types.ts b/src/lib/inference/serving/catalog-types.ts index d97664a51fb..57c051046e2 100644 --- a/src/lib/inference/serving/catalog-types.ts +++ b/src/lib/inference/serving/catalog-types.ts @@ -109,6 +109,7 @@ export interface ManagedInferenceServingRecipe { readonly tensorParallelSize: number; readonly pipelineParallelSize: number; readonly distributedExecutorBackend: string; + readonly rendezvousPort: number; }; readonly serve: { readonly authentication: string; diff --git a/src/lib/inference/serving/dual-spark-fixture.test-support.ts b/src/lib/inference/serving/dual-spark-fixture.test-support.ts deleted file mode 100644 index bb4b6480637..00000000000 --- a/src/lib/inference/serving/dual-spark-fixture.test-support.ts +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { loadManagedInferenceCatalog } from "./catalog.js"; -import type { ResolvedManagedInferenceSelection } from "./catalog-types.js"; -import { type DualSparkVllmPlan, materializeDualSparkVllmPlan } from "./dual-spark-materialize.js"; -import { - type DualSparkTopologyOutput, - dualSparkTopologyOutputDigest, - dualSparkTopologySubjectDigest, -} from "./dual-spark-topology.js"; - -export const FIXTURE_DUAL_SPARK_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731"; - -export function fixtureDualSparkSelection(): ResolvedManagedInferenceSelection { - const catalog = loadManagedInferenceCatalog(); - const compiledPreset = catalog.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, - ); - const compiledRecipe = catalog.recipes.find( - ({ definition }) => definition.metadata.id === compiledPreset?.definition.spec.plan.recipeRef, - ); - if (!compiledPreset || !compiledRecipe) { - throw new Error("managed inference fixture catalog is incomplete"); - } - const preset = structuredClone(compiledPreset.definition); - const recipe = structuredClone(compiledRecipe.definition); - const subjectNodeIds = ["spark-head", "spark-worker"] as const; - const output: DualSparkTopologyOutput = { - headNodeId: "spark-head", - workerNodeId: "spark-worker", - nodes: [ - { nodeId: "spark-head", gpuId: "GPU-head", role: "head" }, - { nodeId: "spark-worker", gpuId: "GPU-worker", role: "worker" }, - ], - rails: [ - { - index: 0, - head: { - nodeId: "spark-head", - netdev: "enp1s0f0np0", - hcaDevice: "rocep1s0f0", - hcaPort: 1, - address: "192.168.100.10", - prefixLength: 24, - peerAddress: "192.168.100.11", - roceGid: { index: 3, value: "::ffff:c0a8:640a" }, - }, - worker: { - nodeId: "spark-worker", - netdev: "enp1s0f1np1", - hcaDevice: "rocep1s0f1", - hcaPort: 1, - address: "192.168.100.11", - prefixLength: 24, - peerAddress: "192.168.100.10", - roceGid: { index: 6, value: "::ffff:c0a8:640b" }, - }, - }, - { - index: 1, - head: { - nodeId: "spark-head", - netdev: "enP2p1s0f0np0", - hcaDevice: "roceP2p1s0f0", - hcaPort: 1, - address: "192.168.101.10", - prefixLength: 24, - peerAddress: "192.168.101.11", - roceGid: { index: 4, value: "::ffff:c0a8:650a" }, - }, - worker: { - nodeId: "spark-worker", - netdev: "enP2p1s0f1np1", - hcaDevice: "roceP2p1s0f1", - hcaPort: 1, - address: "192.168.101.11", - prefixLength: 24, - peerAddress: "192.168.101.10", - roceGid: { index: 7, value: "::ffff:c0a8:650b" }, - }, - }, - ], - masterAddress: "192.168.100.10", - peer: { target: "spark-worker.local", sshBindingHandle: "state/dual-spark/peer" }, - }; - return { - outcome: "selected", - selection: "automatic", - catalogDigest: catalog.catalogDigest, - presetDigest: compiledPreset.definitionDigest, - recipeDigest: compiledRecipe.definitionDigest, - preset, - recipe, - topologyQualification: { - id: "dgx-spark.gb10.dual-cx7", - schemaVersion: 1, - status: "qualified", - subjectNodeIds, - subjectDigest: dualSparkTopologySubjectDigest(subjectNodeIds), - outputDigest: dualSparkTopologyOutputDigest(output), - output, - }, - }; -} - -export function fixtureDualSparkPlan(): DualSparkVllmPlan { - return materializeDualSparkVllmPlan(fixtureDualSparkSelection()); -} diff --git a/src/lib/inference/serving/dual-spark-topology.ts b/src/lib/inference/serving/dual-spark-topology.ts deleted file mode 100644 index f3397403c0e..00000000000 --- a/src/lib/inference/serving/dual-spark-topology.ts +++ /dev/null @@ -1,754 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import net from "node:net"; - -import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; -import type { SystemReadinessReport } from "../../readiness/types.js"; -import { managedInferenceDigest } from "./catalog-integrity.js"; -import type { ManagedInferenceTopologyQualification } from "./catalog-types.js"; - -export const DUAL_SPARK_TOPOLOGY_ID = "dgx-spark.gb10.dual-cx7" as const; -export const DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION = 1 as const; - -const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; -const SAFE_INTERFACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; -const SAFE_BINDING_HANDLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,8191}$/; -const SSH_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; -const SSH_HOST_PATTERN = - /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; - -export type DualSparkQualificationIntent = "automatic" | "explicit" | "resume"; -export type DualSparkRuntimeState = "clear" | "conflict" | "unknown"; -export type DualSparkObservationState = "up" | "down" | "unknown"; -export type DualSparkConnectivityState = "reachable" | "unreachable" | "unknown"; -export type DualSparkRoceGidState = "resolved" | "missing" | "unknown"; - -export interface DualSparkRoceGidObservation { - state: DualSparkRoceGidState; - index?: number; - value?: string; -} - -export interface DualSparkRailObservation { - adapter: "connectx-7" | "other" | "unknown"; - path: "direct" | "switched" | "unknown"; - physicalPortId: string; - netdev: string; - hcaDevice: string; - hcaPort: number; - address: string; - prefixLength: number; - peerNodeId: string; - peerAddress: string; - linkState: DualSparkObservationState; - connectivity: DualSparkConnectivityState; - roceGid: DualSparkRoceGidObservation; -} - -export interface DualSparkNodeObservation { - nodeId: string; - gpuIds: readonly string[]; - readiness: SystemReadinessReport; - runtimeState: DualSparkRuntimeState; - rails: readonly DualSparkRailObservation[]; -} - -export interface DualSparkSshBindingObservation { - state: "pretrusted" | "untrusted" | "unknown"; - fromNodeId: string; - toNodeId: string; - peerTarget: string; - handle: string; -} - -export interface DualSparkPeerObservation extends DualSparkNodeObservation { - sshBinding: DualSparkSshBindingObservation; -} - -export interface DualSparkTopologyQualificationInput { - intent: DualSparkQualificationIntent; - evaluatedAt: string; - maxReadinessAgeMs: number; - local: DualSparkNodeObservation; - peers: readonly DualSparkPeerObservation[]; -} - -export interface DualSparkTopologyNode { - nodeId: string; - gpuId: string; - role: "head" | "worker"; -} - -export interface DualSparkTopologyRoceGid { - index: number; - value: string; -} - -export interface DualSparkTopologyRailEndpoint { - nodeId: string; - netdev: string; - hcaDevice: string; - hcaPort: number; - address: string; - prefixLength: number; - peerAddress: string; - roceGid: DualSparkTopologyRoceGid; -} - -export interface DualSparkTopologyRail { - index: number; - head: DualSparkTopologyRailEndpoint; - worker: DualSparkTopologyRailEndpoint; -} - -export interface DualSparkTopologyOutput { - headNodeId: string; - workerNodeId: string; - nodes: readonly [DualSparkTopologyNode, DualSparkTopologyNode]; - rails: readonly [DualSparkTopologyRail, DualSparkTopologyRail]; - masterAddress: string; - peer: { - target: string; - sshBindingHandle: string; - }; -} - -export type DualSparkTopologyArtifact = - ManagedInferenceTopologyQualification & { - id: typeof DUAL_SPARK_TOPOLOGY_ID; - schemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; - status: "qualified"; - }; - -export type DualSparkTopologyFailureCode = - | "peer-count" - | "qualification-policy-invalid" - | "readiness-schema-incompatible" - | "readiness-stale" - | "readiness-incompatible" - | "readiness-inconclusive" - | "spark-qualification-unavailable" - | "runtime-qualification-unavailable" - | "node-identity-unavailable" - | "duplicate-node-identity" - | "gpu-identity-unavailable" - | "duplicate-gpu-identity" - | "runtime-conflict" - | "runtime-state-unknown" - | "ssh-binding-unavailable" - | "fabric-degraded" - | "fabric-multiple" - | "fabric-mismatch" - | "artifact-digest-failed"; - -export type DualSparkTopologyQualificationResult = - | { outcome: "qualified"; artifact: DualSparkTopologyArtifact } - | { outcome: "no-match"; code: DualSparkTopologyFailureCode; message: string } - | { outcome: "error"; code: DualSparkTopologyFailureCode; message: string }; - -interface QualificationFailure { - code: DualSparkTopologyFailureCode; - message: string; -} - -interface QualifiedNode { - observation: DualSparkNodeObservation; - gpuId: string; -} - -interface ValidatedRail { - observation: DualSparkRailObservation; - gid: DualSparkTopologyRoceGid; -} - -function compareStrings(left: string, right: string): number { - return left < right ? -1 : left > right ? 1 : 0; -} - -function failure( - intent: DualSparkQualificationIntent, - result: QualificationFailure, -): DualSparkTopologyQualificationResult { - return intent === "automatic" - ? { outcome: "no-match", ...result } - : { outcome: "error", ...result }; -} - -function validateQualificationPolicy( - evaluatedAt: string, - maxReadinessAgeMs: number, -): number | QualificationFailure { - const evaluatedAtMs = Date.parse(evaluatedAt); - if ( - !Number.isFinite(evaluatedAtMs) || - !Number.isSafeInteger(maxReadinessAgeMs) || - maxReadinessAgeMs <= 0 - ) { - return { - code: "qualification-policy-invalid", - message: "The topology qualification time or readiness age limit is invalid.", - }; - } - return evaluatedAtMs; -} - -function validateReadiness( - report: SystemReadinessReport, - evaluatedAtMs: number, - maxReadinessAgeMs: number, -): QualificationFailure | undefined { - const compatibility = checkSystemReadinessSchemaVersion(report.schemaVersion); - if (!compatibility.compatible || report.mutated !== false) { - return { - code: "readiness-schema-incompatible", - message: "A node readiness report has an incompatible schema.", - }; - } - - const observedAtMs = Date.parse(report.provenance.observedAt); - const readinessAgeMs = evaluatedAtMs - observedAtMs; - if (!Number.isFinite(observedAtMs) || readinessAgeMs < 0 || readinessAgeMs > maxReadinessAgeMs) { - return { - code: "readiness-stale", - message: "A node readiness report is outside the accepted observation window.", - }; - } - - if (report.status === "inconclusive") { - return { - code: "readiness-inconclusive", - message: "A node readiness report is inconclusive.", - }; - } - if ( - report.status !== "supported" || - report.exitCode !== 0 || - report.findings.some(({ severity }) => severity === "blocking" || severity === "fatal") - ) { - return { - code: "readiness-incompatible", - message: "A node readiness report is incompatible with this topology.", - }; - } - - const sparkQualifications = report.qualifications.filter( - (qualification) => qualification.id === "host.platform.dgx_spark", - ); - if (sparkQualifications.length !== 1 || sparkQualifications[0]?.status !== "qualified") { - return { - code: "spark-qualification-unavailable", - message: "A node does not have one qualified DGX Spark readiness result.", - }; - } - - return undefined; -} - -function validateNode( - node: DualSparkNodeObservation, - evaluatedAtMs: number, - maxReadinessAgeMs: number, -): QualifiedNode | QualificationFailure { - if (!SAFE_ID_PATTERN.test(node.nodeId)) { - return { - code: "node-identity-unavailable", - message: "A node identity is missing or invalid.", - }; - } - if (node.gpuIds.length !== 1 || !SAFE_ID_PATTERN.test(node.gpuIds[0] ?? "")) { - return { - code: "gpu-identity-unavailable", - message: "Each DGX Spark node must have exactly one valid GPU identity.", - }; - } - const readinessFailure = validateReadiness(node.readiness, evaluatedAtMs, maxReadinessAgeMs); - if (readinessFailure) return readinessFailure; - if (node.runtimeState === "conflict") { - return { - code: "runtime-conflict", - message: "An existing runtime conflicts with automatic dual-node activation.", - }; - } - if (node.runtimeState !== "clear") { - return { - code: "runtime-state-unknown", - message: "The existing runtime state is unknown.", - }; - } - return { observation: node, gpuId: node.gpuIds[0]! }; -} - -function validAddress(address: string, prefixLength: number): boolean { - const version = net.isIP(address); - const maxPrefixLength = version === 4 ? 32 : version === 6 ? 128 : 0; - return ( - maxPrefixLength > 0 && - address !== "0.0.0.0" && - address !== "::" && - Number.isInteger(prefixLength) && - prefixLength > 0 && - prefixLength <= maxPrefixLength - ); -} - -function validateRail( - rail: DualSparkRailObservation, - expectedPeerNodeId: string, -): ValidatedRail | QualificationFailure { - if ( - rail.adapter !== "connectx-7" || - rail.path !== "direct" || - rail.linkState !== "up" || - rail.connectivity !== "reachable" - ) { - return { - code: "fabric-degraded", - message: "The direct ConnectX-7 fabric is incomplete or degraded.", - }; - } - if ( - !SAFE_ID_PATTERN.test(rail.physicalPortId) || - !SAFE_INTERFACE_PATTERN.test(rail.netdev) || - !SAFE_INTERFACE_PATTERN.test(rail.hcaDevice) || - !Number.isInteger(rail.hcaPort) || - rail.hcaPort <= 0 || - rail.hcaPort > 255 || - !validAddress(rail.address, rail.prefixLength) || - net.isIP(rail.peerAddress) === 0 || - rail.address === rail.peerAddress || - rail.peerNodeId !== expectedPeerNodeId - ) { - return { - code: "fabric-mismatch", - message: "The ConnectX-7 rail identity or peer address is invalid.", - }; - } - const gid = rail.roceGid; - if ( - gid.state !== "resolved" || - !Number.isInteger(gid.index) || - (gid.index ?? -1) < 0 || - (gid.index ?? 4096) > 4095 || - typeof gid.value !== "string" || - net.isIP(gid.value) !== 6 || - gid.value === "::" - ) { - return { - code: "fabric-degraded", - message: "A ConnectX-7 rail does not have a resolved RoCE GID.", - }; - } - return { observation: rail, gid: { index: gid.index!, value: gid.value } }; -} - -function validateNodeRails( - node: DualSparkNodeObservation, - expectedPeerNodeId: string, -): readonly [ValidatedRail, ValidatedRail] | QualificationFailure { - if (node.rails.length < 2) { - return { - code: "fabric-degraded", - message: "One direct ConnectX-7 cable must expose two logical rails on each node.", - }; - } - if (node.rails.length > 2) { - return { - code: "fabric-multiple", - message: "More than one candidate ConnectX-7 cable topology was observed.", - }; - } - - const physicalPorts = new Set(node.rails.map(({ physicalPortId }) => physicalPortId)); - if (physicalPorts.size !== 1) { - return { - code: "fabric-multiple", - message: "The candidate logical rails belong to more than one physical port.", - }; - } - - const validated = node.rails.map((rail) => validateRail(rail, expectedPeerNodeId)); - const validationFailure = validated.find((rail): rail is QualificationFailure => "code" in rail); - if (validationFailure) return validationFailure; - const rails = validated as ValidatedRail[]; - const uniqueNetdevs = new Set(rails.map(({ observation }) => observation.netdev)); - const uniqueHcas = new Set( - rails.map(({ observation }) => `${observation.hcaDevice}:${observation.hcaPort}`), - ); - const uniqueAddresses = new Set(rails.map(({ observation }) => observation.address)); - const uniqueGids = new Set( - rails.map(({ gid, observation }) => `${observation.hcaDevice}:${gid.index}:${gid.value}`), - ); - if ( - uniqueNetdevs.size !== 2 || - uniqueHcas.size !== 2 || - uniqueAddresses.size !== 2 || - uniqueGids.size !== 2 - ) { - return { - code: "fabric-mismatch", - message: "The two logical ConnectX-7 rails must have distinct interfaces and addresses.", - }; - } - return [rails[0]!, rails[1]!]; -} - -function endpoint(nodeId: string, rail: ValidatedRail): DualSparkTopologyRailEndpoint { - const observation = rail.observation; - return { - nodeId, - netdev: observation.netdev, - hcaDevice: observation.hcaDevice, - hcaPort: observation.hcaPort, - address: observation.address, - prefixLength: observation.prefixLength, - peerAddress: observation.peerAddress, - roceGid: rail.gid, - }; -} - -function matchRails( - local: DualSparkNodeObservation, - peer: DualSparkNodeObservation, -): readonly [DualSparkTopologyRail, DualSparkTopologyRail] | QualificationFailure { - const localRails = validateNodeRails(local, peer.nodeId); - if ("code" in localRails) return localRails; - const peerRails = validateNodeRails(peer, local.nodeId); - if ("code" in peerRails) return peerRails; - - const remainingPeerRails = [...peerRails]; - const matches: Array<{ head: ValidatedRail; worker: ValidatedRail }> = []; - for (const localRail of localRails) { - const peerIndex = remainingPeerRails.findIndex( - ({ observation }) => - observation.address === localRail.observation.peerAddress && - observation.peerAddress === localRail.observation.address && - observation.prefixLength === localRail.observation.prefixLength && - net.isIP(observation.address) === net.isIP(localRail.observation.address), - ); - if (peerIndex === -1) { - return { - code: "fabric-mismatch", - message: "The ConnectX-7 rail addresses are not reciprocal.", - }; - } - matches.push({ head: localRail, worker: remainingPeerRails[peerIndex]! }); - remainingPeerRails.splice(peerIndex, 1); - } - if (remainingPeerRails.length !== 0) { - return { - code: "fabric-mismatch", - message: "The ConnectX-7 rail pairing is ambiguous.", - }; - } - const endpointAddresses = new Set( - matches.flatMap(({ head, worker }) => [head.observation.address, worker.observation.address]), - ); - if (endpointAddresses.size !== 4) { - return { - code: "fabric-mismatch", - message: "The ConnectX-7 rail endpoints must have four distinct addresses.", - }; - } - - matches.sort((left, right) => { - const leftNetdev = left.head.observation.netdev; - const rightNetdev = right.head.observation.netdev; - return ( - compareStrings(leftNetdev.toLowerCase(), rightNetdev.toLowerCase()) || - compareStrings(leftNetdev, rightNetdev) - ); - }); - const makeRail = ( - match: { head: ValidatedRail; worker: ValidatedRail }, - index: number, - ): DualSparkTopologyRail => ({ - index, - head: endpoint(local.nodeId, match.head), - worker: endpoint(peer.nodeId, match.worker), - }); - return [makeRail(matches[0]!, 0), makeRail(matches[1]!, 1)]; -} - -function validSshTarget(target: string): boolean { - if (target.length === 0 || target.length > 286 || target !== target.trim()) return false; - const parts = target.split("@"); - if (parts.length > 2) return false; - const host = parts.at(-1) ?? ""; - const username = parts.length === 2 ? parts[0] : undefined; - return ( - (username === undefined || SSH_USERNAME_PATTERN.test(username)) && - (net.isIP(host) === 4 || SSH_HOST_PATTERN.test(host)) - ); -} - -function validateSshBinding( - binding: DualSparkSshBindingObservation, - localNodeId: string, - peerNodeId: string, -): QualificationFailure | undefined { - if ( - binding.state !== "pretrusted" || - binding.fromNodeId !== localNodeId || - binding.toNodeId !== peerNodeId || - !validSshTarget(binding.peerTarget) || - !SAFE_BINDING_HANDLE_PATTERN.test(binding.handle) - ) { - return { - code: "ssh-binding-unavailable", - message: "The peer does not have a valid pretrusted SSH binding.", - }; - } - return undefined; -} - -function record(value: unknown): Record | undefined { - return typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Record) - : undefined; -} - -function artifactEndpointError(value: unknown, expectedNodeId: string): string | undefined { - const candidate = record(value); - const gid = record(candidate?.roceGid); - if ( - !candidate || - candidate.nodeId !== expectedNodeId || - typeof candidate.netdev !== "string" || - !SAFE_INTERFACE_PATTERN.test(candidate.netdev) || - typeof candidate.hcaDevice !== "string" || - !SAFE_INTERFACE_PATTERN.test(candidate.hcaDevice) || - !Number.isInteger(candidate.hcaPort) || - (candidate.hcaPort as number) <= 0 || - (candidate.hcaPort as number) > 255 || - typeof candidate.address !== "string" || - typeof candidate.prefixLength !== "number" || - !validAddress(candidate.address, candidate.prefixLength) || - typeof candidate.peerAddress !== "string" || - net.isIP(candidate.peerAddress) !== net.isIP(candidate.address) || - candidate.peerAddress === candidate.address || - !gid || - !Number.isInteger(gid.index) || - (gid.index as number) < 0 || - (gid.index as number) > 4095 || - typeof gid.value !== "string" || - net.isIP(gid.value) !== 6 || - gid.value === "::" - ) { - return `the ${expectedNodeId} rail endpoint is invalid`; - } - return undefined; -} - -function topologyOutputError( - value: unknown, - subjectNodeIds: readonly string[], -): string | undefined { - const output = record(value); - if (!output) return "topology qualification output is invalid"; - const { headNodeId, workerNodeId } = output; - if ( - typeof headNodeId !== "string" || - typeof workerNodeId !== "string" || - headNodeId === workerNodeId || - !SAFE_ID_PATTERN.test(headNodeId) || - !SAFE_ID_PATTERN.test(workerNodeId) || - [headNodeId, workerNodeId] - .sort(compareStrings) - .some((nodeId, index) => nodeId !== subjectNodeIds[index]) - ) { - return "topology role nodes do not match its subject"; - } - - if (!Array.isArray(output.nodes) || output.nodes.length !== 2) { - return "topology nodes are invalid"; - } - const nodes = output.nodes.map(record); - const head = nodes[0]; - const worker = nodes[1]; - if ( - !head || - !worker || - head.role !== "head" || - head.nodeId !== headNodeId || - worker.role !== "worker" || - worker.nodeId !== workerNodeId || - typeof head.gpuId !== "string" || - !SAFE_ID_PATTERN.test(head.gpuId) || - typeof worker.gpuId !== "string" || - !SAFE_ID_PATTERN.test(worker.gpuId) || - head.gpuId === worker.gpuId - ) { - return "topology node roles or GPU identities are invalid"; - } - - if (!Array.isArray(output.rails) || output.rails.length !== 2) { - return "topology rails are invalid"; - } - const rails: DualSparkTopologyRail[] = []; - for (const [index, value] of output.rails.entries()) { - const rail = record(value); - if (!rail || rail.index !== index) return "topology rail indexes are invalid"; - const headError = artifactEndpointError(rail.head, headNodeId); - const workerError = artifactEndpointError(rail.worker, workerNodeId); - if (headError || workerError) return headError ?? workerError; - const typedRail = rail as unknown as DualSparkTopologyRail; - if ( - typedRail.head.address !== typedRail.worker.peerAddress || - typedRail.worker.address !== typedRail.head.peerAddress || - typedRail.head.prefixLength !== typedRail.worker.prefixLength - ) { - return "topology rail addresses are not reciprocal"; - } - rails.push(typedRail); - } - if ( - new Set(rails.flatMap(({ head, worker }) => [head.address, worker.address])).size !== 4 || - new Set(rails.map(({ head }) => head.netdev)).size !== 2 || - new Set(rails.map(({ worker }) => worker.netdev)).size !== 2 - ) { - return "topology rail identities are not distinct"; - } - if (output.masterAddress !== rails[0]!.head.address) { - return "topology master address does not match the primary head rail"; - } - - const peer = record(output.peer); - if ( - !peer || - typeof peer.target !== "string" || - !validSshTarget(peer.target) || - typeof peer.sshBindingHandle !== "string" || - !SAFE_BINDING_HANDLE_PATTERN.test(peer.sshBindingHandle) - ) { - return "topology peer binding is invalid"; - } - return undefined; -} - -export function dualSparkTopologySubjectDigest(subjectNodeIds: readonly string[]): string { - return managedInferenceDigest([...subjectNodeIds].sort(compareStrings)); -} - -export function dualSparkTopologyOutputDigest(output: DualSparkTopologyOutput): string { - return managedInferenceDigest(output); -} - -export function getDualSparkTopologyArtifactError( - artifact: ManagedInferenceTopologyQualification, - expectedSubjectNodeIds?: readonly string[], -): string | undefined { - if ( - artifact.id !== DUAL_SPARK_TOPOLOGY_ID || - artifact.schemaVersion !== DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION - ) { - return "topology qualification identity is incompatible"; - } - if (artifact.status !== "qualified") return "topology qualification is not qualified"; - if (!Array.isArray(artifact.subjectNodeIds)) return "topology qualification subject is invalid"; - const subjectNodeIds = [...artifact.subjectNodeIds]; - if ( - subjectNodeIds.length !== 2 || - new Set(subjectNodeIds).size !== 2 || - subjectNodeIds.some((nodeId) => !SAFE_ID_PATTERN.test(nodeId)) || - subjectNodeIds.some((nodeId, index) => index > 0 && subjectNodeIds[index - 1]! >= nodeId) - ) { - return "topology qualification subject is invalid"; - } - if ( - expectedSubjectNodeIds && - subjectNodeIds.some((nodeId, index) => nodeId !== expectedSubjectNodeIds[index]) - ) { - return "topology qualification subject does not match the readiness reports"; - } - - const outputError = topologyOutputError(artifact.output, subjectNodeIds); - if (outputError) return outputError; - try { - if (artifact.subjectDigest !== dualSparkTopologySubjectDigest(subjectNodeIds)) { - return "topology qualification subject digest does not match its subject"; - } - if ( - artifact.outputDigest !== - dualSparkTopologyOutputDigest(artifact.output as DualSparkTopologyOutput) - ) { - return "topology qualification output digest does not match its output"; - } - } catch { - return "topology qualification digest is invalid"; - } - return undefined; -} - -export function qualifyDualSparkTopology( - input: Readonly, -): DualSparkTopologyQualificationResult { - if (input.peers.length !== 1) { - return failure(input.intent, { - code: "peer-count", - message: "Automatic dual-node activation requires exactly one discovered DGX Spark peer.", - }); - } - - const evaluatedAtMs = validateQualificationPolicy(input.evaluatedAt, input.maxReadinessAgeMs); - if (typeof evaluatedAtMs !== "number") return failure(input.intent, evaluatedAtMs); - - const peer = input.peers[0]!; - const localNode = validateNode(input.local, evaluatedAtMs, input.maxReadinessAgeMs); - if ("code" in localNode) return failure(input.intent, localNode); - const peerNode = validateNode(peer, evaluatedAtMs, input.maxReadinessAgeMs); - if ("code" in peerNode) return failure(input.intent, peerNode); - - if (input.local.nodeId === peer.nodeId) { - return failure(input.intent, { - code: "duplicate-node-identity", - message: "The two DGX Spark observations refer to the same node identity.", - }); - } - if (localNode.gpuId === peerNode.gpuId) { - return failure(input.intent, { - code: "duplicate-gpu-identity", - message: "The two DGX Spark observations refer to the same GPU identity.", - }); - } - - const sshFailure = validateSshBinding(peer.sshBinding, input.local.nodeId, peer.nodeId); - if (sshFailure) return failure(input.intent, sshFailure); - const rails = matchRails(input.local, peer); - if ("code" in rails) return failure(input.intent, rails); - - const output: DualSparkTopologyOutput = { - headNodeId: input.local.nodeId, - workerNodeId: peer.nodeId, - nodes: [ - { nodeId: input.local.nodeId, gpuId: localNode.gpuId, role: "head" }, - { nodeId: peer.nodeId, gpuId: peerNode.gpuId, role: "worker" }, - ], - rails, - masterAddress: rails[0].head.address, - peer: { - target: peer.sshBinding.peerTarget, - sshBindingHandle: peer.sshBinding.handle, - }, - }; - const subjectNodeIds = [input.local.nodeId, peer.nodeId].sort(); - try { - return { - outcome: "qualified", - artifact: { - id: DUAL_SPARK_TOPOLOGY_ID, - schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - status: "qualified", - subjectNodeIds, - subjectDigest: dualSparkTopologySubjectDigest(subjectNodeIds), - outputDigest: dualSparkTopologyOutputDigest(output), - output, - }, - }; - } catch { - return failure(input.intent, { - code: "artifact-digest-failed", - message: "The qualified topology could not be bound to its subject and output.", - }); - } -} diff --git a/src/lib/inference/serving/dual-spark-discovery-production.ts b/src/lib/inference/serving/managed-cluster-discovery-production.ts similarity index 95% rename from src/lib/inference/serving/dual-spark-discovery-production.ts rename to src/lib/inference/serving/managed-cluster-discovery-production.ts index 158c34c90e7..6ea96f8155c 100644 --- a/src/lib/inference/serving/dual-spark-discovery-production.ts +++ b/src/lib/inference/serving/managed-cluster-discovery-production.ts @@ -25,14 +25,14 @@ import { writeDualStationSshBinding, } from "../vllm-station-ssh-binding.js"; import type { - DualSparkCommandResult, - DualSparkConnectivityRequest, - DualSparkDiscoveryDeps, - DualSparkHostObservation, - DualSparkPinnedPeerTransport, - DualSparkReadOnlyHostTransport, -} from "./dual-spark-discovery.js"; -import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./spark-runtime-receipt-path.js"; + ManagedClusterCommandResult, + ManagedClusterConnectivityRequest, + ManagedClusterDiscoveryDeps, + ManagedClusterHostObservation, + ManagedClusterPinnedPeerTransport, + ManagedClusterReadOnlyHostTransport, +} from "./managed-cluster-discovery.js"; +import { MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE } from "./managed-cluster-runtime-receipt-path.js"; const COMMAND_TIMEOUT_MS = 20_000; const MAX_COMMAND_OUTPUT_BYTES = 4 * 1024 * 1024; @@ -47,7 +47,7 @@ const SHA256_PATTERN = /^[a-f0-9]{64}$/; const SAFE_SSH_KEY_TYPE_PATTERN = /^(?:ssh-|ecdsa-|sk-)[A-Za-z0-9@._+-]+$/; const SAFE_SSH_KEY_DATA_PATTERN = /^[A-Za-z0-9+/]+={0,3}$/; -export type DualSparkSpawnSync = ( +export type ManagedClusterSpawnSync = ( file: string, args: readonly string[], options: SpawnSyncOptionsWithStringEncoding, @@ -58,7 +58,7 @@ export type DualSparkSpawnSync = ( readonly error?: Error; }; -export type DualSparkHostParser = (value: unknown) => DualSparkHostObservation; +export type ManagedClusterHostParser = (value: unknown) => ManagedClusterHostObservation; function compareStrings(left: string, right: string): number { return left < right ? -1 : left > right ? 1 : 0; @@ -501,7 +501,7 @@ function defaultSpawnSync( file: string, args: readonly string[], options: SpawnSyncOptionsWithStringEncoding, -): ReturnType { +): ReturnType { const result = spawnSync(file, [...args], options); return { status: result.status, @@ -523,12 +523,12 @@ function validateArgv(argv: readonly string[]): void { } function runCommand( - spawn: DualSparkSpawnSync, + spawn: ManagedClusterSpawnSync, file: string, args: readonly string[], input = "", env: Readonly> = buildVllmSshTransportEnv({ LC_ALL: "C", LANG: "C" }), -): DualSparkCommandResult { +): ManagedClusterCommandResult { const result = spawn(file, args, { encoding: "utf8", input, @@ -546,7 +546,7 @@ function runCommand( }; } -function commandSucceeded(result: DualSparkCommandResult, requireOutput = false): boolean { +function commandSucceeded(result: ManagedClusterCommandResult, requireOutput = false): boolean { return ( result.status === 0 && result.error === undefined && @@ -582,7 +582,7 @@ function readBoundedDirectory(directory: string): string[] { return entries.sort(compareStrings); } -function createLocalTransport(spawn: DualSparkSpawnSync): DualSparkReadOnlyHostTransport { +function createLocalTransport(spawn: ManagedClusterSpawnSync): ManagedClusterReadOnlyHostTransport { return { execute(argv) { validateArgv(argv); @@ -599,7 +599,7 @@ function createLocalTransport(spawn: DualSparkSpawnSync): DualSparkReadOnlyHostT }; } -function parseJsonCommandResult(result: DualSparkCommandResult, label: string): unknown { +function parseJsonCommandResult(result: ManagedClusterCommandResult, label: string): unknown { if (!commandSucceeded(result, true)) throw new Error(`${label} failed`); if (Buffer.byteLength(result.stdout, "utf8") > MAX_COMMAND_OUTPUT_BYTES) { throw new Error(`${label} output is too large`); @@ -612,9 +612,9 @@ function parseJsonCommandResult(result: DualSparkCommandResult, label: string): } function probeHostWithTransport( - transport: DualSparkReadOnlyHostTransport, - parseHost: DualSparkHostParser, -): DualSparkHostObservation { + transport: ManagedClusterReadOnlyHostTransport, + parseHost: ManagedClusterHostParser, +): ManagedClusterHostObservation { const result = transport.execute(["python3", "-c", HOST_PROBE_SCRIPT]); return parseHost(parseJsonCommandResult(result, "DGX Spark host probe")); } @@ -692,7 +692,7 @@ function canonicalSshHost(value: string): boolean { } function trustedKnownHostLines( - spawn: DualSparkSpawnSync, + spawn: ManagedClusterSpawnSync, lookupHost: string, files: readonly string[], ): string[] | null { @@ -740,7 +740,7 @@ function trustedKnownHostLines( } function inspectPretrustedTarget( - spawn: DualSparkSpawnSync, + spawn: ManagedClusterSpawnSync, rawTarget: string, ): QualifiedStationSshIdentity | null { const target = validatePeerTarget(rawTarget); @@ -841,11 +841,11 @@ function assertTemporaryPinnedFiles( } function openPinnedPeerTransport( - spawn: DualSparkSpawnSync, + spawn: ManagedClusterSpawnSync, identity: QualifiedStationSshIdentity, -): DualSparkPinnedPeerTransport { +): ManagedClusterPinnedPeerTransport { assertPinnedIdentity(identity); - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dual-spark-")); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-cluster-")); fs.chmodSync(directory, 0o700); const knownHostsFile = path.join(directory, "known_hosts"); try { @@ -866,7 +866,7 @@ function openPinnedPeerTransport( throw error; } - const execute = (argv: readonly string[]): DualSparkCommandResult => { + const execute = (argv: readonly string[]): ManagedClusterCommandResult => { validateArgv(argv); assertTemporaryPinnedFiles(directory, knownHostsFile, identity.hostKeyDigest); const request = Buffer.from(JSON.stringify({ argv }), "utf8").toString("base64url"); @@ -898,7 +898,7 @@ function openPinnedPeerTransport( REMOTE_ARGV_EXECUTOR, ); }; - const transport: DualSparkReadOnlyHostTransport = { + const transport: ManagedClusterReadOnlyHostTransport = { execute, readFile(filePath) { if (!path.posix.isAbsolute(filePath) || path.posix.normalize(filePath) !== filePath) { @@ -953,8 +953,8 @@ function isRecordArray(value: unknown): value is Record[] { } function connectivityCheck( - transport: DualSparkReadOnlyHostTransport, - request: DualSparkConnectivityRequest, + transport: ManagedClusterReadOnlyHostTransport, + request: ManagedClusterConnectivityRequest, ): boolean { const routeResult = transport.execute([ "ip", @@ -1032,8 +1032,8 @@ function connectivityCheck( } function probeConnectivity( - transport: DualSparkReadOnlyHostTransport, - requests: readonly DualSparkConnectivityRequest[], + transport: ManagedClusterReadOnlyHostTransport, + requests: readonly ManagedClusterConnectivityRequest[], ): boolean { if ( requests.length !== 2 || @@ -1052,8 +1052,8 @@ function probeConnectivity( } function createCanonicalReadiness( - host: DualSparkHostObservation, - transport: DualSparkReadOnlyHostTransport, + host: ManagedClusterHostObservation, + transport: ManagedClusterReadOnlyHostTransport, buildIdentity: BuildIdentity, now: Date, ): SystemReadinessReport { @@ -1153,10 +1153,10 @@ function claimBinding(statePath: string): boolean { * Construct the production discovery seams. The optional spawn adapter exists * only so strict SSH argv behavior can be tested without network or host mutation. */ -export function createProductionDualSparkDiscoveryDeps( - parseHost: DualSparkHostParser, - spawn: DualSparkSpawnSync = defaultSpawnSync, -): DualSparkDiscoveryDeps { +export function createProductionManagedClusterDiscoveryDeps( + parseHost: ManagedClusterHostParser, + spawn: ManagedClusterSpawnSync = defaultSpawnSync, +): ManagedClusterDiscoveryDeps { return { now: () => new Date(), currentUid: () => process.getuid?.() ?? null, @@ -1171,7 +1171,7 @@ export function createProductionDualSparkDiscoveryDeps( writeBinding: writeDualStationSshBinding, clearBinding: clearDualStationSshBinding, encodeBinding: encodeDualStationSshBindingHandoff, - resolveBindingStatePath: () => - path.join(managedVllmStateDir(), DUAL_SPARK_MANAGED_SERVING_STATE_FILE), + resolveBindingStatePath: (nodeId) => + path.join(managedVllmStateDir(), `${MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE}.${nodeId}`), }; } diff --git a/src/lib/inference/serving/dual-spark-discovery.test.ts b/src/lib/inference/serving/managed-cluster-discovery.test.ts similarity index 79% rename from src/lib/inference/serving/dual-spark-discovery.test.ts rename to src/lib/inference/serving/managed-cluster-discovery.test.ts index e9f04ba17b3..f85b93eb8fe 100644 --- a/src/lib/inference/serving/dual-spark-discovery.test.ts +++ b/src/lib/inference/serving/managed-cluster-discovery.test.ts @@ -15,20 +15,20 @@ import { stationKnownHostsDigest, } from "../vllm-station-ssh-binding.js"; import { - confirmDualSparkManagedServingCapability, - createDualSparkDiscoveryDeps, - type DualSparkDetectedManagedServingCapability, - type DualSparkDiscoveryDeps, - type DualSparkHostObservation, - type DualSparkReadOnlyHostTransport, - type DualSparkSpawnSync, - NEMOCLAW_DGX_SPARK_PEER_ENV, + confirmManagedClusterManagedServingCapability, + createManagedClusterDiscoveryDeps, + type ManagedClusterDetectedManagedServingCapability, + type ManagedClusterDiscoveryDeps, + type ManagedClusterHostObservation, + type ManagedClusterReadOnlyHostTransport, + type ManagedClusterSpawnSync, + NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV, NEMOCLAW_SERVING_PRESET_ENV, - parseDualSparkHostObservation, - probeDualSparkManagedServingCapability, -} from "./dual-spark-discovery.js"; -import { FIXTURE_DUAL_SPARK_PRESET_ID } from "./dual-spark-fixture.test-support.js"; -import { DUAL_SPARK_MANAGED_LABEL, DUAL_SPARK_VLLM_MASTER_PORT } from "./dual-spark-materialize.js"; + parseManagedClusterHostObservation, + probeManagedClusterManagedServingCapability, +} from "./managed-cluster-discovery.js"; +import { FIXTURE_MANAGED_CLUSTER_PRESET_ID } from "./managed-cluster-fixture.test-support.js"; +import { MANAGED_CLUSTER_MANAGED_LABEL } from "./managed-cluster-materialize.js"; const NOW = new Date("2026-08-02T20:00:00.000Z"); const SOURCE_REVISION = "1d6948d89b46eab739728215f9a19ef40b8f6121"; @@ -68,15 +68,15 @@ const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixtur signal: "managed label", name: "foreign-inference", image: "example.invalid/inference:latest", - labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + labels: { [MANAGED_CLUSTER_MANAGED_LABEL]: "foreign" }, }, ]; -function expectDetectedPair( - detected: ReturnType, -): DualSparkDetectedManagedServingCapability { +function expectDetectedCluster( + detected: ReturnType, +): ManagedClusterDetectedManagedServingCapability { expect(detected.kind).toBe("ready"); - return detected as DualSparkDetectedManagedServingCapability; + return detected as ManagedClusterDetectedManagedServingCapability; } function readiness(overrides: Partial = {}): SystemReadinessReport { @@ -130,8 +130,8 @@ function capacity( function host( role: "local" | "peer", - overrides: Partial = {}, -): DualSparkHostObservation { + overrides: Partial = {}, +): ManagedClusterHostObservation { const local = role === "local"; const uid = 1000; const gid = 1000; @@ -203,7 +203,7 @@ function host( }; } -const transport = (name: string): DualSparkReadOnlyHostTransport => ({ +const transport = (name: string): ManagedClusterReadOnlyHostTransport => ({ execute: () => ({ status: 0, stdout: name, stderr: "" }), readFile: () => name, readdir: () => [], @@ -244,7 +244,7 @@ function binding(peerIdentity: QualifiedStationSshIdentity): DualStationSshBindi }; } -function fixture(overrides: Partial = {}) { +function fixture(overrides: Partial = {}) { const events: string[] = []; const localTransport = transport("local"); const peerTransports = new Map([ @@ -252,7 +252,7 @@ function fixture(overrides: Partial = {}) { ["192.168.101.2", transport("peer-101")], ]); let bindingWrites = 0; - const deps: DualSparkDiscoveryDeps = { + const deps: ManagedClusterDiscoveryDeps = { now: () => NOW, currentUid: () => 1000, getBuildIdentity: () => ({ @@ -285,18 +285,18 @@ function fixture(overrides: Partial = {}) { }, clearBinding: () => events.push("clear-binding"), encodeBinding: () => "binding-token", - resolveBindingStatePath: () => "/state/dual-spark.json", + resolveBindingStatePath: () => "/state/managed-cluster.json", ...overrides, }; return { deps, events, bindingWrites: () => bindingWrites, localTransport }; } -describe("dual DGX Spark managed-serving discovery", () => { +describe("managed DGX Spark cluster discovery", () => { it("accepts the bounded production observation and rejects malformed cache metadata", () => { const observed = host("local"); - expect(parseDualSparkHostObservation(observed)).toBe(observed); + expect(parseManagedClusterHostObservation(observed)).toBe(observed); expect(() => - parseDualSparkHostObservation({ + parseManagedClusterHostObservation({ ...observed, storage: { ...observed.storage, @@ -314,7 +314,7 @@ describe("dual DGX Spark managed-serving discovery", () => { }); expect( - probeDualSparkManagedServingCapability({ + probeManagedClusterManagedServingCapability({ env: { [NEMOCLAW_SERVING_PRESET_ENV]: "another-preset" }, deps, }), @@ -327,7 +327,7 @@ describe("dual DGX Spark managed-serving discovery", () => { expect(bindingWrites()).toBe(0); }); - it("rejects an explicit dual-Spark peer combined with another serving preset", () => { + it("rejects an explicit managed cluster peer combined with another serving preset", () => { const { deps, events, bindingWrites } = fixture({ localTransport: () => { throw new Error("must not probe"); @@ -335,10 +335,10 @@ describe("dual DGX Spark managed-serving discovery", () => { }); expect( - probeDualSparkManagedServingCapability({ + probeManagedClusterManagedServingCapability({ env: { [NEMOCLAW_SERVING_PRESET_ENV]: "another-preset", - [NEMOCLAW_DGX_SPARK_PEER_ENV]: "spark-worker.local", + [NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV]: "spark-worker.local", }, deps, }), @@ -355,8 +355,8 @@ describe("dual DGX Spark managed-serving discovery", () => { }); expect( - probeDualSparkManagedServingCapability({ - env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_DUAL_SPARK_PRESET_ID }, + probeManagedClusterManagedServingCapability({ + env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_MANAGED_CLUSTER_PRESET_ID }, deps, loadCatalog: () => { throw new Error("catalog unavailable"); @@ -367,31 +367,33 @@ describe("dual DGX Spark managed-serving discovery", () => { expect(bindingWrites()).toBe(0); }); - it("persists one binding only after the detected pair is confirmed and revalidated", () => { + it("persists bindings only after the detected cluster is confirmed and revalidated", () => { const { deps, events, bindingWrites } = fixture(); - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); expect(detected).toMatchObject({ kind: "ready", selectionIntent: "automatic", - peerSshBindingStatePath: "/state/dual-spark.json", + sshClaims: [{ statePath: "/state/managed-cluster.json" }], local: { hostname: "spark-head", uid: 1000 }, - peer: { hostname: "spark-worker", uid: 1000 }, + peers: [{ hostname: "spark-worker", uid: 1000 }], topology: { status: "qualified" }, }); expect(bindingWrites()).toBe(0); expect(events).not.toContain("write-binding"); - const confirmed = confirmDualSparkManagedServingCapability(detected, { + const confirmed = confirmManagedClusterManagedServingCapability(detected, { env: {}, deps, }); expect(confirmed).toMatchObject({ kind: "ready", - peerSshBindingHandle: "binding-token", + sshBindings: [{ handle: "binding-token" }], topology: { - output: { peer: { sshBindingHandle: "binding-token" } }, + output: { peers: [{ sshBindingHandle: "binding-token" }] }, }, }); expect(bindingWrites()).toBe(1); @@ -412,7 +414,7 @@ describe("dual DGX Spark managed-serving discovery", () => { inspectPretrustedTarget: () => null, }); - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", code: "no-match", }); @@ -423,8 +425,8 @@ describe("dual DGX Spark managed-serving discovery", () => { const { deps } = fixture({ inspectPretrustedTarget: () => null }); expect( - probeDualSparkManagedServingCapability({ - env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_DUAL_SPARK_PRESET_ID }, + probeManagedClusterManagedServingCapability({ + env: { [NEMOCLAW_SERVING_PRESET_ENV]: FIXTURE_MANAGED_CLUSTER_PRESET_ID }, deps, }), ).toMatchObject({ kind: "unavailable", code: "peer-trust-unavailable" }); @@ -434,8 +436,8 @@ describe("dual DGX Spark managed-serving discovery", () => { const { deps } = fixture({ inspectPretrustedTarget: () => null }); expect( - probeDualSparkManagedServingCapability({ - env: { [NEMOCLAW_DGX_SPARK_PEER_ENV]: "spark-worker.local" }, + probeManagedClusterManagedServingCapability({ + env: { [NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV]: "spark-worker.local" }, deps, }), ).toMatchObject({ kind: "unavailable", code: "peer-trust-unavailable" }); @@ -449,7 +451,7 @@ describe("dual DGX Spark managed-serving discovery", () => { }, }); - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", code: "no-match", }); @@ -462,7 +464,7 @@ describe("dual DGX Spark managed-serving discovery", () => { const base = fixture(); const deps = { ...base.deps, - probeHost: (candidate: DualSparkReadOnlyHostTransport) => + probeHost: (candidate: ManagedClusterReadOnlyHostTransport) => candidate === base.localTransport ? host("local", { runtimeSnapshot: { @@ -482,7 +484,7 @@ describe("dual DGX Spark managed-serving discovery", () => { : host("peer"), }; - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", code: "runtime-conflict", }); @@ -494,7 +496,7 @@ describe("dual DGX Spark managed-serving discovery", () => { const base = fixture(); const deps = { ...base.deps, - probeHost: (candidate: DualSparkReadOnlyHostTransport) => + probeHost: (candidate: ManagedClusterReadOnlyHostTransport) => candidate === base.localTransport ? host("local", { runtimeSnapshot: { @@ -514,7 +516,7 @@ describe("dual DGX Spark managed-serving discovery", () => { : host("peer"), }; - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "ready", }); expect(base.bindingWrites()).toBe(0); @@ -523,7 +525,7 @@ describe("dual DGX Spark managed-serving discovery", () => { it.each([ { name: "an active earlyoom service", - mutate: (value: DualSparkHostObservation) => ({ + mutate: (value: ManagedClusterHostObservation) => ({ ...value, earlyoom: { installed: true, @@ -535,18 +537,27 @@ describe("dual DGX Spark managed-serving discovery", () => { }, { name: "a related runtime", - mutate: (value: DualSparkHostObservation) => ({ + mutate: (value: ManagedClusterHostObservation) => ({ ...value, runtimeSnapshot: { - containers: [], - listeningPorts: [DUAL_SPARK_VLLM_MASTER_PORT], + containers: [ + { + id: "9".repeat(64), + name: "managed-vllm", + image: "example.invalid/vllm:latest", + running: true, + healthy: true, + labels: { [MANAGED_CLUSTER_MANAGED_LABEL]: "true" }, + }, + ], + listeningPorts: [], }, }), code: "runtime-conflict", }, { name: "an inconclusive runtime inspection", - mutate: (value: DualSparkHostObservation) => ({ + mutate: (value: ManagedClusterHostObservation) => ({ ...value, runtimeInspectionComplete: false, }), @@ -554,7 +565,7 @@ describe("dual DGX Spark managed-serving discovery", () => { }, { name: "a missing exact cache root", - mutate: (value: DualSparkHostObservation) => ({ + mutate: (value: ManagedClusterHostObservation) => ({ ...value, storage: { ...value.storage, @@ -567,11 +578,11 @@ describe("dual DGX Spark managed-serving discovery", () => { const base = fixture(); const deps = { ...base.deps, - probeHost: (candidate: DualSparkReadOnlyHostTransport) => + probeHost: (candidate: ManagedClusterReadOnlyHostTransport) => candidate === base.localTransport ? mutate(host("local")) : host("peer"), }; - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", code, }); @@ -582,7 +593,7 @@ describe("dual DGX Spark managed-serving discovery", () => { it("does not claim when the exact pretrusted peer identity changes after confirmation", () => { const base = fixture(); let inspections = 0; - const deps: DualSparkDiscoveryDeps = { + const deps: ManagedClusterDiscoveryDeps = { ...base.deps, inspectPretrustedTarget: (target) => { inspections += 1; @@ -600,9 +611,13 @@ describe("dual DGX Spark managed-serving discovery", () => { return true; }, }; - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); - expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + expect( + confirmManagedClusterManagedServingCapability(detected, { env: {}, deps }), + ).toMatchObject({ kind: "unavailable", code: "peer-identity-ambiguous", }); @@ -613,14 +628,23 @@ describe("dual DGX Spark managed-serving discovery", () => { it("rechecks related runtime and listeners before claiming the binding", () => { const base = fixture(); let runtimeAppeared = false; - const deps: DualSparkDiscoveryDeps = { + const deps: ManagedClusterDiscoveryDeps = { ...base.deps, probeHost: (candidate) => candidate === base.localTransport && runtimeAppeared ? host("local", { runtimeSnapshot: { - containers: [], - listeningPorts: [DUAL_SPARK_VLLM_MASTER_PORT], + containers: [ + { + id: "9".repeat(64), + name: "managed-vllm", + image: "example.invalid/vllm:latest", + running: true, + healthy: true, + labels: { [MANAGED_CLUSTER_MANAGED_LABEL]: "true" }, + }, + ], + listeningPorts: [], }, }) : candidate === base.localTransport @@ -631,10 +655,14 @@ describe("dual DGX Spark managed-serving discovery", () => { return true; }, }; - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); runtimeAppeared = true; - expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + expect( + confirmManagedClusterManagedServingCapability(detected, { env: {}, deps }), + ).toMatchObject({ kind: "unavailable", code: "runtime-conflict", }); @@ -646,9 +674,13 @@ describe("dual DGX Spark managed-serving discovery", () => { const { deps, events, bindingWrites } = fixture({ claimBinding: () => false, }); - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); - expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + expect( + confirmManagedClusterManagedServingCapability(detected, { env: {}, deps }), + ).toMatchObject({ kind: "unavailable", code: "binding-conflict", }); @@ -663,9 +695,13 @@ describe("dual DGX Spark managed-serving discovery", () => { throw new Error("partial write"); }, }); - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); - expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + expect( + confirmManagedClusterManagedServingCapability(detected, { env: {}, deps }), + ).toMatchObject({ kind: "unavailable", code: "binding-persistence-failed", }); @@ -682,9 +718,13 @@ describe("dual DGX Spark managed-serving discovery", () => { throw new Error("encode failed"); }, }; - const detected = expectDetectedPair(probeDualSparkManagedServingCapability({ env: {}, deps })); + const detected = expectDetectedCluster( + probeManagedClusterManagedServingCapability({ env: {}, deps }), + ); - expect(confirmDualSparkManagedServingCapability(detected, { env: {}, deps })).toMatchObject({ + expect( + confirmManagedClusterManagedServingCapability(detected, { env: {}, deps }), + ).toMatchObject({ kind: "unavailable", code: "binding-persistence-failed", }); @@ -697,7 +737,7 @@ describe("dual DGX Spark managed-serving discovery", () => { it("fails closed when the controller UID differs from the local cache owner", () => { const { deps, bindingWrites } = fixture({ currentUid: () => 2000 }); - expect(probeDualSparkManagedServingCapability({ env: {}, deps })).toMatchObject({ + expect(probeManagedClusterManagedServingCapability({ env: {}, deps })).toMatchObject({ kind: "not-selected", code: "no-match", }); @@ -709,9 +749,9 @@ describe("production pinned peer transport", () => { it("atomically preserves an existing binding-root owner", () => { const parent = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-spark-binding-")); fs.chmodSync(parent, 0o700); - const statePath = path.join(parent, "dual-spark.json"); + const statePath = path.join(parent, "managed-cluster.json"); const bindingRoot = `${statePath}.ssh-binding`; - const deps = createDualSparkDiscoveryDeps(() => ({ + const deps = createManagedClusterDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "", @@ -736,8 +776,8 @@ describe("production pinned peer transport", () => { const alias = path.join(root, "alias"); fs.mkdirSync(parent, { mode: 0o700 }); fs.symlinkSync(parent, alias, "dir"); - const statePath = path.join(alias, "dual-spark.json"); - const deps = createDualSparkDiscoveryDeps(() => ({ + const statePath = path.join(alias, "managed-cluster.json"); + const deps = createManagedClusterDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "", @@ -745,7 +785,7 @@ describe("production pinned peer transport", () => { try { expect(() => deps.claimBinding(statePath)).toThrow(); - expect(fs.existsSync(`${path.join(parent, "dual-spark.json")}.ssh-binding`)).toBe(false); + expect(fs.existsSync(`${path.join(parent, "managed-cluster.json")}.ssh-binding`)).toBe(false); } finally { fs.rmSync(root, { force: true, recursive: true }); } @@ -757,7 +797,7 @@ describe("production pinned peer transport", () => { args: readonly string[]; options: SpawnSyncOptionsWithStringEncoding; }> = []; - const spawn: DualSparkSpawnSync = (file, args, options) => { + const spawn: ManagedClusterSpawnSync = (file, args, options) => { calls.push({ file, args: [...args], options }); return { status: 0, @@ -772,7 +812,7 @@ describe("production pinned peer transport", () => { process.env.DOCKER_CONFIG = "/tmp/ambient-docker-config"; try { - const deps = createDualSparkDiscoveryDeps(spawn); + const deps = createManagedClusterDiscoveryDeps(spawn); expect(deps.probeHost(deps.localTransport()).hostname).toBe("spark-head"); const pinned = deps.openPinnedPeerTransport(identity("192.168.100.2")); try { @@ -812,7 +852,7 @@ describe("production pinned peer transport", () => { }); it("requires direct routes, exact neighbors, and jumbo reachability on both rails", () => { - const deps = createDualSparkDiscoveryDeps(() => ({ + const deps = createManagedClusterDiscoveryDeps(() => ({ status: 0, stdout: "", stderr: "", @@ -832,7 +872,7 @@ describe("production pinned peer transport", () => { }, ]; let routedThroughGateway = false; - const directTransport: DualSparkReadOnlyHostTransport = { + const directTransport: ManagedClusterReadOnlyHostTransport = { execute: (argv) => { const routeResponse = () => ({ status: 0, @@ -883,11 +923,11 @@ describe("production pinned peer transport", () => { args: readonly string[]; options: SpawnSyncOptionsWithStringEncoding; }> = []; - const spawn: DualSparkSpawnSync = (file, args, options) => { + const spawn: ManagedClusterSpawnSync = (file, args, options) => { calls.push({ file, args: [...args], options }); return { status: 0, stdout: "aarch64\n", stderr: "" }; }; - const deps = createDualSparkDiscoveryDeps(spawn); + const deps = createManagedClusterDiscoveryDeps(spawn); const pinned = deps.openPinnedPeerTransport(identity("192.168.100.2")); try { diff --git a/src/lib/inference/serving/dual-spark-discovery.ts b/src/lib/inference/serving/managed-cluster-discovery.ts similarity index 56% rename from src/lib/inference/serving/dual-spark-discovery.ts rename to src/lib/inference/serving/managed-cluster-discovery.ts index 4e8dfd56f72..c880b3be535 100644 --- a/src/lib/inference/serving/dual-spark-discovery.ts +++ b/src/lib/inference/serving/managed-cluster-discovery.ts @@ -10,30 +10,27 @@ import { type DualStationSshBinding, type QualifiedStationSshIdentity, } from "../vllm-station-ssh-binding.js"; -import { - DUAL_SPARK_VLLM_MASTER_PORT, - DUAL_SPARK_VLLM_MATERIALIZER_REF, -} from "./adapter-registry.js"; +import { MANAGED_CLUSTER_VLLM_MATERIALIZER_REF } from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; -import { createProductionDualSparkDiscoveryDeps } from "./dual-spark-discovery-production.js"; +import { createProductionManagedClusterDiscoveryDeps } from "./managed-cluster-discovery-production.js"; import { - type DualSparkNodeSnapshot, - type DualSparkObservedContainer, isRelatedManagedVllmContainer, -} from "./dual-spark-lifecycle.js"; + type ManagedClusterNodeSnapshot, + type ManagedClusterObservedContainer, +} from "./managed-cluster-lifecycle.js"; import { - type DualSparkNodeObservation, - type DualSparkPeerObservation, - type DualSparkRailObservation, - type DualSparkTopologyArtifact, - type DualSparkTopologyOutput, - dualSparkTopologyOutputDigest, - getDualSparkTopologyArtifactError, - qualifyDualSparkTopology, -} from "./dual-spark-topology.js"; - -export const NEMOCLAW_DGX_SPARK_PEER_ENV = "NEMOCLAW_DGX_SPARK_PEER" as const; + getManagedClusterTopologyArtifactError, + type ManagedClusterNodeObservation, + type ManagedClusterPeerObservation, + type ManagedClusterRailObservation, + type ManagedClusterTopologyArtifact, + type ManagedClusterTopologyOutput, + managedClusterTopologyOutputDigest, + qualifyManagedClusterTopology, +} from "./managed-cluster-topology.js"; + +export const NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV = "NEMOCLAW_MANAGED_CLUSTER_PEERS" as const; export const NEMOCLAW_SERVING_PRESET_ENV = "NEMOCLAW_SERVING_PRESET" as const; const HOST_PROBE_SCHEMA_VERSION = 1; @@ -51,37 +48,37 @@ const MAC_PATTERN = /^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/; const PCI_ADDRESS_PATTERN = /^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/; const SHA256_PATTERN = /^[a-f0-9]{64}$/; -export interface DualSparkCommandResult { +export interface ManagedClusterCommandResult { readonly status: number | null; readonly stdout: string; readonly stderr: string; readonly error?: string; } -export interface DualSparkReadOnlyHostTransport { - execute(argv: readonly string[]): DualSparkCommandResult; +export interface ManagedClusterReadOnlyHostTransport { + execute(argv: readonly string[]): ManagedClusterCommandResult; readFile(filePath: string): string; readdir(directory: string): string[]; } -export interface DualSparkGpuObservation { +export interface ManagedClusterGpuObservation { readonly index: number; readonly name: string; readonly uuid: string; } -export interface DualSparkIpv4Observation { +export interface ManagedClusterIpv4Observation { readonly address: string; readonly prefixLength: number; } -export interface DualSparkRoceGidHostObservation { +export interface ManagedClusterRoceGidHostObservation { readonly index: number; readonly value: string; readonly ipv4Address: string; } -export interface DualSparkCx7RailHostObservation { +export interface ManagedClusterCx7RailHostObservation { readonly physicalPortId: string; readonly netdev: string; readonly hcaDevice: string; @@ -95,17 +92,17 @@ export interface DualSparkCx7RailHostObservation { readonly linkLayer: string; readonly speedMbps: number; readonly mtu: number; - readonly ipv4Addresses: readonly DualSparkIpv4Observation[]; - readonly roceV2Ipv4Gids: readonly DualSparkRoceGidHostObservation[]; + readonly ipv4Addresses: readonly ManagedClusterIpv4Observation[]; + readonly roceV2Ipv4Gids: readonly ManagedClusterRoceGidHostObservation[]; } -export interface DualSparkEarlyoomObservation { +export interface ManagedClusterEarlyoomObservation { readonly installed: boolean; readonly active: "active" | "inactive" | "unknown"; readonly enabled: "enabled" | "disabled" | "unknown"; } -export interface DualSparkStorageCapacityObservation { +export interface ManagedClusterStorageCapacityObservation { readonly requestedPath: string; readonly probePath: string | null; readonly filesystemId: string | null; @@ -117,16 +114,16 @@ export interface DualSparkStorageCapacityObservation { readonly writableByUser: boolean; } -export interface DualSparkStorageObservation { - readonly huggingFace: DualSparkStorageCapacityObservation & { +export interface ManagedClusterStorageObservation { + readonly huggingFace: ManagedClusterStorageCapacityObservation & { readonly cacheRoot: string; }; - readonly docker: DualSparkStorageCapacityObservation & { + readonly docker: ManagedClusterStorageCapacityObservation & { readonly dockerRootDir: string | null; }; } -export interface DualSparkHostObservation { +export interface ManagedClusterHostObservation { readonly schemaVersion: 1; readonly hostname: string; readonly nodeId: string; @@ -136,53 +133,53 @@ export interface DualSparkHostObservation { readonly username: string; readonly uid: number; readonly gid: number; - readonly gpus: readonly DualSparkGpuObservation[]; - readonly rails: readonly DualSparkCx7RailHostObservation[]; - readonly earlyoom: DualSparkEarlyoomObservation; + readonly gpus: readonly ManagedClusterGpuObservation[]; + readonly rails: readonly ManagedClusterCx7RailHostObservation[]; + readonly earlyoom: ManagedClusterEarlyoomObservation; readonly runtimeInspectionComplete: boolean; - readonly runtimeSnapshot: DualSparkNodeSnapshot; - readonly storage: DualSparkStorageObservation; + readonly runtimeSnapshot: ManagedClusterNodeSnapshot; + readonly storage: ManagedClusterStorageObservation; } -export interface DualSparkPinnedPeerTransport { - readonly transport: DualSparkReadOnlyHostTransport; +export interface ManagedClusterPinnedPeerTransport { + readonly transport: ManagedClusterReadOnlyHostTransport; close(): void; } -export interface DualSparkConnectivityRequest { +export interface ManagedClusterConnectivityRequest { readonly netdev: string; readonly sourceAddress: string; readonly peerAddress: string; readonly expectedPeerMac: string; } -export interface DualSparkDiscoveryDeps { +export interface ManagedClusterDiscoveryDeps { now(): Date; currentUid(): number | null; getBuildIdentity(): BuildIdentity; - localTransport(): DualSparkReadOnlyHostTransport; - probeHost(transport: DualSparkReadOnlyHostTransport): DualSparkHostObservation; + localTransport(): ManagedClusterReadOnlyHostTransport; + probeHost(transport: ManagedClusterReadOnlyHostTransport): ManagedClusterHostObservation; inspectPretrustedTarget(target: string): QualifiedStationSshIdentity | null; - openPinnedPeerTransport(identity: QualifiedStationSshIdentity): DualSparkPinnedPeerTransport; + openPinnedPeerTransport(identity: QualifiedStationSshIdentity): ManagedClusterPinnedPeerTransport; createReadiness( - host: DualSparkHostObservation, - transport: DualSparkReadOnlyHostTransport, + host: ManagedClusterHostObservation, + transport: ManagedClusterReadOnlyHostTransport, buildIdentity: BuildIdentity, now: Date, ): SystemReadinessReport; probeConnectivity( - transport: DualSparkReadOnlyHostTransport, - requests: readonly DualSparkConnectivityRequest[], + transport: ManagedClusterReadOnlyHostTransport, + requests: readonly ManagedClusterConnectivityRequest[], ): boolean; /** Atomically claim a new binding root. False means an existing owner won. */ claimBinding(statePath: string): boolean; writeBinding(statePath: string, identity: QualifiedStationSshIdentity): DualStationSshBinding; clearBinding(statePath: string): void; encodeBinding(binding: DualStationSshBinding): string; - resolveBindingStatePath(): string; + resolveBindingStatePath(nodeId: string): string; } -export type DualSparkManagedServingFailureCode = +export type ManagedClusterManagedServingFailureCode = | "no-match" | "incompatible-selection" | "invalid-peer" @@ -190,6 +187,7 @@ export type DualSparkManagedServingFailureCode = | "peer-trust-unavailable" | "peer-identity-ambiguous" | "peer-host-unavailable" + | "peer-count" | "host-unqualified" | "earlyoom-active" | "earlyoom-unknown" @@ -204,105 +202,113 @@ export type DualSparkManagedServingFailureCode = | "binding-persistence-failed" | "topology-unavailable"; -export type DualSparkDetectedManagedServingCapability = { +export type ManagedClusterDetectedManagedServingCapability = { readonly kind: "ready"; readonly selectionIntent: "automatic" | "explicit"; - readonly topology: DualSparkTopologyArtifact; - readonly local: DualSparkHostObservation; - readonly peer: DualSparkHostObservation; - readonly readiness: readonly [ - { readonly nodeId: string; readonly report: SystemReadinessReport }, - { readonly nodeId: string; readonly report: SystemReadinessReport }, - ]; - /** Exact transaction state path that may be claimed only after confirmation. */ - readonly peerSshBindingStatePath: string; - readonly peerSshIdentity: QualifiedStationSshIdentity; + readonly topology: ManagedClusterTopologyArtifact; + readonly local: ManagedClusterHostObservation; + readonly peers: readonly ManagedClusterHostObservation[]; + readonly readiness: readonly { + readonly nodeId: string; + readonly report: SystemReadinessReport; + }[]; + /** Exact transaction claims that may be persisted only after confirmation. */ + readonly sshClaims: readonly ManagedClusterSshClaim[]; }; -export type DualSparkManagedServingCapability = +export interface ManagedClusterSshClaim { + readonly nodeId: string; + readonly statePath: string; + readonly identity: QualifiedStationSshIdentity; +} + +export interface ManagedClusterSshBinding extends ManagedClusterSshClaim { + readonly binding: DualStationSshBinding; + readonly handle: string; +} + +export type ManagedClusterManagedServingCapability = | { readonly kind: "not-selected"; - readonly code: DualSparkManagedServingFailureCode; + readonly code: ManagedClusterManagedServingFailureCode; readonly reason: string; } | { readonly kind: "unavailable"; - readonly code: DualSparkManagedServingFailureCode; + readonly code: ManagedClusterManagedServingFailureCode; readonly reason: string; } - | DualSparkDetectedManagedServingCapability; + | ManagedClusterDetectedManagedServingCapability; -export type DualSparkConfirmedManagedServingCapability = - DualSparkDetectedManagedServingCapability & { - readonly peerSshBinding: DualStationSshBinding; - readonly peerSshBindingHandle: string; +export type ManagedClusterConfirmedManagedServingCapability = + ManagedClusterDetectedManagedServingCapability & { + readonly sshBindings: readonly ManagedClusterSshBinding[]; }; -export type DualSparkManagedServingConfirmation = - | Exclude - | DualSparkConfirmedManagedServingCapability; +export type ManagedClusterManagedServingConfirmation = + | Exclude + | ManagedClusterConfirmedManagedServingCapability; -export interface ProbeDualSparkManagedServingOptions { +export interface ProbeManagedClusterManagedServingOptions { readonly env?: NodeJS.ProcessEnv; - readonly deps?: DualSparkDiscoveryDeps; + readonly deps?: ManagedClusterDiscoveryDeps; /** @internal Catalog loader seam for fail-closed tests. */ readonly loadCatalog?: typeof loadManagedInferenceCatalog; - readonly bindingStatePath?: string; + readonly bindingStatePaths?: Readonly>; readonly maxReadinessAgeMs?: number; } interface QualifiedRail { - readonly host: DualSparkCx7RailHostObservation; + readonly host: ManagedClusterCx7RailHostObservation; readonly address: string; readonly peerAddress: string; readonly subnet: string; - readonly gid: DualSparkRoceGidHostObservation; + readonly gid: ManagedClusterRoceGidHostObservation; } interface QualifiedHost { - readonly host: DualSparkHostObservation; - readonly gpu: DualSparkGpuObservation; + readonly host: ManagedClusterHostObservation; + readonly gpu: ManagedClusterGpuObservation; readonly rails: readonly [QualifiedRail, QualifiedRail]; } -interface PairPlan { - readonly local: QualifiedHost; - readonly peer: QualifiedHost; - readonly localConnectivity: readonly [DualSparkConnectivityRequest, DualSparkConnectivityRequest]; - readonly peerConnectivity: readonly [DualSparkConnectivityRequest, DualSparkConnectivityRequest]; +interface ClusterPlan { + readonly nodes: readonly QualifiedHost[]; + readonly connectivity: ReadonlyMap; + readonly peerNodeIdsByRail: ReadonlyMap; } type DiscoveryFailure = { - readonly code: DualSparkManagedServingFailureCode; + readonly code: ManagedClusterManagedServingFailureCode; readonly reason: string; }; type Selection = { readonly strict: boolean; readonly intent: "automatic" | "explicit"; - readonly explicitPeer: string | null; + readonly explicitPeers: readonly string[]; }; function notSelected( - code: DualSparkManagedServingFailureCode, + code: ManagedClusterManagedServingFailureCode, reason: string, -): DualSparkManagedServingCapability { +): ManagedClusterManagedServingCapability { return { kind: "not-selected", code, reason }; } function unavailable( - code: DualSparkManagedServingFailureCode, + code: ManagedClusterManagedServingFailureCode, reason: string, -): DualSparkManagedServingCapability { +): ManagedClusterManagedServingCapability { return { kind: "unavailable", code, reason }; } function disposition( selection: Selection, result: DiscoveryFailure, -): DualSparkManagedServingCapability { +): ManagedClusterManagedServingCapability { if (selection.strict) return unavailable(result.code, result.reason); - const code: DualSparkManagedServingFailureCode = [ + const code: ManagedClusterManagedServingFailureCode = [ "runtime-conflict", "runtime-unknown", "binding-conflict", @@ -328,7 +334,9 @@ function validatePeerTarget(raw: string): string { raw !== raw.trim() || /[/,:;`'"\\$(){}[\]<>|&!?*\s\u0000-\u001f\u007f]/.test(raw) ) { - throw new Error(`${NEMOCLAW_DGX_SPARK_PEER_ENV} must name one canonical SSH host or user@host`); + throw new Error( + `${NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV} must contain canonical SSH hosts or user@host values`, + ); } const parts = raw.split("@"); const username = parts.length === 2 ? parts[0] : ""; @@ -339,7 +347,9 @@ function validatePeerTarget(raw: string): string { (username !== "" && !SAFE_USERNAME_PATTERN.test(username)) || (net.isIP(hostname) !== 4 && !SAFE_TARGET_PATTERN.test(hostname)) ) { - throw new Error(`${NEMOCLAW_DGX_SPARK_PEER_ENV} must name one canonical SSH host or user@host`); + throw new Error( + `${NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV} must contain canonical SSH hosts or user@host values`, + ); } return raw; } @@ -347,9 +357,22 @@ function validatePeerTarget(raw: string): string { function selectionFromEnvironment( env: NodeJS.ProcessEnv, loadCatalog: typeof loadManagedInferenceCatalog, -): Selection | DualSparkManagedServingCapability { +): Selection | ManagedClusterManagedServingCapability { const preset = String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); - const peer = String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim(); + const peersValue = String(env[NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV] ?? "").trim(); + let peers: readonly string[] = []; + if (peersValue) { + try { + peers = peersValue.split(",").map((peer) => validatePeerTarget(peer.trim())); + if (new Set(peers).size !== peers.length || peers.length > 1_023) { + throw new Error( + `${NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV} contains duplicate or too many peers`, + ); + } + } catch (error) { + return unavailable("invalid-peer", (error as Error).message); + } + } if (preset) { let catalog; try { @@ -369,30 +392,22 @@ function selectionFromEnvironment( definition.metadata.id === compiledPreset.definition.spec.plan.recipeRef, )?.definition : undefined; - if (recipe?.spec.execution.materializerRef !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { - return peer + if (recipe?.spec.execution.materializerRef !== MANAGED_CLUSTER_VLLM_MATERIALIZER_REF) { + return peers.length > 0 ? unavailable( "incompatible-selection", - `${NEMOCLAW_DGX_SPARK_PEER_ENV} cannot be combined with another serving preset.`, + `${NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV} cannot be combined with another serving preset.`, ) : notSelected("no-match", "Another managed inference preset is selected."); } } - if (peer) { - try { - return { - strict: true, - intent: "explicit", - explicitPeer: validatePeerTarget(peer), - }; - } catch (error) { - return unavailable("invalid-peer", (error as Error).message); - } + if (peers.length > 0) { + return { strict: true, intent: "explicit", explicitPeers: peers }; } return { strict: Boolean(preset), intent: preset ? "explicit" : "automatic", - explicitPeer: null, + explicitPeers: [], }; } @@ -449,7 +464,7 @@ function isSafeInteger( return Number.isInteger(value) && (value as number) >= minimum && (value as number) <= maximum; } -function validStorageCapacity(value: unknown): value is DualSparkStorageCapacityObservation { +function validStorageCapacity(value: unknown): value is ManagedClusterStorageCapacityObservation { if ( !isRecord(value) || !isSafeText(value.requestedPath) || @@ -470,7 +485,7 @@ function validStorageCapacity(value: unknown): value is DualSparkStorageCapacity ); } -function validGpu(value: unknown): value is DualSparkGpuObservation { +function validGpu(value: unknown): value is ManagedClusterGpuObservation { return ( isRecord(value) && isSafeInteger(value.index, 0, 1024) && @@ -480,7 +495,7 @@ function validGpu(value: unknown): value is DualSparkGpuObservation { ); } -function validRail(value: unknown): value is DualSparkCx7RailHostObservation { +function validRail(value: unknown): value is ManagedClusterCx7RailHostObservation { if ( !isRecord(value) || !isSafeText(value.physicalPortId, 128) || @@ -530,7 +545,7 @@ function validRail(value: unknown): value is DualSparkCx7RailHostObservation { ); } -function validContainer(value: unknown): value is DualSparkObservedContainer { +function validContainer(value: unknown): value is ManagedClusterObservedContainer { if ( !isRecord(value) || !isSafeText(value.id, 64) || @@ -550,7 +565,7 @@ function validContainer(value: unknown): value is DualSparkObservedContainer { ); } -export function parseDualSparkHostObservation(value: unknown): DualSparkHostObservation { +export function parseManagedClusterHostObservation(value: unknown): ManagedClusterHostObservation { if ( !isRecord(value) || value.schemaVersion !== HOST_PROBE_SCHEMA_VERSION || @@ -600,10 +615,10 @@ export function parseDualSparkHostObservation(value: unknown): DualSparkHostObse ) { throw new Error("DGX Spark host observation is invalid"); } - return value as unknown as DualSparkHostObservation; + return value as unknown as ManagedClusterHostObservation; } function qualifyHost( - host: DualSparkHostObservation, + host: ManagedClusterHostObservation, label: string, ): QualifiedHost | DiscoveryFailure { if ( @@ -644,7 +659,7 @@ function qualifyHost( peer: slash30Counterpart(address.address, address.prefixLength), })) .filter( - (entry): entry is { address: DualSparkIpv4Observation; peer: string } => + (entry): entry is { address: ManagedClusterIpv4Observation; peer: string } => entry.peer !== null, ); if (addresses.length !== 1) { @@ -683,7 +698,10 @@ function qualifyHost( return { host, gpu: gpus[0]!, rails: [qualified[0]!, qualified[1]!] }; } -function runtimeFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { +function runtimeFailure( + host: ManagedClusterHostObservation, + label: string, +): DiscoveryFailure | null { if (!host.runtimeInspectionComplete) { return { code: "runtime-unknown", reason: `${label} runtime inspection is inconclusive.` }; } @@ -694,18 +712,13 @@ function runtimeFailure(host: DualSparkHostObservation, label: string): Discover reason: `${label} already has related container ${container.name}; it was not changed.`, }; } - const port = host.runtimeSnapshot.listeningPorts.find( - (entry) => entry === DUAL_SPARK_VLLM_MASTER_PORT, - ); - return port === undefined - ? null - : { - code: "runtime-conflict", - reason: `${label} port ${String(port)} is already in use; its listener was not changed.`, - }; + return null; } -function earlyoomFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { +function earlyoomFailure( + host: ManagedClusterHostObservation, + label: string, +): DiscoveryFailure | null { if (!host.earlyoom.installed) return null; if (host.earlyoom.active === "active") { return { @@ -718,7 +731,7 @@ function earlyoomFailure(host: DualSparkHostObservation, label: string): Discove : { code: "earlyoom-unknown", reason: `${label} earlyoom state is inconclusive.` }; } -function validCapacity(capacity: DualSparkStorageCapacityObservation): boolean { +function validCapacity(capacity: ManagedClusterStorageCapacityObservation): boolean { return ( capacity.probePath !== null && capacity.filesystemId !== null && @@ -731,7 +744,10 @@ function validCapacity(capacity: DualSparkStorageCapacityObservation): boolean { ); } -function storageFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { +function storageFailure( + host: ManagedClusterHostObservation, + label: string, +): DiscoveryFailure | null { const huggingFace = host.storage.huggingFace; const docker = host.storage.docker; if (!validCapacity(huggingFace) || !validCapacity(docker)) { @@ -766,48 +782,55 @@ function storageFailure(host: DualSparkHostObservation, label: string): Discover return null; } -function pairHosts(local: QualifiedHost, peer: QualifiedHost): PairPlan | DiscoveryFailure { - if (local.host.nodeId === peer.host.nodeId || local.gpu.uuid === peer.gpu.uuid) { +function matchClusterHosts(nodes: readonly QualifiedHost[]): ClusterPlan | DiscoveryFailure { + if ( + nodes.length < 2 || + new Set(nodes.map(({ host }) => host.nodeId)).size !== nodes.length || + new Set(nodes.map(({ gpu }) => gpu.uuid)).size !== nodes.length + ) { return { code: "peer-identity-ambiguous", - reason: "The peer resolves back to the local DGX Spark.", + reason: "Managed cluster nodes or GPU identities are duplicated.", }; } - const matches = local.rails.map((localRail) => { - const peers = peer.rails.filter( - (peerRail) => - peerRail.subnet === localRail.subnet && - peerRail.address === localRail.peerAddress && - peerRail.peerAddress === localRail.address, - ); - return peers.length === 1 ? { local: localRail, peer: peers[0]! } : null; - }); - if (matches.some((match) => match === null)) { - return { - code: "fabric-unavailable", - reason: "The peer rails are not exact reciprocal /30 endpoints.", - }; + const peerNodeIdsByRail = new Map(); + const connectivity = new Map(); + for (const node of nodes) { + const requests: ManagedClusterConnectivityRequest[] = []; + for (const rail of node.rails) { + const matches = nodes.flatMap((candidate) => + candidate.host.nodeId === node.host.nodeId + ? [] + : candidate.rails + .filter( + (candidateRail) => + candidateRail.subnet === rail.subnet && + candidateRail.address === rail.peerAddress && + candidateRail.peerAddress === rail.address, + ) + .map((candidateRail) => ({ candidate, candidateRail })), + ); + if (matches.length !== 1) { + return { + code: "fabric-unavailable", + reason: "Managed cluster rails are not unique reciprocal /30 endpoints.", + }; + } + const match = matches[0]!; + peerNodeIdsByRail.set(rail, match.candidate.host.nodeId); + requests.push({ + netdev: rail.host.netdev, + sourceAddress: rail.address, + peerAddress: match.candidateRail.address, + expectedPeerMac: match.candidateRail.host.macAddress, + }); + } + connectivity.set(node.host.nodeId, requests); } - const exact = matches as Array<{ local: QualifiedRail; peer: QualifiedRail }>; - return { - local, - peer, - localConnectivity: exact.map(({ local: localRail, peer: peerRail }) => ({ - netdev: localRail.host.netdev, - sourceAddress: localRail.address, - peerAddress: peerRail.address, - expectedPeerMac: peerRail.host.macAddress, - })) as [DualSparkConnectivityRequest, DualSparkConnectivityRequest], - peerConnectivity: exact.map(({ local: localRail, peer: peerRail }) => ({ - netdev: peerRail.host.netdev, - sourceAddress: peerRail.address, - peerAddress: localRail.address, - expectedPeerMac: localRail.host.macAddress, - })) as [DualSparkConnectivityRequest, DualSparkConnectivityRequest], - }; + return { nodes, connectivity, peerNodeIdsByRail }; } -function topologyRail(rail: QualifiedRail, peerNodeId: string): DualSparkRailObservation { +function topologyRail(rail: QualifiedRail, peerNodeId: string): ManagedClusterRailObservation { return { adapter: "connectx-7", path: "direct", @@ -826,38 +849,41 @@ function topologyRail(rail: QualifiedRail, peerNodeId: string): DualSparkRailObs } function topologyObservations( - pair: PairPlan, - localReadiness: SystemReadinessReport, - peerReadiness: SystemReadinessReport, - identity: QualifiedStationSshIdentity, - bindingHandle: string, -): { local: DualSparkNodeObservation; peer: DualSparkPeerObservation } { + cluster: ClusterPlan, + readiness: ReadonlyMap, + identities: ReadonlyMap, + bindingHandles: ReadonlyMap, +): { local: ManagedClusterNodeObservation; peers: readonly ManagedClusterPeerObservation[] } { + const controller = cluster.nodes[0]!; + const nodeObservation = (node: QualifiedHost): ManagedClusterNodeObservation => ({ + nodeId: node.host.nodeId, + gpuIds: [node.gpu.uuid], + readiness: readiness.get(node.host.nodeId)!, + runtimeState: "clear", + rails: node.rails.map((rail) => topologyRail(rail, cluster.peerNodeIdsByRail.get(rail)!)), + }); return { - local: { - nodeId: pair.local.host.nodeId, - gpuIds: [pair.local.gpu.uuid], - readiness: localReadiness, - runtimeState: "clear", - rails: pair.local.rails.map((rail) => topologyRail(rail, pair.peer.host.nodeId)), - }, - peer: { - nodeId: pair.peer.host.nodeId, - gpuIds: [pair.peer.gpu.uuid], - readiness: peerReadiness, - runtimeState: "clear", - rails: pair.peer.rails.map((rail) => topologyRail(rail, pair.local.host.nodeId)), - sshBinding: { - state: "pretrusted", - fromNodeId: pair.local.host.nodeId, - toNodeId: pair.peer.host.nodeId, - peerTarget: identity.sshTarget, - handle: bindingHandle, - }, - }, + local: nodeObservation(controller), + peers: cluster.nodes.slice(1).map((node) => { + const identity = identities.get(node.host.nodeId)!; + return { + ...nodeObservation(node), + sshBinding: { + state: "pretrusted", + fromNodeId: controller.host.nodeId, + toNodeId: node.host.nodeId, + peerTarget: identity.sshTarget, + handle: bindingHandles.get(node.host.nodeId)!, + }, + }; + }), }; } -function hostPolicyFailure(host: DualSparkHostObservation, label: string): DiscoveryFailure | null { +function hostPolicyFailure( + host: ManagedClusterHostObservation, + label: string, +): DiscoveryFailure | null { return earlyoomFailure(host, label) ?? runtimeFailure(host, label) ?? storageFailure(host, label); } @@ -890,8 +916,8 @@ function sameExactSshIdentity( } function samePhysicalHost( - left: DualSparkHostObservation, - right: DualSparkHostObservation, + left: ManagedClusterHostObservation, + right: ManagedClusterHostObservation, ): boolean { return ( left.nodeId === right.nodeId && @@ -901,82 +927,91 @@ function samePhysicalHost( ); } -function topologyFailureReason(result: ReturnType): string { +function topologyFailureReason(result: ReturnType): string { return result.outcome === "qualified" ? "" : result.message; } -function sameDetectedPair( - detected: DualSparkDetectedManagedServingCapability, - revalidated: DualSparkDetectedManagedServingCapability, +function sameHostIdentity( + left: ManagedClusterHostObservation, + right: ManagedClusterHostObservation, +): boolean { + return ( + left.nodeId === right.nodeId && + left.hostname === right.hostname && + left.username === right.username && + left.uid === right.uid && + left.gid === right.gid && + left.home === right.home && + left.gpus[0]?.uuid === right.gpus[0]?.uuid && + left.storage.huggingFace.cacheRoot === right.storage.huggingFace.cacheRoot + ); +} + +function sameDetectedCluster( + detected: ManagedClusterDetectedManagedServingCapability, + revalidated: ManagedClusterDetectedManagedServingCapability, ): boolean { return ( detected.selectionIntent === revalidated.selectionIntent && - detected.peerSshBindingStatePath === revalidated.peerSshBindingStatePath && - sameExactSshIdentity(detected.peerSshIdentity, revalidated.peerSshIdentity) && - detected.local.nodeId === revalidated.local.nodeId && - detected.local.hostname === revalidated.local.hostname && - detected.local.username === revalidated.local.username && - detected.local.uid === revalidated.local.uid && - detected.local.gid === revalidated.local.gid && - detected.local.home === revalidated.local.home && - detected.local.gpus[0]?.uuid === revalidated.local.gpus[0]?.uuid && - detected.local.storage.huggingFace.cacheRoot === - revalidated.local.storage.huggingFace.cacheRoot && - detected.peer.nodeId === revalidated.peer.nodeId && - detected.peer.hostname === revalidated.peer.hostname && - detected.peer.username === revalidated.peer.username && - detected.peer.uid === revalidated.peer.uid && - detected.peer.gid === revalidated.peer.gid && - detected.peer.home === revalidated.peer.home && - detected.peer.gpus[0]?.uuid === revalidated.peer.gpus[0]?.uuid && - detected.peer.storage.huggingFace.cacheRoot === - revalidated.peer.storage.huggingFace.cacheRoot && + sameHostIdentity(detected.local, revalidated.local) && + detected.peers.length === revalidated.peers.length && + detected.peers.every((peer, index) => sameHostIdentity(peer, revalidated.peers[index]!)) && + detected.sshClaims.length === revalidated.sshClaims.length && + detected.sshClaims.every((claim, index) => { + const candidate = revalidated.sshClaims[index]; + return ( + candidate?.nodeId === claim.nodeId && + candidate.statePath === claim.statePath && + sameExactSshIdentity(claim.identity, candidate.identity) + ); + }) && detected.topology.subjectDigest === revalidated.topology.subjectDigest && detected.topology.outputDigest === revalidated.topology.outputDigest ); } function topologyWithBinding( - detected: DualSparkDetectedManagedServingCapability, - peerSshBindingHandle: string, -): DualSparkTopologyArtifact { - const output: DualSparkTopologyOutput = { + detected: ManagedClusterDetectedManagedServingCapability, + bindings: readonly ManagedClusterSshBinding[], +): ManagedClusterTopologyArtifact { + const output: ManagedClusterTopologyOutput = { ...detected.topology.output, - peer: { - ...detected.topology.output.peer, - sshBindingHandle: peerSshBindingHandle, - }, + peers: detected.topology.output.peers.map((peer) => ({ + ...peer, + sshBindingHandle: + bindings.find(({ nodeId }) => nodeId === peer.nodeId)?.handle ?? peer.sshBindingHandle, + })), }; - const artifact = immutableManagedInferenceCopy({ + const artifact = immutableManagedInferenceCopy({ ...detected.topology, output, - outputDigest: dualSparkTopologyOutputDigest(output), + outputDigest: managedClusterTopologyOutputDigest(output), }); - const error = getDualSparkTopologyArtifactError(artifact); + const error = getManagedClusterTopologyArtifactError(artifact); if (error) throw new Error(error); return artifact; } function confirmationUnavailable( - code: DualSparkManagedServingFailureCode, + code: ManagedClusterManagedServingFailureCode, reason: string, -): DualSparkManagedServingConfirmation { +): ManagedClusterManagedServingConfirmation { return { kind: "unavailable", code, reason }; } -export function probeDualSparkManagedServingCapability( - options: ProbeDualSparkManagedServingOptions = {}, -): DualSparkManagedServingCapability { +export function probeManagedClusterManagedServingCapability( + options: ProbeManagedClusterManagedServingOptions = {}, +): ManagedClusterManagedServingCapability { const selection = selectionFromEnvironment( options.env ?? process.env, options.loadCatalog ?? loadManagedInferenceCatalog, ); if (!("strict" in selection)) return selection; - const deps = options.deps ?? defaultDualSparkDiscoveryDeps; - const opened: DualSparkPinnedPeerTransport[] = []; - let local: DualSparkHostObservation; + const deps = options.deps ?? defaultManagedClusterDiscoveryDeps; + const opened: ManagedClusterPinnedPeerTransport[] = []; + let local: ManagedClusterHostObservation; let qualifiedLocal: QualifiedHost; - let localTransport: DualSparkReadOnlyHostTransport; + let localTransport: ManagedClusterReadOnlyHostTransport; try { localTransport = deps.localTransport(); local = deps.probeHost(localTransport); @@ -1000,105 +1035,143 @@ export function probeDualSparkManagedServingCapability( } try { - let selectedIdentity: QualifiedStationSshIdentity; - let selectedTransport: DualSparkReadOnlyHostTransport; - let peer: DualSparkHostObservation; - if (selection.explicitPeer) { - const identity = deps.inspectPretrustedTarget(selection.explicitPeer); - if (!identity) { - return disposition(selection, { - code: "peer-trust-unavailable", - reason: "The explicit DGX Spark peer lacks usable pre-existing SSH trust.", - }); - } + const targets = + selection.explicitPeers.length > 0 + ? selection.explicitPeers + : qualifiedLocal.rails.map(({ peerAddress }) => peerAddress); + const probes = targets.map((target) => { + const identity = deps.inspectPretrustedTarget(target); + if (!identity) return null; const pinned = deps.openPinnedPeerTransport(identity); opened.push(pinned); - selectedIdentity = identity; - selectedTransport = pinned.transport; - peer = deps.probeHost(selectedTransport); - } else { - const targets = qualifiedLocal.rails.map(({ peerAddress }) => peerAddress); - const identities = targets.map((target) => deps.inspectPretrustedTarget(target)); - if (identities.some((identity) => identity === null)) { + return { identity, pinned, host: deps.probeHost(pinned.transport) }; + }); + if (probes.some((probe) => probe === null)) { + return disposition(selection, { + code: "peer-trust-unavailable", + reason: "Every managed cluster peer requires usable pre-existing SSH host-key trust.", + }); + } + + const unique = new Map< + string, + { + identity: QualifiedStationSshIdentity; + transport: ManagedClusterReadOnlyHostTransport; + host: ManagedClusterHostObservation; + } + >(); + for (const probe of probes as Array>) { + if (samePhysicalHost(local, probe.host)) { return disposition(selection, { - code: "peer-trust-unavailable", - reason: "Both derived /30 peer addresses require pre-existing SSH host-key trust.", + code: "peer-identity-ambiguous", + reason: "A managed cluster peer resolves back to the local DGX Spark.", }); } - const trusted = identities as QualifiedStationSshIdentity[]; - if (!samePhysicalSshIdentity(trusted[0]!, trusted[1]!)) { + const existing = unique.get(probe.host.nodeId); + if ( + existing && + (!samePhysicalHost(existing.host, probe.host) || + !samePhysicalSshIdentity(existing.identity, probe.identity)) + ) { return disposition(selection, { code: "peer-identity-ambiguous", - reason: "The two derived rail addresses map to different SSH identities.", + reason: "Multiple peer targets disagree about one physical DGX Spark identity.", + }); + } + if ( + !existing || + compareStrings(probe.identity.requestedTarget, existing.identity.requestedTarget) < 0 + ) { + unique.set(probe.host.nodeId, { + identity: probe.identity, + transport: probe.pinned.transport, + host: probe.host, }); } - const probes = trusted.map((identity) => { - const pinned = deps.openPinnedPeerTransport(identity); - opened.push(pinned); - return { identity, pinned, host: deps.probeHost(pinned.transport) }; + } + const selectedPeers = [...unique.values()].sort((left, right) => + compareStrings(left.host.nodeId, right.host.nodeId), + ); + if (selectedPeers.length === 0) { + return disposition(selection, { + code: "peer-count", + reason: "No distinct managed cluster peer was detected.", }); - if (!samePhysicalHost(probes[0]!.host, probes[1]!.host)) { + } + + const qualifiedPeers: QualifiedHost[] = []; + for (const [index, selected] of selectedPeers.entries()) { + const label = `Managed cluster peer ${String(index + 1)}`; + const qualifiedPeer = qualifyHost(selected.host, label); + if ("code" in qualifiedPeer) return disposition(selection, qualifiedPeer); + if (selected.host.username !== selected.identity.sshUser || selected.host.uid <= 0) { return disposition(selection, { code: "peer-identity-ambiguous", - reason: "The two derived rail addresses do not resolve to one physical DGX Spark.", + reason: `${label} SSH user does not own the probed non-root cache identity.`, }); } - probes.sort((left, right) => - compareStrings(left.identity.requestedTarget, right.identity.requestedTarget), - ); - selectedIdentity = probes[0]!.identity; - selectedTransport = probes[0]!.pinned.transport; - peer = probes[0]!.host; + const policyFailure = hostPolicyFailure(selected.host, label); + if (policyFailure) return disposition(selection, policyFailure); + qualifiedPeers.push(qualifiedPeer); } - const qualifiedPeer = qualifyHost(peer, "Peer DGX Spark"); - if ("code" in qualifiedPeer) return disposition(selection, qualifiedPeer); - if (peer.username !== selectedIdentity.sshUser || peer.uid <= 0) { - return disposition(selection, { - code: "peer-identity-ambiguous", - reason: "The peer SSH user does not own the probed non-root cache identity.", - }); - } - const peerPolicyFailure = hostPolicyFailure(peer, "Peer DGX Spark"); - if (peerPolicyFailure) return disposition(selection, peerPolicyFailure); - const pair = pairHosts(qualifiedLocal, qualifiedPeer); - if ("code" in pair) return disposition(selection, pair); - if ( - !deps.probeConnectivity(localTransport, pair.localConnectivity) || - !deps.probeConnectivity(selectedTransport, pair.peerConnectivity) - ) { - return disposition(selection, { - code: "connectivity-unavailable", - reason: "Direct route, neighbor, or jumbo connectivity failed on a DGX Spark rail.", - }); + const cluster = matchClusterHosts([qualifiedLocal, ...qualifiedPeers]); + if ("code" in cluster) return disposition(selection, cluster); + const transportByNodeId = new Map([ + [local.nodeId, localTransport], + ...selectedPeers.map(({ host, transport }) => [host.nodeId, transport] as const), + ]); + for (const node of cluster.nodes) { + if ( + !deps.probeConnectivity( + transportByNodeId.get(node.host.nodeId)!, + cluster.connectivity.get(node.host.nodeId)!, + ) + ) { + return disposition(selection, { + code: "connectivity-unavailable", + reason: `Direct route, neighbor, or jumbo connectivity failed on ${node.host.hostname}.`, + }); + } } const now = deps.now(); const buildIdentity = deps.getBuildIdentity(); - let localReadiness: SystemReadinessReport; - let peerReadiness: SystemReadinessReport; + const readiness = new Map(); try { - localReadiness = deps.createReadiness(local, localTransport, buildIdentity, now); - peerReadiness = deps.createReadiness(peer, selectedTransport, buildIdentity, now); + for (const node of cluster.nodes) { + readiness.set( + node.host.nodeId, + deps.createReadiness( + node.host, + transportByNodeId.get(node.host.nodeId)!, + buildIdentity, + now, + ), + ); + } } catch { return disposition(selection, { code: "readiness-unavailable", - reason: "Canonical readiness could not be generated for both DGX Spark nodes.", + reason: "Canonical readiness could not be generated for every managed cluster node.", }); } - const temporary = topologyObservations( - pair, - localReadiness, - peerReadiness, - selectedIdentity, - `pretrusted:${selectedIdentity.hostKeyDigest}`, + const identities = new Map( + selectedPeers.map(({ host, identity }) => [host.nodeId, identity] as const), + ); + const temporaryHandles = new Map( + selectedPeers.map( + ({ host, identity }) => [host.nodeId, `pretrusted:${identity.hostKeyDigest}`] as const, + ), ); - const temporaryQualification = qualifyDualSparkTopology({ + const temporary = topologyObservations(cluster, readiness, identities, temporaryHandles); + const temporaryQualification = qualifyManagedClusterTopology({ intent: selection.intent, evaluatedAt: now.toISOString(), maxReadinessAgeMs: options.maxReadinessAgeMs ?? 60_000, local: temporary.local, - peers: [temporary.peer], + peers: temporary.peers, }); if (temporaryQualification.outcome !== "qualified") { return disposition(selection, { @@ -1107,19 +1180,23 @@ export function probeDualSparkManagedServingCapability( }); } - const statePath = options.bindingStatePath ?? deps.resolveBindingStatePath(); + const sshClaims = selectedPeers.map(({ host, identity }) => ({ + nodeId: host.nodeId, + statePath: + options.bindingStatePaths?.[host.nodeId] ?? deps.resolveBindingStatePath(host.nodeId), + identity, + })); return { kind: "ready", selectionIntent: selection.intent, topology: temporaryQualification.artifact, local, - peer, - readiness: [ - { nodeId: local.nodeId, report: localReadiness }, - { nodeId: peer.nodeId, report: peerReadiness }, - ], - peerSshBindingStatePath: statePath, - peerSshIdentity: selectedIdentity, + peers: selectedPeers.map(({ host }) => host), + readiness: cluster.nodes.map(({ host }) => ({ + nodeId: host.nodeId, + report: readiness.get(host.nodeId)!, + })), + sshClaims, }; } catch { return disposition(selection, { @@ -1137,87 +1214,99 @@ export function probeDualSparkManagedServingCapability( } } -/** Revalidate the detected pair without claiming or writing its SSH binding. */ -export function revalidateDualSparkManagedServingCapability( - detected: DualSparkDetectedManagedServingCapability, - options: ProbeDualSparkManagedServingOptions = {}, -): DualSparkManagedServingCapability { - const deps = options.deps ?? defaultDualSparkDiscoveryDeps; - const revalidated = probeDualSparkManagedServingCapability({ +/** Revalidate the detected cluster without claiming or writing SSH bindings. */ +export function revalidateManagedClusterManagedServingCapability( + detected: ManagedClusterDetectedManagedServingCapability, + options: ProbeManagedClusterManagedServingOptions = {}, +): ManagedClusterManagedServingCapability { + const deps = options.deps ?? defaultManagedClusterDiscoveryDeps; + const revalidated = probeManagedClusterManagedServingCapability({ ...options, deps, - bindingStatePath: detected.peerSshBindingStatePath, + bindingStatePaths: Object.fromEntries( + detected.sshClaims.map(({ nodeId, statePath }) => [nodeId, statePath]), + ), }); if (revalidated.kind !== "ready") { return confirmationUnavailable( revalidated.code, - `The confirmed DGX Spark pair no longer qualifies: ${revalidated.reason}`, + `The confirmed managed cluster no longer qualifies: ${revalidated.reason}`, ); } - if (!sameDetectedPair(detected, revalidated)) { + if (!sameDetectedCluster(detected, revalidated)) { return confirmationUnavailable( "peer-identity-ambiguous", - "The confirmed DGX Spark pair or its exact pretrusted SSH identity changed after selection.", + "The confirmed managed cluster or an exact pretrusted SSH identity changed after selection.", ); } return revalidated; } -/** Atomically claim and persist a previously revalidated pair's SSH binding. */ -export function claimDualSparkManagedServingCapability( - revalidated: DualSparkDetectedManagedServingCapability, - options: Pick = {}, -): DualSparkManagedServingConfirmation { - const deps = options.deps ?? defaultDualSparkDiscoveryDeps; - const statePath = revalidated.peerSshBindingStatePath; - if (!deps.claimBinding(statePath)) { - return confirmationUnavailable( - "binding-conflict", - "An existing DGX Spark SSH binding was preserved and not replaced.", - ); - } +/** Claim and persist every previously revalidated peer SSH binding. */ +export function claimManagedClusterManagedServingCapability( + revalidated: ManagedClusterDetectedManagedServingCapability, + options: Pick = {}, +): ManagedClusterManagedServingConfirmation { + const deps = options.deps ?? defaultManagedClusterDiscoveryDeps; + const claimed: string[] = []; try { - const peerSshBinding = deps.writeBinding(statePath, revalidated.peerSshIdentity); - const peerSshBindingHandle = deps.encodeBinding(peerSshBinding); + const sshBindings: ManagedClusterSshBinding[] = []; + for (const claim of revalidated.sshClaims) { + if (!deps.claimBinding(claim.statePath)) { + throw new Error("binding-conflict"); + } + claimed.push(claim.statePath); + const binding = deps.writeBinding(claim.statePath, claim.identity); + sshBindings.push({ ...claim, binding, handle: deps.encodeBinding(binding) }); + } return { ...revalidated, - topology: topologyWithBinding(revalidated, peerSshBindingHandle), - peerSshBinding, - peerSshBindingHandle, + topology: topologyWithBinding(revalidated, sshBindings), + sshBindings, }; - } catch { - try { - deps.clearBinding(statePath); - } catch { + } catch (error) { + let cleanupFailed = false; + for (const statePath of claimed.reverse()) { + try { + deps.clearBinding(statePath); + } catch { + cleanupFailed = true; + } + } + if (cleanupFailed) { return confirmationUnavailable( "binding-persistence-failed", - "The DGX Spark SSH binding failed and its new state could not be cleaned safely.", + "A managed cluster SSH binding failed and newly claimed state could not be cleaned safely.", ); } return confirmationUnavailable( - "binding-persistence-failed", - "The confirmed DGX Spark SSH binding could not be persisted.", + (error as Error).message === "binding-conflict" + ? "binding-conflict" + : "binding-persistence-failed", + (error as Error).message === "binding-conflict" + ? "An existing managed cluster SSH binding was preserved and not replaced." + : "The confirmed managed cluster SSH bindings could not be persisted.", ); } } -/** Revalidate the detected pair, then claim and persist its SSH binding after confirmation. */ -export function confirmDualSparkManagedServingCapability( - detected: DualSparkDetectedManagedServingCapability, - options: ProbeDualSparkManagedServingOptions = {}, -): DualSparkManagedServingConfirmation { - const revalidated = revalidateDualSparkManagedServingCapability(detected, options); +/** Revalidate the detected cluster, then persist its SSH bindings after confirmation. */ +export function confirmManagedClusterManagedServingCapability( + detected: ManagedClusterDetectedManagedServingCapability, + options: ProbeManagedClusterManagedServingOptions = {}, +): ManagedClusterManagedServingConfirmation { + const revalidated = revalidateManagedClusterManagedServingCapability(detected, options); return revalidated.kind === "ready" - ? claimDualSparkManagedServingCapability(revalidated, options) + ? claimManagedClusterManagedServingCapability(revalidated, options) : revalidated; } -export type { DualSparkSpawnSync } from "./dual-spark-discovery-production.js"; +export type { ManagedClusterSpawnSync } from "./managed-cluster-discovery-production.js"; -export function createDualSparkDiscoveryDeps( - spawn?: import("./dual-spark-discovery-production.js").DualSparkSpawnSync, -): DualSparkDiscoveryDeps { - return createProductionDualSparkDiscoveryDeps(parseDualSparkHostObservation, spawn); +export function createManagedClusterDiscoveryDeps( + spawn?: import("./managed-cluster-discovery-production.js").ManagedClusterSpawnSync, +): ManagedClusterDiscoveryDeps { + return createProductionManagedClusterDiscoveryDeps(parseManagedClusterHostObservation, spawn); } -const defaultDualSparkDiscoveryDeps = createDualSparkDiscoveryDeps(); +const defaultManagedClusterDiscoveryDeps = createManagedClusterDiscoveryDeps(); diff --git a/src/lib/inference/serving/dual-spark-executor.test.ts b/src/lib/inference/serving/managed-cluster-executor.test.ts similarity index 66% rename from src/lib/inference/serving/dual-spark-executor.test.ts rename to src/lib/inference/serving/managed-cluster-executor.test.ts index 25b711fb8fe..380db85a6c0 100644 --- a/src/lib/inference/serving/dual-spark-executor.test.ts +++ b/src/lib/inference/serving/managed-cluster-executor.test.ts @@ -9,21 +9,21 @@ import { } from "../vllm-station-ssh-binding.test-support.js"; import { NO_PREPARATION_REF } from "./adapter-registry.js"; import { - assertDualSparkVllmExecutorConfig, - buildDualSparkVllmRunArgs, - createDualSparkVllmExecutor, - type DualSparkVllmExecutorRuntimeDeps, - inspectDualSparkVllmNodesSync, -} from "./dual-spark-executor.js"; -import { fixtureDualSparkPlan } from "./dual-spark-fixture.test-support.js"; + assertManagedClusterVllmExecutorConfig, + buildManagedClusterVllmRunArgs, + createManagedClusterVllmExecutor, + inspectManagedClusterVllmNodesSync, + type ManagedClusterVllmExecutorRuntimeDeps, +} from "./managed-cluster-executor.js"; +import { fixtureManagedClusterPlan } from "./managed-cluster-fixture.test-support.js"; import { - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_MANAGED_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, - type DualSparkVllmPlan, - type DualSparkVllmRole, - type DualSparkVllmRolePlan, -} from "./dual-spark-materialize.js"; + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_MANAGED_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, + type ManagedClusterVllmPlan, + type ManagedClusterVllmRole, + type ManagedClusterVllmRolePlan, +} from "./managed-cluster-materialize.js"; const API_KEY = "a".repeat(64); const FINGERPRINT = "b".repeat(64); @@ -35,7 +35,7 @@ const LOCAL_CACHE_ROOT = "/home/nvidia/.cache/huggingface"; const PEER_CACHE_ROOT = "/home/spark/.cache/huggingface"; type DockerCaptureOptions = NonNullable< - Parameters[1] + Parameters[1] >; type StoppedForeignContainerFixture = { @@ -62,33 +62,33 @@ const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixtur signal: "managed label", name: "foreign-inference", image: "example.invalid/inference:latest", - labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + labels: { [MANAGED_CLUSTER_MANAGED_LABEL]: "foreign" }, }, ]; -function bindPlan(fixture: DualStationSshBindingFixture): DualSparkVllmPlan { - const plan = fixtureDualSparkPlan(); +function bindPlan(fixture: DualStationSshBindingFixture): ManagedClusterVllmPlan { + const plan = fixtureManagedClusterPlan(); return { ...plan, - roles: { - head: plan.roles.head, - worker: { - ...plan.roles.worker, + roles: [ + plan.roles[0], + { + ...plan.roles[1], execution: { kind: "ssh", expectedTarget: fixture.binding.peerTarget, bindingHandle: fixture.token, }, }, - }, + ], }; } -function launchLabels(rolePlan: DualSparkVllmRolePlan): Record { +function launchLabels(rolePlan: ManagedClusterVllmRolePlan): Record { return { ...rolePlan.baseLabels, - [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: FINGERPRINT, - [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + [MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL]: FINGERPRINT, + [MANAGED_CLUSTER_TRANSACTION_LABEL]: TRANSACTION_ID, }; } @@ -115,8 +115,8 @@ function successfulDockerResult(stdout = "") { } function runtimeOverrides( - overrides: Partial = {}, -): Partial { + overrides: Partial = {}, +): Partial { return { dockerCapture: vi.fn(() => ""), dockerForceRm: vi.fn(() => successfulDockerResult()), @@ -160,9 +160,9 @@ function routeDockerCapture( return handler(args, options); } -describe("dual-DGX-Spark vLLM executor", () => { +describe("managed-cluster vLLM executor", () => { let bindingFixture: DualStationSshBindingFixture; - let plan: DualSparkVllmPlan; + let plan: ManagedClusterVllmPlan; beforeEach(() => { bindingFixture = createDualStationSshBindingFixture("spark-worker.local"); @@ -175,8 +175,8 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("builds the YAML-backed role launch without a restart policy or bearer value", () => { - const head = plan.roles.head; - const args = buildDualSparkVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)); + const head = plan.roles[0]; + const args = buildManagedClusterVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)); const command = args.at(-1)!; expect(args).toEqual( @@ -230,14 +230,14 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("dispatches the no-op preparation and YAML-backed executable without patch steps", () => { - const head: DualSparkVllmRolePlan = { - ...plan.roles.head, + const head: ManagedClusterVllmRolePlan = { + ...plan.roles[0], preparation: { ref: NO_PREPARATION_REF, phase: "container-before-exec", modelId: plan.model.id, modelRevision: plan.model.revision, - modelDownloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + modelDownloadSizeBytes: plan.roles[0].preparation.modelDownloadSizeBytes, }, command: { executable: "/opt/vllm/bin/vllm", @@ -245,7 +245,9 @@ describe("dual-DGX-Spark vLLM executor", () => { }, }; - const command = buildDualSparkVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)).at(-1)!; + const command = buildManagedClusterVllmRunArgs(head, LOCAL_CACHE_ROOT, launchLabels(head)).at( + -1, + )!; expect(command).toContain("exec '/opt/vllm/bin/vllm' 'serve' 'synthetic/model'"); expect(command).not.toContain("install -m"); @@ -253,8 +255,8 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("keeps the worker launch headless and free of the bearer environment key", () => { - const worker = plan.roles.worker; - const args = buildDualSparkVllmRunArgs(worker, PEER_CACHE_ROOT, launchLabels(worker)); + const worker = plan.roles[1]; + const args = buildManagedClusterVllmRunArgs(worker, PEER_CACHE_ROOT, launchLabels(worker)); expect(args).not.toContain("VLLM_API_KEY"); expect(args.at(-1)).toContain("'--headless'"); @@ -266,58 +268,70 @@ describe("dual-DGX-Spark vLLM executor", () => { it("rejects a changed binding handoff before any Docker operation", () => { const changedPlan = { ...plan, - roles: { - ...plan.roles, - worker: { - ...plan.roles.worker, + roles: [ + plan.roles[0], + { + ...plan.roles[1], execution: { kind: "ssh" as const, expectedTarget: bindingFixture.binding.peerTarget, bindingHandle: "changed", }, }, - }, + ], }; expect(() => - createDualSparkVllmExecutor( + createManagedClusterVllmExecutor( { plan: changedPlan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides(), ), - ).toThrow(/qualified binding and plan/); + ).toThrow(/executor target .* is invalid/); }); it("revalidates catalog-derived commands and exposes the same synchronous inspector", () => { const config = { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }; - expect(inspectDualSparkVllmNodesSync(config, runtimeOverrides())).toEqual({ - head: { containers: [], listeningPorts: [] }, - worker: { containers: [], listeningPorts: [] }, + expect(inspectManagedClusterVllmNodesSync(config, runtimeOverrides())).toEqual({ + nodes: [ + { nodeId: plan.roles[0].nodeId, snapshot: { containers: [], listeningPorts: [] } }, + { nodeId: plan.roles[1].nodeId, snapshot: { containers: [], listeningPorts: [] } }, + ], }); - const changedPlan: DualSparkVllmPlan = { + const changedPlan: ManagedClusterVllmPlan = { ...plan, - roles: { - ...plan.roles, - head: { - ...plan.roles.head, + roles: [ + { + ...plan.roles[0], command: { - ...plan.roles.head.command, - arguments: [...plan.roles.head.command.arguments, "--changed"], + ...plan.roles[0].command, + arguments: [...plan.roles[0].command.arguments, "--changed"], }, }, - }, + plan.roles[1], + ], }; - expect(() => assertDualSparkVllmExecutorConfig({ ...config, plan: changedPlan })).toThrow( + expect(() => assertManagedClusterVllmExecutorConfig({ ...config, plan: changedPlan })).toThrow( /catalog-derived adapter contract/, ); }); @@ -325,23 +339,28 @@ describe("dual-DGX-Spark vLLM executor", () => { it("validates selected definition digests without pinning the aggregate catalog", () => { const config = { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }; - const catalogExpandedElsewhere: DualSparkVllmPlan = { + const catalogExpandedElsewhere: ManagedClusterVllmPlan = { ...plan, catalogDigest: `sha256:${"e".repeat(64)}`, }; expect(() => - assertDualSparkVllmExecutorConfig({ + assertManagedClusterVllmExecutorConfig({ ...config, plan: catalogExpandedElsewhere, }), ).not.toThrow(); expect(() => - assertDualSparkVllmExecutorConfig({ + assertManagedClusterVllmExecutorConfig({ ...config, plan: { ...plan, recipeDigest: `sha256:${"f".repeat(64)}` }, }), @@ -349,7 +368,7 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("inspects every container plus host listeners and marks only the exact live role healthy", async () => { - const headLabels = launchLabels(plan.roles.head); + const headLabels = launchLabels(plan.roles[0]); const foreignLabels = { "example.foreign": "true" }; const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => routeDockerCapture(args, options, { @@ -358,8 +377,8 @@ describe("dual-DGX-Spark vLLM executor", () => { [ inspectionRow({ id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, + name: plan.roles[0].containerName, + image: plan.roles[0].image, running: true, labels: headLabels, }), @@ -380,17 +399,22 @@ describe("dual-DGX-Spark vLLM executor", () => { () => `LISTEN 0 4096 0.0.0.0:${String(plan.apiPort)} 0.0.0.0:*\nLISTEN 0 128 [::]:${String(plan.masterPort)} [::]:*\n`, ); - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ dockerCapture, captureListeners }), ); - const snapshot = await executor.inspectNode(plan.roles.head); + const snapshot = await executor.inspectNode(plan.roles[0]); expect(snapshot.listeningPorts).toEqual([plan.apiPort, plan.masterPort].sort((a, b) => a - b)); expect(snapshot.containers).toHaveLength(2); @@ -409,24 +433,29 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("fails closed when listener inspection is malformed", async () => { - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ captureListeners: vi.fn(() => "not-an-ss-row") }), ); - await expect(executor.inspectNode(plan.roles.head)).rejects.toThrow(/listener inspection/); + await expect(executor.inspectNode(plan.roles[0])).rejects.toThrow(/listener inspection/); }); it("does not declare the worker-first boundary once a head setup appears", async () => { const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => { - const role = options?.env?.DOCKER_HOST ? "worker" : "head"; - const rolePlan = plan.roles[role]; - const id = role === "worker" ? WORKER_ID : HEAD_ID; + const roleIndex = options?.env?.DOCKER_HOST ? 1 : 0; + const rolePlan = plan.roles[roleIndex]!; + const id = roleIndex === 1 ? WORKER_ID : HEAD_ID; return routeDockerCapture(args, options, { quiet: fixedDockerCapture(id), inspect: fixedDockerCapture( @@ -443,12 +472,17 @@ describe("dual-DGX-Spark vLLM executor", () => { }); }); let tick = 0; - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ dockerCapture, @@ -458,9 +492,9 @@ describe("dual-DGX-Spark vLLM executor", () => { await expect( executor.waitForWorkerDistributedReady({ - rolePlan: plan.roles.worker, + rolePlan: plan.roles[1], containerId: WORKER_ID, - expectedLabels: launchLabels(plan.roles.worker), + expectedLabels: launchLabels(plan.roles[1]), timeoutMs: 1, }), ).resolves.toBe(false); @@ -478,10 +512,10 @@ describe("dual-DGX-Spark vLLM executor", () => { role === "worker" ? inspectionRow({ id, - name: plan.roles.worker.containerName, - image: plan.roles.worker.image, + name: plan.roles[1].containerName, + image: plan.roles[1].image, running: true, - labels: launchLabels(plan.roles.worker), + labels: launchLabels(plan.roles[1]), }) : inspectionRow({ id, @@ -496,12 +530,17 @@ describe("dual-DGX-Spark vLLM executor", () => { }); }); let tick = 0; - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ dockerCapture, @@ -511,24 +550,24 @@ describe("dual-DGX-Spark vLLM executor", () => { await expect( executor.waitForWorkerDistributedReady({ - rolePlan: plan.roles.worker, + rolePlan: plan.roles[1], containerId: WORKER_ID, - expectedLabels: launchLabels(plan.roles.worker), + expectedLabels: launchLabels(plan.roles[1]), timeoutMs: 1, }), ).resolves.toBe(false); }); it("starts one exact head with the bearer only in the Docker subprocess environment", async () => { - const labels = launchLabels(plan.roles.head); + const labels = launchLabels(plan.roles[0]); const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => routeDockerCapture(args, options, { quiet: fixedDockerCapture(HEAD_ID), inspect: fixedDockerCapture( inspectionRow({ id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, + name: plan.roles[0].containerName, + image: plan.roles[0].image, running: true, labels, }), @@ -537,23 +576,28 @@ describe("dual-DGX-Spark vLLM executor", () => { fallback: unexpectedDockerCapture, }), ); - const dockerRunDetached = vi.fn(() => - successfulDockerResult(`${HEAD_ID}\n`), + const dockerRunDetached = vi.fn( + () => successfulDockerResult(`${HEAD_ID}\n`), ); - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ dockerCapture, dockerRunDetached }), ); const result = await executor.startContainer({ - rolePlan: plan.roles.head, + rolePlan: plan.roles[0], labels, - preparation: plan.roles.head.preparation, + preparation: plan.roles[0].preparation, bearerApiKey: API_KEY, }); @@ -570,44 +614,54 @@ describe("dual-DGX-Spark vLLM executor", () => { it("injects staging targets but leaves cleanup construction usable without staging", async () => { const stageNode = vi.fn(async () => ({ ok: true })); - const withStage = createDualSparkVllmExecutor( + const withStage = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], stageNode, }, runtimeOverrides(), ); - const withoutStage = createDualSparkVllmExecutor( + const withoutStage = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides(), ); expect( await withStage.stageNode({ - rolePlan: plan.roles.worker, - preparation: plan.roles.worker.preparation, + rolePlan: plan.roles[1], + preparation: plan.roles[1].preparation, }), ).toEqual({ ok: true }); expect(stageNode).toHaveBeenCalledWith( expect.any(Object), expect.objectContaining({ - role: "worker", + nodeId: plan.roles[1].nodeId, modelCacheRoot: PEER_CACHE_ROOT, - peerSshBinding: bindingFixture.binding, + sshBinding: bindingFixture.binding, }), ); await expect( withoutStage.stageNode({ - rolePlan: plan.roles.head, - preparation: plan.roles.head.preparation, + rolePlan: plan.roles[0], + preparation: plan.roles[0].preparation, }), ).resolves.toMatchObject({ ok: false, @@ -616,15 +670,15 @@ describe("dual-DGX-Spark vLLM executor", () => { }); it("removes only the revalidated exact container ID", async () => { - const labels = launchLabels(plan.roles.head); + const labels = launchLabels(plan.roles[0]); const dockerCapture = vi.fn((args: readonly string[], options?: DockerCaptureOptions) => routeDockerCapture(args, options, { quiet: fixedDockerCapture(HEAD_ID), inspect: fixedDockerCapture( inspectionRow({ id: HEAD_ID, - name: plan.roles.head.containerName, - image: plan.roles.head.image, + name: plan.roles[0].containerName, + image: plan.roles[0].image, running: false, labels, }), @@ -634,22 +688,24 @@ describe("dual-DGX-Spark vLLM executor", () => { }), ); const dockerForceRm = vi.fn(() => successfulDockerResult()); - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ dockerCapture, dockerForceRm }), ); - await expect(executor.removeContainer(plan.roles.head, HEAD_ID)).resolves.toEqual({ ok: true }); + await expect(executor.removeContainer(plan.roles[0], HEAD_ID)).resolves.toEqual({ ok: true }); expect(dockerForceRm).toHaveBeenCalledWith(HEAD_ID, expect.any(Object)); - expect(dockerForceRm).not.toHaveBeenCalledWith( - plan.roles.head.containerName, - expect.anything(), - ); + expect(dockerForceRm).not.toHaveBeenCalledWith(plan.roles[0].containerName, expect.anything()); }); it("performs bounded authenticated model and chat probes without putting the key in argv", async () => { @@ -680,17 +736,22 @@ describe("dual-DGX-Spark vLLM executor", () => { stderr: "", message: "", }); - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ createBearerAuthConfig, runCurlProbe }), ); const request = { - baseUrl: plan.roles.head.endpoint!, + baseUrl: plan.roles[0].endpoint!, apiKey: API_KEY, expectedModel: plan.model.servedName, timeoutMs: 10_000, @@ -721,12 +782,17 @@ describe("dual-DGX-Spark vLLM executor", () => { lockCalls += 1; return await operation(); }; - const executor = createDualSparkVllmExecutor( + const executor = createManagedClusterVllmExecutor( { plan, - peerSshBinding: bindingFixture.binding, - localCacheRoot: LOCAL_CACHE_ROOT, - peerCacheRoot: PEER_CACHE_ROOT, + nodes: [ + { nodeId: plan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: plan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], }, runtimeOverrides({ createTransactionId: () => "d".repeat(32), diff --git a/src/lib/inference/serving/dual-spark-executor.ts b/src/lib/inference/serving/managed-cluster-executor.ts similarity index 75% rename from src/lib/inference/serving/dual-spark-executor.ts rename to src/lib/inference/serving/managed-cluster-executor.ts index 46f64274783..aaaa4372542 100644 --- a/src/lib/inference/serving/dual-spark-executor.ts +++ b/src/lib/inference/serving/managed-cluster-executor.ts @@ -28,41 +28,38 @@ import { getManagedInferenceCompiledPreset, getManagedInferenceCompiledRecipe } import { managedInferenceHexDigest } from "./catalog-integrity.js"; import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; import { - type DualSparkApiProbeRequest, - type DualSparkContainerStartRequest, - type DualSparkContainerWaitRequest, - type DualSparkNodeSnapshot, - type DualSparkObservedContainer, - type DualSparkStageRequest, - type DualSparkVllmLifecycleDeps, isRelatedManagedVllmContainer, -} from "./dual-spark-lifecycle.js"; + type ManagedClusterApiProbeRequest, + type ManagedClusterContainerStartRequest, + type ManagedClusterContainerWaitRequest, + type ManagedClusterNodeSnapshot, + type ManagedClusterObservedContainer, + type ManagedClusterStageRequest, + type ManagedClusterVllmLifecycleDeps, +} from "./managed-cluster-lifecycle.js"; import { - DUAL_SPARK_ADAPTER_LABEL, - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_CLUSTER_LABEL, - DUAL_SPARK_GPU_LABEL, - DUAL_SPARK_IMAGE_LABEL, - DUAL_SPARK_MANAGED_LABEL, - DUAL_SPARK_MODEL_REVISION_LABEL, - DUAL_SPARK_PLAN_LABEL, - DUAL_SPARK_PRESET_LABEL, - DUAL_SPARK_RECIPE_LABEL, - DUAL_SPARK_ROLE_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, - DUAL_SPARK_VLLM_ADAPTER_ID, - DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME, - DUAL_SPARK_VLLM_MASTER_PORT, - DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, - type DualSparkVllmPlan, - type DualSparkVllmRole, - type DualSparkVllmRolePlan, -} from "./dual-spark-materialize.js"; -import { materializeDualSparkVllmPreparation } from "./dual-spark-preparation.js"; + MANAGED_CLUSTER_ADAPTER_LABEL, + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_CLUSTER_LABEL, + MANAGED_CLUSTER_GPU_LABEL, + MANAGED_CLUSTER_IMAGE_LABEL, + MANAGED_CLUSTER_MANAGED_LABEL, + MANAGED_CLUSTER_MODEL_REVISION_LABEL, + MANAGED_CLUSTER_PLAN_LABEL, + MANAGED_CLUSTER_PRESET_LABEL, + MANAGED_CLUSTER_RECIPE_LABEL, + MANAGED_CLUSTER_ROLE_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, + MANAGED_CLUSTER_VLLM_ADAPTER_ID, + type ManagedClusterVllmPlan, + type ManagedClusterVllmRolePlan, + managedClusterHeadRole, +} from "./managed-cluster-materialize.js"; +import { materializeManagedClusterVllmPreparation } from "./managed-cluster-preparation.js"; import { - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, -} from "./dual-spark-topology.js"; + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, +} from "./managed-cluster-topology.js"; const API_KEY_PATTERN = /^[a-f0-9]{64}$/; const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/; @@ -111,31 +108,35 @@ if content.count(existing) != 1: target.write_text(content.replace(existing, replacement), encoding="utf-8") `.trim(); -export interface DualSparkExecutorStageTarget { - readonly role: DualSparkVllmRole; +export interface ManagedClusterExecutorStageTarget { + readonly nodeId: string; readonly dockerEnv: Readonly>; readonly modelCacheRoot: string; - readonly peerSshBinding?: DualStationSshBinding; + readonly sshBinding?: DualStationSshBinding; } -export type DualSparkExecutorStageNode = ( - request: DualSparkStageRequest, - target: DualSparkExecutorStageTarget, +export type ManagedClusterExecutorStageNode = ( + request: ManagedClusterStageRequest, + target: ManagedClusterExecutorStageTarget, ) => Promise<{ ok: boolean; reason?: string }>; -export interface CreateDualSparkVllmExecutorOptions { - readonly plan: DualSparkVllmPlan; - readonly peerSshBinding: DualStationSshBinding; - readonly localCacheRoot: string; - readonly peerCacheRoot: string; - readonly stageNode?: DualSparkExecutorStageNode; +export interface CreateManagedClusterVllmExecutorOptions { + readonly plan: ManagedClusterVllmPlan; + readonly nodes: readonly ManagedClusterExecutorNodeTarget[]; + readonly stageNode?: ManagedClusterExecutorStageNode; } -export interface DualSparkVllmExecutorRuntimeDeps { +export interface ManagedClusterExecutorNodeTarget { + readonly nodeId: string; + readonly modelCacheRoot: string; + readonly sshBinding?: DualStationSshBinding; +} + +export interface ManagedClusterVllmExecutorRuntimeDeps { dockerCapture: typeof dockerCapture; dockerForceRm: typeof dockerForceRm; dockerRunDetached: typeof dockerRunDetached; - captureListeners(role: DualSparkVllmRole, binding: DualStationSshBinding): string; + captureListeners(rolePlan: ManagedClusterVllmRolePlan, binding?: DualStationSshBinding): string; createBearerAuthConfig: typeof createBearerAuthConfig; createTransactionId(): string; now(): number; @@ -146,12 +147,20 @@ export interface DualSparkVllmExecutorRuntimeDeps { type SelectedRecipe = ManagedInferenceServingRecipe["spec"]; -const DEFAULT_DEPS: DualSparkVllmExecutorRuntimeDeps = { +const DEFAULT_DEPS: ManagedClusterVllmExecutorRuntimeDeps = { dockerCapture, dockerForceRm, dockerRunDetached, - captureListeners: (role, binding) => - captureManagedVllmTcpListeners(role, binding, DOCKER_INSPECTION_TIMEOUT_MS), + captureListeners: (rolePlan, binding) => { + if (rolePlan.execution.kind === "ssh" && !binding) { + throw new Error("Managed cluster worker listener probe has no SSH binding"); + } + return captureManagedVllmTcpListeners( + rolePlan.role, + binding ?? ({} as DualStationSshBinding), + DOCKER_INSPECTION_TIMEOUT_MS, + ); + }, createBearerAuthConfig, createTransactionId: () => randomBytes(16).toString("hex"), now: () => Date.now(), @@ -178,13 +187,13 @@ function normalizedAbsoluteHostPath(value: string, label: string): string { function exactKeys(actual: object, expected: readonly string[], label: string): void { const keys = Object.keys(actual).sort(); if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) { - throw new Error(`${label} does not match the dual-Spark adapter contract`); + throw new Error(`${label} does not match the managed cluster adapter contract`); } } function recipeCommandArguments( - rolePlan: DualSparkVllmRolePlan, - plan: DualSparkVllmPlan, + rolePlan: ManagedClusterVllmRolePlan, + plan: ManagedClusterVllmPlan, recipe: SelectedRecipe, ): string[] { const staticArguments = recipe.serve.arguments.flatMap(({ name, value }) => @@ -219,8 +228,8 @@ function recipeCommandArguments( } function assertRolePlan( - rolePlan: DualSparkVllmRolePlan, - plan: DualSparkVllmPlan, + rolePlan: ManagedClusterVllmRolePlan, + plan: ManagedClusterVllmPlan, recipe: SelectedRecipe, ): void { const isHead = rolePlan.role === "head"; @@ -239,18 +248,18 @@ function assertRolePlan( HEADLESS: isHead ? "" : "1", }; const baseLabels = { - [DUAL_SPARK_MANAGED_LABEL]: "true", - [DUAL_SPARK_ADAPTER_LABEL]: DUAL_SPARK_VLLM_ADAPTER_ID, - [DUAL_SPARK_PRESET_LABEL]: plan.presetId, - [DUAL_SPARK_RECIPE_LABEL]: plan.recipeId, - [DUAL_SPARK_ROLE_LABEL]: rolePlan.role, - [DUAL_SPARK_CLUSTER_LABEL]: plan.clusterId, - [DUAL_SPARK_PLAN_LABEL]: plan.planId, - [DUAL_SPARK_GPU_LABEL]: rolePlan.gpuId, - [DUAL_SPARK_IMAGE_LABEL]: recipe.runtime.image, - [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.model.revision, + [MANAGED_CLUSTER_MANAGED_LABEL]: "true", + [MANAGED_CLUSTER_ADAPTER_LABEL]: MANAGED_CLUSTER_VLLM_ADAPTER_ID, + [MANAGED_CLUSTER_PRESET_LABEL]: plan.presetId, + [MANAGED_CLUSTER_RECIPE_LABEL]: plan.recipeId, + [MANAGED_CLUSTER_ROLE_LABEL]: rolePlan.role, + [MANAGED_CLUSTER_CLUSTER_LABEL]: plan.clusterId, + [MANAGED_CLUSTER_PLAN_LABEL]: plan.planId, + [MANAGED_CLUSTER_GPU_LABEL]: rolePlan.gpuId, + [MANAGED_CLUSTER_IMAGE_LABEL]: recipe.runtime.image, + [MANAGED_CLUSTER_MODEL_REVISION_LABEL]: recipe.model.revision, }; - const preparation = materializeDualSparkVllmPreparation({ + const preparation = materializeManagedClusterVllmPreparation({ ...recipe.model, modelCacheTarget: recipe.runtime.modelCache.target, }); @@ -265,12 +274,10 @@ function assertRolePlan( }; const expected = { role: rolePlan.role, - rank: isHead ? 0 : 1, + rank: rolePlan.rank, nodeId: rolePlan.nodeId, gpuId: rolePlan.gpuId, - containerName: isHead - ? DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME - : DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, + containerName: `nemoclaw-vllm-cluster-rank-${String(rolePlan.rank)}`, execution: rolePlan.execution, image: recipe.runtime.image, runtime: { @@ -304,7 +311,8 @@ function assertRolePlan( !rolePlan.nodeId || rolePlan.nodeId.length > 256 || !/^GPU-[A-Za-z0-9-]+$/.test(rolePlan.gpuId) || - rolePlan.fabric.primaryRailIndex !== 0 || + !Number.isSafeInteger(rolePlan.fabric.primaryRailIndex) || + rolePlan.fabric.primaryRailIndex < 0 || !SAFE_DEVICE_PATTERN.test(rolePlan.fabric.netdev) || !SAFE_DEVICE_PATTERN.test(rolePlan.fabric.hcaDevice) || net.isIP(rolePlan.fabric.address) !== 4 || @@ -330,23 +338,36 @@ function recipeApiPort(recipe: SelectedRecipe): number | undefined { } /** Read-only validation shared by installer, receipt, recovery, and cleanup. */ -export function assertDualSparkVllmExecutorConfig( - config: CreateDualSparkVllmExecutorOptions, +export function assertManagedClusterVllmExecutorConfig( + config: CreateManagedClusterVllmExecutorOptions, ): void { exactKeys( config, - [ - "localCacheRoot", - "peerCacheRoot", - "peerSshBinding", - "plan", - ...(Object.hasOwn(config, "stageNode") ? ["stageNode"] : []), - ], - "Dual-Spark executor configuration", + ["nodes", "plan", ...(Object.hasOwn(config, "stageNode") ? ["stageNode"] : [])], + "Managed cluster executor configuration", ); - normalizedAbsoluteHostPath(config.localCacheRoot, "Local model cache root"); - normalizedAbsoluteHostPath(config.peerCacheRoot, "Peer model cache root"); - const { plan, peerSshBinding: binding } = config; + const { plan } = config; + if ( + config.nodes.length !== plan.roles.length || + new Set(config.nodes.map(({ nodeId }) => nodeId)).size !== config.nodes.length || + config.nodes.some(({ nodeId }) => !plan.roles.some((role) => role.nodeId === nodeId)) + ) { + throw new Error("Managed cluster executor node targets do not match the plan"); + } + for (const target of config.nodes) { + normalizedAbsoluteHostPath(target.modelCacheRoot, `${target.nodeId} model cache root`); + const rolePlan = plan.roles.find(({ nodeId }) => nodeId === target.nodeId)!; + if ( + (rolePlan.execution.kind === "local" && target.sshBinding !== undefined) || + (rolePlan.execution.kind === "ssh" && + (!target.sshBinding || + rolePlan.execution.expectedTarget !== target.sshBinding.peerTarget || + rolePlan.execution.bindingHandle !== + encodeDualStationSshBindingHandoff(target.sshBinding))) + ) { + throw new Error(`Managed cluster executor target ${target.nodeId} is invalid`); + } + } const compiledPreset = getManagedInferenceCompiledPreset(plan.presetId); const compiledRecipe = getManagedInferenceCompiledRecipe(plan.recipeId); if ( @@ -357,7 +378,9 @@ export function assertDualSparkVllmExecutorConfig( compiledPreset.definition.spec.plan.recipeRef !== compiledRecipe.definition.metadata.id || compiledPreset.definition.spec.plan.backend !== compiledRecipe.definition.spec.backend ) { - throw new Error("Dual-Spark executor input does not match its selected definition digests"); + throw new Error( + "Managed cluster executor input does not match its selected definition digests", + ); } const recipe = compiledRecipe.definition.spec; const topologyIdentity = { @@ -368,21 +391,21 @@ export function assertDualSparkVllmExecutorConfig( }; const expectedClusterId = managedInferenceHexDigest(topologyIdentity); const expectedPlanId = managedInferenceHexDigest({ - adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + adapterId: MANAGED_CLUSTER_VLLM_ADAPTER_ID, preset: { id: plan.presetId, digest: plan.presetDigest }, recipe: { id: plan.recipeId, digest: plan.recipeDigest }, topology: topologyIdentity, }); const expectedPlan = { schemaVersion: 1, - adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + adapterId: MANAGED_CLUSTER_VLLM_ADAPTER_ID, catalogDigest: plan.catalogDigest, presetId: compiledPreset.definition.metadata.id, presetDigest: compiledPreset.definitionDigest, recipeId: compiledRecipe.definition.metadata.id, recipeDigest: compiledRecipe.definitionDigest, - topologyId: DUAL_SPARK_TOPOLOGY_ID, - topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + topologyId: MANAGED_CLUSTER_TOPOLOGY_ID, + topologySchemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, topologySubjectDigest: plan.topologySubjectDigest, topologyOutputDigest: plan.topologyOutputDigest, clusterId: expectedClusterId, @@ -395,7 +418,7 @@ export function assertDualSparkVllmExecutorConfig( authentication: recipe.serve.authentication, apiPort: recipeApiPort(recipe), masterAddress: plan.masterAddress, - masterPort: DUAL_SPARK_VLLM_MASTER_PORT, + masterPort: recipe.execution.rendezvousPort, readiness: { timeoutMs: recipe.readiness.timeoutSeconds * 1000, expectedModel: recipe.readiness.expectedModel, @@ -407,26 +430,26 @@ export function assertDualSparkVllmExecutorConfig( !SHA256_PATTERN.test(plan.catalogDigest) || !SHA256_PATTERN.test(plan.presetDigest) || !SHA256_PATTERN.test(plan.recipeDigest) || - plan.masterAddress !== plan.roles.head.fabric.address || + plan.masterAddress !== managedClusterHeadRole(plan).fabric.address || !HEX64_PATTERN.test(plan.clusterId) || !HEX64_PATTERN.test(plan.planId) || !SHA256_PATTERN.test(plan.topologySubjectDigest) || !SHA256_PATTERN.test(plan.topologyOutputDigest) || - !isDeepStrictEqual(plan.roles.head.execution, { kind: "local" }) || - !isDeepStrictEqual(plan.roles.worker.execution, { - kind: "ssh", - expectedTarget: binding.peerTarget, - bindingHandle: encodeDualStationSshBindingHandoff(binding), - }) + plan.roles.length !== recipe.execution.nodeCount || + !isDeepStrictEqual(managedClusterHeadRole(plan).execution, { kind: "local" }) || + plan.roles.some( + (rolePlan, index) => + rolePlan.rank !== index || + (index === 0 ? rolePlan.role !== "head" : rolePlan.role !== "worker"), + ) ) { - throw new Error("Dual-Spark executor input does not match its qualified binding and plan"); + throw new Error("Managed cluster executor input does not match its qualified binding and plan"); } - assertRolePlan(plan.roles.head, plan, recipe); - assertRolePlan(plan.roles.worker, plan, recipe); + for (const rolePlan of plan.roles) assertRolePlan(rolePlan, plan, recipe); } function shellQuote(value: string): string { - if (value.includes("\0")) throw new Error("Dual-Spark command value contains a NUL byte"); + if (value.includes("\0")) throw new Error("Managed cluster command value contains a NUL byte"); return `'${value.replaceAll("'", `'"'"'`)}'`; } @@ -434,7 +457,7 @@ function base64url(value: string): string { return Buffer.from(value, "utf8").toString("base64url"); } -function preparationCommand(rolePlan: DualSparkVllmRolePlan): string { +function preparationCommand(rolePlan: ManagedClusterVllmRolePlan): string { const preparation = rolePlan.preparation; const command = ["set -Eeuo pipefail"]; if (preparation.ref === SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF) { @@ -451,7 +474,7 @@ function preparationCommand(rolePlan: DualSparkVllmRolePlan): string { ].join(" "), ); } else if (preparation.ref !== NO_PREPARATION_REF) { - throw new Error("Unsupported dual-Spark preparation"); + throw new Error("Unsupported managed cluster preparation"); } const executable = shellQuote(rolePlan.command.executable); const commandArguments = rolePlan.command.arguments.map(shellQuote).join(" "); @@ -460,13 +483,13 @@ function preparationCommand(rolePlan: DualSparkVllmRolePlan): string { } function validateLaunchLabels( - rolePlan: DualSparkVllmRolePlan, + rolePlan: ManagedClusterVllmRolePlan, labels: Readonly>, ): void { const expectedKeys = [ ...Object.keys(rolePlan.baseLabels), - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, ].sort(); exactKeys(labels, expectedKeys, `${rolePlan.role} launch labels`); for (const [name, value] of Object.entries(labels)) { @@ -482,16 +505,16 @@ function validateLaunchLabels( } if ( !Object.entries(rolePlan.baseLabels).every(([name, value]) => labels[name] === value) || - !HEX64_PATTERN.test(labels[DUAL_SPARK_API_KEY_FINGERPRINT_LABEL] ?? "") || - !TRANSACTION_ID_PATTERN.test(labels[DUAL_SPARK_TRANSACTION_LABEL] ?? "") + !HEX64_PATTERN.test(labels[MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL] ?? "") || + !TRANSACTION_ID_PATTERN.test(labels[MANAGED_CLUSTER_TRANSACTION_LABEL] ?? "") ) { throw new Error(`${rolePlan.role} launch labels do not match its plan`); } } /** Build the exact, non-secret Docker run argv for one materialized role. */ -export function buildDualSparkVllmRunArgs( - rolePlan: DualSparkVllmRolePlan, +export function buildManagedClusterVllmRunArgs( + rolePlan: ManagedClusterVllmRolePlan, modelCacheRoot: string, labels: Readonly>, ): string[] { @@ -649,30 +672,33 @@ function mutationSucceeded(result: ReturnType): boolea return result.status === 0 && !result.error && !result.signal; } -function modelCacheFor( - role: DualSparkVllmRole, - config: CreateDualSparkVllmExecutorOptions, -): string { - return role === "head" ? config.localCacheRoot : config.peerCacheRoot; +function targetFor( + rolePlan: ManagedClusterVllmRolePlan, + config: CreateManagedClusterVllmExecutorOptions, +): ManagedClusterExecutorNodeTarget { + const target = config.nodes.find(({ nodeId }) => nodeId === rolePlan.nodeId); + if (!target) throw new Error(`Managed cluster node ${rolePlan.nodeId} has no executor target`); + return target; } function roleDockerEnv( - rolePlan: DualSparkVllmRolePlan, - config: CreateDualSparkVllmExecutorOptions, + rolePlan: ManagedClusterVllmRolePlan, + config: CreateManagedClusterVllmExecutorOptions, ): Record { + const target = targetFor(rolePlan, config); const env = - rolePlan.role === "head" + rolePlan.execution.kind === "local" ? buildLocalDualStationDockerEnv() - : buildRemoteVllmDockerEnv(config.peerSshBinding); + : buildRemoteVllmDockerEnv(target.sshBinding!); delete env.VLLM_API_KEY; return env; } function processMatchesRole( - rolePlan: DualSparkVllmRolePlan, + rolePlan: ManagedClusterVllmRolePlan, containerId: string, env: Record, - deps: DualSparkVllmExecutorRuntimeDeps, + deps: ManagedClusterVllmExecutorRuntimeDeps, ): boolean { const expected = base64url( JSON.stringify([rolePlan.command.executable, ...rolePlan.command.arguments]), @@ -692,10 +718,10 @@ function processMatchesRole( } function inspectRoleNode( - rolePlan: DualSparkVllmRolePlan, - config: CreateDualSparkVllmExecutorOptions, - deps: DualSparkVllmExecutorRuntimeDeps, -): DualSparkNodeSnapshot { + rolePlan: ManagedClusterVllmRolePlan, + config: CreateManagedClusterVllmExecutorOptions, + deps: ManagedClusterVllmExecutorRuntimeDeps, +): ManagedClusterNodeSnapshot { const env = roleDockerEnv(rolePlan, config); const rawIds = deps.dockerCapture(["container", "ls", "--all", "--no-trunc", "--quiet"], { env, @@ -718,7 +744,7 @@ function inspectRoleNode( ids, ) : []; - const containers: DualSparkObservedContainer[] = inspected.map((container) => ({ + const containers: ManagedClusterObservedContainer[] = inspected.map((container) => ({ ...container, healthy: container.running && @@ -728,33 +754,37 @@ function inspectRoleNode( processMatchesRole(rolePlan, container.id, env, deps), })); const listeningPorts = parseListeningPorts( - deps.captureListeners(rolePlan.role, config.peerSshBinding), + deps.captureListeners(rolePlan, targetFor(rolePlan, config).sshBinding), ); return { containers, listeningPorts }; } -export interface DualSparkVllmNodeSnapshots { - readonly head: DualSparkNodeSnapshot; - readonly worker: DualSparkNodeSnapshot; +export interface ManagedClusterVllmNodeSnapshots { + readonly nodes: readonly { + readonly nodeId: string; + readonly snapshot: ManagedClusterNodeSnapshot; + }[]; } /** Synchronous read-only recovery seam backed by the production inspector. */ -export function inspectDualSparkVllmNodesSync( - config: CreateDualSparkVllmExecutorOptions, - overrides: Partial = {}, -): DualSparkVllmNodeSnapshots { +export function inspectManagedClusterVllmNodesSync( + config: CreateManagedClusterVllmExecutorOptions, + overrides: Partial = {}, +): ManagedClusterVllmNodeSnapshots { const deps = { ...DEFAULT_DEPS, ...overrides }; - assertDualSparkVllmExecutorConfig(config); + assertManagedClusterVllmExecutorConfig(config); return { - head: inspectRoleNode(config.plan.roles.head, config, deps), - worker: inspectRoleNode(config.plan.roles.worker, config, deps), + nodes: config.plan.roles.map((rolePlan) => ({ + nodeId: rolePlan.nodeId, + snapshot: inspectRoleNode(rolePlan, config, deps), + })), }; } function exactWaitObservation( - snapshot: DualSparkNodeSnapshot, - request: DualSparkContainerWaitRequest, -): DualSparkObservedContainer | null { + snapshot: ManagedClusterNodeSnapshot, + request: ManagedClusterContainerWaitRequest, +): ManagedClusterObservedContainer | null { const matches = snapshot.containers.filter(({ id }) => id === request.containerId); if (matches.length !== 1) return null; const observed = matches[0]!; @@ -766,8 +796,8 @@ function exactWaitObservation( } function workerFirstBoundaryIsClear( - snapshot: DualSparkNodeSnapshot, - plan: DualSparkVllmPlan, + snapshot: ManagedClusterNodeSnapshot, + plan: ManagedClusterVllmPlan, ): boolean { return ( !snapshot.listeningPorts.some((port) => port === plan.apiPort || port === plan.masterPort) && @@ -776,9 +806,9 @@ function workerFirstBoundaryIsClear( } async function waitForRoleProcess( - request: DualSparkContainerWaitRequest, - config: CreateDualSparkVllmExecutorOptions, - deps: DualSparkVllmExecutorRuntimeDeps, + request: ManagedClusterContainerWaitRequest, + config: CreateManagedClusterVllmExecutorOptions, + deps: ManagedClusterVllmExecutorRuntimeDeps, stableChecks: number, requireHeadAbsent = false, ): Promise { @@ -793,7 +823,7 @@ async function waitForRoleProcess( const headAbsent = !requireHeadAbsent || workerFirstBoundaryIsClear( - inspectRoleNode(config.plan.roles.head, config, deps), + inspectRoleNode(managedClusterHeadRole(config.plan), config, deps), config.plan, ); consecutive = observed?.running && observed.healthy && headAbsent ? consecutive + 1 : 0; @@ -833,9 +863,9 @@ function validApiBody(body: string, expectedModel: string, kind: "models" | "cha } async function probeAuthenticatedApi( - request: DualSparkApiProbeRequest, + request: ManagedClusterApiProbeRequest, kind: "models" | "chat", - deps: DualSparkVllmExecutorRuntimeDeps, + deps: ManagedClusterVllmExecutorRuntimeDeps, ): Promise { if (!API_KEY_PATTERN.test(request.apiKey)) return false; const maximum = kind === "models" ? MAX_MODELS_PROBE_MS : MAX_CHAT_PROBE_MS; @@ -846,7 +876,7 @@ async function probeAuthenticatedApi( let authConfig: ReturnType | undefined; try { authConfig = deps.createBearerAuthConfig(request.apiKey, { - prefix: "nemoclaw-dual-spark-vllm-probe", + prefix: "nemoclaw-managed-cluster-vllm-probe", }); const baseUrl = request.baseUrl.replace(/\/+$/, ""); const body = @@ -891,27 +921,32 @@ async function probeAuthenticatedApi( } /** - * Bind the code-owned lifecycle to two exact Docker daemons and the qualified, + * Bind the code-owned lifecycle to every exact Docker daemon and each qualified, * owner-only SSH handoff. Staging stays caller-injected so this module does not * depend on installer/model-download orchestration. */ -export function createDualSparkVllmExecutor( - config: CreateDualSparkVllmExecutorOptions, - overrides: Partial = {}, -): DualSparkVllmLifecycleDeps { +export function createManagedClusterVllmExecutor( + config: CreateManagedClusterVllmExecutorOptions, + overrides: Partial = {}, +): ManagedClusterVllmLifecycleDeps { const deps = { ...DEFAULT_DEPS, ...overrides }; - assertDualSparkVllmExecutorConfig(config); + assertManagedClusterVllmExecutorConfig(config); const capturedPlan = structuredClone(config.plan); - const assertPlan = (plan: DualSparkVllmPlan): void => { + const assertPlan = (plan: ManagedClusterVllmPlan): void => { if (!isDeepStrictEqual(plan, capturedPlan)) { - throw new Error("Dual-Spark executor refused a changed materialized plan"); + throw new Error("Managed cluster executor refused a changed materialized plan"); } - assertDualSparkVllmExecutorConfig(config); + assertManagedClusterVllmExecutorConfig(config); }; - const assertRole = (rolePlan: DualSparkVllmRolePlan): void => { + const assertRole = (rolePlan: ManagedClusterVllmRolePlan): void => { assertPlan(config.plan); - if (!isDeepStrictEqual(rolePlan, config.plan.roles[rolePlan.role])) { - throw new Error("Dual-Spark executor refused a role outside its materialized plan"); + if ( + !isDeepStrictEqual( + rolePlan, + config.plan.roles.find(({ nodeId }) => nodeId === rolePlan.nodeId), + ) + ) { + throw new Error("Managed cluster executor refused a role outside its materialized plan"); } }; @@ -926,17 +961,18 @@ export function createDualSparkVllmExecutor( return { ok: false, reason: `${request.rolePlan.role} preparation contract changed` }; } if (!config.stageNode) { - return { ok: false, reason: "dual-Spark model and image staging is not configured" }; + return { ok: false, reason: "managed cluster model and image staging is not configured" }; } const dockerEnv = roleDockerEnv(request.rolePlan, config); + const target = targetFor(request.rolePlan, config); return await config.stageNode(request, { - role: request.rolePlan.role, + nodeId: request.rolePlan.nodeId, dockerEnv, - modelCacheRoot: modelCacheFor(request.rolePlan.role, config), - ...(request.rolePlan.role === "worker" ? { peerSshBinding: config.peerSshBinding } : {}), + modelCacheRoot: target.modelCacheRoot, + ...(target.sshBinding ? { sshBinding: target.sshBinding } : {}), }); }, - async startContainer(request: DualSparkContainerStartRequest) { + async startContainer(request: ManagedClusterContainerStartRequest) { assertRole(request.rolePlan); if (!isDeepStrictEqual(request.preparation, request.rolePlan.preparation)) { return { ok: false, reason: `${request.rolePlan.role} preparation contract changed` }; @@ -951,16 +987,16 @@ export function createDualSparkVllmExecutor( } let args: string[]; try { - args = buildDualSparkVllmRunArgs( + args = buildManagedClusterVllmRunArgs( request.rolePlan, - modelCacheFor(request.rolePlan.role, config), + targetFor(request.rolePlan, config).modelCacheRoot, request.labels, ); } catch (error) { return { ok: false, reason: (error as Error).message }; } if (request.bearerApiKey && JSON.stringify(args).includes(request.bearerApiKey)) { - return { ok: false, reason: "dual-Spark bearer key entered Docker argv" }; + return { ok: false, reason: "managed cluster bearer key entered Docker argv" }; } const env = roleDockerEnv(request.rolePlan, config); if (isHead) env.VLLM_API_KEY = request.bearerApiKey!; @@ -975,7 +1011,7 @@ export function createDualSparkVllmExecutor( } catch { // Reconcile an exact transaction-owned create below. } - let observed: DualSparkObservedContainer | null = null; + let observed: ManagedClusterObservedContainer | null = null; try { const snapshot = await inspectRoleNode(request.rolePlan, config, deps); const candidates = snapshot.containers.filter( @@ -1011,7 +1047,7 @@ export function createDualSparkVllmExecutor( async waitForWorkerDistributedReady(request) { assertRole(request.rolePlan); if (request.rolePlan.role !== "worker") return false; - // Two spaced exact-process observations prove rank 1 remained alive + // Two spaced exact-process observations prove the worker remained alive // while rank 0 was still absent, the worker-first rendezvous boundary. return await waitForRoleProcess(request, config, deps, 2, true); }, @@ -1058,7 +1094,7 @@ export function createDualSparkVllmExecutor( }, async probeModels(request) { if ( - request.baseUrl !== config.plan.roles.head.endpoint || + request.baseUrl !== managedClusterHeadRole(config.plan).endpoint || request.expectedModel !== config.plan.readiness.expectedModel ) { return false; @@ -1067,7 +1103,7 @@ export function createDualSparkVllmExecutor( }, async probeChat(request) { if ( - request.baseUrl !== config.plan.roles.head.endpoint || + request.baseUrl !== managedClusterHeadRole(config.plan).endpoint || request.expectedModel !== config.plan.readiness.expectedModel ) { return false; diff --git a/src/lib/inference/serving/managed-cluster-fixture.test-support.ts b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts new file mode 100644 index 00000000000..017f67a2e48 --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts @@ -0,0 +1,121 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { loadManagedInferenceCatalog } from "./catalog.js"; +import type { ResolvedManagedInferenceSelection } from "./catalog-types.js"; +import { + type ManagedClusterVllmPlan, + materializeManagedClusterVllmPlan, +} from "./managed-cluster-materialize.js"; +import { + type ManagedClusterTopologyOutput, + managedClusterTopologyOutputDigest, + managedClusterTopologySubjectDigest, +} from "./managed-cluster-topology.js"; + +export const FIXTURE_MANAGED_CLUSTER_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731"; + +export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelection { + const catalog = loadManagedInferenceCatalog(); + const compiledPreset = catalog.presets.find( + ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, + ); + const compiledRecipe = catalog.recipes.find( + ({ definition }) => definition.metadata.id === compiledPreset?.definition.spec.plan.recipeRef, + ); + if (!compiledPreset || !compiledRecipe) { + throw new Error("managed inference fixture catalog is incomplete"); + } + const preset = structuredClone(compiledPreset.definition); + const recipe = structuredClone(compiledRecipe.definition); + const subjectNodeIds = ["spark-head", "spark-worker"] as const; + const output: ManagedClusterTopologyOutput = { + controllerNodeId: "spark-head", + nodes: [ + { nodeId: "spark-head", gpuId: "GPU-head", rank: 0, role: "head" }, + { nodeId: "spark-worker", gpuId: "GPU-worker", rank: 1, role: "worker" }, + ], + rails: [ + { + index: 0, + endpoints: [ + { + nodeId: "spark-head", + netdev: "enp1s0f0np0", + hcaDevice: "rocep1s0f0", + hcaPort: 1, + address: "192.168.100.10", + prefixLength: 24, + peerAddress: "192.168.100.11", + roceGid: { index: 3, value: "::ffff:c0a8:640a" }, + }, + { + nodeId: "spark-worker", + netdev: "enp1s0f1np1", + hcaDevice: "rocep1s0f1", + hcaPort: 1, + address: "192.168.100.11", + prefixLength: 24, + peerAddress: "192.168.100.10", + roceGid: { index: 6, value: "::ffff:c0a8:640b" }, + }, + ], + }, + { + index: 1, + endpoints: [ + { + nodeId: "spark-head", + netdev: "enP2p1s0f0np0", + hcaDevice: "roceP2p1s0f0", + hcaPort: 1, + address: "192.168.101.10", + prefixLength: 24, + peerAddress: "192.168.101.11", + roceGid: { index: 4, value: "::ffff:c0a8:650a" }, + }, + { + nodeId: "spark-worker", + netdev: "enP2p1s0f1np1", + hcaDevice: "roceP2p1s0f1", + hcaPort: 1, + address: "192.168.101.11", + prefixLength: 24, + peerAddress: "192.168.101.10", + roceGid: { index: 7, value: "::ffff:c0a8:650b" }, + }, + ], + }, + ], + masterAddress: "192.168.100.10", + peers: [ + { + nodeId: "spark-worker", + target: "spark-worker.local", + sshBindingHandle: "state/managed-cluster/peer", + }, + ], + }; + return { + outcome: "selected", + selection: "automatic", + catalogDigest: catalog.catalogDigest, + presetDigest: compiledPreset.definitionDigest, + recipeDigest: compiledRecipe.definitionDigest, + preset, + recipe, + topologyQualification: { + id: "host-cluster.direct-cx7", + schemaVersion: 1, + status: "qualified", + subjectNodeIds, + subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), + outputDigest: managedClusterTopologyOutputDigest(output), + output, + }, + }; +} + +export function fixtureManagedClusterPlan(): ManagedClusterVllmPlan { + return materializeManagedClusterVllmPlan(fixtureManagedClusterSelection()); +} diff --git a/src/lib/inference/serving/dual-spark-installer.test.ts b/src/lib/inference/serving/managed-cluster-installer.test.ts similarity index 76% rename from src/lib/inference/serving/dual-spark-installer.test.ts rename to src/lib/inference/serving/managed-cluster-installer.test.ts index 4fdf803a078..62b8c22028b 100644 --- a/src/lib/inference/serving/dual-spark-installer.test.ts +++ b/src/lib/inference/serving/managed-cluster-installer.test.ts @@ -4,27 +4,28 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { - DualSparkConfirmedManagedServingCapability, - DualSparkDetectedManagedServingCapability, -} from "./dual-spark-discovery.js"; + ManagedClusterConfirmedManagedServingCapability, + ManagedClusterDetectedManagedServingCapability, +} from "./managed-cluster-discovery.js"; import type { - CreateDualSparkVllmExecutorOptions, - DualSparkExecutorStageNode, -} from "./dual-spark-executor.js"; -import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; + CreateManagedClusterVllmExecutorOptions, + ManagedClusterExecutorStageNode, +} from "./managed-cluster-executor.js"; +import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { - type DualSparkInstallerEffects, - tryInstallDualSparkManagedVllm, -} from "./dual-spark-installer.js"; -import type { DualSparkVllmLifecycleDeps } from "./dual-spark-lifecycle.js"; + type ManagedClusterInstallerEffects, + tryInstallManagedClusterManagedVllm, +} from "./managed-cluster-installer.js"; +import type { ManagedClusterVllmLifecycleDeps } from "./managed-cluster-lifecycle.js"; const API_KEY = "a".repeat(64); const HEAD_ID = "b".repeat(64); const WORKER_ID = "c".repeat(64); -function readyCapability(): DualSparkDetectedManagedServingCapability { - const selection = fixtureDualSparkSelection(); - const host = (hostname: string, home: string, uid: number) => ({ +function readyCapability(): ManagedClusterDetectedManagedServingCapability { + const selection = fixtureManagedClusterSelection(); + const host = (nodeId: string, hostname: string, home: string, uid: number) => ({ + nodeId, hostname, home, uid, @@ -46,25 +47,35 @@ function readyCapability(): DualSparkDetectedManagedServingCapability { kind: "ready", selectionIntent: "automatic", topology: selection.topologyQualification, - local: host("spark-a", "/home/alice", 1000), - peer: host("spark-b", "/home/bob", 1001), + local: host("spark-head", "spark-a", "/home/alice", 1000), + peers: [host("spark-worker", "spark-b", "/home/bob", 1001)], readiness: [], - peerSshBindingStatePath: "/state/dual-spark-managed-serving.json", - peerSshIdentity: { sshTarget: "spark-b" }, - } as unknown as DualSparkDetectedManagedServingCapability; + sshClaims: [ + { + nodeId: "spark-worker", + statePath: "/state/managed-cluster-managed-serving.json.spark-worker", + identity: { sshTarget: "spark-b" }, + }, + ], + } as unknown as ManagedClusterDetectedManagedServingCapability; } function confirmedCapability( - detected: DualSparkDetectedManagedServingCapability, -): DualSparkConfirmedManagedServingCapability { + detected: ManagedClusterDetectedManagedServingCapability, +): ManagedClusterConfirmedManagedServingCapability { return { ...detected, - peerSshBinding: { peerTarget: "spark-b" }, - peerSshBindingHandle: "binding", - } as unknown as DualSparkConfirmedManagedServingCapability; + sshBindings: [ + { + ...detected.sshClaims[0], + binding: { peerTarget: "spark-b" }, + handle: "binding", + }, + ], + } as unknown as ManagedClusterConfirmedManagedServingCapability; } -function effects(): DualSparkInstallerEffects { +function effects(): ManagedClusterInstallerEffects { return { prerequisites: vi.fn(() => ({ ok: true })), pullImage: vi.fn(async () => ({ ok: true })), @@ -78,13 +89,15 @@ function successfulStart(reusedExisting = false) { ok: true as const, reusedExisting, baseUrl: "http://192.168.100.10:8000", - headContainerId: HEAD_ID, - workerContainerId: WORKER_ID, + containers: [ + { nodeId: "spark-head", containerId: HEAD_ID }, + { nodeId: "spark-worker", containerId: WORKER_ID }, + ], apiKeyFingerprint: "d".repeat(64), }; } -describe("two-Spark managed vLLM installer selection", () => { +describe("managed-cluster vLLM installer selection", () => { beforeEach(() => vi.restoreAllMocks()); it("leaves non-Spark and conflict-free explicit legacy vLLM intent untouched", async () => { @@ -94,14 +107,14 @@ describe("two-Spark managed vLLM installer selection", () => { reason: "no related distributed runtime", })); await expect( - tryInstallDualSparkManagedVllm( + tryInstallManagedClusterManagedVllm( { platform: "station", nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability }, ), ).resolves.toEqual({ kind: "not-selected" }); await expect( - tryInstallDualSparkManagedVllm( + tryInstallManagedClusterManagedVllm( { platform: "spark", env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, @@ -117,7 +130,7 @@ describe("two-Spark managed vLLM installer selection", () => { it("does not let explicit legacy intent bypass a related-runtime conflict", async () => { const installEffects = effects(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, @@ -145,7 +158,7 @@ describe("two-Spark managed vLLM installer selection", () => { const revalidateCapability = vi.fn(); const claimCapability = vi.fn(); const resolveSelection = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: { NEMOCLAW_VLLM_MODEL: "nvidia/Qwen3.6-35B-A3B-NVFP4" }, @@ -169,14 +182,14 @@ describe("two-Spark managed vLLM installer selection", () => { }); it("falls back only for an ordinary automatic no-match", async () => { - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability: () => ({ kind: "not-selected", code: "no-match", - reason: "no exact pair", + reason: "no exact cluster", }), }, ); @@ -186,7 +199,7 @@ describe("two-Spark managed vLLM installer selection", () => { it("stops on durable distributed ownership before capability probing or effects", async () => { const installEffects = effects(); const probeCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, installEffects, { @@ -206,7 +219,7 @@ describe("two-Spark managed vLLM installer selection", () => { it("stops before effects when a related runtime is already present", async () => { const installEffects = effects(); const error = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, installEffects, { @@ -225,7 +238,7 @@ describe("two-Spark managed vLLM installer selection", () => { }); it("admits the selected recipe port before prompting or claiming binding state", async () => { - const selection = fixtureDualSparkSelection(); + const selection = fixtureManagedClusterSelection(); const port = Number( selection.recipe.spec.serve.arguments.find(({ name }) => name === "--port")?.value, ); @@ -236,13 +249,13 @@ describe("two-Spark managed vLLM installer selection", () => { ...base.local, runtimeSnapshot: { ...base.local.runtimeSnapshot, listeningPorts: [port] }, }, - } as DualSparkDetectedManagedServingCapability; + } as ManagedClusterDetectedManagedServingCapability; const promptFn = vi.fn(async () => "yes"); const revalidateCapability = vi.fn(); const claimCapability = vi.fn(); const installEffects = effects(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn }, installEffects, { @@ -262,7 +275,7 @@ describe("two-Spark managed vLLM installer selection", () => { }); it("budgets the selected model and image at full size before prompting", async () => { - const selection = fixtureDualSparkSelection(); + const selection = fixtureManagedClusterSelection(); const base = readyCapability(); const capability = { ...base, @@ -274,11 +287,11 @@ describe("two-Spark managed vLLM installer selection", () => { huggingFace: { ...base.local.storage.huggingFace, availableBytes: 1 }, }, }, - } as DualSparkDetectedManagedServingCapability; + } as ManagedClusterDetectedManagedServingCapability; const promptFn = vi.fn(async () => "yes"); const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn }, effects(), { @@ -296,20 +309,20 @@ describe("two-Spark managed vLLM installer selection", () => { it("rechecks the selected port after consent and before claiming binding state", async () => { const capability = readyCapability(); - const selection = fixtureDualSparkSelection(); + const selection = fixtureManagedClusterSelection(); const port = Number( selection.recipe.spec.serve.arguments.find(({ name }) => name === "--port")?.value, ); const revalidated = { ...capability, - peer: { - ...capability.peer, - runtimeSnapshot: { ...capability.peer.runtimeSnapshot, listeningPorts: [port] }, - }, - } as DualSparkDetectedManagedServingCapability; + peers: capability.peers.map((peer) => ({ + ...peer, + runtimeSnapshot: { ...peer.runtimeSnapshot, listeningPorts: [port] }, + })), + } as ManagedClusterDetectedManagedServingCapability; const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, effects(), { @@ -338,17 +351,17 @@ describe("two-Spark managed vLLM installer selection", () => { huggingFace: { ...capability.local.storage.huggingFace, availableBytes: 1 }, }, }, - } as DualSparkDetectedManagedServingCapability; + } as ManagedClusterDetectedManagedServingCapability; const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, effects(), { probeCapability: () => capability, revalidateCapability: () => revalidated, claimCapability, - resolveSelection: () => fixtureDualSparkSelection(), + resolveSelection: () => fixtureManagedClusterSelection(), assertNoRuntimeReceipts: vi.fn(), log: vi.fn(), error: vi.fn(), @@ -363,7 +376,7 @@ describe("two-Spark managed vLLM installer selection", () => { const capability = readyCapability(); const resolveSelection = vi .fn() - .mockReturnValueOnce(fixtureDualSparkSelection()) + .mockReturnValueOnce(fixtureManagedClusterSelection()) .mockReturnValueOnce({ outcome: "no-match", code: "requirements-not-met", @@ -371,7 +384,7 @@ describe("two-Spark managed vLLM installer selection", () => { }); const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "yes" }, effects(), { @@ -390,7 +403,7 @@ describe("two-Spark managed vLLM installer selection", () => { expect(claimCapability).not.toHaveBeenCalled(); }); - it("revalidates only after consent and stops before effects when the pair changed", async () => { + it("revalidates only after consent and stops before effects when the cluster changed", async () => { const capability = readyCapability(); const installEffects = effects(); const clearBinding = vi.fn(); @@ -407,14 +420,14 @@ describe("two-Spark managed vLLM installer selection", () => { }); const assertNoRuntimeReceipts = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn }, installEffects, { probeCapability: () => capability, revalidateCapability, claimCapability, - resolveSelection: () => fixtureDualSparkSelection(), + resolveSelection: () => fixtureManagedClusterSelection(), assertNoRuntimeReceipts, clearBinding, log: vi.fn(), @@ -442,12 +455,12 @@ describe("two-Spark managed vLLM installer selection", () => { const revalidateCapability = vi.fn(); const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn }, installEffects, { probeCapability: () => capability, - resolveSelection: () => fixtureDualSparkSelection(), + resolveSelection: () => fixtureManagedClusterSelection(), assertGatedModelAccess, revalidateCapability, claimCapability, @@ -469,32 +482,32 @@ describe("two-Spark managed vLLM installer selection", () => { it("stages both exact nodes, launches, persists ownership, and retires temporary binding state", async () => { const capability = readyCapability(); const confirmed = confirmedCapability(capability); - const selection = fixtureDualSparkSelection(); + const selection = fixtureManagedClusterSelection(); const installEffects = effects(); const beforeInstall = vi.fn(); const clearBinding = vi.fn(); const persistReceipt = vi.fn(); - let capturedStage: DualSparkExecutorStageNode | undefined; - const executor = {} as DualSparkVllmLifecycleDeps; - const createExecutor = vi.fn((config: CreateDualSparkVllmExecutorOptions) => { + let capturedStage: ManagedClusterExecutorStageNode | undefined; + const executor = {} as ManagedClusterVllmLifecycleDeps; + const createExecutor = vi.fn((config: CreateManagedClusterVllmExecutorOptions) => { capturedStage = config.stageNode; return executor; }); const start = vi.fn(async (plan) => { expect(capturedStage).toBeDefined(); await capturedStage!( - { rolePlan: plan.roles.worker, preparation: plan.roles.worker.preparation }, + { rolePlan: plan.roles[1], preparation: plan.roles[1].preparation }, { - role: "worker", + nodeId: plan.roles[1].nodeId, dockerEnv: { DOCKER_HOST: "ssh://spark-b" }, - modelCacheRoot: capability.peer.storage.huggingFace.cacheRoot, - peerSshBinding: confirmed.peerSshBinding, + modelCacheRoot: capability.peers[0].storage.huggingFace.cacheRoot, + sshBinding: confirmed.sshBindings[0].binding, }, ); await capturedStage!( - { rolePlan: plan.roles.head, preparation: plan.roles.head.preparation }, + { rolePlan: plan.roles[0], preparation: plan.roles[0].preparation }, { - role: "head", + nodeId: plan.roles[0].nodeId, dockerEnv: {}, modelCacheRoot: capability.local.storage.huggingFace.cacheRoot, }, @@ -502,7 +515,7 @@ describe("two-Spark managed vLLM installer selection", () => { return successfulStart(); }); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, @@ -534,20 +547,28 @@ describe("two-Spark managed vLLM installer selection", () => { expect.objectContaining({ revision: selection.recipe.spec.model.revision }), { DOCKER_HOST: "ssh://spark-b" }, { - hostCacheDir: capability.peer.storage.huggingFace.cacheRoot, + hostCacheDir: capability.peers[0].storage.huggingFace.cacheRoot, userIdentity: "1001:1001", }, ); expect(start).toHaveBeenCalledWith(expect.anything(), API_KEY, executor); expect(persistReceipt).toHaveBeenCalledWith( expect.objectContaining({ - headContainerId: HEAD_ID, - workerContainerId: WORKER_ID, - localCacheRoot: "/home/alice/.cache/huggingface", - peerCacheRoot: "/home/bob/.cache/huggingface", + nodes: [ + expect.objectContaining({ + nodeId: "spark-head", + containerId: HEAD_ID, + cacheRoot: "/home/alice/.cache/huggingface", + }), + expect.objectContaining({ + nodeId: "spark-worker", + containerId: WORKER_ID, + cacheRoot: "/home/bob/.cache/huggingface", + }), + ], }), ); - expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + expect(clearBinding).toHaveBeenCalledWith(capability.sshClaims[0].statePath); }); it("keeps a successful receipt-owned install when temporary binding retirement fails", async () => { @@ -558,15 +579,15 @@ describe("two-Spark managed vLLM installer selection", () => { }); const warn = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability: () => capability, revalidateCapability: () => capability, claimCapability: () => confirmedCapability(capability), - resolveSelection: () => fixtureDualSparkSelection(), - createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + resolveSelection: () => fixtureManagedClusterSelection(), + createExecutor: () => ({}) as ManagedClusterVllmLifecycleDeps, start: async () => successfulStart(), ensureApiKey: () => API_KEY, persistReceipt, @@ -578,24 +599,24 @@ describe("two-Spark managed vLLM installer selection", () => { expect(result).toEqual({ kind: "handled", result: { ok: true } }); expect(persistReceipt).toHaveBeenCalledOnce(); - expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + expect(clearBinding).toHaveBeenCalledWith(capability.sshClaims[0].statePath); expect(persistReceipt.mock.invocationCallOrder[0]).toBeLessThan( clearBinding.mock.invocationCallOrder[0]!, ); expect(warn).toHaveBeenCalledWith( - expect.stringContaining("temporary two-Spark SSH state could not be retired"), + expect.stringContaining("temporary managed cluster SSH state could not be retired"), ); }); - it("cleans only a newly-created exact pair when receipt persistence fails", async () => { + it("cleans only a newly-created exact cluster when receipt persistence fails", async () => { const capability = readyCapability(); - const selection = fixtureDualSparkSelection(); + const selection = fixtureManagedClusterSelection(); const cleanup = vi.fn(async () => ({ ok: true as const, removedContainerIds: [HEAD_ID, WORKER_ID], })); const clearBinding = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { @@ -603,7 +624,7 @@ describe("two-Spark managed vLLM installer selection", () => { revalidateCapability: () => capability, claimCapability: () => confirmedCapability(capability), resolveSelection: () => selection, - createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + createExecutor: () => ({}) as ManagedClusterVllmLifecycleDeps, start: async () => successfulStart(false), cleanup, ensureApiKey: () => API_KEY, @@ -617,22 +638,22 @@ describe("two-Spark managed vLLM installer selection", () => { ); expect(result).toEqual({ kind: "handled", result: { ok: false } }); expect(cleanup).toHaveBeenCalledOnce(); - expect(clearBinding).toHaveBeenCalledWith(capability.peerSshBindingStatePath); + expect(clearBinding).toHaveBeenCalledWith(capability.sshClaims[0].statePath); }); it("retains the claimed binding when receipt-failure rollback is incomplete", async () => { const capability = readyCapability(); const clearBinding = vi.fn(); const warn = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability: () => capability, revalidateCapability: () => capability, claimCapability: () => confirmedCapability(capability), - resolveSelection: () => fixtureDualSparkSelection(), - createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + resolveSelection: () => fixtureManagedClusterSelection(), + createExecutor: () => ({}) as ManagedClusterVllmLifecycleDeps, start: async () => successfulStart(false), cleanup: async () => ({ ok: false, @@ -652,22 +673,24 @@ describe("two-Spark managed vLLM installer selection", () => { expect(result).toEqual({ kind: "handled", result: { ok: false } }); expect(clearBinding).not.toHaveBeenCalled(); - expect(warn).toHaveBeenCalledWith(expect.stringContaining("retained two-Spark SSH ownership")); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("retained managed cluster SSH ownership"), + ); }); it("retains the claimed binding when lifecycle rollback leaves a container", async () => { const capability = readyCapability(); const clearBinding = vi.fn(); const warn = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability: () => capability, revalidateCapability: () => capability, claimCapability: () => confirmedCapability(capability), - resolveSelection: () => fixtureDualSparkSelection(), - createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + resolveSelection: () => fixtureManagedClusterSelection(), + createExecutor: () => ({}) as ManagedClusterVllmLifecycleDeps, start: async () => ({ ok: false, code: "start-failed", @@ -684,22 +707,24 @@ describe("two-Spark managed vLLM installer selection", () => { expect(result).toEqual({ kind: "handled", result: { ok: false } }); expect(clearBinding).not.toHaveBeenCalled(); - expect(warn).toHaveBeenCalledWith(expect.stringContaining("retained two-Spark SSH ownership")); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("retained managed cluster SSH ownership"), + ); }); - it("does not remove an exact reused pair when receipt persistence fails", async () => { + it("does not remove an exact reused cluster when receipt persistence fails", async () => { const capability = readyCapability(); const cleanup = vi.fn(); const clearBinding = vi.fn(); - await tryInstallDualSparkManagedVllm( + await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: true, promptFn: vi.fn() }, effects(), { probeCapability: () => capability, revalidateCapability: () => capability, claimCapability: () => confirmedCapability(capability), - resolveSelection: () => fixtureDualSparkSelection(), - createExecutor: () => ({}) as DualSparkVllmLifecycleDeps, + resolveSelection: () => fixtureManagedClusterSelection(), + createExecutor: () => ({}) as ManagedClusterVllmLifecycleDeps, start: async () => successfulStart(true), cleanup, ensureApiKey: () => API_KEY, @@ -720,14 +745,14 @@ describe("two-Spark managed vLLM installer selection", () => { const clearBinding = vi.fn(); const revalidateCapability = vi.fn(); const claimCapability = vi.fn(); - const result = await tryInstallDualSparkManagedVllm( + const result = await tryInstallManagedClusterManagedVllm( { platform: "spark", env: {}, nonInteractive: false, promptFn: async () => "no" }, effects(), { probeCapability: () => capability, revalidateCapability, claimCapability, - resolveSelection: () => fixtureDualSparkSelection(), + resolveSelection: () => fixtureManagedClusterSelection(), clearBinding, log: vi.fn(), }, diff --git a/src/lib/inference/serving/dual-spark-installer.ts b/src/lib/inference/serving/managed-cluster-installer.ts similarity index 62% rename from src/lib/inference/serving/dual-spark-installer.ts rename to src/lib/inference/serving/managed-cluster-installer.ts index 82792a9bde2..3dc4fbc1997 100644 --- a/src/lib/inference/serving/dual-spark-installer.ts +++ b/src/lib/inference/serving/managed-cluster-installer.ts @@ -4,7 +4,7 @@ import { isAffirmativeAnswer } from "../../onboard/prompt-helpers.js"; import type { VllmProfile } from "../vllm.js"; import { ensureManagedVllmApiKey } from "../vllm-api-key.js"; -import { assertGatedModelAccess, type VllmModelDef, VLLM_EXTRA_ARGS_ENV } from "../vllm-models.js"; +import { assertGatedModelAccess, VLLM_EXTRA_ARGS_ENV, type VllmModelDef } from "../vllm-models.js"; import { clearDualStationSshBinding } from "../vllm-station-ssh-binding.js"; import { imageStorageRequirementBytes, modelStorageRequirementBytes } from "../vllm-storage.js"; import { @@ -13,40 +13,40 @@ import { type ManagedInferenceServingRecipe, } from "./catalog-types.js"; import { - claimDualSparkManagedServingCapability, - type DualSparkConfirmedManagedServingCapability, - type DualSparkDetectedManagedServingCapability, - type DualSparkHostObservation, - type DualSparkStorageCapacityObservation, - NEMOCLAW_DGX_SPARK_PEER_ENV, + claimManagedClusterManagedServingCapability, + type ManagedClusterConfirmedManagedServingCapability, + type ManagedClusterDetectedManagedServingCapability, + type ManagedClusterHostObservation, + type ManagedClusterStorageCapacityObservation, + NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV, NEMOCLAW_SERVING_PRESET_ENV, - probeDualSparkManagedServingCapability, - revalidateDualSparkManagedServingCapability, -} from "./dual-spark-discovery.js"; + probeManagedClusterManagedServingCapability, + revalidateManagedClusterManagedServingCapability, +} from "./managed-cluster-discovery.js"; import { - type CreateDualSparkVllmExecutorOptions, - createDualSparkVllmExecutor, - type DualSparkExecutorStageNode, -} from "./dual-spark-executor.js"; + type CreateManagedClusterVllmExecutorOptions, + createManagedClusterVllmExecutor, + type ManagedClusterExecutorStageNode, +} from "./managed-cluster-executor.js"; import { - cleanupDualSparkManagedVllm, - type StartDualSparkVllmResult, - startAutomaticDualSparkVllm, -} from "./dual-spark-lifecycle.js"; + cleanupManagedClusterManagedVllm, + type StartManagedClusterVllmResult, + startAutomaticManagedClusterVllm, +} from "./managed-cluster-lifecycle.js"; import { - DUAL_SPARK_VLLM_MASTER_PORT, - type DualSparkVllmPlan, - materializeDualSparkVllmPlan, -} from "./dual-spark-materialize.js"; -import type { DualSparkTopologyOutput } from "./dual-spark-topology.js"; + type ManagedClusterVllmPlan, + managedClusterHeadRole, + materializeManagedClusterVllmPlan, +} from "./managed-cluster-materialize.js"; +import { + type PersistManagedClusterVllmRuntimeReceiptInput, + persistManagedClusterVllmRuntimeReceipt, +} from "./managed-cluster-runtime-receipt.js"; +import type { ManagedClusterTopologyOutput } from "./managed-cluster-topology.js"; import { assertNoManagedDistributedVllmRuntimeReceipts } from "./managed-runtime-receipts.js"; import { resolveManagedInferenceServing } from "./resolver.js"; -import { - type PersistDualSparkVllmRuntimeReceiptInput, - persistDualSparkVllmRuntimeReceipt, -} from "./spark-runtime-receipt.js"; -export interface DualSparkInstallerOptions { +export interface ManagedClusterInstallerOptions { readonly env?: NodeJS.ProcessEnv; readonly nonInteractive: boolean; readonly platform: VllmProfile["platform"]; @@ -54,7 +54,7 @@ export interface DualSparkInstallerOptions { readonly beforeInstall?: (modelId: string) => void; } -export interface DualSparkInstallerEffects { +export interface ManagedClusterInstallerEffects { readonly prerequisites: () => { ok: boolean; reason?: string }; readonly pullImage: ( profile: VllmProfile, @@ -69,22 +69,22 @@ export interface DualSparkInstallerEffects { readonly printDownloadAuthentication: (nonInteractive: boolean) => void; } -export type DualSparkInstallerResult = +export type ManagedClusterInstallerResult = | { readonly kind: "not-selected" } | { readonly kind: "handled"; readonly result: { readonly ok: boolean } }; -interface DualSparkInstallerDeps { - readonly probeCapability: typeof probeDualSparkManagedServingCapability; - readonly revalidateCapability: typeof revalidateDualSparkManagedServingCapability; - readonly claimCapability: typeof claimDualSparkManagedServingCapability; +interface ManagedClusterInstallerDeps { + readonly probeCapability: typeof probeManagedClusterManagedServingCapability; + readonly revalidateCapability: typeof revalidateManagedClusterManagedServingCapability; + readonly claimCapability: typeof claimManagedClusterManagedServingCapability; readonly resolveSelection: ( - input: ManagedInferenceResolverInput, - ) => ManagedInferenceResolution; - readonly materializePlan: typeof materializeDualSparkVllmPlan; - readonly createExecutor: typeof createDualSparkVllmExecutor; - readonly start: typeof startAutomaticDualSparkVllm; - readonly cleanup: typeof cleanupDualSparkManagedVllm; - readonly persistReceipt: typeof persistDualSparkVllmRuntimeReceipt; + input: ManagedInferenceResolverInput, + ) => ManagedInferenceResolution; + readonly materializePlan: typeof materializeManagedClusterVllmPlan; + readonly createExecutor: typeof createManagedClusterVllmExecutor; + readonly start: typeof startAutomaticManagedClusterVllm; + readonly cleanup: typeof cleanupManagedClusterManagedVllm; + readonly persistReceipt: typeof persistManagedClusterVllmRuntimeReceipt; readonly ensureApiKey: typeof ensureManagedVllmApiKey; readonly assertNoRuntimeReceipts: typeof assertNoManagedDistributedVllmRuntimeReceipts; readonly clearBinding: typeof clearDualStationSshBinding; @@ -94,16 +94,16 @@ interface DualSparkInstallerDeps { readonly warn: (line: string) => void; } -const DEFAULT_DEPS: DualSparkInstallerDeps = { - probeCapability: probeDualSparkManagedServingCapability, - revalidateCapability: revalidateDualSparkManagedServingCapability, - claimCapability: claimDualSparkManagedServingCapability, +const DEFAULT_DEPS: ManagedClusterInstallerDeps = { + probeCapability: probeManagedClusterManagedServingCapability, + revalidateCapability: revalidateManagedClusterManagedServingCapability, + claimCapability: claimManagedClusterManagedServingCapability, resolveSelection: resolveManagedInferenceServing, - materializePlan: materializeDualSparkVllmPlan, - createExecutor: createDualSparkVllmExecutor, - start: startAutomaticDualSparkVllm, - cleanup: cleanupDualSparkManagedVllm, - persistReceipt: persistDualSparkVllmRuntimeReceipt, + materializePlan: materializeManagedClusterVllmPlan, + createExecutor: createManagedClusterVllmExecutor, + start: startAutomaticManagedClusterVllm, + cleanup: cleanupManagedClusterManagedVllm, + persistReceipt: persistManagedClusterVllmRuntimeReceipt, ensureApiKey: ensureManagedVllmApiKey, assertNoRuntimeReceipts: assertNoManagedDistributedVllmRuntimeReceipts, clearBinding: clearDualStationSshBinding, @@ -137,13 +137,13 @@ function recipeApiPort(recipe: ManagedInferenceServingRecipe): number | null { } function selectedHostStorageFailure( - host: DualSparkHostObservation, + host: ManagedClusterHostObservation, label: string, recipe: ManagedInferenceServingRecipe, ): SelectedRecipeAdmissionFailure | null { const requirements = new Map(); const available = new Map(); - const add = (capacity: DualSparkStorageCapacityObservation, required: bigint): boolean => { + const add = (capacity: ManagedClusterStorageCapacityObservation, required: bigint): boolean => { if (capacity.filesystemId === null || capacity.availableBytes === null) return false; requirements.set( capacity.filesystemId, @@ -182,19 +182,17 @@ function selectedHostStorageFailure( } function selectedRecipeAdmissionFailure( - capability: DualSparkDetectedManagedServingCapability, + capability: ManagedClusterDetectedManagedServingCapability, recipe: ManagedInferenceServingRecipe, ): SelectedRecipeAdmissionFailure | null { const apiPort = recipeApiPort(recipe); if (apiPort === null) { return { code: "runtime-unknown", reason: "The selected recipe serving port is invalid." }; } - for (const [host, label] of [ - [capability.local, "Local DGX Spark"], - [capability.peer, "Peer DGX Spark"], - ] as const) { + for (const [index, host] of [capability.local, ...capability.peers].entries()) { + const label = index === 0 ? "Local DGX Spark" : `Managed cluster peer ${String(index)}`; const occupied = host.runtimeSnapshot.listeningPorts.find( - (port) => port === apiPort || port === DUAL_SPARK_VLLM_MASTER_PORT, + (port) => port === apiPort || port === recipe.spec.execution.rendezvousPort, ); if (occupied !== undefined) { return { @@ -227,32 +225,33 @@ function requiredPositiveIntegerArgument( } function managedProfile( - plan: DualSparkVllmPlan, + plan: ManagedClusterVllmPlan, recipe: ManagedInferenceServingRecipe, ): VllmProfile { + const head = managedClusterHeadRole(plan); return { name: recipe.metadata.displayName, platform: "spark", - image: plan.roles.head.image, - imageDownloadSizeBytes: plan.roles.head.runtime.imageDownloadSizeBytes, + image: head.image, + imageDownloadSizeBytes: head.runtime.imageDownloadSizeBytes, defaultModel: managedModel(plan, recipe), - containerName: plan.roles.head.containerName, + containerName: head.containerName, dockerRunFlags: [], pullTimeoutSec: recipe.spec.runtime.pullTimeoutSeconds, loadTimeoutSec: Math.ceil(plan.readiness.timeoutMs / 1000), - modelDownloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + modelDownloadSizeBytes: head.preparation.modelDownloadSizeBytes, }; } function managedModel( - plan: DualSparkVllmPlan, + plan: ManagedClusterVllmPlan, recipe: ManagedInferenceServingRecipe, ): VllmModelDef { return { id: plan.model.id, label: recipe.metadata.displayName, envValue: plan.model.servedName, - downloadSizeBytes: plan.roles.head.preparation.modelDownloadSizeBytes, + downloadSizeBytes: managedClusterHeadRole(plan).preparation.modelDownloadSizeBytes, maxModelLen: requiredPositiveIntegerArgument(recipe, "--max-model-len"), revision: plan.model.revision, servedModelId: plan.model.servedName, @@ -275,54 +274,65 @@ function selectionIntent(env: NodeJS.ProcessEnv) { } function automaticIntentDefersToLegacy(env: NodeJS.ProcessEnv): boolean { - const pairIntent = - String(env[NEMOCLAW_DGX_SPARK_PEER_ENV] ?? "").trim() || + const clusterIntent = + String(env[NEMOCLAW_MANAGED_CLUSTER_PEERS_ENV] ?? "").trim() || String(env[NEMOCLAW_SERVING_PRESET_ENV] ?? "").trim(); - if (pairIntent) return false; + if (clusterIntent) return false; return Boolean( String(env.NEMOCLAW_VLLM_MODEL ?? "").trim() || String(env[VLLM_EXTRA_ARGS_ENV] ?? "").trim(), ); } function printSummary( - capability: DualSparkDetectedManagedServingCapability, - plan: DualSparkVllmPlan, - deps: DualSparkInstallerDeps, + capability: ManagedClusterDetectedManagedServingCapability, + plan: ManagedClusterVllmPlan, + deps: ManagedClusterInstallerDeps, ): void { const rails = capability.topology.output.rails - .map( - ({ head, worker }) => - `${head.address}/${String(head.prefixLength)} to ${worker.address}/${String(worker.prefixLength)}`, + .map(({ endpoints }) => + endpoints + .map(({ address, prefixLength }) => `${address}/${String(prefixLength)}`) + .join(" to "), ) .join(", "); + const head = managedClusterHeadRole(plan); deps.log(); - deps.log(" vLLM (two DGX Sparks, experimental):"); + deps.log(` vLLM (${String(plan.roles.length)}-node DGX Spark cluster, experimental):`); deps.log(` Serving profile: ${plan.presetId}`); deps.log(` Recipe: ${plan.recipeId}`); - deps.log(` Image: ${plan.roles.head.image}`); + deps.log(` Image: ${head.image}`); deps.log(` Model: ${plan.model.id}@${plan.model.revision}`); deps.log(` Served model: ${plan.model.servedName}`); - deps.log(` Topology: ${capability.local.hostname} + ${capability.peer.hostname}`); + deps.log( + ` Topology: ${[capability.local, ...capability.peers] + .map(({ hostname }) => hostname) + .join(" + ")}`, + ); deps.log(` Direct rails: ${rails}`); deps.log( ` RoCEv2 GIDs: ${capability.topology.output.rails - .map(({ head, worker }) => `${String(head.roceGid.index)}/${String(worker.roceGid.index)}`) + .map(({ endpoints }) => endpoints.map(({ roceGid }) => String(roceGid.index)).join("/")) .join(", ")}`, ); deps.log( - ` Model caches: ${capability.local.storage.huggingFace.cacheRoot}, ${capability.peer.storage.huggingFace.cacheRoot}`, + ` Model caches: ${[capability.local, ...capability.peers] + .map(({ storage }) => storage.huggingFace.cacheRoot) + .join(", ")}`, ); - deps.log(" Launch order: worker first, then head"); - deps.log(" Restart policy: none; a stopped pair requires explicit cleanup"); - deps.log(" Experimental: physical two-node end-to-end validation is pending"); + deps.log(" Launch order: descending worker ranks, then head"); + deps.log(" Restart policy: none; a stopped cluster requires explicit cleanup"); + deps.log(" Experimental: physical end-to-end validation is pending"); } function resolutionFailure( - resolution: Exclude, { outcome: "selected" }>, - selectionIntent: DualSparkDetectedManagedServingCapability["selectionIntent"], + resolution: Exclude< + ManagedInferenceResolution, + { outcome: "selected" } + >, + selectionIntent: ManagedClusterDetectedManagedServingCapability["selectionIntent"], allowAutomaticFallback: boolean, - deps: DualSparkInstallerDeps, -): DualSparkInstallerResult { + deps: ManagedClusterInstallerDeps, +): ManagedClusterInstallerResult { if ( allowAutomaticFallback && selectionIntent === "automatic" && @@ -330,16 +340,16 @@ function resolutionFailure( ) { return { kind: "not-selected" }; } - deps.error(` Two-Spark managed vLLM setup unavailable: ${resolution.message}`); + deps.error(` Managed-cluster vLLM setup unavailable: ${resolution.message}`); return { kind: "handled", result: { ok: false } }; } function admissionFailure( failure: SelectedRecipeAdmissionFailure, - selectionIntent: DualSparkDetectedManagedServingCapability["selectionIntent"], + selectionIntent: ManagedClusterDetectedManagedServingCapability["selectionIntent"], allowAutomaticFallback: boolean, - deps: DualSparkInstallerDeps, -): DualSparkInstallerResult { + deps: ManagedClusterInstallerDeps, +): ManagedClusterInstallerResult { if ( allowAutomaticFallback && selectionIntent === "automatic" && @@ -347,32 +357,43 @@ function admissionFailure( ) { return { kind: "not-selected" }; } - deps.error(` Two-Spark managed vLLM setup stopped: ${failure.reason}`); + deps.error(` Managed-cluster vLLM setup stopped: ${failure.reason}`); return { kind: "handled", result: { ok: false } }; } function receiptInput( - capability: DualSparkConfirmedManagedServingCapability, - plan: DualSparkVllmPlan, - started: Extract, -): PersistDualSparkVllmRuntimeReceiptInput { + capability: ManagedClusterConfirmedManagedServingCapability, + plan: ManagedClusterVllmPlan, + started: Extract, +): PersistManagedClusterVllmRuntimeReceiptInput { + const hosts = new Map( + [capability.local, ...capability.peers].map((host) => [host.nodeId, host] as const), + ); return { plan, - peerSshBinding: capability.peerSshBinding, - localCacheRoot: capability.local.storage.huggingFace.cacheRoot, - peerCacheRoot: capability.peer.storage.huggingFace.cacheRoot, apiKeyFingerprint: started.apiKeyFingerprint, - headContainerId: started.headContainerId, - workerContainerId: started.workerContainerId, + nodes: plan.roles.map((rolePlan) => { + const host = hosts.get(rolePlan.nodeId)!; + const owned = started.containers.find(({ nodeId }) => nodeId === rolePlan.nodeId)!; + const transport = capability.sshBindings.find(({ nodeId }) => nodeId === rolePlan.nodeId); + return { + nodeId: rolePlan.nodeId, + cacheRoot: host.storage.huggingFace.cacheRoot, + containerId: owned.containerId, + ...(transport + ? { sshBinding: transport.binding, discoveryStatePath: transport.statePath } + : {}), + }; + }), }; } -/** Select and run the automatic two-Spark profile without changing the legacy Spark path. */ -export async function tryInstallDualSparkManagedVllm( - options: DualSparkInstallerOptions, - effects: DualSparkInstallerEffects, - overrides: Partial = {}, -): Promise { +/** Select and run the automatic managed cluster profile without changing the legacy DGX Spark path. */ +export async function tryInstallManagedClusterManagedVllm( + options: ManagedClusterInstallerOptions, + effects: ManagedClusterInstallerEffects, + overrides: Partial = {}, +): Promise { if (options.platform !== "spark") return { kind: "not-selected" }; const env = options.env ?? process.env; const deferToLegacy = automaticIntentDefersToLegacy(env); @@ -390,14 +411,14 @@ export async function tryInstallDualSparkManagedVllm( return { kind: "not-selected" }; } if (detected.kind !== "ready") { - deps.error(` Two-Spark managed vLLM setup stopped: ${detected.reason}`); + deps.error(` Managed-cluster vLLM setup stopped: ${detected.reason}`); return { kind: "handled", result: { ok: false } }; } - let confirmedBinding: DualSparkConfirmedManagedServingCapability | null = null; + let confirmedBinding: ManagedClusterConfirmedManagedServingCapability | null = null; let retainBinding = false; try { - // Explicit legacy model/argument intent keeps the single-Spark path, but + // Explicit legacy model/argument intent keeps the single-host DGX Spark path, but // only after read-only discovery has proved that doing so will not overlap // a related distributed runtime or ambiguous binding. if (deferToLegacy) return { kind: "not-selected" }; @@ -415,17 +436,17 @@ export async function tryInstallDualSparkManagedVllm( return admissionFailure(previewAdmission, detected.selectionIntent, true, deps); } - let previewPlan: DualSparkVllmPlan; + let previewPlan: ManagedClusterVllmPlan; try { previewPlan = deps.materializePlan(previewResolution); } catch (error) { - deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + deps.error(` Managed-cluster vLLM setup stopped: ${(error as Error).message}`); return { kind: "handled", result: { ok: false } }; } try { deps.assertGatedModelAccess(managedModel(previewPlan, previewResolution.recipe), env); } catch (error) { - deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + deps.error(` Managed-cluster vLLM setup stopped: ${(error as Error).message}`); return { kind: "handled", result: { ok: false } }; } printSummary(detected, previewPlan, deps); @@ -445,7 +466,7 @@ export async function tryInstallDualSparkManagedVllm( const revalidated = deps.revalidateCapability(detected, { env }); if (revalidated.kind !== "ready") { - deps.error(` Two-Spark managed vLLM setup stopped: ${revalidated.reason}`); + deps.error(` Managed-cluster vLLM setup stopped: ${revalidated.reason}`); return { kind: "handled", result: { ok: false } }; } @@ -468,13 +489,13 @@ export async function tryInstallDualSparkManagedVllm( revalidatedResolution.presetDigest !== previewResolution.presetDigest || revalidatedResolution.recipeDigest !== previewResolution.recipeDigest ) { - deps.error(" Two-Spark managed vLLM setup stopped: the selected profile changed."); + deps.error(" Managed-cluster vLLM setup stopped: the selected profile changed."); return { kind: "handled", result: { ok: false } }; } const confirmation = deps.claimCapability(revalidated); if (confirmation.kind !== "ready") { - deps.error(` Two-Spark managed vLLM setup stopped: ${confirmation.reason}`); + deps.error(` Managed-cluster vLLM setup stopped: ${confirmation.reason}`); return { kind: "handled", result: { ok: false } }; } confirmedBinding = confirmation; @@ -483,11 +504,11 @@ export async function tryInstallDualSparkManagedVllm( topologyQualification: confirmation.topology, }; - let plan: DualSparkVllmPlan; + let plan: ManagedClusterVllmPlan; try { plan = deps.materializePlan(resolution); } catch (error) { - deps.error(` Two-Spark managed vLLM setup stopped: ${(error as Error).message}`); + deps.error(` Managed-cluster vLLM setup stopped: ${(error as Error).message}`); return { kind: "handled", result: { ok: false } }; } if ( @@ -496,9 +517,10 @@ export async function tryInstallDualSparkManagedVllm( plan.model.id !== previewPlan.model.id || plan.model.revision !== previewPlan.model.revision || plan.model.servedName !== previewPlan.model.servedName || - plan.roles.head.image !== previewPlan.roles.head.image + plan.roles.length !== previewPlan.roles.length || + plan.roles.some((role, index) => role.image !== previewPlan.roles[index]?.image) ) { - deps.error(" Two-Spark managed vLLM setup stopped: the presented serving plan changed."); + deps.error(" Managed-cluster vLLM setup stopped: the presented serving plan changed."); return { kind: "handled", result: { ok: false } }; } @@ -520,12 +542,11 @@ export async function tryInstallDualSparkManagedVllm( return { kind: "handled", result: { ok: false } }; } - const hosts = { - head: confirmation.local, - worker: confirmation.peer, - } as const; - const stageNode: DualSparkExecutorStageNode = async (_request, target) => { - const host = hosts[target.role]; + const hosts = new Map( + [confirmation.local, ...confirmation.peers].map((host) => [host.nodeId, host] as const), + ); + const stageNode: ManagedClusterExecutorStageNode = async (_request, target) => { + const host = hosts.get(target.nodeId)!; deps.log(` ==> Staging pinned vLLM image and model on ${host.hostname}`); const pull = await effects.pullImage(profile, { ...target.dockerEnv }); if (!pull.ok) return pull; @@ -539,11 +560,17 @@ export async function tryInstallDualSparkManagedVllm( }, ); }; - const executorOptions: CreateDualSparkVllmExecutorOptions = { + const executorOptions: CreateManagedClusterVllmExecutorOptions = { plan, - peerSshBinding: confirmation.peerSshBinding, - localCacheRoot: confirmation.local.storage.huggingFace.cacheRoot, - peerCacheRoot: confirmation.peer.storage.huggingFace.cacheRoot, + nodes: plan.roles.map((rolePlan) => { + const host = hosts.get(rolePlan.nodeId)!; + const binding = confirmation.sshBindings.find(({ nodeId }) => nodeId === rolePlan.nodeId); + return { + nodeId: rolePlan.nodeId, + modelCacheRoot: host.storage.huggingFace.cacheRoot, + ...(binding ? { sshBinding: binding.binding } : {}), + }; + }), stageNode, }; const executor = deps.createExecutor(executorOptions); @@ -563,7 +590,7 @@ export async function tryInstallDualSparkManagedVllm( } catch (error) { if (!started.reusedExisting) { const cleanup = await deps.cleanup(plan, apiKey, executor); - const expected = new Set([started.headContainerId, started.workerContainerId]); + const expected = new Set(started.containers.map(({ containerId }) => containerId)); if ( cleanup.ok && cleanup.removedContainerIds.length === expected.size && @@ -573,33 +600,41 @@ export async function tryInstallDualSparkManagedVllm( retainBinding = false; } else { deps.warn( - ` vLLM rollback warning: ${cleanup.ok ? "exact pair cleanup was incomplete" : cleanup.reason}`, + ` vLLM rollback warning: ${cleanup.ok ? "exact cluster cleanup was incomplete" : cleanup.reason}`, ); } } deps.error( - ` vLLM install failed: could not persist managed two-Spark cleanup ownership: ${(error as Error).message}`, + ` vLLM install failed: could not persist managed cluster cleanup ownership: ${(error as Error).message}`, ); return { kind: "handled", result: { ok: false } }; } - deps.log(` ✓ vLLM ready across two DGX Sparks at ${started.baseUrl}`); + deps.log( + ` ✓ vLLM ready across ${String(plan.roles.length)} DGX Spark systems at ${started.baseUrl}`, + ); return { kind: "handled", result: { ok: true } }; } catch (error) { - deps.error(` Two-Spark managed vLLM setup failed closed: ${(error as Error).message}`); + deps.error(` Managed-cluster vLLM setup failed closed: ${(error as Error).message}`); return { kind: "handled", result: { ok: false } }; } finally { if (confirmedBinding && retainBinding) { deps.warn( - ` vLLM rollback warning: retained two-Spark SSH ownership state at ${confirmedBinding.peerSshBindingStatePath} because exact container rollback is incomplete. Resolve the related runtime state before retrying setup or uninstall.`, + ` vLLM rollback warning: retained managed cluster SSH ownership state at ${confirmedBinding.sshBindings + .map(({ statePath }) => statePath) + .join( + ", ", + )} because exact container rollback is incomplete. Resolve the related runtime state before retrying setup or uninstall.`, ); } else if (confirmedBinding) { - try { - deps.clearBinding(confirmedBinding.peerSshBindingStatePath); - } catch (error) { - deps.warn( - ` vLLM cleanup warning: temporary two-Spark SSH state could not be retired: ${(error as Error).message}`, - ); + for (const { statePath } of confirmedBinding.sshBindings) { + try { + deps.clearBinding(statePath); + } catch (error) { + deps.warn( + ` vLLM cleanup warning: temporary managed cluster SSH state could not be retired: ${(error as Error).message}`, + ); + } } } } diff --git a/src/lib/inference/serving/dual-spark-lifecycle.test.ts b/src/lib/inference/serving/managed-cluster-lifecycle.test.ts similarity index 73% rename from src/lib/inference/serving/dual-spark-lifecycle.test.ts rename to src/lib/inference/serving/managed-cluster-lifecycle.test.ts index c3b7cbd64ef..b70b0522aa5 100644 --- a/src/lib/inference/serving/dual-spark-lifecycle.test.ts +++ b/src/lib/inference/serving/managed-cluster-lifecycle.test.ts @@ -3,25 +3,25 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { fixtureDualSparkPlan } from "./dual-spark-fixture.test-support.js"; +import { fixtureManagedClusterPlan } from "./managed-cluster-fixture.test-support.js"; import { - classifyDualSparkExistingState, - cleanupDualSparkManagedVllm, - type DualSparkContainerStartRequest, - type DualSparkNodeSnapshot, - type DualSparkObservedContainer, - type DualSparkVllmLifecycleDeps, - dualSparkVllmApiKeyFingerprint, - startAutomaticDualSparkVllm, -} from "./dual-spark-lifecycle.js"; + classifyManagedClusterExistingState, + cleanupManagedClusterManagedVllm, + type ManagedClusterContainerStartRequest, + type ManagedClusterNodeSnapshot, + type ManagedClusterObservedContainer, + type ManagedClusterVllmLifecycleDeps, + managedClusterVllmApiKeyFingerprint, + startAutomaticManagedClusterVllm, +} from "./managed-cluster-lifecycle.js"; import { - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_MANAGED_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, - type DualSparkVllmPlan, - type DualSparkVllmRole, - type DualSparkVllmRolePlan, -} from "./dual-spark-materialize.js"; + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_MANAGED_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, + type ManagedClusterVllmPlan, + type ManagedClusterVllmRole, + type ManagedClusterVllmRolePlan, +} from "./managed-cluster-materialize.js"; const API_KEY = "a".repeat(64); const TRANSACTION_ID = "b".repeat(32); @@ -52,18 +52,18 @@ const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixtur signal: "managed label", name: "foreign-inference", image: "example.invalid/inference:latest", - labels: { [DUAL_SPARK_MANAGED_LABEL]: "foreign" }, + labels: { [MANAGED_CLUSTER_MANAGED_LABEL]: "foreign" }, }, ]; type Harness = ReturnType; function managedContainer( - plan: DualSparkVllmPlan, - role: DualSparkVllmRole, - overrides: Partial = {}, -): DualSparkObservedContainer { - const rolePlan = plan.roles[role]; + plan: ManagedClusterVllmPlan, + role: ManagedClusterVllmRole, + overrides: Partial = {}, +): ManagedClusterObservedContainer { + const rolePlan = plan.roles.find((candidate) => candidate.role === role)!; return { id: role === "head" ? HEAD_ID : WORKER_ID, name: rolePlan.containerName, @@ -72,28 +72,38 @@ function managedContainer( healthy: true, labels: { ...rolePlan.baseLabels, - [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: dualSparkVllmApiKeyFingerprint(API_KEY), - [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + [MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL]: managedClusterVllmApiKeyFingerprint(API_KEY), + [MANAGED_CLUSTER_TRANSACTION_LABEL]: TRANSACTION_ID, }, ...overrides, }; } -function createHarness(plan: DualSparkVllmPlan) { +function classifiedSnapshots( + plan: ManagedClusterVllmPlan, + snapshots: Record, +) { + return plan.roles.map((rolePlan) => ({ + nodeId: rolePlan.nodeId, + snapshot: snapshots[rolePlan.role], + })); +} + +function createHarness(plan: ManagedClusterVllmPlan) { const events: string[] = []; - const snapshots: Record = { + const snapshots: Record = { head: { containers: [], listeningPorts: [] }, worker: { containers: [], listeningPorts: [] }, }; - const inspectNode = vi.fn(async (rolePlan: DualSparkVllmRolePlan) => { + const inspectNode = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan) => { events.push(`inspect:${rolePlan.role}`); return snapshots[rolePlan.role]; }); - const stageNode = vi.fn(async ({ rolePlan }: { rolePlan: DualSparkVllmRolePlan }) => { + const stageNode = vi.fn(async ({ rolePlan }: { rolePlan: ManagedClusterVllmRolePlan }) => { events.push(`stage:${rolePlan.role}`); return { ok: true }; }); - const startContainer = vi.fn(async (request: DualSparkContainerStartRequest) => { + const startContainer = vi.fn(async (request: ManagedClusterContainerStartRequest) => { const { rolePlan, labels } = request; events.push(`start:${rolePlan.role}`); const id = rolePlan.role === "head" ? HEAD_ID : WORKER_ID; @@ -120,7 +130,7 @@ function createHarness(plan: DualSparkVllmPlan) { events.push(`distributed:${request.rolePlan.role}`); return true; }); - const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + const removeContainer = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan, id: string) => { events.push(`remove:${rolePlan.role}:${id}`); snapshots[rolePlan.role] = { ...snapshots[rolePlan.role], @@ -136,7 +146,7 @@ function createHarness(plan: DualSparkVllmPlan) { events.push("probe:chat"); return true; }); - const deps: DualSparkVllmLifecycleDeps = { + const deps: ManagedClusterVllmLifecycleDeps = { inspectNode, stageNode, startContainer, @@ -161,17 +171,17 @@ function createHarness(plan: DualSparkVllmPlan) { }; } -describe("automatic dual-DGX-Spark vLLM lifecycle", () => { - let plan: DualSparkVllmPlan; +describe("automatic managed-cluster vLLM lifecycle", () => { + let plan: ManagedClusterVllmPlan; let harness: Harness; beforeEach(() => { - plan = fixtureDualSparkPlan(); + plan = fixtureManagedClusterPlan(); harness = createHarness(plan); }); it("inspects both nodes before staging either node", async () => { - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result.ok).toBe(true); const firstStage = harness.events.findIndex((event) => event.startsWith("stage:")); @@ -195,7 +205,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { listeningPorts: [], }; - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "conflict" }); expect(harness.stageNode).not.toHaveBeenCalled(); @@ -220,7 +230,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { listeningPorts: [], }; - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "conflict" }); expect(harness.stageNode).not.toHaveBeenCalled(); @@ -247,11 +257,15 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { }; expect( - classifyDualSparkExistingState(plan, dualSparkVllmApiKeyFingerprint(API_KEY), snapshots), + classifyManagedClusterExistingState( + plan, + managedClusterVllmApiKeyFingerprint(API_KEY), + classifiedSnapshots(plan, snapshots), + ), ).toEqual({ outcome: "clear" }); }); - it("reuses only one exact healthy pair with the same transaction", async () => { + it("reuses only one exact healthy cluster with the same transaction", async () => { harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [8000], @@ -261,13 +275,15 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { listeningPorts: [25000], }; - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: true, reusedExisting: true, - headContainerId: HEAD_ID, - workerContainerId: WORKER_ID, + containers: [ + { nodeId: plan.roles[0].nodeId, containerId: HEAD_ID }, + { nodeId: plan.roles[1].nodeId, containerId: WORKER_ID }, + ], }); expect(harness.probeModels).toHaveBeenCalledOnce(); expect(harness.probeChat).toHaveBeenCalledOnce(); @@ -285,7 +301,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { listeningPorts: [], }; - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "conflict" }); expect(harness.startContainer).not.toHaveBeenCalled(); @@ -293,7 +309,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { }); it("starts and prepares rank 1 before rank 0 without exposing its API key", async () => { - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result.ok).toBe(true); expect(harness.events.indexOf("start:worker")).toBeLessThan( @@ -330,12 +346,12 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { throw new Error("Docker create outcome was ambiguous"); }); - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "start-failed" }); const failed = result as Extract; expect(failed.rollbackErrors).toContain( - "dual-Spark post-failure runtime state could not be proven clear; SSH ownership state was retained", + "managed cluster post-failure runtime state could not be proven clear; SSH ownership state was retained", ); expect(harness.removeContainer).not.toHaveBeenCalled(); }); @@ -345,7 +361,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { throw new Error("Docker create failed before mutation"); }); - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, @@ -360,7 +376,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { return false; }); - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, @@ -382,7 +398,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { ...worker, labels: { ...worker.labels, - [DUAL_SPARK_TRANSACTION_LABEL]: "c".repeat(32), + [MANAGED_CLUSTER_TRANSACTION_LABEL]: "c".repeat(32), }, }, ], @@ -390,7 +406,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { return false; }); - const result = await startAutomaticDualSparkVllm(plan, API_KEY, harness.deps); + const result = await startAutomaticManagedClusterVllm(plan, API_KEY, harness.deps); expect(result).toMatchObject({ ok: false, code: "health-failed" }); const failed = result as Extract; @@ -403,17 +419,21 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { it("classifies port conflicts on either node as nonselectable", () => { expect( - classifyDualSparkExistingState(plan, dualSparkVllmApiKeyFingerprint(API_KEY), { - head: { containers: [], listeningPorts: [] }, - worker: { containers: [], listeningPorts: [25000] }, - }), + classifyManagedClusterExistingState( + plan, + managedClusterVllmApiKeyFingerprint(API_KEY), + classifiedSnapshots(plan, { + head: { containers: [], listeningPorts: [] }, + worker: { containers: [], listeningPorts: [25000] }, + }), + ), ).toEqual({ outcome: "conflict", - reason: "worker port 25000 is already in use", + reason: `${plan.roles[1].nodeId} port 25000 is already in use`, }); }); - it("cleans up only a complete exact pair and retains all cache state", async () => { + it("cleans up only a complete exact cluster and retains all cache state", async () => { harness.snapshots.head = { containers: [managedContainer(plan, "head")], listeningPorts: [], @@ -423,7 +443,7 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { listeningPorts: [], }; - const result = await cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps); + const result = await cleanupManagedClusterManagedVllm(plan, API_KEY, harness.deps); expect(result).toEqual({ ok: true, @@ -459,19 +479,21 @@ describe("automatic dual-DGX-Spark vLLM lifecycle", () => { : removeOwnedContainer(); }); const ownership = { - headContainerId: HEAD_ID, - workerContainerId: WORKER_ID, + containers: [ + { nodeId: plan.roles[0].nodeId, containerId: HEAD_ID }, + { nodeId: plan.roles[1].nodeId, containerId: WORKER_ID }, + ], }; await expect( - cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps, ownership), + cleanupManagedClusterManagedVllm(plan, API_KEY, harness.deps, ownership), ).resolves.toEqual({ ok: false, reason: "worker daemon unavailable", removedContainerIds: [HEAD_ID], }); await expect( - cleanupDualSparkManagedVllm(plan, API_KEY, harness.deps, ownership), + cleanupManagedClusterManagedVllm(plan, API_KEY, harness.deps, ownership), ).resolves.toEqual({ ok: true, removedContainerIds: [WORKER_ID], diff --git a/src/lib/inference/serving/dual-spark-lifecycle.ts b/src/lib/inference/serving/managed-cluster-lifecycle.ts similarity index 51% rename from src/lib/inference/serving/dual-spark-lifecycle.ts rename to src/lib/inference/serving/managed-cluster-lifecycle.ts index 2afd09ea218..1a64139fe0f 100644 --- a/src/lib/inference/serving/dual-spark-lifecycle.ts +++ b/src/lib/inference/serving/managed-cluster-lifecycle.ts @@ -4,25 +4,25 @@ import { createHmac } from "node:crypto"; import { - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_MANAGED_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, - DUAL_SPARK_VLLM_PROJECT_ID, - type DualSparkVllmPlan, - type DualSparkVllmRolePlan, -} from "./dual-spark-materialize.js"; + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_MANAGED_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, + MANAGED_CLUSTER_VLLM_PROJECT_ID, + type ManagedClusterVllmPlan, + type ManagedClusterVllmRolePlan, +} from "./managed-cluster-materialize.js"; const API_KEY_PATTERN = /^[a-f0-9]{64}$/; const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/; const TRANSACTION_ID_PATTERN = /^[a-f0-9]{32}$/; -const FINGERPRINT_CONTEXT = "nemoclaw-dual-dgx-spark-vllm-api-key\0"; +const FINGERPRINT_CONTEXT = "nemoclaw-managed-cluster-vllm-api-key\0"; const STATION_CONTAINER_NAMES = new Set(["nemoclaw-vllm", "nemoclaw-vllm-worker"]); const STATION_LABEL_PREFIX = "com.nvidia.nemoclaw.vllm-"; const COMPOSE_PROJECT_LABEL = "com.docker.compose.project"; const COMPOSE_SERVICE_LABEL = "com.docker.compose.service"; const VLLM_TOKEN_PATTERN = /(?:^|[./:_-])vllm(?:$|[./:@_-])/i; -export interface DualSparkObservedContainer { +export interface ManagedClusterObservedContainer { readonly id: string; readonly name: string; readonly image: string; @@ -32,57 +32,56 @@ export interface DualSparkObservedContainer { readonly labels: Readonly>; } -export interface DualSparkNodeSnapshot { +export interface ManagedClusterNodeSnapshot { /** All containers visible to the node daemon, including stopped containers. */ - readonly containers: readonly DualSparkObservedContainer[]; - /** Host-network listeners. The executor must inspect both requested ports. */ + readonly containers: readonly ManagedClusterObservedContainer[]; + /** Host-network listeners. The executor must inspect all requested ports. */ readonly listeningPorts: readonly number[]; } -export type DualSparkExistingState = +export type ManagedClusterExistingState = | { readonly outcome: "clear" } | { readonly outcome: "reuse"; - readonly headContainerId: string; - readonly workerContainerId: string; + readonly containers: readonly ManagedClusterOwnedContainer[]; readonly transactionId: string; } | { readonly outcome: "conflict"; readonly reason: string } | { readonly outcome: "unknown"; readonly reason: string }; -export interface DualSparkStageRequest { - readonly rolePlan: DualSparkVllmRolePlan; +export interface ManagedClusterStageRequest { + readonly rolePlan: ManagedClusterVllmRolePlan; /** Verify or fetch only the pinned model snapshot and immutable image. */ - readonly preparation: DualSparkVllmRolePlan["preparation"]; + readonly preparation: ManagedClusterVllmRolePlan["preparation"]; } -export interface DualSparkContainerStartRequest { - readonly rolePlan: DualSparkVllmRolePlan; +export interface ManagedClusterContainerStartRequest { + readonly rolePlan: ManagedClusterVllmRolePlan; readonly labels: Readonly>; /** * The executor performs this code-owned preparation inside the newly * created container, then directly execs the role command. Copy/replace * operations must match exactly or creation fails before vLLM starts. */ - readonly preparation: DualSparkVllmRolePlan["preparation"]; + readonly preparation: ManagedClusterVllmRolePlan["preparation"]; /** Present only for the head. The executor must not persist it in labels or the plan. */ readonly bearerApiKey?: string; } -export interface DualSparkContainerStartResult { +export interface ManagedClusterContainerStartResult { readonly ok: boolean; readonly containerId?: string; readonly reason?: string; } -export interface DualSparkContainerWaitRequest { - readonly rolePlan: DualSparkVllmRolePlan; +export interface ManagedClusterContainerWaitRequest { + readonly rolePlan: ManagedClusterVllmRolePlan; readonly containerId: string; readonly expectedLabels: Readonly>; readonly timeoutMs: number; } -export interface DualSparkApiProbeRequest { +export interface ManagedClusterApiProbeRequest { readonly baseUrl: string; readonly apiKey: string; readonly expectedModel: string; @@ -94,32 +93,31 @@ export interface DualSparkApiProbeRequest { * binding in each worker role plan and performs Docker operations using argv, * never a caller-built command string. */ -export interface DualSparkVllmLifecycleDeps { - inspectNode(rolePlan: DualSparkVllmRolePlan): Promise; - stageNode(request: DualSparkStageRequest): Promise<{ ok: boolean; reason?: string }>; - startContainer(request: DualSparkContainerStartRequest): Promise; - waitForContainerReady(request: DualSparkContainerWaitRequest): Promise; - /** Prove the rank-1 process is alive and waiting at the distributed rendezvous. */ - waitForWorkerDistributedReady(request: DualSparkContainerWaitRequest): Promise; +export interface ManagedClusterVllmLifecycleDeps { + inspectNode(rolePlan: ManagedClusterVllmRolePlan): Promise; + stageNode(request: ManagedClusterStageRequest): Promise<{ ok: boolean; reason?: string }>; + startContainer( + request: ManagedClusterContainerStartRequest, + ): Promise; + waitForContainerReady(request: ManagedClusterContainerWaitRequest): Promise; + /** Prove a worker process is alive and waiting at the distributed rendezvous. */ + waitForWorkerDistributedReady(request: ManagedClusterContainerWaitRequest): Promise; removeContainer( - rolePlan: DualSparkVllmRolePlan, + rolePlan: ManagedClusterVllmRolePlan, exactContainerId: string, ): Promise<{ ok: boolean; reason?: string }>; - probeModels(request: DualSparkApiProbeRequest): Promise; - probeChat(request: DualSparkApiProbeRequest): Promise; + probeModels(request: ManagedClusterApiProbeRequest): Promise; + probeChat(request: ManagedClusterApiProbeRequest): Promise; createTransactionId(): string; - withLifecycleLock(plan: DualSparkVllmPlan, operation: () => Promise): Promise; + withLifecycleLock(plan: ManagedClusterVllmPlan, operation: () => Promise): Promise; } -export interface DualSparkRuntimeInspection { - readonly state: DualSparkExistingState; - readonly snapshots?: { - readonly head: DualSparkNodeSnapshot; - readonly worker: DualSparkNodeSnapshot; - }; +export interface ManagedClusterRuntimeInspection { + readonly state: ManagedClusterExistingState; + readonly snapshots?: readonly ManagedClusterRoleSnapshot[]; } -export type CleanupDualSparkVllmResult = +export type CleanupManagedClusterVllmResult = | { readonly ok: true; readonly removedContainerIds: readonly string[]; @@ -131,18 +129,26 @@ export type CleanupDualSparkVllmResult = readonly removedContainerIds: readonly string[]; }; -export interface DualSparkCleanupOwnership { - readonly headContainerId: string; - readonly workerContainerId: string; +export interface ManagedClusterCleanupOwnership { + readonly containers: readonly ManagedClusterOwnedContainer[]; +} + +export interface ManagedClusterOwnedContainer { + readonly nodeId: string; + readonly containerId: string; +} + +export interface ManagedClusterRoleSnapshot { + readonly nodeId: string; + readonly snapshot: ManagedClusterNodeSnapshot; } -export type StartDualSparkVllmResult = +export type StartManagedClusterVllmResult = | { readonly ok: true; readonly reusedExisting: boolean; readonly baseUrl: string; - readonly headContainerId: string; - readonly workerContainerId: string; + readonly containers: readonly ManagedClusterOwnedContainer[]; readonly apiKeyFingerprint: string; } | { @@ -153,13 +159,13 @@ export type StartDualSparkVllmResult = }; interface RoleObservation { - rolePlan: DualSparkVllmRolePlan; - container: DualSparkObservedContainer; + rolePlan: ManagedClusterVllmRolePlan; + container: ManagedClusterObservedContainer; expectedLabels: Readonly>; } interface CreatedContainer { - rolePlan: DualSparkVllmRolePlan; + rolePlan: ManagedClusterVllmRolePlan; containerId: string; expectedLabels: Readonly>; } @@ -172,18 +178,18 @@ function labelsMatch( } function exactRoleObservation( - snapshot: DualSparkNodeSnapshot, - rolePlan: DualSparkVllmRolePlan, + snapshot: ManagedClusterNodeSnapshot, + rolePlan: ManagedClusterVllmRolePlan, apiKeyFingerprint: string, ): RoleObservation | null { const matches = snapshot.containers.filter(({ name }) => name === rolePlan.containerName); if (matches.length !== 1) return null; const container = matches[0]!; - const transactionId = container.labels[DUAL_SPARK_TRANSACTION_LABEL] ?? ""; + const transactionId = container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL] ?? ""; const expectedLabels = { ...rolePlan.baseLabels, - [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, - [DUAL_SPARK_TRANSACTION_LABEL]: transactionId, + [MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, + [MANAGED_CLUSTER_TRANSACTION_LABEL]: transactionId, }; if ( !CONTAINER_ID_PATTERN.test(container.id) || @@ -197,18 +203,18 @@ function exactRoleObservation( } /** Recognize only containers that declare or visibly identify a vLLM runtime. */ -export function isRelatedManagedVllmContainer(container: DualSparkObservedContainer): boolean { +export function isRelatedManagedVllmContainer(container: ManagedClusterObservedContainer): boolean { if (STATION_CONTAINER_NAMES.has(container.name)) return true; if (VLLM_TOKEN_PATTERN.test(container.name) || VLLM_TOKEN_PATTERN.test(container.image)) { return true; } - if (Object.hasOwn(container.labels, DUAL_SPARK_MANAGED_LABEL)) return true; - if (container.labels[COMPOSE_PROJECT_LABEL] === DUAL_SPARK_VLLM_PROJECT_ID) return true; - if (container.labels[COMPOSE_SERVICE_LABEL] === "vllm-dspark") return true; + if (Object.hasOwn(container.labels, MANAGED_CLUSTER_MANAGED_LABEL)) return true; + if (container.labels[COMPOSE_PROJECT_LABEL] === MANAGED_CLUSTER_VLLM_PROJECT_ID) return true; + if (container.labels[COMPOSE_SERVICE_LABEL] === "vllm-cluster") return true; return Object.keys(container.labels).some((key) => key.startsWith(STATION_LABEL_PREFIX)); } -function invalidSnapshotReason(snapshot: DualSparkNodeSnapshot, node: string): string | null { +function invalidSnapshotReason(snapshot: ManagedClusterNodeSnapshot, node: string): string | null { if ( snapshot.listeningPorts.some((port) => !Number.isInteger(port) || port < 1 || port > 65_535) ) { @@ -222,168 +228,169 @@ function invalidSnapshotReason(snapshot: DualSparkNodeSnapshot, node: string): s } /** Pure, fail-closed classification shared by discovery and lifecycle preflight. */ -export function classifyDualSparkExistingState( - plan: DualSparkVllmPlan, +export function classifyManagedClusterExistingState( + plan: ManagedClusterVllmPlan, apiKeyFingerprint: string, - snapshots: { - readonly head: DualSparkNodeSnapshot; - readonly worker: DualSparkNodeSnapshot; - }, -): DualSparkExistingState { + snapshots: readonly ManagedClusterRoleSnapshot[], +): ManagedClusterExistingState { if (!/^[a-f0-9]{64}$/.test(apiKeyFingerprint)) { - return { outcome: "unknown", reason: "dual-Spark API key fingerprint is invalid" }; + return { outcome: "unknown", reason: "managed cluster API key fingerprint is invalid" }; } - for (const [node, snapshot] of [ - ["head", snapshots.head], - ["worker", snapshots.worker], - ] as const) { - const invalid = invalidSnapshotReason(snapshot, node); + if ( + snapshots.length !== plan.roles.length || + new Set(snapshots.map(({ nodeId }) => nodeId)).size !== snapshots.length || + snapshots.some(({ nodeId }) => !plan.roles.some((role) => role.nodeId === nodeId)) + ) { + return { outcome: "unknown", reason: "managed cluster node inspection is incomplete" }; + } + for (const { nodeId, snapshot } of snapshots) { + const invalid = invalidSnapshotReason(snapshot, nodeId); if (invalid) return { outcome: "unknown", reason: invalid }; } - const head = exactRoleObservation(snapshots.head, plan.roles.head, apiKeyFingerprint); - const worker = exactRoleObservation(snapshots.worker, plan.roles.worker, apiKeyFingerprint); - const allContainers = [...snapshots.head.containers, ...snapshots.worker.containers]; - const exactIds = new Set([head?.container.id, worker?.container.id].filter(Boolean)); + const observations = plan.roles.map((rolePlan) => { + const snapshot = snapshots.find(({ nodeId }) => nodeId === rolePlan.nodeId)!.snapshot; + return exactRoleObservation(snapshot, rolePlan, apiKeyFingerprint); + }); + const allContainers = snapshots.flatMap(({ snapshot }) => snapshot.containers); + const exactIds = new Set(observations.flatMap((entry) => (entry ? [entry.container.id] : []))); const unexpectedRelated = allContainers.find( (container) => isRelatedManagedVllmContainer(container) && !exactIds.has(container.id), ); if (unexpectedRelated) { return { outcome: "conflict", - reason: `existing related container ${unexpectedRelated.name} is not the exact managed pair`, + reason: `existing related container ${unexpectedRelated.name} is not part of the exact managed cluster`, }; } - if (head || worker) { - if (!head || !worker) { - return { outcome: "conflict", reason: "managed dual-Spark deployment is incomplete" }; + if (observations.some(Boolean)) { + if (observations.some((observation) => !observation)) { + return { outcome: "conflict", reason: "managed cluster deployment is incomplete" }; } - const headTransaction = head.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; - const workerTransaction = worker.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; - if (headTransaction !== workerTransaction) { - return { outcome: "conflict", reason: "managed dual-Spark transaction labels do not match" }; + const exact = observations as RoleObservation[]; + const transactions = new Set( + exact.map(({ container }) => container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL]), + ); + if (transactions.size !== 1) { + return { outcome: "conflict", reason: "managed cluster transaction labels do not match" }; } - if ( - !head.container.running || - !head.container.healthy || - !worker.container.running || - !worker.container.healthy - ) { + if (exact.some(({ container }) => !container.running || !container.healthy)) { return { outcome: "conflict", - reason: "managed dual-Spark deployment is stopped, incomplete, or unhealthy", + reason: "managed cluster deployment is stopped, incomplete, or unhealthy", }; } return { outcome: "reuse", - headContainerId: head.container.id, - workerContainerId: worker.container.id, - transactionId: headTransaction, + containers: exact.map(({ rolePlan, container }) => ({ + nodeId: rolePlan.nodeId, + containerId: container.id, + })), + transactionId: exact[0]!.container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL]!, }; } - const dedicatedNameExists = allContainers.some( - ({ name }) => - name === plan.roles.head.containerName || name === plan.roles.worker.containerName, - ); + const dedicatedNames = new Set(plan.roles.map(({ containerName }) => containerName)); + const dedicatedNameExists = allContainers.some(({ name }) => dedicatedNames.has(name)); if (dedicatedNameExists) { - return { outcome: "conflict", reason: "dual-Spark container name ownership is foreign" }; + return { outcome: "conflict", reason: "managed cluster container name ownership is foreign" }; } - for (const [node, snapshot] of [ - ["head", snapshots.head], - ["worker", snapshots.worker], - ] as const) { + for (const { nodeId, snapshot } of snapshots) { const occupied = snapshot.listeningPorts.find( (port) => port === plan.apiPort || port === plan.masterPort, ); if (occupied !== undefined) { - return { outcome: "conflict", reason: `${node} port ${String(occupied)} is already in use` }; + return { + outcome: "conflict", + reason: `${nodeId} port ${String(occupied)} is already in use`, + }; } } return { outcome: "clear" }; } /** Domain-separated non-secret ownership binding for the managed endpoint key. */ -export function dualSparkVllmApiKeyFingerprint(apiKey: string): string { +export function managedClusterVllmApiKeyFingerprint(apiKey: string): string { if (!API_KEY_PATTERN.test(apiKey)) { - throw new Error("Dual-Spark vLLM API key must be 64 lowercase hexadecimal characters."); + throw new Error("Managed cluster vLLM API key must be 64 lowercase hexadecimal characters."); } return createHmac("sha256", Buffer.from(apiKey, "hex")).update(FINGERPRINT_CONTEXT).digest("hex"); } -async function inspectBoth( - plan: DualSparkVllmPlan, - deps: Pick, -): Promise<{ head: DualSparkNodeSnapshot; worker: DualSparkNodeSnapshot } | null> { +async function inspectAll( + plan: ManagedClusterVllmPlan, + deps: Pick, +): Promise { try { - const [head, worker] = await Promise.all([ - deps.inspectNode(plan.roles.head), - deps.inspectNode(plan.roles.worker), - ]); - return { head, worker }; + return await Promise.all( + plan.roles.map(async (rolePlan) => ({ + nodeId: rolePlan.nodeId, + snapshot: await deps.inspectNode(rolePlan), + })), + ); } catch { return null; } } -/** Inspect both daemons before any image, cache, or container mutation. */ -export async function preflightDualSparkVllm( - plan: DualSparkVllmPlan, +/** Inspect every daemon before any image, cache, or container mutation. */ +export async function preflightManagedClusterVllm( + plan: ManagedClusterVllmPlan, apiKey: string, - deps: Pick, -): Promise { + deps: Pick, +): Promise { let fingerprint: string; try { - fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + fingerprint = managedClusterVllmApiKeyFingerprint(apiKey); } catch (error) { return { outcome: "unknown", reason: (error as Error).message }; } - const snapshots = await inspectBoth(plan, deps); + const snapshots = await inspectAll(plan, deps); return snapshots - ? classifyDualSparkExistingState(plan, fingerprint, snapshots) - : { outcome: "unknown", reason: "could not inspect both dual-Spark container daemons" }; + ? classifyManagedClusterExistingState(plan, fingerprint, snapshots) + : { outcome: "unknown", reason: "could not inspect every managed cluster container daemon" }; } /** Plan- and key-specific read-only inspection for installer/runtime recovery. */ -export async function inspectDualSparkManagedRuntime( - plan: DualSparkVllmPlan, +export async function inspectManagedClusterManagedRuntime( + plan: ManagedClusterVllmPlan, apiKey: string, - deps: Pick, -): Promise { + deps: Pick, +): Promise { let fingerprint: string; try { - fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + fingerprint = managedClusterVllmApiKeyFingerprint(apiKey); } catch (error) { return { state: { outcome: "unknown", reason: (error as Error).message } }; } - const snapshots = await inspectBoth(plan, deps); + const snapshots = await inspectAll(plan, deps); return snapshots - ? { state: classifyDualSparkExistingState(plan, fingerprint, snapshots), snapshots } + ? { state: classifyManagedClusterExistingState(plan, fingerprint, snapshots), snapshots } : { state: { outcome: "unknown", - reason: "could not inspect both dual-Spark container daemons", + reason: "could not inspect every managed cluster container daemon", }, }; } function labelsForStart( - rolePlan: DualSparkVllmRolePlan, + rolePlan: ManagedClusterVllmRolePlan, apiKeyFingerprint: string, transactionId: string, ): Readonly> { return { ...rolePlan.baseLabels, - [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, - [DUAL_SPARK_TRANSACTION_LABEL]: transactionId, + [MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL]: apiKeyFingerprint, + [MANAGED_CLUSTER_TRANSACTION_LABEL]: transactionId, }; } function exactCreatedContainer( - snapshot: DualSparkNodeSnapshot, + snapshot: ManagedClusterNodeSnapshot, created: CreatedContainer, -): DualSparkObservedContainer | null { +): ManagedClusterObservedContainer | null { const matches = snapshot.containers.filter(({ id }) => id === created.containerId); if (matches.length !== 1) return null; const container = matches[0]!; @@ -396,11 +403,11 @@ function exactCreatedContainer( async function rollbackCreated( created: readonly CreatedContainer[], - deps: DualSparkVllmLifecycleDeps, + deps: ManagedClusterVllmLifecycleDeps, ): Promise { const errors: string[] = []; for (const item of [...created].reverse()) { - let snapshot: DualSparkNodeSnapshot; + let snapshot: ManagedClusterNodeSnapshot; try { snapshot = await deps.inspectNode(item.rolePlan); } catch { @@ -424,38 +431,38 @@ async function rollbackCreated( } async function rollbackCreatedAndProveClear( - plan: DualSparkVllmPlan, + plan: ManagedClusterVllmPlan, apiKeyFingerprint: string, created: readonly CreatedContainer[], - deps: DualSparkVllmLifecycleDeps, + deps: ManagedClusterVllmLifecycleDeps, ): Promise { const rollbackErrors = await rollbackCreated(created, deps); - const snapshots = await inspectBoth(plan, deps); + const snapshots = await inspectAll(plan, deps); if ( snapshots && - classifyDualSparkExistingState(plan, apiKeyFingerprint, snapshots).outcome === "clear" + classifyManagedClusterExistingState(plan, apiKeyFingerprint, snapshots).outcome === "clear" ) { return []; } return [ ...rollbackErrors, - "dual-Spark post-failure runtime state could not be proven clear; SSH ownership state was retained", + "managed cluster post-failure runtime state could not be proven clear; SSH ownership state was retained", ]; } async function startRole( - rolePlan: DualSparkVllmRolePlan, + rolePlan: ManagedClusterVllmRolePlan, apiKey: string, apiKeyFingerprint: string, transactionId: string, timeoutMs: number, - deps: DualSparkVllmLifecycleDeps, + deps: ManagedClusterVllmLifecycleDeps, ): Promise< | { ok: true; created: CreatedContainer } | { ok: false; reason: string; created?: CreatedContainer } > { const expectedLabels = labelsForStart(rolePlan, apiKeyFingerprint, transactionId); - let started: DualSparkContainerStartResult; + let started: ManagedClusterContainerStartResult; try { started = await deps.startContainer({ rolePlan, @@ -499,7 +506,7 @@ async function startRole( if (!ready) return { ok: false, reason: `${rolePlan.role} container did not become ready`, created }; - let snapshot: DualSparkNodeSnapshot; + let snapshot: ManagedClusterNodeSnapshot; try { snapshot = await deps.inspectNode(rolePlan); } catch { @@ -517,19 +524,19 @@ async function startRole( } function failure( - code: Extract["code"], + code: Extract["code"], reason: string, rollbackErrors: readonly string[] = [], -): StartDualSparkVllmResult { +): StartManagedClusterVllmResult { return { ok: false, code, reason, rollbackErrors }; } async function probeManagedApi( - plan: DualSparkVllmPlan, + plan: ManagedClusterVllmPlan, apiKey: string, - deps: Pick, + deps: Pick, ): Promise { - const baseUrl = plan.roles.head.endpoint; + const baseUrl = plan.roles.find(({ rank }) => rank === 0)?.endpoint; if (!baseUrl) return false; const request = { baseUrl, @@ -545,35 +552,41 @@ async function probeManagedApi( } } -async function startNewPair( - plan: DualSparkVllmPlan, +async function startNewCluster( + plan: ManagedClusterVllmPlan, apiKey: string, apiKeyFingerprint: string, - deps: DualSparkVllmLifecycleDeps, -): Promise { + deps: ManagedClusterVllmLifecycleDeps, +): Promise { const staged = await Promise.all( - [plan.roles.worker, plan.roles.head].map(async (rolePlan) => { - try { - return await deps.stageNode({ rolePlan, preparation: rolePlan.preparation }); - } catch { - return { ok: false, reason: `${rolePlan.role} staging failed` }; - } - }), + [...plan.roles] + .sort((left, right) => right.rank - left.rank) + .map(async (rolePlan) => { + try { + return await deps.stageNode({ rolePlan, preparation: rolePlan.preparation }); + } catch { + return { ok: false, reason: `${rolePlan.role} staging failed` }; + } + }), ); const failedStage = staged.find((result) => !result.ok); if (failedStage) { - return failure("staging-failed", failedStage.reason ?? "dual-Spark staging failed"); + return failure("staging-failed", failedStage.reason ?? "managed cluster staging failed"); } - const afterStageSnapshots = await inspectBoth(plan, deps); + const afterStageSnapshots = await inspectAll(plan, deps); if (!afterStageSnapshots) { - return failure("unknown", "could not re-inspect both daemons after staging"); + return failure("unknown", "could not re-inspect every daemon after staging"); } - const afterStage = classifyDualSparkExistingState(plan, apiKeyFingerprint, afterStageSnapshots); + const afterStage = classifyManagedClusterExistingState( + plan, + apiKeyFingerprint, + afterStageSnapshots, + ); if (afterStage.outcome !== "clear") { return failure( afterStage.outcome === "unknown" ? "unknown" : "conflict", - `dual-Spark ownership changed during staging: ${ + `managed cluster ownership changed during staging: ${ "reason" in afterStage ? afterStage.reason : afterStage.outcome }`, ); @@ -581,77 +594,68 @@ async function startNewPair( const transactionId = deps.createTransactionId(); if (!TRANSACTION_ID_PATTERN.test(transactionId)) { - return failure("unknown", "dual-Spark lifecycle transaction ID is invalid"); + return failure("unknown", "managed cluster lifecycle transaction ID is invalid"); } const created: CreatedContainer[] = []; - const worker = await startRole( - plan.roles.worker, - apiKey, - apiKeyFingerprint, - transactionId, - plan.readiness.timeoutMs, - deps, - ); - if (!worker.ok) { - if (worker.created) created.push(worker.created); - return failure( - "start-failed", - worker.reason, - await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), - ); - } - created.push(worker.created); - - const head = await startRole( - plan.roles.head, - apiKey, - apiKeyFingerprint, - transactionId, - plan.readiness.timeoutMs, - deps, - ); - if (!head.ok) { - if (head.created) created.push(head.created); - return failure( - "start-failed", - head.reason, - await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + for (const rolePlan of [...plan.roles].sort((left, right) => right.rank - left.rank)) { + const result = await startRole( + rolePlan, + apiKey, + apiKeyFingerprint, + transactionId, + plan.readiness.timeoutMs, + deps, ); + if (!result.ok) { + if (result.created) created.push(result.created); + return failure( + "start-failed", + result.reason, + await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), + ); + } + created.push(result.created); } - created.push(head.created); if (!(await probeManagedApi(plan, apiKey, deps))) { return failure( "health-failed", - "dual-Spark models or chat health check failed", + "managed cluster models or chat health check failed", await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), ); } - const finalSnapshots = await inspectBoth(plan, deps); + const finalSnapshots = await inspectAll(plan, deps); const finalState = finalSnapshots - ? classifyDualSparkExistingState(plan, apiKeyFingerprint, finalSnapshots) + ? classifyManagedClusterExistingState(plan, apiKeyFingerprint, finalSnapshots) : null; if ( !finalState || finalState.outcome !== "reuse" || finalState.transactionId !== transactionId || - finalState.headContainerId !== head.created.containerId || - finalState.workerContainerId !== worker.created.containerId + finalState.containers.length !== created.length || + created.some( + ({ rolePlan, containerId }) => + !finalState.containers.some( + (owned) => owned.nodeId === rolePlan.nodeId && owned.containerId === containerId, + ), + ) ) { return failure( "health-failed", - "dual-Spark ownership changed before lifecycle commit", + "managed cluster ownership changed before lifecycle commit", await rollbackCreatedAndProveClear(plan, apiKeyFingerprint, created, deps), ); } return { ok: true, reusedExisting: false, - baseUrl: plan.roles.head.endpoint!, - headContainerId: head.created.containerId, - workerContainerId: worker.created.containerId, + baseUrl: plan.roles.find(({ rank }) => rank === 0)!.endpoint!, + containers: created.map(({ rolePlan, containerId }) => ({ + nodeId: rolePlan.nodeId, + containerId, + })), apiKeyFingerprint, }; } @@ -661,21 +665,21 @@ async function startNewPair( * Stopped, partial, mismatched, Station, singleton, and foreign deployments * are never repaired or replaced. */ -export async function startAutomaticDualSparkVllm( - plan: DualSparkVllmPlan, +export async function startAutomaticManagedClusterVllm( + plan: ManagedClusterVllmPlan, apiKey: string, - deps: DualSparkVllmLifecycleDeps, -): Promise { + deps: ManagedClusterVllmLifecycleDeps, +): Promise { let apiKeyFingerprint: string; try { - apiKeyFingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + apiKeyFingerprint = managedClusterVllmApiKeyFingerprint(apiKey); } catch (error) { return failure("unknown", (error as Error).message); } try { return await deps.withLifecycleLock(plan, async () => { - const preflight = await preflightDualSparkVllm(plan, apiKey, deps); + const preflight = await preflightManagedClusterVllm(plan, apiKey, deps); if (preflight.outcome === "unknown" || preflight.outcome === "conflict") { return failure(preflight.outcome, preflight.reason); } @@ -683,49 +687,53 @@ export async function startAutomaticDualSparkVllm( if (!(await probeManagedApi(plan, apiKey, deps))) { return failure( "conflict", - "existing managed dual-Spark API is unhealthy; no repair attempted", + "existing managed cluster API is unhealthy; no repair attempted", ); } return { ok: true, reusedExisting: true, - baseUrl: plan.roles.head.endpoint!, - headContainerId: preflight.headContainerId, - workerContainerId: preflight.workerContainerId, + baseUrl: plan.roles.find(({ rank }) => rank === 0)!.endpoint!, + containers: preflight.containers, apiKeyFingerprint, }; } - return await startNewPair(plan, apiKey, apiKeyFingerprint, deps); + return await startNewCluster(plan, apiKey, apiKeyFingerprint, deps); }); } catch (error) { - return failure("unknown", `dual-Spark lifecycle failed: ${(error as Error).message}`); + return failure("unknown", `managed cluster lifecycle failed: ${(error as Error).message}`); } } -function exactPairForCleanup( - plan: DualSparkVllmPlan, +function exactClusterForCleanup( + plan: ManagedClusterVllmPlan, apiKeyFingerprint: string, - snapshots: { readonly head: DualSparkNodeSnapshot; readonly worker: DualSparkNodeSnapshot }, -): { head: RoleObservation; worker: RoleObservation } | null { - const head = exactRoleObservation(snapshots.head, plan.roles.head, apiKeyFingerprint); - const worker = exactRoleObservation(snapshots.worker, plan.roles.worker, apiKeyFingerprint); - if (!head || !worker) return null; - const transactionId = head.container.labels[DUAL_SPARK_TRANSACTION_LABEL]; - if (!transactionId || transactionId !== worker.container.labels[DUAL_SPARK_TRANSACTION_LABEL]) { + snapshots: readonly ManagedClusterRoleSnapshot[], +): readonly RoleObservation[] | null { + const observations = plan.roles.map((rolePlan) => { + const snapshot = snapshots.find(({ nodeId }) => nodeId === rolePlan.nodeId)?.snapshot; + return snapshot ? exactRoleObservation(snapshot, rolePlan, apiKeyFingerprint) : null; + }); + if (observations.some((observation) => !observation)) return null; + const exact = observations as RoleObservation[]; + const transactions = new Set( + exact.map(({ container }) => container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL]), + ); + if (transactions.size !== 1 || !exact[0]?.container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL]) { return null; } - const exactIds = new Set([head.container.id, worker.container.id]); - const related = [...snapshots.head.containers, ...snapshots.worker.containers].find( - (container) => isRelatedManagedVllmContainer(container) && !exactIds.has(container.id), - ); - return related ? null : { head, worker }; + const exactIds = new Set(exact.map(({ container }) => container.id)); + const related = snapshots + .flatMap(({ snapshot }) => snapshot.containers) + .find((container) => isRelatedManagedVllmContainer(container) && !exactIds.has(container.id)); + return related ? null : exact; } function receiptOwnedTargetsForCleanup( - plan: DualSparkVllmPlan, + plan: ManagedClusterVllmPlan, apiKeyFingerprint: string, - snapshots: { readonly head: DualSparkNodeSnapshot; readonly worker: DualSparkNodeSnapshot }, - ownership: DualSparkCleanupOwnership, + snapshots: readonly ManagedClusterRoleSnapshot[], + ownership: ManagedClusterCleanupOwnership, ): | { readonly ok: true; @@ -733,22 +741,30 @@ function receiptOwnedTargetsForCleanup( readonly alreadyAbsentContainerIds: readonly string[]; } | { readonly ok: false; readonly reason: string } { - const expectedIds = [ownership.headContainerId, ownership.workerContainerId]; + const expectedIds = ownership.containers.map(({ containerId }) => containerId); if ( + ownership.containers.length !== plan.roles.length || expectedIds.some((id) => !CONTAINER_ID_PATTERN.test(id)) || - ownership.headContainerId === ownership.workerContainerId + new Set(expectedIds).size !== expectedIds.length || + new Set(ownership.containers.map(({ nodeId }) => nodeId)).size !== + ownership.containers.length || + ownership.containers.some(({ nodeId }) => !plan.roles.some((role) => role.nodeId === nodeId)) ) { - return { ok: false, reason: "dual-Spark cleanup receipt identities are invalid" }; + return { ok: false, reason: "managed cluster cleanup receipt identities are invalid" }; } const observations: RoleObservation[] = []; const alreadyAbsentContainerIds: string[] = []; let transactionId: string | null = null; - for (const [role, snapshot, expectedId] of [ - ["head", snapshots.head, ownership.headContainerId], - ["worker", snapshots.worker, ownership.workerContainerId], - ] as const) { - const invalid = invalidSnapshotReason(snapshot, role); + for (const rolePlan of plan.roles) { + const snapshot = snapshots.find(({ nodeId }) => nodeId === rolePlan.nodeId)?.snapshot; + const expectedId = ownership.containers.find( + ({ nodeId }) => nodeId === rolePlan.nodeId, + )?.containerId; + if (!snapshot || !expectedId) { + return { ok: false, reason: "managed cluster cleanup receipt is incomplete" }; + } + const invalid = invalidSnapshotReason(snapshot, rolePlan.nodeId); if (invalid) return { ok: false, reason: invalid }; const related = snapshot.containers.filter(isRelatedManagedVllmContainer); const expected = snapshot.containers.find(({ id }) => id === expectedId); @@ -756,23 +772,23 @@ function receiptOwnedTargetsForCleanup( if (related.length > 0) { return { ok: false, - reason: `${role} receipt-owned container is absent but related runtime state exists`, + reason: `${rolePlan.nodeId} receipt-owned container is absent but related runtime state exists`, }; } alreadyAbsentContainerIds.push(expectedId); continue; } - const observation = exactRoleObservation(snapshot, plan.roles[role], apiKeyFingerprint); + const observation = exactRoleObservation(snapshot, rolePlan, apiKeyFingerprint); if ( !observation || observation.container.id !== expectedId || related.some(({ id }) => id !== expectedId) ) { - return { ok: false, reason: `${role} receipt-owned container identity changed` }; + return { ok: false, reason: `${rolePlan.nodeId} receipt-owned container identity changed` }; } - const observedTransaction = observation.container.labels[DUAL_SPARK_TRANSACTION_LABEL]!; + const observedTransaction = observation.container.labels[MANAGED_CLUSTER_TRANSACTION_LABEL]!; if (transactionId !== null && transactionId !== observedTransaction) { - return { ok: false, reason: "dual-Spark receipt-owned transaction identity changed" }; + return { ok: false, reason: "managed cluster receipt-owned transaction identity changed" }; } transactionId = observedTransaction; observations.push(observation); @@ -780,26 +796,29 @@ function receiptOwnedTargetsForCleanup( return { ok: true, observations, alreadyAbsentContainerIds }; } -/** Remove only a complete, plan/key/transaction-owned pair. Model caches remain. */ -export async function cleanupDualSparkManagedVllm( - plan: DualSparkVllmPlan, +/** Remove only a complete, plan/key/transaction-owned cluster. Model caches remain. */ +export async function cleanupManagedClusterManagedVllm( + plan: ManagedClusterVllmPlan, apiKey: string, - deps: Pick, - ownership?: DualSparkCleanupOwnership, -): Promise { + deps: Pick< + ManagedClusterVllmLifecycleDeps, + "inspectNode" | "removeContainer" | "withLifecycleLock" + >, + ownership?: ManagedClusterCleanupOwnership, +): Promise { let fingerprint: string; try { - fingerprint = dualSparkVllmApiKeyFingerprint(apiKey); + fingerprint = managedClusterVllmApiKeyFingerprint(apiKey); } catch (error) { return { ok: false, reason: (error as Error).message, removedContainerIds: [] }; } try { return await deps.withLifecycleLock(plan, async () => { - const snapshots = await inspectBoth(plan, deps); + const snapshots = await inspectAll(plan, deps); if (!snapshots) { return { ok: false, - reason: "could not inspect both dual-Spark container daemons", + reason: "could not inspect every managed cluster container daemon", removedContainerIds: [], }; } @@ -809,15 +828,15 @@ export async function cleanupDualSparkManagedVllm( if (owned && !owned.ok) { return { ok: false, reason: owned.reason, removedContainerIds: [] }; } - const pair = ownership ? null : exactPairForCleanup(plan, fingerprint, snapshots); - if (!ownership && !pair) { + const cluster = ownership ? null : exactClusterForCleanup(plan, fingerprint, snapshots); + if (!ownership && !cluster) { return { ok: false, - reason: "dual-Spark cleanup requires one complete exact owned pair", + reason: "managed cluster cleanup requires one complete exact owned cluster", removedContainerIds: [], }; } - const observations = owned?.ok ? owned.observations : [pair!.head, pair!.worker]; + const observations = owned?.ok ? owned.observations : cluster!; const removedContainerIds: string[] = []; for (const observation of observations) { const removed = await deps.removeContainer(observation.rolePlan, observation.container.id); @@ -841,7 +860,7 @@ export async function cleanupDualSparkManagedVllm( } catch (error) { return { ok: false, - reason: `dual-Spark cleanup failed: ${(error as Error).message}`, + reason: `managed cluster cleanup failed: ${(error as Error).message}`, removedContainerIds: [], }; } diff --git a/src/lib/inference/serving/dual-spark-materialize.test.ts b/src/lib/inference/serving/managed-cluster-materialize.test.ts similarity index 67% rename from src/lib/inference/serving/dual-spark-materialize.test.ts rename to src/lib/inference/serving/managed-cluster-materialize.test.ts index a5dcd7cad3c..2eb65cca993 100644 --- a/src/lib/inference/serving/dual-spark-materialize.test.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.test.ts @@ -15,25 +15,25 @@ import type { ManagedInferenceServingRecipe, ResolvedManagedInferenceSelection, } from "./catalog-types.js"; -import { fixtureDualSparkSelection } from "./dual-spark-fixture.test-support.js"; +import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { - DUAL_SPARK_PRESET_LABEL, - DUAL_SPARK_RECIPE_LABEL, - DUAL_SPARK_VLLM_MASTER_PORT, - materializeDualSparkVllmPlan, -} from "./dual-spark-materialize.js"; + MANAGED_CLUSTER_PRESET_LABEL, + MANAGED_CLUSTER_RECIPE_LABEL, + materializeManagedClusterVllmPlan, +} from "./managed-cluster-materialize.js"; import { - type DualSparkTopologyOutput, - dualSparkTopologyOutputDigest, -} from "./dual-spark-topology.js"; + type ManagedClusterTopologyOutput, + managedClusterTopologyOutputDigest, + managedClusterTopologySubjectDigest, +} from "./managed-cluster-topology.js"; interface SyntheticProfile { readonly catalog: CompiledManagedInferenceCatalog; - readonly selection: ResolvedManagedInferenceSelection; + readonly selection: ResolvedManagedInferenceSelection; } -function selectionWithDigests(): ResolvedManagedInferenceSelection { - const selection = fixtureDualSparkSelection(); +function selectionWithDigests(): ResolvedManagedInferenceSelection { + const selection = fixtureManagedClusterSelection(); return { ...selection, presetDigest: managedInferenceDigest(selection.preset), @@ -41,10 +41,70 @@ function selectionWithDigests(): ResolvedManagedInferenceSelection["topologyQualification"] { + const endpoint = (nodeId: string, peerAddress: string, address: string, index: number) => ({ + nodeId, + netdev: `eth${String(index)}`, + hcaDevice: `roce${String(index)}`, + hcaPort: 1, + address, + prefixLength: 30, + peerAddress, + roceGid: { index: 3 + index, value: `fe80::${address.replaceAll(".", ":")}` }, + }); + const output: ManagedClusterTopologyOutput = { + controllerNodeId: "spark-head", + nodes: [ + { nodeId: "spark-head", gpuId: "GPU-head", rank: 0, role: "head" }, + { nodeId: "spark-worker-a", gpuId: "GPU-worker-a", rank: 1, role: "worker" }, + { nodeId: "spark-worker-b", gpuId: "GPU-worker-b", rank: 2, role: "worker" }, + ], + rails: [ + { + index: 0, + endpoints: [ + endpoint("spark-head", "192.168.100.2", "192.168.100.1", 0), + endpoint("spark-worker-a", "192.168.100.1", "192.168.100.2", 0), + ], + }, + { + index: 1, + endpoints: [ + endpoint("spark-worker-a", "192.168.101.2", "192.168.101.1", 1), + endpoint("spark-worker-b", "192.168.101.1", "192.168.101.2", 0), + ], + }, + { + index: 2, + endpoints: [ + endpoint("spark-head", "192.168.102.2", "192.168.102.1", 1), + endpoint("spark-worker-b", "192.168.102.1", "192.168.102.2", 1), + ], + }, + ], + masterAddress: "192.168.100.1", + peers: [ + { nodeId: "spark-worker-a", target: "worker-a.local", sshBindingHandle: "binding-a" }, + { nodeId: "spark-worker-b", target: "worker-b.local", sshBindingHandle: "binding-b" }, + ], + }; + const subjectNodeIds = output.nodes.map(({ nodeId }) => nodeId); + return { + ...fixtureManagedClusterSelection().topologyQualification, + subjectNodeIds, + subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), + output, + outputDigest: managedClusterTopologyOutputDigest(output), + }; +} + +function syntheticSecondProfile( + temporaryFilesystemTarget = "/dev/shm-scratch", + nodeCount = 2, +): SyntheticProfile { const baseCatalog = loadManagedInferenceCatalog(); const baseSelection = selectionWithDigests(); - const topology = baseSelection.topologyQualification; + const topology = nodeCount === 3 ? threeNodeTopology() : baseSelection.topologyQualification; const basePreset = baseCatalog.presets.find( ({ definition }) => definition.metadata.id === baseSelection.preset.metadata.id, )?.definition; @@ -59,8 +119,8 @@ function syntheticSecondProfile(temporaryFilesystemTarget = "/dev/shm-scratch"): const recipe: ManagedInferenceServingRecipe = { ...recipeTemplate, metadata: { - id: "vllm.synthetic-model.spark-dual.v1", - displayName: "Synthetic model on two compatible nodes", + id: "vllm.synthetic-model.managed-cluster.v1", + displayName: "Synthetic model on a compatible cluster", }, spec: { ...recipeTemplate.spec, @@ -103,6 +163,11 @@ function syntheticSecondProfile(temporaryFilesystemTarget = "/dev/shm-scratch"): ], environment: { SYNTHETIC_PROFILE: "enabled" }, }, + execution: { + ...recipeTemplate.spec.execution, + nodeCount, + tensorParallelSize: nodeCount, + }, serve: { ...recipeTemplate.spec.serve, executable: "/opt/vllm/bin/vllm", @@ -118,8 +183,8 @@ function syntheticSecondProfile(temporaryFilesystemTarget = "/dev/shm-scratch"): const preset: ManagedInferenceServingPreset = { ...presetTemplate, metadata: { - id: "vllm.synthetic-profile.spark-dual", - displayName: "Synthetic profile on two compatible nodes", + id: "vllm.synthetic-profile.managed-cluster", + displayName: "Synthetic profile on a compatible cluster", }, spec: { ...presetTemplate.spec, @@ -129,8 +194,8 @@ function syntheticSecondProfile(temporaryFilesystemTarget = "/dev/shm-scratch"): }; const recipeDigest = managedInferenceDigest(recipe); const presetDigest = managedInferenceDigest(preset); - const recipeSourceFile = "managed-inference/recipes/vllm.synthetic-model.spark-dual.v1.yaml"; - const presetSourceFile = "managed-inference/presets/vllm.synthetic-profile.spark-dual.yaml"; + const recipeSourceFile = "managed-inference/recipes/vllm.synthetic-model.managed-cluster.v1.yaml"; + const presetSourceFile = "managed-inference/presets/vllm.synthetic-profile.managed-cluster.yaml"; const sourceFiles = [ ...baseCatalog.sourceFiles, { @@ -183,13 +248,13 @@ function syntheticSecondProfile(temporaryFilesystemTarget = "/dev/shm-scratch"): }; } -describe("dual-DGX-Spark vLLM materializer", () => { +describe("managed-cluster vLLM materializer", () => { it("creates deterministic plans entirely from the selected catalog definitions", () => { const selection = selectionWithDigests(); - const plan = materializeDualSparkVllmPlan(selection); + const plan = materializeManagedClusterVllmPlan(selection); const recipe = selection.recipe.spec; - expect(materializeDualSparkVllmPlan(selection)).toEqual(plan); + expect(materializeManagedClusterVllmPlan(selection)).toEqual(plan); expect(Object.isFrozen(plan)).toBe(true); expect(plan).toMatchObject({ catalogDigest: selection.catalogDigest, @@ -208,7 +273,7 @@ describe("dual-DGX-Spark vLLM materializer", () => { expectedModel: recipe.readiness.expectedModel, }, }); - expect(plan.roles.head).toMatchObject({ + expect(plan.roles[0]).toMatchObject({ image: recipe.runtime.image, runtime: { architecture: recipe.runtime.architecture, @@ -230,20 +295,20 @@ describe("dual-DGX-Spark vLLM materializer", () => { }); const configuredPort = recipe.serve.arguments.find(({ name }) => name === "--port")?.value; expect(plan.apiPort).toBe(configuredPort); - expect(plan.roles.head.endpoint).toBe(`http://${plan.masterAddress}:${String(configuredPort)}`); + expect(plan.roles[0].endpoint).toBe(`http://${plan.masterAddress}:${String(configuredPort)}`); }); it("uses role-local topology values and starts rank 1 headless", () => { - const plan = materializeDualSparkVllmPlan(selectionWithDigests()); + const plan = materializeManagedClusterVllmPlan(selectionWithDigests()); - expect(plan.roles.head.environment).toMatchObject({ + expect(plan.roles[0].environment).toMatchObject({ VLLM_HOST_IP: "192.168.100.10", NCCL_IB_HCA: "rocep1s0f0:1", NCCL_SOCKET_IFNAME: "enp1s0f0np0", NCCL_IB_GID_INDEX: "3", NODE_RANK: "0", }); - expect(plan.roles.worker.environment).toMatchObject({ + expect(plan.roles[1].environment).toMatchObject({ VLLM_HOST_IP: "192.168.100.11", NCCL_IB_HCA: "rocep1s0f1:1", NCCL_SOCKET_IFNAME: "enp1s0f1np1", @@ -251,14 +316,14 @@ describe("dual-DGX-Spark vLLM materializer", () => { NODE_RANK: "1", HEADLESS: "1", }); - expect(plan.roles.head.command.arguments).toEqual( + expect(plan.roles[0].command.arguments).toEqual( expect.arrayContaining(["--host", "192.168.100.10"]), ); - expect(plan.roles.worker.command.arguments).toEqual( + expect(plan.roles[1].command.arguments).toEqual( expect.arrayContaining(["--host", "192.168.100.11", "--headless"]), ); - expect(plan.roles.head.command.arguments).not.toContain("--headless"); - expect(plan.roles.worker.command.arguments).toEqual( + expect(plan.roles[0].command.arguments).not.toContain("--headless"); + expect(plan.roles[1].command.arguments).toEqual( expect.arrayContaining([ "--tensor-parallel-size", "2", @@ -271,15 +336,15 @@ describe("dual-DGX-Spark vLLM materializer", () => { "--node-rank", "1", "--master-port", - String(DUAL_SPARK_VLLM_MASTER_PORT), + String(selectionWithDigests().recipe.spec.execution.rendezvousPort), ]), ); }); it("passes every recipe serving argument without embedding an API key", () => { const selection = selectionWithDigests(); - const plan = materializeDualSparkVllmPlan(selection); - const headArguments = plan.roles.head.command.arguments; + const plan = materializeManagedClusterVllmPlan(selection); + const headArguments = plan.roles[0].command.arguments; for (const argument of selection.recipe.spec.serve.arguments) { const index = headArguments.indexOf(argument.name); @@ -292,7 +357,7 @@ describe("dual-DGX-Spark vLLM materializer", () => { expect(headArguments[index + 1]).toBe(String(argument.value)); } expect(headArguments).not.toContain("--api-key"); - expect(plan.roles.worker.command.arguments).not.toContain("--api-key"); + expect(plan.roles[1].command.arguments).not.toContain("--api-key"); }); it("rejects a selected definition changed after catalog resolution", () => { @@ -300,35 +365,35 @@ describe("dual-DGX-Spark vLLM materializer", () => { (selection.recipe.spec.runtime as { image: string }).image = `registry.example.test/vllm@sha256:${"d".repeat(64)}`; - expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/definition digest/u); + expect(() => materializeManagedClusterVllmPlan(selection)).toThrow(/definition digest/u); }); it("rejects stale topology subject and output digests", () => { const staleSubject = selectionWithDigests(); (staleSubject.topologyQualification as { subjectDigest: string }).subjectDigest = `sha256:${"f".repeat(64)}`; - expect(() => materializeDualSparkVllmPlan(staleSubject)).toThrow(/subject digest/u); + expect(() => materializeManagedClusterVllmPlan(staleSubject)).toThrow(/subject digest/u); const staleOutput = selectionWithDigests(); - (staleOutput.topologyQualification.output.peer as { target: string }).target = + (staleOutput.topologyQualification.output.peers[0] as { target: string }).target = "other-worker.local"; - expect(() => materializeDualSparkVllmPlan(staleOutput)).toThrow(/output digest/u); + expect(() => materializeManagedClusterVllmPlan(staleOutput)).toThrow(/output digest/u); }); it("rejects an inconsistent master address even with a recomputed digest", () => { const selection = selectionWithDigests(); const artifact = selection.topologyQualification; (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; - (artifact as { outputDigest: string }).outputDigest = dualSparkTopologyOutputDigest( + (artifact as { outputDigest: string }).outputDigest = managedClusterTopologyOutputDigest( artifact.output, ); - expect(() => materializeDualSparkVllmPlan(selection)).toThrow(/master address/u); + expect(() => materializeManagedClusterVllmPlan(selection)).toThrow(/master address/u); }); it("materializes bounded preparation operations from recipe data", () => { const selection = selectionWithDigests(); - const preparation = materializeDualSparkVllmPlan(selection).roles.head.preparation; + const preparation = materializeManagedClusterVllmPlan(selection).roles[0].preparation; const configured = selection.recipe.spec.model.preparation; expect(configured.ref).not.toBe(NO_PREPARATION_REF); const boundedConfigured = configured as Extract< @@ -360,7 +425,7 @@ describe("dual-DGX-Spark vLLM materializer", () => { it("materializes a synthetic second profile without materializer code changes", () => { const { catalog, selection } = syntheticSecondProfile(); - const plan = materializeDualSparkVllmPlan(selection, { catalog }); + const plan = materializeManagedClusterVllmPlan(selection, { catalog }); expect(plan).toMatchObject({ presetId: selection.preset.metadata.id, @@ -372,7 +437,7 @@ describe("dual-DGX-Spark vLLM materializer", () => { apiPort: 9_001, readiness: { timeoutMs: 900_000, expectedModel: "synthetic-model" }, }); - expect(plan.roles.head).toMatchObject({ + expect(plan.roles[0]).toMatchObject({ image: selection.recipe.spec.runtime.image, runtime: { sharedMemoryBytes: 8_589_934_592, @@ -397,31 +462,55 @@ describe("dual-DGX-Spark vLLM materializer", () => { }, command: { executable: "/opt/vllm/bin/vllm" }, baseLabels: { - [DUAL_SPARK_PRESET_LABEL]: selection.preset.metadata.id, - [DUAL_SPARK_RECIPE_LABEL]: selection.recipe.metadata.id, + [MANAGED_CLUSTER_PRESET_LABEL]: selection.preset.metadata.id, + [MANAGED_CLUSTER_RECIPE_LABEL]: selection.recipe.metadata.id, }, }); - expect(plan.roles.head.environment).toMatchObject({ + expect(plan.roles[0].environment).toMatchObject({ HF_HOME: "/models/cache", SYNTHETIC_PROFILE: "enabled", }); - expect(plan.roles.head.command.arguments).toEqual( + expect(plan.roles[0].command.arguments).toEqual( expect.arrayContaining(["--port", "9001", "--max-model-len", "4096"]), ); const originalSelection = selectionWithDigests(); - const originalPlan = materializeDualSparkVllmPlan(originalSelection); - const originalFromExpandedCatalog = materializeDualSparkVllmPlan( + const originalPlan = materializeManagedClusterVllmPlan(originalSelection); + const originalFromExpandedCatalog = materializeManagedClusterVllmPlan( { ...originalSelection, catalogDigest: catalog.catalogDigest }, { catalog }, ); expect(originalFromExpandedCatalog.planId).toBe(originalPlan.planId); }); + it("takes cluster cardinality and parallelism from a synthetic three-node catalog profile", () => { + const { catalog, selection } = syntheticSecondProfile("/dev/shm-scratch", 3); + const plan = materializeManagedClusterVllmPlan(selection, { catalog }); + + expect(plan.roles).toHaveLength(3); + expect(plan.roles.map(({ rank, role }) => ({ rank, role }))).toEqual([ + { rank: 0, role: "head" }, + { rank: 1, role: "worker" }, + { rank: 2, role: "worker" }, + ]); + for (const role of plan.roles) { + expect(role.command.arguments).toEqual( + expect.arrayContaining([ + "--nnodes", + "3", + "--tensor-parallel-size", + "3", + "--node-rank", + String(role.rank), + ]), + ); + } + }); + it("rejects a temporary filesystem that shadows the model cache", () => { const { catalog, selection } = syntheticSecondProfile("/models"); - expect(() => materializeDualSparkVllmPlan(selection, { catalog })).toThrow( + expect(() => materializeManagedClusterVllmPlan(selection, { catalog })).toThrow( /temporary filesystem cannot shadow the model cache/u, ); }); diff --git a/src/lib/inference/serving/dual-spark-materialize.ts b/src/lib/inference/serving/managed-cluster-materialize.ts similarity index 73% rename from src/lib/inference/serving/dual-spark-materialize.ts rename to src/lib/inference/serving/managed-cluster-materialize.ts index 8339c57f7ab..410cea99a5f 100644 --- a/src/lib/inference/serving/dual-spark-materialize.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.ts @@ -5,13 +5,12 @@ import path from "node:path"; import { containerPathContains, - DUAL_SPARK_VLLM_MASTER_PORT, - DUAL_SPARK_VLLM_MATERIALIZER_REF, getManagedInferenceLifecycleDescriptor, getManagedInferenceMaterializerDescriptor, getManagedInferenceRecipeRegistrationError, getManagedInferenceTopologyQualificationDescriptor, - isDualSparkMaterializerOwnedEnvironment, + isManagedClusterMaterializerOwnedEnvironment, + MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, } from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { @@ -20,44 +19,41 @@ import { managedInferenceHexDigest, } from "./catalog-integrity.js"; import { - isManagedInferenceMaterializerOwnedArgument, type CompiledManagedInferenceCatalog, type CompiledManagedInferenceDefinition, + isManagedInferenceMaterializerOwnedArgument, type ManagedInferenceServingPreset, type ManagedInferenceServingRecipe, type ResolvedManagedInferenceSelection, } from "./catalog-types.js"; import { - materializeDualSparkVllmPreparation, - type DualSparkVllmPreparationPlan, -} from "./dual-spark-preparation.js"; + type ManagedClusterVllmPreparationPlan, + materializeManagedClusterVllmPreparation, +} from "./managed-cluster-preparation.js"; import { - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - type DualSparkTopologyOutput, - type DualSparkTopologyRailEndpoint, -} from "./dual-spark-topology.js"; + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + type ManagedClusterTopologyOutput, + type ManagedClusterTopologyRailEndpoint, +} from "./managed-cluster-topology.js"; /** Stable adapter identity; profile identities and values come from the selected catalog entries. */ -export const DUAL_SPARK_VLLM_ADAPTER_ID = DUAL_SPARK_VLLM_MATERIALIZER_REF; -export { DUAL_SPARK_VLLM_MASTER_PORT }; -export const DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME = "nemoclaw-vllm-dspark-head"; -export const DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME = "nemoclaw-vllm-dspark-worker"; -export const DUAL_SPARK_VLLM_PROJECT_ID = "nemoclaw-vllm-dspark"; - -export const DUAL_SPARK_MANAGED_LABEL = "com.nvidia.nemoclaw.managed-vllm"; -export const DUAL_SPARK_ADAPTER_LABEL = "com.nvidia.nemoclaw.serving-adapter"; -export const DUAL_SPARK_PRESET_LABEL = "com.nvidia.nemoclaw.serving-preset"; -export const DUAL_SPARK_RECIPE_LABEL = "com.nvidia.nemoclaw.serving-recipe"; -export const DUAL_SPARK_ROLE_LABEL = "com.nvidia.nemoclaw.serving-role"; -export const DUAL_SPARK_CLUSTER_LABEL = "com.nvidia.nemoclaw.serving-cluster"; -export const DUAL_SPARK_PLAN_LABEL = "com.nvidia.nemoclaw.serving-plan"; -export const DUAL_SPARK_GPU_LABEL = "com.nvidia.nemoclaw.serving-gpu"; -export const DUAL_SPARK_IMAGE_LABEL = "com.nvidia.nemoclaw.serving-image"; -export const DUAL_SPARK_MODEL_REVISION_LABEL = "com.nvidia.nemoclaw.serving-model-revision"; -export const DUAL_SPARK_API_KEY_FINGERPRINT_LABEL = +export const MANAGED_CLUSTER_VLLM_ADAPTER_ID = MANAGED_CLUSTER_VLLM_MATERIALIZER_REF; +export const MANAGED_CLUSTER_VLLM_PROJECT_ID = "nemoclaw-vllm-cluster"; + +export const MANAGED_CLUSTER_MANAGED_LABEL = "com.nvidia.nemoclaw.managed-vllm"; +export const MANAGED_CLUSTER_ADAPTER_LABEL = "com.nvidia.nemoclaw.serving-adapter"; +export const MANAGED_CLUSTER_PRESET_LABEL = "com.nvidia.nemoclaw.serving-preset"; +export const MANAGED_CLUSTER_RECIPE_LABEL = "com.nvidia.nemoclaw.serving-recipe"; +export const MANAGED_CLUSTER_ROLE_LABEL = "com.nvidia.nemoclaw.serving-role"; +export const MANAGED_CLUSTER_CLUSTER_LABEL = "com.nvidia.nemoclaw.serving-cluster"; +export const MANAGED_CLUSTER_PLAN_LABEL = "com.nvidia.nemoclaw.serving-plan"; +export const MANAGED_CLUSTER_GPU_LABEL = "com.nvidia.nemoclaw.serving-gpu"; +export const MANAGED_CLUSTER_IMAGE_LABEL = "com.nvidia.nemoclaw.serving-image"; +export const MANAGED_CLUSTER_MODEL_REVISION_LABEL = "com.nvidia.nemoclaw.serving-model-revision"; +export const MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL = "com.nvidia.nemoclaw.serving-api-key-fingerprint"; -export const DUAL_SPARK_TRANSACTION_LABEL = "com.nvidia.nemoclaw.serving-transaction"; +export const MANAGED_CLUSTER_TRANSACTION_LABEL = "com.nvidia.nemoclaw.serving-transaction"; const SAFE_DEVICE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/u; const SAFE_ABSOLUTE_PATH_PATTERN = /^\/(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9._+/-]+$/u; @@ -78,11 +74,11 @@ const TMPFS_OPTIONS = new Set([ "noatime", "relatime", ]); -export type DualSparkVllmRole = "head" | "worker"; +export type ManagedClusterVllmRole = "head" | "worker"; -export interface DualSparkVllmRolePlan { - readonly role: DualSparkVllmRole; - readonly rank: 0 | 1; +export interface ManagedClusterVllmRolePlan { + readonly role: ManagedClusterVllmRole; + readonly rank: number; readonly nodeId: string; readonly gpuId: string; readonly containerName: string; @@ -118,7 +114,7 @@ export interface DualSparkVllmRolePlan { readonly options: readonly string[]; }[]; }; - readonly preparation: DualSparkVllmPreparationPlan; + readonly preparation: ManagedClusterVllmPreparationPlan; readonly fabric: { readonly primaryRailIndex: number; readonly netdev: string; @@ -137,16 +133,16 @@ export interface DualSparkVllmRolePlan { readonly baseLabels: Readonly>; } -export interface DualSparkVllmPlan { +export interface ManagedClusterVllmPlan { readonly schemaVersion: 1; - readonly adapterId: typeof DUAL_SPARK_VLLM_ADAPTER_ID; + readonly adapterId: typeof MANAGED_CLUSTER_VLLM_ADAPTER_ID; readonly catalogDigest: string; readonly presetId: string; readonly presetDigest: string; readonly recipeId: string; readonly recipeDigest: string; - readonly topologyId: typeof DUAL_SPARK_TOPOLOGY_ID; - readonly topologySchemaVersion: typeof DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION; + readonly topologyId: typeof MANAGED_CLUSTER_TOPOLOGY_ID; + readonly topologySchemaVersion: typeof MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION; readonly topologySubjectDigest: string; readonly topologyOutputDigest: string; readonly clusterId: string; @@ -159,18 +155,15 @@ export interface DualSparkVllmPlan { readonly authentication: string; readonly apiPort: number; readonly masterAddress: string; - readonly masterPort: typeof DUAL_SPARK_VLLM_MASTER_PORT; + readonly masterPort: number; readonly readiness: { readonly timeoutMs: number; readonly expectedModel: string; }; - readonly roles: { - readonly worker: DualSparkVllmRolePlan; - readonly head: DualSparkVllmRolePlan; - }; + readonly roles: readonly ManagedClusterVllmRolePlan[]; } -export interface DualSparkVllmMaterializeOptions { +export interface ManagedClusterVllmMaterializeOptions { /** Explicit catalog input keeps the materializer testable with additional YAML-compiled profiles. */ readonly catalog?: CompiledManagedInferenceCatalog; } @@ -186,7 +179,7 @@ interface ParsedServingArguments { } function fail(message: string): never { - throw new Error(`Cannot materialize dual-DGX-Spark vLLM: ${message}`); + throw new Error(`Cannot materialize managed-cluster vLLM: ${message}`); } function positiveSafeInteger(value: number, maximum = Number.MAX_SAFE_INTEGER): boolean { @@ -226,7 +219,7 @@ function selectedDefinition, + selection: ResolvedManagedInferenceSelection, catalog: CompiledManagedInferenceCatalog, ): CatalogSelection { const { catalogDigest, ...catalogContents } = catalog; @@ -286,7 +279,7 @@ function assertCatalogSelection( const materializer = getManagedInferenceMaterializerDescriptor( recipe.spec.execution.materializerRef, ); - if (!materializer || materializer.ref !== DUAL_SPARK_VLLM_MATERIALIZER_REF) { + if (!materializer || materializer.ref !== MANAGED_CLUSTER_VLLM_MATERIALIZER_REF) { fail(`recipe selects unsupported materializer ${recipe.spec.execution.materializerRef}`); } const lifecycle = getManagedInferenceLifecycleDescriptor(recipe.spec.execution.lifecycleRef); @@ -317,6 +310,9 @@ function assertCatalogSelection( } const topologyError = topologyDescriptor.validateArtifact(topology); if (topologyError) fail(topologyError); + if (topology.output.nodes.length !== recipe.spec.execution.nodeCount) { + fail("topology node count does not match the recipe execution shape"); + } return { preset, recipe }; } @@ -386,7 +382,7 @@ function assertRecipeValues(recipe: ManagedInferenceServingRecipe): void { environmentEntries.some( ([name, value]) => !SAFE_ENVIRONMENT_NAME_PATTERN.test(name) || - isDualSparkMaterializerOwnedEnvironment(name) || + isManagedClusterMaterializerOwnedEnvironment(name) || Buffer.byteLength(value, "utf8") > 4_096 || value.includes("\0"), ) @@ -443,9 +439,9 @@ function servingArguments(recipe: ManagedInferenceServingRecipe): ParsedServingA function commandArguments( recipe: ManagedInferenceServingRecipe, - topology: ResolvedManagedInferenceSelection["topologyQualification"], + topology: ResolvedManagedInferenceSelection["topologyQualification"], staticArguments: readonly string[], - rank: 0 | 1, + rank: number, hostAddress: string, ): string[] { return [ @@ -471,69 +467,76 @@ function commandArguments( "--master-addr", topology.output.masterAddress, "--master-port", - String(DUAL_SPARK_VLLM_MASTER_PORT), - ...(rank === 1 ? ["--headless"] : []), + String(recipe.spec.execution.rendezvousPort), + ...(rank > 0 ? ["--headless"] : []), ]; } -function endpointForRole( - output: DualSparkTopologyOutput, - role: DualSparkVllmRole, -): DualSparkTopologyRailEndpoint { - const endpoint = output.rails[0]?.[role]; - if (!endpoint || endpoint.nodeId !== output[`${role}NodeId`]) { - fail(`primary ${role} fabric endpoint does not match the role node`); - } - if (!SAFE_DEVICE_PATTERN.test(endpoint.hcaDevice) || !SAFE_DEVICE_PATTERN.test(endpoint.netdev)) { - fail(`primary ${role} fabric device identity is invalid`); +function endpointsForNode( + output: ManagedClusterTopologyOutput, + nodeId: string, +): readonly (ManagedClusterTopologyRailEndpoint & { readonly railIndex: number })[] { + const endpoints = output.rails + .flatMap((rail) => + rail.endpoints + .filter((endpoint) => endpoint.nodeId === nodeId) + .map((endpoint) => ({ ...endpoint, railIndex: rail.index })), + ) + .sort((left, right) => left.railIndex - right.railIndex); + if ( + endpoints.length === 0 || + endpoints.some( + (endpoint) => + !SAFE_DEVICE_PATTERN.test(endpoint.hcaDevice) || !SAFE_DEVICE_PATTERN.test(endpoint.netdev), + ) + ) { + fail(`node ${nodeId} has no valid fabric endpoints`); } - return endpoint; + return endpoints; } interface RolePlanInput { - readonly selection: ResolvedManagedInferenceSelection; + readonly selection: ResolvedManagedInferenceSelection; readonly preset: ManagedInferenceServingPreset; readonly recipe: ManagedInferenceServingRecipe; readonly serving: ParsedServingArguments; - readonly preparation: DualSparkVllmPreparationPlan; - readonly role: DualSparkVllmRole; + readonly preparation: ManagedClusterVllmPreparationPlan; + readonly node: ManagedClusterTopologyOutput["nodes"][number]; readonly clusterId: string; readonly planId: string; } -function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { - const { clusterId, planId, preparation, preset, recipe, role, selection, serving } = input; +function rolePlan(input: RolePlanInput): ManagedClusterVllmRolePlan { + const { clusterId, node, planId, preparation, preset, recipe, selection, serving } = input; const output = selection.topologyQualification.output; - const rank = role === "head" ? 0 : 1; - const nodeId = role === "head" ? output.headNodeId : output.workerNodeId; - const node = output.nodes.find( - (candidate) => candidate.nodeId === nodeId && candidate.role === role, - ); - if (!node) fail(`${role} node is missing from the topology artifact`); - const endpoint = endpointForRole(output, role); + const { nodeId, rank, role } = node; + const fabricEndpoints = endpointsForNode(output, nodeId); + const primaryEndpoint = fabricEndpoints[0]!; + const peer = output.peers.find((candidate) => candidate.nodeId === nodeId); + if (rank > 0 && !peer) fail(`worker rank ${String(rank)} is missing its SSH binding`); const baseLabels = { - [DUAL_SPARK_MANAGED_LABEL]: "true", - [DUAL_SPARK_ADAPTER_LABEL]: DUAL_SPARK_VLLM_ADAPTER_ID, - [DUAL_SPARK_PRESET_LABEL]: preset.metadata.id, - [DUAL_SPARK_RECIPE_LABEL]: recipe.metadata.id, - [DUAL_SPARK_ROLE_LABEL]: role, - [DUAL_SPARK_CLUSTER_LABEL]: clusterId, - [DUAL_SPARK_PLAN_LABEL]: planId, - [DUAL_SPARK_GPU_LABEL]: node.gpuId, - [DUAL_SPARK_IMAGE_LABEL]: recipe.spec.runtime.image, - [DUAL_SPARK_MODEL_REVISION_LABEL]: recipe.spec.model.revision, + [MANAGED_CLUSTER_MANAGED_LABEL]: "true", + [MANAGED_CLUSTER_ADAPTER_LABEL]: MANAGED_CLUSTER_VLLM_ADAPTER_ID, + [MANAGED_CLUSTER_PRESET_LABEL]: preset.metadata.id, + [MANAGED_CLUSTER_RECIPE_LABEL]: recipe.metadata.id, + [MANAGED_CLUSTER_ROLE_LABEL]: role, + [MANAGED_CLUSTER_CLUSTER_LABEL]: clusterId, + [MANAGED_CLUSTER_PLAN_LABEL]: planId, + [MANAGED_CLUSTER_GPU_LABEL]: node.gpuId, + [MANAGED_CLUSTER_IMAGE_LABEL]: recipe.spec.runtime.image, + [MANAGED_CLUSTER_MODEL_REVISION_LABEL]: recipe.spec.model.revision, }; const environment = { ...recipe.spec.runtime.environment, HF_HOME: recipe.spec.runtime.modelCache.target, - VLLM_HOST_IP: endpoint.address, - NCCL_IB_HCA: `${endpoint.hcaDevice}:${String(endpoint.hcaPort)}`, - NCCL_SOCKET_IFNAME: endpoint.netdev, - TP_SOCKET_IFNAME: endpoint.netdev, - GLOO_SOCKET_IFNAME: endpoint.netdev, - NCCL_IB_GID_INDEX: String(endpoint.roceGid.index), + VLLM_HOST_IP: primaryEndpoint.address, + NCCL_IB_HCA: `${primaryEndpoint.hcaDevice}:${String(primaryEndpoint.hcaPort)}`, + NCCL_SOCKET_IFNAME: primaryEndpoint.netdev, + TP_SOCKET_IFNAME: primaryEndpoint.netdev, + GLOO_SOCKET_IFNAME: primaryEndpoint.netdev, + NCCL_IB_GID_INDEX: String(primaryEndpoint.roceGid.index), MASTER_ADDR: output.masterAddress, - MASTER_PORT: String(DUAL_SPARK_VLLM_MASTER_PORT), + MASTER_PORT: String(recipe.spec.execution.rendezvousPort), NODE_RANK: String(rank), HEADLESS: role === "worker" ? "1" : "", }; @@ -544,15 +547,14 @@ function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { rank, nodeId, gpuId: node.gpuId, - containerName: - role === "head" ? DUAL_SPARK_VLLM_HEAD_CONTAINER_NAME : DUAL_SPARK_VLLM_WORKER_CONTAINER_NAME, + containerName: `nemoclaw-vllm-cluster-rank-${String(rank)}`, execution: role === "head" ? { kind: "local" } : { kind: "ssh", - expectedTarget: output.peer.target, - bindingHandle: output.peer.sshBindingHandle, + expectedTarget: peer!.target, + bindingHandle: peer!.sshBindingHandle, }, image: runtime.image, runtime: { @@ -570,13 +572,13 @@ function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { }, preparation, fabric: { - primaryRailIndex: output.rails[0].index, - netdev: endpoint.netdev, - hcaDevice: endpoint.hcaDevice, - hcaPort: endpoint.hcaPort, - address: endpoint.address, - roceGidIndex: endpoint.roceGid.index, - roceGidValue: endpoint.roceGid.value, + primaryRailIndex: primaryEndpoint.railIndex, + netdev: primaryEndpoint.netdev, + hcaDevice: primaryEndpoint.hcaDevice, + hcaPort: primaryEndpoint.hcaPort, + address: primaryEndpoint.address, + roceGidIndex: primaryEndpoint.roceGid.index, + roceGidValue: primaryEndpoint.roceGid.value, }, environment, command: { @@ -586,7 +588,7 @@ function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { selection.topologyQualification, serving.arguments, rank, - endpoint.address, + primaryEndpoint.address, ), }, endpoint: role === "head" ? `http://${output.masterAddress}:${String(serving.apiPort)}` : null, @@ -595,11 +597,11 @@ function rolePlan(input: RolePlanInput): DualSparkVllmRolePlan { } /** Compile one resolved, qualified catalog selection into immutable role-local plans. */ -export function materializeDualSparkVllmPlan( - selection: ResolvedManagedInferenceSelection, - options: DualSparkVllmMaterializeOptions = {}, -): DualSparkVllmPlan { - let snapshot: ResolvedManagedInferenceSelection; +export function materializeManagedClusterVllmPlan( + selection: ResolvedManagedInferenceSelection, + options: ManagedClusterVllmMaterializeOptions = {}, +): ManagedClusterVllmPlan { + let snapshot: ResolvedManagedInferenceSelection; let catalog: CompiledManagedInferenceCatalog; try { snapshot = immutableManagedInferenceCopy(selection); @@ -614,9 +616,9 @@ export function materializeDualSparkVllmPlan( const catalogSelection = { ...snapshot, ...selected }; assertRecipeValues(selected.recipe); const serving = servingArguments(selected.recipe); - let preparation: DualSparkVllmPreparationPlan; + let preparation: ManagedClusterVllmPreparationPlan; try { - preparation = materializeDualSparkVllmPreparation({ + preparation = materializeManagedClusterVllmPreparation({ ...selected.recipe.spec.model, modelCacheTarget: selected.recipe.spec.runtime.modelCache.target, }); @@ -632,7 +634,7 @@ export function materializeDualSparkVllmPlan( }; const clusterId = managedInferenceHexDigest(topologyIdentity); const planId = managedInferenceHexDigest({ - adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + adapterId: MANAGED_CLUSTER_VLLM_ADAPTER_ID, preset: { id: selected.preset.metadata.id, digest: snapshot.presetDigest }, recipe: { id: selected.recipe.metadata.id, digest: snapshot.recipeDigest }, topology: topologyIdentity, @@ -640,14 +642,14 @@ export function materializeDualSparkVllmPlan( const output = snapshot.topologyQualification.output; return immutableManagedInferenceCopy({ schemaVersion: 1, - adapterId: DUAL_SPARK_VLLM_ADAPTER_ID, + adapterId: MANAGED_CLUSTER_VLLM_ADAPTER_ID, catalogDigest: snapshot.catalogDigest, presetId: selected.preset.metadata.id, presetDigest: snapshot.presetDigest, recipeId: selected.recipe.metadata.id, recipeDigest: snapshot.recipeDigest, - topologyId: DUAL_SPARK_TOPOLOGY_ID, - topologySchemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + topologyId: MANAGED_CLUSTER_TOPOLOGY_ID, + topologySchemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, topologySubjectDigest: snapshot.topologyQualification.subjectDigest, topologyOutputDigest: snapshot.topologyQualification.outputDigest, clusterId, @@ -660,32 +662,34 @@ export function materializeDualSparkVllmPlan( authentication: selected.recipe.spec.serve.authentication, apiPort: serving.apiPort, masterAddress: output.masterAddress, - masterPort: DUAL_SPARK_VLLM_MASTER_PORT, + masterPort: selected.recipe.spec.execution.rendezvousPort, readiness: { timeoutMs: selected.recipe.spec.readiness.timeoutSeconds * 1000, expectedModel: selected.recipe.spec.readiness.expectedModel, }, - roles: { - worker: rolePlan({ - selection: catalogSelection, - preset: selected.preset, - recipe: selected.recipe, - serving, - preparation, - role: "worker", - clusterId, - planId, - }), - head: rolePlan({ + roles: output.nodes.map((node) => + rolePlan({ selection: catalogSelection, preset: selected.preset, recipe: selected.recipe, serving, preparation, - role: "head", + node, clusterId, planId, }), - }, + ), }); } + +export function managedClusterHeadRole(plan: ManagedClusterVllmPlan): ManagedClusterVllmRolePlan { + const head = plan.roles.find((role) => role.rank === 0 && role.role === "head"); + if (!head) fail("plan has no rank-zero head role"); + return head; +} + +export function managedClusterWorkerRoles( + plan: ManagedClusterVllmPlan, +): readonly ManagedClusterVllmRolePlan[] { + return plan.roles.filter((role) => role.rank > 0 && role.role === "worker"); +} diff --git a/src/lib/inference/serving/dual-spark-preparation.test.ts b/src/lib/inference/serving/managed-cluster-preparation.test.ts similarity index 90% rename from src/lib/inference/serving/dual-spark-preparation.test.ts rename to src/lib/inference/serving/managed-cluster-preparation.test.ts index 7088f6a6da9..753cf4fc488 100644 --- a/src/lib/inference/serving/dual-spark-preparation.test.ts +++ b/src/lib/inference/serving/managed-cluster-preparation.test.ts @@ -7,7 +7,7 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; -import { materializeDualSparkVllmPreparation } from "./dual-spark-preparation.js"; +import { materializeManagedClusterVllmPreparation } from "./managed-cluster-preparation.js"; const MODEL = { id: "example-org/Synthetic-Model", @@ -16,9 +16,9 @@ const MODEL = { modelCacheTarget: "/models/alternate-cache", } as const; -describe("dual-DGX-Spark vLLM preparation materializer", () => { +describe("managed cluster vLLM preparation materializer", () => { it("materializes the registered no-op without executable input", () => { - const preparation = materializeDualSparkVllmPreparation({ + const preparation = materializeManagedClusterVllmPreparation({ ...MODEL, preparation: { ref: NO_PREPARATION_REF }, }); @@ -34,7 +34,7 @@ describe("dual-DGX-Spark vLLM preparation materializer", () => { }); it("derives the snapshot root and opaque target paths from recipe data", () => { - const preparation = materializeDualSparkVllmPreparation({ + const preparation = materializeManagedClusterVllmPreparation({ ...MODEL, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, @@ -107,6 +107,6 @@ describe("dual-DGX-Spark vLLM preparation materializer", () => { }, }, ])("rejects bounded operation input with $label", ({ preparation }) => { - expect(() => materializeDualSparkVllmPreparation({ ...MODEL, preparation })).toThrow(); + expect(() => materializeManagedClusterVllmPreparation({ ...MODEL, preparation })).toThrow(); }); }); diff --git a/src/lib/inference/serving/dual-spark-preparation.ts b/src/lib/inference/serving/managed-cluster-preparation.ts similarity index 93% rename from src/lib/inference/serving/dual-spark-preparation.ts rename to src/lib/inference/serving/managed-cluster-preparation.ts index db475a4d67e..0d7418f78ce 100644 --- a/src/lib/inference/serving/dual-spark-preparation.ts +++ b/src/lib/inference/serving/managed-cluster-preparation.ts @@ -13,7 +13,7 @@ const MODEL_REVISION = /^[0-9a-f]{40,64}$/u; const MAX_PATH_BYTES = 4_096; const MAX_REPLACEMENT_BYTES = 64 * 1_024; -export type DualSparkVllmPreparationRecipe = +export type ManagedClusterVllmPreparationRecipe = | { readonly ref: typeof NO_PREPARATION_REF } | { readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; @@ -31,16 +31,16 @@ export type DualSparkVllmPreparationRecipe = }; }; -interface DualSparkVllmPreparationPlanBase { +interface ManagedClusterVllmPreparationPlanBase { readonly phase: "container-before-exec"; readonly modelId: string; readonly modelRevision: string; readonly modelDownloadSizeBytes: number; } -export type DualSparkVllmPreparationPlan = - | (DualSparkVllmPreparationPlanBase & { readonly ref: typeof NO_PREPARATION_REF }) - | (DualSparkVllmPreparationPlanBase & { +export type ManagedClusterVllmPreparationPlan = + | (ManagedClusterVllmPreparationPlanBase & { readonly ref: typeof NO_PREPARATION_REF }) + | (ManagedClusterVllmPreparationPlanBase & { readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; readonly snapshotCopy: { readonly sourcePath: string; @@ -115,7 +115,7 @@ function containerPath(value: unknown, label: string): string { return candidate; } -function preparationRecipe(value: unknown): DualSparkVllmPreparationRecipe { +function preparationRecipe(value: unknown): ManagedClusterVllmPreparationRecipe { if (!isRecord(value)) throw new Error("model preparation must be an object"); if (value.ref === NO_PREPARATION_REF) { exactKeys(value, ["ref"], "model preparation"); @@ -164,9 +164,9 @@ function preparationRecipe(value: unknown): DualSparkVllmPreparationRecipe { } /** Materialize one allowlisted, non-executable preparation operation from recipe data. */ -export function materializeDualSparkVllmPreparation( +export function materializeManagedClusterVllmPreparation( model: PreparationModel, -): DualSparkVllmPreparationPlan { +): ManagedClusterVllmPreparationPlan { if (!MODEL_ID.test(model.id) || !MODEL_REVISION.test(model.revision)) { throw new Error("model preparation identity is invalid"); } diff --git a/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts b/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts new file mode 100644 index 00000000000..ba72b49559f --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export const MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE = "managed-cluster-vllm-runtime.json"; +export const MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE = "managed-cluster-managed-serving.json"; + +const SAFE_NODE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; +const RUNTIME_BINDING_PREFIX = `${MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE}.rank-`; +const DISCOVERY_BINDING_PREFIX = `${MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE}.`; +const BINDING_SUFFIX = ".ssh-binding"; + +export function isManagedClusterRuntimeBindingStateEntry(entry: string): boolean { + if (!entry.startsWith(RUNTIME_BINDING_PREFIX) || !entry.endsWith(BINDING_SUFFIX)) return false; + const rank = entry.slice(RUNTIME_BINDING_PREFIX.length, -BINDING_SUFFIX.length); + return /^(?:[1-9]\d{0,3})$/u.test(rank) && Number(rank) <= 1_023; +} + +export function isManagedClusterDiscoveryBindingStateEntry(entry: string): boolean { + if (!entry.startsWith(DISCOVERY_BINDING_PREFIX) || !entry.endsWith(BINDING_SUFFIX)) return false; + const nodeId = entry.slice(DISCOVERY_BINDING_PREFIX.length, -BINDING_SUFFIX.length); + return SAFE_NODE_ID_PATTERN.test(nodeId); +} diff --git a/src/lib/inference/serving/managed-cluster-runtime-receipt.ts b/src/lib/inference/serving/managed-cluster-runtime-receipt.ts new file mode 100644 index 00000000000..2544d14a898 --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-runtime-receipt.ts @@ -0,0 +1,723 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { ensureLocalAdapterStateDir } from "../local-adapter-lifecycle"; +import { loadManagedVllmApiKey, managedVllmStateDir } from "../vllm-api-key"; +import { + clearDualStationSshBinding, + copyDualStationSshBinding, + type DualStationSshBinding, + encodeDualStationSshBindingHandoff, + loadDualStationSshBindingForStatePath, + loadDualStationSshBindingHandoff, +} from "../vllm-station-ssh-binding"; +import { managedInferenceHexDigest } from "./catalog-integrity"; +import { + assertManagedClusterVllmExecutorConfig, + createManagedClusterVllmExecutor, + inspectManagedClusterVllmNodesSync, + type ManagedClusterVllmNodeSnapshots, +} from "./managed-cluster-executor"; +import { + classifyManagedClusterExistingState, + cleanupManagedClusterManagedVllm, + type ManagedClusterVllmLifecycleDeps, + managedClusterVllmApiKeyFingerprint, +} from "./managed-cluster-lifecycle"; +import { type ManagedClusterVllmPlan, managedClusterHeadRole } from "./managed-cluster-materialize"; +import { MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE } from "./managed-cluster-runtime-receipt-path"; + +const MAX_RECEIPT_BYTES = 128 * 1024; +const SHA256 = /^[a-f0-9]{64}$/; +const CONTAINER_ID = /^[a-f0-9]{64}$/; +const BINDING_HANDLE = /^[A-Za-z0-9_-]{1,8192}$/; +const RECEIPT_KEYS = ["apiKeyFingerprint", "nodes", "plan", "planDigest", "schemaVersion"] as const; +const RECEIPT_NODE_KEYS = [ + "cacheRoot", + "containerId", + "discoveryBindingDigest", + "discoveryStatePath", + "nodeId", + "sshBinding", +] as const; +const EXACT_BINDING_KEYS = [ + "schemaVersion", + "peerTarget", + "resolvedHost", + "sshUser", + "port", + "lookupHost", + "hostKeyDigest", + "dockerCliFile", + "dockerShimFile", + "dockerShimSha256", + "knownHostsFile", + "knownHostsSha256", + "bindingFile", + "sshWrapperDirectory", + "sshWrapperFile", + "sshWrapperSha256", +] as const satisfies readonly (keyof DualStationSshBinding)[]; + +interface PersistedReceipt { + readonly schemaVersion: 1; + readonly plan: ManagedClusterVllmPlan; + readonly planDigest: string; + readonly nodes: readonly PersistedReceiptNode[]; + readonly apiKeyFingerprint: string; +} + +interface PersistedReceiptNode { + readonly nodeId: string; + readonly cacheRoot: string; + readonly containerId: string; + readonly sshBinding: string | null; + readonly discoveryStatePath: string | null; + readonly discoveryBindingDigest: string | null; +} + +export interface PersistManagedClusterVllmRuntimeReceiptInput { + readonly plan: ManagedClusterVllmPlan; + readonly nodes: readonly PersistManagedClusterVllmRuntimeReceiptNode[]; + readonly apiKeyFingerprint: string; +} + +export interface PersistManagedClusterVllmRuntimeReceiptNode { + readonly nodeId: string; + readonly cacheRoot: string; + readonly containerId: string; + readonly sshBinding?: DualStationSshBinding; + readonly discoveryStatePath?: string; +} + +export interface LoadedManagedClusterVllmRuntime { + readonly plan: ManagedClusterVllmPlan; + readonly nodes: readonly LoadedManagedClusterVllmRuntimeNode[]; + readonly apiKeyFingerprint: string; +} + +export interface LoadedManagedClusterVllmRuntimeNode extends PersistedReceiptNode { + readonly binding?: DualStationSshBinding; +} + +type CleanupDeps = Pick< + ManagedClusterVllmLifecycleDeps, + "inspectNode" | "removeContainer" | "withLifecycleLock" +>; + +export interface ManagedClusterVllmRuntimeReceiptOptions { + readonly stateDir?: string; + /** @internal Test seam. */ + readonly loadApiKey?: () => string | null; + /** @internal Test seam. */ + readonly createLifecycleDeps?: (runtime: LoadedManagedClusterVllmRuntime) => CleanupDeps; + /** @internal Test seam. */ + readonly inspectNodesSync?: ( + runtime: LoadedManagedClusterVllmRuntime, + ) => ManagedClusterVllmNodeSnapshots; +} + +export interface RecoveredManagedClusterVllmEndpoint { + readonly baseUrl: string; + readonly apiKey: string; + readonly apiKeyFingerprint: string; + readonly plan: ManagedClusterVllmPlan; +} + +export type ManagedClusterVllmRuntimeCleanupResult = + | { readonly kind: "not-installed" } + | { readonly kind: "removed"; readonly removedContainerIds: readonly string[] }; + +export function managedClusterVllmRuntimeReceiptPath(stateDir = managedVllmStateDir()): string { + return path.join(stateDir, MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function exactKeys( + value: Record, + expected: readonly string[], + label: string, +): void { + const actual = Object.keys(value).sort(); + const sorted = [...expected].sort(); + if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) { + throw new Error(`${label} fields are invalid`); + } +} + +function requireString(value: unknown, label: string, pattern: RegExp, maximum = 8192): string { + if ( + typeof value !== "string" || + value.length === 0 || + value.length > maximum || + value !== value.trim() || + !pattern.test(value) + ) { + throw new Error(`${label} is invalid`); + } + return value; +} + +function requireAbsolutePath(value: unknown, label: string): string { + const candidate = requireString(value, label, /^[^\u0000-\u001f\u007f]+$/, 4096); + if (!path.posix.isAbsolute(candidate) || path.posix.normalize(candidate) !== candidate) { + throw new Error(`${label} must be a normalized absolute POSIX path`); + } + return candidate; +} + +function planDigest(plan: ManagedClusterVllmPlan): string { + return managedInferenceHexDigest(plan); +} + +function workerTarget(plan: ManagedClusterVllmPlan, nodeId: string): string { + const roles = Array.isArray(plan.roles) ? plan.roles : []; + const worker = roles.find((role) => isRecord(role) && role.nodeId === nodeId); + const execution = worker && isRecord(worker.execution) ? worker.execution : null; + if (!execution || execution.kind !== "ssh") { + throw new Error("Managed cluster worker SSH execution is invalid"); + } + return requireString( + execution.expectedTarget, + "managed cluster worker SSH target", + /^(?:[A-Za-z_][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/, + 286, + ); +} + +function assertExecutorContract( + plan: ManagedClusterVllmPlan, + nodes: readonly LoadedManagedClusterVllmRuntimeNode[], +): void { + assertManagedClusterVllmExecutorConfig({ + plan, + nodes: nodes.map(({ nodeId, cacheRoot, binding }) => ({ + nodeId, + modelCacheRoot: cacheRoot, + ...(binding ? { sshBinding: binding } : {}), + })), + }); +} + +function parseReceipt(value: unknown): PersistedReceipt { + if (!isRecord(value)) throw new Error("Managed cluster vLLM runtime receipt is invalid"); + exactKeys(value, RECEIPT_KEYS, "Managed cluster vLLM runtime receipt"); + if (value.schemaVersion !== 1 || !isRecord(value.plan)) { + throw new Error("Managed cluster vLLM runtime receipt schema is unsupported"); + } + const plan = value.plan as unknown as ManagedClusterVllmPlan; + const digest = requireString(value.planDigest, "managed cluster plan digest", SHA256, 64); + if (planDigest(plan) !== digest) + throw new Error("Managed cluster vLLM runtime plan digest changed"); + if (!Array.isArray(value.nodes) || value.nodes.length !== plan.roles.length) { + throw new Error("Managed cluster runtime receipt node ownership is incomplete"); + } + const nodes = value.nodes.map((entry, index): PersistedReceiptNode => { + if (!isRecord(entry)) throw new Error("Managed cluster runtime receipt node is invalid"); + exactKeys(entry, RECEIPT_NODE_KEYS, "Managed cluster runtime receipt node"); + const nodeId = requireString( + entry.nodeId, + "managed cluster node ID", + /^[A-Za-z0-9._:-]+$/, + 128, + ); + const rolePlan = plan.roles.find((role) => role.nodeId === nodeId); + if (!rolePlan || rolePlan.rank !== index) { + throw new Error("Managed cluster runtime receipt node order does not match the plan"); + } + const remote = rolePlan.execution.kind === "ssh"; + return { + nodeId, + cacheRoot: requireAbsolutePath(entry.cacheRoot, "managed cluster cache root"), + containerId: requireString( + entry.containerId, + "managed cluster container ID", + CONTAINER_ID, + 64, + ), + sshBinding: remote + ? requireString(entry.sshBinding, "managed cluster SSH binding", BINDING_HANDLE) + : entry.sshBinding === null + ? null + : (() => { + throw new Error("Managed cluster local node cannot contain an SSH binding"); + })(), + discoveryStatePath: remote + ? requireAbsolutePath(entry.discoveryStatePath, "managed cluster discovery state path") + : entry.discoveryStatePath === null + ? null + : (() => { + throw new Error("Managed cluster local node cannot contain discovery state"); + })(), + discoveryBindingDigest: remote + ? requireString( + entry.discoveryBindingDigest, + "managed cluster discovery SSH binding digest", + SHA256, + 64, + ) + : entry.discoveryBindingDigest === null + ? null + : (() => { + throw new Error("Managed cluster local node cannot contain a binding digest"); + })(), + }; + }); + if ( + new Set(nodes.map(({ nodeId }) => nodeId)).size !== nodes.length || + new Set(nodes.map(({ containerId }) => containerId)).size !== nodes.length + ) { + throw new Error("Managed cluster container identities are ambiguous"); + } + return { + schemaVersion: 1, + plan, + planDigest: digest, + nodes, + apiKeyFingerprint: requireString( + value.apiKeyFingerprint, + "managed cluster API key fingerprint", + SHA256, + 64, + ), + }; +} + +function assertPrivateReceipt(stat: fs.Stats, filePath: string): void { + if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) { + throw new Error( + `Managed cluster vLLM runtime receipt must be a private regular file: ${filePath}`, + ); + } + if (typeof process.getuid === "function" && stat.uid !== process.getuid()) { + throw new Error(`Managed cluster vLLM runtime receipt has the wrong owner: ${filePath}`); + } +} + +function loadPersistedReceipt(stateDir: string): PersistedReceipt | null { + const filePath = managedClusterVllmRuntimeReceiptPath(stateDir); + if (typeof fs.constants.O_NOFOLLOW !== "number") { + throw new Error("Secure no-follow file opens are unavailable on this platform"); + } + let fd: number | undefined; + try { + try { + fd = fs.openSync( + filePath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | (fs.constants.O_NONBLOCK ?? 0), + ); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === "ENOENT") return null; + if (code === "ELOOP") { + throw new Error(`Refusing to read managed cluster runtime receipt through a symbolic link`); + } + throw error; + } + const stat = fs.fstatSync(fd); + assertPrivateReceipt(stat, filePath); + if (stat.size < 2 || stat.size > MAX_RECEIPT_BYTES) { + throw new Error(`Managed cluster vLLM runtime receipt is malformed: ${filePath}`); + } + return parseReceipt(JSON.parse(fs.readFileSync(fd, "utf8"))); + } catch (error) { + if (error instanceof SyntaxError) { + throw new Error(`Managed cluster vLLM runtime receipt is malformed: ${filePath}`); + } + throw error; + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + +function fsyncDirectory(directory: string): void { + const fd = fs.openSync(directory, fs.constants.O_RDONLY); + try { + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } +} + +function writeReceipt(receipt: PersistedReceipt, stateDir: string): void { + ensureLocalAdapterStateDir(stateDir); + const filePath = managedClusterVllmRuntimeReceiptPath(stateDir); + const temporary = `${filePath}.tmp-${String(process.pid)}-${Date.now().toString(16)}`; + let fd: number | undefined; + try { + fd = fs.openSync( + temporary, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, + 0o600, + ); + assertPrivateReceipt(fs.fstatSync(fd), temporary); + fs.writeFileSync(fd, `${JSON.stringify(receipt)}\n`, "utf8"); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = undefined; + fs.renameSync(temporary, filePath); + fsyncDirectory(stateDir); + } catch (error) { + if (fd !== undefined) { + try { + fs.closeSync(fd); + } catch { + // Preserve the receipt-write failure. + } + } + try { + fs.unlinkSync(temporary); + } catch { + // A leftover unique temporary file must not mask the receipt-write failure. + } + throw error; + } +} + +function durablePlan( + plan: ManagedClusterVllmPlan, + sshBindings: ReadonlyMap, +): ManagedClusterVllmPlan { + return { + ...plan, + roles: plan.roles.map((rolePlan) => + rolePlan.execution.kind === "ssh" + ? { + ...rolePlan, + execution: { + ...rolePlan.execution, + bindingHandle: + sshBindings.get(rolePlan.nodeId) ?? + (() => { + throw new Error(`Managed cluster worker ${rolePlan.nodeId} has no SSH binding`); + })(), + }, + } + : rolePlan, + ), + }; +} + +function loadedRuntime(receipt: PersistedReceipt): LoadedManagedClusterVllmRuntime { + const nodes = receipt.nodes.map((node): LoadedManagedClusterVllmRuntimeNode => { + if (node.sshBinding === null) return node; + const binding = loadDualStationSshBindingHandoff( + node.sshBinding, + workerTarget(receipt.plan, node.nodeId), + ); + if (encodeDualStationSshBindingHandoff(binding) !== node.sshBinding) { + throw new Error("Managed cluster runtime SSH binding identity changed"); + } + return { ...node, binding }; + }); + assertExecutorContract(receipt.plan, nodes); + return { ...receipt, nodes }; +} + +function bindingDigest(binding: DualStationSshBinding): string { + return managedInferenceHexDigest( + Object.fromEntries(EXACT_BINDING_KEYS.map((field) => [field, binding[field]])), + ); +} + +function loadReceiptOwnedDiscoveryBinding( + runtime: LoadedManagedClusterVllmRuntime, +): readonly { readonly nodeId: string; readonly binding: DualStationSshBinding | null }[] { + return runtime.nodes + .filter((node) => node.binding) + .map((node) => { + const binding = loadDualStationSshBindingForStatePath( + node.discoveryStatePath!, + node.binding!.peerTarget, + node.binding!.hostKeyDigest, + ); + if (binding && bindingDigest(binding) !== node.discoveryBindingDigest) { + throw new Error( + "Managed cluster discovery SSH binding does not match the runtime receipt identity", + ); + } + return { nodeId: node.nodeId, binding }; + }); +} + +export function loadManagedClusterVllmRuntimeReceipt( + options: Pick = {}, +): LoadedManagedClusterVllmRuntime | null { + const receipt = loadPersistedReceipt(options.stateDir ?? managedVllmStateDir()); + return receipt ? loadedRuntime(receipt) : null; +} + +function sameInput( + existing: LoadedManagedClusterVllmRuntime, + input: PersistManagedClusterVllmRuntimeReceiptInput, +): boolean { + const durable = durablePlan( + input.plan, + new Map( + existing.nodes.flatMap((node) => + node.sshBinding ? [[node.nodeId, node.sshBinding] as const] : [], + ), + ), + ); + return ( + planDigest(durable) === planDigest(existing.plan) && + input.apiKeyFingerprint === existing.apiKeyFingerprint && + input.nodes.length === existing.nodes.length && + input.nodes.every((node, index) => { + const current = existing.nodes[index]; + return ( + current?.nodeId === node.nodeId && + current.cacheRoot === node.cacheRoot && + current.containerId === node.containerId && + current.discoveryStatePath === (node.discoveryStatePath ?? null) && + current.discoveryBindingDigest === (node.sshBinding ? bindingDigest(node.sshBinding) : null) + ); + }) + ); +} + +/** Persist immutable ownership and pinned transport state for recovery/uninstall. */ +export function persistManagedClusterVllmRuntimeReceipt( + input: PersistManagedClusterVllmRuntimeReceiptInput, + options: Pick = {}, +): LoadedManagedClusterVllmRuntime { + const stateDir = options.stateDir ?? managedVllmStateDir(); + ensureLocalAdapterStateDir(stateDir); + requireString(input.apiKeyFingerprint, "managed cluster API key fingerprint", SHA256, 64); + if ( + input.nodes.length !== input.plan.roles.length || + new Set(input.nodes.map(({ nodeId }) => nodeId)).size !== input.nodes.length || + new Set(input.nodes.map(({ containerId }) => containerId)).size !== input.nodes.length + ) { + throw new Error("Managed cluster runtime receipt node ownership is incomplete or ambiguous"); + } + const inputNodes = input.plan.roles.map( + (rolePlan, index): LoadedManagedClusterVllmRuntimeNode => { + const node = input.nodes.find((candidate) => candidate.nodeId === rolePlan.nodeId); + if (!node) throw new Error(`Managed cluster rank ${String(index)} has no receipt input`); + requireString(node.containerId, "managed cluster container ID", CONTAINER_ID, 64); + const cacheRoot = requireAbsolutePath(node.cacheRoot, "managed cluster cache root"); + if ( + (rolePlan.execution.kind === "local" && + (node.sshBinding !== undefined || node.discoveryStatePath !== undefined)) || + (rolePlan.execution.kind === "ssh" && (!node.sshBinding || !node.discoveryStatePath)) + ) { + throw new Error(`Managed cluster node ${node.nodeId} transport ownership is invalid`); + } + return { + nodeId: node.nodeId, + cacheRoot, + containerId: node.containerId, + sshBinding: node.sshBinding ? encodeDualStationSshBindingHandoff(node.sshBinding) : null, + discoveryStatePath: node.discoveryStatePath ?? null, + discoveryBindingDigest: node.sshBinding ? bindingDigest(node.sshBinding) : null, + ...(node.sshBinding ? { binding: node.sshBinding } : {}), + }; + }, + ); + assertExecutorContract(input.plan, inputNodes); + + const existing = loadManagedClusterVllmRuntimeReceipt({ stateDir }); + if (existing) { + if (!sameInput(existing, input)) { + throw new Error("A different managed cluster runtime receipt already owns recovery state"); + } + return existing; + } + + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); + const createdBindingStatePaths: string[] = []; + try { + const runtimeBindings = new Map(); + const persistedNodes = inputNodes.map((node, rank): PersistedReceiptNode => { + const { binding, ...persisted } = node; + if (!binding) return persisted; + const runtimeStatePath = `${receiptPath}.rank-${String(rank)}`; + const bindingPath = `${runtimeStatePath}.ssh-binding`; + try { + fs.mkdirSync(bindingPath, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "EEXIST") { + throw new Error(`Managed cluster SSH binding state already exists: ${bindingPath}`); + } + throw error; + } + createdBindingStatePaths.push(runtimeStatePath); + const runtimeBinding = copyDualStationSshBinding(runtimeStatePath, binding); + runtimeBindings.set(node.nodeId, runtimeBinding); + return { ...persisted, sshBinding: encodeDualStationSshBindingHandoff(runtimeBinding) }; + }); + fsyncDirectory(stateDir); + const plan = durablePlan( + input.plan, + new Map( + persistedNodes.flatMap((node) => + node.sshBinding ? [[node.nodeId, node.sshBinding] as const] : [], + ), + ), + ); + const loadedNodes = persistedNodes.map((node) => ({ + ...node, + ...(runtimeBindings.has(node.nodeId) ? { binding: runtimeBindings.get(node.nodeId)! } : {}), + })); + assertExecutorContract(plan, loadedNodes); + const receipt: PersistedReceipt = { + schemaVersion: 1, + plan, + planDigest: planDigest(plan), + nodes: persistedNodes, + apiKeyFingerprint: input.apiKeyFingerprint, + }; + writeReceipt(receipt, stateDir); + return loadedRuntime(receipt); + } catch (error) { + try { + for (const statePath of createdBindingStatePaths.reverse()) { + clearDualStationSshBinding(statePath); + } + } catch { + // Preserve the receipt persistence error. + } + throw error; + } +} + +function clearReceipt(stateDir: string, runtime: LoadedManagedClusterVllmRuntime): void { + const filePath = managedClusterVllmRuntimeReceiptPath(stateDir); + fs.unlinkSync(filePath); + for (const rolePlan of runtime.plan.roles) { + if (rolePlan.execution.kind === "ssh") { + clearDualStationSshBinding(`${filePath}.rank-${String(rolePlan.rank)}`); + } + } + fsyncDirectory(stateDir); +} + +function defaultCreateLifecycleDeps(runtime: LoadedManagedClusterVllmRuntime): CleanupDeps { + return createManagedClusterVllmExecutor({ + plan: runtime.plan, + nodes: runtime.nodes.map(({ nodeId, cacheRoot, binding }) => ({ + nodeId, + modelCacheRoot: cacheRoot, + ...(binding ? { sshBinding: binding } : {}), + })), + }); +} + +function defaultInspectNodesSync( + runtime: LoadedManagedClusterVllmRuntime, +): ManagedClusterVllmNodeSnapshots { + return inspectManagedClusterVllmNodesSync({ + plan: runtime.plan, + nodes: runtime.nodes.map(({ nodeId, cacheRoot, binding }) => ({ + nodeId, + modelCacheRoot: cacheRoot, + ...(binding ? { sshBinding: binding } : {}), + })), + }); +} + +/** Recover only the exact healthy receipt-owned cluster; unsafe managed state is explicit. */ +export function recoverInstalledManagedClusterVllmEndpoint( + options: Pick< + ManagedClusterVllmRuntimeReceiptOptions, + "inspectNodesSync" | "loadApiKey" | "stateDir" + > = {}, +): RecoveredManagedClusterVllmEndpoint | null { + const runtime = loadManagedClusterVllmRuntimeReceipt({ stateDir: options.stateDir }); + if (!runtime) return null; + const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); + if (!apiKey || managedClusterVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { + throw new Error("Managed cluster API key no longer matches the runtime receipt"); + } + let snapshots: ManagedClusterVllmNodeSnapshots; + try { + snapshots = (options.inspectNodesSync ?? defaultInspectNodesSync)(runtime); + } catch (error) { + throw new Error( + `Could not inspect the managed cluster: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + const state = classifyManagedClusterExistingState( + runtime.plan, + runtime.apiKeyFingerprint, + snapshots.nodes, + ); + const expectedContainers = new Map( + runtime.nodes.map(({ nodeId, containerId }) => [nodeId, containerId]), + ); + if ( + state.outcome !== "reuse" || + state.containers.length !== expectedContainers.size || + state.containers.some( + ({ nodeId, containerId }) => expectedContainers.get(nodeId) !== containerId, + ) + ) { + const reason = "reason" in state ? state.reason : "receipt-owned container IDs changed"; + throw new Error(`Managed cluster runtime is not recoverable: ${reason}`); + } + const baseUrl = managedClusterHeadRole(runtime.plan).endpoint; + if (!baseUrl) throw new Error("Managed cluster head endpoint is invalid"); + return { + baseUrl, + apiKey, + apiKeyFingerprint: runtime.apiKeyFingerprint, + plan: runtime.plan, + }; +} + +/** Remove only receipt-ID-owned containers, then retire fully accounted ownership state. */ +export async function cleanupInstalledManagedClusterVllmRuntime( + options: ManagedClusterVllmRuntimeReceiptOptions = {}, +): Promise { + const stateDir = options.stateDir ?? managedVllmStateDir(); + const runtime = loadManagedClusterVllmRuntimeReceipt({ stateDir }); + if (!runtime) return { kind: "not-installed" }; + + const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); + if (!apiKey || managedClusterVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { + throw new Error("Managed cluster API key no longer matches the runtime receipt"); + } + const discoveryBindings = loadReceiptOwnedDiscoveryBinding(runtime); + const deps = (options.createLifecycleDeps ?? defaultCreateLifecycleDeps)(runtime); + const cleanup = await cleanupManagedClusterManagedVllm(runtime.plan, apiKey, deps, { + containers: runtime.nodes.map(({ nodeId, containerId }) => ({ nodeId, containerId })), + }); + if (!cleanup.ok) throw new Error(cleanup.reason); + const expected = new Set(runtime.nodes.map(({ containerId }) => containerId)); + const accounted = [...cleanup.removedContainerIds, ...(cleanup.alreadyAbsentContainerIds ?? [])]; + if ( + accounted.length !== expected.size || + new Set(accounted).size !== expected.size || + accounted.some((id) => !expected.has(id)) + ) { + throw new Error("Managed cluster cleanup returned unexpected container identities"); + } + const currentDiscoveryBindings = loadReceiptOwnedDiscoveryBinding(runtime); + if ( + discoveryBindings.length !== currentDiscoveryBindings.length || + discoveryBindings.some( + (entry, index) => + entry.nodeId !== currentDiscoveryBindings[index]?.nodeId || + (entry.binding === null) !== (currentDiscoveryBindings[index]?.binding === null), + ) + ) { + throw new Error("Managed cluster discovery SSH binding changed during runtime cleanup"); + } + for (const entry of currentDiscoveryBindings) { + if (entry.binding) { + const node = runtime.nodes.find(({ nodeId }) => nodeId === entry.nodeId)!; + clearDualStationSshBinding(node.discoveryStatePath!); + } + } + clearReceipt(stateDir, runtime); + return { kind: "removed", removedContainerIds: cleanup.removedContainerIds }; +} diff --git a/src/lib/inference/serving/dual-spark-topology.test.ts b/src/lib/inference/serving/managed-cluster-topology.test.ts similarity index 61% rename from src/lib/inference/serving/dual-spark-topology.test.ts rename to src/lib/inference/serving/managed-cluster-topology.test.ts index f81267f6a88..d3002a18eab 100644 --- a/src/lib/inference/serving/dual-spark-topology.test.ts +++ b/src/lib/inference/serving/managed-cluster-topology.test.ts @@ -5,14 +5,14 @@ import { describe, expect, it } from "vitest"; import type { SystemReadinessReport } from "../../readiness/types.js"; import { - DUAL_SPARK_TOPOLOGY_ID, - DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, - type DualSparkNodeObservation, - type DualSparkPeerObservation, - type DualSparkRailObservation, - type DualSparkTopologyQualificationInput, - qualifyDualSparkTopology, -} from "./dual-spark-topology.js"; + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + type ManagedClusterNodeObservation, + type ManagedClusterPeerObservation, + type ManagedClusterRailObservation, + type ManagedClusterTopologyQualificationInput, + qualifyManagedClusterTopology, +} from "./managed-cluster-topology.js"; const EVALUATED_AT = "2026-08-02T18:00:00.000Z"; const READINESS_OBSERVED_AT = "2026-08-02T17:59:30.000Z"; @@ -60,8 +60,8 @@ function readiness(overrides: Partial = {}): SystemReadin function rail( node: "head" | "worker", index: 0 | 1, - overrides: Partial = {}, -): DualSparkRailObservation { + overrides: Partial = {}, +): ManagedClusterRailObservation { const headAddress = `192.168.${100 + index}.10`; const workerAddress = `192.168.${100 + index}.11`; const isHead = node === "head"; @@ -87,7 +87,7 @@ function rail( }; } -function localNode(): DualSparkNodeObservation { +function localNode(): ManagedClusterNodeObservation { return { nodeId: "spark-head", gpuIds: ["GPU-head"], @@ -97,7 +97,7 @@ function localNode(): DualSparkNodeObservation { }; } -function peerNode(index = 0): DualSparkPeerObservation { +function peerNode(index = 0): ManagedClusterPeerObservation { const suffix = index === 0 ? "" : `-${index}`; return { nodeId: `spark-worker${suffix}`, @@ -122,8 +122,8 @@ function peerNode(index = 0): DualSparkPeerObservation { } function qualificationInput( - peers: readonly DualSparkPeerObservation[] = [peerNode()], -): DualSparkTopologyQualificationInput { + peers: readonly ManagedClusterPeerObservation[] = [peerNode()], +): ManagedClusterTopologyQualificationInput { return { intent: "automatic", evaluatedAt: EVALUATED_AT, @@ -133,80 +133,159 @@ function qualificationInput( }; } +function ringRail( + nodeId: string, + peerNodeId: string, + subnet: number, + addressHost: number, + peerHost: number, + index: number, +): ManagedClusterRailObservation { + return { + adapter: "connectx-7", + path: "direct", + physicalPortId: `cx7-${nodeId}`, + netdev: `eth${String(index)}`, + hcaDevice: `roce${String(index)}`, + hcaPort: 1, + address: `192.168.${String(subnet)}.${String(addressHost)}`, + prefixLength: 30, + peerNodeId, + peerAddress: `192.168.${String(subnet)}.${String(peerHost)}`, + linkState: "up", + connectivity: "reachable", + roceGid: { + state: "resolved", + index: 3 + index, + value: `fe80::${String(subnet)}:${String(addressHost)}`, + }, + }; +} + +function threeNodeQualificationInput(): ManagedClusterTopologyQualificationInput { + const input = qualificationInput(); + input.local.rails = [ + ringRail("spark-head", "spark-worker-a", 100, 1, 2, 0), + ringRail("spark-head", "spark-worker-b", 102, 1, 2, 1), + ]; + input.peers = [ + { + ...peerNode(), + nodeId: "spark-worker-a", + gpuIds: ["GPU-worker-a"], + rails: [ + ringRail("spark-worker-a", "spark-head", 100, 2, 1, 0), + ringRail("spark-worker-a", "spark-worker-b", 101, 1, 2, 1), + ], + sshBinding: { + state: "pretrusted", + fromNodeId: "spark-head", + toNodeId: "spark-worker-a", + peerTarget: "spark-worker-a.local", + handle: "ssh-binding:worker-a", + }, + }, + { + ...peerNode(), + nodeId: "spark-worker-b", + gpuIds: ["GPU-worker-b"], + rails: [ + ringRail("spark-worker-b", "spark-worker-a", 101, 2, 1, 0), + ringRail("spark-worker-b", "spark-head", 102, 2, 1, 1), + ], + sshBinding: { + state: "pretrusted", + fromNodeId: "spark-head", + toNodeId: "spark-worker-b", + peerTarget: "spark-worker-b.local", + handle: "ssh-binding:worker-b", + }, + }, + ]; + return input; +} + function clone(value: T): T { return structuredClone(value); } -describe("dual DGX Spark topology qualification", () => { +describe("managed DGX Spark cluster topology qualification", () => { it("returns no match when discovery finds no peer", () => { - expect(qualifyDualSparkTopology(qualificationInput([]))).toMatchObject({ + expect(qualifyManagedClusterTopology(qualificationInput([]))).toMatchObject({ outcome: "no-match", code: "peer-count", }); }); - it("qualifies one peer as a two-node direct ConnectX-7 topology", () => { - const result = qualifyDualSparkTopology(qualificationInput()); + it("qualifies the profile-declared node set as a direct ConnectX-7 topology", () => { + const result = qualifyManagedClusterTopology(qualificationInput()); - expect(result.outcome).toBe("qualified"); + expect(result).toMatchObject({ outcome: "qualified" }); const qualified = result as Extract; expect(qualified.artifact).toMatchObject({ - id: DUAL_SPARK_TOPOLOGY_ID, - schemaVersion: DUAL_SPARK_TOPOLOGY_SCHEMA_VERSION, + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, status: "qualified", subjectNodeIds: ["spark-head", "spark-worker"], output: { - headNodeId: "spark-head", - workerNodeId: "spark-worker", - masterAddress: "192.168.100.10", - peer: { - target: "spark-worker.local", - sshBindingHandle: "ssh-binding:worker-0", - }, + controllerNodeId: "spark-head", + peers: [ + { + nodeId: "spark-worker", + target: "spark-worker.local", + sshBindingHandle: "ssh-binding:worker-0", + }, + ], }, }); expect(qualified.artifact.subjectDigest).toMatch(/^sha256:[a-f0-9]{64}$/); expect(qualified.artifact.outputDigest).toMatch(/^sha256:[a-f0-9]{64}$/); expect(qualified.artifact.output.nodes).toEqual([ - { nodeId: "spark-head", gpuId: "GPU-head", role: "head" }, - { nodeId: "spark-worker", gpuId: "GPU-worker", role: "worker" }, + { nodeId: "spark-head", gpuId: "GPU-head", rank: 0, role: "head" }, + { nodeId: "spark-worker", gpuId: "GPU-worker", rank: 1, role: "worker" }, ]); expect(qualified.artifact.output.rails).toHaveLength(2); - expect(qualified.artifact.output.rails.map(({ head }) => head.netdev)).toEqual([ - "enp1s0f0np0", - "enP2p1s0f0np0", - ]); - expect(qualified.artifact.output.rails[0]).toMatchObject({ - index: 0, - head: { - hcaDevice: "rocep1s0f0", - address: "192.168.100.10", - peerAddress: "192.168.100.11", - roceGid: { index: 5, value: "fe80::10" }, - }, - worker: { - hcaDevice: "rocep1s0f0", - address: "192.168.100.11", - peerAddress: "192.168.100.10", - roceGid: { index: 5, value: "fe80::20" }, - }, - }); + expect( + qualified.artifact.output.rails.flatMap(({ endpoints }) => + endpoints.map(({ nodeId }) => nodeId), + ), + ).toEqual(expect.arrayContaining(["spark-head", "spark-worker"])); }); - it("returns no match when discovery finds two peers", () => { - expect(qualifyDualSparkTopology(qualificationInput([peerNode(), peerNode(1)]))).toMatchObject({ + it("reports a fabric mismatch rather than rejecting a larger cluster by cardinality", () => { + expect( + qualifyManagedClusterTopology(qualificationInput([peerNode(), peerNode(1)])), + ).toMatchObject({ outcome: "no-match", - code: "peer-count", + code: "fabric-mismatch", }); }); - it("returns a strict error when discovery finds more than two peers", () => { + it("qualifies a three-node ring and assigns deterministic ranks", () => { + const result = qualifyManagedClusterTopology(threeNodeQualificationInput()); + if (result.outcome !== "qualified") throw new Error(`${result.code}: ${result.message}`); + + expect(result).toMatchObject({ outcome: "qualified" }); + const artifact = (result as Extract).artifact; + expect(artifact.output.nodes).toEqual([ + { nodeId: "spark-head", gpuId: "GPU-head", rank: 0, role: "head" }, + { nodeId: "spark-worker-a", gpuId: "GPU-worker-a", rank: 1, role: "worker" }, + { nodeId: "spark-worker-b", gpuId: "GPU-worker-b", rank: 2, role: "worker" }, + ]); + expect(artifact.output.rails).toHaveLength(3); + expect(artifact.output.peers.map(({ nodeId }) => nodeId)).toEqual([ + "spark-worker-a", + "spark-worker-b", + ]); + }); + + it("reports strict fabric errors without a fixed peer-count branch", () => { const input = qualificationInput([peerNode(), peerNode(1), peerNode(2)]); input.intent = "explicit"; - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "error", - code: "peer-count", + code: "fabric-mismatch", }); }); @@ -214,7 +293,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput([]); input.intent = "resume"; - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "error", code: "peer-count", }); @@ -273,7 +352,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); mutate(input.peers[0]!.readiness); - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code, }); @@ -288,7 +367,7 @@ describe("dual DGX Spark topology qualification", () => { : capability, ); - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "qualified", }); }); @@ -296,7 +375,7 @@ describe("dual DGX Spark topology qualification", () => { it.each([ { name: "the same node identity", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.peers[0]!.nodeId = input.local.nodeId; input.peers[0]!.sshBinding.toNodeId = input.local.nodeId; }, @@ -304,14 +383,14 @@ describe("dual DGX Spark topology qualification", () => { }, { name: "the same GPU identity", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.peers[0]!.gpuIds = input.local.gpuIds; }, code: "duplicate-gpu-identity", }, { name: "more than one local GPU identity", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.gpuIds = ["GPU-head", "GPU-extra"]; }, code: "gpu-identity-unavailable", @@ -320,7 +399,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); mutate(input); - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code, }); @@ -333,7 +412,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); input.peers[0]!.runtimeState = state; - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code, }); @@ -342,49 +421,49 @@ describe("dual DGX Spark topology qualification", () => { it.each([ { name: "one logical rail", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.rails = input.local.rails.slice(0, 1); }, code: "fabric-degraded", }, { name: "three logical rails", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.rails = [...input.local.rails, rail("head", 0, { netdev: "extra0" })]; }, code: "fabric-multiple", }, { name: "two physical ports", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.rails[1]!.physicalPortId = "cx7-right-head"; }, code: "fabric-multiple", }, { name: "a switched path", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.rails[0]!.path = "switched"; }, code: "fabric-degraded", }, { name: "an unreachable peer address", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.peers[0]!.rails[0]!.connectivity = "unreachable"; }, code: "fabric-degraded", }, { name: "nonreciprocal addresses", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.peers[0]!.rails[0]!.peerAddress = "192.168.100.99"; }, code: "fabric-mismatch", }, { name: "an unresolved RoCE GID", - mutate: (input: DualSparkTopologyQualificationInput) => { + mutate: (input: ManagedClusterTopologyQualificationInput) => { input.local.rails[0]!.roceGid = { state: "unknown" }; }, code: "fabric-degraded", @@ -393,7 +472,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); mutate(input); - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code, }); @@ -403,7 +482,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); input.peers[0]!.sshBinding.state = "untrusted"; - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code: "ssh-binding-unavailable", }); @@ -413,7 +492,7 @@ describe("dual DGX Spark topology qualification", () => { const input = qualificationInput(); input.peers[0]!.sshBinding.handle = " "; - expect(qualifyDualSparkTopology(input)).toMatchObject({ + expect(qualifyManagedClusterTopology(input)).toMatchObject({ outcome: "no-match", code: "ssh-binding-unavailable", }); @@ -425,8 +504,8 @@ describe("dual DGX Spark topology qualification", () => { secondInput.local.rails = [...secondInput.local.rails].reverse(); secondInput.peers[0]!.rails = [...secondInput.peers[0]!.rails].reverse(); - const first = qualifyDualSparkTopology(firstInput); - const second = qualifyDualSparkTopology(secondInput); + const first = qualifyManagedClusterTopology(firstInput); + const second = qualifyManagedClusterTopology(secondInput); expect(first.outcome).toBe("qualified"); expect(second.outcome).toBe("qualified"); const firstQualified = first as Extract; diff --git a/src/lib/inference/serving/managed-cluster-topology.ts b/src/lib/inference/serving/managed-cluster-topology.ts new file mode 100644 index 00000000000..1f3ddddad5a --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-topology.ts @@ -0,0 +1,880 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import net from "node:net"; + +import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; +import type { SystemReadinessReport } from "../../readiness/types.js"; +import { managedInferenceDigest } from "./catalog-integrity.js"; +import type { ManagedInferenceTopologyQualification } from "./catalog-types.js"; + +export const MANAGED_CLUSTER_TOPOLOGY_ID = "host-cluster.direct-cx7" as const; +export const MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION = 1 as const; + +const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; +const SAFE_INTERFACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; +const SAFE_BINDING_HANDLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,8191}$/; +const SSH_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const SSH_HOST_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/; + +export type ManagedClusterQualificationIntent = "automatic" | "explicit" | "resume"; +export type ManagedClusterRuntimeState = "clear" | "conflict" | "unknown"; +export type ManagedClusterObservationState = "up" | "down" | "unknown"; +export type ManagedClusterConnectivityState = "reachable" | "unreachable" | "unknown"; +export type ManagedClusterRoceGidState = "resolved" | "missing" | "unknown"; + +export interface ManagedClusterRoceGidObservation { + state: ManagedClusterRoceGidState; + index?: number; + value?: string; +} + +export interface ManagedClusterRailObservation { + adapter: "connectx-7" | "other" | "unknown"; + path: "direct" | "switched" | "unknown"; + physicalPortId: string; + netdev: string; + hcaDevice: string; + hcaPort: number; + address: string; + prefixLength: number; + peerNodeId: string; + peerAddress: string; + linkState: ManagedClusterObservationState; + connectivity: ManagedClusterConnectivityState; + roceGid: ManagedClusterRoceGidObservation; +} + +export interface ManagedClusterNodeObservation { + nodeId: string; + gpuIds: readonly string[]; + readiness: SystemReadinessReport; + runtimeState: ManagedClusterRuntimeState; + rails: readonly ManagedClusterRailObservation[]; +} + +export interface ManagedClusterSshBindingObservation { + state: "pretrusted" | "untrusted" | "unknown"; + fromNodeId: string; + toNodeId: string; + peerTarget: string; + handle: string; +} + +export interface ManagedClusterPeerObservation extends ManagedClusterNodeObservation { + sshBinding: ManagedClusterSshBindingObservation; +} + +export interface ManagedClusterTopologyQualificationInput { + intent: ManagedClusterQualificationIntent; + evaluatedAt: string; + maxReadinessAgeMs: number; + local: ManagedClusterNodeObservation; + peers: readonly ManagedClusterPeerObservation[]; +} + +export interface ManagedClusterTopologyNode { + nodeId: string; + gpuId: string; + rank: number; + role: "head" | "worker"; +} + +export interface ManagedClusterTopologyRoceGid { + index: number; + value: string; +} + +export interface ManagedClusterTopologyRailEndpoint { + nodeId: string; + netdev: string; + hcaDevice: string; + hcaPort: number; + address: string; + prefixLength: number; + peerAddress: string; + roceGid: ManagedClusterTopologyRoceGid; +} + +export interface ManagedClusterTopologyRail { + index: number; + endpoints: readonly [ManagedClusterTopologyRailEndpoint, ManagedClusterTopologyRailEndpoint]; +} + +export interface ManagedClusterTopologyOutput { + controllerNodeId: string; + nodes: readonly ManagedClusterTopologyNode[]; + rails: readonly ManagedClusterTopologyRail[]; + masterAddress: string; + peers: readonly { + nodeId: string; + target: string; + sshBindingHandle: string; + }[]; +} + +export type ManagedClusterTopologyArtifact = + ManagedInferenceTopologyQualification & { + id: typeof MANAGED_CLUSTER_TOPOLOGY_ID; + schemaVersion: typeof MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION; + status: "qualified"; + }; + +export type ManagedClusterTopologyFailureCode = + | "peer-count" + | "qualification-policy-invalid" + | "readiness-schema-incompatible" + | "readiness-stale" + | "readiness-incompatible" + | "readiness-inconclusive" + | "spark-qualification-unavailable" + | "runtime-qualification-unavailable" + | "node-identity-unavailable" + | "duplicate-node-identity" + | "gpu-identity-unavailable" + | "duplicate-gpu-identity" + | "runtime-conflict" + | "runtime-state-unknown" + | "ssh-binding-unavailable" + | "fabric-degraded" + | "fabric-multiple" + | "fabric-mismatch" + | "artifact-digest-failed"; + +export type ManagedClusterTopologyQualificationResult = + | { outcome: "qualified"; artifact: ManagedClusterTopologyArtifact } + | { outcome: "no-match"; code: ManagedClusterTopologyFailureCode; message: string } + | { outcome: "error"; code: ManagedClusterTopologyFailureCode; message: string }; + +interface QualificationFailure { + code: ManagedClusterTopologyFailureCode; + message: string; +} + +interface QualifiedNode { + observation: ManagedClusterNodeObservation; + gpuId: string; +} + +interface ValidatedRail { + observation: ManagedClusterRailObservation; + gid: ManagedClusterTopologyRoceGid; +} + +function compareStrings(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function failure( + intent: ManagedClusterQualificationIntent, + result: QualificationFailure, +): ManagedClusterTopologyQualificationResult { + return intent === "automatic" + ? { outcome: "no-match", ...result } + : { outcome: "error", ...result }; +} + +function validateQualificationPolicy( + evaluatedAt: string, + maxReadinessAgeMs: number, +): number | QualificationFailure { + const evaluatedAtMs = Date.parse(evaluatedAt); + if ( + !Number.isFinite(evaluatedAtMs) || + !Number.isSafeInteger(maxReadinessAgeMs) || + maxReadinessAgeMs <= 0 + ) { + return { + code: "qualification-policy-invalid", + message: "The topology qualification time or readiness age limit is invalid.", + }; + } + return evaluatedAtMs; +} + +function validateReadiness( + report: SystemReadinessReport, + evaluatedAtMs: number, + maxReadinessAgeMs: number, +): QualificationFailure | undefined { + const compatibility = checkSystemReadinessSchemaVersion(report.schemaVersion); + if (!compatibility.compatible || report.mutated !== false) { + return { + code: "readiness-schema-incompatible", + message: "A node readiness report has an incompatible schema.", + }; + } + + const observedAtMs = Date.parse(report.provenance.observedAt); + const readinessAgeMs = evaluatedAtMs - observedAtMs; + if (!Number.isFinite(observedAtMs) || readinessAgeMs < 0 || readinessAgeMs > maxReadinessAgeMs) { + return { + code: "readiness-stale", + message: "A node readiness report is outside the accepted observation window.", + }; + } + + if (report.status === "inconclusive") { + return { + code: "readiness-inconclusive", + message: "A node readiness report is inconclusive.", + }; + } + if ( + report.status !== "supported" || + report.exitCode !== 0 || + report.findings.some(({ severity }) => severity === "blocking" || severity === "fatal") + ) { + return { + code: "readiness-incompatible", + message: "A node readiness report is incompatible with this topology.", + }; + } + + const sparkQualifications = report.qualifications.filter( + (qualification) => qualification.id === "host.platform.dgx_spark", + ); + if (sparkQualifications.length !== 1 || sparkQualifications[0]?.status !== "qualified") { + return { + code: "spark-qualification-unavailable", + message: "A node does not have one qualified DGX Spark readiness result.", + }; + } + + return undefined; +} + +function validateNode( + node: ManagedClusterNodeObservation, + evaluatedAtMs: number, + maxReadinessAgeMs: number, +): QualifiedNode | QualificationFailure { + if (!SAFE_ID_PATTERN.test(node.nodeId)) { + return { + code: "node-identity-unavailable", + message: "A node identity is missing or invalid.", + }; + } + if (node.gpuIds.length !== 1 || !SAFE_ID_PATTERN.test(node.gpuIds[0] ?? "")) { + return { + code: "gpu-identity-unavailable", + message: "Each DGX Spark node must have exactly one valid GPU identity.", + }; + } + const readinessFailure = validateReadiness(node.readiness, evaluatedAtMs, maxReadinessAgeMs); + if (readinessFailure) return readinessFailure; + if (node.runtimeState === "conflict") { + return { + code: "runtime-conflict", + message: "An existing runtime conflicts with automatic managed cluster activation.", + }; + } + if (node.runtimeState !== "clear") { + return { + code: "runtime-state-unknown", + message: "The existing runtime state is unknown.", + }; + } + return { observation: node, gpuId: node.gpuIds[0]! }; +} + +function validAddress(address: string, prefixLength: number): boolean { + const version = net.isIP(address); + const maxPrefixLength = version === 4 ? 32 : version === 6 ? 128 : 0; + return ( + maxPrefixLength > 0 && + address !== "0.0.0.0" && + address !== "::" && + Number.isInteger(prefixLength) && + prefixLength > 0 && + prefixLength <= maxPrefixLength + ); +} + +function validateRail(rail: ManagedClusterRailObservation): ValidatedRail | QualificationFailure { + if ( + rail.adapter !== "connectx-7" || + rail.path !== "direct" || + rail.linkState !== "up" || + rail.connectivity !== "reachable" + ) { + return { + code: "fabric-degraded", + message: "The direct ConnectX-7 fabric is incomplete or degraded.", + }; + } + if ( + !SAFE_ID_PATTERN.test(rail.physicalPortId) || + !SAFE_INTERFACE_PATTERN.test(rail.netdev) || + !SAFE_INTERFACE_PATTERN.test(rail.hcaDevice) || + !Number.isInteger(rail.hcaPort) || + rail.hcaPort <= 0 || + rail.hcaPort > 255 || + !validAddress(rail.address, rail.prefixLength) || + net.isIP(rail.peerAddress) === 0 || + rail.address === rail.peerAddress || + !SAFE_ID_PATTERN.test(rail.peerNodeId) + ) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail identity or peer address is invalid.", + }; + } + const gid = rail.roceGid; + if ( + gid.state !== "resolved" || + !Number.isInteger(gid.index) || + (gid.index ?? -1) < 0 || + (gid.index ?? 4096) > 4095 || + typeof gid.value !== "string" || + net.isIP(gid.value) !== 6 || + gid.value === "::" + ) { + return { + code: "fabric-degraded", + message: "A ConnectX-7 rail does not have a resolved RoCE GID.", + }; + } + return { observation: rail, gid: { index: gid.index!, value: gid.value } }; +} + +function validateNodeRails( + node: ManagedClusterNodeObservation, +): readonly ValidatedRail[] | QualificationFailure { + if (node.rails.length < 2) { + return { + code: "fabric-degraded", + message: "One direct ConnectX-7 cable must expose two logical rails on each node.", + }; + } + if (node.rails.length > 2) { + return { + code: "fabric-multiple", + message: "More than one candidate ConnectX-7 cable topology was observed.", + }; + } + + const physicalPorts = new Set(node.rails.map(({ physicalPortId }) => physicalPortId)); + if (physicalPorts.size !== 1) { + return { + code: "fabric-multiple", + message: "The candidate logical rails belong to more than one physical port.", + }; + } + + const validated = node.rails.map((rail) => validateRail(rail)); + const validationFailure = validated.find((rail): rail is QualificationFailure => "code" in rail); + if (validationFailure) return validationFailure; + const rails = validated as ValidatedRail[]; + const uniqueNetdevs = new Set(rails.map(({ observation }) => observation.netdev)); + const uniqueHcas = new Set( + rails.map(({ observation }) => `${observation.hcaDevice}:${observation.hcaPort}`), + ); + const uniqueAddresses = new Set(rails.map(({ observation }) => observation.address)); + const uniqueGids = new Set( + rails.map(({ gid, observation }) => `${observation.hcaDevice}:${gid.index}:${gid.value}`), + ); + if ( + uniqueNetdevs.size !== 2 || + uniqueHcas.size !== 2 || + uniqueAddresses.size !== 2 || + uniqueGids.size !== 2 + ) { + return { + code: "fabric-mismatch", + message: "The two logical ConnectX-7 rails must have distinct interfaces and addresses.", + }; + } + return rails; +} + +function endpoint(nodeId: string, rail: ValidatedRail): ManagedClusterTopologyRailEndpoint { + const observation = rail.observation; + return { + nodeId, + netdev: observation.netdev, + hcaDevice: observation.hcaDevice, + hcaPort: observation.hcaPort, + address: observation.address, + prefixLength: observation.prefixLength, + peerAddress: observation.peerAddress, + roceGid: rail.gid, + }; +} + +function matchRails( + orderedNodes: readonly ManagedClusterNodeObservation[], +): readonly ManagedClusterTopologyRail[] | QualificationFailure { + const ranks = new Map(orderedNodes.map(({ nodeId }, rank) => [nodeId, rank])); + const validatedByNode = new Map(); + for (const node of orderedNodes) { + const validated = validateNodeRails(node); + if ("code" in validated) return validated; + validatedByNode.set(node.nodeId, validated); + } + + const candidates = orderedNodes.flatMap((node) => + validatedByNode.get(node.nodeId)!.map((rail) => ({ nodeId: node.nodeId, rail })), + ); + const used = new Set(); + const matches: Array<{ + leftNodeId: string; + left: ValidatedRail; + rightNodeId: string; + right: ValidatedRail; + }> = []; + const candidateKey = ({ nodeId, rail }: (typeof candidates)[number]) => + `${nodeId}\0${rail.observation.netdev}`; + + for (const candidate of candidates) { + if (used.has(candidateKey(candidate))) continue; + const observation = candidate.rail.observation; + const reciprocal = candidates.filter( + (other) => + other.nodeId === observation.peerNodeId && + other.rail.observation.peerNodeId === candidate.nodeId && + other.rail.observation.address === observation.peerAddress && + other.rail.observation.peerAddress === observation.address && + other.rail.observation.prefixLength === observation.prefixLength && + net.isIP(other.rail.observation.address) === net.isIP(observation.address), + ); + if (reciprocal.length !== 1) { + return { + code: "fabric-mismatch", + message: "Every ConnectX-7 rail must have one reciprocal endpoint in the cluster.", + }; + } + const peer = reciprocal[0]!; + const peerKey = candidateKey(peer); + if (used.has(peerKey)) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail pairing is ambiguous.", + }; + } + used.add(candidateKey(candidate)); + used.add(peerKey); + const candidateRank = ranks.get(candidate.nodeId)!; + const peerRank = ranks.get(peer.nodeId)!; + matches.push( + candidateRank < peerRank + ? { + leftNodeId: candidate.nodeId, + left: candidate.rail, + rightNodeId: peer.nodeId, + right: peer.rail, + } + : { + leftNodeId: peer.nodeId, + left: peer.rail, + rightNodeId: candidate.nodeId, + right: candidate.rail, + }, + ); + } + + if (used.size !== candidates.length) { + return { code: "fabric-mismatch", message: "The ConnectX-7 cluster graph is incomplete." }; + } + const endpointAddresses = new Set( + matches.flatMap(({ left, right }) => [left.observation.address, right.observation.address]), + ); + if (endpointAddresses.size !== candidates.length) { + return { + code: "fabric-mismatch", + message: "The ConnectX-7 rail endpoints must have distinct addresses.", + }; + } + + const adjacency = new Map(orderedNodes.map(({ nodeId }) => [nodeId, new Set()])); + for (const { leftNodeId, rightNodeId } of matches) { + adjacency.get(leftNodeId)!.add(rightNodeId); + adjacency.get(rightNodeId)!.add(leftNodeId); + } + const visited = new Set(); + const queue = [orderedNodes[0]!.nodeId]; + while (queue.length > 0) { + const nodeId = queue.shift()!; + if (visited.has(nodeId)) continue; + visited.add(nodeId); + queue.push(...adjacency.get(nodeId)!); + } + if (visited.size !== orderedNodes.length) { + return { code: "fabric-mismatch", message: "The ConnectX-7 cluster graph is disconnected." }; + } + + matches.sort( + (left, right) => + ranks.get(left.leftNodeId)! - ranks.get(right.leftNodeId)! || + compareStrings(left.left.observation.netdev, right.left.observation.netdev) || + ranks.get(left.rightNodeId)! - ranks.get(right.rightNodeId)!, + ); + return matches.map(({ leftNodeId, left, rightNodeId, right }, index) => ({ + index, + endpoints: [endpoint(leftNodeId, left), endpoint(rightNodeId, right)], + })); +} + +function validSshTarget(target: string): boolean { + if (target.length === 0 || target.length > 286 || target !== target.trim()) return false; + const parts = target.split("@"); + if (parts.length > 2) return false; + const host = parts.at(-1) ?? ""; + const username = parts.length === 2 ? parts[0] : undefined; + return ( + (username === undefined || SSH_USERNAME_PATTERN.test(username)) && + (net.isIP(host) === 4 || SSH_HOST_PATTERN.test(host)) + ); +} + +function validateSshBinding( + binding: ManagedClusterSshBindingObservation, + localNodeId: string, + peerNodeId: string, +): QualificationFailure | undefined { + if ( + binding.state !== "pretrusted" || + binding.fromNodeId !== localNodeId || + binding.toNodeId !== peerNodeId || + !validSshTarget(binding.peerTarget) || + !SAFE_BINDING_HANDLE_PATTERN.test(binding.handle) + ) { + return { + code: "ssh-binding-unavailable", + message: "The peer does not have a valid pretrusted SSH binding.", + }; + } + return undefined; +} + +function record(value: unknown): Record | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function artifactEndpointError(value: unknown, expectedNodeId: string): string | undefined { + const candidate = record(value); + const gid = record(candidate?.roceGid); + if ( + !candidate || + candidate.nodeId !== expectedNodeId || + typeof candidate.netdev !== "string" || + !SAFE_INTERFACE_PATTERN.test(candidate.netdev) || + typeof candidate.hcaDevice !== "string" || + !SAFE_INTERFACE_PATTERN.test(candidate.hcaDevice) || + !Number.isInteger(candidate.hcaPort) || + (candidate.hcaPort as number) <= 0 || + (candidate.hcaPort as number) > 255 || + typeof candidate.address !== "string" || + typeof candidate.prefixLength !== "number" || + !validAddress(candidate.address, candidate.prefixLength) || + typeof candidate.peerAddress !== "string" || + net.isIP(candidate.peerAddress) !== net.isIP(candidate.address) || + candidate.peerAddress === candidate.address || + !gid || + !Number.isInteger(gid.index) || + (gid.index as number) < 0 || + (gid.index as number) > 4095 || + typeof gid.value !== "string" || + net.isIP(gid.value) !== 6 || + gid.value === "::" + ) { + return `the ${expectedNodeId} rail endpoint is invalid`; + } + return undefined; +} + +function topologyOutputError( + value: unknown, + subjectNodeIds: readonly string[], +): string | undefined { + const output = record(value); + if (!output) return "topology qualification output is invalid"; + const controllerNodeId = output.controllerNodeId; + if (typeof controllerNodeId !== "string" || !SAFE_ID_PATTERN.test(controllerNodeId)) { + return "topology controller node is invalid"; + } + if (!Array.isArray(output.nodes) || output.nodes.length !== subjectNodeIds.length) { + return "topology nodes are invalid"; + } + const nodes = output.nodes.map(record); + if (nodes.some((node) => !node)) return "topology nodes are invalid"; + const typedNodes = nodes as Record[]; + const nodeIds = typedNodes.map(({ nodeId }) => nodeId); + const gpuIds = typedNodes.map(({ gpuId }) => gpuId); + if ( + typedNodes.some( + (node, rank) => + node.rank !== rank || + node.role !== (rank === 0 ? "head" : "worker") || + typeof node.nodeId !== "string" || + !SAFE_ID_PATTERN.test(node.nodeId) || + typeof node.gpuId !== "string" || + !SAFE_ID_PATTERN.test(node.gpuId), + ) || + nodeIds[0] !== controllerNodeId || + new Set(nodeIds).size !== nodeIds.length || + new Set(gpuIds).size !== gpuIds.length || + [...(nodeIds as string[])] + .sort(compareStrings) + .some((nodeId, index) => nodeId !== subjectNodeIds[index]) + ) { + return "topology node roles or GPU identities are invalid"; + } + + if (!Array.isArray(output.rails) || output.rails.length !== typedNodes.length) { + return "topology rails are invalid"; + } + const rails: ManagedClusterTopologyRail[] = []; + const endpointCounts = new Map((nodeIds as string[]).map((nodeId) => [nodeId, 0])); + const endpointNetdevs = new Map( + (nodeIds as string[]).map((nodeId) => [nodeId, new Set()]), + ); + const endpointAddresses = new Set(); + const adjacency = new Map((nodeIds as string[]).map((nodeId) => [nodeId, new Set()])); + for (const [index, candidate] of output.rails.entries()) { + const rail = record(candidate); + if ( + !rail || + rail.index !== index || + !Array.isArray(rail.endpoints) || + rail.endpoints.length !== 2 + ) { + return "topology rail indexes or endpoints are invalid"; + } + const endpoints = rail.endpoints.map(record); + const leftNodeId = endpoints[0]?.nodeId; + const rightNodeId = endpoints[1]?.nodeId; + if ( + typeof leftNodeId !== "string" || + typeof rightNodeId !== "string" || + leftNodeId === rightNodeId || + !endpointCounts.has(leftNodeId) || + !endpointCounts.has(rightNodeId) + ) { + return "topology rail node identities are invalid"; + } + const leftError = artifactEndpointError(rail.endpoints[0], leftNodeId); + const rightError = artifactEndpointError(rail.endpoints[1], rightNodeId); + if (leftError || rightError) return leftError ?? rightError; + const typedRail = rail as unknown as ManagedClusterTopologyRail; + const [left, right] = typedRail.endpoints; + if ( + left.address !== right.peerAddress || + right.address !== left.peerAddress || + left.prefixLength !== right.prefixLength + ) { + return "topology rail addresses are not reciprocal"; + } + endpointCounts.set(leftNodeId, endpointCounts.get(leftNodeId)! + 1); + endpointCounts.set(rightNodeId, endpointCounts.get(rightNodeId)! + 1); + endpointNetdevs.get(leftNodeId)!.add(left.netdev); + endpointNetdevs.get(rightNodeId)!.add(right.netdev); + endpointAddresses.add(left.address); + endpointAddresses.add(right.address); + adjacency.get(leftNodeId)!.add(rightNodeId); + adjacency.get(rightNodeId)!.add(leftNodeId); + rails.push(typedRail); + } + if ( + [...endpointCounts.values()].some((count) => count !== 2) || + [...endpointNetdevs.values()].some((netdevs) => netdevs.size !== 2) || + endpointAddresses.size !== rails.length * 2 + ) { + return "topology rail identities are not distinct"; + } + const visited = new Set(); + const queue = [controllerNodeId]; + while (queue.length > 0) { + const nodeId = queue.shift()!; + if (visited.has(nodeId)) continue; + visited.add(nodeId); + queue.push(...adjacency.get(nodeId)!); + } + if (visited.size !== typedNodes.length) return "topology rail graph is disconnected"; + const controllerAddresses = rails.flatMap(({ endpoints }) => + endpoints.filter(({ nodeId }) => nodeId === controllerNodeId).map(({ address }) => address), + ); + if ( + typeof output.masterAddress !== "string" || + !controllerAddresses.includes(output.masterAddress) + ) { + return "topology master address does not belong to the controller node"; + } + + if (!Array.isArray(output.peers) || output.peers.length !== typedNodes.length - 1) { + return "topology peer binding is invalid"; + } + const workerNodeIds = new Set((nodeIds as string[]).slice(1)); + const boundNodeIds = new Set(); + for (const candidate of output.peers) { + const peer = record(candidate); + if ( + !peer || + typeof peer.nodeId !== "string" || + !workerNodeIds.has(peer.nodeId) || + boundNodeIds.has(peer.nodeId) || + typeof peer.target !== "string" || + !validSshTarget(peer.target) || + typeof peer.sshBindingHandle !== "string" || + !SAFE_BINDING_HANDLE_PATTERN.test(peer.sshBindingHandle) + ) { + return "topology peer binding is invalid"; + } + boundNodeIds.add(peer.nodeId); + } + return undefined; +} + +export function managedClusterTopologySubjectDigest(subjectNodeIds: readonly string[]): string { + return managedInferenceDigest([...subjectNodeIds].sort(compareStrings)); +} + +export function managedClusterTopologyOutputDigest(output: ManagedClusterTopologyOutput): string { + return managedInferenceDigest(output); +} + +export function getManagedClusterTopologyArtifactError( + artifact: ManagedInferenceTopologyQualification, + expectedSubjectNodeIds?: readonly string[], +): string | undefined { + if ( + artifact.id !== MANAGED_CLUSTER_TOPOLOGY_ID || + artifact.schemaVersion !== MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION + ) { + return "topology qualification identity is incompatible"; + } + if (artifact.status !== "qualified") return "topology qualification is not qualified"; + if (!Array.isArray(artifact.subjectNodeIds)) return "topology qualification subject is invalid"; + const subjectNodeIds = [...artifact.subjectNodeIds]; + if ( + subjectNodeIds.length < 2 || + subjectNodeIds.length > 1024 || + new Set(subjectNodeIds).size !== subjectNodeIds.length || + subjectNodeIds.some((nodeId) => !SAFE_ID_PATTERN.test(nodeId)) || + subjectNodeIds.some((nodeId, index) => index > 0 && subjectNodeIds[index - 1]! >= nodeId) + ) { + return "topology qualification subject is invalid"; + } + if ( + expectedSubjectNodeIds && + subjectNodeIds.some((nodeId, index) => nodeId !== expectedSubjectNodeIds[index]) + ) { + return "topology qualification subject does not match the readiness reports"; + } + + const outputError = topologyOutputError(artifact.output, subjectNodeIds); + if (outputError) return outputError; + try { + if (artifact.subjectDigest !== managedClusterTopologySubjectDigest(subjectNodeIds)) { + return "topology qualification subject digest does not match its subject"; + } + if ( + artifact.outputDigest !== + managedClusterTopologyOutputDigest(artifact.output as ManagedClusterTopologyOutput) + ) { + return "topology qualification output digest does not match its output"; + } + } catch { + return "topology qualification digest is invalid"; + } + return undefined; +} + +export function qualifyManagedClusterTopology( + input: Readonly, +): ManagedClusterTopologyQualificationResult { + if (input.peers.length < 1 || input.peers.length > 1023) { + return failure(input.intent, { + code: "peer-count", + message: "Managed cluster activation requires between one and 1023 discovered peers.", + }); + } + + const evaluatedAtMs = validateQualificationPolicy(input.evaluatedAt, input.maxReadinessAgeMs); + if (typeof evaluatedAtMs !== "number") return failure(input.intent, evaluatedAtMs); + + const orderedObservations = [ + input.local, + ...[...input.peers].sort((left, right) => compareStrings(left.nodeId, right.nodeId)), + ]; + const qualifiedNodes: QualifiedNode[] = []; + for (const observation of orderedObservations) { + const qualified = validateNode(observation, evaluatedAtMs, input.maxReadinessAgeMs); + if ("code" in qualified) return failure(input.intent, qualified); + qualifiedNodes.push(qualified); + } + const nodeIds = orderedObservations.map(({ nodeId }) => nodeId); + if (new Set(nodeIds).size !== nodeIds.length) { + return failure(input.intent, { + code: "duplicate-node-identity", + message: "The managed cluster observations contain a duplicate node identity.", + }); + } + const gpuIds = qualifiedNodes.map(({ gpuId }) => gpuId); + if (new Set(gpuIds).size !== gpuIds.length) { + return failure(input.intent, { + code: "duplicate-gpu-identity", + message: "The managed cluster observations contain a duplicate GPU identity.", + }); + } + + for (const peer of input.peers) { + const sshFailure = validateSshBinding(peer.sshBinding, input.local.nodeId, peer.nodeId); + if (sshFailure) return failure(input.intent, sshFailure); + } + const rails = matchRails(orderedObservations); + if ("code" in rails) return failure(input.intent, rails); + const controllerEndpoint = rails + .flatMap(({ endpoints }) => endpoints) + .filter(({ nodeId }) => nodeId === input.local.nodeId) + .sort((left, right) => compareStrings(left.netdev, right.netdev))[0]; + if (!controllerEndpoint) { + return failure(input.intent, { + code: "fabric-mismatch", + message: "The managed cluster controller has no qualified fabric endpoint.", + }); + } + + const output: ManagedClusterTopologyOutput = { + controllerNodeId: input.local.nodeId, + nodes: qualifiedNodes.map(({ observation, gpuId }, rank) => ({ + nodeId: observation.nodeId, + gpuId, + rank, + role: rank === 0 ? "head" : "worker", + })), + rails, + masterAddress: controllerEndpoint.address, + peers: orderedObservations.slice(1).map((observation) => { + const peer = observation as ManagedClusterPeerObservation; + return { + nodeId: peer.nodeId, + target: peer.sshBinding.peerTarget, + sshBindingHandle: peer.sshBinding.handle, + }; + }), + }; + const subjectNodeIds = [...nodeIds].sort(compareStrings); + try { + return { + outcome: "qualified", + artifact: { + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + status: "qualified", + subjectNodeIds, + subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), + outputDigest: managedClusterTopologyOutputDigest(output), + output, + }, + }; + } catch { + return failure(input.intent, { + code: "artifact-digest-failed", + message: "The qualified topology could not be bound to its subject and output.", + }); + } +} diff --git a/src/lib/inference/serving/managed-runtime-receipts.ts b/src/lib/inference/serving/managed-runtime-receipts.ts index 63557f81590..a98a4655b19 100644 --- a/src/lib/inference/serving/managed-runtime-receipts.ts +++ b/src/lib/inference/serving/managed-runtime-receipts.ts @@ -9,22 +9,26 @@ import { listGatewayStateRoots } from "../../state/gateway-registry"; import { managedVllmStateDir } from "../vllm-api-key"; import { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../vllm-station-runtime-receipt-path"; import { - DUAL_SPARK_MANAGED_SERVING_STATE_FILE, - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, -} from "./spark-runtime-receipt-path"; + isManagedClusterDiscoveryBindingStateEntry, + isManagedClusterRuntimeBindingStateEntry, + MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE, + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, +} from "./managed-cluster-runtime-receipt-path"; export { MCP_LIFECYCLE_LOCK_DIRNAME } from "../../state/mcp-lifecycle-lock-storage"; export { MANAGED_VLLM_API_KEY_FILE } from "../vllm-api-key"; export { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../vllm-station-runtime-receipt-path"; export { - DUAL_SPARK_MANAGED_SERVING_STATE_FILE, - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, -} from "./spark-runtime-receipt-path"; + isManagedClusterDiscoveryBindingStateEntry, + isManagedClusterRuntimeBindingStateEntry, + MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE, + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, +} from "./managed-cluster-runtime-receipt-path"; export interface ManagedDistributedVllmRuntimeReceipts { - readonly sparkBindingPath: string | null; - readonly sparkDiscoveryBindingPaths: readonly string[]; - readonly sparkPath: string | null; + readonly managedClusterBindingPaths: readonly string[]; + readonly managedClusterDiscoveryBindingPaths: readonly string[]; + readonly managedClusterPath: string | null; readonly stationBindingPaths: readonly string[]; readonly stationPaths: readonly string[]; } @@ -39,27 +43,53 @@ function pathExistsNoFollow(filePath: string): boolean { } } +function matchingStateEntries( + stateRoots: readonly { readonly root: string }[], + predicate: (entry: string) => boolean, +): readonly string[] { + return stateRoots + .flatMap(({ root }) => { + try { + return fs + .readdirSync(root) + .filter(predicate) + .map((entry) => path.join(root, entry)); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + }) + .sort(); +} + /** Locate durable distributed-runtime ownership without parsing or following receipt paths. */ export function findManagedDistributedVllmRuntimeReceipts( options: { readonly homeDir?: string } = {}, ): ManagedDistributedVllmRuntimeReceipts { const homeDir = options.homeDir ?? os.homedir(); const stateRoots = listGatewayStateRoots(homeDir); - const sparkPath = path.join(managedVllmStateDir(homeDir), DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE); + const managedClusterPath = path.join( + managedVllmStateDir(homeDir), + MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, + ); const stationPaths = stateRoots .map(({ root }) => path.join(root, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE)) .filter(pathExistsNoFollow); - const sparkBindingPath = `${sparkPath}.ssh-binding`; - const sparkDiscoveryBindingPaths = stateRoots - .map(({ root }) => `${path.join(root, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)}.ssh-binding`) - .filter(pathExistsNoFollow); + const managedClusterBindingPaths = matchingStateEntries( + stateRoots, + isManagedClusterRuntimeBindingStateEntry, + ); + const managedClusterDiscoveryBindingPaths = matchingStateEntries( + stateRoots, + isManagedClusterDiscoveryBindingStateEntry, + ); const stationBindingPaths = stateRoots .map(({ root }) => `${path.join(root, DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE)}.ssh-binding`) .filter(pathExistsNoFollow); return { - sparkBindingPath: pathExistsNoFollow(sparkBindingPath) ? sparkBindingPath : null, - sparkDiscoveryBindingPaths, - sparkPath: pathExistsNoFollow(sparkPath) ? sparkPath : null, + managedClusterBindingPaths, + managedClusterDiscoveryBindingPaths, + managedClusterPath: pathExistsNoFollow(managedClusterPath) ? managedClusterPath : null, stationBindingPaths, stationPaths, }; @@ -71,9 +101,9 @@ export function assertNoManagedDistributedVllmRuntimeReceipts( ): void { const receipts = findManagedDistributedVllmRuntimeReceipts(options); const paths = [ - ...(receipts.sparkPath ? [receipts.sparkPath] : []), - ...(receipts.sparkBindingPath ? [receipts.sparkBindingPath] : []), - ...receipts.sparkDiscoveryBindingPaths, + ...(receipts.managedClusterPath ? [receipts.managedClusterPath] : []), + ...receipts.managedClusterBindingPaths, + ...receipts.managedClusterDiscoveryBindingPaths, ...receipts.stationPaths, ...receipts.stationBindingPaths, ]; diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 15811557221..02b35a705ab 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -15,13 +15,13 @@ import type { ManagedInferenceTopologyQualification, } from "./catalog-types.js"; import { - FIXTURE_DUAL_SPARK_PRESET_ID, - fixtureDualSparkSelection, -} from "./dual-spark-fixture.test-support.js"; + FIXTURE_MANAGED_CLUSTER_PRESET_ID, + fixtureManagedClusterSelection, +} from "./managed-cluster-fixture.test-support.js"; import { - type DualSparkTopologyOutput, - dualSparkTopologyOutputDigest, -} from "./dual-spark-topology.js"; + type ManagedClusterTopologyOutput, + managedClusterTopologyOutputDigest, +} from "./managed-cluster-topology.js"; import { resolveManagedInferenceServing } from "./resolver.js"; const NOW = new Date("2026-08-02T18:00:00.000Z"); @@ -35,7 +35,7 @@ function shippedCompiledPreset( catalog = shippedCatalog(), ): CompiledManagedInferenceCatalog["presets"][number] { const preset = catalog.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, + ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, ); expect(preset).toBeDefined(); return preset as CompiledManagedInferenceCatalog["presets"][number]; @@ -135,15 +135,15 @@ function readinessSources(): ManagedInferenceReadinessSource[] { } function topology( - overrides: Partial> = {}, -): ManagedInferenceTopologyQualification { - const artifact = structuredClone(fixtureDualSparkSelection().topologyQualification); + overrides: Partial> = {}, +): ManagedInferenceTopologyQualification { + const artifact = structuredClone(fixtureManagedClusterSelection().topologyQualification); return { ...artifact, ...overrides }; } function resolverInput( - overrides: Partial> = {}, -): ManagedInferenceResolverInput { + overrides: Partial> = {}, +): ManagedInferenceResolverInput { return { readinessReports: readinessSources(), topologyQualifications: [topology()], @@ -644,7 +644,7 @@ describe("managed inference resolver", () => { it("rejects an internally inconsistent topology with a recomputed output digest", () => { const artifact = topology(); (artifact.output as { masterAddress: string }).masterAddress = "192.168.100.99"; - (artifact as { outputDigest: string }).outputDigest = dualSparkTopologyOutputDigest( + (artifact as { outputDigest: string }).outputDigest = managedClusterTopologyOutputDigest( artifact.output, ); diff --git a/src/lib/inference/serving/spark-runtime-receipt-path.ts b/src/lib/inference/serving/spark-runtime-receipt-path.ts deleted file mode 100644 index ca99cb91d89..00000000000 --- a/src/lib/inference/serving/spark-runtime-receipt-path.ts +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -export const DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE = "dual-spark-vllm-runtime.json"; -export const DUAL_SPARK_MANAGED_SERVING_STATE_FILE = "dual-spark-managed-serving.json"; diff --git a/src/lib/inference/serving/spark-runtime-receipt.ts b/src/lib/inference/serving/spark-runtime-receipt.ts deleted file mode 100644 index 86db3a53be3..00000000000 --- a/src/lib/inference/serving/spark-runtime-receipt.ts +++ /dev/null @@ -1,588 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import path from "node:path"; - -import { ensureLocalAdapterStateDir } from "../local-adapter-lifecycle"; -import { loadManagedVllmApiKey, managedVllmStateDir } from "../vllm-api-key"; -import { - clearDualStationSshBinding, - copyDualStationSshBinding, - type DualStationSshBinding, - encodeDualStationSshBindingHandoff, - loadDualStationSshBindingForStatePath, - loadDualStationSshBindingHandoff, -} from "../vllm-station-ssh-binding"; -import { managedInferenceHexDigest } from "./catalog-integrity"; -import { - assertDualSparkVllmExecutorConfig, - createDualSparkVllmExecutor, - type DualSparkVllmNodeSnapshots, - inspectDualSparkVllmNodesSync, -} from "./dual-spark-executor"; -import { - classifyDualSparkExistingState, - cleanupDualSparkManagedVllm, - type DualSparkVllmLifecycleDeps, - dualSparkVllmApiKeyFingerprint, -} from "./dual-spark-lifecycle"; -import type { DualSparkVllmPlan } from "./dual-spark-materialize"; -import { - DUAL_SPARK_MANAGED_SERVING_STATE_FILE, - DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE, -} from "./spark-runtime-receipt-path"; - -const MAX_RECEIPT_BYTES = 128 * 1024; -const SHA256 = /^[a-f0-9]{64}$/; -const CONTAINER_ID = /^[a-f0-9]{64}$/; -const BINDING_HANDLE = /^[A-Za-z0-9_-]{1,8192}$/; -const RECEIPT_KEYS = [ - "apiKeyFingerprint", - "discoveryBindingDigest", - "headContainerId", - "localCacheRoot", - "peerCacheRoot", - "plan", - "planDigest", - "schemaVersion", - "sshBinding", - "workerContainerId", -] as const; -const EXACT_BINDING_KEYS = [ - "schemaVersion", - "peerTarget", - "resolvedHost", - "sshUser", - "port", - "lookupHost", - "hostKeyDigest", - "dockerCliFile", - "dockerShimFile", - "dockerShimSha256", - "knownHostsFile", - "knownHostsSha256", - "bindingFile", - "sshWrapperDirectory", - "sshWrapperFile", - "sshWrapperSha256", -] as const satisfies readonly (keyof DualStationSshBinding)[]; - -interface PersistedReceipt { - readonly schemaVersion: 1; - readonly plan: DualSparkVllmPlan; - readonly planDigest: string; - readonly sshBinding: string; - readonly discoveryBindingDigest: string; - readonly localCacheRoot: string; - readonly peerCacheRoot: string; - readonly apiKeyFingerprint: string; - readonly headContainerId: string; - readonly workerContainerId: string; -} - -export interface PersistDualSparkVllmRuntimeReceiptInput { - readonly plan: DualSparkVllmPlan; - readonly peerSshBinding: DualStationSshBinding; - readonly localCacheRoot: string; - readonly peerCacheRoot: string; - readonly apiKeyFingerprint: string; - readonly headContainerId: string; - readonly workerContainerId: string; -} - -export interface LoadedDualSparkVllmRuntime { - readonly plan: DualSparkVllmPlan; - readonly peerSshBinding: DualStationSshBinding; - readonly sshBinding: string; - readonly discoveryBindingDigest: string; - readonly localCacheRoot: string; - readonly peerCacheRoot: string; - readonly apiKeyFingerprint: string; - readonly headContainerId: string; - readonly workerContainerId: string; -} - -type CleanupDeps = Pick< - DualSparkVllmLifecycleDeps, - "inspectNode" | "removeContainer" | "withLifecycleLock" ->; - -export interface DualSparkVllmRuntimeReceiptOptions { - readonly stateDir?: string; - /** @internal Test seam. */ - readonly loadApiKey?: () => string | null; - /** @internal Test seam. */ - readonly createLifecycleDeps?: (runtime: LoadedDualSparkVllmRuntime) => CleanupDeps; - /** @internal Test seam. */ - readonly inspectNodesSync?: (runtime: LoadedDualSparkVllmRuntime) => DualSparkVllmNodeSnapshots; -} - -export interface RecoveredDualSparkVllmEndpoint { - readonly baseUrl: string; - readonly apiKey: string; - readonly apiKeyFingerprint: string; - readonly plan: DualSparkVllmPlan; -} - -export type DualSparkVllmRuntimeCleanupResult = - | { readonly kind: "not-installed" } - | { readonly kind: "removed"; readonly removedContainerIds: readonly string[] }; - -export function dualSparkVllmRuntimeReceiptPath(stateDir = managedVllmStateDir()): string { - return path.join(stateDir, DUAL_SPARK_VLLM_RUNTIME_RECEIPT_FILE); -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function exactKeys( - value: Record, - expected: readonly string[], - label: string, -): void { - const actual = Object.keys(value).sort(); - const sorted = [...expected].sort(); - if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) { - throw new Error(`${label} fields are invalid`); - } -} - -function requireString(value: unknown, label: string, pattern: RegExp, maximum = 8192): string { - if ( - typeof value !== "string" || - value.length === 0 || - value.length > maximum || - value !== value.trim() || - !pattern.test(value) - ) { - throw new Error(`${label} is invalid`); - } - return value; -} - -function requireAbsolutePath(value: unknown, label: string): string { - const candidate = requireString(value, label, /^[^\u0000-\u001f\u007f]+$/, 4096); - if (!path.posix.isAbsolute(candidate) || path.posix.normalize(candidate) !== candidate) { - throw new Error(`${label} must be a normalized absolute POSIX path`); - } - return candidate; -} - -function planDigest(plan: DualSparkVllmPlan): string { - return managedInferenceHexDigest(plan); -} - -function workerTarget(plan: DualSparkVllmPlan): string { - const roles = isRecord(plan.roles) ? plan.roles : null; - const worker = roles && isRecord(roles.worker) ? roles.worker : null; - const execution = worker && isRecord(worker.execution) ? worker.execution : null; - if (!execution || execution.kind !== "ssh") { - throw new Error("Dual-Spark worker SSH execution is invalid"); - } - return requireString( - execution.expectedTarget, - "dual-Spark worker SSH target", - /^(?:[A-Za-z_][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/, - 286, - ); -} - -function assertExecutorContract( - plan: DualSparkVllmPlan, - peerSshBinding: DualStationSshBinding, - localCacheRoot: string, - peerCacheRoot: string, -): void { - assertDualSparkVllmExecutorConfig({ - plan, - peerSshBinding, - localCacheRoot, - peerCacheRoot, - }); -} - -function parseReceipt(value: unknown): PersistedReceipt { - if (!isRecord(value)) throw new Error("Dual-Spark vLLM runtime receipt is invalid"); - exactKeys(value, RECEIPT_KEYS, "Dual-Spark vLLM runtime receipt"); - if (value.schemaVersion !== 1 || !isRecord(value.plan)) { - throw new Error("Dual-Spark vLLM runtime receipt schema is unsupported"); - } - const plan = value.plan as unknown as DualSparkVllmPlan; - const digest = requireString(value.planDigest, "dual-Spark plan digest", SHA256, 64); - if (planDigest(plan) !== digest) throw new Error("Dual-Spark vLLM runtime plan digest changed"); - const headContainerId = requireString( - value.headContainerId, - "dual-Spark head container ID", - CONTAINER_ID, - 64, - ); - const workerContainerId = requireString( - value.workerContainerId, - "dual-Spark worker container ID", - CONTAINER_ID, - 64, - ); - if (headContainerId === workerContainerId) { - throw new Error("Dual-Spark container identities are ambiguous"); - } - return { - schemaVersion: 1, - plan, - planDigest: digest, - sshBinding: requireString(value.sshBinding, "dual-Spark SSH binding", BINDING_HANDLE), - discoveryBindingDigest: requireString( - value.discoveryBindingDigest, - "dual-Spark discovery SSH binding digest", - SHA256, - 64, - ), - localCacheRoot: requireAbsolutePath(value.localCacheRoot, "dual-Spark local cache root"), - peerCacheRoot: requireAbsolutePath(value.peerCacheRoot, "dual-Spark peer cache root"), - apiKeyFingerprint: requireString( - value.apiKeyFingerprint, - "dual-Spark API key fingerprint", - SHA256, - 64, - ), - headContainerId, - workerContainerId, - }; -} - -function assertPrivateReceipt(stat: fs.Stats, filePath: string): void { - if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) { - throw new Error(`Dual-Spark vLLM runtime receipt must be a private regular file: ${filePath}`); - } - if (typeof process.getuid === "function" && stat.uid !== process.getuid()) { - throw new Error(`Dual-Spark vLLM runtime receipt has the wrong owner: ${filePath}`); - } -} - -function loadPersistedReceipt(stateDir: string): PersistedReceipt | null { - const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); - if (typeof fs.constants.O_NOFOLLOW !== "number") { - throw new Error("Secure no-follow file opens are unavailable on this platform"); - } - let fd: number | undefined; - try { - try { - fd = fs.openSync( - filePath, - fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | (fs.constants.O_NONBLOCK ?? 0), - ); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === "ENOENT") return null; - if (code === "ELOOP") { - throw new Error(`Refusing to read dual-Spark runtime receipt through a symbolic link`); - } - throw error; - } - const stat = fs.fstatSync(fd); - assertPrivateReceipt(stat, filePath); - if (stat.size < 2 || stat.size > MAX_RECEIPT_BYTES) { - throw new Error(`Dual-Spark vLLM runtime receipt is malformed: ${filePath}`); - } - return parseReceipt(JSON.parse(fs.readFileSync(fd, "utf8"))); - } catch (error) { - if (error instanceof SyntaxError) { - throw new Error(`Dual-Spark vLLM runtime receipt is malformed: ${filePath}`); - } - throw error; - } finally { - if (fd !== undefined) fs.closeSync(fd); - } -} - -function fsyncDirectory(directory: string): void { - const fd = fs.openSync(directory, fs.constants.O_RDONLY); - try { - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } -} - -function writeReceipt(receipt: PersistedReceipt, stateDir: string): void { - ensureLocalAdapterStateDir(stateDir); - const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); - const temporary = `${filePath}.tmp-${String(process.pid)}-${Date.now().toString(16)}`; - let fd: number | undefined; - try { - fd = fs.openSync( - temporary, - fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, - 0o600, - ); - assertPrivateReceipt(fs.fstatSync(fd), temporary); - fs.writeFileSync(fd, `${JSON.stringify(receipt)}\n`, "utf8"); - fs.fsyncSync(fd); - fs.closeSync(fd); - fd = undefined; - fs.renameSync(temporary, filePath); - fsyncDirectory(stateDir); - } catch (error) { - if (fd !== undefined) { - try { - fs.closeSync(fd); - } catch { - // Preserve the receipt-write failure. - } - } - try { - fs.unlinkSync(temporary); - } catch { - // A leftover unique temporary file must not mask the receipt-write failure. - } - throw error; - } -} - -function durablePlan(plan: DualSparkVllmPlan, sshBinding: string): DualSparkVllmPlan { - if (plan.roles.worker.execution.kind !== "ssh") { - throw new Error("Dual-Spark worker SSH execution is invalid"); - } - return { - ...plan, - roles: { - ...plan.roles, - worker: { - ...plan.roles.worker, - execution: { ...plan.roles.worker.execution, bindingHandle: sshBinding }, - }, - }, - }; -} - -function loadedRuntime(receipt: PersistedReceipt): LoadedDualSparkVllmRuntime { - const binding = loadDualStationSshBindingHandoff(receipt.sshBinding, workerTarget(receipt.plan)); - if (encodeDualStationSshBindingHandoff(binding) !== receipt.sshBinding) { - throw new Error("Dual-Spark runtime SSH binding identity changed"); - } - assertExecutorContract(receipt.plan, binding, receipt.localCacheRoot, receipt.peerCacheRoot); - return { ...receipt, peerSshBinding: binding }; -} - -function bindingDigest(binding: DualStationSshBinding): string { - return managedInferenceHexDigest( - Object.fromEntries(EXACT_BINDING_KEYS.map((field) => [field, binding[field]])), - ); -} - -function loadReceiptOwnedDiscoveryBinding( - stateDir: string, - runtime: LoadedDualSparkVllmRuntime, -): DualStationSshBinding | null { - const binding = loadDualStationSshBindingForStatePath( - path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE), - runtime.peerSshBinding.peerTarget, - runtime.peerSshBinding.hostKeyDigest, - ); - if (binding && bindingDigest(binding) !== runtime.discoveryBindingDigest) { - throw new Error("Dual-Spark discovery SSH binding does not match the runtime receipt identity"); - } - return binding; -} - -export function loadDualSparkVllmRuntimeReceipt( - options: Pick = {}, -): LoadedDualSparkVllmRuntime | null { - const receipt = loadPersistedReceipt(options.stateDir ?? managedVllmStateDir()); - return receipt ? loadedRuntime(receipt) : null; -} - -function sameInput( - existing: LoadedDualSparkVllmRuntime, - input: PersistDualSparkVllmRuntimeReceiptInput, -): boolean { - return ( - planDigest(durablePlan(input.plan, existing.sshBinding)) === planDigest(existing.plan) && - input.peerSshBinding.peerTarget === existing.peerSshBinding.peerTarget && - input.peerSshBinding.hostKeyDigest === existing.peerSshBinding.hostKeyDigest && - input.peerSshBinding.resolvedHost === existing.peerSshBinding.resolvedHost && - input.peerSshBinding.sshUser === existing.peerSshBinding.sshUser && - input.peerSshBinding.port === existing.peerSshBinding.port && - bindingDigest(input.peerSshBinding) === existing.discoveryBindingDigest && - input.localCacheRoot === existing.localCacheRoot && - input.peerCacheRoot === existing.peerCacheRoot && - input.apiKeyFingerprint === existing.apiKeyFingerprint && - input.headContainerId === existing.headContainerId && - input.workerContainerId === existing.workerContainerId - ); -} - -/** Persist immutable ownership and pinned transport state for recovery/uninstall. */ -export function persistDualSparkVllmRuntimeReceipt( - input: PersistDualSparkVllmRuntimeReceiptInput, - options: Pick = {}, -): LoadedDualSparkVllmRuntime { - const stateDir = options.stateDir ?? managedVllmStateDir(); - ensureLocalAdapterStateDir(stateDir); - requireString(input.apiKeyFingerprint, "dual-Spark API key fingerprint", SHA256, 64); - requireString(input.headContainerId, "dual-Spark head container ID", CONTAINER_ID, 64); - requireString(input.workerContainerId, "dual-Spark worker container ID", CONTAINER_ID, 64); - if (input.headContainerId === input.workerContainerId) { - throw new Error("Dual-Spark container identities are ambiguous"); - } - assertExecutorContract( - input.plan, - input.peerSshBinding, - input.localCacheRoot, - input.peerCacheRoot, - ); - - const existing = loadDualSparkVllmRuntimeReceipt({ stateDir }); - if (existing) { - if (!sameInput(existing, input)) { - throw new Error("A different managed dual-Spark runtime receipt already owns recovery state"); - } - return existing; - } - - const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); - const bindingPath = `${receiptPath}.ssh-binding`; - try { - fs.mkdirSync(bindingPath, { mode: 0o700 }); - fsyncDirectory(stateDir); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "EEXIST") { - throw new Error(`Managed dual-Spark SSH binding state already exists: ${bindingPath}`); - } - throw error; - } - try { - const runtimeBinding = copyDualStationSshBinding(receiptPath, input.peerSshBinding); - const sshBinding = encodeDualStationSshBindingHandoff(runtimeBinding); - const plan = durablePlan(input.plan, sshBinding); - assertExecutorContract(plan, runtimeBinding, input.localCacheRoot, input.peerCacheRoot); - const receipt: PersistedReceipt = { - schemaVersion: 1, - plan, - planDigest: planDigest(plan), - sshBinding, - discoveryBindingDigest: bindingDigest(input.peerSshBinding), - localCacheRoot: input.localCacheRoot, - peerCacheRoot: input.peerCacheRoot, - apiKeyFingerprint: input.apiKeyFingerprint, - headContainerId: input.headContainerId, - workerContainerId: input.workerContainerId, - }; - writeReceipt(receipt, stateDir); - return loadedRuntime(receipt); - } catch (error) { - try { - clearDualStationSshBinding(receiptPath); - } catch { - // Preserve the receipt persistence error. - } - throw error; - } -} - -function clearReceipt(stateDir: string): void { - const filePath = dualSparkVllmRuntimeReceiptPath(stateDir); - fs.unlinkSync(filePath); - clearDualStationSshBinding(filePath); - fsyncDirectory(stateDir); -} - -function defaultCreateLifecycleDeps(runtime: LoadedDualSparkVllmRuntime): CleanupDeps { - return createDualSparkVllmExecutor({ - plan: runtime.plan, - peerSshBinding: runtime.peerSshBinding, - localCacheRoot: runtime.localCacheRoot, - peerCacheRoot: runtime.peerCacheRoot, - }); -} - -function defaultInspectNodesSync(runtime: LoadedDualSparkVllmRuntime): DualSparkVllmNodeSnapshots { - return inspectDualSparkVllmNodesSync({ - plan: runtime.plan, - peerSshBinding: runtime.peerSshBinding, - localCacheRoot: runtime.localCacheRoot, - peerCacheRoot: runtime.peerCacheRoot, - }); -} - -/** Recover only the exact healthy receipt-owned pair; unsafe managed state is explicit. */ -export function recoverInstalledDualSparkVllmEndpoint( - options: Pick< - DualSparkVllmRuntimeReceiptOptions, - "inspectNodesSync" | "loadApiKey" | "stateDir" - > = {}, -): RecoveredDualSparkVllmEndpoint | null { - const runtime = loadDualSparkVllmRuntimeReceipt({ stateDir: options.stateDir }); - if (!runtime) return null; - const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); - if (!apiKey || dualSparkVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { - throw new Error("Managed dual-Spark API key no longer matches the runtime receipt"); - } - let snapshots: DualSparkVllmNodeSnapshots; - try { - snapshots = (options.inspectNodesSync ?? defaultInspectNodesSync)(runtime); - } catch (error) { - throw new Error( - `Could not inspect the managed dual-Spark pair: ${ - error instanceof Error ? error.message : String(error) - }`, - ); - } - const state = classifyDualSparkExistingState(runtime.plan, runtime.apiKeyFingerprint, snapshots); - if ( - state.outcome !== "reuse" || - state.headContainerId !== runtime.headContainerId || - state.workerContainerId !== runtime.workerContainerId - ) { - const reason = "reason" in state ? state.reason : "receipt-owned container IDs changed"; - throw new Error(`Managed dual-Spark runtime is not recoverable: ${reason}`); - } - const baseUrl = runtime.plan.roles.head.endpoint; - if (!baseUrl) throw new Error("Managed dual-Spark head endpoint is invalid"); - return { - baseUrl, - apiKey, - apiKeyFingerprint: runtime.apiKeyFingerprint, - plan: runtime.plan, - }; -} - -/** Remove only receipt-ID-owned containers, then retire fully accounted ownership state. */ -export async function cleanupInstalledDualSparkVllmRuntime( - options: DualSparkVllmRuntimeReceiptOptions = {}, -): Promise { - const stateDir = options.stateDir ?? managedVllmStateDir(); - const runtime = loadDualSparkVllmRuntimeReceipt({ stateDir }); - if (!runtime) return { kind: "not-installed" }; - - const apiKey = (options.loadApiKey ?? loadManagedVllmApiKey)(); - if (!apiKey || dualSparkVllmApiKeyFingerprint(apiKey) !== runtime.apiKeyFingerprint) { - throw new Error("Managed dual-Spark API key no longer matches the runtime receipt"); - } - const discoveryBinding = loadReceiptOwnedDiscoveryBinding(stateDir, runtime); - const deps = (options.createLifecycleDeps ?? defaultCreateLifecycleDeps)(runtime); - const cleanup = await cleanupDualSparkManagedVllm(runtime.plan, apiKey, deps, { - headContainerId: runtime.headContainerId, - workerContainerId: runtime.workerContainerId, - }); - if (!cleanup.ok) throw new Error(cleanup.reason); - const expected = new Set([runtime.headContainerId, runtime.workerContainerId]); - const accounted = [...cleanup.removedContainerIds, ...(cleanup.alreadyAbsentContainerIds ?? [])]; - if ( - accounted.length !== expected.size || - new Set(accounted).size !== expected.size || - accounted.some((id) => !expected.has(id)) - ) { - throw new Error("Managed dual-Spark cleanup returned unexpected container identities"); - } - const currentDiscoveryBinding = loadReceiptOwnedDiscoveryBinding(stateDir, runtime); - if ((discoveryBinding === null) !== (currentDiscoveryBinding === null)) { - throw new Error("Dual-Spark discovery SSH binding changed during runtime cleanup"); - } - if (currentDiscoveryBinding) { - clearDualStationSshBinding(path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE)); - } - clearReceipt(stateDir); - return { kind: "removed", removedContainerIds: cleanup.removedContainerIds }; -} diff --git a/src/lib/inference/serving/vllm-managed-support.ts b/src/lib/inference/serving/vllm-managed-support.ts index 7e26c4f70a2..a384ccdd3ec 100644 --- a/src/lib/inference/serving/vllm-managed-support.ts +++ b/src/lib/inference/serving/vllm-managed-support.ts @@ -8,5 +8,5 @@ export { buildVllmDockerEnv, } from "../vllm-docker-env.js"; export { resolveVllmInstallModel } from "../vllm-prompt.js"; -export { tryInstallDualSparkManagedVllm } from "./dual-spark-installer.js"; -export { recoverInstalledDualSparkVllmEndpoint } from "./spark-runtime-receipt.js"; +export { tryInstallManagedClusterManagedVllm } from "./managed-cluster-installer.js"; +export { recoverInstalledManagedClusterVllmEndpoint } from "./managed-cluster-runtime-receipt.js"; diff --git a/src/lib/inference/vllm-api-key.ts b/src/lib/inference/vllm-api-key.ts index b600b17729d..4cd619a8b04 100644 --- a/src/lib/inference/vllm-api-key.ts +++ b/src/lib/inference/vllm-api-key.ts @@ -14,7 +14,7 @@ export const DUAL_STATION_VLLM_API_KEY_FILE = "dual-station-vllm-api-key"; export const DUAL_STATION_VLLM_API_KEY_PATTERN = /^[a-f0-9]{64}$/; // The original managed endpoint key was introduced with dual-Station serving. // Keep its path stable while exposing topology-neutral names for later managed -// serving profiles such as dual Spark. +// serving profiles. export const MANAGED_VLLM_API_KEY_FILE = DUAL_STATION_VLLM_API_KEY_FILE; export const MANAGED_VLLM_API_KEY_PATTERN = DUAL_STATION_VLLM_API_KEY_PATTERN; diff --git a/src/lib/inference/vllm-spark-runtime-receipt.test.ts b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts similarity index 59% rename from src/lib/inference/vllm-spark-runtime-receipt.test.ts rename to src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts index d4f3f745a22..ff05f9c86a1 100644 --- a/src/lib/inference/vllm-spark-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts @@ -6,32 +6,32 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { fixtureDualSparkSelection } from "./serving/dual-spark-fixture.test-support"; import { loadManagedInferenceCatalog } from "./serving/catalog"; import { managedInferenceDigest } from "./serving/catalog-integrity"; import type { CompiledManagedInferenceCatalog } from "./serving/catalog-types"; +import { fixtureManagedClusterSelection } from "./serving/managed-cluster-fixture.test-support"; import { - type DualSparkNodeSnapshot, - type DualSparkVllmLifecycleDeps, - dualSparkVllmApiKeyFingerprint, -} from "./serving/dual-spark-lifecycle"; + type ManagedClusterNodeSnapshot, + type ManagedClusterVllmLifecycleDeps, + managedClusterVllmApiKeyFingerprint, +} from "./serving/managed-cluster-lifecycle"; import { - DUAL_SPARK_API_KEY_FINGERPRINT_LABEL, - DUAL_SPARK_TRANSACTION_LABEL, - type DualSparkVllmPlan, - type DualSparkVllmRolePlan, - materializeDualSparkVllmPlan, -} from "./serving/dual-spark-materialize"; -import { dualSparkTopologyOutputDigest } from "./serving/dual-spark-topology"; + MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL, + MANAGED_CLUSTER_TRANSACTION_LABEL, + type ManagedClusterVllmPlan, + type ManagedClusterVllmRolePlan, + materializeManagedClusterVllmPlan, +} from "./serving/managed-cluster-materialize"; import { - cleanupInstalledDualSparkVllmRuntime, - dualSparkVllmRuntimeReceiptPath, - loadDualSparkVllmRuntimeReceipt, - type PersistDualSparkVllmRuntimeReceiptInput, - persistDualSparkVllmRuntimeReceipt, - recoverInstalledDualSparkVllmEndpoint, -} from "./serving/spark-runtime-receipt"; -import { DUAL_SPARK_MANAGED_SERVING_STATE_FILE } from "./serving/spark-runtime-receipt-path"; + cleanupInstalledManagedClusterVllmRuntime, + loadManagedClusterVllmRuntimeReceipt, + managedClusterVllmRuntimeReceiptPath, + type PersistManagedClusterVllmRuntimeReceiptInput, + persistManagedClusterVllmRuntimeReceipt, + recoverInstalledManagedClusterVllmEndpoint, +} from "./serving/managed-cluster-runtime-receipt"; +import { MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE } from "./serving/managed-cluster-runtime-receipt-path"; +import { managedClusterTopologyOutputDigest } from "./serving/managed-cluster-topology"; import { clearDualStationSshBinding, copyDualStationSshBinding, @@ -53,7 +53,7 @@ let stateDir: string; let sshFixture: DualStationSshBindingFixture; beforeEach(() => { - root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-spark-runtime-receipt-")); + root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-cluster-runtime-receipt-")); stateDir = path.join(root, ".nemoclaw"); sshFixture = createDualStationSshBindingFixture("nvidia@spark-worker.local"); }); @@ -66,37 +66,45 @@ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); -function plan(peerSshBinding: DualStationSshBinding = sshFixture.binding): DualSparkVllmPlan { - const selection = fixtureDualSparkSelection(); +function plan(sshBinding: DualStationSshBinding = sshFixture.binding): ManagedClusterVllmPlan { + const selection = fixtureManagedClusterSelection(); const sourceTopology = selection.topologyQualification; const output = { ...sourceTopology.output, - peer: { - target: peerSshBinding.peerTarget, - sshBindingHandle: encodeDualStationSshBindingHandoff(peerSshBinding), - }, + peers: sourceTopology.output.peers.map((peer) => ({ + ...peer, + target: sshBinding.peerTarget, + sshBindingHandle: encodeDualStationSshBindingHandoff(sshBinding), + })), }; - return materializeDualSparkVllmPlan({ + return materializeManagedClusterVllmPlan({ ...selection, topologyQualification: { ...sourceTopology, - outputDigest: dualSparkTopologyOutputDigest(output), + outputDigest: managedClusterTopologyOutputDigest(output), output, }, }); } function input( - peerSshBinding: DualStationSshBinding = sshFixture.binding, -): PersistDualSparkVllmRuntimeReceiptInput { + sshBinding: DualStationSshBinding = sshFixture.binding, +): PersistManagedClusterVllmRuntimeReceiptInput { + const runtimePlan = plan(sshBinding); return { - plan: plan(peerSshBinding), - peerSshBinding, - localCacheRoot: "/home/nvidia/.cache/huggingface", - peerCacheRoot: "/home/nvidia/.cache/huggingface", - apiKeyFingerprint: dualSparkVllmApiKeyFingerprint(API_KEY), - headContainerId: HEAD_ID, - workerContainerId: WORKER_ID, + plan: runtimePlan, + nodes: runtimePlan.roles.map((rolePlan) => ({ + nodeId: rolePlan.nodeId, + cacheRoot: "/home/nvidia/.cache/huggingface", + containerId: rolePlan.rank === 0 ? HEAD_ID : WORKER_ID, + ...(rolePlan.execution.kind === "ssh" + ? { + sshBinding, + discoveryStatePath: path.join(stateDir, MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE), + } + : {}), + })), + apiKeyFingerprint: managedClusterVllmApiKeyFingerprint(API_KEY), }; } @@ -158,19 +166,22 @@ function catalogWithUnrelatedProfile(): CompiledManagedInferenceCatalog { function persistWithDiscoveryBinding(): { discoveryBindingPath: string; discoveryStatePath: string; - runtime: ReturnType; + runtime: ReturnType; } { fs.mkdirSync(stateDir, { mode: 0o700 }); - const discoveryStatePath = path.join(stateDir, DUAL_SPARK_MANAGED_SERVING_STATE_FILE); + const discoveryStatePath = path.join(stateDir, MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE); const binding = copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); return { discoveryBindingPath: `${discoveryStatePath}.ssh-binding`, discoveryStatePath, - runtime: persistDualSparkVllmRuntimeReceipt(input(binding), { stateDir }), + runtime: persistManagedClusterVllmRuntimeReceipt(input(binding), { stateDir }), }; } -function snapshot(rolePlan: DualSparkVllmRolePlan, containerId: string): DualSparkNodeSnapshot { +function snapshot( + rolePlan: ManagedClusterVllmRolePlan, + containerId: string, +): ManagedClusterNodeSnapshot { return { containers: [ { @@ -181,8 +192,8 @@ function snapshot(rolePlan: DualSparkVllmRolePlan, containerId: string): DualSpa healthy: true, labels: { ...rolePlan.baseLabels, - [DUAL_SPARK_API_KEY_FINGERPRINT_LABEL]: dualSparkVllmApiKeyFingerprint(API_KEY), - [DUAL_SPARK_TRANSACTION_LABEL]: TRANSACTION_ID, + [MANAGED_CLUSTER_API_KEY_FINGERPRINT_LABEL]: managedClusterVllmApiKeyFingerprint(API_KEY), + [MANAGED_CLUSTER_TRANSACTION_LABEL]: TRANSACTION_ID, }, }, ], @@ -192,10 +203,13 @@ function snapshot(rolePlan: DualSparkVllmRolePlan, containerId: string): DualSpa } function cleanupDeps( - runtimePlan: DualSparkVllmPlan, + runtimePlan: ManagedClusterVllmPlan, ids: { head: string; worker: string } = { head: HEAD_ID, worker: WORKER_ID }, ): { - deps: Pick; + deps: Pick< + ManagedClusterVllmLifecycleDeps, + "inspectNode" | "removeContainer" | "withLifecycleLock" + >; removeContainer: ReturnType; } { const removeContainer = vi.fn(async () => ({ ok: true as const })); @@ -203,8 +217,8 @@ function cleanupDeps( deps: { inspectNode: async (rolePlan) => rolePlan.role === "head" - ? snapshot(runtimePlan.roles.head, ids.head) - : snapshot(runtimePlan.roles.worker, ids.worker), + ? snapshot(runtimePlan.roles[0], ids.head) + : snapshot(runtimePlan.roles[1], ids.worker), removeContainer, withLifecycleLock: async (_plan, operation) => await operation(), }, @@ -212,50 +226,58 @@ function cleanupDeps( }; } -describe("dual-Spark vLLM runtime receipt", () => { +describe("managed cluster vLLM runtime receipt", () => { it("uses the host-global default gateway state root", async () => { vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080"); vi.resetModules(); - const { dualSparkVllmRuntimeReceiptPath: selectedReceiptPath } = await import( - "./serving/spark-runtime-receipt" + const { managedClusterVllmRuntimeReceiptPath: selectedReceiptPath } = await import( + "./serving/managed-cluster-runtime-receipt" ); expect(selectedReceiptPath()).toBe( - path.join(os.homedir(), ".nemoclaw", "dual-spark-vllm-runtime.json"), + path.join(os.homedir(), ".nemoclaw", "managed-cluster-vllm-runtime.json"), ); }); it("persists a private exact runtime plan with a promoted SSH binding and no bearer key", () => { const source = input(); - const runtime = persistDualSparkVllmRuntimeReceipt(source, { stateDir }); - const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const runtime = persistManagedClusterVllmRuntimeReceipt(source, { stateDir }); + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); const raw = fs.readFileSync(receiptPath, "utf8"); + const worker = runtime.nodes.find((node) => node.binding)!; expect(fs.statSync(receiptPath).mode & 0o777).toBe(0o600); - expect(fs.lstatSync(`${receiptPath}.ssh-binding`).isDirectory()).toBe(true); + expect(fs.lstatSync(`${receiptPath}.rank-1.ssh-binding`).isDirectory()).toBe(true); expect(raw).not.toContain(API_KEY); - expect(runtime.sshBinding).not.toBe(sshFixture.token); - expect(runtime.plan.roles.worker.execution).toMatchObject({ + expect(worker.sshBinding).not.toBe(sshFixture.token); + expect(runtime.plan.roles[1].execution).toMatchObject({ kind: "ssh", expectedTarget: sshFixture.binding.peerTarget, - bindingHandle: runtime.sshBinding, + bindingHandle: worker.sshBinding, }); - expect(runtime.peerSshBinding.bindingFile).toContain(`${receiptPath}.ssh-binding/`); - expect(loadDualSparkVllmRuntimeReceipt({ stateDir })).toEqual(runtime); + expect(worker.binding?.bindingFile).toContain(`${receiptPath}.rank-1.ssh-binding/`); + expect(loadManagedClusterVllmRuntimeReceipt({ stateDir })).toEqual(runtime); }); it("is idempotent only for the same committed runtime", () => { const source = input(); - const first = persistDualSparkVllmRuntimeReceipt(source, { stateDir }); - const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + const first = persistManagedClusterVllmRuntimeReceipt(source, { stateDir }); + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); const original = fs.readFileSync(receiptPath, "utf8"); - expect(persistDualSparkVllmRuntimeReceipt(source, { stateDir })).toEqual(first); + expect(persistManagedClusterVllmRuntimeReceipt(source, { stateDir })).toEqual(first); expect(() => - persistDualSparkVllmRuntimeReceipt( - { ...source, workerContainerId: "e".repeat(64) }, + persistManagedClusterVllmRuntimeReceipt( + { + ...source, + nodes: source.nodes.map((node) => + node.nodeId === source.plan.roles[1]?.nodeId + ? { ...node, containerId: "e".repeat(64) } + : node, + ), + }, { stateDir }, ), - ).toThrow("different managed dual-Spark runtime receipt"); + ).toThrow("different managed cluster runtime receipt"); expect(fs.readFileSync(receiptPath, "utf8")).toBe(original); }); @@ -263,13 +285,13 @@ describe("dual-Spark vLLM runtime receipt", () => { const source = input(); const currentCatalog = loadManagedInferenceCatalog(); const changedCatalog = catalogWithUnrelatedProfile(); - persistDualSparkVllmRuntimeReceipt(source, { stateDir }); + persistManagedClusterVllmRuntimeReceipt(source, { stateDir }); expect(changedCatalog.catalogDigest).not.toBe(currentCatalog.catalogDigest); vi.doMock("./serving/generated/catalog.json", () => ({ default: changedCatalog })); vi.resetModules(); - const { loadDualSparkVllmRuntimeReceipt: loadAgainstChangedCatalog } = await import( - "./serving/spark-runtime-receipt" + const { loadManagedClusterVllmRuntimeReceipt: loadAgainstChangedCatalog } = await import( + "./serving/managed-cluster-runtime-receipt" ); const loaded = loadAgainstChangedCatalog({ stateDir }); const currentPreset = changedCatalog.presets.find( @@ -292,7 +314,7 @@ describe("dual-Spark vLLM runtime receipt", () => { throw new Error("temporary cleanup failed"); }); - expect(() => persistDualSparkVllmRuntimeReceipt(input(), { stateDir })).toThrow( + expect(() => persistManagedClusterVllmRuntimeReceipt(input(), { stateDir })).toThrow( "receipt rename failed", ); expect(rename).toHaveBeenCalledOnce(); @@ -301,14 +323,14 @@ describe("dual-Spark vLLM runtime receipt", () => { it("refuses a pre-existing SSH binding tree without mutating it", () => { fs.mkdirSync(stateDir, { mode: 0o700 }); - const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); - const bindingPath = `${receiptPath}.ssh-binding`; + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); + const bindingPath = `${receiptPath}.rank-1.ssh-binding`; const markerPath = path.join(bindingPath, "foreign-state"); fs.mkdirSync(bindingPath, { mode: 0o700 }); fs.writeFileSync(markerPath, "leave intact\n", { mode: 0o600 }); - expect(() => persistDualSparkVllmRuntimeReceipt(input(), { stateDir })).toThrow( - "Managed dual-Spark SSH binding state already exists", + expect(() => persistManagedClusterVllmRuntimeReceipt(input(), { stateDir })).toThrow( + "Managed cluster SSH binding state already exists", ); expect(fs.readFileSync(markerPath, "utf8")).toBe("leave intact\n"); expect(fs.existsSync(receiptPath)).toBe(false); @@ -318,36 +340,38 @@ describe("dual-Spark vLLM runtime receipt", () => { fs.mkdirSync(stateDir, { mode: 0o700 }); const target = path.join(root, "redirected.json"); fs.writeFileSync(target, "{}\n", { mode: 0o600 }); - fs.symlinkSync(target, dualSparkVllmRuntimeReceiptPath(stateDir)); + fs.symlinkSync(target, managedClusterVllmRuntimeReceiptPath(stateDir)); - expect(() => loadDualSparkVllmRuntimeReceipt({ stateDir })).toThrow("symbolic link"); + expect(() => loadManagedClusterVllmRuntimeReceipt({ stateDir })).toThrow("symbolic link"); }); it("rejects changed plan contents before using the persisted binding", () => { - persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); - const receiptPath = dualSparkVllmRuntimeReceiptPath(stateDir); + persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf8")); receipt.plan.model.id = "foreign/model"; fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { mode: 0o600, }); - expect(() => loadDualSparkVllmRuntimeReceipt({ stateDir })).toThrow("plan digest changed"); + expect(() => loadManagedClusterVllmRuntimeReceipt({ stateDir })).toThrow("plan digest changed"); }); it("recovers only the exact healthy receipt-owned endpoint synchronously", () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const runtime = persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); expect( - recoverInstalledDualSparkVllmEndpoint({ + recoverInstalledManagedClusterVllmEndpoint({ stateDir, loadApiKey: () => API_KEY, inspectNodesSync: () => ({ - head: snapshot(runtime.plan.roles.head, HEAD_ID), - worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + nodes: runtime.plan.roles.map((rolePlan) => ({ + nodeId: rolePlan.nodeId, + snapshot: snapshot(rolePlan, rolePlan.rank === 0 ? HEAD_ID : WORKER_ID), + })), }), }), ).toEqual({ - baseUrl: runtime.plan.roles.head.endpoint, + baseUrl: runtime.plan.roles[0].endpoint, apiKey: API_KEY, apiKeyFingerprint: runtime.apiKeyFingerprint, plan: runtime.plan, @@ -355,23 +379,25 @@ describe("dual-Spark vLLM runtime receipt", () => { }); it("signals a managed endpoint whose exact receipt-owned IDs changed", () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const runtime = persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); expect(() => - recoverInstalledDualSparkVllmEndpoint({ + recoverInstalledManagedClusterVllmEndpoint({ stateDir, loadApiKey: () => API_KEY, inspectNodesSync: () => ({ - head: snapshot(runtime.plan.roles.head, "e".repeat(64)), - worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + nodes: runtime.plan.roles.map((rolePlan) => ({ + nodeId: rolePlan.nodeId, + snapshot: snapshot(rolePlan, rolePlan.rank === 0 ? "e".repeat(64) : WORKER_ID), + })), }), }), ).toThrow("not recoverable"); }); it("signals a persisted managed endpoint whose key no longer matches", () => { - persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); expect(() => - recoverInstalledDualSparkVllmEndpoint({ + recoverInstalledManagedClusterVllmEndpoint({ stateDir, loadApiKey: () => "f".repeat(64), inspectNodesSync: vi.fn(), @@ -383,7 +409,7 @@ describe("dual-Spark vLLM runtime receipt", () => { const { discoveryStatePath, runtime } = persistWithDiscoveryBinding(); const { deps, removeContainer } = cleanupDeps(runtime.plan); await expect( - cleanupInstalledDualSparkVllmRuntime({ + cleanupInstalledManagedClusterVllmRuntime({ stateDir, loadApiKey: () => API_KEY, createLifecycleDeps: () => deps, @@ -392,11 +418,13 @@ describe("dual-Spark vLLM runtime receipt", () => { kind: "removed", removedContainerIds: [HEAD_ID, WORKER_ID], }); - expect(removeContainer).toHaveBeenNthCalledWith(1, runtime.plan.roles.head, HEAD_ID); - expect(removeContainer).toHaveBeenNthCalledWith(2, runtime.plan.roles.worker, WORKER_ID); + expect(removeContainer).toHaveBeenNthCalledWith(1, runtime.plan.roles[0], HEAD_ID); + expect(removeContainer).toHaveBeenNthCalledWith(2, runtime.plan.roles[1], WORKER_ID); expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(false); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); - expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(false); + expect( + fs.existsSync(`${managedClusterVllmRuntimeReceiptPath(stateDir)}.rank-1.ssh-binding`), + ).toBe(false); }); it("preserves a replaced canonical discovery binding before container cleanup", async () => { @@ -407,7 +435,7 @@ describe("dual-Spark vLLM runtime receipt", () => { const createLifecycleDeps = vi.fn(() => deps); await expect( - cleanupInstalledDualSparkVllmRuntime({ + cleanupInstalledManagedClusterVllmRuntime({ stateDir, loadApiKey: () => API_KEY, createLifecycleDeps, @@ -417,21 +445,23 @@ describe("dual-Spark vLLM runtime receipt", () => { expect(createLifecycleDeps).not.toHaveBeenCalled(); expect(removeContainer).not.toHaveBeenCalled(); expect(fs.existsSync(discoveryBindingPath)).toBe(true); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); - expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect( + fs.existsSync(`${managedClusterVllmRuntimeReceiptPath(stateDir)}.rank-1.ssh-binding`), + ).toBe(true); }); it("retains durable ownership when a leftover discovery binding is unsafe to retire", async () => { const { discoveryBindingPath, runtime } = persistWithDiscoveryBinding(); - const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { - head: snapshot(runtime.plan.roles.head, HEAD_ID), - worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + const snapshots: Record<"head" | "worker", ManagedClusterNodeSnapshot> = { + head: snapshot(runtime.plan.roles[0], HEAD_ID), + worker: snapshot(runtime.plan.roles[1], WORKER_ID), }; - const discoveryBindingModeByRole: Record = { + const discoveryBindingModeByRole: Record = { head: 0o700, worker: 0o755, }; - const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + const removeContainer = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan, id: string) => { snapshots[rolePlan.role] = { ...snapshots[rolePlan.role], containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), @@ -443,41 +473,45 @@ describe("dual-Spark vLLM runtime receipt", () => { stateDir, loadApiKey: () => API_KEY, createLifecycleDeps: () => ({ - inspectNode: async (rolePlan: DualSparkVllmRolePlan) => snapshots[rolePlan.role], + inspectNode: async (rolePlan: ManagedClusterVllmRolePlan) => snapshots[rolePlan.role], removeContainer, - withLifecycleLock: async (_plan: DualSparkVllmPlan, operation: () => Promise) => + withLifecycleLock: async (_plan: ManagedClusterVllmPlan, operation: () => Promise) => await operation(), }), }; - await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow( + await expect(cleanupInstalledManagedClusterVllmRuntime(options)).rejects.toThrow( "must be an owner-only directory", ); expect(removeContainer).toHaveBeenCalledTimes(2); expect(fs.existsSync(discoveryBindingPath)).toBe(true); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); - expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect( + fs.existsSync(`${managedClusterVllmRuntimeReceiptPath(stateDir)}.rank-1.ssh-binding`), + ).toBe(true); fs.chmodSync(discoveryBindingPath, 0o700); - await expect(cleanupInstalledDualSparkVllmRuntime(options)).resolves.toEqual({ + await expect(cleanupInstalledManagedClusterVllmRuntime(options)).resolves.toEqual({ kind: "removed", removedContainerIds: [], }); expect(removeContainer).toHaveBeenCalledTimes(2); expect(fs.existsSync(discoveryBindingPath)).toBe(false); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); - expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(false); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(false); + expect( + fs.existsSync(`${managedClusterVllmRuntimeReceiptPath(stateDir)}.rank-1.ssh-binding`), + ).toBe(false); }); it("retains the receipt and resumes after one exact container removal fails", async () => { const { discoveryStatePath, runtime } = persistWithDiscoveryBinding(); - const snapshots: Record<"head" | "worker", DualSparkNodeSnapshot> = { - head: snapshot(runtime.plan.roles.head, HEAD_ID), - worker: snapshot(runtime.plan.roles.worker, WORKER_ID), + const snapshots: Record<"head" | "worker", ManagedClusterNodeSnapshot> = { + head: snapshot(runtime.plan.roles[0], HEAD_ID), + worker: snapshot(runtime.plan.roles[1], WORKER_ID), }; let workerAttempts = 0; - const removeContainer = vi.fn(async (rolePlan: DualSparkVllmRolePlan, id: string) => { + const removeContainer = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan, id: string) => { const shouldFailWorker = rolePlan.role === "worker" && workerAttempts === 0; workerAttempts += Number(rolePlan.role === "worker"); const removeOwnedContainer = () => { @@ -497,9 +531,9 @@ describe("dual-Spark vLLM runtime receipt", () => { : removeOwnedContainer(); }); const deps = { - inspectNode: async (rolePlan: DualSparkVllmRolePlan) => snapshots[rolePlan.role], + inspectNode: async (rolePlan: ManagedClusterVllmRolePlan) => snapshots[rolePlan.role], removeContainer, - withLifecycleLock: async (_plan: DualSparkVllmPlan, operation: () => Promise) => + withLifecycleLock: async (_plan: ManagedClusterVllmPlan, operation: () => Promise) => await operation(), }; const options = { @@ -508,12 +542,12 @@ describe("dual-Spark vLLM runtime receipt", () => { createLifecycleDeps: () => deps, }; - await expect(cleanupInstalledDualSparkVllmRuntime(options)).rejects.toThrow( + await expect(cleanupInstalledManagedClusterVllmRuntime(options)).rejects.toThrow( "worker daemon unavailable", ); expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(true); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); - await expect(cleanupInstalledDualSparkVllmRuntime(options)).resolves.toEqual({ + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(true); + await expect(cleanupInstalledManagedClusterVllmRuntime(options)).resolves.toEqual({ kind: "removed", removedContainerIds: [WORKER_ID], }); @@ -523,44 +557,46 @@ describe("dual-Spark vLLM runtime receipt", () => { WORKER_ID, ]); expect(fs.existsSync(`${discoveryStatePath}.ssh-binding`)).toBe(false); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(false); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(false); }); it("preserves recovery state when the observed container IDs changed", async () => { - const runtime = persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + const runtime = persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); const { deps, removeContainer } = cleanupDeps(runtime.plan, { head: "e".repeat(64), worker: WORKER_ID, }); await expect( - cleanupInstalledDualSparkVllmRuntime({ + cleanupInstalledManagedClusterVllmRuntime({ stateDir, loadApiKey: () => API_KEY, createLifecycleDeps: () => deps, }), ).rejects.toThrow("head receipt-owned container is absent but related runtime state exists"); expect(removeContainer).not.toHaveBeenCalled(); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); - expect(fs.existsSync(`${dualSparkVllmRuntimeReceiptPath(stateDir)}.ssh-binding`)).toBe(true); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect( + fs.existsSync(`${managedClusterVllmRuntimeReceiptPath(stateDir)}.rank-1.ssh-binding`), + ).toBe(true); }); it("preserves recovery state when the managed API key changed", async () => { - persistDualSparkVllmRuntimeReceipt(input(), { stateDir }); + persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); const createLifecycleDeps = vi.fn(); await expect( - cleanupInstalledDualSparkVllmRuntime({ + cleanupInstalledManagedClusterVllmRuntime({ stateDir, loadApiKey: () => "f".repeat(64), createLifecycleDeps, }), ).rejects.toThrow("API key no longer matches"); expect(createLifecycleDeps).not.toHaveBeenCalled(); - expect(fs.existsSync(dualSparkVllmRuntimeReceiptPath(stateDir))).toBe(true); + expect(fs.existsSync(managedClusterVllmRuntimeReceiptPath(stateDir))).toBe(true); }); it("does nothing when no runtime receipt exists", async () => { await expect( - cleanupInstalledDualSparkVllmRuntime({ + cleanupInstalledManagedClusterVllmRuntime({ stateDir, loadApiKey: vi.fn(), createLifecycleDeps: vi.fn(), diff --git a/src/lib/inference/vllm-managed-recovery.test.ts b/src/lib/inference/vllm-managed-recovery.test.ts index 709620c7bd9..691a52b05a1 100644 --- a/src/lib/inference/vllm-managed-recovery.test.ts +++ b/src/lib/inference/vllm-managed-recovery.test.ts @@ -3,22 +3,22 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -const sparkRecovery = vi.hoisted(() => ({ endpoint: vi.fn() })); +const managedClusterRecovery = vi.hoisted(() => ({ endpoint: vi.fn() })); -vi.mock("./serving/spark-runtime-receipt", async (importOriginal) => ({ - ...(await importOriginal()), - recoverInstalledDualSparkVllmEndpoint: sparkRecovery.endpoint, +vi.mock("./serving/managed-cluster-runtime-receipt", async (importOriginal) => ({ + ...(await importOriginal()), + recoverInstalledManagedClusterVllmEndpoint: managedClusterRecovery.endpoint, })); import { isNemoClawManagedVllmRunning, persistConfiguredManagedVllmRuntimeReceipt } from "./vllm"; -describe("managed vLLM Spark recovery", () => { +describe("managed vLLM cluster recovery", () => { beforeEach(() => { - sparkRecovery.endpoint.mockReset(); + managedClusterRecovery.endpoint.mockReset(); }); - it("recognizes and confirms an installer-owned Spark receipt", async () => { - sparkRecovery.endpoint.mockReturnValue({ + it("recognizes and confirms an installer-owned managed cluster receipt", async () => { + managedClusterRecovery.endpoint.mockReturnValue({ baseUrl: "http://10.40.0.1:8000", apiKey: "a".repeat(64), }); @@ -30,8 +30,8 @@ describe("managed vLLM Spark recovery", () => { }); }); - it("fails closed instead of falling through when Spark receipt recovery is unsafe", async () => { - sparkRecovery.endpoint.mockImplementation(() => { + it("fails closed instead of falling through when managed cluster recovery is unsafe", async () => { + managedClusterRecovery.endpoint.mockImplementation(() => { throw new Error("receipt-owned container IDs changed"); }); diff --git a/src/lib/inference/vllm-managed-runtime-receipts.test.ts b/src/lib/inference/vllm-managed-runtime-receipts.test.ts index 42678780fd4..478d5e75dbf 100644 --- a/src/lib/inference/vllm-managed-runtime-receipts.test.ts +++ b/src/lib/inference/vllm-managed-runtime-receipts.test.ts @@ -8,12 +8,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { DEFAULT_GATEWAY_PORT } from "../core/ports"; import { nemoclawStateRoot } from "../state/state-root"; -import { createProductionDualSparkDiscoveryDeps } from "./serving/dual-spark-discovery-production"; +import { createProductionManagedClusterDiscoveryDeps } from "./serving/managed-cluster-discovery-production"; +import { managedClusterVllmRuntimeReceiptPath } from "./serving/managed-cluster-runtime-receipt"; import { assertNoManagedDistributedVllmRuntimeReceipts, findManagedDistributedVllmRuntimeReceipts, } from "./serving/managed-runtime-receipts"; -import { dualSparkVllmRuntimeReceiptPath } from "./serving/spark-runtime-receipt"; import { dualStationVllmRuntimeReceiptPath } from "./vllm-station-runtime-receipt"; const temporaryHomes: string[] = []; @@ -41,17 +41,17 @@ describe("managed distributed vLLM receipt preflight", () => { ).not.toThrow(); }); - it("blocks a host-global Spark receipt without parsing stale contents", () => { + it("blocks a host-global managed cluster receipt without parsing stale contents", () => { const homeDir = temporaryHome(); - const receiptPath = dualSparkVllmRuntimeReceiptPath( + const receiptPath = managedClusterVllmRuntimeReceiptPath( nemoclawStateRoot(homeDir, DEFAULT_GATEWAY_PORT), ); touch(receiptPath); expect(findManagedDistributedVllmRuntimeReceipts({ homeDir })).toEqual({ - sparkBindingPath: null, - sparkDiscoveryBindingPaths: [], - sparkPath: receiptPath, + managedClusterBindingPaths: [], + managedClusterDiscoveryBindingPaths: [], + managedClusterPath: receiptPath, stationBindingPaths: [], stationPaths: [], }); @@ -78,47 +78,70 @@ describe("managed distributed vLLM receipt preflight", () => { const stateRoot = nemoclawStateRoot(homeDir, gatewayPort); const receiptPath = topology === "Spark" - ? dualSparkVllmRuntimeReceiptPath(stateRoot) + ? managedClusterVllmRuntimeReceiptPath(stateRoot) : dualStationVllmRuntimeReceiptPath(stateRoot); - const bindingPath = `${receiptPath}.ssh-binding`; + const bindingPath = + topology === "Spark" ? `${receiptPath}.rank-1.ssh-binding` : `${receiptPath}.ssh-binding`; fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow(bindingPath); }); - it("blocks an orphaned Spark discovery binding claim", () => { + it("blocks an orphaned managed cluster discovery binding claim", () => { const homeDir = temporaryHome(); const bindingPath = path.join( nemoclawStateRoot(homeDir), - "dual-spark-managed-serving.json.ssh-binding", + "managed-cluster-managed-serving.json.spark-worker.ssh-binding", ); fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); expect( - findManagedDistributedVllmRuntimeReceipts({ homeDir }).sparkDiscoveryBindingPaths, + findManagedDistributedVllmRuntimeReceipts({ homeDir }).managedClusterDiscoveryBindingPaths, ).toEqual([bindingPath]); expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow(bindingPath); }); - it("places the production Spark discovery claim in the scanner-visible gateway root", () => { + it("enumerates every ranked runtime binding and per-node discovery claim", () => { + const homeDir = temporaryHome(); + const stateRoot = nemoclawStateRoot(homeDir); + const runtimeBindings = [ + "managed-cluster-vllm-runtime.json.rank-1.ssh-binding", + "managed-cluster-vllm-runtime.json.rank-2.ssh-binding", + ].map((entry) => path.join(stateRoot, entry)); + const discoveryBindings = [ + "managed-cluster-managed-serving.json.node-a.ssh-binding", + "managed-cluster-managed-serving.json.node-b.ssh-binding", + ].map((entry) => path.join(stateRoot, entry)); + for (const bindingPath of [...runtimeBindings, ...discoveryBindings]) { + fs.mkdirSync(bindingPath, { recursive: true, mode: 0o700 }); + } + + const receipts = findManagedDistributedVllmRuntimeReceipts({ homeDir }); + expect(receipts.managedClusterBindingPaths).toEqual(runtimeBindings); + expect(receipts.managedClusterDiscoveryBindingPaths).toEqual(discoveryBindings); + }); + + it("places each production cluster discovery claim in the scanner-visible gateway root", () => { const homeDir = temporaryHome(); vi.stubEnv("HOME", homeDir); - const deps = createProductionDualSparkDiscoveryDeps(() => { + const deps = createProductionManagedClusterDiscoveryDeps(() => { throw new Error("unexpected host probe"); }); - expect(deps.resolveBindingStatePath()).toBe( - path.join(nemoclawStateRoot(homeDir), "dual-spark-managed-serving.json"), + expect(deps.resolveBindingStatePath("spark-worker")).toBe( + path.join(nemoclawStateRoot(homeDir), "managed-cluster-managed-serving.json.spark-worker"), ); }); it("treats a receipt symlink as existing without following it", () => { const homeDir = temporaryHome(); - const receiptPath = dualSparkVllmRuntimeReceiptPath(nemoclawStateRoot(homeDir)); + const receiptPath = managedClusterVllmRuntimeReceiptPath(nemoclawStateRoot(homeDir)); fs.mkdirSync(path.dirname(receiptPath), { recursive: true }); fs.symlinkSync(path.join(homeDir, "missing-target"), receiptPath); - expect(findManagedDistributedVllmRuntimeReceipts({ homeDir }).sparkPath).toBe(receiptPath); + expect(findManagedDistributedVllmRuntimeReceipts({ homeDir }).managedClusterPath).toBe( + receiptPath, + ); expect(() => assertNoManagedDistributedVllmRuntimeReceipts({ homeDir })).toThrow( "Managed vLLM runtime state already exists", ); diff --git a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts index 39d5a03939e..eab35358293 100644 --- a/src/lib/inference/vllm-station-runtime-cleanup-entry.ts +++ b/src/lib/inference/vllm-station-runtime-cleanup-entry.ts @@ -5,9 +5,9 @@ import fs from "node:fs"; import path from "node:path"; import { - cleanupInstalledDualSparkVllmRuntime, - dualSparkVllmRuntimeReceiptPath, -} from "./serving/spark-runtime-receipt"; + cleanupInstalledManagedClusterVllmRuntime, + managedClusterVllmRuntimeReceiptPath, +} from "./serving/managed-cluster-runtime-receipt"; import { cleanupInstalledDualStationVllmRuntime, dualStationVllmRuntimeReceiptPath, @@ -26,7 +26,7 @@ function pathExistsNoFollow(filePath: string): boolean { function requestedReceipt(): { readonly filePath: string; readonly stateDir: string; - readonly topology: "spark" | "station"; + readonly topology: "managed-cluster" | "station"; } { const args = process.argv.slice(2); if (args.length !== 1) { @@ -37,8 +37,8 @@ function requestedReceipt(): { throw new Error("managed distributed vLLM cleanup receipt path is invalid"); } const stateDir = path.dirname(filePath); - if (filePath === dualSparkVllmRuntimeReceiptPath(stateDir)) { - return { filePath, stateDir, topology: "spark" }; + if (filePath === managedClusterVllmRuntimeReceiptPath(stateDir)) { + return { filePath, stateDir, topology: "managed-cluster" }; } if (filePath === dualStationVllmRuntimeReceiptPath(stateDir)) { return { filePath, stateDir, topology: "station" }; @@ -52,24 +52,26 @@ async function main(): Promise { throw new Error(`managed distributed vLLM receipt disappeared: ${receipt.filePath}`); } const otherReceipt = - receipt.topology === "spark" + receipt.topology === "managed-cluster" ? dualStationVllmRuntimeReceiptPath(receipt.stateDir) - : dualSparkVllmRuntimeReceiptPath(receipt.stateDir); + : managedClusterVllmRuntimeReceiptPath(receipt.stateDir); if (pathExistsNoFollow(otherReceipt)) { throw new Error( - "both dual-Spark and dual-Station runtime receipts exist; refusing ambiguous cleanup", + "both managed cluster and dual-Station runtime receipts exist; refusing ambiguous cleanup", ); } - if (receipt.topology === "spark") { - const spark = await cleanupInstalledDualSparkVllmRuntime({ stateDir: receipt.stateDir }); - if (spark.kind !== "removed" || pathExistsNoFollow(receipt.filePath)) { - throw new Error("the requested dual-Spark runtime receipt was not removed"); + if (receipt.topology === "managed-cluster") { + const managedCluster = await cleanupInstalledManagedClusterVllmRuntime({ + stateDir: receipt.stateDir, + }); + if (managedCluster.kind !== "removed" || pathExistsNoFollow(receipt.filePath)) { + throw new Error("the requested managed cluster runtime receipt was not removed"); } console.log( - spark.removedContainerIds.length > 0 - ? `Removed managed dual-Spark vLLM containers: ${spark.removedContainerIds.join(", ")}` - : "Removed managed dual-Spark vLLM state; no receipt-owned containers remained.", + managedCluster.removedContainerIds.length > 0 + ? `Removed managed cluster vLLM containers: ${managedCluster.removedContainerIds.join(", ")}` + : "Removed managed cluster vLLM state; no receipt-owned containers remained.", ); return; } diff --git a/src/lib/inference/vllm.ts b/src/lib/inference/vllm.ts index bc5403fa3c3..a41408b1df6 100644 --- a/src/lib/inference/vllm.ts +++ b/src/lib/inference/vllm.ts @@ -38,9 +38,9 @@ import { buildVllmDockerEnv, ensureDualStationVllmApiKey, loadDualStationVllmApiKey, - recoverInstalledDualSparkVllmEndpoint, + recoverInstalledManagedClusterVllmEndpoint, resolveVllmInstallModel, - tryInstallDualSparkManagedVllm, + tryInstallManagedClusterManagedVllm, } from "./serving/vllm-managed-support"; import { buildVllmServeCommand, @@ -895,7 +895,7 @@ function vllmContainerReplacementTarget( export function isNemoClawManagedVllmRunning(): boolean { try { - if (recoverInstalledDualSparkVllmEndpoint()) return true; + if (recoverInstalledManagedClusterVllmEndpoint()) return true; } catch { return false; } @@ -913,7 +913,7 @@ export type PersistConfiguredManagedVllmRuntimeResult = */ export async function persistConfiguredManagedVllmRuntimeReceipt(): Promise { try { - if (recoverInstalledDualSparkVllmEndpoint()) return { ok: true, persisted: true }; + if (recoverInstalledManagedClusterVllmEndpoint()) return { ok: true, persisted: true }; } catch (error) { return { ok: false, reason: `managed vLLM recovery failed: ${(error as Error).message}` }; } @@ -1577,7 +1577,7 @@ async function runVllmInstall( profile: VllmProfile, opts: InstallVllmOptions, ): Promise<{ ok: boolean }> { - const dualSpark = await tryInstallDualSparkManagedVllm( + const managedCluster = await tryInstallManagedClusterManagedVllm( { platform: profile.platform, nonInteractive: opts.nonInteractive, @@ -1591,7 +1591,7 @@ async function runVllmInstall( printDownloadAuthentication: printHfDownloadAuthentication, }, ); - if (dualSpark.kind === "handled") return dualSpark.result; + if (managedCluster.kind === "handled") return managedCluster.result; let dualStationPlan: DualStationVllmPlan | null = null; let peerModelSnapshot: "ready" | "staging-required" | null = null; diff --git a/test/install-express-prompt.test.ts b/test/install-express-prompt.test.ts index 53a9350afa6..84d50136cfc 100644 --- a/test/install-express-prompt.test.ts +++ b/test/install-express-prompt.test.ts @@ -295,7 +295,7 @@ DGX_COMMIT_ID="d0e99cc"\nDGX_PLATFORM="DGX Server for GALAXY-GB300" expect(output).toMatch( /Express install will configure managed vLLM with automatic DGX Spark serving-profile selection/, ); - expect(output).toMatch(/one exactly qualified pretrusted two-Spark topology/); + expect(output).toMatch(/one exactly qualified pretrusted managed cluster topology/); expect(output).toMatch(/related or ambiguous setup remains untouched and stops installation/); expect(output).toMatch(/experimental pending physical end-to-end validation/); expect(output).toMatch(/Sandbox name: my-assistant/); diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index 3b06ac20ee3..379e92209ec 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -20,17 +20,17 @@ import type { ResolvedManagedInferenceSelection, } from "../src/lib/inference/serving/catalog-types.js"; import { - FIXTURE_DUAL_SPARK_PRESET_ID, - fixtureDualSparkSelection, -} from "../src/lib/inference/serving/dual-spark-fixture.test-support.js"; -import { materializeDualSparkVllmPlan } from "../src/lib/inference/serving/dual-spark-materialize.js"; -import type { DualSparkTopologyOutput } from "../src/lib/inference/serving/dual-spark-topology.js"; + FIXTURE_MANAGED_CLUSTER_PRESET_ID, + fixtureManagedClusterSelection, +} from "../src/lib/inference/serving/managed-cluster-fixture.test-support.js"; +import { materializeManagedClusterVllmPlan } from "../src/lib/inference/serving/managed-cluster-materialize.js"; +import type { ManagedClusterTopologyOutput } from "../src/lib/inference/serving/managed-cluster-topology.js"; import { resolveManagedInferenceServing } from "../src/lib/inference/serving/resolver.js"; import type { SystemReadinessReport } from "../src/lib/readiness/types.js"; const REPOSITORY_ROOT = fileURLToPath(new URL("..", import.meta.url)); const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; -const FIXTURE_DUAL_SPARK_RECIPE_ID = fixtureDualSparkSelection().recipe.metadata.id; +const FIXTURE_MANAGED_CLUSTER_RECIPE_ID = fixtureManagedClusterSelection().recipe.metadata.id; function catalogSources(): ManagedInferenceCatalogSource[] { return SOURCE_DIRECTORIES.flatMap((directory) => @@ -55,7 +55,9 @@ function replaceDefinition( replace: (definition: TDefinition) => TDefinition, ): ManagedInferenceCatalogSource[] { const fixtureId = - kind === "ServingPreset" ? FIXTURE_DUAL_SPARK_PRESET_ID : FIXTURE_DUAL_SPARK_RECIPE_ID; + kind === "ServingPreset" + ? FIXTURE_MANAGED_CLUSTER_PRESET_ID + : FIXTURE_MANAGED_CLUSTER_RECIPE_ID; const replacementIndex = sources.findIndex((source) => { const definition = parse(source.contents) as { readonly kind?: unknown; @@ -79,7 +81,7 @@ function syntheticProfileSources( ): ManagedInferenceCatalogSource[] { const compiled = compileManagedInferenceCatalogSources(sources).catalog; const sourcePreset = compiled.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_PRESET_ID, + ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, )?.definition; expect(sourcePreset).toBeDefined(); const presetTemplate = sourcePreset as ManagedInferenceServingPreset; @@ -293,7 +295,7 @@ describe("managed inference catalog compiler", () => { ({ definition }) => definition.metadata.id === "vllm.synthetic-model.generic-topology", )?.definition; expect(preset).toBeDefined(); - const topologyQualification = fixtureDualSparkSelection().topologyQualification; + const topologyQualification = fixtureManagedClusterSelection().topologyQualification; const resolution = resolveManagedInferenceServing( { readinessReports: matchingReadinessSources(preset as ManagedInferenceServingPreset), @@ -308,11 +310,11 @@ describe("managed inference catalog compiler", () => { preset: { metadata: { id: "vllm.synthetic-model.generic-topology" } }, recipe: { metadata: { id: "vllm.synthetic-model.generic-topology.v1" } }, }); - const plan = materializeDualSparkVllmPlan( - resolution as ResolvedManagedInferenceSelection, + const plan = materializeManagedClusterVllmPlan( + resolution as ResolvedManagedInferenceSelection, { catalog }, ); - const revisionIndex = plan.roles.head.command.arguments.indexOf("--revision"); + const revisionIndex = plan.roles[0].command.arguments.indexOf("--revision"); expect(plan).toMatchObject({ model: { @@ -322,31 +324,29 @@ describe("managed inference catalog compiler", () => { }, apiPort: 8_101, readiness: { timeoutMs: 900_000, expectedModel: "synthetic-model" }, - roles: { - head: { - image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, - runtime: { - sharedMemoryBytes: 34_359_738_368, - imageDownloadSizeBytes: 2_345_678_901, - modelCache: { source: "huggingface-cache", target: "/models/synthetic-cache" }, - }, - preparation: { - ref: "none/v1", - modelDownloadSizeBytes: 12_345_678_901, - }, - environment: { - HF_HOME: "/models/synthetic-cache", - SYNTHETIC_PROFILE: "enabled", - }, - command: { executable: "/opt/vllm/bin/vllm" }, - }, + }); + expect(plan.roles[0]).toMatchObject({ + image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, + runtime: { + sharedMemoryBytes: 34_359_738_368, + imageDownloadSizeBytes: 2_345_678_901, + modelCache: { source: "huggingface-cache", target: "/models/synthetic-cache" }, + }, + preparation: { + ref: "none/v1", + modelDownloadSizeBytes: 12_345_678_901, + }, + environment: { + HF_HOME: "/models/synthetic-cache", + SYNTHETIC_PROFILE: "enabled", }, + command: { executable: "/opt/vllm/bin/vllm" }, }); expect(revisionIndex).toBeGreaterThanOrEqual(0); - expect(plan.roles.head.command.arguments[revisionIndex + 1]).toBe( + expect(plan.roles[0].command.arguments[revisionIndex + 1]).toBe( "1111111111111111111111111111111111111111", ); - expect(plan.roles.head.command.arguments).toEqual( + expect(plan.roles[0].command.arguments).toEqual( expect.arrayContaining(["--port", "8101", "--max-model-len", "131072"]), ); }); @@ -399,7 +399,7 @@ describe("managed inference catalog compiler", () => { it("derives a new definition digest when YAML profile data changes", () => { const sources = catalogSources(); const before = compileManagedInferenceCatalogSources(sources).catalog.recipes.find( - ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_RECIPE_ID, + ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_RECIPE_ID, ); const changed = replaceDefinition( sources, @@ -419,7 +419,7 @@ describe("managed inference catalog compiler", () => { }), ); const after = compileManagedInferenceCatalogSources(changed).catalog.recipes.find( - ({ definition }) => definition.metadata.id === FIXTURE_DUAL_SPARK_RECIPE_ID, + ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_RECIPE_ID, ); expect(before).toBeDefined(); expect(after).toBeDefined(); From 0e48fad0173034285495b8162abee106c50ba095 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 16:55:22 -0700 Subject: [PATCH 16/27] test(inference): keep topology coverage linear Signed-off-by: Aaron Erickson --- src/lib/inference/serving/managed-cluster-topology.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/lib/inference/serving/managed-cluster-topology.test.ts b/src/lib/inference/serving/managed-cluster-topology.test.ts index d3002a18eab..8de59e10428 100644 --- a/src/lib/inference/serving/managed-cluster-topology.test.ts +++ b/src/lib/inference/serving/managed-cluster-topology.test.ts @@ -263,8 +263,6 @@ describe("managed DGX Spark cluster topology qualification", () => { it("qualifies a three-node ring and assigns deterministic ranks", () => { const result = qualifyManagedClusterTopology(threeNodeQualificationInput()); - if (result.outcome !== "qualified") throw new Error(`${result.code}: ${result.message}`); - expect(result).toMatchObject({ outcome: "qualified" }); const artifact = (result as Extract).artifact; expect(artifact.output.nodes).toEqual([ From 02576b111c5f7c244e2f1257abbdc6602b94a0e4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 17:09:20 -0700 Subject: [PATCH 17/27] test(installer): align Spark profile wording Signed-off-by: Aaron Erickson --- test/install-express-prompt.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/install-express-prompt.test.ts b/test/install-express-prompt.test.ts index 84d50136cfc..dc23a017c29 100644 --- a/test/install-express-prompt.test.ts +++ b/test/install-express-prompt.test.ts @@ -319,7 +319,7 @@ DGX_COMMIT_ID="d0e99cc"\nDGX_PLATFORM="DGX Server for GALAXY-GB300" /Express install will configure managed local vLLM with model custom-qwen3\.6/, ); expect(output).toMatch(/The explicit model remains authoritative/); - expect(output).toMatch(/keeps the existing single-Spark profile/); + expect(output).toMatch(/keeps the existing single-host DGX Spark profile/); expect(output).toMatch( /RESULT NON_INTERACTIVE=1 SUDO_MODE=prompt PROVIDER=install-vllm MODEL= VLLM_MODEL=custom-qwen3\.6 POLICY=suggested YES=1 SANDBOX=my-assistant/, ); From 692731ad91c8da92346cd9bb450f5d355e85f89c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 17:55:08 -0700 Subject: [PATCH 18/27] fix(inference): harden managed cluster contracts Signed-off-by: Aaron Erickson --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 2 +- src/lib/inference/serving/adapter-registry.ts | 2 +- .../managed-cluster-discovery-production.ts | 53 +++++++------- .../serving/managed-cluster-discovery.test.ts | 16 ++--- .../serving/managed-cluster-discovery.ts | 34 ++++----- .../serving/managed-cluster-executor.test.ts | 45 +++++++++--- .../serving/managed-cluster-executor.ts | 32 +++++---- .../managed-cluster-fixture.test-support.ts | 37 ++++++---- .../serving/managed-cluster-identifiers.ts | 5 ++ .../serving/managed-cluster-installer.test.ts | 6 +- .../serving/managed-cluster-installer.ts | 6 +- .../serving/managed-cluster-lifecycle.test.ts | 67 +++++++++--------- .../serving/managed-cluster-lifecycle.ts | 7 +- .../managed-cluster-materialize.test.ts | 42 +++++------ .../serving/managed-cluster-materialize.ts | 11 ++- .../managed-cluster-preparation.test.ts | 9 ++- .../managed-cluster-runtime-receipt-path.ts | 6 +- .../managed-cluster-runtime-receipt.ts | 70 +++++++++++-------- ...anaged-cluster-ssh-binding.test-support.ts | 8 +++ .../serving/managed-cluster-ssh-binding.ts | 28 ++++++++ .../serving/managed-cluster-topology.test.ts | 2 +- .../serving/managed-cluster-topology.ts | 52 ++++++-------- .../serving/managed-runtime-receipts.ts | 1 - src/lib/inference/vllm-docker-env.ts | 5 +- ...lm-managed-cluster-runtime-receipt.test.ts | 63 +++++++++++------ test/vitest-watch-triggers.test.ts | 6 +- 27 files changed, 375 insertions(+), 242 deletions(-) create mode 100644 src/lib/inference/serving/managed-cluster-identifiers.ts create mode 100644 src/lib/inference/serving/managed-cluster-ssh-binding.test-support.ts create mode 100644 src/lib/inference/serving/managed-cluster-ssh-binding.ts diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 36a11be1a67..8bbd4f46e19 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -43,7 +43,7 @@ When uninstall confirms that no sibling gateways remain, it also removes the sha During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first revalidate the recorded plan and every cluster node, GPU, container, and SSH peer identity. It then removes only the exact receipt-owned containers. The managed-cluster receipt is host-global under `~/.nemoclaw/`. -A dual-DGX Station receipt uses the selected gateway state root. +A legacy dual-DGX Station receipt uses the selected gateway state root. NemoClaw starts the remaining full-uninstall steps only after distributed runtime cleanup succeeds. For a host-global managed-cluster receipt, successful cleanup also retires every recorded temporary discovery claim. An interrupted transaction can leave `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/` without a durable runtime receipt. diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml index 651f3adb37c..eb76b403e71 100644 --- a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -99,7 +99,7 @@ spec: execution: materializerRef: vllm.managed-cluster/v1 - lifecycleRef: vllm.managed-cluster/v1 + lifecycleRef: vllm.managed-cluster.lifecycle/v1 topologyBinding: sparkTopology nodeCount: 2 tensorParallelSize: 2 diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index 7c1c845ad3f..04ba4f286a1 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -12,7 +12,7 @@ import { } from "./managed-cluster-topology.js"; export const MANAGED_CLUSTER_VLLM_MATERIALIZER_REF = "vllm.managed-cluster/v1" as const; -export const MANAGED_CLUSTER_VLLM_LIFECYCLE_REF = "vllm.managed-cluster/v1" as const; +export const MANAGED_CLUSTER_VLLM_LIFECYCLE_REF = "vllm.managed-cluster.lifecycle/v1" as const; export const SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF = "snapshot-copy-and-exact-text-replacement/v1" as const; export const NO_PREPARATION_REF = "none/v1" as const; diff --git a/src/lib/inference/serving/managed-cluster-discovery-production.ts b/src/lib/inference/serving/managed-cluster-discovery-production.ts index 6ea96f8155c..a5c2ab47d32 100644 --- a/src/lib/inference/serving/managed-cluster-discovery-production.ts +++ b/src/lib/inference/serving/managed-cluster-discovery-production.ts @@ -14,16 +14,7 @@ import { createHostReadinessReport } from "../../readiness/host.js"; import { collectPlatformIdentity } from "../../readiness/platform-qualification.js"; import type { SystemReadinessReport } from "../../readiness/types.js"; import { managedVllmStateDir } from "../vllm-api-key.js"; -import { buildLocalDualStationDockerEnv, buildVllmSshTransportEnv } from "../vllm-docker-env.js"; -import { - clearDualStationSshBinding, - dualStationSshBindingDirectory, - encodeDualStationSshBindingHandoff, - type QualifiedStationSshIdentity, - stationKnownHostsDigest, - strictStationSshTransportArgs, - writeDualStationSshBinding, -} from "../vllm-station-ssh-binding.js"; +import { buildLocalManagedVllmDockerEnv, buildVllmSshTransportEnv } from "../vllm-docker-env.js"; import type { ManagedClusterCommandResult, ManagedClusterConnectivityRequest, @@ -33,6 +24,15 @@ import type { ManagedClusterReadOnlyHostTransport, } from "./managed-cluster-discovery.js"; import { MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE } from "./managed-cluster-runtime-receipt-path.js"; +import { + clearManagedVllmSshBinding, + encodeManagedVllmSshBindingHandoff, + managedVllmKnownHostsDigest, + managedVllmSshBindingDirectory, + type QualifiedManagedVllmSshIdentity, + strictManagedVllmSshTransportArgs, + writeManagedVllmSshBinding, +} from "./managed-cluster-ssh-binding.js"; const COMMAND_TIMEOUT_MS = 20_000; const MAX_COMMAND_OUTPUT_BYTES = 4 * 1024 * 1024; @@ -591,7 +591,7 @@ function createLocalTransport(spawn: ManagedClusterSpawnSync): ManagedClusterRea argv[0]!, argv.slice(1), "", - buildLocalDualStationDockerEnv({ LC_ALL: "C", LANG: "C" }), + buildLocalManagedVllmDockerEnv({ LC_ALL: "C", LANG: "C" }), ); }, readFile: readBoundedLocalFile, @@ -735,16 +735,21 @@ function trustedKnownHostLines( } if (!positive || lines.size === 0) return null; const result = [...lines].sort(compareStrings); - stationKnownHostsDigest(`${result.join("\n")}\n`); + managedVllmKnownHostsDigest(`${result.join("\n")}\n`); return result; } function inspectPretrustedTarget( spawn: ManagedClusterSpawnSync, rawTarget: string, -): QualifiedStationSshIdentity | null { +): QualifiedManagedVllmSshIdentity | null { const target = validatePeerTarget(rawTarget); - const result = runCommand(spawn, "ssh", ["-G", ...strictStationSshTransportArgs(), "--", target]); + const result = runCommand(spawn, "ssh", [ + "-G", + ...strictManagedVllmSshTransportArgs(), + "--", + target, + ]); if (!commandSucceeded(result, true)) return null; const config = parseSshConfiguration(result.stdout); assertStrictSshConfiguration(config); @@ -778,12 +783,12 @@ function inspectPretrustedTarget( sshUser, port, lookupHost, - hostKeyDigest: stationKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), + hostKeyDigest: managedVllmKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), knownHostsLines, }; } -function assertPinnedIdentity(identity: QualifiedStationSshIdentity): void { +function assertPinnedIdentity(identity: QualifiedManagedVllmSshIdentity): void { if ( validatePeerTarget(identity.sshTarget) !== identity.sshTarget || identity.requestedTarget !== identity.sshTarget || @@ -809,7 +814,7 @@ function assertPinnedIdentity(identity: QualifiedStationSshIdentity): void { identity.knownHostsLines.some( (line) => !line || line !== line.trim() || /[\u0000\r\n]/.test(line), ) || - stationKnownHostsDigest(contents) !== identity.hostKeyDigest + managedVllmKnownHostsDigest(contents) !== identity.hostKeyDigest ) { throw new Error("Qualified DGX Spark SSH host-key evidence is invalid"); } @@ -834,7 +839,7 @@ function assertTemporaryPinnedFiles( fileMetadata.uid !== uid || (fileMetadata.mode & 0o777) !== 0o600 || fs.readdirSync(directory).some((entry) => entry !== path.basename(knownHostsFile)) || - stationKnownHostsDigest(readBoundedLocalFile(knownHostsFile)) !== expectedDigest + managedVllmKnownHostsDigest(readBoundedLocalFile(knownHostsFile)) !== expectedDigest ) { throw new Error("Temporary DGX Spark SSH host-key pin is unsafe"); } @@ -842,7 +847,7 @@ function assertTemporaryPinnedFiles( function openPinnedPeerTransport( spawn: ManagedClusterSpawnSync, - identity: QualifiedStationSshIdentity, + identity: QualifiedManagedVllmSshIdentity, ): ManagedClusterPinnedPeerTransport { assertPinnedIdentity(identity); const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-cluster-")); @@ -876,7 +881,7 @@ function openPinnedPeerTransport( [ "-F", "/dev/null", - ...strictStationSshTransportArgs(), + ...strictManagedVllmSshTransportArgs(), "-o", `UserKnownHostsFile=${knownHostsFile}`, "-o", @@ -1108,7 +1113,7 @@ function createCanonicalReadiness( } function claimBinding(statePath: string): boolean { - const bindingDirectory = dualStationSshBindingDirectory(statePath); + const bindingDirectory = managedVllmSshBindingDirectory(statePath); const parent = path.dirname(bindingDirectory); const uid = process.getuid?.(); if (uid === undefined) throw new Error("DGX Spark binding claim requires a POSIX user identity"); @@ -1168,9 +1173,9 @@ export function createProductionManagedClusterDiscoveryDeps( createReadiness: createCanonicalReadiness, probeConnectivity, claimBinding, - writeBinding: writeDualStationSshBinding, - clearBinding: clearDualStationSshBinding, - encodeBinding: encodeDualStationSshBindingHandoff, + writeBinding: writeManagedVllmSshBinding, + clearBinding: clearManagedVllmSshBinding, + encodeBinding: encodeManagedVllmSshBindingHandoff, resolveBindingStatePath: (nodeId) => path.join(managedVllmStateDir(), `${MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE}.${nodeId}`), }; diff --git a/src/lib/inference/serving/managed-cluster-discovery.test.ts b/src/lib/inference/serving/managed-cluster-discovery.test.ts index f85b93eb8fe..8b601164037 100644 --- a/src/lib/inference/serving/managed-cluster-discovery.test.ts +++ b/src/lib/inference/serving/managed-cluster-discovery.test.ts @@ -9,11 +9,6 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import type { SystemReadinessReport } from "../../readiness/types.js"; -import { - type DualStationSshBinding, - type QualifiedStationSshIdentity, - stationKnownHostsDigest, -} from "../vllm-station-ssh-binding.js"; import { confirmManagedClusterManagedServingCapability, createManagedClusterDiscoveryDeps, @@ -29,6 +24,11 @@ import { } from "./managed-cluster-discovery.js"; import { FIXTURE_MANAGED_CLUSTER_PRESET_ID } from "./managed-cluster-fixture.test-support.js"; import { MANAGED_CLUSTER_MANAGED_LABEL } from "./managed-cluster-materialize.js"; +import { + type ManagedVllmSshBinding, + managedVllmKnownHostsDigest, + type QualifiedManagedVllmSshIdentity, +} from "./managed-cluster-ssh-binding.js"; const NOW = new Date("2026-08-02T20:00:00.000Z"); const SOURCE_REVISION = "1d6948d89b46eab739728215f9a19ef40b8f6121"; @@ -209,7 +209,7 @@ const transport = (name: string): ManagedClusterReadOnlyHostTransport => ({ readdir: () => [], }); -function identity(target: string): QualifiedStationSshIdentity { +function identity(target: string): QualifiedManagedVllmSshIdentity { const knownHostsLines = [`${target} ssh-ed25519 AAAA`]; return { requestedTarget: target, @@ -218,12 +218,12 @@ function identity(target: string): QualifiedStationSshIdentity { sshUser: "nvidia", port: 22, lookupHost: target, - hostKeyDigest: stationKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), + hostKeyDigest: managedVllmKnownHostsDigest(`${knownHostsLines.join("\n")}\n`), knownHostsLines, }; } -function binding(peerIdentity: QualifiedStationSshIdentity): DualStationSshBinding { +function binding(peerIdentity: QualifiedManagedVllmSshIdentity): ManagedVllmSshBinding { return { schemaVersion: 2, peerTarget: peerIdentity.sshTarget, diff --git a/src/lib/inference/serving/managed-cluster-discovery.ts b/src/lib/inference/serving/managed-cluster-discovery.ts index c880b3be535..6cc010d04c0 100644 --- a/src/lib/inference/serving/managed-cluster-discovery.ts +++ b/src/lib/inference/serving/managed-cluster-discovery.ts @@ -6,10 +6,6 @@ import path from "node:path"; import type { BuildIdentity } from "../../core/version.js"; import type { SystemReadinessReport } from "../../readiness/types.js"; -import { - type DualStationSshBinding, - type QualifiedStationSshIdentity, -} from "../vllm-station-ssh-binding.js"; import { MANAGED_CLUSTER_VLLM_MATERIALIZER_REF } from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; @@ -19,6 +15,10 @@ import { type ManagedClusterNodeSnapshot, type ManagedClusterObservedContainer, } from "./managed-cluster-lifecycle.js"; +import { + type ManagedVllmSshBinding, + type QualifiedManagedVllmSshIdentity, +} from "./managed-cluster-ssh-binding.js"; import { getManagedClusterTopologyArtifactError, type ManagedClusterNodeObservation, @@ -159,8 +159,10 @@ export interface ManagedClusterDiscoveryDeps { getBuildIdentity(): BuildIdentity; localTransport(): ManagedClusterReadOnlyHostTransport; probeHost(transport: ManagedClusterReadOnlyHostTransport): ManagedClusterHostObservation; - inspectPretrustedTarget(target: string): QualifiedStationSshIdentity | null; - openPinnedPeerTransport(identity: QualifiedStationSshIdentity): ManagedClusterPinnedPeerTransport; + inspectPretrustedTarget(target: string): QualifiedManagedVllmSshIdentity | null; + openPinnedPeerTransport( + identity: QualifiedManagedVllmSshIdentity, + ): ManagedClusterPinnedPeerTransport; createReadiness( host: ManagedClusterHostObservation, transport: ManagedClusterReadOnlyHostTransport, @@ -173,9 +175,9 @@ export interface ManagedClusterDiscoveryDeps { ): boolean; /** Atomically claim a new binding root. False means an existing owner won. */ claimBinding(statePath: string): boolean; - writeBinding(statePath: string, identity: QualifiedStationSshIdentity): DualStationSshBinding; + writeBinding(statePath: string, identity: QualifiedManagedVllmSshIdentity): ManagedVllmSshBinding; clearBinding(statePath: string): void; - encodeBinding(binding: DualStationSshBinding): string; + encodeBinding(binding: ManagedVllmSshBinding): string; resolveBindingStatePath(nodeId: string): string; } @@ -219,11 +221,11 @@ export type ManagedClusterDetectedManagedServingCapability = { export interface ManagedClusterSshClaim { readonly nodeId: string; readonly statePath: string; - readonly identity: QualifiedStationSshIdentity; + readonly identity: QualifiedManagedVllmSshIdentity; } export interface ManagedClusterSshBinding extends ManagedClusterSshClaim { - readonly binding: DualStationSshBinding; + readonly binding: ManagedVllmSshBinding; readonly handle: string; } @@ -851,7 +853,7 @@ function topologyRail(rail: QualifiedRail, peerNodeId: string): ManagedClusterRa function topologyObservations( cluster: ClusterPlan, readiness: ReadonlyMap, - identities: ReadonlyMap, + identities: ReadonlyMap, bindingHandles: ReadonlyMap, ): { local: ManagedClusterNodeObservation; peers: readonly ManagedClusterPeerObservation[] } { const controller = cluster.nodes[0]!; @@ -888,8 +890,8 @@ function hostPolicyFailure( } function samePhysicalSshIdentity( - left: QualifiedStationSshIdentity, - right: QualifiedStationSshIdentity, + left: QualifiedManagedVllmSshIdentity, + right: QualifiedManagedVllmSshIdentity, ): boolean { return ( left.sshUser === right.sshUser && @@ -899,8 +901,8 @@ function samePhysicalSshIdentity( } function sameExactSshIdentity( - left: QualifiedStationSshIdentity, - right: QualifiedStationSshIdentity, + left: QualifiedManagedVllmSshIdentity, + right: QualifiedManagedVllmSshIdentity, ): boolean { return ( left.requestedTarget === right.requestedTarget && @@ -1056,7 +1058,7 @@ export function probeManagedClusterManagedServingCapability( const unique = new Map< string, { - identity: QualifiedStationSshIdentity; + identity: QualifiedManagedVllmSshIdentity; transport: ManagedClusterReadOnlyHostTransport; host: ManagedClusterHostObservation; } diff --git a/src/lib/inference/serving/managed-cluster-executor.test.ts b/src/lib/inference/serving/managed-cluster-executor.test.ts index 380db85a6c0..f45b5c13dd8 100644 --- a/src/lib/inference/serving/managed-cluster-executor.test.ts +++ b/src/lib/inference/serving/managed-cluster-executor.test.ts @@ -2,11 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { - createDualStationSshBindingFixture, - type DualStationSshBindingFixture, -} from "../vllm-station-ssh-binding.test-support.js"; import { NO_PREPARATION_REF } from "./adapter-registry.js"; import { assertManagedClusterVllmExecutorConfig, @@ -24,6 +19,10 @@ import { type ManagedClusterVllmRole, type ManagedClusterVllmRolePlan, } from "./managed-cluster-materialize.js"; +import { + createManagedVllmSshBindingFixture, + type ManagedVllmSshBindingFixture, +} from "./managed-cluster-ssh-binding.test-support.js"; const API_KEY = "a".repeat(64); const FINGERPRINT = "b".repeat(64); @@ -66,7 +65,7 @@ const STOPPED_FOREIGN_CONTAINER_FIXTURES: readonly StoppedForeignContainerFixtur }, ]; -function bindPlan(fixture: DualStationSshBindingFixture): ManagedClusterVllmPlan { +function bindPlan(fixture: ManagedVllmSshBindingFixture): ManagedClusterVllmPlan { const plan = fixtureManagedClusterPlan(); return { ...plan, @@ -161,11 +160,11 @@ function routeDockerCapture( } describe("managed-cluster vLLM executor", () => { - let bindingFixture: DualStationSshBindingFixture; + let bindingFixture: ManagedVllmSshBindingFixture; let plan: ManagedClusterVllmPlan; beforeEach(() => { - bindingFixture = createDualStationSshBindingFixture("spark-worker.local"); + bindingFixture = createManagedVllmSshBindingFixture("spark-worker.local"); plan = bindPlan(bindingFixture); }); @@ -776,6 +775,36 @@ describe("managed-cluster vLLM executor", () => { expect(runCurlProbe).toHaveBeenCalledTimes(2); }); + it("rejects API probes after a caller-owned plan changes", async () => { + const mutablePlan = structuredClone(plan); + const runCurlProbe = vi.fn(); + const executor = createManagedClusterVllmExecutor( + { + plan: mutablePlan, + nodes: [ + { nodeId: mutablePlan.roles[0].nodeId, modelCacheRoot: LOCAL_CACHE_ROOT }, + { + nodeId: mutablePlan.roles[1].nodeId, + modelCacheRoot: PEER_CACHE_ROOT, + sshBinding: bindingFixture.binding, + }, + ], + }, + runtimeOverrides({ runCurlProbe }), + ); + const request = { + baseUrl: mutablePlan.roles[0].endpoint!, + apiKey: API_KEY, + expectedModel: mutablePlan.model.servedName, + timeoutMs: 10_000, + }; + (mutablePlan.readiness as { expectedModel: string }).expectedModel = "mutated-model"; + + await expect(executor.probeModels(request)).rejects.toThrow("changed materialized plan"); + await expect(executor.probeChat(request)).rejects.toThrow("changed materialized plan"); + expect(runCurlProbe).not.toHaveBeenCalled(); + }); + it("generates 32-hex transactions and serializes through the shared lifecycle lock", async () => { let lockCalls = 0; const withLifecycleLock = async (operation: () => Promise): Promise => { diff --git a/src/lib/inference/serving/managed-cluster-executor.ts b/src/lib/inference/serving/managed-cluster-executor.ts index aaaa4372542..5fe3d2099d5 100644 --- a/src/lib/inference/serving/managed-cluster-executor.ts +++ b/src/lib/inference/serving/managed-cluster-executor.ts @@ -11,15 +11,11 @@ import { dockerCapture } from "../../adapters/docker/run.js"; import { createBearerAuthConfig } from "../../adapters/http/auth-config.js"; import { runCurlProbe } from "../../adapters/http/probe.js"; import { - buildLocalDualStationDockerEnv, + buildLocalManagedVllmDockerEnv, buildRemoteVllmDockerEnv, captureManagedVllmTcpListeners, } from "../vllm-docker-env.js"; import { withHostGlobalVllmLifecycleLock } from "../vllm-station-lifecycle-lock.js"; -import { - type DualStationSshBinding, - encodeDualStationSshBindingHandoff, -} from "../vllm-station-ssh-binding.js"; import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, @@ -56,6 +52,10 @@ import { managedClusterHeadRole, } from "./managed-cluster-materialize.js"; import { materializeManagedClusterVllmPreparation } from "./managed-cluster-preparation.js"; +import { + encodeManagedVllmSshBindingHandoff, + type ManagedVllmSshBinding, +} from "./managed-cluster-ssh-binding.js"; import { MANAGED_CLUSTER_TOPOLOGY_ID, MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, @@ -112,7 +112,7 @@ export interface ManagedClusterExecutorStageTarget { readonly nodeId: string; readonly dockerEnv: Readonly>; readonly modelCacheRoot: string; - readonly sshBinding?: DualStationSshBinding; + readonly sshBinding?: ManagedVllmSshBinding; } export type ManagedClusterExecutorStageNode = ( @@ -129,14 +129,14 @@ export interface CreateManagedClusterVllmExecutorOptions { export interface ManagedClusterExecutorNodeTarget { readonly nodeId: string; readonly modelCacheRoot: string; - readonly sshBinding?: DualStationSshBinding; + readonly sshBinding?: ManagedVllmSshBinding; } export interface ManagedClusterVllmExecutorRuntimeDeps { dockerCapture: typeof dockerCapture; dockerForceRm: typeof dockerForceRm; dockerRunDetached: typeof dockerRunDetached; - captureListeners(rolePlan: ManagedClusterVllmRolePlan, binding?: DualStationSshBinding): string; + captureListeners(rolePlan: ManagedClusterVllmRolePlan, binding?: ManagedVllmSshBinding): string; createBearerAuthConfig: typeof createBearerAuthConfig; createTransactionId(): string; now(): number; @@ -157,7 +157,7 @@ const DEFAULT_DEPS: ManagedClusterVllmExecutorRuntimeDeps = { } return captureManagedVllmTcpListeners( rolePlan.role, - binding ?? ({} as DualStationSshBinding), + binding ?? ({} as ManagedVllmSshBinding), DOCKER_INSPECTION_TIMEOUT_MS, ); }, @@ -363,7 +363,7 @@ export function assertManagedClusterVllmExecutorConfig( (!target.sshBinding || rolePlan.execution.expectedTarget !== target.sshBinding.peerTarget || rolePlan.execution.bindingHandle !== - encodeDualStationSshBindingHandoff(target.sshBinding))) + encodeManagedVllmSshBindingHandoff(target.sshBinding))) ) { throw new Error(`Managed cluster executor target ${target.nodeId} is invalid`); } @@ -688,7 +688,7 @@ function roleDockerEnv( const target = targetFor(rolePlan, config); const env = rolePlan.execution.kind === "local" - ? buildLocalDualStationDockerEnv() + ? buildLocalManagedVllmDockerEnv() : buildRemoteVllmDockerEnv(target.sshBinding!); delete env.VLLM_API_KEY; return env; @@ -817,7 +817,7 @@ async function waitForRoleProcess( do { try { const observed = exactWaitObservation( - await inspectRoleNode(request.rolePlan, config, deps), + inspectRoleNode(request.rolePlan, config, deps), request, ); const headAbsent = @@ -1013,7 +1013,7 @@ export function createManagedClusterVllmExecutor( } let observed: ManagedClusterObservedContainer | null = null; try { - const snapshot = await inspectRoleNode(request.rolePlan, config, deps); + const snapshot = inspectRoleNode(request.rolePlan, config, deps); const candidates = snapshot.containers.filter( (container) => container.name === request.rolePlan.containerName && @@ -1056,7 +1056,7 @@ export function createManagedClusterVllmExecutor( if (!CONTAINER_ID_PATTERN.test(exactContainerId)) { return { ok: false, reason: `${rolePlan.role} cleanup container ID is invalid` }; } - const before = await inspectRoleNode(rolePlan, config, deps); + const before = inspectRoleNode(rolePlan, config, deps); const matches = before.containers.filter(({ id }) => id === exactContainerId); if ( matches.length !== 1 || @@ -1082,7 +1082,7 @@ export function createManagedClusterVllmExecutor( } if (!removed) { try { - const after = await inspectRoleNode(rolePlan, config, deps); + const after = inspectRoleNode(rolePlan, config, deps); removed = !after.containers.some(({ id }) => id === exactContainerId); } catch { removed = false; @@ -1093,6 +1093,7 @@ export function createManagedClusterVllmExecutor( : { ok: false, reason: `${rolePlan.role} exact container removal failed` }; }, async probeModels(request) { + assertPlan(config.plan); if ( request.baseUrl !== managedClusterHeadRole(config.plan).endpoint || request.expectedModel !== config.plan.readiness.expectedModel @@ -1102,6 +1103,7 @@ export function createManagedClusterVllmExecutor( return await probeAuthenticatedApi(request, "models", deps); }, async probeChat(request) { + assertPlan(config.plan); if ( request.baseUrl !== managedClusterHeadRole(config.plan).endpoint || request.expectedModel !== config.plan.readiness.expectedModel diff --git a/src/lib/inference/serving/managed-cluster-fixture.test-support.ts b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts index 017f67a2e48..fb4d77fe8d5 100644 --- a/src/lib/inference/serving/managed-cluster-fixture.test-support.ts +++ b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { MANAGED_CLUSTER_VLLM_MATERIALIZER_REF } from "./adapter-registry.js"; import { loadManagedInferenceCatalog } from "./catalog.js"; import type { ResolvedManagedInferenceSelection } from "./catalog-types.js"; import { @@ -8,24 +9,34 @@ import { materializeManagedClusterVllmPlan, } from "./managed-cluster-materialize.js"; import { + MANAGED_CLUSTER_TOPOLOGY_ID, + MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, type ManagedClusterTopologyOutput, managedClusterTopologyOutputDigest, managedClusterTopologySubjectDigest, } from "./managed-cluster-topology.js"; -export const FIXTURE_MANAGED_CLUSTER_PRESET_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731"; - -export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelection { +function fixtureCatalogDefinitions() { const catalog = loadManagedInferenceCatalog(); - const compiledPreset = catalog.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, - ); - const compiledRecipe = catalog.recipes.find( - ({ definition }) => definition.metadata.id === compiledPreset?.definition.spec.plan.recipeRef, - ); - if (!compiledPreset || !compiledRecipe) { - throw new Error("managed inference fixture catalog is incomplete"); + for (const compiledPreset of catalog.presets) { + const compiledRecipe = catalog.recipes.find( + ({ definition }) => definition.metadata.id === compiledPreset.definition.spec.plan.recipeRef, + ); + if ( + compiledRecipe?.definition.spec.execution.materializerRef === + MANAGED_CLUSTER_VLLM_MATERIALIZER_REF + ) { + return { catalog, compiledPreset, compiledRecipe }; + } } + throw new Error("managed inference fixture catalog is incomplete"); +} + +export const FIXTURE_MANAGED_CLUSTER_PRESET_ID = + fixtureCatalogDefinitions().compiledPreset.definition.metadata.id; + +export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelection { + const { catalog, compiledPreset, compiledRecipe } = fixtureCatalogDefinitions(); const preset = structuredClone(compiledPreset.definition); const recipe = structuredClone(compiledRecipe.definition); const subjectNodeIds = ["spark-head", "spark-worker"] as const; @@ -105,8 +116,8 @@ export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelect preset, recipe, topologyQualification: { - id: "host-cluster.direct-cx7", - schemaVersion: 1, + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, status: "qualified", subjectNodeIds, subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), diff --git a/src/lib/inference/serving/managed-cluster-identifiers.ts b/src/lib/inference/serving/managed-cluster-identifiers.ts new file mode 100644 index 00000000000..ab1247e11a9 --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-identifiers.ts @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** Shared bounded identity contract for cluster nodes and hardware observations. */ +export const MANAGED_CLUSTER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; diff --git a/src/lib/inference/serving/managed-cluster-installer.test.ts b/src/lib/inference/serving/managed-cluster-installer.test.ts index 62b8c22028b..a8a4004da85 100644 --- a/src/lib/inference/serving/managed-cluster-installer.test.ts +++ b/src/lib/inference/serving/managed-cluster-installer.test.ts @@ -487,6 +487,7 @@ describe("managed-cluster vLLM installer selection", () => { const beforeInstall = vi.fn(); const clearBinding = vi.fn(); const persistReceipt = vi.fn(); + const stageCalls: string[] = []; let capturedStage: ManagedClusterExecutorStageNode | undefined; const executor = {} as ManagedClusterVllmLifecycleDeps; const createExecutor = vi.fn((config: CreateManagedClusterVllmExecutorOptions) => { @@ -494,7 +495,7 @@ describe("managed-cluster vLLM installer selection", () => { return executor; }); const start = vi.fn(async (plan) => { - expect(capturedStage).toBeDefined(); + stageCalls.push(plan.roles[1].nodeId); await capturedStage!( { rolePlan: plan.roles[1], preparation: plan.roles[1].preparation }, { @@ -504,6 +505,7 @@ describe("managed-cluster vLLM installer selection", () => { sshBinding: confirmed.sshBindings[0].binding, }, ); + stageCalls.push(plan.roles[0].nodeId); await capturedStage!( { rolePlan: plan.roles[0], preparation: plan.roles[0].preparation }, { @@ -539,6 +541,8 @@ describe("managed-cluster vLLM installer selection", () => { ); expect(result).toEqual({ kind: "handled", result: { ok: true } }); + expect(capturedStage).toBeDefined(); + expect(stageCalls).toEqual(["spark-worker", "spark-head"]); expect(beforeInstall).toHaveBeenCalledWith("deepseek-v4-flash-0731"); expect(installEffects.pullImage).toHaveBeenCalledTimes(2); expect(installEffects.downloadModel).toHaveBeenNthCalledWith( diff --git a/src/lib/inference/serving/managed-cluster-installer.ts b/src/lib/inference/serving/managed-cluster-installer.ts index 3dc4fbc1997..de354a8c226 100644 --- a/src/lib/inference/serving/managed-cluster-installer.ts +++ b/src/lib/inference/serving/managed-cluster-installer.ts @@ -5,7 +5,6 @@ import { isAffirmativeAnswer } from "../../onboard/prompt-helpers.js"; import type { VllmProfile } from "../vllm.js"; import { ensureManagedVllmApiKey } from "../vllm-api-key.js"; import { assertGatedModelAccess, VLLM_EXTRA_ARGS_ENV, type VllmModelDef } from "../vllm-models.js"; -import { clearDualStationSshBinding } from "../vllm-station-ssh-binding.js"; import { imageStorageRequirementBytes, modelStorageRequirementBytes } from "../vllm-storage.js"; import { type ManagedInferenceResolution, @@ -42,6 +41,7 @@ import { type PersistManagedClusterVllmRuntimeReceiptInput, persistManagedClusterVllmRuntimeReceipt, } from "./managed-cluster-runtime-receipt.js"; +import { clearManagedVllmSshBinding } from "./managed-cluster-ssh-binding.js"; import type { ManagedClusterTopologyOutput } from "./managed-cluster-topology.js"; import { assertNoManagedDistributedVllmRuntimeReceipts } from "./managed-runtime-receipts.js"; import { resolveManagedInferenceServing } from "./resolver.js"; @@ -87,7 +87,7 @@ interface ManagedClusterInstallerDeps { readonly persistReceipt: typeof persistManagedClusterVllmRuntimeReceipt; readonly ensureApiKey: typeof ensureManagedVllmApiKey; readonly assertNoRuntimeReceipts: typeof assertNoManagedDistributedVllmRuntimeReceipts; - readonly clearBinding: typeof clearDualStationSshBinding; + readonly clearBinding: typeof clearManagedVllmSshBinding; readonly assertGatedModelAccess: typeof assertGatedModelAccess; readonly log: (line?: string) => void; readonly error: (line: string) => void; @@ -106,7 +106,7 @@ const DEFAULT_DEPS: ManagedClusterInstallerDeps = { persistReceipt: persistManagedClusterVllmRuntimeReceipt, ensureApiKey: ensureManagedVllmApiKey, assertNoRuntimeReceipts: assertNoManagedDistributedVllmRuntimeReceipts, - clearBinding: clearDualStationSshBinding, + clearBinding: clearManagedVllmSshBinding, assertGatedModelAccess, log: (line = "") => console.log(line), error: (line) => console.error(line), diff --git a/src/lib/inference/serving/managed-cluster-lifecycle.test.ts b/src/lib/inference/serving/managed-cluster-lifecycle.test.ts index b70b0522aa5..94e0d69486e 100644 --- a/src/lib/inference/serving/managed-cluster-lifecycle.test.ts +++ b/src/lib/inference/serving/managed-cluster-lifecycle.test.ts @@ -81,23 +81,22 @@ function managedContainer( function classifiedSnapshots( plan: ManagedClusterVllmPlan, - snapshots: Record, + snapshots: Record, ) { return plan.roles.map((rolePlan) => ({ nodeId: rolePlan.nodeId, - snapshot: snapshots[rolePlan.role], + snapshot: snapshots[rolePlan.nodeId], })); } function createHarness(plan: ManagedClusterVllmPlan) { const events: string[] = []; - const snapshots: Record = { - head: { containers: [], listeningPorts: [] }, - worker: { containers: [], listeningPorts: [] }, - }; + const snapshots: Record = Object.fromEntries( + plan.roles.map(({ nodeId }) => [nodeId, { containers: [], listeningPorts: [] }]), + ); const inspectNode = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan) => { events.push(`inspect:${rolePlan.role}`); - return snapshots[rolePlan.role]; + return snapshots[rolePlan.nodeId]; }); const stageNode = vi.fn(async ({ rolePlan }: { rolePlan: ManagedClusterVllmRolePlan }) => { events.push(`stage:${rolePlan.role}`); @@ -107,8 +106,8 @@ function createHarness(plan: ManagedClusterVllmPlan) { const { rolePlan, labels } = request; events.push(`start:${rolePlan.role}`); const id = rolePlan.role === "head" ? HEAD_ID : WORKER_ID; - snapshots[rolePlan.role] = { - ...snapshots[rolePlan.role], + snapshots[rolePlan.nodeId] = { + ...snapshots[rolePlan.nodeId], containers: [ { id, @@ -132,9 +131,9 @@ function createHarness(plan: ManagedClusterVllmPlan) { }); const removeContainer = vi.fn(async (rolePlan: ManagedClusterVllmRolePlan, id: string) => { events.push(`remove:${rolePlan.role}:${id}`); - snapshots[rolePlan.role] = { - ...snapshots[rolePlan.role], - containers: snapshots[rolePlan.role].containers.filter((container) => container.id !== id), + snapshots[rolePlan.nodeId] = { + ...snapshots[rolePlan.nodeId], + containers: snapshots[rolePlan.nodeId]!.containers.filter((container) => container.id !== id), }; return { ok: true }; }); @@ -191,7 +190,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { }); it("preserves singleton, Station, and related external setups", async () => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [ { id: "9".repeat(64), @@ -216,7 +215,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { it.each( STOPPED_FOREIGN_CONTAINER_FIXTURES, )("preserves a stopped foreign vLLM setup identified by $signal", async (container) => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [ { id: "9".repeat(64), @@ -240,7 +239,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { it("does not classify an arbitrary stopped container as a managed vLLM setup", () => { const snapshots = { - head: { + [plan.roles[0].nodeId]: { containers: [ { id: "9".repeat(64), @@ -253,7 +252,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { ], listeningPorts: [], }, - worker: { containers: [], listeningPorts: [] }, + [plan.roles[1].nodeId]: { containers: [], listeningPorts: [] }, }; expect( @@ -266,11 +265,11 @@ describe("automatic managed-cluster vLLM lifecycle", () => { }); it("reuses only one exact healthy cluster with the same transaction", async () => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [managedContainer(plan, "head")], listeningPorts: [8000], }; - harness.snapshots.worker = { + harness.snapshots[plan.roles[1].nodeId] = { containers: [managedContainer(plan, "worker")], listeningPorts: [25000], }; @@ -292,11 +291,11 @@ describe("automatic managed-cluster vLLM lifecycle", () => { }); it("does not implicitly repair a stopped or partial managed deployment", async () => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [managedContainer(plan, "head", { running: false, healthy: false })], listeningPorts: [], }; - harness.snapshots.worker = { + harness.snapshots[plan.roles[1].nodeId] = { containers: [managedContainer(plan, "worker")], listeningPorts: [], }; @@ -330,7 +329,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { it("retains SSH ownership when a failed worker create leaves runtime state", async () => { harness.startContainer.mockImplementation(async ({ rolePlan, labels }) => { - harness.snapshots.worker = { + harness.snapshots[plan.roles[1].nodeId] = { containers: [ { id: WORKER_ID, @@ -390,9 +389,9 @@ describe("automatic managed-cluster vLLM lifecycle", () => { it("leaves a container untouched when transaction ownership changes before rollback", async () => { harness.probeChat.mockImplementation(async () => { - const worker = harness.snapshots.worker.containers[0]!; - harness.snapshots.worker = { - ...harness.snapshots.worker, + const worker = harness.snapshots[plan.roles[1].nodeId]!.containers[0]!; + harness.snapshots[plan.roles[1].nodeId] = { + ...harness.snapshots[plan.roles[1].nodeId], containers: [ { ...worker, @@ -414,7 +413,7 @@ describe("automatic managed-cluster vLLM lifecycle", () => { "worker rollback ownership changed; container was left untouched", ); expect(harness.removeContainer.mock.calls.map((call) => call[1])).toEqual([HEAD_ID]); - expect(harness.snapshots.worker.containers).toHaveLength(1); + expect(harness.snapshots[plan.roles[1].nodeId]!.containers).toHaveLength(1); }); it("classifies port conflicts on either node as nonselectable", () => { @@ -423,8 +422,8 @@ describe("automatic managed-cluster vLLM lifecycle", () => { plan, managedClusterVllmApiKeyFingerprint(API_KEY), classifiedSnapshots(plan, { - head: { containers: [], listeningPorts: [] }, - worker: { containers: [], listeningPorts: [25000] }, + [plan.roles[0].nodeId]: { containers: [], listeningPorts: [] }, + [plan.roles[1].nodeId]: { containers: [], listeningPorts: [25000] }, }), ), ).toEqual({ @@ -434,11 +433,11 @@ describe("automatic managed-cluster vLLM lifecycle", () => { }); it("cleans up only a complete exact cluster and retains all cache state", async () => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [managedContainer(plan, "head")], listeningPorts: [], }; - harness.snapshots.worker = { + harness.snapshots[plan.roles[1].nodeId] = { containers: [managedContainer(plan, "worker")], listeningPorts: [], }; @@ -453,11 +452,11 @@ describe("automatic managed-cluster vLLM lifecycle", () => { }); it("retries cleanup after one receipt-owned container was already removed", async () => { - harness.snapshots.head = { + harness.snapshots[plan.roles[0].nodeId] = { containers: [managedContainer(plan, "head")], listeningPorts: [], }; - harness.snapshots.worker = { + harness.snapshots[plan.roles[1].nodeId] = { containers: [managedContainer(plan, "worker")], listeningPorts: [], }; @@ -466,9 +465,9 @@ describe("automatic managed-cluster vLLM lifecycle", () => { const shouldFailWorker = rolePlan.role === "worker" && workerAttempts === 0; workerAttempts += Number(rolePlan.role === "worker"); const removeOwnedContainer = () => { - harness.snapshots[rolePlan.role] = { - ...harness.snapshots[rolePlan.role], - containers: harness.snapshots[rolePlan.role].containers.filter( + harness.snapshots[rolePlan.nodeId] = { + ...harness.snapshots[rolePlan.nodeId], + containers: harness.snapshots[rolePlan.nodeId]!.containers.filter( (container) => container.id !== id, ), }; diff --git a/src/lib/inference/serving/managed-cluster-lifecycle.ts b/src/lib/inference/serving/managed-cluster-lifecycle.ts index 1a64139fe0f..15013e92ae0 100644 --- a/src/lib/inference/serving/managed-cluster-lifecycle.ts +++ b/src/lib/inference/serving/managed-cluster-lifecycle.ts @@ -10,6 +10,7 @@ import { MANAGED_CLUSTER_VLLM_PROJECT_ID, type ManagedClusterVllmPlan, type ManagedClusterVllmRolePlan, + managedClusterHeadRole, } from "./managed-cluster-materialize.js"; const API_KEY_PATTERN = /^[a-f0-9]{64}$/; @@ -536,7 +537,7 @@ async function probeManagedApi( apiKey: string, deps: Pick, ): Promise { - const baseUrl = plan.roles.find(({ rank }) => rank === 0)?.endpoint; + const baseUrl = managedClusterHeadRole(plan).endpoint; if (!baseUrl) return false; const request = { baseUrl, @@ -651,7 +652,7 @@ async function startNewCluster( return { ok: true, reusedExisting: false, - baseUrl: plan.roles.find(({ rank }) => rank === 0)!.endpoint!, + baseUrl: managedClusterHeadRole(plan).endpoint!, containers: created.map(({ rolePlan, containerId }) => ({ nodeId: rolePlan.nodeId, containerId, @@ -693,7 +694,7 @@ export async function startAutomaticManagedClusterVllm( return { ok: true, reusedExisting: true, - baseUrl: plan.roles.find(({ rank }) => rank === 0)!.endpoint!, + baseUrl: managedClusterHeadRole(plan).endpoint!, containers: preflight.containers, apiKeyFingerprint, }; diff --git a/src/lib/inference/serving/managed-cluster-materialize.test.ts b/src/lib/inference/serving/managed-cluster-materialize.test.ts index 2eb65cca993..fdec7414a36 100644 --- a/src/lib/inference/serving/managed-cluster-materialize.test.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.test.ts @@ -391,6 +391,20 @@ describe("managed-cluster vLLM materializer", () => { expect(() => materializeManagedClusterVllmPlan(selection)).toThrow(/master address/u); }); + it("selects each role endpoint by direct reachability to the qualified master", () => { + const selection = selectionWithDigests(); + const artifact = selection.topologyQualification; + (artifact.output as { masterAddress: string }).masterAddress = "192.168.101.10"; + (artifact as { outputDigest: string }).outputDigest = managedClusterTopologyOutputDigest( + artifact.output, + ); + + const plan = materializeManagedClusterVllmPlan(selection); + + expect(plan.roles[0].fabric.address).toBe("192.168.101.10"); + expect(plan.roles[1].fabric.address).toBe("192.168.101.11"); + }); + it("materializes bounded preparation operations from recipe data", () => { const selection = selectionWithDigests(); const preparation = materializeManagedClusterVllmPlan(selection).roles[0].preparation; @@ -483,28 +497,16 @@ describe("managed-cluster vLLM materializer", () => { expect(originalFromExpandedCatalog.planId).toBe(originalPlan.planId); }); - it("takes cluster cardinality and parallelism from a synthetic three-node catalog profile", () => { + it("rejects a larger catalog profile only when its fabric cannot reach the master", () => { const { catalog, selection } = syntheticSecondProfile("/dev/shm-scratch", 3); - const plan = materializeManagedClusterVllmPlan(selection, { catalog }); - expect(plan.roles).toHaveLength(3); - expect(plan.roles.map(({ rank, role }) => ({ rank, role }))).toEqual([ - { rank: 0, role: "head" }, - { rank: 1, role: "worker" }, - { rank: 2, role: "worker" }, - ]); - for (const role of plan.roles) { - expect(role.command.arguments).toEqual( - expect.arrayContaining([ - "--nnodes", - "3", - "--tensor-parallel-size", - "3", - "--node-rank", - String(role.rank), - ]), - ); - } + expect(selection.recipe.spec.execution).toMatchObject({ + nodeCount: 3, + tensorParallelSize: 3, + }); + expect(() => materializeManagedClusterVllmPlan(selection, { catalog })).toThrow( + /spark-worker-b has no direct fabric endpoint to master address/u, + ); }); it("rejects a temporary filesystem that shadows the model cache", () => { diff --git a/src/lib/inference/serving/managed-cluster-materialize.ts b/src/lib/inference/serving/managed-cluster-materialize.ts index 410cea99a5f..60d3047a171 100644 --- a/src/lib/inference/serving/managed-cluster-materialize.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.ts @@ -511,7 +511,14 @@ function rolePlan(input: RolePlanInput): ManagedClusterVllmRolePlan { const output = selection.topologyQualification.output; const { nodeId, rank, role } = node; const fabricEndpoints = endpointsForNode(output, nodeId); - const primaryEndpoint = fabricEndpoints[0]!; + const primaryEndpoint = fabricEndpoints.find((endpoint) => + role === "head" + ? endpoint.address === output.masterAddress + : endpoint.peerAddress === output.masterAddress, + ); + if (!primaryEndpoint) { + fail(`node ${nodeId} has no direct fabric endpoint to master address ${output.masterAddress}`); + } const peer = output.peers.find((candidate) => candidate.nodeId === nodeId); if (rank > 0 && !peer) fail(`worker rank ${String(rank)} is missing its SSH binding`); const baseLabels = { @@ -547,7 +554,7 @@ function rolePlan(input: RolePlanInput): ManagedClusterVllmRolePlan { rank, nodeId, gpuId: node.gpuId, - containerName: `nemoclaw-vllm-cluster-rank-${String(rank)}`, + containerName: `${MANAGED_CLUSTER_VLLM_PROJECT_ID}-rank-${String(rank)}`, execution: role === "head" ? { kind: "local" } diff --git a/src/lib/inference/serving/managed-cluster-preparation.test.ts b/src/lib/inference/serving/managed-cluster-preparation.test.ts index 753cf4fc488..7edbc6cb530 100644 --- a/src/lib/inference/serving/managed-cluster-preparation.test.ts +++ b/src/lib/inference/serving/managed-cluster-preparation.test.ts @@ -72,6 +72,7 @@ describe("managed cluster vLLM preparation materializer", () => { it.each([ { label: "snapshot traversal", + error: /snapshot copy source path must be a normalized relative POSIX path/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: "../escape.py", targetPath: "/opt/vllm/copied.py" }, @@ -84,6 +85,7 @@ describe("managed cluster vLLM preparation materializer", () => { }, { label: "relative container target", + error: /snapshot copy target path must be a normalized absolute container path/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: "safe.py", targetPath: "relative/copied.py" }, @@ -96,6 +98,7 @@ describe("managed cluster vLLM preparation materializer", () => { }, { label: "unchanged replacement", + error: /exact-text replacement must change the matched text/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: "safe.py", targetPath: "/opt/vllm/copied.py" }, @@ -106,7 +109,9 @@ describe("managed cluster vLLM preparation materializer", () => { }, }, }, - ])("rejects bounded operation input with $label", ({ preparation }) => { - expect(() => materializeManagedClusterVllmPreparation({ ...MODEL, preparation })).toThrow(); + ])("rejects bounded operation input with $label", ({ error, preparation }) => { + expect(() => materializeManagedClusterVllmPreparation({ ...MODEL, preparation })).toThrow( + error, + ); }); }); diff --git a/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts b/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts index ba72b49559f..628369b5a3e 100644 --- a/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts +++ b/src/lib/inference/serving/managed-cluster-runtime-receipt-path.ts @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { MANAGED_CLUSTER_ID_PATTERN } from "./managed-cluster-identifiers.js"; + export const MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE = "managed-cluster-vllm-runtime.json"; export const MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE = "managed-cluster-managed-serving.json"; -const SAFE_NODE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; const RUNTIME_BINDING_PREFIX = `${MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE}.rank-`; const DISCOVERY_BINDING_PREFIX = `${MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE}.`; const BINDING_SUFFIX = ".ssh-binding"; @@ -12,11 +13,12 @@ const BINDING_SUFFIX = ".ssh-binding"; export function isManagedClusterRuntimeBindingStateEntry(entry: string): boolean { if (!entry.startsWith(RUNTIME_BINDING_PREFIX) || !entry.endsWith(BINDING_SUFFIX)) return false; const rank = entry.slice(RUNTIME_BINDING_PREFIX.length, -BINDING_SUFFIX.length); + // Rank 0 is local; only remote SSH execution roles own copied binding directories. return /^(?:[1-9]\d{0,3})$/u.test(rank) && Number(rank) <= 1_023; } export function isManagedClusterDiscoveryBindingStateEntry(entry: string): boolean { if (!entry.startsWith(DISCOVERY_BINDING_PREFIX) || !entry.endsWith(BINDING_SUFFIX)) return false; const nodeId = entry.slice(DISCOVERY_BINDING_PREFIX.length, -BINDING_SUFFIX.length); - return SAFE_NODE_ID_PATTERN.test(nodeId); + return MANAGED_CLUSTER_ID_PATTERN.test(nodeId); } diff --git a/src/lib/inference/serving/managed-cluster-runtime-receipt.ts b/src/lib/inference/serving/managed-cluster-runtime-receipt.ts index 2544d14a898..fc0537dbb4e 100644 --- a/src/lib/inference/serving/managed-cluster-runtime-receipt.ts +++ b/src/lib/inference/serving/managed-cluster-runtime-receipt.ts @@ -6,14 +6,6 @@ import path from "node:path"; import { ensureLocalAdapterStateDir } from "../local-adapter-lifecycle"; import { loadManagedVllmApiKey, managedVllmStateDir } from "../vllm-api-key"; -import { - clearDualStationSshBinding, - copyDualStationSshBinding, - type DualStationSshBinding, - encodeDualStationSshBindingHandoff, - loadDualStationSshBindingForStatePath, - loadDualStationSshBindingHandoff, -} from "../vllm-station-ssh-binding"; import { managedInferenceHexDigest } from "./catalog-integrity"; import { assertManagedClusterVllmExecutorConfig, @@ -21,6 +13,7 @@ import { inspectManagedClusterVllmNodesSync, type ManagedClusterVllmNodeSnapshots, } from "./managed-cluster-executor"; +import { MANAGED_CLUSTER_ID_PATTERN } from "./managed-cluster-identifiers"; import { classifyManagedClusterExistingState, cleanupManagedClusterManagedVllm, @@ -29,6 +22,14 @@ import { } from "./managed-cluster-lifecycle"; import { type ManagedClusterVllmPlan, managedClusterHeadRole } from "./managed-cluster-materialize"; import { MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE } from "./managed-cluster-runtime-receipt-path"; +import { + clearManagedVllmSshBinding, + copyManagedVllmSshBinding, + encodeManagedVllmSshBindingHandoff, + loadManagedVllmSshBindingForStatePath, + loadManagedVllmSshBindingHandoff, + type ManagedVllmSshBinding, +} from "./managed-cluster-ssh-binding"; const MAX_RECEIPT_BYTES = 128 * 1024; const SHA256 = /^[a-f0-9]{64}$/; @@ -43,7 +44,13 @@ const RECEIPT_NODE_KEYS = [ "nodeId", "sshBinding", ] as const; -const EXACT_BINDING_KEYS = [ +function exactBindingKeys( + keys: Keys & (Exclude extends never ? unknown : never), +): Keys { + return keys; +} + +const EXACT_BINDING_KEYS = exactBindingKeys([ "schemaVersion", "peerTarget", "resolvedHost", @@ -60,7 +67,7 @@ const EXACT_BINDING_KEYS = [ "sshWrapperDirectory", "sshWrapperFile", "sshWrapperSha256", -] as const satisfies readonly (keyof DualStationSshBinding)[]; +] as const); interface PersistedReceipt { readonly schemaVersion: 1; @@ -89,7 +96,7 @@ export interface PersistManagedClusterVllmRuntimeReceiptNode { readonly nodeId: string; readonly cacheRoot: string; readonly containerId: string; - readonly sshBinding?: DualStationSshBinding; + readonly sshBinding?: ManagedVllmSshBinding; readonly discoveryStatePath?: string; } @@ -100,7 +107,7 @@ export interface LoadedManagedClusterVllmRuntime { } export interface LoadedManagedClusterVllmRuntimeNode extends PersistedReceiptNode { - readonly binding?: DualStationSshBinding; + readonly binding?: ManagedVllmSshBinding; } type CleanupDeps = Pick< @@ -212,6 +219,9 @@ function parseReceipt(value: unknown): PersistedReceipt { throw new Error("Managed cluster vLLM runtime receipt schema is unsupported"); } const plan = value.plan as unknown as ManagedClusterVllmPlan; + if (!Array.isArray(plan.roles)) { + throw new Error("Managed cluster runtime receipt node ownership is incomplete"); + } const digest = requireString(value.planDigest, "managed cluster plan digest", SHA256, 64); if (planDigest(plan) !== digest) throw new Error("Managed cluster vLLM runtime plan digest changed"); @@ -224,7 +234,7 @@ function parseReceipt(value: unknown): PersistedReceipt { const nodeId = requireString( entry.nodeId, "managed cluster node ID", - /^[A-Za-z0-9._:-]+$/, + MANAGED_CLUSTER_ID_PATTERN, 128, ); const rolePlan = plan.roles.find((role) => role.nodeId === nodeId); @@ -407,11 +417,11 @@ function durablePlan( function loadedRuntime(receipt: PersistedReceipt): LoadedManagedClusterVllmRuntime { const nodes = receipt.nodes.map((node): LoadedManagedClusterVllmRuntimeNode => { if (node.sshBinding === null) return node; - const binding = loadDualStationSshBindingHandoff( + const binding = loadManagedVllmSshBindingHandoff( node.sshBinding, workerTarget(receipt.plan, node.nodeId), ); - if (encodeDualStationSshBindingHandoff(binding) !== node.sshBinding) { + if (encodeManagedVllmSshBindingHandoff(binding) !== node.sshBinding) { throw new Error("Managed cluster runtime SSH binding identity changed"); } return { ...node, binding }; @@ -420,7 +430,7 @@ function loadedRuntime(receipt: PersistedReceipt): LoadedManagedClusterVllmRunti return { ...receipt, nodes }; } -function bindingDigest(binding: DualStationSshBinding): string { +function bindingDigest(binding: ManagedVllmSshBinding): string { return managedInferenceHexDigest( Object.fromEntries(EXACT_BINDING_KEYS.map((field) => [field, binding[field]])), ); @@ -428,11 +438,11 @@ function bindingDigest(binding: DualStationSshBinding): string { function loadReceiptOwnedDiscoveryBinding( runtime: LoadedManagedClusterVllmRuntime, -): readonly { readonly nodeId: string; readonly binding: DualStationSshBinding | null }[] { +): readonly { readonly nodeId: string; readonly binding: ManagedVllmSshBinding | null }[] { return runtime.nodes .filter((node) => node.binding) .map((node) => { - const binding = loadDualStationSshBindingForStatePath( + const binding = loadManagedVllmSshBindingForStatePath( node.discoveryStatePath!, node.binding!.peerTarget, node.binding!.hostKeyDigest, @@ -465,12 +475,13 @@ function sameInput( ), ), ); + const existingNodes = new Map(existing.nodes.map((node) => [node.nodeId, node])); return ( planDigest(durable) === planDigest(existing.plan) && input.apiKeyFingerprint === existing.apiKeyFingerprint && input.nodes.length === existing.nodes.length && - input.nodes.every((node, index) => { - const current = existing.nodes[index]; + input.nodes.every((node) => { + const current = existingNodes.get(node.nodeId); return ( current?.nodeId === node.nodeId && current.cacheRoot === node.cacheRoot && @@ -514,7 +525,7 @@ export function persistManagedClusterVllmRuntimeReceipt( nodeId: node.nodeId, cacheRoot, containerId: node.containerId, - sshBinding: node.sshBinding ? encodeDualStationSshBindingHandoff(node.sshBinding) : null, + sshBinding: node.sshBinding ? encodeManagedVllmSshBindingHandoff(node.sshBinding) : null, discoveryStatePath: node.discoveryStatePath ?? null, discoveryBindingDigest: node.sshBinding ? bindingDigest(node.sshBinding) : null, ...(node.sshBinding ? { binding: node.sshBinding } : {}), @@ -534,11 +545,12 @@ export function persistManagedClusterVllmRuntimeReceipt( const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); const createdBindingStatePaths: string[] = []; try { - const runtimeBindings = new Map(); - const persistedNodes = inputNodes.map((node, rank): PersistedReceiptNode => { + const runtimeBindings = new Map(); + const persistedNodes = inputNodes.map((node, index): PersistedReceiptNode => { const { binding, ...persisted } = node; if (!binding) return persisted; - const runtimeStatePath = `${receiptPath}.rank-${String(rank)}`; + const rolePlan = input.plan.roles[index]!; + const runtimeStatePath = `${receiptPath}.rank-${String(rolePlan.rank)}`; const bindingPath = `${runtimeStatePath}.ssh-binding`; try { fs.mkdirSync(bindingPath, { mode: 0o700 }); @@ -549,9 +561,9 @@ export function persistManagedClusterVllmRuntimeReceipt( throw error; } createdBindingStatePaths.push(runtimeStatePath); - const runtimeBinding = copyDualStationSshBinding(runtimeStatePath, binding); + const runtimeBinding = copyManagedVllmSshBinding(runtimeStatePath, binding); runtimeBindings.set(node.nodeId, runtimeBinding); - return { ...persisted, sshBinding: encodeDualStationSshBindingHandoff(runtimeBinding) }; + return { ...persisted, sshBinding: encodeManagedVllmSshBindingHandoff(runtimeBinding) }; }); fsyncDirectory(stateDir); const plan = durablePlan( @@ -579,7 +591,7 @@ export function persistManagedClusterVllmRuntimeReceipt( } catch (error) { try { for (const statePath of createdBindingStatePaths.reverse()) { - clearDualStationSshBinding(statePath); + clearManagedVllmSshBinding(statePath); } } catch { // Preserve the receipt persistence error. @@ -593,7 +605,7 @@ function clearReceipt(stateDir: string, runtime: LoadedManagedClusterVllmRuntime fs.unlinkSync(filePath); for (const rolePlan of runtime.plan.roles) { if (rolePlan.execution.kind === "ssh") { - clearDualStationSshBinding(`${filePath}.rank-${String(rolePlan.rank)}`); + clearManagedVllmSshBinding(`${filePath}.rank-${String(rolePlan.rank)}`); } } fsyncDirectory(stateDir); @@ -715,7 +727,7 @@ export async function cleanupInstalledManagedClusterVllmRuntime( for (const entry of currentDiscoveryBindings) { if (entry.binding) { const node = runtime.nodes.find(({ nodeId }) => nodeId === entry.nodeId)!; - clearDualStationSshBinding(node.discoveryStatePath!); + clearManagedVllmSshBinding(node.discoveryStatePath!); } } clearReceipt(stateDir, runtime); diff --git a/src/lib/inference/serving/managed-cluster-ssh-binding.test-support.ts b/src/lib/inference/serving/managed-cluster-ssh-binding.test-support.ts new file mode 100644 index 00000000000..a97f9670263 --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-ssh-binding.test-support.ts @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export type { DualStationSshBindingFixture as ManagedVllmSshBindingFixture } from "../vllm-station-ssh-binding.test-support.js"; +export { + createDualStationSshBindingFixture as createManagedVllmSshBindingFixture, + retargetDualStationSshBindingFixture as retargetManagedVllmSshBindingFixture, +} from "../vllm-station-ssh-binding.test-support.js"; diff --git a/src/lib/inference/serving/managed-cluster-ssh-binding.ts b/src/lib/inference/serving/managed-cluster-ssh-binding.ts new file mode 100644 index 00000000000..e0e143008ea --- /dev/null +++ b/src/lib/inference/serving/managed-cluster-ssh-binding.ts @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export type { + DualStationSshBinding as ManagedVllmSshBinding, + QualifiedStationSshIdentity as QualifiedManagedVllmSshIdentity, + WriteDualStationSshBindingOptions as WriteManagedVllmSshBindingOptions, +} from "../vllm-station-ssh-binding.js"; +/** + * Cardinality-neutral names for the pinned SSH transport shared by managed + * vLLM clusters. The legacy Station implementation remains the compatibility + * provider until that existing path is migrated to the serving catalog. + */ +export { + assertDualStationSshBindingFiles as assertManagedVllmSshBindingFiles, + clearDualStationSshBinding as clearManagedVllmSshBinding, + copyDualStationSshBinding as copyManagedVllmSshBinding, + dualStationDockerSshUri as managedVllmDockerSshUri, + dualStationPinnedSshArgs as managedVllmPinnedSshArgs, + dualStationSshBindingDirectory as managedVllmSshBindingDirectory, + encodeDualStationSshBindingHandoff as encodeManagedVllmSshBindingHandoff, + loadDualStationSshBinding as loadManagedVllmSshBinding, + loadDualStationSshBindingForStatePath as loadManagedVllmSshBindingForStatePath, + loadDualStationSshBindingHandoff as loadManagedVllmSshBindingHandoff, + stationKnownHostsDigest as managedVllmKnownHostsDigest, + strictStationSshTransportArgs as strictManagedVllmSshTransportArgs, + writeDualStationSshBinding as writeManagedVllmSshBinding, +} from "../vllm-station-ssh-binding.js"; diff --git a/src/lib/inference/serving/managed-cluster-topology.test.ts b/src/lib/inference/serving/managed-cluster-topology.test.ts index 8de59e10428..3ba75b7ba05 100644 --- a/src/lib/inference/serving/managed-cluster-topology.test.ts +++ b/src/lib/inference/serving/managed-cluster-topology.test.ts @@ -252,7 +252,7 @@ describe("managed DGX Spark cluster topology qualification", () => { ).toEqual(expect.arrayContaining(["spark-head", "spark-worker"])); }); - it("reports a fabric mismatch rather than rejecting a larger cluster by cardinality", () => { + it("reports a fabric mismatch when two peers claim the same rail addresses", () => { expect( qualifyManagedClusterTopology(qualificationInput([peerNode(), peerNode(1)])), ).toMatchObject({ diff --git a/src/lib/inference/serving/managed-cluster-topology.ts b/src/lib/inference/serving/managed-cluster-topology.ts index 1f3ddddad5a..ed13c46dfae 100644 --- a/src/lib/inference/serving/managed-cluster-topology.ts +++ b/src/lib/inference/serving/managed-cluster-topology.ts @@ -7,11 +7,11 @@ import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility import type { SystemReadinessReport } from "../../readiness/types.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; import type { ManagedInferenceTopologyQualification } from "./catalog-types.js"; +import { MANAGED_CLUSTER_ID_PATTERN } from "./managed-cluster-identifiers.js"; export const MANAGED_CLUSTER_TOPOLOGY_ID = "host-cluster.direct-cx7" as const; export const MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION = 1 as const; -const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const SAFE_INTERFACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/; const SAFE_BINDING_HANDLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,8191}$/; const SSH_USERNAME_PATTERN = /^[A-Za-z_][A-Za-z0-9._-]*$/; @@ -139,8 +139,7 @@ export type ManagedClusterTopologyFailureCode = | "ssh-binding-unavailable" | "fabric-degraded" | "fabric-multiple" - | "fabric-mismatch" - | "artifact-digest-failed"; + | "fabric-mismatch"; export type ManagedClusterTopologyQualificationResult = | { outcome: "qualified"; artifact: ManagedClusterTopologyArtifact } @@ -250,13 +249,13 @@ function validateNode( evaluatedAtMs: number, maxReadinessAgeMs: number, ): QualifiedNode | QualificationFailure { - if (!SAFE_ID_PATTERN.test(node.nodeId)) { + if (!MANAGED_CLUSTER_ID_PATTERN.test(node.nodeId)) { return { code: "node-identity-unavailable", message: "A node identity is missing or invalid.", }; } - if (node.gpuIds.length !== 1 || !SAFE_ID_PATTERN.test(node.gpuIds[0] ?? "")) { + if (node.gpuIds.length !== 1 || !MANAGED_CLUSTER_ID_PATTERN.test(node.gpuIds[0] ?? "")) { return { code: "gpu-identity-unavailable", message: "Each DGX Spark node must have exactly one valid GPU identity.", @@ -305,7 +304,7 @@ function validateRail(rail: ManagedClusterRailObservation): ValidatedRail | Qual }; } if ( - !SAFE_ID_PATTERN.test(rail.physicalPortId) || + !MANAGED_CLUSTER_ID_PATTERN.test(rail.physicalPortId) || !SAFE_INTERFACE_PATTERN.test(rail.netdev) || !SAFE_INTERFACE_PATTERN.test(rail.hcaDevice) || !Number.isInteger(rail.hcaPort) || @@ -314,7 +313,7 @@ function validateRail(rail: ManagedClusterRailObservation): ValidatedRail | Qual !validAddress(rail.address, rail.prefixLength) || net.isIP(rail.peerAddress) === 0 || rail.address === rail.peerAddress || - !SAFE_ID_PATTERN.test(rail.peerNodeId) + !MANAGED_CLUSTER_ID_PATTERN.test(rail.peerNodeId) ) { return { code: "fabric-mismatch", @@ -593,7 +592,7 @@ function topologyOutputError( const output = record(value); if (!output) return "topology qualification output is invalid"; const controllerNodeId = output.controllerNodeId; - if (typeof controllerNodeId !== "string" || !SAFE_ID_PATTERN.test(controllerNodeId)) { + if (typeof controllerNodeId !== "string" || !MANAGED_CLUSTER_ID_PATTERN.test(controllerNodeId)) { return "topology controller node is invalid"; } if (!Array.isArray(output.nodes) || output.nodes.length !== subjectNodeIds.length) { @@ -610,9 +609,9 @@ function topologyOutputError( node.rank !== rank || node.role !== (rank === 0 ? "head" : "worker") || typeof node.nodeId !== "string" || - !SAFE_ID_PATTERN.test(node.nodeId) || + !MANAGED_CLUSTER_ID_PATTERN.test(node.nodeId) || typeof node.gpuId !== "string" || - !SAFE_ID_PATTERN.test(node.gpuId), + !MANAGED_CLUSTER_ID_PATTERN.test(node.gpuId), ) || nodeIds[0] !== controllerNodeId || new Set(nodeIds).size !== nodeIds.length || @@ -753,7 +752,7 @@ export function getManagedClusterTopologyArtifactError( subjectNodeIds.length < 2 || subjectNodeIds.length > 1024 || new Set(subjectNodeIds).size !== subjectNodeIds.length || - subjectNodeIds.some((nodeId) => !SAFE_ID_PATTERN.test(nodeId)) || + subjectNodeIds.some((nodeId) => !MANAGED_CLUSTER_ID_PATTERN.test(nodeId)) || subjectNodeIds.some((nodeId, index) => index > 0 && subjectNodeIds[index - 1]! >= nodeId) ) { return "topology qualification subject is invalid"; @@ -858,23 +857,16 @@ export function qualifyManagedClusterTopology( }), }; const subjectNodeIds = [...nodeIds].sort(compareStrings); - try { - return { - outcome: "qualified", - artifact: { - id: MANAGED_CLUSTER_TOPOLOGY_ID, - schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, - status: "qualified", - subjectNodeIds, - subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), - outputDigest: managedClusterTopologyOutputDigest(output), - output, - }, - }; - } catch { - return failure(input.intent, { - code: "artifact-digest-failed", - message: "The qualified topology could not be bound to its subject and output.", - }); - } + return { + outcome: "qualified", + artifact: { + id: MANAGED_CLUSTER_TOPOLOGY_ID, + schemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, + status: "qualified", + subjectNodeIds, + subjectDigest: managedClusterTopologySubjectDigest(subjectNodeIds), + outputDigest: managedClusterTopologyOutputDigest(output), + output, + }, + }; } diff --git a/src/lib/inference/serving/managed-runtime-receipts.ts b/src/lib/inference/serving/managed-runtime-receipts.ts index a98a4655b19..c720da8341e 100644 --- a/src/lib/inference/serving/managed-runtime-receipts.ts +++ b/src/lib/inference/serving/managed-runtime-receipts.ts @@ -11,7 +11,6 @@ import { DUAL_STATION_VLLM_RUNTIME_RECEIPT_FILE } from "../vllm-station-runtime- import { isManagedClusterDiscoveryBindingStateEntry, isManagedClusterRuntimeBindingStateEntry, - MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE, MANAGED_CLUSTER_VLLM_RUNTIME_RECEIPT_FILE, } from "./managed-cluster-runtime-receipt-path"; diff --git a/src/lib/inference/vllm-docker-env.ts b/src/lib/inference/vllm-docker-env.ts index 70e76c56c31..77302fc7939 100644 --- a/src/lib/inference/vllm-docker-env.ts +++ b/src/lib/inference/vllm-docker-env.ts @@ -148,6 +148,9 @@ export function buildLocalDualStationDockerEnv( return env; } +/** Cardinality-neutral name for managed-cluster consumers. */ +export const buildLocalManagedVllmDockerEnv = buildLocalDualStationDockerEnv; + /** Minimal environment shared by strict SSH probes and Docker's SSH helper. */ export function buildVllmSshTransportEnv( extra: Record = {}, @@ -161,7 +164,7 @@ export function buildVllmSshTransportEnv( return { ...env, ...extra }; } -/** Capture the listening TCP sockets from one side of a pinned managed-vLLM pair. */ +/** Capture the listening TCP sockets from one node in a pinned managed-vLLM cluster. */ export function captureManagedVllmTcpListeners( role: "head" | "worker", binding: DualStationSshBinding, diff --git a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts index ff05f9c86a1..7c2cab4ee23 100644 --- a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts @@ -7,7 +7,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { loadManagedInferenceCatalog } from "./serving/catalog"; -import { managedInferenceDigest } from "./serving/catalog-integrity"; +import { managedInferenceDigest, managedInferenceHexDigest } from "./serving/catalog-integrity"; import type { CompiledManagedInferenceCatalog } from "./serving/catalog-types"; import { fixtureManagedClusterSelection } from "./serving/managed-cluster-fixture.test-support"; import { @@ -31,17 +31,17 @@ import { recoverInstalledManagedClusterVllmEndpoint, } from "./serving/managed-cluster-runtime-receipt"; import { MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE } from "./serving/managed-cluster-runtime-receipt-path"; -import { managedClusterTopologyOutputDigest } from "./serving/managed-cluster-topology"; import { - clearDualStationSshBinding, - copyDualStationSshBinding, - type DualStationSshBinding, - encodeDualStationSshBindingHandoff, -} from "./vllm-station-ssh-binding"; + clearManagedVllmSshBinding, + copyManagedVllmSshBinding, + encodeManagedVllmSshBindingHandoff, + type ManagedVllmSshBinding, +} from "./serving/managed-cluster-ssh-binding"; import { - createDualStationSshBindingFixture, - type DualStationSshBindingFixture, -} from "./vllm-station-ssh-binding.test-support"; + createManagedVllmSshBindingFixture, + type ManagedVllmSshBindingFixture, +} from "./serving/managed-cluster-ssh-binding.test-support"; +import { managedClusterTopologyOutputDigest } from "./serving/managed-cluster-topology"; const API_KEY = "a".repeat(64); const HEAD_ID = "b".repeat(64); @@ -50,12 +50,12 @@ const TRANSACTION_ID = "d".repeat(32); let root: string; let stateDir: string; -let sshFixture: DualStationSshBindingFixture; +let sshFixture: ManagedVllmSshBindingFixture; beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-cluster-runtime-receipt-")); stateDir = path.join(root, ".nemoclaw"); - sshFixture = createDualStationSshBindingFixture("nvidia@spark-worker.local"); + sshFixture = createManagedVllmSshBindingFixture("nvidia@spark-worker.local"); }); afterEach(() => { @@ -66,7 +66,7 @@ afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); -function plan(sshBinding: DualStationSshBinding = sshFixture.binding): ManagedClusterVllmPlan { +function plan(sshBinding: ManagedVllmSshBinding = sshFixture.binding): ManagedClusterVllmPlan { const selection = fixtureManagedClusterSelection(); const sourceTopology = selection.topologyQualification; const output = { @@ -74,7 +74,7 @@ function plan(sshBinding: DualStationSshBinding = sshFixture.binding): ManagedCl peers: sourceTopology.output.peers.map((peer) => ({ ...peer, target: sshBinding.peerTarget, - sshBindingHandle: encodeDualStationSshBindingHandoff(sshBinding), + sshBindingHandle: encodeManagedVllmSshBindingHandoff(sshBinding), })), }; return materializeManagedClusterVllmPlan({ @@ -88,7 +88,7 @@ function plan(sshBinding: DualStationSshBinding = sshFixture.binding): ManagedCl } function input( - sshBinding: DualStationSshBinding = sshFixture.binding, + sshBinding: ManagedVllmSshBinding = sshFixture.binding, ): PersistManagedClusterVllmRuntimeReceiptInput { const runtimePlan = plan(sshBinding); return { @@ -114,11 +114,11 @@ function catalogWithUnrelatedProfile(): CompiledManagedInferenceCatalog { const selectedRecipe = current.recipes[0]!; const unrelatedRecipe = { ...selectedRecipe.definition, - metadata: { ...selectedRecipe.definition.metadata, id: "vllm.unrelated.spark-dual.v1" }, + metadata: { ...selectedRecipe.definition.metadata, id: "vllm.unrelated.managed-cluster.v1" }, }; const unrelatedPreset = { ...selectedPreset.definition, - metadata: { ...selectedPreset.definition.metadata, id: "vllm.unrelated.spark-dual" }, + metadata: { ...selectedPreset.definition.metadata, id: "vllm.unrelated.managed-cluster" }, spec: { ...selectedPreset.definition.spec, plan: { @@ -130,11 +130,11 @@ function catalogWithUnrelatedProfile(): CompiledManagedInferenceCatalog { const sourceFiles = [ ...current.sourceFiles, { - path: "managed-inference/presets/vllm.unrelated.spark-dual.yaml", + path: "managed-inference/presets/vllm.unrelated.managed-cluster.yaml", digest: `sha256:${"1".repeat(64)}`, }, { - path: "managed-inference/recipes/vllm.unrelated.spark-dual.v1.yaml", + path: "managed-inference/recipes/vllm.unrelated.managed-cluster.v1.yaml", digest: `sha256:${"2".repeat(64)}`, }, ] as const; @@ -170,7 +170,7 @@ function persistWithDiscoveryBinding(): { } { fs.mkdirSync(stateDir, { mode: 0o700 }); const discoveryStatePath = path.join(stateDir, MANAGED_CLUSTER_MANAGED_SERVING_STATE_FILE); - const binding = copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + const binding = copyManagedVllmSshBinding(discoveryStatePath, sshFixture.binding); return { discoveryBindingPath: `${discoveryStatePath}.ssh-binding`, discoveryStatePath, @@ -265,6 +265,12 @@ describe("managed cluster vLLM runtime receipt", () => { const original = fs.readFileSync(receiptPath, "utf8"); expect(persistManagedClusterVllmRuntimeReceipt(source, { stateDir })).toEqual(first); + expect( + persistManagedClusterVllmRuntimeReceipt( + { ...source, nodes: [...source.nodes].reverse() }, + { stateDir }, + ), + ).toEqual(first); expect(() => persistManagedClusterVllmRuntimeReceipt( { @@ -357,6 +363,19 @@ describe("managed cluster vLLM runtime receipt", () => { expect(() => loadManagedClusterVllmRuntimeReceipt({ stateDir })).toThrow("plan digest changed"); }); + it("rejects a digest-valid receipt whose plan omits role ownership", () => { + persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); + const receiptPath = managedClusterVllmRuntimeReceiptPath(stateDir); + const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf8")); + receipt.plan.roles = {}; + receipt.planDigest = managedInferenceHexDigest(receipt.plan); + fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { mode: 0o600 }); + + expect(() => loadManagedClusterVllmRuntimeReceipt({ stateDir })).toThrow( + "node ownership is incomplete", + ); + }); + it("recovers only the exact healthy receipt-owned endpoint synchronously", () => { const runtime = persistManagedClusterVllmRuntimeReceipt(input(), { stateDir }); expect( @@ -429,8 +448,8 @@ describe("managed cluster vLLM runtime receipt", () => { it("preserves a replaced canonical discovery binding before container cleanup", async () => { const { discoveryBindingPath, discoveryStatePath, runtime } = persistWithDiscoveryBinding(); - clearDualStationSshBinding(discoveryStatePath); - copyDualStationSshBinding(discoveryStatePath, sshFixture.binding); + clearManagedVllmSshBinding(discoveryStatePath); + copyManagedVllmSshBinding(discoveryStatePath, sshFixture.binding); const { deps, removeContainer } = cleanupDeps(runtime.plan); const createLifecycleDeps = vi.fn(() => deps); diff --git a/test/vitest-watch-triggers.test.ts b/test/vitest-watch-triggers.test.ts index dc5f0679e77..e9cca2cd0ad 100644 --- a/test/vitest-watch-triggers.test.ts +++ b/test/vitest-watch-triggers.test.ts @@ -48,7 +48,7 @@ const E2E_WORKFLOW_CONTRACTS = [ ] as const; const OPAQUE_INPUTS = [ - "managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml", + "managed-inference/recipes/vllm.example.managed-cluster.v1.yaml", "Dockerfile", "agents/hermes/Dockerfile", "agents/langchain-deepagents-code/Dockerfile", @@ -88,9 +88,7 @@ describe("Vitest opaque-input watch triggers", () => { }); it("maps current opaque inputs to their direct contract tests (#6692)", () => { - expect( - triggeredBy("managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml"), - ).toEqual([ + expect(triggeredBy("managed-inference/recipes/vllm.example.managed-cluster.v1.yaml")).toEqual([ "src/lib/inference/serving/catalog.test.ts", "src/lib/inference/serving/resolver.test.ts", "test/managed-inference-catalog-compiler.test.ts", From 975c688bd166ad2fccb8b2f7c5dc966b0772082f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 18:03:52 -0700 Subject: [PATCH 19/27] chore(mcp): drop unrelated audit pin changes Signed-off-by: Aaron Erickson --- .../package-lock.json | 18 +++++++++--------- tools/mcp-tool-discovery-runtime/package.json | 4 +--- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/tools/mcp-tool-discovery-runtime/package-lock.json b/tools/mcp-tool-discovery-runtime/package-lock.json index 192c1694a38..f5cc6c8aea8 100644 --- a/tools/mcp-tool-discovery-runtime/package-lock.json +++ b/tools/mcp-tool-discovery-runtime/package-lock.json @@ -947,9 +947,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", + "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", "funding": [ { "type": "github", @@ -1084,9 +1084,9 @@ } }, "node_modules/hono": { - "version": "4.12.34", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.34.tgz", - "integrity": "sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA==", + "version": "4.12.30", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.30.tgz", + "integrity": "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -1135,9 +1135,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz", - "integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", "license": "MIT", "engines": { "node": ">= 12" diff --git a/tools/mcp-tool-discovery-runtime/package.json b/tools/mcp-tool-discovery-runtime/package.json index d8e5569f426..73aa3261835 100644 --- a/tools/mcp-tool-discovery-runtime/package.json +++ b/tools/mcp-tool-discovery-runtime/package.json @@ -16,9 +16,7 @@ }, "overrides": { "@hono/node-server": "2.0.11", - "fast-uri": "3.1.5", - "hono": "4.12.34", - "ip-address": "10.4.0" + "fast-uri": "3.1.4" }, "engines": { "node": ">=22.19.0" From d0513107c7a1dce4b126ead9173ee6049dd4bec1 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 21:37:55 -0700 Subject: [PATCH 20/27] refactor(inference): use canonical serving catalog Signed-off-by: Aaron Erickson --- .gitignore | 3 - .pre-commit-config.yaml | 2 +- managed-inference/schemas/catalog.schema.json | 84 +-- managed-inference/schemas/preset.schema.json | 24 +- managed-inference/schemas/recipe.schema.json | 39 +- package.json | 10 +- scripts/managed-inference/compile-catalog.mts | 434 ------------- .../serving/adapter-registry.test.ts | 9 +- src/lib/inference/serving/adapter-registry.ts | 40 +- src/lib/inference/serving/catalog-loader.ts | 55 ++ src/lib/inference/serving/catalog.test.ts | 363 +++++++++-- src/lib/inference/serving/catalog.ts | 594 +++++++++++++----- src/lib/inference/serving/generate-catalog.ts | 84 +++ .../serving/managed-cluster-discovery.ts | 11 +- .../serving/managed-cluster-executor.ts | 27 +- .../managed-cluster-fixture.test-support.ts | 22 +- .../serving/managed-cluster-installer.ts | 6 +- .../managed-cluster-materialize.test.ts | 49 +- .../serving/managed-cluster-materialize.ts | 21 +- .../serving/managed-cluster-topology.ts | 2 +- src/lib/inference/serving/resolver.test.ts | 68 +- src/lib/inference/serving/resolver.ts | 26 +- .../serving/{catalog-types.ts => types.ts} | 232 +++++-- ...lm-managed-cluster-runtime-receipt.test.ts | 69 +- .../support/e2e-semantic-phase-check.test.ts | 6 +- ...managed-inference-catalog-compiler.test.ts | 594 +++--------------- .../managed-inference-catalog.test.ts | 113 ++-- 27 files changed, 1454 insertions(+), 1533 deletions(-) delete mode 100644 scripts/managed-inference/compile-catalog.mts create mode 100644 src/lib/inference/serving/catalog-loader.ts create mode 100644 src/lib/inference/serving/generate-catalog.ts rename src/lib/inference/serving/{catalog-types.ts => types.ts} (50%) diff --git a/.gitignore b/.gitignore index e1548b6b329..bb4d9305487 100644 --- a/.gitignore +++ b/.gitignore @@ -9,9 +9,6 @@ coverage/ dist/ docs/_build/ node_modules/ -# Managed inference compiler output and its pre-JSON legacy path. -src/lib/inference/serving/generated/catalog.ts -src/lib/inference/serving/generated/catalog.json # OS metadata .DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 90119417586..95c4f387a11 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -172,7 +172,7 @@ repos: entry: npm run catalog:check language: system pass_filenames: false - files: ^(managed-inference/(?:presets|recipes)/.*\.yaml$|managed-inference/schemas/.*\.json$|scripts/managed-inference/compile-catalog\.mts$|src/lib/inference/serving/(?:adapter-registry|catalog-integrity|catalog-types)\.ts$) + files: ^(managed-inference/(?:presets|recipes)/.*\.yaml$|managed-inference/schemas/.*\.json$|src/lib/inference/serving/(?:adapter-registry|catalog|generate-catalog|types)\.ts$) priority: 10 - id: repository-checks diff --git a/managed-inference/schemas/catalog.schema.json b/managed-inference/schemas/catalog.schema.json index d3a51fac651..ba141726798 100644 --- a/managed-inference/schemas/catalog.schema.json +++ b/managed-inference/schemas/catalog.schema.json @@ -2,72 +2,52 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/catalog.schema.json", "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0", + "title": "NemoClaw compiled managed inference serving catalog", "type": "object", - "required": ["catalogDigest", "compilerVersion", "presets", "recipes", "schemaVersion", "sourceFiles", "sourceRevision"], + "required": [ + "schemaVersion", + "compilerVersion", + "sourceRevision", + "readinessSchemaRef", + "recipes", + "presets", + "sources", + "catalogDigest" + ], "properties": { - "catalogDigest": { "$ref": "#/$defs/digest" }, + "schemaVersion": { "const": "1.0.0" }, "compilerVersion": { "const": "1.0.0" }, - "presets": { - "type": "array", - "minItems": 1, - "items": { - "allOf": [ - { "$ref": "#/$defs/compiledDefinition" }, - { - "type": "object", - "properties": { - "definition": { "$ref": "preset.schema.json" } - } - } - ] - } + "sourceRevision": { "type": "string", "pattern": "^[0-9a-f]{40,64}$" }, + "readinessSchemaRef": { + "const": "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json" }, "recipes": { "type": "array", - "minItems": 1, - "items": { - "allOf": [ - { "$ref": "#/$defs/compiledDefinition" }, - { - "type": "object", - "properties": { - "definition": { "$ref": "recipe.schema.json" } - } - } - ] - } + "items": { "$ref": "recipe.schema.json" } }, - "schemaVersion": { "const": "1.0.0" }, - "sourceFiles": { + "presets": { + "type": "array", + "items": { "$ref": "preset.schema.json" } + }, + "sources": { "type": "array", - "minItems": 2, "items": { "type": "object", - "required": ["digest", "path"], + "required": ["path", "kind", "id", "digest"], "properties": { - "digest": { "$ref": "#/$defs/digest" }, - "path": { "type": "string", "pattern": "^managed-inference/(?:presets|recipes)/[a-z0-9._-]+\\.yaml$" } + "path": { + "type": "string", + "pattern": "^managed-inference/(?:recipes|presets)/.+\\.ya?ml$", + "maxLength": 512 + }, + "kind": { "enum": ["ServingRecipe", "ServingPreset"] }, + "id": { "type": "string", "minLength": 1, "maxLength": 160 }, + "digest": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" } }, "additionalProperties": false } }, - "sourceRevision": { "$ref": "#/$defs/digest" } + "catalogDigest": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" } }, - "additionalProperties": false, - "$defs": { - "digest": { - "type": "string", - "pattern": "^sha256:[0-9a-f]{64}$" - }, - "compiledDefinition": { - "type": "object", - "required": ["definition", "definitionDigest", "sourceFile"], - "properties": { - "definition": { "type": "object" }, - "definitionDigest": { "$ref": "#/$defs/digest" }, - "sourceFile": { "type": "string" } - }, - "additionalProperties": false - } - } + "additionalProperties": false } diff --git a/managed-inference/schemas/preset.schema.json b/managed-inference/schemas/preset.schema.json index c49b8d0e1bd..b891ea52413 100644 --- a/managed-inference/schemas/preset.schema.json +++ b/managed-inference/schemas/preset.schema.json @@ -10,7 +10,7 @@ "metadata": { "$ref": "#/$defs/metadata" }, "spec": { "type": "object", - "required": ["selection", "priority", "requirements", "plan"], + "required": ["selection", "priority", "plan"], "properties": { "selection": { "enum": ["automatic", "explicit-only", "disabled"] }, "priority": { "type": "integer", "minimum": -1000000, "maximum": 1000000 }, @@ -36,7 +36,7 @@ }, "plan": { "type": "object", - "required": ["backend", "recipeRef", "bindings"], + "required": ["backend", "recipeRef"], "properties": { "backend": { "$ref": "#/$defs/token" }, "recipeRef": { "$ref": "#/$defs/stableId" }, @@ -58,7 +58,7 @@ "$defs": { "metadata": { "type": "object", - "required": ["id", "displayName"], + "required": ["id"], "properties": { "id": { "$ref": "#/$defs/stableId" }, "displayName": { "type": "string", "minLength": 1, "maxLength": 128 } @@ -78,7 +78,7 @@ "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }, "scope": { - "enum": ["everyNode", "anyNode"] + "enum": ["controller", "everyNode", "anyNode"] }, "state": { "type": "string", @@ -129,12 +129,24 @@ "operator": { "enum": ["equals", "oneOf", "atLeast", "atMost", "between"] }, "value": { "oneOf": [ - { "type": ["string", "number", "boolean"] }, + { + "oneOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" } + ] + }, { "type": "array", "minItems": 1, "maxItems": 128, - "items": { "type": ["string", "number", "boolean"] } + "items": { + "oneOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" } + ] + } } ] } diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json index 9a56b71f063..6dd98c23200 100644 --- a/managed-inference/schemas/recipe.schema.json +++ b/managed-inference/schemas/recipe.schema.json @@ -10,7 +10,7 @@ "metadata": { "$ref": "#/$defs/metadata" }, "spec": { "type": "object", - "required": ["backend", "bindings", "model", "runtime", "execution", "serve", "readiness"], + "required": ["backend", "model", "execution"], "properties": { "backend": { "$ref": "#/$defs/token" }, "bindings": { @@ -22,21 +22,39 @@ }, "model": { "type": "object", - "required": ["id", "revision", "servedName", "downloadSizeBytes", "gated", "installFastSafetensors", "preparation"], + "required": ["id", "revision"], "properties": { "id": { "type": "string", "pattern": "^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$", "maxLength": 256 }, - "revision": { "type": "string", "pattern": "^[0-9a-f]{40,64}$" }, + "revision": { "type": "string", "pattern": "^(?:[0-9a-f]{40}|[0-9a-f]{64}|sha256:[0-9a-f]{64})$" }, "servedName": { "$ref": "#/$defs/stableId" }, "downloadSizeBytes": { "$ref": "#/$defs/positiveSafeInteger" }, "gated": { "type": "boolean" }, "installFastSafetensors": { "type": "boolean" }, - "preparation": { "$ref": "#/$defs/modelPreparation" } + "preparation": { "$ref": "#/$defs/modelPreparation" }, + "files": { + "type": "array", + "minItems": 1, + "maxItems": 32, + "items": { + "type": "object", + "required": ["path", "digest"], + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^(?!\\.{1,2}(?:/|$))(?!.*\\/\\.{1,2}(?:/|$))[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$" + }, + "digest": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" } + }, + "additionalProperties": false + } + } }, "additionalProperties": false }, "runtime": { "type": "object", - "required": ["image", "imageDownloadSizeBytes", "pullTimeoutSeconds", "architecture", "networkMode", "ipcMode", "sharedMemoryBytes", "gpuRequest", "devices", "ulimits", "modelCache", "temporaryFilesystems", "environment"], "properties": { "image": { "type": "string", "pattern": "^[a-z0-9.-]+(?::[0-9]+)?(?:/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$", "maxLength": 1024 }, "imageDownloadSizeBytes": { "$ref": "#/$defs/positiveSafeInteger" }, @@ -85,13 +103,19 @@ "maxProperties": 128, "propertyNames": { "pattern": "^[A-Z][A-Z0-9_]{0,127}$" }, "additionalProperties": { "type": "string", "maxLength": 4096 } + }, + "components": { + "type": "object", + "maxProperties": 32, + "propertyNames": { "$ref": "#/$defs/stableId" }, + "additionalProperties": { "type": "string", "minLength": 1, "maxLength": 128 } } }, "additionalProperties": false }, "execution": { "type": "object", - "required": ["materializerRef", "lifecycleRef", "topologyBinding", "nodeCount", "tensorParallelSize", "pipelineParallelSize", "distributedExecutorBackend", "rendezvousPort"], + "required": ["materializerRef", "lifecycleRef"], "properties": { "materializerRef": { "$ref": "#/$defs/stableId" }, "lifecycleRef": { "$ref": "#/$defs/stableId" }, @@ -106,7 +130,6 @@ }, "serve": { "type": "object", - "required": ["authentication", "executable", "arguments"], "properties": { "authentication": { "$ref": "#/$defs/token" }, "executable": { "$ref": "#/$defs/absolutePath" }, @@ -149,7 +172,7 @@ "$defs": { "metadata": { "type": "object", - "required": ["id", "displayName"], + "required": ["id"], "properties": { "id": { "$ref": "#/$defs/stableId" }, "displayName": { "type": "string", "minLength": 1, "maxLength": 128 } diff --git a/package.json b/package.json index c95b3a0d962..5647788d063 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "test:watch": "npm run catalog:compile && vitest watch --project cli --project plugin --project e2e-support", "test:shuffle": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", "test:diagnose:leaks": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", - "test:e2e-phases:check": "npm run catalog:compile && npm run build:policy-boundary && node --experimental-strip-types --no-warnings tools/e2e/check-semantic-phases.mts", + "test:e2e-phases:check": "npm run build:policy-boundary && node --experimental-strip-types --no-warnings tools/e2e/check-semantic-phases.mts", "test:runtime-audit": "tsx scripts/audit-test-runtime.mts", "test:integration": "npm run clean:cli && npm run build:cli && vitest run --project integration --project installer-integration", "test:package": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project package-contract", @@ -55,11 +55,11 @@ "check:installer-hash": "bash scripts/check-installer-hash.sh", "typecheck": "tsc -p jsconfig.json", "build:policy-boundary": "tsc -p nemoclaw/tsconfig.shared.json", - "catalog:compile": "tsx scripts/managed-inference/compile-catalog.mts --write", - "catalog:check": "tsx scripts/managed-inference/compile-catalog.mts", - "build:cli": "npm run build:policy-boundary && npm run catalog:compile && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", + "catalog:compile": "tsx src/lib/inference/serving/generate-catalog.ts", + "catalog:check": "tsx src/lib/inference/serving/generate-catalog.ts --check", + "build:cli": "npm run build:policy-boundary && tsc -p tsconfig.src.json && node dist/lib/core/generate-build-identity.js && node dist/lib/inference/serving/generate-catalog.js && node dist/lib/cli/generate-oclif-metadata-manifest.js && if find nemoclaw-blueprint/scripts -name '*.ts' -print -quit | grep -q .; then tsc -p nemoclaw-blueprint/tsconfig.json; fi", "clean:cli": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", - "typecheck:cli": "npm run catalog:compile && tsc -p tsconfig.cli.json", + "typecheck:cli": "tsc -p tsconfig.cli.json", "validate:configs": "tsx scripts/validate-configs.mts", "type-safety:hotspots": "tsx scripts/type-safety-hotspots.mts", "source-shape:scan": "tsx scripts/find-source-shape-tests.mts --metrics", diff --git a/scripts/managed-inference/compile-catalog.mts b/scripts/managed-inference/compile-catalog.mts deleted file mode 100644 index c8ce7051bae..00000000000 --- a/scripts/managed-inference/compile-catalog.mts +++ /dev/null @@ -1,434 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -import Ajv2020, { type AnySchema, type ValidateFunction } from "ajv/dist/2020.js"; -import { parseDocument } from "yaml"; - -import catalogSchema from "../../managed-inference/schemas/catalog.schema.json" with { - type: "json", -}; -import presetSchema from "../../managed-inference/schemas/preset.schema.json" with { type: "json" }; -import recipeSchema from "../../managed-inference/schemas/recipe.schema.json" with { type: "json" }; -import * as adapterRegistryModule from "../../src/lib/inference/serving/adapter-registry.ts"; -import * as catalogIntegrityModule from "../../src/lib/inference/serving/catalog-integrity.ts"; -import type { - CompiledManagedInferenceCatalog, - ManagedInferenceFactRequirement, - ManagedInferenceServingPreset, - ManagedInferenceServingRecipe, -} from "../../src/lib/inference/serving/catalog-types.ts"; -import * as catalogTypesModule from "../../src/lib/inference/serving/catalog-types.ts"; - -const compatibleAdapterRegistryModule = adapterRegistryModule as unknown as { - default?: typeof adapterRegistryModule; -}; -const { - getManagedInferenceRecipeRegistrationError, - getManagedInferenceTopologyQualificationDescriptor, -} = compatibleAdapterRegistryModule.default ?? adapterRegistryModule; -const compatibleCatalogIntegrityModule = catalogIntegrityModule as unknown as { - default?: typeof catalogIntegrityModule; -}; -const { canonicalManagedInferenceJson, managedInferenceDigest, managedInferenceTextDigest } = - compatibleCatalogIntegrityModule.default ?? catalogIntegrityModule; -const compatibleCatalogTypesModule = catalogTypesModule as unknown as { - default?: typeof catalogTypesModule; -}; -const { - isManagedInferenceMaterializerOwnedArgument, - MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, - MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, -} = compatibleCatalogTypesModule.default ?? catalogTypesModule; - -const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); -const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; -const GENERATED_CATALOG_DOCUMENT_PATH = "src/lib/inference/serving/generated/catalog.json"; -const LEGACY_GENERATED_CATALOG_PATHS = [ - "src/lib/inference/serving/generated/catalog.ts", - "dist/lib/inference/serving/generated/catalog.js", - "dist/lib/inference/serving/generated/catalog.js.map", - "dist/lib/inference/serving/generated/catalog.d.ts", - "dist/lib/inference/serving/generated/catalog.d.ts.map", -] as const; -const RECIPE_SCHEMA_ID = recipeSchema.$id; -const PRESET_SCHEMA_ID = presetSchema.$id; -const SHA256 = /^sha256:[0-9a-f]{64}$/u; - -export interface ManagedInferenceCatalogSource { - readonly path: string; - readonly contents: string; -} - -export interface CompiledManagedInferenceCatalogResult { - readonly catalog: CompiledManagedInferenceCatalog; - readonly document: string; -} - -export function renderManagedInferenceCatalogDocument( - catalog: CompiledManagedInferenceCatalog, -): string { - return `${JSON.stringify(catalog, null, 2)}\n`; -} - -function compareStrings(left: string, right: string): number { - return left < right ? -1 : left > right ? 1 : 0; -} - -function validationError(label: string, validate: ValidateFunction): Error { - const details = validate.errors - ?.map((error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`) - .join("; "); - return new Error(`${label} failed schema validation${details ? `: ${details}` : ""}`); -} - -function parseYamlSource(source: ManagedInferenceCatalogSource): unknown { - const document = parseDocument(source.contents, { - schema: "core", - strict: true, - uniqueKeys: true, - }); - if (document.errors.length > 0) { - throw new Error( - `${source.path} is invalid YAML: ${document.errors[0]?.message ?? "parse failed"}`, - ); - } - try { - return document.toJS({ maxAliasCount: 0 }); - } catch (error) { - throw new Error( - `${source.path} is invalid YAML: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -function createValidators(): { - validateCatalog: ValidateFunction; - validatePreset: ValidateFunction; - validateRecipe: ValidateFunction; -} { - const ajv = new Ajv2020({ allErrors: true, allowUnionTypes: true, strict: true }); - ajv.addSchema(recipeSchema as AnySchema); - ajv.addSchema(presetSchema as AnySchema); - const validateRecipe = ajv.getSchema(RECIPE_SCHEMA_ID); - const validatePreset = ajv.getSchema(PRESET_SCHEMA_ID); - if (!validateRecipe || !validatePreset) throw new Error("managed inference schemas did not load"); - return { - validateCatalog: ajv.compile(catalogSchema as AnySchema), - validatePreset, - validateRecipe, - }; -} - -function factRequirementError(requirement: ManagedInferenceFactRequirement): string | undefined { - if (requirement.fact !== "cluster.nodeCount") { - return "unsupported selection fact"; - } - const { operator, value } = requirement; - const arrayValue = Array.isArray(value) ? value : null; - if (operator === "oneOf") { - return arrayValue && arrayValue.length > 0 - ? undefined - : "oneOf requires a non-empty value array"; - } - if (operator === "between") { - return arrayValue?.length === 2 && arrayValue.every((item) => typeof item === "number") - ? undefined - : "between requires exactly two numeric values"; - } - if (arrayValue) return `${operator} requires one scalar value`; - if ((operator === "atLeast" || operator === "atMost") && typeof value !== "number") { - return `${operator} requires one numeric value`; - } - return undefined; -} - -function validateRecipeSemantics(recipe: ManagedInferenceServingRecipe): void { - if (!SHA256.test(recipe.spec.runtime.image.slice(recipe.spec.runtime.image.indexOf("@") + 1))) { - throw new Error(`${recipe.metadata.id} must pin its runtime image by sha256 digest`); - } - if (!Object.hasOwn(recipe.spec.bindings, recipe.spec.execution.topologyBinding)) { - throw new Error( - `${recipe.metadata.id} references unknown topology binding ${recipe.spec.execution.topologyBinding}`, - ); - } - const seenArguments = new Set(); - for (const argument of recipe.spec.serve.arguments) { - if (seenArguments.has(argument.name)) { - throw new Error(`${recipe.metadata.id} contains duplicate serving argument ${argument.name}`); - } - if (isManagedInferenceMaterializerOwnedArgument(argument.name)) { - throw new Error(`${recipe.metadata.id} assigns materializer-owned argument ${argument.name}`); - } - seenArguments.add(argument.name); - } - const temporaryTargets = recipe.spec.runtime.temporaryFilesystems.map(({ target }) => target); - if (new Set(temporaryTargets).size !== temporaryTargets.length) { - throw new Error(`${recipe.metadata.id} contains duplicate temporary filesystem targets`); - } - for (const filesystem of recipe.spec.runtime.temporaryFilesystems) { - const options = new Set(filesystem.options); - if ( - (options.has("rw") && options.has("ro")) || - (options.has("exec") && options.has("noexec")) - ) { - throw new Error(`${recipe.metadata.id} contains conflicting temporary filesystem options`); - } - } - const registrationError = getManagedInferenceRecipeRegistrationError(recipe); - if (registrationError) { - throw new Error( - `${recipe.metadata.id} is incompatible with its registered adapters: ${registrationError}`, - ); - } -} - -function sortedKeys(value: object): string[] { - return Object.keys(value).sort(compareStrings); -} - -function validatePresetSemantics( - preset: ManagedInferenceServingPreset, - recipes: ReadonlyMap, -): void { - const recipe = recipes.get(preset.spec.plan.recipeRef); - if (!recipe) { - throw new Error( - `${preset.metadata.id} references unknown recipe ${preset.spec.plan.recipeRef}`, - ); - } - if (recipe.spec.backend !== preset.spec.plan.backend) { - throw new Error(`${preset.metadata.id} backend does not match its recipe`); - } - - const recipeBindingNames = sortedKeys(recipe.spec.bindings); - const presetBindingNames = sortedKeys(preset.spec.plan.bindings); - if ( - recipeBindingNames.length !== presetBindingNames.length || - recipeBindingNames.some((name, index) => name !== presetBindingNames[index]) - ) { - throw new Error(`${preset.metadata.id} bindings do not exactly satisfy its recipe`); - } - const topologyRequirements = preset.spec.requirements.all - .filter((requirement) => "topologyQualification" in requirement) - .map(({ topologyQualification }) => topologyQualification); - if (topologyRequirements.length !== recipeBindingNames.length) { - throw new Error( - `${preset.metadata.id} topology requirements do not exactly satisfy its recipe bindings`, - ); - } - for (const name of recipeBindingNames) { - const recipeBinding = recipe.spec.bindings[name]!; - const presetBinding = preset.spec.plan.bindings[name]!.valueFromTopologyQualification; - const descriptor = getManagedInferenceTopologyQualificationDescriptor( - recipeBinding.qualificationId, - recipeBinding.schemaVersion, - ); - if ( - !descriptor || - presetBinding.id !== recipeBinding.qualificationId || - presetBinding.schemaVersion !== recipeBinding.schemaVersion || - presetBinding.output !== descriptor.bindingOutput - ) { - throw new Error(`${preset.metadata.id} binding ${name} does not match its recipe`); - } - const matchingRequirements = topologyRequirements.filter( - ({ id, schemaVersion, status }) => - id === presetBinding.id && - schemaVersion === presetBinding.schemaVersion && - status === "qualified", - ); - if (matchingRequirements.length !== 1) { - throw new Error( - `${preset.metadata.id} binding ${name} requires one matching qualified topology requirement`, - ); - } - } - for (const requirement of preset.spec.requirements.all) { - if (!("fact" in requirement)) continue; - const error = factRequirementError(requirement); - if (error) throw new Error(`${preset.metadata.id} fact ${requirement.fact}: ${error}`); - if ( - requirement.fact === "cluster.nodeCount" && - requirement.state === "present" && - requirement.operator === "equals" && - requirement.value !== recipe.spec.execution.nodeCount - ) { - throw new Error(`${preset.metadata.id} node-count requirement does not match its recipe`); - } - } -} - -function assertUniqueDefinitionIds( - presets: readonly { readonly definition: ManagedInferenceServingPreset }[], - recipes: readonly { readonly definition: ManagedInferenceServingRecipe }[], -): void { - const seen = new Map(); - for (const [kind, definitions] of [ - ["preset", presets], - ["recipe", recipes], - ] as const) { - for (const { definition } of definitions) { - const existing = seen.get(definition.metadata.id); - if (existing) { - throw new Error( - `managed inference definition ID ${definition.metadata.id} is duplicated by ${existing} and ${kind}`, - ); - } - seen.set(definition.metadata.id, kind); - } - } -} - -function sortedJson(value: unknown): unknown { - return JSON.parse(canonicalManagedInferenceJson(value)); -} - -export function compileManagedInferenceCatalogSources( - sources: readonly ManagedInferenceCatalogSource[], -): CompiledManagedInferenceCatalogResult { - const sortedSources = [...sources].sort((left, right) => compareStrings(left.path, right.path)); - if (new Set(sortedSources.map((source) => source.path)).size !== sortedSources.length) { - throw new Error("managed inference catalog contains a duplicate source path"); - } - const { validateCatalog, validatePreset, validateRecipe } = createValidators(); - const recipes: { - definition: ManagedInferenceServingRecipe; - definitionDigest: string; - sourceFile: string; - }[] = []; - const presets: { - definition: ManagedInferenceServingPreset; - definitionDigest: string; - sourceFile: string; - }[] = []; - - for (const source of sortedSources) { - if (!/^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u.test(source.path)) { - throw new Error(`unsupported managed inference source path ${source.path}`); - } - const parsed = parseYamlSource(source); - const kind = - typeof parsed === "object" && parsed !== null - ? (parsed as { readonly kind?: unknown }).kind - : undefined; - if (kind === "ServingRecipe") { - if (!source.path.startsWith("managed-inference/recipes/") || !validateRecipe(parsed)) { - throw validationError(source.path, validateRecipe); - } - recipes.push({ - definition: parsed as ManagedInferenceServingRecipe, - definitionDigest: managedInferenceDigest(parsed), - sourceFile: source.path, - }); - } else if (kind === "ServingPreset") { - if (!source.path.startsWith("managed-inference/presets/") || !validatePreset(parsed)) { - throw validationError(source.path, validatePreset); - } - presets.push({ - definition: parsed as ManagedInferenceServingPreset, - definitionDigest: managedInferenceDigest(parsed), - sourceFile: source.path, - }); - } else { - throw new Error(`${source.path} has unsupported kind ${String(kind)}`); - } - } - - if (recipes.length === 0 || presets.length === 0) { - throw new Error("managed inference catalog requires at least one recipe and one preset"); - } - assertUniqueDefinitionIds(presets, recipes); - for (const { definition } of recipes) validateRecipeSemantics(definition); - const recipesById = new Map( - recipes.map(({ definition }) => [definition.metadata.id, definition]), - ); - for (const { definition } of presets) validatePresetSemantics(definition, recipesById); - recipes.sort((left, right) => - compareStrings(left.definition.metadata.id, right.definition.metadata.id), - ); - presets.sort((left, right) => - compareStrings(left.definition.metadata.id, right.definition.metadata.id), - ); - - const sourceFiles = sortedSources.map((source) => ({ - digest: managedInferenceTextDigest(source.contents), - path: source.path, - })); - const withoutDigest = { - compilerVersion: MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, - presets, - recipes, - schemaVersion: MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, - sourceFiles, - sourceRevision: managedInferenceDigest(sourceFiles), - } as const; - const catalog = sortedJson({ - ...withoutDigest, - catalogDigest: managedInferenceDigest(withoutDigest), - }) as CompiledManagedInferenceCatalog; - if (!validateCatalog(catalog)) { - throw validationError("compiled managed inference catalog", validateCatalog); - } - return { - catalog, - document: renderManagedInferenceCatalogDocument(catalog), - }; -} - -function readCatalogSources(repositoryRoot: string): ManagedInferenceCatalogSource[] { - return SOURCE_DIRECTORIES.flatMap((directory) => { - const absoluteDirectory = path.join(repositoryRoot, directory); - return fs - .readdirSync(absoluteDirectory, { withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".yaml")) - .map((entry) => { - const sourcePath = `${directory}/${entry.name}`; - return { - path: sourcePath, - contents: fs.readFileSync(path.join(repositoryRoot, sourcePath), "utf8"), - }; - }); - }); -} - -export function compileManagedInferenceCatalog( - repositoryRoot = REPOSITORY_ROOT, -): CompiledManagedInferenceCatalogResult { - return compileManagedInferenceCatalogSources(readCatalogSources(repositoryRoot)); -} - -export function writeManagedInferenceCatalog( - repositoryRoot = REPOSITORY_ROOT, -): CompiledManagedInferenceCatalogResult { - const compiled = compileManagedInferenceCatalog(repositoryRoot); - const outputPath = path.join(repositoryRoot, GENERATED_CATALOG_DOCUMENT_PATH); - fs.mkdirSync(path.dirname(outputPath), { recursive: true }); - fs.writeFileSync(outputPath, compiled.document, "utf8"); - for (const legacyPath of LEGACY_GENERATED_CATALOG_PATHS) { - fs.rmSync(path.join(repositoryRoot, legacyPath), { force: true }); - } - return compiled; -} - -function main(): void { - const unknownArguments = process.argv.slice(2).filter((argument) => argument !== "--write"); - if (unknownArguments.length > 0) throw new Error(`unknown argument ${unknownArguments[0]}`); - if (process.argv.includes("--write")) { - writeManagedInferenceCatalog(); - } else { - compileManagedInferenceCatalog(); - } -} - -if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) { - try { - main(); - } catch (error) { - console.error(error instanceof Error ? error.message : String(error)); - process.exitCode = 1; - } -} diff --git a/src/lib/inference/serving/adapter-registry.test.ts b/src/lib/inference/serving/adapter-registry.test.ts index 8a14666a361..3af8b1b9dce 100644 --- a/src/lib/inference/serving/adapter-registry.test.ts +++ b/src/lib/inference/serving/adapter-registry.test.ts @@ -18,8 +18,8 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; -import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; +import type { ManagedInferenceServingRecipe } from "./types.js"; import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { MANAGED_CLUSTER_TOPOLOGY_ID, @@ -28,9 +28,8 @@ import { function shippedRecipe(): ManagedInferenceServingRecipe { const recipe = loadManagedInferenceCatalog().recipes.find( - ({ definition }) => - definition.spec.execution.materializerRef === MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, - )?.definition; + ({ spec }) => spec.execution.materializerRef === MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, + ); expect(recipe).toBeDefined(); return structuredClone(recipe as ManagedInferenceServingRecipe); } diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index 04ba4f286a1..cd1981c6358 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -2,9 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import type { + ReadinessEntityKind, + ServingCatalogRegistries, + ServingRecipe, ManagedInferenceServingRecipe, ManagedInferenceTopologyQualification, -} from "./catalog-types.js"; +} from "./types.js"; import { getManagedClusterTopologyArtifactError, MANAGED_CLUSTER_TOPOLOGY_ID, @@ -486,3 +489,38 @@ export function getManagedInferenceRecipeRegistrationError( preparation.validateRecipe(recipe) ); } + +const SERVING_READINESS_REGISTRY: ServingCatalogRegistries["readiness"] = new Map< + string, + ReadinessEntityKind | ReadonlySet +>([ + ["host.platform.dgx_spark", new Set(["qualification", "capability"] as const)], + ["host.platform.supported", "capability"], + ["host.docker.available", "capability"], + ["host.docker.daemon_reachable", "capability"], + ["host.docker.runtime_supported", "capability"], + ["host.docker.storage_compatible", "capability"], + ["host.gpu.nvidia_available", "capability"], + ["host.gpu.container_toolkit_available", "capability"], + ["host.gpu.cdi_healthy", "capability"], +] as const); + +export function getManagedInferenceServingCatalogRegistries(): ServingCatalogRegistries { + return { + materializers: new Set(MATERIALIZER_DESCRIPTORS.map(({ ref }) => ref)), + lifecycles: new Set(LIFECYCLE_DESCRIPTORS.map(({ ref }) => ref)), + readiness: SERVING_READINESS_REGISTRY, + facts: new Set(["cluster.nodeCount"]), + topologyQualifications: new Map( + TOPOLOGY_DESCRIPTORS.map((descriptor) => [ + `${descriptor.id}@${String(descriptor.schemaVersion)}`, + { + bindingOutput: descriptor.bindingOutput, + outputSchema: descriptor.outputSchema, + }, + ]), + ), + validateRecipe: (recipe: ServingRecipe) => + getManagedInferenceRecipeRegistrationError(recipe as ManagedInferenceServingRecipe), + }; +} diff --git a/src/lib/inference/serving/catalog-loader.ts b/src/lib/inference/serving/catalog-loader.ts new file mode 100644 index 00000000000..9a736acd478 --- /dev/null +++ b/src/lib/inference/serving/catalog-loader.ts @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; +import { parseCompiledServingCatalogJson } from "./catalog.js"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ServingCatalogSchemas, +} from "./types.js"; + +function readJson(path: string): object { + return JSON.parse(readFileSync(path, "utf8")) as object; +} + +function repositoryRoot(): string { + return join(__dirname, "..", "..", "..", ".."); +} + +function loadSchemas(rootDir: string): ServingCatalogSchemas { + const schemaRoot = join(rootDir, "managed-inference", "schemas"); + return { + catalog: readJson(join(schemaRoot, "catalog.schema.json")), + preset: readJson(join(schemaRoot, "preset.schema.json")), + recipe: readJson(join(schemaRoot, "recipe.schema.json")), + }; +} + +let loadedCatalog: CompiledManagedInferenceCatalog | undefined; + +export function loadManagedInferenceCatalog(): CompiledManagedInferenceCatalog { + if (loadedCatalog) return loadedCatalog; + const rootDir = repositoryRoot(); + const source = readFileSync(join(rootDir, "dist", "managed-inference", "catalog.json"), "utf8"); + loadedCatalog = immutableManagedInferenceCopy( + parseCompiledServingCatalogJson(source, loadSchemas(rootDir)), + ) as CompiledManagedInferenceCatalog; + return loadedCatalog; +} + +export function getManagedInferenceCompiledPreset( + id: string, +): ManagedInferenceServingPreset | undefined { + return loadManagedInferenceCatalog().presets.find(({ metadata }) => metadata.id === id); +} + +export function getManagedInferenceCompiledRecipe( + id: string, +): ManagedInferenceServingRecipe | undefined { + return loadManagedInferenceCatalog().recipes.find(({ metadata }) => metadata.id === id); +} diff --git a/src/lib/inference/serving/catalog.test.ts b/src/lib/inference/serving/catalog.test.ts index 86b9460611e..9f90b7c6181 100644 --- a/src/lib/inference/serving/catalog.test.ts +++ b/src/lib/inference/serving/catalog.test.ts @@ -2,52 +2,337 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; - +import catalogSchema from "../../../../managed-inference/schemas/catalog.schema.json" with { + type: "json", +}; +import presetSchema from "../../../../managed-inference/schemas/preset.schema.json" with { + type: "json", +}; +import recipeSchema from "../../../../managed-inference/schemas/recipe.schema.json" with { + type: "json", +}; import { - getManagedInferenceCompiledPreset, - getManagedInferenceCompiledRecipe, - loadManagedInferenceCatalog, -} from "./catalog.js"; - -describe("managed inference catalog", () => { - it("loads every compiled YAML definition with unique IDs and resolvable references", () => { - const catalog = loadManagedInferenceCatalog(); - expect(catalog.catalogDigest).toMatch(/^sha256:[0-9a-f]{64}$/u); - expect(catalog.presets.length).toBeGreaterThan(0); - expect(catalog.recipes.length).toBeGreaterThan(0); - - const ids = [ - ...catalog.presets.map(({ definition }) => definition.metadata.id), - ...catalog.recipes.map(({ definition }) => definition.metadata.id), - ]; - expect(new Set(ids).size).toBe(ids.length); - for (const compiledPreset of catalog.presets) { - expect(getManagedInferenceCompiledPreset(compiledPreset.definition.metadata.id)).toBe( - compiledPreset, - ); - const compiledRecipe = getManagedInferenceCompiledRecipe( - compiledPreset.definition.spec.plan.recipeRef, - ); - expect(compiledRecipe?.definition.spec.backend).toBe( - compiledPreset.definition.spec.plan.backend, - ); + compileTrustedServingCatalog, + parseCompiledServingCatalogJson, + serializeCompiledServingCatalog, +} from "./catalog"; +import type { + ServingCatalogRegistries, + ServingCatalogSchemas, + ServingCatalogSource, +} from "./types"; + +const SOURCE_REVISION = "a".repeat(40); +const IMAGE_DIGEST = "b".repeat(64); +const MODEL_REVISION = "c".repeat(40); +const SCHEMAS: ServingCatalogSchemas = { + catalog: catalogSchema, + preset: presetSchema, + recipe: recipeSchema, +}; +const REGISTRIES: ServingCatalogRegistries = { + materializers: new Set(["test.materializer/v1"]), + lifecycles: new Set(["test.lifecycle/v1"]), + readiness: new Map([ + ["test.runtime.present", "capability"], + ["test.runtime.other", "capability"], + ]), +}; + +function recipeSource( + id = "test.recipe.v1", + overrides: { image?: string; execution?: string } = {}, +): ServingCatalogSource { + return { + path: `managed-inference/recipes/test/${id}.yaml`, + contents: ` +apiVersion: nemoclaw.nvidia.com/managed-inference/v1 +kind: ServingRecipe +metadata: + id: ${id} +spec: + backend: test + model: + id: test/model + revision: ${MODEL_REVISION} + servedName: test-model + files: + - path: model.gguf + digest: sha256:${"d".repeat(64)} + runtime: + image: ${overrides.image ?? `registry.example/test/server@sha256:${IMAGE_DIGEST}`} + architecture: amd64 + execution: +${overrides.execution ?? " materializerRef: test.materializer/v1\n lifecycleRef: test.lifecycle/v1"} + serve: + arguments: + - name: --port + value: 8081 + readiness: + timeoutSeconds: 30 + expectedModel: test-model +`, + }; +} + +function presetSource( + id = "test.preset.auto", + options: { priority?: number; recipeRef?: string; readinessId?: string } = {}, +): ServingCatalogSource { + return { + path: `managed-inference/presets/test/${id}.yaml`, + contents: ` +apiVersion: nemoclaw.nvidia.com/managed-inference/v1 +kind: ServingPreset +metadata: + id: ${id} +spec: + selection: automatic + priority: ${options.priority ?? 100} + requirements: + all: + - readiness: + scope: everyNode + kind: capability + id: ${options.readinessId ?? "test.runtime.present"} + state: present + plan: + backend: test + recipeRef: ${options.recipeRef ?? "test.recipe.v1"} +`, + }; +} + +function compile(sources: readonly ServingCatalogSource[], registries = REGISTRIES) { + return compileTrustedServingCatalog({ + sources, + sourceRevision: SOURCE_REVISION, + schemas: SCHEMAS, + registries, + }); +} + +function requireValidationFailure(run: () => void, expectedMessage: string): void { + expect(run).toThrow(expectedMessage); +} + +function recipeWithModelRevision(revision: string): ServingCatalogSource { + const source = recipeSource(); + return { + ...source, + contents: source.contents.replace(`revision: ${MODEL_REVISION}`, `revision: ${revision}`), + }; +} + +describe("managed inference serving catalog compiler", () => { + it("compiles managed-inference YAML to deterministic canonical JSON (#8144)", () => { + const recipe = recipeSource(); + const preset = presetSource(); + + const first = compile([recipe, preset]); + const second = compile([preset, recipe]); + + expect(serializeCompiledServingCatalog(first)).toBe(serializeCompiledServingCatalog(second)); + expect(first.readinessSchemaRef).toBe( + "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json", + ); + expect(first.recipes.map((definition) => definition.metadata.id)).toEqual(["test.recipe.v1"]); + expect(first.presets.map((definition) => definition.metadata.id)).toEqual(["test.preset.auto"]); + expect(first.sources.map((source) => source.path)).toEqual([ + "managed-inference/presets/test/test.preset.auto.yaml", + "managed-inference/recipes/test/test.recipe.v1.yaml", + ]); + }); + + it("rejects duplicate definition IDs and dangling recipe references (#8144)", () => { + const duplicate = { + ...recipeSource(), + path: "managed-inference/recipes/test/duplicate.yaml", + }; + expect(() => compile([recipeSource(), duplicate])).toThrow("ID test.recipe.v1 is duplicated"); + expect(() => + compile([ + recipeSource(), + presetSource("test.preset.missing", { + recipeRef: "test.recipe.missing", + }), + ]), + ).toThrow("references unknown recipe test.recipe.missing"); + }); + + it("rejects executable fields and mutable artifact references (#8144)", () => { + expect(() => + compile([ + recipeSource("test.recipe.shell", { + execution: + " materializerRef: test.materializer/v1\n lifecycleRef: test.lifecycle/v1\n command: sh -c server", + }), + ]), + ).toThrow("does not satisfy the ServingRecipe schema"); + expect(() => + compile([ + recipeSource("test.recipe.mutable", { + image: "registry.example/test/server:latest", + }), + ]), + ).toThrow("does not satisfy the ServingRecipe schema"); + }); + + it("accepts only exact immutable model revision forms (#8144)", () => { + for (const revision of ["e".repeat(40), "e".repeat(64), `sha256:${"e".repeat(64)}`]) { + expect(() => compile([recipeWithModelRevision(revision)])).not.toThrow(); } - for (const compiledRecipe of catalog.recipes) { - expect(getManagedInferenceCompiledRecipe(compiledRecipe.definition.metadata.id)).toBe( - compiledRecipe, + for (const revision of ["e".repeat(41), "e".repeat(63)]) { + expect(() => compile([recipeWithModelRevision(revision)])).toThrow( + "does not satisfy the ServingRecipe schema", ); - expect(compiledRecipe.definitionDigest).toMatch(/^sha256:[0-9a-f]{64}$/u); } }); - it("returns one deeply frozen catalog instance", () => { - const first = loadManagedInferenceCatalog(); - const second = loadManagedInferenceCatalog(); + it("rejects duplicate source paths and YAML aliases (#8144)", () => { + const duplicatePath = { ...presetSource(), path: recipeSource().path }; + expect(() => compile([recipeSource(), duplicatePath])).toThrow( + `Catalog source path ${recipeSource().path} is duplicated`, + ); + + const recipe = recipeSource("test.recipe.alias"); + const aliasedRecipe = { + ...recipe, + contents: recipe.contents + .replace("id: test/model", "id: &model-id test/model") + .replace("servedName: test-model", "servedName: *model-id"), + }; + expect(() => compile([aliasedRecipe])).toThrow("cannot use YAML aliases"); + }); + + it("rejects duplicate structured arguments and model files (#8144)", () => { + const argumentRecipe = recipeSource("test.recipe.duplicate-argument"); + const duplicateArgument = { + ...argumentRecipe, + contents: argumentRecipe.contents.replace( + " - name: --port\n value: 8081", + " - name: --port\n value: 8081\n - name: --port\n value: 8082", + ), + }; + expect(() => compile([duplicateArgument])).toThrow("repeats structured argument --port"); + + const modelRecipe = recipeSource("test.recipe.duplicate-model-file"); + const duplicateModelFile = { + ...modelRecipe, + contents: modelRecipe.contents.replace( + ` - path: model.gguf\n digest: sha256:${"d".repeat(64)}`, + ` - path: model.gguf\n digest: sha256:${"d".repeat(64)}\n - path: model.gguf\n digest: sha256:${"e".repeat(64)}`, + ), + }; + expect(() => compile([duplicateModelFile])).toThrow("repeats model file model.gguf"); - expect(second).toBe(first); - expect(Object.isFrozen(first)).toBe(true); - for (const { definition } of first.recipes) { - expect(Object.isFrozen(definition.spec.runtime.environment)).toBe(true); + for (const path of [ + "./model.gguf", + "models//model.gguf", + "models/./model.gguf", + "models/", + "models\\model.gguf", + "C:\\model.gguf", + ]) { + const pathRecipe = recipeSource("test.recipe.noncanonical-model-file"); + const noncanonicalModelFile = { + ...pathRecipe, + contents: pathRecipe.contents.replace("path: model.gguf", `path: ${path}`), + }; + expect(() => compile([noncanonicalModelFile])).toThrow( + "does not satisfy the ServingRecipe schema", + ); } }); + + it("rejects adapter and readiness IDs outside the injected registries (#8144)", () => { + expect(() => + compile([recipeSource()], { + ...REGISTRIES, + materializers: new Set(), + }), + ).toThrow("references unknown materializer test.materializer/v1"); + expect(() => + compile([ + recipeSource(), + presetSource("test.preset.unknown", { + readinessId: "test.readiness.unknown", + }), + ]), + ).toThrow("references unknown readiness entity test.readiness.unknown"); + + const mismatchedKind = presetSource("test.preset.kind-mismatch"); + expect(() => + compile([ + recipeSource(), + { + ...mismatchedKind, + contents: mismatchedKind.contents.replace("kind: capability", "kind: observation"), + }, + ]), + ).toThrow( + "uses test.runtime.present as observation, but the readiness registry declares capability", + ); + + const duplicateRequirement = presetSource("test.preset.duplicate-requirement"); + const readinessRequirement = ` - readiness: + scope: everyNode + kind: capability + id: test.runtime.present + state: present`; + expect(() => + compile([ + recipeSource(), + { + ...duplicateRequirement, + contents: duplicateRequirement.contents.replace( + readinessRequirement, + `${readinessRequirement}\n${readinessRequirement}`, + ), + }, + ]), + ).toThrow("repeats readiness requirement"); + }); + + it("rejects duplicate automatic selectors at one priority (#8144)", () => { + expect(() => + compile([ + recipeSource(), + presetSource(), + presetSource("test.preset.other", { priority: 100 }), + ]), + ).toThrow("have the same selector at priority 100 for backend test"); + }); + + it("accepts disjoint automatic selectors at one priority (#8144)", () => { + const catalog = compile([ + recipeSource(), + presetSource(), + presetSource("test.preset.other", { + priority: 100, + readinessId: "test.runtime.other", + }), + ]); + + expect(catalog.presets.map((preset) => preset.metadata.id)).toEqual([ + "test.preset.auto", + "test.preset.other", + ]); + }); + + it("accepts only compiled JSON whose digest matches its content (#8144)", () => { + const serialized = serializeCompiledServingCatalog(compile([recipeSource(), presetSource()])); + const parsed = parseCompiledServingCatalogJson(serialized, SCHEMAS); + const tampered = serialized.replace("test/model", "test/other-model"); + requireValidationFailure( + () => parseCompiledServingCatalogJson(tampered, SCHEMAS), + "digest mismatch", + ); + requireValidationFailure( + () => parseCompiledServingCatalogJson("apiVersion: v1", SCHEMAS), + "is not valid JSON", + ); + + expect(parsed.catalogDigest).toMatch(/^sha256:[0-9a-f]{64}$/); + }); }); diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts index 583a4ef110e..50dbe8b95cd 100644 --- a/src/lib/inference/serving/catalog.ts +++ b/src/lib/inference/serving/catalog.ts @@ -1,205 +1,461 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { - getManagedInferenceRecipeRegistrationError, - getManagedInferenceTopologyQualificationDescriptor, -} from "./adapter-registry.js"; -import { immutableManagedInferenceCopy, managedInferenceDigest } from "./catalog-integrity.js"; -import { - type CompiledManagedInferenceCatalog, - MANAGED_INFERENCE_CATALOG_COMPILER_VERSION, - MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION, - type ManagedInferenceServingPreset, - type ManagedInferenceServingRecipe, -} from "./catalog-types.js"; -import generatedCatalog from "./generated/catalog.json"; - -const SHA256 = /^sha256:[0-9a-f]{64}$/u; -const SOURCE_PATH = /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u; +import { createHash } from "node:crypto"; +import { posix } from "node:path"; + +import Ajv2020, { type AnySchema, type ValidateFunction } from "ajv/dist/2020.js"; +import { parseDocument } from "yaml"; + +import type { + CompiledServingCatalog, + CompiledServingCatalogPayload, + ServingCatalogRegistries, + ServingCatalogSchemas, + ServingCatalogSource, + ServingCatalogSourceProvenance, + ServingDefinitionKind, + ServingPreset, + ServingRecipe, +} from "./types"; + +const API_VERSION = "nemoclaw.nvidia.com/managed-inference/v1" as const; +const CATALOG_SCHEMA_VERSION = "1.0.0" as const; +const COMPILER_VERSION = "1.0.0" as const; +const READINESS_SCHEMA_REF = + "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json" as const; +const RECIPE_SCHEMA_ID = + "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/recipe.schema.json"; +const PRESET_SCHEMA_ID = + "https://github.com/NVIDIA/NemoClaw/managed-inference/schemas/preset.schema.json"; +const CATALOG_SOURCE_PATTERN = /^managed-inference\/(recipes|presets)\/.+\.ya?ml$/; + +interface CatalogValidators { + catalog: ValidateFunction; + preset: ValidateFunction; + recipe: ValidateFunction; +} + +interface CompileServingCatalogOptions { + sources: readonly ServingCatalogSource[]; + sourceRevision: string; + schemas: ServingCatalogSchemas; + registries: ServingCatalogRegistries; +} + +export class ServingCatalogValidationError extends Error { + constructor(message: string) { + super(message); + this.name = "ServingCatalogValidationError"; + } +} + +function compareCanonicalText(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} + +function normalizeForCanonicalJson(value: unknown): unknown { + if (Array.isArray(value)) return value.map(normalizeForCanonicalJson); + if (value !== null && typeof value === "object") { + return Object.fromEntries( + Object.entries(value) + .sort(([left], [right]) => compareCanonicalText(left, right)) + .map(([key, nested]) => [key, normalizeForCanonicalJson(nested)]), + ); + } + return value; +} + +export function canonicalServingCatalogJson(value: unknown): string { + return JSON.stringify(normalizeForCanonicalJson(value)); +} + +export function servingCatalogDigest(value: unknown): string { + return `sha256:${createHash("sha256").update(canonicalServingCatalogJson(value)).digest("hex")}`; +} + +function createValidators(schemas: ServingCatalogSchemas): CatalogValidators { + const ajv = new Ajv2020({ allErrors: true, strict: true }); + ajv.addSchema(schemas.recipe as AnySchema); + ajv.addSchema(schemas.preset as AnySchema); + const recipe = ajv.getSchema(RECIPE_SCHEMA_ID); + const preset = ajv.getSchema(PRESET_SCHEMA_ID); + if (!recipe || !preset) { + throw new ServingCatalogValidationError("Serving catalog schemas have invalid identifiers."); + } + return { recipe, preset, catalog: ajv.compile(schemas.catalog as AnySchema) }; +} + +function validationDetails(validate: ValidateFunction): string { + return (validate.errors ?? []) + .map((error) => `${error.instancePath || "/"} ${error.message ?? "is invalid"}`) + .join("; "); +} function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function parseTrustedYaml(source: ServingCatalogSource): Record { + let document; + try { + document = parseDocument(source.contents, { strict: true, uniqueKeys: true }); + } catch (error) { + throw new ServingCatalogValidationError( + `${source.path} is not valid YAML: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (document.errors.length > 0) { + throw new ServingCatalogValidationError( + `${source.path} is not valid YAML: ${document.errors.map((error) => error.message).join("; ")}`, + ); + } + let value: unknown; + try { + value = document.toJS({ maxAliasCount: 0 }); + } catch (error) { + throw new ServingCatalogValidationError( + `${source.path} cannot use YAML aliases: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if (!isRecord(value)) { + throw new ServingCatalogValidationError(`${source.path} must contain one YAML mapping.`); + } + return value; } -function definitionId(value: unknown): string | undefined { - if (!isRecord(value)) return undefined; +function definitionIdentity( + source: ServingCatalogSource, + value: Record, +): { kind: ServingDefinitionKind; id: string } { + const kind = value.kind; const metadata = value.metadata; - if (!isRecord(metadata)) return undefined; - return typeof metadata.id === "string" && metadata.id.length > 0 ? metadata.id : undefined; -} - -function assertCompiledDefinitions( - definitions: - | CompiledManagedInferenceCatalog["presets"] - | CompiledManagedInferenceCatalog["recipes"], - kind: "ServingPreset" | "ServingRecipe", - sourceDirectory: "presets" | "recipes", - sourcePaths: ReadonlySet, - seenIds: Set, - seenSources: Set, -): void { - for (const compiled of definitions) { - const id = definitionId(compiled.definition); - if ( - !id || - !isRecord(compiled.definition) || - compiled.definition.kind !== kind || - seenIds.has(id) || - !SHA256.test(compiled.definitionDigest) || - compiled.definitionDigest !== managedInferenceDigest(compiled.definition) || - typeof compiled.sourceFile !== "string" || - !compiled.sourceFile.startsWith(`managed-inference/${sourceDirectory}/`) || - !sourcePaths.has(compiled.sourceFile) || - seenSources.has(compiled.sourceFile) - ) { - throw new Error(`managed inference ${kind} definition is invalid`); - } - seenIds.add(id); - seenSources.add(compiled.sourceFile); + const id = isRecord(metadata) ? metadata.id : undefined; + if ((kind !== "ServingRecipe" && kind !== "ServingPreset") || typeof id !== "string") { + throw new ServingCatalogValidationError( + `${source.path} must declare a ServingRecipe or ServingPreset with metadata.id.`, + ); } + return { kind, id }; } -function assertReferences( - presets: readonly { readonly definition: ManagedInferenceServingPreset }[], - recipes: readonly { readonly definition: ManagedInferenceServingRecipe }[], +function validateRecipeSemantics( + recipe: ServingRecipe, + registries: ServingCatalogRegistries, ): void { - const recipesById = new Map( - recipes.map(({ definition }) => [definition.metadata.id, definition]), - ); - for (const { definition: recipe } of recipes) { - const registrationError = getManagedInferenceRecipeRegistrationError(recipe); - if (registrationError) { - throw new Error( - `managed inference recipe ${recipe.metadata.id} is incompatible with its registered adapters: ${registrationError}`, + const { materializerRef, lifecycleRef } = recipe.spec.execution; + if (!registries.materializers.has(materializerRef)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} references unknown materializer ${materializerRef}.`, + ); + } + if (!registries.lifecycles.has(lifecycleRef)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} references unknown lifecycle adapter ${lifecycleRef}.`, + ); + } + + const argumentNames = new Set(); + for (const argument of recipe.spec.serve?.arguments ?? []) { + if (argumentNames.has(argument.name)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} repeats structured argument ${argument.name}.`, ); } + argumentNames.add(argument.name); } - for (const { definition: preset } of presets) { - const recipe = recipesById.get(preset.spec.plan.recipeRef); - if (!recipe || recipe.spec.backend !== preset.spec.plan.backend) { - throw new Error( - `managed inference preset ${preset.metadata.id} has an invalid recipe reference`, + + const modelFiles = new Set(); + for (const file of recipe.spec.model.files ?? []) { + const normalizedPath = posix.normalize(file.path); + if (normalizedPath !== file.path) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} uses noncanonical model file path ${file.path}.`, ); } - const recipeBindings = Object.keys(recipe.spec.bindings).sort(); - const presetBindings = Object.keys(preset.spec.plan.bindings).sort(); - if ( - recipeBindings.length !== presetBindings.length || - recipeBindings.some((name, index) => name !== presetBindings[index]) - ) { - throw new Error(`managed inference preset ${preset.metadata.id} has invalid bindings`); - } - for (const name of recipeBindings) { - const expected = recipe.spec.bindings[name]!; - const actual = preset.spec.plan.bindings[name]!.valueFromTopologyQualification; - const descriptor = getManagedInferenceTopologyQualificationDescriptor( - expected.qualificationId, - expected.schemaVersion, + if (modelFiles.has(normalizedPath)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} repeats model file ${normalizedPath}.`, ); - if ( - !descriptor || - actual.id !== expected.qualificationId || - actual.schemaVersion !== expected.schemaVersion || - actual.output !== descriptor.bindingOutput - ) { - throw new Error( - `managed inference preset ${preset.metadata.id} has invalid binding ${name}`, + } + modelFiles.add(normalizedPath); + } + + let registrationError: string | undefined; + try { + registrationError = registries.validateRecipe?.(recipe); + } catch { + registrationError = "does not satisfy its registered adapter contract"; + } + if (registrationError) { + throw new ServingCatalogValidationError(`Recipe ${recipe.metadata.id}: ${registrationError}.`); + } +} + +function validatePresetRequirements( + preset: ServingPreset, + registries: ServingCatalogRegistries, +): void { + const requirements = new Set(); + for (const requirement of preset.spec.requirements?.all ?? []) { + const requirementKey = canonicalServingCatalogJson(requirement); + if (requirements.has(requirementKey)) { + const requirementLabel = "readiness" in requirement ? "readiness requirement" : "requirement"; + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} repeats ${requirementLabel} ${requirementKey}.`, + ); + } + requirements.add(requirementKey); + + if ("readiness" in requirement) { + const registeredKind = registries.readiness.get(requirement.readiness.id); + if (registeredKind === undefined) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} references unknown readiness entity ${requirement.readiness.id}.`, + ); + } + const kindMatches = + registeredKind === requirement.readiness.kind || + (typeof registeredKind !== "string" && registeredKind.has(requirement.readiness.kind)); + if (!kindMatches) { + const registeredKinds = + typeof registeredKind === "string" ? registeredKind : [...registeredKind].join(" or "); + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} uses ${requirement.readiness.id} as ${requirement.readiness.kind}, but the readiness registry declares ${registeredKinds}.`, ); } + continue; + } + if ("fact" in requirement) { + if (registries.facts && !registries.facts.has(requirement.fact)) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} references unknown selection fact ${requirement.fact}.`, + ); + } + continue; + } + const key = `${requirement.topologyQualification.id}@${String(requirement.topologyQualification.schemaVersion)}`; + if (registries.topologyQualifications && !registries.topologyQualifications.has(key)) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} references unknown topology qualification ${key}.`, + ); } } } -function assertCatalogIntegrity(value: unknown): asserts value is CompiledManagedInferenceCatalog { - if (!isRecord(value)) throw new Error("managed inference catalog must be an object"); - const catalog = value as unknown as Partial; +function validateBindings( + preset: ServingPreset, + recipe: ServingRecipe, + registries: ServingCatalogRegistries, +): void { + const recipeBindingsByName = recipe.spec.bindings ?? {}; + const presetBindingsByName = preset.spec.plan.bindings ?? {}; + const recipeBindings = Object.keys(recipeBindingsByName).sort(); + const presetBindings = Object.keys(presetBindingsByName).sort(); if ( - catalog.schemaVersion !== MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION || - catalog.compilerVersion !== MANAGED_INFERENCE_CATALOG_COMPILER_VERSION + recipeBindings.length !== presetBindings.length || + recipeBindings.some((name, index) => name !== presetBindings[index]) ) { - throw new Error("managed inference catalog version is unsupported"); - } - if (!SHA256.test(catalog.catalogDigest ?? "") || !SHA256.test(catalog.sourceRevision ?? "")) { - throw new Error("managed inference catalog provenance is invalid"); + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} bindings do not match recipe ${recipe.metadata.id}.`, + ); } - if ( - !Array.isArray(catalog.sourceFiles) || - !Array.isArray(catalog.recipes) || - !Array.isArray(catalog.presets) || - catalog.recipes.length === 0 || - catalog.presets.length === 0 - ) { - throw new Error("managed inference catalog definitions are invalid"); + for (const name of recipeBindings) { + const expected = recipeBindingsByName[name]!; + const actual = presetBindingsByName[name]!.valueFromTopologyQualification; + const key = `${expected.qualificationId}@${String(expected.schemaVersion)}`; + const descriptor = registries.topologyQualifications?.get(key); + if ( + actual.id !== expected.qualificationId || + actual.schemaVersion !== expected.schemaVersion || + (descriptor && + (actual.output !== descriptor.bindingOutput || + expected.outputSchema !== descriptor.outputSchema)) + ) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} has invalid topology binding ${name}.`, + ); + } } +} - const { catalogDigest, ...withoutDigest } = catalog as CompiledManagedInferenceCatalog; - if (managedInferenceDigest(withoutDigest) !== catalogDigest) { - throw new Error("managed inference catalog digest does not match its contents"); +function validateCatalogSemantics( + recipes: readonly ServingRecipe[], + presets: readonly ServingPreset[], + registries: ServingCatalogRegistries, +): void { + const recipesById = new Map(recipes.map((recipe) => [recipe.metadata.id, recipe])); + for (const preset of presets) { + const recipe = recipesById.get(preset.spec.plan.recipeRef); + if (!recipe) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} references unknown recipe ${preset.spec.plan.recipeRef}.`, + ); + } + if (recipe.spec.backend !== preset.spec.plan.backend) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} selects backend ${preset.spec.plan.backend}, but recipe ${recipe.metadata.id} uses ${recipe.spec.backend}.`, + ); + } + validateBindings(preset, recipe, registries); + const nodeCount = (preset.spec.requirements?.all ?? []).find( + (requirement) => + "fact" in requirement && + requirement.fact === "cluster.nodeCount" && + requirement.operator === "equals" && + typeof requirement.value === "number", + ); + if (nodeCount && "fact" in nodeCount && recipe.spec.execution.nodeCount !== nodeCount.value) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} node-count requirement does not match recipe ${recipe.metadata.id}.`, + ); + } } - if (managedInferenceDigest(catalog.sourceFiles) !== catalog.sourceRevision) { - throw new Error("managed inference catalog source revision does not match its provenance"); + + const automaticSelectors = new Map(); + for (const preset of presets) { + if (preset.spec.selection !== "automatic") continue; + const requirements = (preset.spec.requirements?.all ?? []) + .map((requirement) => canonicalServingCatalogJson(requirement)) + .sort(); + const key = canonicalServingCatalogJson({ + backend: preset.spec.plan.backend, + priority: preset.spec.priority, + requirements, + }); + const previous = automaticSelectors.get(key); + if (previous) { + throw new ServingCatalogValidationError( + `Automatic presets ${previous} and ${preset.metadata.id} have the same selector at priority ${preset.spec.priority} for backend ${preset.spec.plan.backend}.`, + ); + } + automaticSelectors.set(key, preset.metadata.id); } +} + +function catalogPayload(catalog: CompiledServingCatalog): CompiledServingCatalogPayload { + const { catalogDigest: _catalogDigest, ...payload } = catalog; + return payload; +} + +export function compileTrustedServingCatalog( + options: CompileServingCatalogOptions, +): CompiledServingCatalog { + const validators = createValidators(options.schemas); + const recipes: ServingRecipe[] = []; + const presets: ServingPreset[] = []; + const sources: ServingCatalogSourceProvenance[] = []; + const definitionIds = new Set(); const sourcePaths = new Set(); - for (const source of catalog.sourceFiles) { - if ( - !isRecord(source) || - typeof source.path !== "string" || - !SOURCE_PATH.test(source.path) || - sourcePaths.has(source.path) || - typeof source.digest !== "string" || - !SHA256.test(source.digest) - ) { - throw new Error("managed inference catalog source provenance is invalid"); + + for (const source of [...options.sources].sort((left, right) => + compareCanonicalText(left.path, right.path), + )) { + const sourceMatch = CATALOG_SOURCE_PATTERN.exec(source.path); + const hasUnsafeSegment = source.path + .split("/") + .some((segment) => segment === "" || segment === "." || segment === ".."); + if (!sourceMatch || hasUnsafeSegment) { + throw new ServingCatalogValidationError( + `Catalog source ${source.path} is outside managed-inference/recipes or managed-inference/presets.`, + ); + } + if (sourcePaths.has(source.path)) { + throw new ServingCatalogValidationError(`Catalog source path ${source.path} is duplicated.`); } sourcePaths.add(source.path); + + const value = parseTrustedYaml(source); + const { kind, id } = definitionIdentity(source, value); + const expectedDirectory = kind === "ServingRecipe" ? "recipes" : "presets"; + if (sourceMatch[1] !== expectedDirectory) { + throw new ServingCatalogValidationError( + `${source.path} must place ${kind} definitions under managed-inference/${expectedDirectory}.`, + ); + } + const validate = kind === "ServingRecipe" ? validators.recipe : validators.preset; + if (!validate(value)) { + throw new ServingCatalogValidationError( + `${source.path} does not satisfy the ${kind} schema: ${validationDetails(validate)}`, + ); + } + if (definitionIds.has(id)) { + throw new ServingCatalogValidationError(`Serving definition ID ${id} is duplicated.`); + } + definitionIds.add(id); + + if (kind === "ServingRecipe") { + const recipe = value as unknown as ServingRecipe; + validateRecipeSemantics(recipe, options.registries); + recipes.push(recipe); + } else { + const preset = value as unknown as ServingPreset; + validatePresetRequirements(preset, options.registries); + presets.push(preset); + } + sources.push({ path: source.path, kind, id, digest: servingCatalogDigest(value) }); } - if (sourcePaths.size !== catalog.recipes.length + catalog.presets.length) { - throw new Error("managed inference catalog source provenance is incomplete"); - } - - const seenIds = new Set(); - const seenSources = new Set(); - assertCompiledDefinitions( - catalog.recipes, - "ServingRecipe", - "recipes", - sourcePaths, - seenIds, - seenSources, - ); - assertCompiledDefinitions( - catalog.presets, - "ServingPreset", - "presets", - sourcePaths, - seenIds, - seenSources, - ); - assertReferences(catalog.presets, catalog.recipes); -} - -let loadedCatalog: CompiledManagedInferenceCatalog | undefined; - -export function loadManagedInferenceCatalog(): CompiledManagedInferenceCatalog { - if (loadedCatalog) return loadedCatalog; - assertCatalogIntegrity(generatedCatalog); - loadedCatalog = immutableManagedInferenceCopy(generatedCatalog); - return loadedCatalog; -} - -export function getManagedInferenceCompiledPreset( - id: string, -): CompiledManagedInferenceCatalog["presets"][number] | undefined { - return loadManagedInferenceCatalog().presets.find( - ({ definition }) => definition.metadata.id === id, - ); -} - -export function getManagedInferenceCompiledRecipe( - id: string, -): CompiledManagedInferenceCatalog["recipes"][number] | undefined { - return loadManagedInferenceCatalog().recipes.find( - ({ definition }) => definition.metadata.id === id, - ); + + recipes.sort((left, right) => compareCanonicalText(left.metadata.id, right.metadata.id)); + presets.sort((left, right) => compareCanonicalText(left.metadata.id, right.metadata.id)); + validateCatalogSemantics(recipes, presets, options.registries); + + const payload: CompiledServingCatalogPayload = { + schemaVersion: CATALOG_SCHEMA_VERSION, + compilerVersion: COMPILER_VERSION, + sourceRevision: options.sourceRevision, + readinessSchemaRef: READINESS_SCHEMA_REF, + recipes, + presets, + sources, + }; + const catalog: CompiledServingCatalog = { + ...payload, + catalogDigest: servingCatalogDigest(payload), + }; + if (!validators.catalog(catalog)) { + throw new ServingCatalogValidationError( + `Compiled serving catalog is invalid: ${validationDetails(validators.catalog)}`, + ); + } + return catalog; } + +export function parseCompiledServingCatalogJson( + source: string, + schemas: ServingCatalogSchemas, +): CompiledServingCatalog { + let value: unknown; + try { + value = JSON.parse(source); + } catch (error) { + throw new ServingCatalogValidationError( + `Compiled serving catalog is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + ); + } + const validators = createValidators(schemas); + if (!validators.catalog(value)) { + throw new ServingCatalogValidationError( + `Compiled serving catalog is invalid: ${validationDetails(validators.catalog)}`, + ); + } + const catalog = value as CompiledServingCatalog; + const expectedDigest = servingCatalogDigest(catalogPayload(catalog)); + if (catalog.catalogDigest !== expectedDigest) { + throw new ServingCatalogValidationError( + `Compiled serving catalog digest mismatch: expected ${expectedDigest}.`, + ); + } + return catalog; +} + +export function serializeCompiledServingCatalog(catalog: CompiledServingCatalog): string { + return `${canonicalServingCatalogJson(catalog)}\n`; +} + +export const servingCatalogContract = Object.freeze({ + apiVersion: API_VERSION, + catalogSchemaVersion: CATALOG_SCHEMA_VERSION, + compilerVersion: COMPILER_VERSION, + readinessSchemaRef: READINESS_SCHEMA_REF, +}); diff --git a/src/lib/inference/serving/generate-catalog.ts b/src/lib/inference/serving/generate-catalog.ts new file mode 100644 index 00000000000..30d34c6f027 --- /dev/null +++ b/src/lib/inference/serving/generate-catalog.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; + +import { resolveSourceBuildIdentity } from "../../core/version"; +import { getManagedInferenceServingCatalogRegistries } from "./adapter-registry"; +import { compileTrustedServingCatalog, serializeCompiledServingCatalog } from "./catalog"; +import type { + ServingCatalogRegistries, + ServingCatalogSchemas, + ServingCatalogSource, +} from "./types"; + +function readJson(path: string): object { + return JSON.parse(readFileSync(path, "utf8")) as object; +} + +function loadSchemas(rootDir: string): ServingCatalogSchemas { + const schemaRoot = join(rootDir, "managed-inference", "schemas"); + return { + catalog: readJson(join(schemaRoot, "catalog.schema.json")), + preset: readJson(join(schemaRoot, "preset.schema.json")), + recipe: readJson(join(schemaRoot, "recipe.schema.json")), + }; +} + +function discoverYamlFiles(directory: string): string[] { + if (!existsSync(directory)) return []; + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = join(directory, entry.name); + if (entry.isDirectory()) return discoverYamlFiles(path); + return entry.isFile() && /\.ya?ml$/.test(entry.name) ? [path] : []; + }); +} + +function loadSources(rootDir: string): ServingCatalogSource[] { + const managedInferenceRoot = join(rootDir, "managed-inference"); + const files = [ + ...discoverYamlFiles(join(managedInferenceRoot, "recipes")), + ...discoverYamlFiles(join(managedInferenceRoot, "presets")), + ]; + return files + .sort((left, right) => (left < right ? -1 : left > right ? 1 : 0)) + .map((path) => ({ + path: relative(rootDir, path).replaceAll("\\", "/"), + contents: readFileSync(path, "utf8"), + })); +} + +export interface GenerateServingCatalogOptions { + rootDir: string; + outputPath?: string; + registries?: ServingCatalogRegistries; +} + +function compileServingCatalog(options: GenerateServingCatalogOptions) { + return compileTrustedServingCatalog({ + sources: loadSources(options.rootDir), + sourceRevision: resolveSourceBuildIdentity({ rootDir: options.rootDir }).sourceRevision, + schemas: loadSchemas(options.rootDir), + registries: options.registries ?? getManagedInferenceServingCatalogRegistries(), + }); +} + +export function checkServingCatalog(options: GenerateServingCatalogOptions): void { + compileServingCatalog(options); +} + +export function generateServingCatalog(options: GenerateServingCatalogOptions): string { + const outputPath = + options.outputPath ?? join(options.rootDir, "dist", "managed-inference", "catalog.json"); + const catalog = compileServingCatalog(options); + mkdirSync(dirname(outputPath), { recursive: true }); + writeFileSync(outputPath, serializeCompiledServingCatalog(catalog)); + return outputPath; +} + +if (require.main === module) { + const rootDir = join(__dirname, "..", "..", "..", ".."); + if (process.argv.includes("--check")) checkServingCatalog({ rootDir }); + else generateServingCatalog({ rootDir }); +} diff --git a/src/lib/inference/serving/managed-cluster-discovery.ts b/src/lib/inference/serving/managed-cluster-discovery.ts index 6cc010d04c0..0dbd3e25423 100644 --- a/src/lib/inference/serving/managed-cluster-discovery.ts +++ b/src/lib/inference/serving/managed-cluster-discovery.ts @@ -7,7 +7,7 @@ import path from "node:path"; import type { BuildIdentity } from "../../core/version.js"; import type { SystemReadinessReport } from "../../readiness/types.js"; import { MANAGED_CLUSTER_VLLM_MATERIALIZER_REF } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; import { createProductionManagedClusterDiscoveryDeps } from "./managed-cluster-discovery-production.js"; import { @@ -385,14 +385,9 @@ function selectionFromEnvironment( "The selected managed inference preset catalog is unavailable.", ); } - const compiledPreset = catalog.presets.find( - ({ definition }) => definition.metadata.id === preset, - ); + const compiledPreset = catalog.presets.find(({ metadata }) => metadata.id === preset); const recipe = compiledPreset - ? catalog.recipes.find( - ({ definition }) => - definition.metadata.id === compiledPreset.definition.spec.plan.recipeRef, - )?.definition + ? catalog.recipes.find(({ metadata }) => metadata.id === compiledPreset.spec.plan.recipeRef) : undefined; if (recipe?.spec.execution.materializerRef !== MANAGED_CLUSTER_VLLM_MATERIALIZER_REF) { return peers.length > 0 diff --git a/src/lib/inference/serving/managed-cluster-executor.ts b/src/lib/inference/serving/managed-cluster-executor.ts index 5fe3d2099d5..7b19d31c6f1 100644 --- a/src/lib/inference/serving/managed-cluster-executor.ts +++ b/src/lib/inference/serving/managed-cluster-executor.ts @@ -20,9 +20,12 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; -import { getManagedInferenceCompiledPreset, getManagedInferenceCompiledRecipe } from "./catalog.js"; -import { managedInferenceHexDigest } from "./catalog-integrity.js"; -import type { ManagedInferenceServingRecipe } from "./catalog-types.js"; +import { + getManagedInferenceCompiledPreset, + getManagedInferenceCompiledRecipe, +} from "./catalog-loader.js"; +import { managedInferenceDigest, managedInferenceHexDigest } from "./catalog-integrity.js"; +import type { ManagedInferenceServingRecipe } from "./types.js"; import { isRelatedManagedVllmContainer, type ManagedClusterApiProbeRequest, @@ -373,16 +376,16 @@ export function assertManagedClusterVllmExecutorConfig( if ( !compiledPreset || !compiledRecipe || - compiledPreset.definitionDigest !== plan.presetDigest || - compiledRecipe.definitionDigest !== plan.recipeDigest || - compiledPreset.definition.spec.plan.recipeRef !== compiledRecipe.definition.metadata.id || - compiledPreset.definition.spec.plan.backend !== compiledRecipe.definition.spec.backend + managedInferenceDigest(compiledPreset) !== plan.presetDigest || + managedInferenceDigest(compiledRecipe) !== plan.recipeDigest || + compiledPreset.spec.plan.recipeRef !== compiledRecipe.metadata.id || + compiledPreset.spec.plan.backend !== compiledRecipe.spec.backend ) { throw new Error( "Managed cluster executor input does not match its selected definition digests", ); } - const recipe = compiledRecipe.definition.spec; + const recipe = compiledRecipe.spec; const topologyIdentity = { id: plan.topologyId, schemaVersion: plan.topologySchemaVersion, @@ -400,10 +403,10 @@ export function assertManagedClusterVllmExecutorConfig( schemaVersion: 1, adapterId: MANAGED_CLUSTER_VLLM_ADAPTER_ID, catalogDigest: plan.catalogDigest, - presetId: compiledPreset.definition.metadata.id, - presetDigest: compiledPreset.definitionDigest, - recipeId: compiledRecipe.definition.metadata.id, - recipeDigest: compiledRecipe.definitionDigest, + presetId: compiledPreset.metadata.id, + presetDigest: managedInferenceDigest(compiledPreset), + recipeId: compiledRecipe.metadata.id, + recipeDigest: managedInferenceDigest(compiledRecipe), topologyId: MANAGED_CLUSTER_TOPOLOGY_ID, topologySchemaVersion: MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, topologySubjectDigest: plan.topologySubjectDigest, diff --git a/src/lib/inference/serving/managed-cluster-fixture.test-support.ts b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts index fb4d77fe8d5..32c947a145f 100644 --- a/src/lib/inference/serving/managed-cluster-fixture.test-support.ts +++ b/src/lib/inference/serving/managed-cluster-fixture.test-support.ts @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { MANAGED_CLUSTER_VLLM_MATERIALIZER_REF } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; -import type { ResolvedManagedInferenceSelection } from "./catalog-types.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; +import { managedInferenceDigest } from "./catalog-integrity.js"; +import type { ResolvedManagedInferenceSelection } from "./types.js"; import { type ManagedClusterVllmPlan, materializeManagedClusterVllmPlan, @@ -20,12 +21,9 @@ function fixtureCatalogDefinitions() { const catalog = loadManagedInferenceCatalog(); for (const compiledPreset of catalog.presets) { const compiledRecipe = catalog.recipes.find( - ({ definition }) => definition.metadata.id === compiledPreset.definition.spec.plan.recipeRef, + ({ metadata }) => metadata.id === compiledPreset.spec.plan.recipeRef, ); - if ( - compiledRecipe?.definition.spec.execution.materializerRef === - MANAGED_CLUSTER_VLLM_MATERIALIZER_REF - ) { + if (compiledRecipe?.spec.execution.materializerRef === MANAGED_CLUSTER_VLLM_MATERIALIZER_REF) { return { catalog, compiledPreset, compiledRecipe }; } } @@ -33,12 +31,12 @@ function fixtureCatalogDefinitions() { } export const FIXTURE_MANAGED_CLUSTER_PRESET_ID = - fixtureCatalogDefinitions().compiledPreset.definition.metadata.id; + fixtureCatalogDefinitions().compiledPreset.metadata.id; export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelection { const { catalog, compiledPreset, compiledRecipe } = fixtureCatalogDefinitions(); - const preset = structuredClone(compiledPreset.definition); - const recipe = structuredClone(compiledRecipe.definition); + const preset = structuredClone(compiledPreset); + const recipe = structuredClone(compiledRecipe); const subjectNodeIds = ["spark-head", "spark-worker"] as const; const output: ManagedClusterTopologyOutput = { controllerNodeId: "spark-head", @@ -111,8 +109,8 @@ export function fixtureManagedClusterSelection(): ResolvedManagedInferenceSelect outcome: "selected", selection: "automatic", catalogDigest: catalog.catalogDigest, - presetDigest: compiledPreset.definitionDigest, - recipeDigest: compiledRecipe.definitionDigest, + presetDigest: managedInferenceDigest(compiledPreset), + recipeDigest: managedInferenceDigest(compiledRecipe), preset, recipe, topologyQualification: { diff --git a/src/lib/inference/serving/managed-cluster-installer.ts b/src/lib/inference/serving/managed-cluster-installer.ts index de354a8c226..a49e3b40e6c 100644 --- a/src/lib/inference/serving/managed-cluster-installer.ts +++ b/src/lib/inference/serving/managed-cluster-installer.ts @@ -10,7 +10,7 @@ import { type ManagedInferenceResolution, type ManagedInferenceResolverInput, type ManagedInferenceServingRecipe, -} from "./catalog-types.js"; +} from "./types.js"; import { claimManagedClusterManagedServingCapability, type ManagedClusterConfirmedManagedServingCapability, @@ -230,7 +230,7 @@ function managedProfile( ): VllmProfile { const head = managedClusterHeadRole(plan); return { - name: recipe.metadata.displayName, + name: recipe.metadata.displayName ?? recipe.metadata.id, platform: "spark", image: head.image, imageDownloadSizeBytes: head.runtime.imageDownloadSizeBytes, @@ -249,7 +249,7 @@ function managedModel( ): VllmModelDef { return { id: plan.model.id, - label: recipe.metadata.displayName, + label: recipe.metadata.displayName ?? recipe.metadata.id, envValue: plan.model.servedName, downloadSizeBytes: managedClusterHeadRole(plan).preparation.modelDownloadSizeBytes, maxModelLen: requiredPositiveIntegerArgument(recipe, "--max-model-len"), diff --git a/src/lib/inference/serving/managed-cluster-materialize.test.ts b/src/lib/inference/serving/managed-cluster-materialize.test.ts index fdec7414a36..77c77991130 100644 --- a/src/lib/inference/serving/managed-cluster-materialize.test.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.test.ts @@ -7,14 +7,14 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; -import { managedInferenceDigest, managedInferenceTextDigest } from "./catalog-integrity.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; +import { managedInferenceDigest } from "./catalog-integrity.js"; import type { CompiledManagedInferenceCatalog, ManagedInferenceServingPreset, ManagedInferenceServingRecipe, ResolvedManagedInferenceSelection, -} from "./catalog-types.js"; +} from "./types.js"; import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { MANAGED_CLUSTER_PRESET_LABEL, @@ -106,11 +106,11 @@ function syntheticSecondProfile( const baseSelection = selectionWithDigests(); const topology = nodeCount === 3 ? threeNodeTopology() : baseSelection.topologyQualification; const basePreset = baseCatalog.presets.find( - ({ definition }) => definition.metadata.id === baseSelection.preset.metadata.id, - )?.definition; + ({ metadata }) => metadata.id === baseSelection.preset.metadata.id, + ); const baseRecipe = baseCatalog.recipes.find( - ({ definition }) => definition.metadata.id === baseSelection.recipe.metadata.id, - )?.definition; + ({ metadata }) => metadata.id === baseSelection.recipe.metadata.id, + ); expect(basePreset).toBeDefined(); expect(baseRecipe).toBeDefined(); const presetTemplate = basePreset as ManagedInferenceServingPreset; @@ -196,38 +196,29 @@ function syntheticSecondProfile( const presetDigest = managedInferenceDigest(preset); const recipeSourceFile = "managed-inference/recipes/vllm.synthetic-model.managed-cluster.v1.yaml"; const presetSourceFile = "managed-inference/presets/vllm.synthetic-profile.managed-cluster.yaml"; - const sourceFiles = [ - ...baseCatalog.sourceFiles, + const sources = [ + ...baseCatalog.sources, { path: presetSourceFile, - digest: managedInferenceTextDigest("synthetic preset"), + kind: "ServingPreset" as const, + id: preset.metadata.id, + digest: presetDigest, }, { path: recipeSourceFile, - digest: managedInferenceTextDigest("synthetic recipe"), + kind: "ServingRecipe" as const, + id: recipe.metadata.id, + digest: recipeDigest, }, ]; const catalogContents = { compilerVersion: baseCatalog.compilerVersion, - presets: [ - ...baseCatalog.presets, - { - definition: preset, - definitionDigest: presetDigest, - sourceFile: presetSourceFile, - }, - ], - recipes: [ - ...baseCatalog.recipes, - { - definition: recipe, - definitionDigest: recipeDigest, - sourceFile: recipeSourceFile, - }, - ], + presets: [...baseCatalog.presets, preset], + recipes: [...baseCatalog.recipes, recipe], + readinessSchemaRef: baseCatalog.readinessSchemaRef, schemaVersion: baseCatalog.schemaVersion, - sourceFiles, - sourceRevision: managedInferenceDigest(sourceFiles), + sources, + sourceRevision: baseCatalog.sourceRevision, } as const; const catalog: CompiledManagedInferenceCatalog = { ...catalogContents, diff --git a/src/lib/inference/serving/managed-cluster-materialize.ts b/src/lib/inference/serving/managed-cluster-materialize.ts index 60d3047a171..5038fd39889 100644 --- a/src/lib/inference/serving/managed-cluster-materialize.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.ts @@ -12,7 +12,7 @@ import { isManagedClusterMaterializerOwnedEnvironment, MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { immutableManagedInferenceCopy, managedInferenceDigest, @@ -20,12 +20,11 @@ import { } from "./catalog-integrity.js"; import { type CompiledManagedInferenceCatalog, - type CompiledManagedInferenceDefinition, isManagedInferenceMaterializerOwnedArgument, type ManagedInferenceServingPreset, type ManagedInferenceServingRecipe, type ResolvedManagedInferenceSelection, -} from "./catalog-types.js"; +} from "./types.js"; import { type ManagedClusterVllmPreparationPlan, materializeManagedClusterVllmPreparation, @@ -195,27 +194,24 @@ function safeAbsolutePath(value: string): boolean { } function selectedDefinition( - definitions: readonly CompiledManagedInferenceDefinition[], + definitions: readonly TDefinition[], selected: TDefinition, selectedDigest: string, label: string, ): TDefinition { - const matches = definitions.filter( - ({ definition }) => definition.metadata.id === selected.metadata.id, - ); + const matches = definitions.filter(({ metadata }) => metadata.id === selected.metadata.id); if (matches.length !== 1) { fail(`selected ${label} ${selected.metadata.id} is not unique in the compiled catalog`); } const compiled = matches[0]!; if ( !SHA256_PATTERN.test(selectedDigest) || - compiled.definitionDigest !== selectedDigest || - managedInferenceDigest(compiled.definition) !== selectedDigest || + managedInferenceDigest(compiled) !== selectedDigest || managedInferenceDigest(selected) !== selectedDigest ) { fail(`selected ${label} ${selected.metadata.id} does not match its definition digest`); } - return compiled.definition; + return compiled; } function assertCatalogSelection( @@ -230,10 +226,7 @@ function assertCatalogSelection( ) { fail("the resolved selection does not match the compiled catalog digest"); } - if ( - !SHA256_PATTERN.test(catalog.sourceRevision) || - managedInferenceDigest(catalog.sourceFiles) !== catalog.sourceRevision - ) { + if (!/^[0-9a-f]{40,64}$/u.test(catalog.sourceRevision)) { fail("the compiled catalog provenance is invalid"); } diff --git a/src/lib/inference/serving/managed-cluster-topology.ts b/src/lib/inference/serving/managed-cluster-topology.ts index ed13c46dfae..568d62d20ae 100644 --- a/src/lib/inference/serving/managed-cluster-topology.ts +++ b/src/lib/inference/serving/managed-cluster-topology.ts @@ -6,7 +6,7 @@ import net from "node:net"; import { checkSystemReadinessSchemaVersion } from "../../readiness/compatibility.js"; import type { SystemReadinessReport } from "../../readiness/types.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; -import type { ManagedInferenceTopologyQualification } from "./catalog-types.js"; +import type { ManagedInferenceTopologyQualification } from "./types.js"; import { MANAGED_CLUSTER_ID_PATTERN } from "./managed-cluster-identifiers.js"; export const MANAGED_CLUSTER_TOPOLOGY_ID = "host-cluster.direct-cx7" as const; diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 02b35a705ab..7d051fd1558 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import type { SystemReadinessReport } from "../../readiness/types.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; import type { CompiledManagedInferenceCatalog, @@ -13,7 +13,7 @@ import type { ManagedInferenceServingPreset, ManagedInferenceServingRecipe, ManagedInferenceTopologyQualification, -} from "./catalog-types.js"; +} from "./types.js"; import { FIXTURE_MANAGED_CLUSTER_PRESET_ID, fixtureManagedClusterSelection, @@ -35,27 +35,27 @@ function shippedCompiledPreset( catalog = shippedCatalog(), ): CompiledManagedInferenceCatalog["presets"][number] { const preset = catalog.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, + ({ metadata }) => metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, ); expect(preset).toBeDefined(); return preset as CompiledManagedInferenceCatalog["presets"][number]; } function shippedPreset(catalog = shippedCatalog()): ManagedInferenceServingPreset { - return shippedCompiledPreset(catalog).definition; + return shippedCompiledPreset(catalog); } function shippedCompiledRecipe( catalog = shippedCatalog(), ): CompiledManagedInferenceCatalog["recipes"][number] { - const recipeRef = shippedCompiledPreset(catalog).definition.spec.plan.recipeRef; - const recipe = catalog.recipes.find(({ definition }) => definition.metadata.id === recipeRef); + const recipeRef = shippedCompiledPreset(catalog).spec.plan.recipeRef; + const recipe = catalog.recipes.find(({ metadata }) => metadata.id === recipeRef); expect(recipe).toBeDefined(); return recipe as CompiledManagedInferenceCatalog["recipes"][number]; } function shippedRecipe(catalog = shippedCatalog()): ManagedInferenceServingRecipe { - return shippedCompiledRecipe(catalog).definition; + return shippedCompiledRecipe(catalog); } function shippedFixtureCatalog(): CompiledManagedInferenceCatalog { @@ -210,28 +210,8 @@ function catalogWithSecondProfile(options: { return { catalog: { ...catalog, - presets: [ - { - ...firstCompiledPreset, - definition: normalizedFirst, - definitionDigest: managedInferenceDigest(normalizedFirst), - }, - { - ...firstCompiledPreset, - definition: secondPreset, - definitionDigest: managedInferenceDigest(secondPreset), - sourceFile: "managed-inference/presets/vllm.synthetic.dual-second.yaml", - }, - ], - recipes: [ - firstCompiledRecipe, - { - ...firstCompiledRecipe, - definition: secondRecipe, - definitionDigest: managedInferenceDigest(secondRecipe), - sourceFile: "managed-inference/recipes/vllm.synthetic.second-recipe.yaml", - }, - ], + presets: [normalizedFirst, secondPreset], + recipes: [firstCompiledRecipe, secondRecipe], }, secondPresetId, secondRecipeId, @@ -248,8 +228,8 @@ describe("managed inference resolver", () => { expect(result).toMatchObject({ outcome: "selected", selection: "automatic", - presetDigest: compiledPreset.definitionDigest, - recipeDigest: compiledRecipe.definitionDigest, + presetDigest: managedInferenceDigest(compiledPreset), + recipeDigest: managedInferenceDigest(compiledRecipe), preset: { metadata: { id: shippedPreset(catalog).metadata.id } }, recipe: { metadata: { id: shippedRecipe(catalog).metadata.id } }, topologyQualification: { output: { masterAddress: "192.168.100.10" } }, @@ -302,10 +282,10 @@ describe("managed inference resolver", () => { }); const highCompiledPreset = shippedCompiledPreset(baseCatalog); const secondCompiledPreset = baseCatalog.presets.find( - ({ definition }) => definition.metadata.id === secondPresetId, + ({ metadata }) => metadata.id === secondPresetId, ); expect(secondCompiledPreset).toBeDefined(); - const highPreset = highCompiledPreset.definition; + const highPreset = highCompiledPreset; const unavailableHighPreset = { ...highPreset, spec: { @@ -328,11 +308,7 @@ describe("managed inference resolver", () => { const catalog: CompiledManagedInferenceCatalog = { ...baseCatalog, presets: [ - { - ...highCompiledPreset, - definition: unavailableHighPreset, - definitionDigest: managedInferenceDigest(unavailableHighPreset), - }, + unavailableHighPreset, secondCompiledPreset as CompiledManagedInferenceCatalog["presets"][number], ], }; @@ -393,13 +369,7 @@ describe("managed inference resolver", () => { } as ManagedInferenceServingPreset; const customizedCatalog: CompiledManagedInferenceCatalog = { ...catalog, - presets: [ - { - ...shippedCompiledPreset(catalog), - definition: customizedPreset, - definitionDigest: managedInferenceDigest(customizedPreset), - }, - ], + presets: [customizedPreset], }; expect(resolveManagedInferenceServing(resolverInput(), customizedCatalog)).toMatchObject({ @@ -452,13 +422,7 @@ describe("managed inference resolver", () => { } as ManagedInferenceServingPreset; const customizedCatalog: CompiledManagedInferenceCatalog = { ...catalog, - presets: [ - { - ...shippedCompiledPreset(catalog), - definition: customizedPreset, - definitionDigest: managedInferenceDigest(customizedPreset), - }, - ], + presets: [customizedPreset], }; const reports = readinessSources(); reports[1] = { diff --git a/src/lib/inference/serving/resolver.ts b/src/lib/inference/serving/resolver.ts index 1dff1932c5d..c44584c6eef 100644 --- a/src/lib/inference/serving/resolver.ts +++ b/src/lib/inference/serving/resolver.ts @@ -7,8 +7,8 @@ import { getManagedInferenceRecipeRegistrationError, getManagedInferenceTopologyQualificationDescriptor, } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog.js"; -import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; +import { immutableManagedInferenceCopy, managedInferenceDigest } from "./catalog-integrity.js"; import type { CompiledManagedInferenceCatalog, ManagedInferenceFactRequirement, @@ -22,7 +22,7 @@ import type { ManagedInferenceServingRecipe, ManagedInferenceTopologyQualification, ManagedInferenceTopologyRequirement, -} from "./catalog-types.js"; +} from "./types.js"; export const MANAGED_INFERENCE_READINESS_MAX_AGE_MS = 30_000; const MAX_FUTURE_CLOCK_SKEW_MS = 5_000; @@ -315,7 +315,7 @@ function recipeForPreset( preset: ManagedInferenceServingPreset, ): CompiledManagedInferenceCatalog["recipes"][number] { const matches = catalog.recipes.filter( - ({ definition }) => definition.metadata.id === preset.spec.plan.recipeRef, + ({ metadata }) => metadata.id === preset.spec.plan.recipeRef, ); if (matches.length !== 1) { throw new Error( @@ -323,7 +323,7 @@ function recipeForPreset( ); } const compiledRecipe = matches[0]!; - const recipe = compiledRecipe.definition; + const recipe = compiledRecipe; if (recipe.spec.backend !== preset.spec.plan.backend) { throw new Error( `managed inference preset ${preset.metadata.id} backend does not match its recipe`, @@ -345,9 +345,9 @@ function matchingCandidate( | { readonly outcome: "unmet"; readonly message: string } | { readonly outcome: "invalid-topology"; readonly message: string } | { readonly outcome: "incompatible-intent"; readonly message: string } { - const preset = compiledPreset.definition; + const preset = compiledPreset; const compiledRecipe = recipeForPreset(catalog, preset); - const recipe = compiledRecipe.definition; + const recipe = compiledRecipe; const intentError = intentCompatibilityError(input.intent ?? {}, preset, recipe); if (intentError) return { outcome: "incompatible-intent", message: intentError }; const requirements = evaluateRequirements( @@ -366,9 +366,9 @@ function matchingCandidate( outcome: "matched", candidate: { preset, - presetDigest: compiledPreset.definitionDigest, + presetDigest: managedInferenceDigest(compiledPreset), recipe, - recipeDigest: compiledRecipe.definitionDigest, + recipeDigest: managedInferenceDigest(compiledRecipe), priority: presetPriority(preset), topologyQualification: requirements.topologyQualifications[0]!, }, @@ -431,9 +431,7 @@ export function resolveManagedInferenceServing( } if (explicitPresetId) { - const matches = catalog.presets.filter( - ({ definition }) => definition.metadata.id === explicitPresetId, - ); + const matches = catalog.presets.filter(({ metadata }) => metadata.id === explicitPresetId); if (matches.length !== 1) { return { outcome: "rejected", @@ -442,7 +440,7 @@ export function resolveManagedInferenceServing( }; } const compiledPreset = matches[0]!; - const preset = compiledPreset.definition; + const preset = compiledPreset; if (preset.spec.selection === "disabled") { return { outcome: "rejected", @@ -469,7 +467,7 @@ export function resolveManagedInferenceServing( const matching: MatchingCandidate[] = []; let firstInvalidTopology: string | undefined; for (const compiledPreset of catalog.presets) { - const preset = compiledPreset.definition; + const preset = compiledPreset; if (preset.spec.selection !== "automatic") continue; const evaluated = matchingCandidate(catalog, compiledPreset, input); if (evaluated.outcome === "matched") matching.push(evaluated.candidate); diff --git a/src/lib/inference/serving/catalog-types.ts b/src/lib/inference/serving/types.ts similarity index 50% rename from src/lib/inference/serving/catalog-types.ts rename to src/lib/inference/serving/types.ts index 57c051046e2..17e70fc1e28 100644 --- a/src/lib/inference/serving/catalog-types.ts +++ b/src/lib/inference/serving/types.ts @@ -3,46 +3,28 @@ import type { SystemReadinessReport } from "../../readiness/types.js"; -export const MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION = "1.0.0" as const; -export const MANAGED_INFERENCE_CATALOG_COMPILER_VERSION = "1.0.0" as const; +export type ServingDefinitionKind = "ServingRecipe" | "ServingPreset"; +export type ServingSelectionPolicy = "automatic" | "explicit-only" | "disabled"; +export type ReadinessEntityKind = "observation" | "capability" | "qualification"; -const MATERIALIZER_OWNED_SERVE_ARGUMENTS = new Set([ - "--api-key", - "--distributed-executor-backend", - "--headless", - "--host", - "--master-addr", - "--master-port", - "--nnodes", - "--node-rank", - "--pipeline-parallel-size", - "--revision", - "--served-model-name", - "--tensor-parallel-size", -]); - -export function isManagedInferenceMaterializerOwnedArgument(name: string): boolean { - return MATERIALIZER_OWNED_SERVE_ARGUMENTS.has(name); -} - -export interface ManagedInferenceMetadata { +export interface ServingMetadata { readonly id: string; - readonly displayName: string; + readonly displayName?: string; } -export interface ManagedInferenceServingArgument { +export interface ServingArgument { readonly name: string; readonly value?: string | number | boolean; } -export interface ManagedInferenceTopologyBinding { +export interface ServingTopologyBinding { readonly type: "topologyQualificationOutput"; readonly qualificationId: string; readonly schemaVersion: number; readonly outputSchema: string; } -export type ManagedInferenceModelPreparation = +export type ServingModelPreparation = | { readonly ref: "none/v1" } | { readonly ref: "snapshot-copy-and-exact-text-replacement/v1"; @@ -57,7 +39,7 @@ export type ManagedInferenceModelPreparation = }; }; -export interface ManagedInferenceTemporaryFilesystem { +export interface ServingTemporaryFilesystem { readonly target: string; readonly sizeBytes: number; readonly mode: string; @@ -67,18 +49,19 @@ export interface ManagedInferenceTemporaryFilesystem { export interface ManagedInferenceServingRecipe { readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; readonly kind: "ServingRecipe"; - readonly metadata: ManagedInferenceMetadata; + readonly metadata: ServingMetadata; readonly spec: { readonly backend: string; - readonly bindings: Readonly>; + readonly bindings: Readonly>; readonly model: { readonly id: string; readonly revision: string; readonly servedName: string; + readonly files?: readonly { readonly path: string; readonly digest: string }[]; readonly downloadSizeBytes: number; readonly gated: boolean; readonly installFastSafetensors: boolean; - readonly preparation: ManagedInferenceModelPreparation; + readonly preparation: ServingModelPreparation; }; readonly runtime: { readonly image: string; @@ -98,8 +81,9 @@ export interface ManagedInferenceServingRecipe { readonly source: string; readonly target: string; }; - readonly temporaryFilesystems: readonly ManagedInferenceTemporaryFilesystem[]; + readonly temporaryFilesystems: readonly ServingTemporaryFilesystem[]; readonly environment: Readonly>; + readonly components?: Readonly>; }; readonly execution: { readonly materializerRef: string; @@ -114,7 +98,7 @@ export interface ManagedInferenceServingRecipe { readonly serve: { readonly authentication: string; readonly executable: string; - readonly arguments: readonly ManagedInferenceServingArgument[]; + readonly arguments: readonly ServingArgument[]; }; readonly readiness: { readonly timeoutSeconds: number; @@ -123,10 +107,52 @@ export interface ManagedInferenceServingRecipe { }; } -export type ManagedInferenceReadinessRequirement = +export interface ServingRecipe { + readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; + readonly kind: "ServingRecipe"; + readonly metadata: ServingMetadata; + readonly spec: { + readonly backend: string; + readonly bindings?: Readonly>; + readonly model: { + readonly id: string; + readonly revision: string; + readonly servedName?: string; + readonly files?: readonly { readonly path: string; readonly digest: string }[]; + readonly downloadSizeBytes?: number; + readonly gated?: boolean; + readonly installFastSafetensors?: boolean; + readonly preparation?: ServingModelPreparation; + }; + readonly runtime?: Partial & { + readonly components?: Readonly>; + }; + readonly execution: { + readonly materializerRef: string; + readonly lifecycleRef: string; + readonly topologyBinding?: string; + readonly nodeCount?: number; + readonly tensorParallelSize?: number; + readonly pipelineParallelSize?: number; + readonly distributedExecutorBackend?: string; + readonly rendezvousPort?: number; + }; + readonly serve?: { + readonly authentication?: string; + readonly executable?: string; + readonly arguments?: readonly ServingArgument[]; + }; + readonly readiness?: { + readonly timeoutSeconds?: number; + readonly expectedModel?: string; + }; + }; +} + +export type ServingReadinessRequirement = | { readonly readiness: { - readonly scope: "everyNode" | "anyNode"; + readonly scope: "controller" | "everyNode" | "anyNode"; readonly kind: "qualification"; readonly id: string; readonly status: string; @@ -134,27 +160,23 @@ export type ManagedInferenceReadinessRequirement = } | { readonly readiness: { - readonly scope: "everyNode" | "anyNode"; + readonly scope: "controller" | "everyNode" | "anyNode"; readonly kind: "observation" | "capability"; readonly id: string; readonly state: string; }; }; -export type ManagedInferenceFactValue = - | string - | number - | boolean - | readonly (string | number | boolean)[]; +export type ServingFactValue = string | number | boolean | readonly (string | number | boolean)[]; -export interface ManagedInferenceFactRequirement { +export interface ServingFactRequirement { readonly fact: string; readonly state: "present" | "absent"; readonly operator: "equals" | "oneOf" | "atLeast" | "atMost" | "between"; - readonly value: ManagedInferenceFactValue; + readonly value: ServingFactValue; } -export interface ManagedInferenceTopologyRequirement { +export interface ServingTopologyRequirement { readonly topologyQualification: { readonly id: string; readonly schemaVersion: number; @@ -162,12 +184,12 @@ export interface ManagedInferenceTopologyRequirement { }; } -export type ManagedInferencePresetRequirement = - | ManagedInferenceReadinessRequirement - | ManagedInferenceFactRequirement - | ManagedInferenceTopologyRequirement; +export type ServingPresetRequirement = + | ServingReadinessRequirement + | ServingFactRequirement + | ServingTopologyRequirement; -export interface ManagedInferencePresetTopologyBinding { +export interface ServingPresetTopologyBinding { readonly valueFromTopologyQualification: { readonly id: string; readonly schemaVersion: number; @@ -178,38 +200,114 @@ export interface ManagedInferencePresetTopologyBinding { export interface ManagedInferenceServingPreset { readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; readonly kind: "ServingPreset"; - readonly metadata: ManagedInferenceMetadata; + readonly metadata: ServingMetadata; readonly spec: { - readonly selection: "automatic" | "explicit-only" | "disabled"; + readonly selection: ServingSelectionPolicy; readonly priority: number; - readonly requirements: { - readonly all: readonly ManagedInferencePresetRequirement[]; + readonly requirements: { readonly all: readonly ServingPresetRequirement[] }; + readonly plan: { + readonly backend: string; + readonly recipeRef: string; + readonly bindings: Readonly>; }; + }; +} + +export interface ServingPreset { + readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; + readonly kind: "ServingPreset"; + readonly metadata: ServingMetadata; + readonly spec: { + readonly selection: ServingSelectionPolicy; + readonly priority: number; + readonly requirements?: { readonly all: readonly ServingPresetRequirement[] }; readonly plan: { readonly backend: string; readonly recipeRef: string; - readonly bindings: Readonly>; + readonly bindings?: Readonly>; }; }; } -export interface CompiledManagedInferenceDefinition { - readonly definition: TDefinition; - readonly definitionDigest: string; - readonly sourceFile: string; +export interface ServingCatalogSourceProvenance { + readonly path: string; + readonly kind: ServingDefinitionKind; + readonly id: string; + readonly digest: string; } -export interface CompiledManagedInferenceCatalog { - readonly catalogDigest: string; - readonly compilerVersion: typeof MANAGED_INFERENCE_CATALOG_COMPILER_VERSION; - readonly presets: readonly CompiledManagedInferenceDefinition[]; - readonly recipes: readonly CompiledManagedInferenceDefinition[]; - readonly schemaVersion: typeof MANAGED_INFERENCE_CATALOG_SCHEMA_VERSION; - readonly sourceFiles: readonly { - readonly digest: string; - readonly path: string; - }[]; +export interface CompiledServingCatalogPayload { + readonly schemaVersion: "1.0.0"; + readonly compilerVersion: "1.0.0"; readonly sourceRevision: string; + readonly readinessSchemaRef: "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json"; + readonly recipes: readonly ServingRecipe[]; + readonly presets: readonly ServingPreset[]; + readonly sources: readonly ServingCatalogSourceProvenance[]; +} + +export interface CompiledServingCatalog extends CompiledServingCatalogPayload { + readonly catalogDigest: string; +} + +export interface ServingCatalogSource { + readonly path: string; + readonly contents: string; +} + +export interface ServingCatalogSchemas { + readonly catalog: object; + readonly preset: object; + readonly recipe: object; +} + +export interface ServingTopologyRegistryEntry { + readonly bindingOutput: string; + readonly outputSchema: string; +} + +export interface ServingCatalogRegistries { + readonly materializers: ReadonlySet; + readonly lifecycles: ReadonlySet; + readonly readiness: ReadonlyMap>; + readonly facts?: ReadonlySet; + readonly topologyQualifications?: ReadonlyMap; + readonly validateRecipe?: (recipe: ServingRecipe) => string | undefined; +} + +export type ManagedInferenceServingArgument = ServingArgument; +export type ManagedInferenceTopologyBinding = ServingTopologyBinding; +export type ManagedInferenceModelPreparation = ServingModelPreparation; +export type ManagedInferenceTemporaryFilesystem = ServingTemporaryFilesystem; +export type ManagedInferenceReadinessRequirement = ServingReadinessRequirement; +export type ManagedInferenceFactValue = ServingFactValue; +export type ManagedInferenceFactRequirement = ServingFactRequirement; +export type ManagedInferenceTopologyRequirement = ServingTopologyRequirement; +export type ManagedInferencePresetRequirement = ServingPresetRequirement; +export type ManagedInferencePresetTopologyBinding = ServingPresetTopologyBinding; +export interface CompiledManagedInferenceCatalog + extends Omit { + readonly presets: readonly ManagedInferenceServingPreset[]; + readonly recipes: readonly ManagedInferenceServingRecipe[]; +} + +const MATERIALIZER_OWNED_SERVE_ARGUMENTS = new Set([ + "--api-key", + "--distributed-executor-backend", + "--headless", + "--host", + "--master-addr", + "--master-port", + "--nnodes", + "--node-rank", + "--pipeline-parallel-size", + "--revision", + "--served-model-name", + "--tensor-parallel-size", +]); + +export function isManagedInferenceMaterializerOwnedArgument(name: string): boolean { + return MATERIALIZER_OWNED_SERVE_ARGUMENTS.has(name); } export interface ManagedInferenceTopologyQualification { diff --git a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts index 7c2cab4ee23..aea982ab04c 100644 --- a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts @@ -6,9 +6,9 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadManagedInferenceCatalog } from "./serving/catalog"; +import { loadManagedInferenceCatalog } from "./serving/catalog-loader"; import { managedInferenceDigest, managedInferenceHexDigest } from "./serving/catalog-integrity"; -import type { CompiledManagedInferenceCatalog } from "./serving/catalog-types"; +import type { CompiledManagedInferenceCatalog } from "./serving/types"; import { fixtureManagedClusterSelection } from "./serving/managed-cluster-fixture.test-support"; import { type ManagedClusterNodeSnapshot, @@ -60,7 +60,7 @@ beforeEach(() => { afterEach(() => { vi.unstubAllEnvs(); - vi.doUnmock("./serving/generated/catalog.json"); + vi.doUnmock("./serving/catalog-loader"); vi.resetModules(); sshFixture.cleanup(); fs.rmSync(root, { recursive: true, force: true }); @@ -113,52 +113,43 @@ function catalogWithUnrelatedProfile(): CompiledManagedInferenceCatalog { const selectedPreset = current.presets[0]!; const selectedRecipe = current.recipes[0]!; const unrelatedRecipe = { - ...selectedRecipe.definition, - metadata: { ...selectedRecipe.definition.metadata, id: "vllm.unrelated.managed-cluster.v1" }, + ...selectedRecipe, + metadata: { ...selectedRecipe.metadata, id: "vllm.unrelated.managed-cluster.v1" }, }; const unrelatedPreset = { - ...selectedPreset.definition, - metadata: { ...selectedPreset.definition.metadata, id: "vllm.unrelated.managed-cluster" }, + ...selectedPreset, + metadata: { ...selectedPreset.metadata, id: "vllm.unrelated.managed-cluster" }, spec: { - ...selectedPreset.definition.spec, + ...selectedPreset.spec, plan: { - ...selectedPreset.definition.spec.plan, + ...selectedPreset.spec.plan, recipeRef: unrelatedRecipe.metadata.id, }, }, }; - const sourceFiles = [ - ...current.sourceFiles, + const sources = [ + ...current.sources, { path: "managed-inference/presets/vllm.unrelated.managed-cluster.yaml", - digest: `sha256:${"1".repeat(64)}`, + kind: "ServingPreset" as const, + id: unrelatedPreset.metadata.id, + digest: managedInferenceDigest(unrelatedPreset), }, { path: "managed-inference/recipes/vllm.unrelated.managed-cluster.v1.yaml", - digest: `sha256:${"2".repeat(64)}`, + kind: "ServingRecipe" as const, + id: unrelatedRecipe.metadata.id, + digest: managedInferenceDigest(unrelatedRecipe), }, ] as const; const contents = { compilerVersion: current.compilerVersion, - presets: [ - ...current.presets, - { - definition: unrelatedPreset, - definitionDigest: managedInferenceDigest(unrelatedPreset), - sourceFile: sourceFiles.at(-2)!.path, - }, - ], - recipes: [ - ...current.recipes, - { - definition: unrelatedRecipe, - definitionDigest: managedInferenceDigest(unrelatedRecipe), - sourceFile: sourceFiles.at(-1)!.path, - }, - ], + presets: [...current.presets, unrelatedPreset], + recipes: [...current.recipes, unrelatedRecipe], + readinessSchemaRef: current.readinessSchemaRef, schemaVersion: current.schemaVersion, - sourceFiles, - sourceRevision: managedInferenceDigest(sourceFiles), + sources, + sourceRevision: current.sourceRevision, } as const; return { ...contents, catalogDigest: managedInferenceDigest(contents) }; } @@ -294,22 +285,28 @@ describe("managed cluster vLLM runtime receipt", () => { persistManagedClusterVllmRuntimeReceipt(source, { stateDir }); expect(changedCatalog.catalogDigest).not.toBe(currentCatalog.catalogDigest); - vi.doMock("./serving/generated/catalog.json", () => ({ default: changedCatalog })); + vi.doMock("./serving/catalog-loader", () => ({ + loadManagedInferenceCatalog: () => changedCatalog, + getManagedInferenceCompiledPreset: (id: string) => + changedCatalog.presets.find(({ metadata }) => metadata.id === id), + getManagedInferenceCompiledRecipe: (id: string) => + changedCatalog.recipes.find(({ metadata }) => metadata.id === id), + })); vi.resetModules(); const { loadManagedClusterVllmRuntimeReceipt: loadAgainstChangedCatalog } = await import( "./serving/managed-cluster-runtime-receipt" ); const loaded = loadAgainstChangedCatalog({ stateDir }); const currentPreset = changedCatalog.presets.find( - ({ definition }) => definition.metadata.id === source.plan.presetId, + ({ metadata }) => metadata.id === source.plan.presetId, ); const currentRecipe = changedCatalog.recipes.find( - ({ definition }) => definition.metadata.id === source.plan.recipeId, + ({ metadata }) => metadata.id === source.plan.recipeId, ); expect(loaded?.plan.catalogDigest).toBe(currentCatalog.catalogDigest); - expect(loaded?.plan.presetDigest).toBe(currentPreset?.definitionDigest); - expect(loaded?.plan.recipeDigest).toBe(currentRecipe?.definitionDigest); + expect(loaded?.plan.presetDigest).toBe(managedInferenceDigest(currentPreset)); + expect(loaded?.plan.recipeDigest).toBe(managedInferenceDigest(currentRecipe)); }); it("preserves a receipt-write failure when temporary-file cleanup also fails", () => { diff --git a/test/e2e/support/e2e-semantic-phase-check.test.ts b/test/e2e/support/e2e-semantic-phase-check.test.ts index 43b40995d15..4e3b2066041 100644 --- a/test/e2e/support/e2e-semantic-phase-check.test.ts +++ b/test/e2e/support/e2e-semantic-phase-check.test.ts @@ -31,7 +31,7 @@ const TEST_PROGRESS_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/progress.ts const FAKE_OPENAI_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/fake-openai-compatible.ts"); describe("semantic E2E phase checker", () => { - // source-shape-contract: compatibility -- Generated catalog and policy output must precede semantic collection and remain shared with the canonical CLI build + // source-shape-contract: compatibility -- Generated policy output must precede semantic collection and remain shared with the canonical CLI build test("builds the policy boundary before semantic collection and CLI compilation", () => { const scripts = ( JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8")) as { @@ -41,10 +41,10 @@ describe("semantic E2E phase checker", () => { expect(scripts["build:policy-boundary"]).toBe("tsc -p nemoclaw/tsconfig.shared.json"); expect(scripts["test:e2e-phases:check"]).toMatch( - /^npm run catalog:compile && npm run build:policy-boundary && node .*tools\/e2e\/check-semantic-phases\.mts$/u, + /^npm run build:policy-boundary && node .*tools\/e2e\/check-semantic-phases\.mts$/u, ); expect(scripts["build:cli"]).toMatch( - /^npm run build:policy-boundary && npm run catalog:compile && tsc -p tsconfig\.src\.json &&/u, + /^npm run build:policy-boundary && tsc -p tsconfig\.src\.json &&/u, ); }); diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index 379e92209ec..f3804669628 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -1,545 +1,95 @@ // 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 { readFileSync, readdirSync } from "node:fs"; import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; -import { parse, stringify } from "yaml"; - -import { - compileManagedInferenceCatalogSources, - type ManagedInferenceCatalogSource, - writeManagedInferenceCatalog, -} from "../scripts/managed-inference/compile-catalog.mts"; -import type { - ManagedInferenceReadinessSource, - ManagedInferenceServingPreset, - ManagedInferenceServingRecipe, - ResolvedManagedInferenceSelection, -} from "../src/lib/inference/serving/catalog-types.js"; -import { - FIXTURE_MANAGED_CLUSTER_PRESET_ID, - fixtureManagedClusterSelection, -} from "../src/lib/inference/serving/managed-cluster-fixture.test-support.js"; -import { materializeManagedClusterVllmPlan } from "../src/lib/inference/serving/managed-cluster-materialize.js"; -import type { ManagedClusterTopologyOutput } from "../src/lib/inference/serving/managed-cluster-topology.js"; -import { resolveManagedInferenceServing } from "../src/lib/inference/serving/resolver.js"; -import type { SystemReadinessReport } from "../src/lib/readiness/types.js"; -const REPOSITORY_ROOT = fileURLToPath(new URL("..", import.meta.url)); -const SOURCE_DIRECTORIES = ["managed-inference/presets", "managed-inference/recipes"] as const; -const FIXTURE_MANAGED_CLUSTER_RECIPE_ID = fixtureManagedClusterSelection().recipe.metadata.id; - -function catalogSources(): ManagedInferenceCatalogSource[] { - return SOURCE_DIRECTORIES.flatMap((directory) => - fs - .readdirSync(path.join(REPOSITORY_ROOT, directory), { - withFileTypes: true, - }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".yaml")) - .map((entry) => { - const sourcePath = `${directory}/${entry.name}`; - return { - path: sourcePath, - contents: fs.readFileSync(path.join(REPOSITORY_ROOT, sourcePath), "utf8"), - }; - }), - ); -} - -function replaceDefinition( - sources: readonly ManagedInferenceCatalogSource[], - kind: "ServingPreset" | "ServingRecipe", - replace: (definition: TDefinition) => TDefinition, -): ManagedInferenceCatalogSource[] { - const fixtureId = - kind === "ServingPreset" - ? FIXTURE_MANAGED_CLUSTER_PRESET_ID - : FIXTURE_MANAGED_CLUSTER_RECIPE_ID; - const replacementIndex = sources.findIndex((source) => { - const definition = parse(source.contents) as { - readonly kind?: unknown; - readonly metadata?: { readonly id?: unknown }; - }; - return definition.kind === kind && definition.metadata?.id === fixtureId; +import { describe, expect, it } from "vitest"; +import catalogSchema from "../managed-inference/schemas/catalog.schema.json" with { type: "json" }; +import presetSchema from "../managed-inference/schemas/preset.schema.json" with { type: "json" }; +import recipeSchema from "../managed-inference/schemas/recipe.schema.json" with { type: "json" }; +import { getManagedInferenceServingCatalogRegistries } from "../src/lib/inference/serving/adapter-registry.js"; +import { compileTrustedServingCatalog } from "../src/lib/inference/serving/catalog.js"; +import type { ServingCatalogSource } from "../src/lib/inference/serving/types.js"; + +const REPOSITORY_ROOT = path.join(import.meta.dirname, ".."); +const PROFILE_ID = "vllm.dgx-spark-gb10.dual.deepseek-v4-flash-0731"; +const RECIPE_ID = "vllm.deepseek-v4-flash-0731.spark-dual.v1"; + +function catalogSources(): ServingCatalogSource[] { + return (["presets", "recipes"] as const).flatMap((kind) => { + const directory = path.join(REPOSITORY_ROOT, "managed-inference", kind); + return readdirSync(directory) + .filter((name) => name.endsWith(".yaml")) + .map((name) => ({ + path: `managed-inference/${kind}/${name}`, + contents: readFileSync(path.join(directory, name), "utf8"), + })); }); - expect(replacementIndex).toBeGreaterThanOrEqual(0); - return sources.map((source, index) => - index === replacementIndex - ? { - ...source, - contents: stringify(replace(parse(source.contents) as TDefinition)), - } - : source, - ); -} - -function syntheticProfileSources( - sources: readonly ManagedInferenceCatalogSource[], -): ManagedInferenceCatalogSource[] { - const compiled = compileManagedInferenceCatalogSources(sources).catalog; - const sourcePreset = compiled.presets.find( - ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_PRESET_ID, - )?.definition; - expect(sourcePreset).toBeDefined(); - const presetTemplate = sourcePreset as ManagedInferenceServingPreset; - const sourceRecipe = compiled.recipes.find( - ({ definition }) => definition.metadata.id === presetTemplate.spec.plan.recipeRef, - )?.definition; - expect(sourceRecipe).toBeDefined(); - const recipeTemplate = sourceRecipe as ManagedInferenceServingRecipe; - - const recipe: ManagedInferenceServingRecipe = { - ...recipeTemplate, - metadata: { - id: "vllm.synthetic-model.generic-topology.v1", - displayName: "Synthetic model on a registered topology", - }, - spec: { - ...recipeTemplate.spec, - model: { - ...recipeTemplate.spec.model, - id: "example/Synthetic-Model", - revision: "1111111111111111111111111111111111111111", - servedName: "synthetic-model", - downloadSizeBytes: 12_345_678_901, - preparation: { ref: "none/v1" }, - }, - runtime: { - ...recipeTemplate.spec.runtime, - image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, - imageDownloadSizeBytes: 2_345_678_901, - sharedMemoryBytes: 34_359_738_368, - modelCache: { - ...recipeTemplate.spec.runtime.modelCache, - target: "/models/synthetic-cache", - }, - temporaryFilesystems: recipeTemplate.spec.runtime.temporaryFilesystems.map((filesystem) => - filesystem.target === recipeTemplate.spec.runtime.modelCache.target - ? { ...filesystem, target: "/models/synthetic-cache", sizeBytes: 8_589_934_592 } - : filesystem, - ), - environment: { - ...recipeTemplate.spec.runtime.environment, - FLASHINFER_WORKSPACE_BASE: "/models/synthetic-cache/flashinfer", - VLLM_CACHE_ROOT: "/models/synthetic-cache/vllm-cache", - SYNTHETIC_PROFILE: "enabled", - }, - }, - serve: { - ...recipeTemplate.spec.serve, - executable: "/opt/vllm/bin/vllm", - arguments: recipeTemplate.spec.serve.arguments.map((argument) => - argument.name === "--port" - ? { ...argument, value: 8_101 } - : argument.name === "--max-model-len" - ? { ...argument, value: 131_072 } - : argument, - ), - }, - readiness: { - ...recipeTemplate.spec.readiness, - timeoutSeconds: 900, - expectedModel: "synthetic-model", - }, - }, - }; - const preset: ManagedInferenceServingPreset = { - ...presetTemplate, - metadata: { - id: "vllm.synthetic-model.generic-topology", - displayName: "Synthetic model on a registered topology", - }, - spec: { - ...presetTemplate.spec, - priority: presetTemplate.spec.priority + 1, - plan: { ...presetTemplate.spec.plan, recipeRef: recipe.metadata.id }, - }, - }; - return [ - ...sources, - { - path: "managed-inference/recipes/vllm.synthetic-model.generic-topology.v1.yaml", - contents: stringify(recipe), - }, - { - path: "managed-inference/presets/vllm.synthetic-model.generic-topology.yaml", - contents: stringify(preset), - }, - ]; } -function matchingReadinessSources( - preset: ManagedInferenceServingPreset, -): ManagedInferenceReadinessSource[] { - const requirements = preset.spec.requirements.all.flatMap((requirement) => - "readiness" in requirement ? [requirement.readiness] : [], - ); - const report: SystemReadinessReport = { - schemaVersion: "1.1.0", - mutated: false, - provenance: { - nemoclawVersion: "0.1.0", - sourceRevision: "a".repeat(40), - observedAt: "2026-08-03T12:00:00.000Z", +function compile(sources: readonly ServingCatalogSource[]) { + return compileTrustedServingCatalog({ + sources, + sourceRevision: "a".repeat(40), + schemas: { + catalog: catalogSchema, + preset: presetSchema, + recipe: recipeSchema, }, - observations: requirements.flatMap((requirement) => - requirement.kind === "observation" - ? [ - { - id: requirement.id, - state: requirement.state as SystemReadinessReport["observations"][number]["state"], - }, - ] - : [], - ), - capabilities: requirements.flatMap((requirement) => - requirement.kind === "capability" - ? [ - { - id: requirement.id, - state: requirement.state as SystemReadinessReport["capabilities"][number]["state"], - }, - ] - : [], - ), - qualifications: requirements.flatMap((requirement) => - requirement.kind === "qualification" - ? [ - { - id: requirement.id, - status: - requirement.status as SystemReadinessReport["qualifications"][number]["status"], - }, - ] - : [], - ), - findings: [], - evidence: [], - status: "supported", - exitCode: 0, - }; - return ["spark-head", "spark-worker"].map((nodeId) => ({ - nodeId, - report: structuredClone(report), - })); -} - -describe("managed inference catalog compiler", () => { - it("produces an identical generated JSON document regardless of source enumeration order", () => { - const sources = catalogSources(); - const compiled = compileManagedInferenceCatalogSources(sources); - expect(compiled.document).toBe( - compileManagedInferenceCatalogSources([...sources].reverse()).document, - ); - expect(JSON.parse(compiled.document)).toEqual(compiled.catalog); - expect(compiled.document.endsWith("\n")).toBe(true); + registries: getManagedInferenceServingCatalogRegistries(), }); +} - it("writes the JSON artifact and removes legacy generated TypeScript outputs", () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-catalog-compiler-")); - const sources = catalogSources(); - const legacyPaths = [ - "src/lib/inference/serving/generated/catalog.ts", - "dist/lib/inference/serving/generated/catalog.js", - "dist/lib/inference/serving/generated/catalog.js.map", - "dist/lib/inference/serving/generated/catalog.d.ts", - "dist/lib/inference/serving/generated/catalog.d.ts.map", - ]; - try { - for (const source of sources) { - const sourcePath = path.join(root, source.path); - fs.mkdirSync(path.dirname(sourcePath), { recursive: true }); - fs.writeFileSync(sourcePath, source.contents, "utf8"); - } - for (const legacyPath of legacyPaths) { - const artifactPath = path.join(root, legacyPath); - fs.mkdirSync(path.dirname(artifactPath), { recursive: true }); - fs.writeFileSync(artifactPath, "legacy generated artifact\n", "utf8"); - } - - const compiled = writeManagedInferenceCatalog(root); - const documentPath = path.join(root, "src/lib/inference/serving/generated/catalog.json"); - expect(JSON.parse(fs.readFileSync(documentPath, "utf8"))).toEqual(compiled.catalog); - expect(legacyPaths.every((legacyPath) => !fs.existsSync(path.join(root, legacyPath)))).toBe( - true, - ); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } +describe("managed inference YAML profile contract", () => { + it("compiles the shipped managed-cluster profile through the canonical catalog (#8129)", () => { + const catalog = compile(catalogSources()); + const preset = catalog.presets.find(({ metadata }) => metadata.id === PROFILE_ID); + const recipe = catalog.recipes.find(({ metadata }) => metadata.id === RECIPE_ID); + + expect(preset?.spec.plan.recipeRef).toBe(RECIPE_ID); + expect(recipe?.spec.execution.nodeCount).toBe(2); + expect(preset?.spec.requirements?.all).toContainEqual({ + fact: "cluster.nodeCount", + state: "present", + operator: "equals", + value: 2, + }); }); - it("compiles a synthetic second YAML-only profile without schema or TypeScript changes", () => { + it("accepts another compatible profile as YAML-only catalog additions (#8129)", () => { const sources = catalogSources(); - const base = compileManagedInferenceCatalogSources(sources).catalog; - const compiled = compileManagedInferenceCatalogSources(syntheticProfileSources(sources)); - expect(compiled.catalog.presets).toHaveLength(base.presets.length + 1); - expect(compiled.catalog.recipes).toHaveLength(base.recipes.length + 1); - expect(compiled.catalog.presets.map(({ definition }) => definition.metadata.id)).toContain( - "vllm.synthetic-model.generic-topology", - ); - expect(compiled.catalog.recipes.map(({ definition }) => definition.metadata.id)).toContain( - "vllm.synthetic-model.generic-topology.v1", - ); - expect(compiled.document).toContain("vllm.synthetic-model.generic-topology"); - expect(compiled.document).toContain("vllm.synthetic-model.generic-topology.v1"); - }); - - it("resolves and materializes the second YAML-only profile without profile-specific code", () => { - const catalog = compileManagedInferenceCatalogSources( - syntheticProfileSources(catalogSources()), - ).catalog; - const preset = catalog.presets.find( - ({ definition }) => definition.metadata.id === "vllm.synthetic-model.generic-topology", - )?.definition; - expect(preset).toBeDefined(); - const topologyQualification = fixtureManagedClusterSelection().topologyQualification; - const resolution = resolveManagedInferenceServing( + const recipeSource = sources.find(({ path: sourcePath }) => sourcePath.includes("/recipes/"))!; + const presetSource = sources.find(({ path: sourcePath }) => sourcePath.includes("/presets/"))!; + const syntheticRecipeId = "vllm.synthetic.managed-cluster.v1"; + const syntheticPresetId = "vllm.synthetic.managed-cluster"; + const catalog = compile([ + ...sources, { - readinessReports: matchingReadinessSources(preset as ManagedInferenceServingPreset), - topologyQualifications: [topologyQualification], - now: new Date("2026-08-03T12:00:10.000Z"), - }, - catalog, - ); - expect(resolution).toMatchObject({ - outcome: "selected", - selection: "automatic", - preset: { metadata: { id: "vllm.synthetic-model.generic-topology" } }, - recipe: { metadata: { id: "vllm.synthetic-model.generic-topology.v1" } }, - }); - const plan = materializeManagedClusterVllmPlan( - resolution as ResolvedManagedInferenceSelection, - { catalog }, - ); - const revisionIndex = plan.roles[0].command.arguments.indexOf("--revision"); - - expect(plan).toMatchObject({ - model: { - id: "example/Synthetic-Model", - revision: "1111111111111111111111111111111111111111", - servedName: "synthetic-model", - }, - apiPort: 8_101, - readiness: { timeoutMs: 900_000, expectedModel: "synthetic-model" }, - }); - expect(plan.roles[0]).toMatchObject({ - image: `registry.example.test/vllm@sha256:${"2".repeat(64)}`, - runtime: { - sharedMemoryBytes: 34_359_738_368, - imageDownloadSizeBytes: 2_345_678_901, - modelCache: { source: "huggingface-cache", target: "/models/synthetic-cache" }, + path: "managed-inference/recipes/vllm.synthetic.managed-cluster.v1.yaml", + contents: recipeSource.contents.replace(RECIPE_ID, syntheticRecipeId), }, - preparation: { - ref: "none/v1", - modelDownloadSizeBytes: 12_345_678_901, - }, - environment: { - HF_HOME: "/models/synthetic-cache", - SYNTHETIC_PROFILE: "enabled", + { + path: "managed-inference/presets/vllm.synthetic.managed-cluster.yaml", + contents: presetSource.contents + .replace(PROFILE_ID, syntheticPresetId) + .replace(RECIPE_ID, syntheticRecipeId) + .replace("priority: 400", "priority: 399"), }, - command: { executable: "/opt/vllm/bin/vllm" }, - }); - expect(revisionIndex).toBeGreaterThanOrEqual(0); - expect(plan.roles[0].command.arguments[revisionIndex + 1]).toBe( - "1111111111111111111111111111111111111111", - ); - expect(plan.roles[0].command.arguments).toEqual( - expect.arrayContaining(["--port", "8101", "--max-model-len", "131072"]), - ); - }); - - it("rejects duplicate definition IDs across YAML files", () => { - const sources = catalogSources(); - const recipeSource = sources.find((source) => source.path.includes("/recipes/")); - expect(recipeSource).toBeDefined(); - expect(() => - compileManagedInferenceCatalogSources([ - ...sources, - { - ...(recipeSource as ManagedInferenceCatalogSource), - path: "managed-inference/recipes/duplicate.yaml", - }, - ]), - ).toThrow(/definition ID .* duplicated/u); - }); - - it("rejects an unknown recipe field", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingRecipe", - (recipe) => ({ - ...recipe, - spec: { ...recipe.spec, unsupportedField: true }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/additional properties/u); - }); + ]); - it("rejects a mutable runtime image reference", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingRecipe", - (recipe) => ({ - ...recipe, - spec: { - ...recipe.spec, - runtime: { - ...recipe.spec.runtime, - image: "registry.example.test/runtime:latest", - }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/schema validation/u); + expect(catalog.recipes.some(({ metadata }) => metadata.id === syntheticRecipeId)).toBe(true); + expect(catalog.presets.some(({ metadata }) => metadata.id === syntheticPresetId)).toBe(true); }); - it("derives a new definition digest when YAML profile data changes", () => { - const sources = catalogSources(); - const before = compileManagedInferenceCatalogSources(sources).catalog.recipes.find( - ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_RECIPE_ID, - ); - const changed = replaceDefinition( - sources, - "ServingRecipe", - (recipe) => ({ - ...recipe, - spec: { - ...recipe.spec, - runtime: { - ...recipe.spec.runtime, - environment: { - ...recipe.spec.runtime.environment, - SYNTHETIC_SETTING: "enabled", - }, - }, - }, - }), - ); - const after = compileManagedInferenceCatalogSources(changed).catalog.recipes.find( - ({ definition }) => definition.metadata.id === FIXTURE_MANAGED_CLUSTER_RECIPE_ID, - ); - expect(before).toBeDefined(); - expect(after).toBeDefined(); - expect(after?.definitionDigest).not.toBe(before?.definitionDigest); - }); - - it.each([ - "--node-rank", - "--headless", - "--host", - "--revision", - ])("rejects materializer-owned serving argument %s", (argument) => { - const sources = replaceDefinition( - catalogSources(), - "ServingRecipe", - (recipe) => ({ - ...recipe, - spec: { - ...recipe.spec, - serve: { - ...recipe.spec.serve, - arguments: [{ name: argument }, ...recipe.spec.serve.arguments], - }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( - new RegExp(`materializer-owned argument ${argument}`), - ); - }); - - it("rejects an unresolved preset recipe reference", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingPreset", - (preset) => ({ - ...preset, - spec: { - ...preset.spec, - plan: { ...preset.spec.plan, recipeRef: "vllm.missing.recipe" }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( - /references unknown recipe/u, - ); - }); - - it("rejects an unsupported selection fact even when it requests absence", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingPreset", - (preset) => ({ - ...preset, - spec: { - ...preset.spec, - requirements: { - all: [ - ...preset.spec.requirements.all, - { - fact: "cluster.unknown", - state: "absent", - operator: "equals", - value: true, - }, - ], - }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( - /unsupported selection fact/u, - ); - }); - - it("rejects a preset topology output not declared by the registered adapter", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingPreset", - (preset) => ({ - ...preset, - spec: { - ...preset.spec, - plan: { - ...preset.spec.plan, - bindings: Object.fromEntries( - Object.entries(preset.spec.plan.bindings).map(([name, binding]) => [ - name, - { - valueFromTopologyQualification: { - ...binding.valueFromTopologyQualification, - output: "unsupported-output", - }, - }, - ]), - ), - }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow( - /binding .* does not match its recipe/u, - ); - }); + it("keeps shipped profile identities out of production TypeScript (#8129)", () => { + const servingRoot = path.join(REPOSITORY_ROOT, "src", "lib", "inference", "serving"); + const productionSources = readdirSync(servingRoot) + .filter((name) => name.endsWith(".ts") && !name.endsWith(".test.ts")) + .map((name) => readFileSync(path.join(servingRoot, name), "utf8")) + .join("\n"); - it("rejects a recipe whose adapter reference is not registered", () => { - const sources = replaceDefinition( - catalogSources(), - "ServingRecipe", - (recipe) => ({ - ...recipe, - spec: { - ...recipe.spec, - execution: { - ...recipe.spec.execution, - materializerRef: "vllm.missing-adapter/v1", - }, - }, - }), - ); - expect(() => compileManagedInferenceCatalogSources(sources)).toThrow(/unknown materializer/u); + expect(productionSources).not.toContain(PROFILE_ID); + expect(productionSources).not.toContain(RECIPE_ID); }); }); diff --git a/test/package-contract/managed-inference-catalog.test.ts b/test/package-contract/managed-inference-catalog.test.ts index 62f9fe63232..23976654e7d 100644 --- a/test/package-contract/managed-inference-catalog.test.ts +++ b/test/package-contract/managed-inference-catalog.test.ts @@ -1,47 +1,86 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import fs from "node:fs"; -import { createRequire } from "node:module"; +import { execFileSync } from "node:child_process"; +import { + copyFileSync, + cpSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; import path from "node:path"; -import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; +import { parseCompiledServingCatalogJson } from "../../dist/lib/inference/serving/catalog"; +import catalogSchema from "../../managed-inference/schemas/catalog.schema.json" with { + type: "json", +}; +import presetSchema from "../../managed-inference/schemas/preset.schema.json" with { type: "json" }; +import recipeSchema from "../../managed-inference/schemas/recipe.schema.json" with { type: "json" }; -const require = createRequire(import.meta.url); -const REPOSITORY_ROOT = fileURLToPath(new URL("../..", import.meta.url)); -const GENERATED_CATALOG_DIRECTORY = path.join( - REPOSITORY_ROOT, - "dist/lib/inference/serving/generated", -); - -describe("managed inference catalog package contract", () => { - it("does not ship legacy generated TypeScript outputs", () => { - expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.js"))).toBe(false); - expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.js.map"))).toBe(false); - expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.d.ts"))).toBe(false); - expect(fs.existsSync(path.join(GENERATED_CATALOG_DIRECTORY, "catalog.d.ts.map"))).toBe(false); - }); +const REPOSITORY_ROOT = path.join(import.meta.dirname, "..", ".."); + +function createPackFixture(): string { + const fixtureRoot = mkdtempSync(path.join(tmpdir(), "nemoclaw-serving-catalog-pack-")); + const packageJson = JSON.parse( + readFileSync(path.join(REPOSITORY_ROOT, "package.json"), "utf8"), + ) as { scripts?: Record }; + // Local-directory packs always prepare first; keep this fixture scoped to packlist behavior. + packageJson.scripts = {}; + + writeFileSync( + path.join(fixtureRoot, "package.json"), + `${JSON.stringify(packageJson, null, 2)}\n`, + ); + copyFileSync(path.join(REPOSITORY_ROOT, ".gitignore"), path.join(fixtureRoot, ".gitignore")); + mkdirSync(path.join(fixtureRoot, "dist"), { recursive: true }); + cpSync( + path.join(REPOSITORY_ROOT, "dist", "managed-inference"), + path.join(fixtureRoot, "dist", "managed-inference"), + { recursive: true }, + ); + cpSync( + path.join(REPOSITORY_ROOT, "managed-inference"), + path.join(fixtureRoot, "managed-inference"), + { recursive: true }, + ); + return fixtureRoot; +} - it("loads and validates the compiled catalog through the packaged runtime", () => { - const catalogModule = require( - path.join(REPOSITORY_ROOT, "dist/lib/inference/serving/catalog.js"), - ) as { - loadManagedInferenceCatalog(): { - readonly presets: readonly unknown[]; - readonly recipes: readonly unknown[]; - readonly sourceFiles: readonly { readonly path: string }[]; - }; - }; - - const catalog = catalogModule.loadManagedInferenceCatalog(); - expect(catalog.presets.length).toBeGreaterThan(0); - expect(catalog.recipes.length).toBeGreaterThan(0); - expect(catalog.sourceFiles).toHaveLength(catalog.presets.length + catalog.recipes.length); - expect( - catalog.sourceFiles.every(({ path: sourcePath }) => - /^managed-inference\/(?:presets|recipes)\/[a-z0-9._-]+\.yaml$/u.test(sourcePath), - ), - ).toBe(true); +describe("compiled managed inference serving catalog", () => { + it("build output contains a schema-valid catalog with a source revision and matching digest (#8144)", () => { + const source = readFileSync( + path.join(REPOSITORY_ROOT, "dist", "managed-inference", "catalog.json"), + "utf8", + ); + parseCompiledServingCatalogJson(source, { + catalog: catalogSchema, + preset: presetSchema, + recipe: recipeSchema, + }); }); + + it("includes the compiled catalog in the npm package (#8144)", () => { + const fixtureRoot = createPackFixture(); + try { + const result = JSON.parse( + execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { + cwd: fixtureRoot, + encoding: "utf8", + }), + ) as Array<{ files: Array<{ path: string }> }>; + const files = result[0]?.files.map((file) => file.path) ?? []; + + expect(files).toContain("dist/managed-inference/catalog.json"); + expect(files).toContain("managed-inference/schemas/catalog.schema.json"); + expect(files).toContain("managed-inference/schemas/recipe.schema.json"); + expect(files).toContain("managed-inference/schemas/preset.schema.json"); + } finally { + rmSync(fixtureRoot, { recursive: true, force: true }); + } + }, 120_000); }); From bfe13858bf6f3debc8f6408604c6c8d7741fdf3e Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 22:13:46 -0700 Subject: [PATCH 21/27] test(inference): reconcile Station receipt coverage Signed-off-by: Aaron Erickson --- src/lib/inference/vllm-dual-station.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/inference/vllm-dual-station.test.ts b/src/lib/inference/vllm-dual-station.test.ts index 536520e4936..ba137c3a0f4 100644 --- a/src/lib/inference/vllm-dual-station.test.ts +++ b/src/lib/inference/vllm-dual-station.test.ts @@ -369,7 +369,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { return true; }); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: true, persisted: true, }); @@ -398,7 +398,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { } }); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "the managed dual-Station peer configuration is missing", }); @@ -415,7 +415,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { reason: "could not revalidate the managed pair: managed runtime identity changed", }); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "the managed dual-Station cleanup receipt is unsafe: could not revalidate the managed pair: managed runtime identity changed", @@ -431,7 +431,7 @@ describe("dual DGX Station running-runtime receipt adoption", () => { mocks.recoverRuntime.mockReturnValue({ kind: "ready", plan: recoveredPlan }); mocks.areContainersRunning.mockReturnValue(false); - await expect(persistConfiguredDualStationVllmRuntimeReceipt()).resolves.toEqual({ + await expect(persistConfiguredManagedVllmRuntimeReceipt()).resolves.toEqual({ ok: false, reason: "the managed dual-Station containers changed before cleanup ownership validation", }); From 8fc42624c218d524a4e78dc235f869e39eeed7c6 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 22:30:04 -0700 Subject: [PATCH 22/27] docs(inference): clarify managed runtime ownership Signed-off-by: Aaron Erickson --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 3 ++- docs/reference/host-files-and-state.mdx | 8 +++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 8bbd4f46e19..055e8ba6384 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -43,7 +43,8 @@ When uninstall confirms that no sibling gateways remain, it also removes the sha During full uninstall, a managed distributed-vLLM receipt makes NemoClaw first revalidate the recorded plan and every cluster node, GPU, container, and SSH peer identity. It then removes only the exact receipt-owned containers. The managed-cluster receipt is host-global under `~/.nemoclaw/`. -A legacy dual-DGX Station receipt uses the selected gateway state root. +Current dual-DGX Station receipts and copied SSH bindings are also host-global under `~/.nemoclaw/`. +Earlier releases can leave Station receipts and bindings under `~/.nemoclaw/gateways//`; NemoClaw discovers and validates those legacy locations in place. NemoClaw starts the remaining full-uninstall steps only after distributed runtime cleanup succeeds. For a host-global managed-cluster receipt, successful cleanup also retires every recorded temporary discovery claim. An interrupted transaction can leave `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/` without a durable runtime receipt. diff --git a/docs/reference/host-files-and-state.mdx b/docs/reference/host-files-and-state.mdx index 97729542a87..992b4558c49 100644 --- a/docs/reference/host-files-and-state.mdx +++ b/docs/reference/host-files-and-state.mdx @@ -18,14 +18,12 @@ Deep Agents-specific runtime state lives inside the sandbox under `/sandbox/.dee -Do not paste a legacy `credentials.json`, provider tokens, bot tokens, proxy tokens, or debug archives containing them into chat or issue comments. +Do not paste a legacy `credentials.json`, provider tokens, bot tokens, proxy tokens, `dual-station-vllm-api-key`, or debug archives containing them into chat or issue comments. Share redacted diagnostics only. ## Files -In the table, `` is `~/.nemoclaw/` for the default gateway or `~/.nemoclaw/gateways//` for a non-default gateway. - | Path | Purpose | Safe to delete | |---|---|---| | `~/.nemoclaw/config.json` | Host-level CLI configuration and defaults created by onboarding or config commands. | Only if you want NemoClaw to forget host defaults and rebuild them on the next setup. | @@ -38,8 +36,8 @@ In the table, `` is `~/.nemoclaw/` for the default gateway | `~/.nemoclaw/managed-cluster-vllm-runtime.json` | Owner-only host-global managed-cluster cleanup receipt. It contains no serving API key and binds the exact plan, ranked nodes, containers, and temporary discovery-claim identities. | No while the managed cluster exists. Full uninstall removes it after every exact container is removed. | | `~/.nemoclaw/managed-cluster-vllm-runtime.json.rank-.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach one recorded worker rank during full uninstall. | No while the managed cluster exists. Full uninstall removes every rank binding with the cleanup receipt after cluster cleanup succeeds. | | `~/.nemoclaw/managed-cluster-managed-serving.json..ssh-binding/` | Owner-only host-global temporary SSH host-key and Docker-command claim written for one peer after setup confirmation and repeated topology qualification. Each claim is distinct from its durable runtime binding and applies to every gateway on the host. | Only after confirming that no setup transaction is active. Without a durable runtime receipt, an orphaned claim makes a new managed-vLLM install and full uninstall fail closed without mutation. With the matching host-global managed-cluster receipt, full uninstall retires every recorded claim after it removes every exact container. If claim retirement fails, it preserves the receipt for a retry. Gateway-scoped uninstall preserves each claim. | -| `/dual-station-vllm-runtime.json` | Owner-only managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | -| `/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | +| `~/.nemoclaw/dual-station-vllm-runtime.json` | Owner-only host-global managed dual-Station cleanup receipt. It contains no serving API key and binds the peer, cluster, and GPU identities used to revalidate and remove both managed vLLM containers during full uninstall. | No while the managed pair exists. A full `$$nemoclaw uninstall` removes the receipt after both exact containers are removed; gateway-scoped uninstall preserves it. | +| `~/.nemoclaw/dual-station-vllm-runtime.json.ssh-binding/` | Owner-only host-global copied SSH host-key and Docker-command binding needed to reach the recorded worker during full uninstall. | No while the managed pair exists. Full uninstall removes it with the cleanup receipt after pair cleanup succeeds; gateway-scoped uninstall preserves it. | Earlier releases can store the dual-Station runtime receipt and its SSH-binding directory under `~/.nemoclaw/gateways//` when the managed pair was created from a non-default gateway port. The API key remains host-global at `~/.nemoclaw/dual-station-vllm-api-key`. From a010d7dc5e38ee2ae13b64359e214d7357cc3ab4 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 22:33:23 -0700 Subject: [PATCH 23/27] test(inference): remove stale compiled preset Signed-off-by: Aaron Erickson --- src/lib/inference/serving/resolver.test.ts | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 7d051fd1558..4d1f9ec65da 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -3,17 +3,8 @@ import { describe, expect, it } from "vitest"; import type { SystemReadinessReport } from "../../readiness/types.js"; -import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; -import type { - CompiledManagedInferenceCatalog, - ManagedInferencePresetRequirement, - ManagedInferenceReadinessSource, - ManagedInferenceResolverInput, - ManagedInferenceServingPreset, - ManagedInferenceServingRecipe, - ManagedInferenceTopologyQualification, -} from "./types.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { FIXTURE_MANAGED_CLUSTER_PRESET_ID, fixtureManagedClusterSelection, @@ -23,6 +14,15 @@ import { managedClusterTopologyOutputDigest, } from "./managed-cluster-topology.js"; import { resolveManagedInferenceServing } from "./resolver.js"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferencePresetRequirement, + ManagedInferenceReadinessSource, + ManagedInferenceResolverInput, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ManagedInferenceTopologyQualification, +} from "./types.js"; const NOW = new Date("2026-08-02T18:00:00.000Z"); const SOURCE_REVISION = "a".repeat(40); @@ -162,7 +162,6 @@ function catalogWithSecondProfile(options: { readonly secondRecipeId: string; } { const catalog = shippedCatalog(); - const firstCompiledPreset = shippedCompiledPreset(catalog); const firstCompiledRecipe = shippedCompiledRecipe(catalog); const firstPreset = shippedPreset(catalog); const firstRecipe = shippedRecipe(catalog); From e8506a1c4d631a22a3a606910f96d1fd484d9693 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 3 Aug 2026 23:27:36 -0700 Subject: [PATCH 24/27] fix(inference): reconcile managed catalog with main Signed-off-by: Aaron Erickson --- managed-inference/schemas/preset.schema.json | 137 ++++ managed-inference/schemas/recipe.schema.json | 737 +++++++++++++++++- src/lib/actions/uninstall/run-plan.ts | 300 ++++--- src/lib/inference/serving/adapter-registry.ts | 13 +- src/lib/inference/serving/catalog.ts | 244 +++++- src/lib/inference/serving/resolver.test.ts | 2 +- src/lib/inference/serving/resolver.ts | 1 + src/lib/inference/serving/types.ts | 149 +++- 8 files changed, 1435 insertions(+), 148 deletions(-) diff --git a/managed-inference/schemas/preset.schema.json b/managed-inference/schemas/preset.schema.json index e4e8e0e5877..9f939b6106f 100644 --- a/managed-inference/schemas/preset.schema.json +++ b/managed-inference/schemas/preset.schema.json @@ -57,6 +57,9 @@ { "$ref": "#/$defs/readinessStateRequirement" }, + { + "$ref": "#/$defs/readinessComparisonRequirement" + }, { "$ref": "#/$defs/factRequirement" }, @@ -335,6 +338,140 @@ } }, "additionalProperties": false + }, + "comparisonScalar": { + "oneOf": [ + { + "$ref": "#/$defs/comparisonString" + }, + { + "type": "number", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "boolean" + } + ] + }, + "comparisonString": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._+:-]{0,127}$", + "maxLength": 128 + }, + "version": { + "type": "string", + "pattern": "^[0-9]+(?:\\.[0-9]+){1,3}(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$", + "maxLength": 64 + }, + "readinessComparisonRequirement": { + "type": "object", + "required": [ + "readiness" + ], + "properties": { + "readiness": { + "type": "object", + "required": [ + "scope", + "kind", + "id", + "comparison" + ], + "properties": { + "scope": { + "enum": [ + "controller", + "everyNode" + ] + }, + "kind": { + "const": "observation" + }, + "id": { + "$ref": "#/$defs/stableId" + }, + "comparison": { + "oneOf": [ + { + "type": "object", + "required": [ + "operator", + "value" + ], + "properties": { + "operator": { + "const": "equals" + }, + "value": { + "$ref": "#/$defs/comparisonScalar" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "operator", + "values" + ], + "properties": { + "operator": { + "const": "one-of" + }, + "values": { + "type": "array", + "minItems": 1, + "maxItems": 16, + "uniqueItems": true, + "items": { + "$ref": "#/$defs/comparisonScalar" + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "operator", + "value" + ], + "properties": { + "operator": { + "const": "at-least" + }, + "value": { + "type": "number", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "operator", + "value" + ], + "properties": { + "operator": { + "const": "version-at-least" + }, + "value": { + "$ref": "#/$defs/version" + } + }, + "additionalProperties": false + } + ] + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false } }, "title": "NemoClaw managed inference serving preset" diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json index 69c964969b0..4925f05887c 100644 --- a/managed-inference/schemas/recipe.schema.json +++ b/managed-inference/schemas/recipe.schema.json @@ -90,8 +90,21 @@ "pattern": "^(?!\\.{1,2}(?:/|$))(?!.*\\/\\.{1,2}(?:/|$))[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$" }, "digest": { - "type": "string", - "pattern": "^sha256:[0-9a-f]{64}$" + "$ref": "#/$defs/sha256" + }, + "sizeBytes": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "format": { + "const": "gguf" + }, + "quantization": { + "$ref": "#/$defs/artifactLabel" + }, + "license": { + "$ref": "#/$defs/artifactLabel" } }, "additionalProperties": false @@ -105,8 +118,7 @@ "properties": { "image": { "type": "string", - "pattern": "^[a-z0-9.-]+(?::[0-9]+)?(?:/[a-z0-9._-]+)+@sha256:[0-9a-f]{64}$", - "maxLength": 1024 + "pattern": "^(?:[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]+)?/)?(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*@sha256:[0-9a-f]{64}$" }, "imageDownloadSizeBytes": { "$ref": "#/$defs/positiveSafeInteger" @@ -117,7 +129,10 @@ "maximum": 86400 }, "architecture": { - "$ref": "#/$defs/token" + "enum": [ + "amd64", + "arm64" + ] }, "networkMode": { "$ref": "#/$defs/token" @@ -213,6 +228,102 @@ "minLength": 1, "maxLength": 128 } + }, + "platforms": { + "type": "array", + "minItems": 2, + "maxItems": 2, + "uniqueItems": true, + "items": { + "enum": [ + "linux/amd64", + "linux/arm64" + ] + }, + "allOf": [ + { + "contains": { + "const": "linux/amd64" + } + }, + { + "contains": { + "const": "linux/arm64" + } + } + ] + }, + "containerRuntime": { + "const": "docker" + }, + "hosts": { + "const": 1 + }, + "cuda": { + "type": "object", + "required": [ + "baseImage", + "minimumDriverVersion" + ], + "properties": { + "baseImage": { + "$ref": "#/$defs/imageDigest" + }, + "minimumDriverVersion": { + "$ref": "#/$defs/version" + } + }, + "additionalProperties": false + }, + "gpu": { + "type": "object", + "required": [ + "vendor", + "count", + "offload", + "cpuFallback" + ], + "properties": { + "vendor": { + "const": "nvidia" + }, + "count": { + "const": 1 + }, + "offload": { + "const": "full" + }, + "cpuFallback": { + "const": "reject" + } + }, + "additionalProperties": false + }, + "resources": { + "type": "object", + "required": [ + "memoryBytes", + "writableStorageBytes", + "pidsLimit" + ], + "properties": { + "memoryBytes": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "writableStorageBytes": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "pidsLimit": { + "type": "integer", + "minimum": 1, + "maximum": 1048576 + } + }, + "additionalProperties": false } }, "additionalProperties": false @@ -225,10 +336,10 @@ ], "properties": { "materializerRef": { - "$ref": "#/$defs/stableId" + "$ref": "#/$defs/adapterId" }, "lifecycleRef": { - "$ref": "#/$defs/stableId" + "$ref": "#/$defs/adapterId" }, "topologyBinding": { "$ref": "#/$defs/bindingName" @@ -255,6 +366,9 @@ "type": "integer", "minimum": 1, "maximum": 65535 + }, + "receiptRef": { + "$ref": "#/$defs/adapterId" } }, "additionalProperties": false @@ -279,28 +393,73 @@ "properties": { "name": { "type": "string", - "pattern": "^--[a-z0-9]+(?:-[a-z0-9]+)*$", + "pattern": "^--[a-z0-9][a-z0-9-]*$", "maxLength": 128 }, "value": { - "oneOf": [ - { - "type": "string", - "maxLength": 16384 - }, - { - "type": "number", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "boolean" - } - ] + "$ref": "#/$defs/scalar" } }, "additionalProperties": false } + }, + "protocol": { + "const": "openai-completions" + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "chatTemplate": { + "$ref": "#/$defs/artifactLabel" + }, + "contextSize": { + "type": "integer", + "minimum": 1, + "maximum": 1048576 + }, + "slots": { + "type": "integer", + "minimum": 1, + "maximum": 1024 + }, + "idleSleepSeconds": { + "type": "integer", + "minimum": -1, + "maximum": 86400 + }, + "limits": { + "type": "object", + "required": [ + "maxRequestBodyBytes", + "maxPromptTokens", + "maxCompletionTokens", + "requestTimeoutSeconds" + ], + "properties": { + "maxRequestBodyBytes": { + "type": "integer", + "minimum": 1, + "maximum": 1073741824 + }, + "maxPromptTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1048576 + }, + "maxCompletionTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1048576 + }, + "requestTimeoutSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 86400 + } + }, + "additionalProperties": false } }, "additionalProperties": false @@ -319,12 +478,203 @@ }, "expectedModel": { "$ref": "#/$defs/stableId" + }, + "contractRef": { + "$ref": "#/$defs/adapterId" + }, + "probes": { + "type": "object", + "required": [ + "models", + "health", + "properties", + "metrics" + ], + "properties": { + "models": { + "const": true + }, + "health": { + "const": true + }, + "properties": { + "const": true + }, + "metrics": { + "const": true + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "providerId": { + "$ref": "#/$defs/backendId" + }, + "server": { + "type": "object", + "required": [ + "technology", + "source" + ], + "properties": { + "technology": { + "const": "llama.cpp" + }, + "source": { + "type": "object", + "required": [ + "repository", + "revision" + ], + "properties": { + "repository": { + "$ref": "#/$defs/repositoryId" + }, + "revision": { + "$ref": "#/$defs/sourceRevision" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "policy": { + "type": "object", + "required": [ + "egress", + "modelSource", + "modelDownloads" + ], + "properties": { + "egress": { + "const": "disabled" + }, + "modelSource": { + "const": "verified-local" + }, + "modelDownloads": { + "const": "disabled" + } + }, + "additionalProperties": false + }, + "surfaces": { + "type": "object", + "required": [ + "ui", + "slotInspection", + "router", + "mcpProxy", + "serverTools", + "agentMode", + "multimodalProjection" + ], + "properties": { + "ui": { + "const": "disabled" + }, + "slotInspection": { + "const": "disabled" + }, + "router": { + "const": "disabled" + }, + "mcpProxy": { + "const": "disabled" + }, + "serverTools": { + "const": "disabled" + }, + "agentMode": { + "const": "disabled" + }, + "multimodalProjection": { + "const": "disabled" + } + }, + "additionalProperties": false + }, + "capabilities": { + "type": "object", + "required": [ + "agents", + "protocols", + "streaming", + "toolCalls", + "structuredOutputs", + "parallelToolCalls", + "responsesApi", + "embeddings", + "reranking", + "multimodal" + ], + "properties": { + "agents": { + "type": "array", + "maxItems": 16, + "uniqueItems": true, + "items": { + "type": "object", + "required": [ + "id", + "qualificationRef" + ], + "properties": { + "id": { + "$ref": "#/$defs/nonPathStableId" + }, + "qualificationRef": { + "$ref": "#/$defs/stableId" + } + }, + "additionalProperties": false + } + }, + "protocols": { + "type": "array", + "minItems": 1, + "maxItems": 1, + "items": { + "const": "openai-completions" + } + }, + "streaming": { + "type": "boolean" + }, + "toolCalls": { + "type": "boolean" + }, + "structuredOutputs": { + "type": "boolean" + }, + "parallelToolCalls": { + "const": false + }, + "responsesApi": { + "const": false + }, + "embeddings": { + "const": false + }, + "reranking": { + "const": false + }, + "multimodal": { + "const": false } }, "additionalProperties": false } }, - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "$ref": "#/$defs/llamaCppRecipeSpec" + } + ] } }, "additionalProperties": false, @@ -506,6 +856,347 @@ } }, "additionalProperties": false + }, + "nonPathStableId": { + "type": "string", + "pattern": "^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$", + "maxLength": 160 + }, + "backendId": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{0,63}$" + }, + "repositoryId": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$", + "maxLength": 192 + }, + "sourceRevision": { + "type": "string", + "pattern": "^[0-9a-f]{40,64}$" + }, + "artifactLabel": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$", + "maxLength": 128 + }, + "version": { + "type": "string", + "pattern": "^[0-9]+(?:\\.[0-9]+){1,3}(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$", + "maxLength": 64 + }, + "imageDigest": { + "type": "string", + "pattern": "^(?:[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]+)?/)?(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*@sha256:[0-9a-f]{64}$" + }, + "adapterId": { + "type": "string", + "pattern": "^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+/v[1-9][0-9]*$", + "maxLength": 160 + }, + "sha256": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "scalar": { + "oneOf": [ + { + "type": "string", + "maxLength": 1024 + }, + { + "type": "number" + }, + { + "type": "boolean" + } + ] + }, + "llamaCppRecipeSpec": { + "if": { + "type": "object", + "anyOf": [ + { + "properties": { + "backend": { + "const": "install-llama-cpp" + } + }, + "required": [ + "backend" + ] + }, + { + "properties": { + "providerId": { + "const": "llama-cpp-local" + } + }, + "required": [ + "providerId" + ] + }, + { + "properties": { + "server": { + "type": "object", + "properties": { + "technology": { + "const": "llama.cpp" + } + }, + "required": [ + "technology" + ] + } + }, + "required": [ + "server" + ] + } + ] + }, + "then": { + "type": "object", + "required": [ + "providerId", + "server", + "model", + "runtime", + "execution", + "serve", + "readiness", + "policy", + "surfaces", + "capabilities" + ], + "properties": { + "backend": { + "const": "install-llama-cpp" + }, + "providerId": { + "const": "llama-cpp-local" + }, + "server": { + "type": "object", + "properties": { + "technology": { + "const": "llama.cpp" + } + }, + "required": [ + "technology" + ] + }, + "model": { + "type": "object", + "required": [ + "id", + "revision", + "servedName", + "files" + ], + "properties": { + "id": { + "$ref": "#/$defs/repositoryId" + }, + "revision": { + "$ref": "#/$defs/sourceRevision" + }, + "servedName": { + "$ref": "#/$defs/nonPathStableId" + }, + "files": { + "type": "array", + "minItems": 1, + "maxItems": 1, + "items": { + "type": "object", + "required": [ + "path", + "digest", + "sizeBytes", + "format", + "quantization", + "license" + ], + "properties": { + "path": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*\\.gguf$", + "maxLength": 255 + }, + "digest": {}, + "sizeBytes": {}, + "format": {}, + "quantization": {}, + "license": {} + } + } + } + } + }, + "runtime": { + "type": "object", + "required": [ + "image", + "platforms", + "containerRuntime", + "hosts", + "cuda", + "gpu", + "resources" + ], + "properties": { + "image": {}, + "platforms": {}, + "containerRuntime": {}, + "hosts": {}, + "cuda": {}, + "gpu": {}, + "resources": {} + }, + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "architecture": {} + }, + "required": [ + "architecture" + ] + }, + { + "type": "object", + "properties": { + "components": {} + }, + "required": [ + "components" + ] + } + ] + } + }, + "execution": { + "type": "object", + "required": [ + "receiptRef", + "materializerRef", + "lifecycleRef" + ], + "properties": { + "receiptRef": {}, + "materializerRef": {}, + "lifecycleRef": {} + } + }, + "serve": { + "type": "object", + "required": [ + "protocol", + "port", + "chatTemplate", + "contextSize", + "slots", + "idleSleepSeconds", + "limits" + ], + "properties": { + "protocol": {}, + "port": { + "const": 8081 + }, + "chatTemplate": {}, + "contextSize": {}, + "slots": { + "const": 1 + }, + "idleSleepSeconds": { + "const": -1 + }, + "limits": {} + }, + "not": { + "type": "object", + "properties": { + "arguments": {} + }, + "required": [ + "arguments" + ] + } + }, + "readiness": { + "type": "object", + "required": [ + "contractRef", + "timeoutSeconds", + "expectedModel", + "probes" + ], + "properties": { + "contractRef": {}, + "timeoutSeconds": {}, + "expectedModel": {}, + "probes": {} + } + }, + "policy": { + "type": "object" + }, + "surfaces": { + "type": "object" + }, + "capabilities": { + "type": "object" + } + } + }, + "else": { + "type": "object", + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "providerId": {} + }, + "required": [ + "providerId" + ] + }, + { + "type": "object", + "properties": { + "policy": {} + }, + "required": [ + "policy" + ] + }, + { + "type": "object", + "properties": { + "surfaces": {} + }, + "required": [ + "surfaces" + ] + }, + { + "type": "object", + "properties": { + "capabilities": {} + }, + "required": [ + "capabilities" + ] + } + ] + } + } } }, "title": "NemoClaw managed inference serving recipe" diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 8839e2acbf1..39c75135374 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -43,13 +43,16 @@ import { NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, } from "../../onboard/docker-driver-gateway-service"; -import { resolveGatewayName } from "../../onboard/gateway-binding"; +import { resolveGatewayName, resolveGatewayPortFromName } from "../../onboard/gateway-binding"; import { isExternallySupervised } from "../../onboard/gateway-ownership"; import { type GatewayTeardownAuthorityResolver, resolveGatewayTeardownAuthority, } from "../../onboard/gateway-teardown-authority"; -import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; +import { + type StopHostGatewayOptions, + stopHostGatewayProcesses, +} from "../../onboard/host-gateway-process"; import { isModelRouterCommandLineForPort } from "../../onboard/model-router-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; import { @@ -93,7 +96,9 @@ export interface UninstallRunDeps { platform?: NodeJS.Platform; readProcessArgv?: (pid: number) => readonly string[] | null; readLine?: () => string | null; + requireCompleteGatewayProcessCleanup?: boolean; resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver; + retainedGatewayPorts?: readonly number[]; rmSync?: typeof fs.rmSync; run?: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; runDocker?: (args: string[], options?: SpawnSyncOptions) => RunResult; @@ -102,6 +107,7 @@ export interface UninstallRunDeps { export interface UninstallRunOutcome { exitCode: number; + otherGatewayEnvironmentsRemain?: boolean; plan: UninstallPlan; } @@ -170,29 +176,37 @@ function pathEntryExists(target: string, runtime: Pick, liveGatewayNames: () => Set | null, -): SharedRegistrySiblingStatus { +): SharedRegistrySiblings { const sharedRoot = path.dirname(paths.managedSwapMarkerPath); const registryFile = path.join(sharedRoot, "sandboxes.json"); - if (!pathEntryExists(registryFile, runtime)) return "none"; + if (!pathEntryExists(registryFile, runtime)) return { ports: [], status: "none" }; try { const registry = readGatewayRegistryFile(path.dirname(sharedRoot), registryFile); - if (!registry) return "uncertain"; + if (!registry) return { ports: [], status: "uncertain" }; const siblingPorts = Object.values(registry.sandboxes) .map((entry) => registryEntryGatewayPort(entry)) .filter((port) => port !== GATEWAY_PORT); - if (siblingPorts.length === 0) return "none"; + if (siblingPorts.length === 0) return { ports: [], status: "none" }; // A non-current registry row is a live sibling only while OpenShell still // knows its gateway; a stale row must not report "present". const live = liveGatewayNames(); - if (live === null) return "present"; - return siblingPorts.some((port) => live.has(resolveGatewayName(port))) ? "present" : "none"; + if (live === null) return { ports: siblingPorts, status: "present" }; + const livePorts = siblingPorts.filter((port) => live.has(resolveGatewayName(port))); + return livePorts.length > 0 + ? { ports: livePorts, status: "present" } + : { ports: [], status: "none" }; } catch { // Unknown ownership must never permit host-global cleanup. - return "uncertain"; + return { ports: [], status: "uncertain" }; } } @@ -386,7 +400,9 @@ interface UninstallRuntime { platform: NodeJS.Platform; readProcessArgv: ((pid: number) => readonly string[] | null) | undefined; readLine: () => string | null; + requireCompleteGatewayProcessCleanup: boolean; resolveGatewayTeardownAuthority: GatewayTeardownAuthorityResolver; + retainedGatewayPorts: readonly number[]; rmSync: typeof fs.rmSync; run: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; runDocker: (args: string[], options?: SpawnSyncOptions) => RunResult; @@ -419,8 +435,10 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { platform: deps.platform ?? process.platform, readProcessArgv: deps.readProcessArgv, readLine: deps.readLine ?? readLineFromStdin, + requireCompleteGatewayProcessCleanup: deps.requireCompleteGatewayProcessCleanup ?? false, resolveGatewayTeardownAuthority: deps.resolveGatewayTeardownAuthority ?? resolveGatewayTeardownAuthority, + retainedGatewayPorts: deps.retainedGatewayPorts ?? [], rmSync: deps.rmSync ?? fs.rmSync, run: deps.run ?? defaultRun, runDocker: deps.runDocker ?? defaultRunDocker, @@ -1282,6 +1300,10 @@ function removeManagedDistributedVllmRuntime( ): boolean { const rootStatus = managedDistributedVllmStateRootStatus(paths, runtime); if (rootStatus !== "directory") return rootStatus === "absent"; + const apiKeyPath = path.join( + path.dirname(paths.managedSwapMarkerPath), + MANAGED_VLLM_API_KEY_FILE, + ); let state: ReturnType; try { state = findManagedDistributedVllmRuntimeReceipts({ @@ -1321,7 +1343,10 @@ function removeManagedDistributedVllmRuntime( ); return false; } - if (receipts.length === 0) return true; + if (receipts.length === 0) { + removePath(apiKeyPath, runtime); + return true; + } if (state.managedClusterPath && state.stationPaths.length > 0) { runtime.error( "Both managed cluster and dual-Station managed runtime receipts exist. NemoClaw refused ambiguous cleanup before making changes.", @@ -1339,10 +1364,7 @@ function removeManagedDistributedVllmRuntime( stdio: "inherit", }); if (result.status === 0) { - removePath( - path.join(path.dirname(paths.managedSwapMarkerPath), DUAL_STATION_VLLM_API_KEY_FILE), - runtime, - ); + removePath(apiKeyPath, runtime); return true; } runtime.error( @@ -1429,7 +1451,29 @@ function removeOllamaModels(options: UninstallRunOptions, runtime: UninstallRunt interface OtherGatewayInspection { otherGatewayEnvironmentsRemain: boolean; + otherGatewayPorts: readonly number[]; sharedRegistryMustBePreserved: boolean; + unidentifiedOtherGateways: boolean; +} + +const NO_OTHER_GATEWAY_ENVIRONMENTS: OtherGatewayInspection = { + otherGatewayEnvironmentsRemain: false, + otherGatewayPorts: [], + sharedRegistryMustBePreserved: false, + unidentifiedOtherGateways: false, +}; + +function otherGatewaysRemain( + ports: readonly number[], + sharedRegistryMustBePreserved = false, + unidentifiedOtherGateways = false, +): OtherGatewayInspection { + return { + otherGatewayEnvironmentsRemain: true, + otherGatewayPorts: [...new Set(ports)].sort((left, right) => left - right), + sharedRegistryMustBePreserved, + unidentifiedOtherGateways: unidentifiedOtherGateways || ports.length === 0, + }; } /** @@ -1460,9 +1504,30 @@ function collectLiveOpenShellGatewayNames(runtime: UninstallRuntime): Set name !== resolveGatewayName(GATEWAY_PORT))) { - return { - otherGatewayEnvironmentsRemain: true, - sharedRegistryMustBePreserved: false, - }; + const liveSiblingNames = [...liveNames].filter( + (name) => name !== resolveGatewayName(GATEWAY_PORT), + ); + if (liveSiblingNames.length > 0) { + const livePorts = liveSiblingNames + .map((name) => resolveGatewayPortFromName(name)) + .filter((port): port is number => port !== null); + return otherGatewaysRemain(livePorts, false, livePorts.length !== liveSiblingNames.length); } if (!selectedIsDefault && pathEntryExists(sharedRoot, runtime)) { @@ -1510,44 +1572,40 @@ function inspectOtherGatewayEnvironments( !(entry === "state" && dormantHostGlobalLifecycleState(sharedRoot)), ) ) { - return { - otherGatewayEnvironmentsRemain: true, - sharedRegistryMustBePreserved: false, - }; + return otherGatewaysRemain([DEFAULT_GATEWAY_PORT]); } } catch { // Do not remove a host-shared resource when we cannot prove that the // default-port environment is absent. - return { - otherGatewayEnvironmentsRemain: true, - sharedRegistryMustBePreserved: false, - }; + return otherGatewaysRemain([]); } } const gatewaysDir = path.join(sharedRoot, GATEWAYS_SUBDIR); if (!pathEntryExists(gatewaysDir, runtime)) { - return { - otherGatewayEnvironmentsRemain: false, - sharedRegistryMustBePreserved: false, - }; + return NO_OTHER_GATEWAY_ENVIRONMENTS; } try { const gatewaysStat = fs.lstatSync(gatewaysDir); if (gatewaysStat.isSymbolicLink() || !gatewaysStat.isDirectory()) { - return { - otherGatewayEnvironmentsRemain: true, - sharedRegistryMustBePreserved: false, - }; + return otherGatewaysRemain([]); } - const siblingExists = fs.readdirSync(gatewaysDir, { withFileTypes: true }).some((entry) => { + const siblingPorts: number[] = []; + let unidentified = false; + for (const entry of fs.readdirSync(gatewaysDir, { withFileTypes: true })) { const candidate = path.resolve(gatewaysDir, entry.name); - if (candidate === selectedRoot) return false; + if (candidate === selectedRoot) continue; // Never follow or dismiss a symlink or non-directory: a surprising shape // may hide live gateway state, so keep the conservative treatment. - if (entry.isSymbolicLink() || !entry.isDirectory()) return true; + if (entry.isSymbolicLink() || !entry.isDirectory()) { + unidentified = true; + continue; + } const port = Number(entry.name); - if (!Number.isInteger(port) || port < 1 || port > 65535) return true; + if (!Number.isInteger(port) || port < 1 || port > 65535) { + unidentified = true; + continue; + } // A directory named for the gateway being uninstalled is that gateway's // own state, never a sibling. Path identity alone does not catch it: for // the default port `selectedRoot` is the shared root, so @@ -1555,26 +1613,55 @@ function inspectOtherGatewayEnvironments( // selected gateway counts itself as a sibling, scoping cleanup to // preserve resources nothing else owns (#7987). Match on port identity // like every other sibling filter here and like `listGatewayStateRoots`. - if (port === GATEWAY_PORT) return false; + if (port === GATEWAY_PORT) continue; // A per-port directory whose gateway OpenShell no longer knows is an // orphan; dismiss it only when the live set positively lacks it. const live = liveGatewayNames(); - if (live === null) return true; - return live.has(resolveGatewayName(port)); - }); - return { - otherGatewayEnvironmentsRemain: siblingExists, - sharedRegistryMustBePreserved: false, - }; + if (live === null) { + unidentified = true; + continue; + } + if (live.has(resolveGatewayName(port))) siblingPorts.push(port); + } + return siblingPorts.length > 0 || unidentified + ? otherGatewaysRemain(siblingPorts, false, unidentified) + : NO_OTHER_GATEWAY_ENVIRONMENTS; } catch { // An unreadable sibling registry is still potentially live. - return { - otherGatewayEnvironmentsRemain: true, - sharedRegistryMustBePreserved: false, - }; + return otherGatewaysRemain([]); } } +/** + * Name the gateway-port environments this uninstall deliberately leaves alone. + * Without this the surviving gateway keeps its port bound with nothing to + * explain why, which reads as a leaked listener rather than a second + * environment (#7791). + */ +function reportOtherGatewayEnvironments( + inspection: OtherGatewayInspection, + runtime: UninstallRuntime, +): void { + if (!inspection.otherGatewayEnvironmentsRemain) return; + const branding = runtimeBranding(runtime); + runtime.log( + `Other ${branding.display} gateway-port environments remain on this host and are outside this uninstall:`, + ); + for (const port of inspection.otherGatewayPorts) { + runtime.log(` · gateway '${resolveGatewayName(port)}' on port ${String(port)}`); + } + if (inspection.unidentifiedOtherGateways) { + runtime.log(" · one or more gateway environments whose port could not be read"); + } + const [firstPort] = inspection.otherGatewayPorts; + if (firstPort !== undefined) { + runtime.log( + ` Remove one of them: NEMOCLAW_GATEWAY_PORT=${String(firstPort)} ${branding.cli} uninstall`, + ); + } + runtime.log(` Remove every gateway port: ${branding.cli} uninstall --all-gateway-ports`); +} + function removeManagedSwap( paths: UninstallPaths, runtime: UninstallRuntime, @@ -1725,15 +1812,8 @@ function executePlan( }); stopOrphanedOpenShell(runtime); if (!externallySupervised) { - stopHostGatewayProcesses( - { - run: runtime.run, - kill: runtime.kill, - env: runtime.env, - log: runtime.log, - warn: runtime.warn, - commandExists: runtime.commandExists, - }, + stopHostGatewayProcessesForUninstall( + runtime, GATEWAY_PORT === DEFAULT_GATEWAY_PORT ? { logNoProcesses: true } : { @@ -1777,24 +1857,14 @@ function executePlan( return { ok: false }; } if (scopedToSelectedGateway && !options.keepOpenShell && !externallySupervised) { - stopHostGatewayProcesses( - { - run: runtime.run, - kill: runtime.kill, - env: runtime.env, - log: runtime.log, - warn: runtime.warn, - commandExists: runtime.commandExists, - }, - { - gatewayBin: runtime.env.NEMOCLAW_OPENSHELL_GATEWAY_BIN, - logNoProcesses: true, - openShellGatewayName: options.gatewayName || resolveGatewayName(GATEWAY_PORT), - openShellGatewayPort: GATEWAY_PORT, - preserveRuntimeFilesOnNonMatching: true, - stateDir: paths.selectedGatewayLocalStateDir, - }, - ); + stopHostGatewayProcessesForUninstall(runtime, { + gatewayBin: runtime.env.NEMOCLAW_OPENSHELL_GATEWAY_BIN, + logNoProcesses: true, + openShellGatewayName: options.gatewayName || resolveGatewayName(GATEWAY_PORT), + openShellGatewayPort: GATEWAY_PORT, + preserveRuntimeFilesOnNonMatching: true, + stateDir: paths.selectedGatewayLocalStateDir, + }); } else if (scopedToSelectedGateway && externallySupervised) { runtime.log("Kept the externally supervised OpenShell gateway process running."); } @@ -1935,6 +2005,29 @@ function executePlan( return { ok }; } +class IncompleteHostGatewayCleanupError extends Error {} + +function stopHostGatewayProcessesForUninstall( + runtime: UninstallRuntime, + options: StopHostGatewayOptions, +): void { + const result = stopHostGatewayProcesses( + { + run: runtime.run, + kill: runtime.kill, + env: runtime.env, + log: runtime.log, + warn: runtime.warn, + commandExists: runtime.commandExists, + }, + options, + ); + if (!runtime.requireCompleteGatewayProcessCleanup) return; + if (result.failed.length === 0 && result.orphanScanComplete !== false) return; + runtime.error("Cannot continue uninstall because host gateway process cleanup did not complete."); + throw new IncompleteHostGatewayCleanupError(); +} + export function buildRunPlan( options: UninstallRunOptions, deps: UninstallRunDeps = {}, @@ -2006,6 +2099,7 @@ export function runUninstallPlan( } } printBanner(runtime, scopedToSelectedGateway, expectedGatewayName); + reportOtherGatewayEnvironments(gatewayInspection, runtime); if (!confirm(resolvedOptions, runtime, paths, scopedToSelectedGateway)) { return { exitCode: 0, plan }; } @@ -2023,6 +2117,7 @@ export function runUninstallPlan( runtime.warn( "A sibling gateway appeared during uninstall preparation; switching to gateway-scoped cleanup.", ); + reportOtherGatewayEnvironments(boundaryInspection, runtime); } } if (!runtime.commandExists("openshell")) { @@ -2030,17 +2125,22 @@ export function runUninstallPlan( return { exitCode: 1, plan }; } const preserveUnderStateDir = resolvePreserveSet(paths, resolvedOptions, runtime); - const { ok } = executePlan( - plan, - paths, - resolvedOptions, - runtime, - preserveUnderStateDir, - scopedToSelectedGateway, - gatewayInspection.sharedRegistryMustBePreserved, - sandboxNames, - externallySupervised, - ); + let ok = false; + try { + ({ ok } = executePlan( + plan, + paths, + resolvedOptions, + runtime, + preserveUnderStateDir, + scopedToSelectedGateway, + gatewayInspection.sharedRegistryMustBePreserved, + sandboxNames, + externallySupervised, + )); + } catch (error) { + if (!(error instanceof IncompleteHostGatewayCleanupError)) throw error; + } if (ok) { printBye(runtime); } else { @@ -2048,5 +2148,5 @@ export function runUninstallPlan( "Uninstall completed with errors. Some state may remain on disk; see warnings above.", ); } - return { exitCode: ok ? 0 : 1, plan }; + return { exitCode: ok ? 0 : 1, otherGatewayEnvironmentsRemain: scopedToSelectedGateway, plan }; } diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index cd1981c6358..61bf54d5787 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -507,8 +507,10 @@ const SERVING_READINESS_REGISTRY: ServingCatalogRegistries["readiness"] = new Ma export function getManagedInferenceServingCatalogRegistries(): ServingCatalogRegistries { return { + receipts: new Set(), materializers: new Set(MATERIALIZER_DESCRIPTORS.map(({ ref }) => ref)), lifecycles: new Set(LIFECYCLE_DESCRIPTORS.map(({ ref }) => ref)), + readinessContracts: new Set(), readiness: SERVING_READINESS_REGISTRY, facts: new Set(["cluster.nodeCount"]), topologyQualifications: new Map( @@ -520,7 +522,14 @@ export function getManagedInferenceServingCatalogRegistries(): ServingCatalogReg }, ]), ), - validateRecipe: (recipe: ServingRecipe) => - getManagedInferenceRecipeRegistrationError(recipe as ManagedInferenceServingRecipe), + validateRecipe: (recipe: ServingRecipe) => { + if ( + recipe.spec.execution.materializerRef !== MANAGED_CLUSTER_VLLM_MATERIALIZER_REF && + recipe.spec.execution.lifecycleRef !== MANAGED_CLUSTER_VLLM_LIFECYCLE_REF + ) { + return undefined; + } + return getManagedInferenceRecipeRegistrationError(recipe as ManagedInferenceServingRecipe); + }, }; } diff --git a/src/lib/inference/serving/catalog.ts b/src/lib/inference/serving/catalog.ts index 50dbe8b95cd..1ebcac0f811 100644 --- a/src/lib/inference/serving/catalog.ts +++ b/src/lib/inference/serving/catalog.ts @@ -16,12 +16,17 @@ import type { ServingCatalogSourceProvenance, ServingDefinitionKind, ServingPreset, + ServingReadinessComparison, + ServingReadinessObservationRole, + ServingReadinessRegistryEntry, + ServingReadinessRequirement, + ServingReadinessRegistryValue, ServingRecipe, } from "./types"; const API_VERSION = "nemoclaw.nvidia.com/managed-inference/v1" as const; const CATALOG_SCHEMA_VERSION = "1.0.0" as const; -const COMPILER_VERSION = "1.0.0" as const; +const COMPILER_VERSION = "1.1.0" as const; const READINESS_SCHEMA_REF = "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json" as const; const RECIPE_SCHEMA_ID = @@ -139,11 +144,51 @@ function definitionIdentity( return { kind, id }; } +type LlamaCppServingRecipe = Extract; + +function isLlamaCppServingRecipe(recipe: ServingRecipe): recipe is LlamaCppServingRecipe { + return recipe.spec.providerId === "llama-cpp-local"; +} + +function isReadinessRegistryEntry( + registered: ServingReadinessRegistryValue, +): registered is ServingReadinessRegistryEntry { + return typeof registered === "object" && registered !== null && "kind" in registered; +} + +function readinessKindMatches( + registered: ServingReadinessRegistryValue, + kind: ServingReadinessRequirement["readiness"]["kind"], +): boolean { + if (typeof registered === "string") return registered === kind; + if (isReadinessRegistryEntry(registered)) return registered.kind === kind; + return registered.has(kind); +} + +function readinessKindLabel(registered: ServingReadinessRegistryValue): string { + if (typeof registered === "string") return registered; + if (isReadinessRegistryEntry(registered)) return registered.kind; + return [...registered].join(" or "); +} + +function readinessDescriptor( + registered: ServingReadinessRegistryValue | undefined, + kind: ServingReadinessRequirement["readiness"]["kind"], +): ServingReadinessRegistryEntry | undefined { + if (registered === undefined || !readinessKindMatches(registered, kind)) return undefined; + return isReadinessRegistryEntry(registered) ? registered : { kind }; +} + function validateRecipeSemantics( recipe: ServingRecipe, registries: ServingCatalogRegistries, ): void { - const { materializerRef, lifecycleRef } = recipe.spec.execution; + const { receiptRef, materializerRef, lifecycleRef } = recipe.spec.execution; + if (receiptRef && !registries.receipts.has(receiptRef)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} references unknown receipt contract ${receiptRef}.`, + ); + } if (!registries.materializers.has(materializerRef)) { throw new ServingCatalogValidationError( `Recipe ${recipe.metadata.id} references unknown materializer ${materializerRef}.`, @@ -155,14 +200,23 @@ function validateRecipeSemantics( ); } - const argumentNames = new Set(); - for (const argument of recipe.spec.serve?.arguments ?? []) { - if (argumentNames.has(argument.name)) { - throw new ServingCatalogValidationError( - `Recipe ${recipe.metadata.id} repeats structured argument ${argument.name}.`, - ); + const readinessContractRef = recipe.spec.readiness?.contractRef; + if (readinessContractRef && !registries.readinessContracts.has(readinessContractRef)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} references unknown readiness contract ${readinessContractRef}.`, + ); + } + + if (!isLlamaCppServingRecipe(recipe)) { + const argumentNames = new Set(); + for (const argument of recipe.spec.serve?.arguments ?? []) { + if (argumentNames.has(argument.name)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} repeats structured argument ${argument.name}.`, + ); + } + argumentNames.add(argument.name); } - argumentNames.add(argument.name); } const modelFiles = new Set(); @@ -181,6 +235,35 @@ function validateRecipeSemantics( modelFiles.add(normalizedPath); } + if (isLlamaCppServingRecipe(recipe)) { + const servedName = recipe.spec.model.servedName; + if (recipe.spec.readiness.expectedModel !== servedName) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} readiness expectedModel must match model servedName.`, + ); + } + const { serve } = recipe.spec; + if (serve.limits.maxPromptTokens + serve.limits.maxCompletionTokens > serve.contextSize) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} request token limits exceed serve.contextSize.`, + ); + } + const agents = new Set(); + for (const agent of recipe.spec.capabilities.agents) { + if (agents.has(agent.id)) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} repeats agent capability ${agent.id}.`, + ); + } + agents.add(agent.id); + if (!readinessDescriptor(registries.readiness.get(agent.qualificationRef), "qualification")) { + throw new ServingCatalogValidationError( + `Recipe ${recipe.metadata.id} references unknown agent qualification ${agent.qualificationRef} for ${agent.id}.`, + ); + } + } + } + let registrationError: string | undefined; try { registrationError = registries.validateRecipe?.(recipe); @@ -192,11 +275,29 @@ function validateRecipeSemantics( } } +function comparisonValueType( + comparison: ServingReadinessComparison, +): "boolean" | "number" | "string" | "version" | "mixed" { + if (comparison.operator === "at-least") return "number"; + if (comparison.operator === "version-at-least") return "version"; + const values = comparison.operator === "one-of" ? comparison.values : [comparison.value]; + const types = new Set(values.map((value) => typeof value)); + if (types.size !== 1) return "mixed"; + const [type] = types; + return type === "boolean" || type === "number" || type === "string" ? type : "mixed"; +} + +function readinessRequirementKey(requirement: ServingReadinessRequirement): string { + const readiness = requirement.readiness; + return `${readiness.scope}:${readiness.kind}:${readiness.id}`; +} + function validatePresetRequirements( preset: ServingPreset, registries: ServingCatalogRegistries, ): void { const requirements = new Set(); + const requirementsByEntity = new Map(); for (const requirement of preset.spec.requirements?.all ?? []) { const requirementKey = canonicalServingCatalogJson(requirement); if (requirements.has(requirementKey)) { @@ -208,22 +309,37 @@ function validatePresetRequirements( requirements.add(requirementKey); if ("readiness" in requirement) { - const registeredKind = registries.readiness.get(requirement.readiness.id); - if (registeredKind === undefined) { + const { readiness } = requirement; + const registered = registries.readiness.get(readiness.id); + if (registered === undefined) { throw new ServingCatalogValidationError( - `Preset ${preset.metadata.id} references unknown readiness entity ${requirement.readiness.id}.`, + `Preset ${preset.metadata.id} references unknown readiness entity ${readiness.id}.`, ); } - const kindMatches = - registeredKind === requirement.readiness.kind || - (typeof registeredKind !== "string" && registeredKind.has(requirement.readiness.kind)); - if (!kindMatches) { - const registeredKinds = - typeof registeredKind === "string" ? registeredKind : [...registeredKind].join(" or "); + if (!readinessKindMatches(registered, readiness.kind)) { throw new ServingCatalogValidationError( - `Preset ${preset.metadata.id} uses ${requirement.readiness.id} as ${requirement.readiness.kind}, but the readiness registry declares ${registeredKinds}.`, + `Preset ${preset.metadata.id} uses ${readiness.id} as ${readiness.kind}, but the readiness registry declares ${readinessKindLabel(registered)}.`, ); } + + if ("comparison" in readiness) { + const descriptor = readinessDescriptor(registered, readiness.kind); + const comparisonType = comparisonValueType(readiness.comparison); + if (!descriptor?.valueType || comparisonType !== descriptor.valueType) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} compares ${readiness.id} as ${comparisonType}, but the readiness registry declares ${descriptor?.valueType ?? "no value type"}.`, + ); + } + } + + const key = readinessRequirementKey(requirement); + const previous = requirementsByEntity.get(key); + if (previous !== undefined && previous !== requirementKey) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} has contradictory readiness requirements for ${key}.`, + ); + } + requirementsByEntity.set(key, requirementKey); continue; } if ("fact" in requirement) { @@ -243,6 +359,83 @@ function validatePresetRequirements( } } +function canonicalReadinessComparison(comparison: ServingReadinessComparison): string { + if (comparison.operator !== "one-of") return canonicalServingCatalogJson(comparison); + return canonicalServingCatalogJson({ + ...comparison, + values: [...comparison.values].sort((left, right) => + compareCanonicalText(canonicalServingCatalogJson(left), canonicalServingCatalogJson(right)), + ), + }); +} + +function validateLlamaCppPreset( + recipe: LlamaCppServingRecipe, + preset: ServingPreset, + registries: ServingCatalogRegistries, +): void { + const expectedComparisons = new Map([ + ["operating-system", { operator: "equals", value: "linux" }], + [ + "architecture", + { + operator: "one-of", + values: recipe.spec.runtime.platforms.map((platform) => platform.slice("linux/".length)), + }, + ], + ["container-runtime", { operator: "equals", value: recipe.spec.runtime.containerRuntime }], + ["gpu-count", { operator: "at-least", value: recipe.spec.runtime.gpu.count }], + [ + "driver-version", + { operator: "version-at-least", value: recipe.spec.runtime.cuda.minimumDriverVersion }, + ], + ]); + const seenRoles = new Set(); + const qualified = new Set(); + + for (const requirement of preset.spec.requirements?.all ?? []) { + if (!("readiness" in requirement)) continue; + const { readiness } = requirement; + if (readiness.kind === "qualification" && readiness.status === "qualified") { + qualified.add(readiness.id); + } + const registered = registries.readiness.get(readiness.id); + if (registered === undefined || !isReadinessRegistryEntry(registered)) continue; + if (registered.kind !== "observation" || registered.role === undefined) continue; + const expected = expectedComparisons.get(registered.role); + if (!expected) continue; + if (seenRoles.has(registered.role)) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} repeats llama.cpp readiness role ${registered.role}.`, + ); + } + seenRoles.add(registered.role); + if ( + !("comparison" in readiness) || + canonicalReadinessComparison(readiness.comparison) !== canonicalReadinessComparison(expected) + ) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} must require ${registered.role} matching llama.cpp recipe ${recipe.metadata.id}.`, + ); + } + } + + for (const role of expectedComparisons.keys()) { + if (!seenRoles.has(role)) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} must require ${role} matching llama.cpp recipe ${recipe.metadata.id}.`, + ); + } + } + for (const agent of recipe.spec.capabilities.agents) { + if (!qualified.has(agent.qualificationRef)) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} must require qualified status for ${agent.qualificationRef} before selecting llama.cpp recipe ${recipe.metadata.id}.`, + ); + } + } +} + function validateBindings( preset: ServingPreset, recipe: ServingRecipe, @@ -297,6 +490,19 @@ function validateCatalogSemantics( `Preset ${preset.metadata.id} selects backend ${preset.spec.plan.backend}, but recipe ${recipe.metadata.id} uses ${recipe.spec.backend}.`, ); } + if (isLlamaCppServingRecipe(recipe)) { + if (preset.spec.selection !== "explicit-only") { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} must use explicit-only selection for llama.cpp recipe ${recipe.metadata.id}.`, + ); + } + if ((preset.spec.requirements?.all.length ?? 0) === 0) { + throw new ServingCatalogValidationError( + `Preset ${preset.metadata.id} must declare readiness requirements for llama.cpp recipe ${recipe.metadata.id}.`, + ); + } + validateLlamaCppPreset(recipe, preset, registries); + } validateBindings(preset, recipe, registries); const nodeCount = (preset.spec.requirements?.all ?? []).find( (requirement) => diff --git a/src/lib/inference/serving/resolver.test.ts b/src/lib/inference/serving/resolver.test.ts index 4d1f9ec65da..068512fcb9d 100644 --- a/src/lib/inference/serving/resolver.test.ts +++ b/src/lib/inference/serving/resolver.test.ts @@ -76,7 +76,7 @@ function catalogReadinessEntities(): Pick< ); return { observations: readinessRequirements.flatMap((readiness) => - readiness.kind === "observation" + readiness.kind === "observation" && "state" in readiness ? [ { id: readiness.id, diff --git a/src/lib/inference/serving/resolver.ts b/src/lib/inference/serving/resolver.ts index c44584c6eef..ff727c662e8 100644 --- a/src/lib/inference/serving/resolver.ts +++ b/src/lib/inference/serving/resolver.ts @@ -165,6 +165,7 @@ function readinessRequirementMatches( const matches = report.qualifications.filter(({ id }) => id === requirement.id); return matches.length === 1 && matches[0]!.status === requirement.status; } + if ("comparison" in requirement) return false; const collection = requirement.kind === "observation" ? report.observations : report.capabilities; const matches = collection.filter(({ id }) => id === requirement.id); diff --git a/src/lib/inference/serving/types.ts b/src/lib/inference/serving/types.ts index 17e70fc1e28..8e7cd2ee322 100644 --- a/src/lib/inference/serving/types.ts +++ b/src/lib/inference/serving/types.ts @@ -6,6 +6,13 @@ import type { SystemReadinessReport } from "../../readiness/types.js"; export type ServingDefinitionKind = "ServingRecipe" | "ServingPreset"; export type ServingSelectionPolicy = "automatic" | "explicit-only" | "disabled"; export type ReadinessEntityKind = "observation" | "capability" | "qualification"; +export type ReadinessValueType = "boolean" | "number" | "string" | "version"; +export type ServingReadinessObservationRole = + | "operating-system" + | "architecture" + | "container-runtime" + | "gpu-count" + | "driver-version"; export interface ServingMetadata { readonly id: string; @@ -107,12 +114,17 @@ export interface ManagedInferenceServingRecipe { }; } -export interface ServingRecipe { +interface ServingRecipeEnvelope { readonly apiVersion: "nemoclaw.nvidia.com/managed-inference/v1"; readonly kind: "ServingRecipe"; readonly metadata: ServingMetadata; +} + +interface GenericServingRecipe extends ServingRecipeEnvelope { readonly spec: { readonly backend: string; + readonly providerId?: never; + readonly server?: never; readonly bindings?: Readonly>; readonly model: { readonly id: string; @@ -128,6 +140,7 @@ export interface ServingRecipe { readonly components?: Readonly>; }; readonly execution: { + readonly receiptRef?: string; readonly materializerRef: string; readonly lifecycleRef: string; readonly topologyBinding?: string; @@ -143,12 +156,121 @@ export interface ServingRecipe { readonly arguments?: readonly ServingArgument[]; }; readonly readiness?: { + readonly contractRef?: string; readonly timeoutSeconds?: number; readonly expectedModel?: string; }; }; } +interface LlamaCppServingRecipe extends ServingRecipeEnvelope { + readonly spec: { + readonly backend: "install-llama-cpp"; + readonly providerId: "llama-cpp-local"; + readonly bindings?: never; + readonly server: { + readonly technology: "llama.cpp"; + readonly source: { readonly repository: string; readonly revision: string }; + }; + readonly model: { + readonly id: string; + readonly revision: string; + readonly servedName: string; + readonly files: readonly { + readonly path: string; + readonly digest: string; + readonly sizeBytes: number; + readonly format: "gguf"; + readonly quantization: string; + readonly license: string; + }[]; + }; + readonly runtime: { + readonly image: string; + readonly platforms: readonly ("linux/amd64" | "linux/arm64")[]; + readonly containerRuntime: "docker"; + readonly hosts: 1; + readonly cuda: { readonly baseImage: string; readonly minimumDriverVersion: string }; + readonly gpu: { + readonly vendor: "nvidia"; + readonly count: 1; + readonly offload: "full"; + readonly cpuFallback: "reject"; + }; + readonly resources: { + readonly memoryBytes: number; + readonly writableStorageBytes: number; + readonly pidsLimit: number; + }; + }; + readonly execution: { + readonly receiptRef: string; + readonly materializerRef: string; + readonly lifecycleRef: string; + readonly nodeCount?: never; + }; + readonly serve: { + readonly protocol: "openai-completions"; + readonly port: 8081; + readonly chatTemplate: string; + readonly contextSize: number; + readonly slots: 1; + readonly idleSleepSeconds: -1; + readonly limits: { + readonly maxRequestBodyBytes: number; + readonly maxPromptTokens: number; + readonly maxCompletionTokens: number; + readonly requestTimeoutSeconds: number; + }; + }; + readonly readiness: { + readonly contractRef: string; + readonly timeoutSeconds: number; + readonly expectedModel: string; + readonly probes: { + readonly models: true; + readonly health: true; + readonly properties: true; + readonly metrics: true; + }; + }; + readonly policy: { + readonly egress: "disabled"; + readonly modelSource: "verified-local"; + readonly modelDownloads: "disabled"; + }; + readonly surfaces: { + readonly ui: "disabled"; + readonly slotInspection: "disabled"; + readonly router: "disabled"; + readonly mcpProxy: "disabled"; + readonly serverTools: "disabled"; + readonly agentMode: "disabled"; + readonly multimodalProjection: "disabled"; + }; + readonly capabilities: { + readonly agents: readonly { readonly id: string; readonly qualificationRef: string }[]; + readonly protocols: readonly ["openai-completions"]; + readonly streaming: boolean; + readonly toolCalls: boolean; + readonly structuredOutputs: boolean; + readonly parallelToolCalls: false; + readonly responsesApi: false; + readonly embeddings: false; + readonly reranking: false; + readonly multimodal: false; + }; + }; +} + +export type ServingRecipe = GenericServingRecipe | LlamaCppServingRecipe; + +export type ServingReadinessComparison = + | { readonly operator: "equals"; readonly value: string | number | boolean } + | { readonly operator: "one-of"; readonly values: readonly (string | number | boolean)[] } + | { readonly operator: "at-least"; readonly value: number } + | { readonly operator: "version-at-least"; readonly value: string }; + export type ServingReadinessRequirement = | { readonly readiness: { @@ -165,6 +287,14 @@ export type ServingReadinessRequirement = readonly id: string; readonly state: string; }; + } + | { + readonly readiness: { + readonly scope: "controller" | "everyNode" | "anyNode"; + readonly kind: "observation"; + readonly id: string; + readonly comparison: ServingReadinessComparison; + }; }; export type ServingFactValue = string | number | boolean | readonly (string | number | boolean)[]; @@ -238,7 +368,7 @@ export interface ServingCatalogSourceProvenance { export interface CompiledServingCatalogPayload { readonly schemaVersion: "1.0.0"; - readonly compilerVersion: "1.0.0"; + readonly compilerVersion: "1.1.0"; readonly sourceRevision: string; readonly readinessSchemaRef: "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json"; readonly recipes: readonly ServingRecipe[]; @@ -266,10 +396,23 @@ export interface ServingTopologyRegistryEntry { readonly outputSchema: string; } +export interface ServingReadinessRegistryEntry { + readonly kind: ReadinessEntityKind; + readonly valueType?: ReadinessValueType; + readonly role?: ServingReadinessObservationRole; +} + +export type ServingReadinessRegistryValue = + | ReadinessEntityKind + | ReadonlySet + | ServingReadinessRegistryEntry; + export interface ServingCatalogRegistries { + readonly receipts: ReadonlySet; readonly materializers: ReadonlySet; readonly lifecycles: ReadonlySet; - readonly readiness: ReadonlyMap>; + readonly readinessContracts: ReadonlySet; + readonly readiness: ReadonlyMap; readonly facts?: ReadonlySet; readonly topologyQualifications?: ReadonlyMap; readonly validateRecipe?: (recipe: ServingRecipe) => string | undefined; From bcc28f872cb7a51f185bf1e0f8cbf9b230e30b65 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 4 Aug 2026 00:10:22 -0700 Subject: [PATCH 25/27] fix(inference): pin managed model preparation code Signed-off-by: Aaron Erickson --- .../set-up-vllm-on-two-dgx-sparks.mdx | 2 + ....deepseek-v4-flash-0731.spark-dual.v1.yaml | 2 +- managed-inference/schemas/recipe.schema.json | 4 ++ src/lib/inference/serving/adapter-registry.ts | 19 ++++++---- .../serving/managed-cluster-executor.test.ts | 5 +++ .../serving/managed-cluster-executor.ts | 20 +++++++++- .../managed-cluster-materialize.test.ts | 17 +++++---- .../managed-cluster-preparation.test.ts | 37 +++++++++++++++++-- .../serving/managed-cluster-preparation.ts | 18 ++++++++- src/lib/inference/serving/types.ts | 1 + ...managed-inference-catalog-compiler.test.ts | 12 +++++- 11 files changed, 114 insertions(+), 23 deletions(-) diff --git a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx index b4a41c5d905..53848323a01 100644 --- a/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx +++ b/docs/inference/set-up-vllm-on-two-dgx-sparks.mdx @@ -95,6 +95,8 @@ Apply network controls before you start the distributed containers. The pinned image runs as root in both containers. Each container receives all host GPUs, `/dev/infiniband`, Docker host networking, host inter-process communication, `64 GB` of shared memory, and unlimited locked memory. The launch does not use a read-only root filesystem, drop Linux capabilities, or set `no-new-privileges`. +The serving command does not enable vLLM's `--trust-remote-code` switch. +Before it copies the pinned snapshot's required encoder module into the runtime package, it verifies that file against the recipe's exact SHA-256 digest. The head binds HTTP port `8000` only to the qualified primary rail address. vLLM applies bearer API key authentication to its authenticated API routes, including the inventory and chat routes that NemoClaw verifies. The API key does not authenticate every endpoint on port `8000`. diff --git a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml index eb76b403e71..a73d1e6bc28 100644 --- a/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml +++ b/managed-inference/recipes/vllm.deepseek-v4-flash-0731.spark-dual.v1.yaml @@ -29,6 +29,7 @@ spec: ref: snapshot-copy-and-exact-text-replacement/v1 snapshotCopy: sourcePath: encoding/encoding_dsv4.py + digest: sha256:abc0d26120250dda0ae077dc64aa28836026e61e970854aaeb792445e6a0dde6 targetPath: /usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4_encoding.py exactTextReplacement: targetPath: /usr/local/lib/python3.12/dist-packages/vllm/tokenizers/deepseek_v4.py @@ -113,7 +114,6 @@ spec: arguments: - name: --port value: 8000 - - name: --trust-remote-code - name: --kv-cache-dtype value: nvfp4_ds_mla - name: --block-size diff --git a/managed-inference/schemas/recipe.schema.json b/managed-inference/schemas/recipe.schema.json index 4925f05887c..1cf5f6dd5b2 100644 --- a/managed-inference/schemas/recipe.schema.json +++ b/managed-inference/schemas/recipe.schema.json @@ -777,12 +777,16 @@ "type": "object", "required": [ "sourcePath", + "digest", "targetPath" ], "properties": { "sourcePath": { "$ref": "#/$defs/relativePath" }, + "digest": { + "$ref": "#/$defs/sha256" + }, "targetPath": { "$ref": "#/$defs/absolutePath" } diff --git a/src/lib/inference/serving/adapter-registry.ts b/src/lib/inference/serving/adapter-registry.ts index 61bf54d5787..910011bf69f 100644 --- a/src/lib/inference/serving/adapter-registry.ts +++ b/src/lib/inference/serving/adapter-registry.ts @@ -1,18 +1,18 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { - ReadinessEntityKind, - ServingCatalogRegistries, - ServingRecipe, - ManagedInferenceServingRecipe, - ManagedInferenceTopologyQualification, -} from "./types.js"; import { getManagedClusterTopologyArtifactError, MANAGED_CLUSTER_TOPOLOGY_ID, MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, } from "./managed-cluster-topology.js"; +import type { + ManagedInferenceServingRecipe, + ManagedInferenceTopologyQualification, + ReadinessEntityKind, + ServingCatalogRegistries, + ServingRecipe, +} from "./types.js"; export const MANAGED_CLUSTER_VLLM_MATERIALIZER_REF = "vllm.managed-cluster/v1" as const; export const MANAGED_CLUSTER_VLLM_LIFECYCLE_REF = "vllm.managed-cluster.lifecycle/v1" as const; @@ -68,6 +68,7 @@ const MANAGED_CLUSTER_TOPOLOGY_OUTPUT_SCHEMA = "nemoclaw.nvidia.com/managed-cluster-topology/v1" as const; const MANAGED_CLUSTER_PLAN_SCHEMA = "nemoclaw.nvidia.com/managed-cluster-vllm-plan/v1" as const; const LOWERCASE_STABLE_ID = /^[a-z0-9][a-z0-9._/-]{0,159}$/u; +const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/u; const MANAGED_CLUSTER_MATERIALIZER_OWNED_ENVIRONMENT = new Set([ "GLOO_SOCKET_IFNAME", "HEADLESS", @@ -249,6 +250,7 @@ interface SnapshotPreparationInput { readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; readonly snapshotCopy: { readonly sourcePath: string; + readonly digest: string; readonly targetPath: string; }; readonly exactTextReplacement: { @@ -320,8 +322,9 @@ function validateSnapshotPreparationRecipe( } if ( !preparation.snapshotCopy || - !hasExactKeys(preparation.snapshotCopy, ["sourcePath", "targetPath"]) || + !hasExactKeys(preparation.snapshotCopy, ["digest", "sourcePath", "targetPath"]) || !safeRelativeSnapshotPath(preparation.snapshotCopy.sourcePath) || + !SHA256_DIGEST.test(preparation.snapshotCopy.digest) || !safeAbsoluteContainerPath(preparation.snapshotCopy.targetPath) ) { return "snapshot preparation copy paths are invalid"; diff --git a/src/lib/inference/serving/managed-cluster-executor.test.ts b/src/lib/inference/serving/managed-cluster-executor.test.ts index f45b5c13dd8..3c9e7580c49 100644 --- a/src/lib/inference/serving/managed-cluster-executor.test.ts +++ b/src/lib/inference/serving/managed-cluster-executor.test.ts @@ -221,6 +221,11 @@ describe("managed-cluster vLLM executor", () => { { ref: typeof NO_PREPARATION_REF } >; expect(command).toContain(boundedPreparation.snapshotCopy.targetPath); + expect(command).toContain(boundedPreparation.snapshotCopy.digest); + expect(command).toContain("snapshot copy source digest mismatch"); + expect(command.indexOf("snapshot copy source digest mismatch")).toBeLessThan( + command.indexOf("install -m 0644 --"), + ); expect(command).toContain("preparation source text did not match exactly once"); expect(command).not.toContain("--api-key"); expect(command).not.toContain("$VLLM_API_KEY"); diff --git a/src/lib/inference/serving/managed-cluster-executor.ts b/src/lib/inference/serving/managed-cluster-executor.ts index 7b19d31c6f1..bb845134016 100644 --- a/src/lib/inference/serving/managed-cluster-executor.ts +++ b/src/lib/inference/serving/managed-cluster-executor.ts @@ -20,12 +20,11 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; +import { managedInferenceDigest, managedInferenceHexDigest } from "./catalog-integrity.js"; import { getManagedInferenceCompiledPreset, getManagedInferenceCompiledRecipe, } from "./catalog-loader.js"; -import { managedInferenceDigest, managedInferenceHexDigest } from "./catalog-integrity.js"; -import type { ManagedInferenceServingRecipe } from "./types.js"; import { isRelatedManagedVllmContainer, type ManagedClusterApiProbeRequest, @@ -63,6 +62,7 @@ import { MANAGED_CLUSTER_TOPOLOGY_ID, MANAGED_CLUSTER_TOPOLOGY_SCHEMA_VERSION, } from "./managed-cluster-topology.js"; +import type { ManagedInferenceServingRecipe } from "./types.js"; const API_KEY_PATTERN = /^[a-f0-9]{64}$/; const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/; @@ -111,6 +111,15 @@ if content.count(existing) != 1: target.write_text(content.replace(existing, replacement), encoding="utf-8") `.trim(); +const VERIFY_FILE_SHA256_SCRIPT = String.raw` +import hashlib, pathlib, sys +target = pathlib.Path(sys.argv[1]) +expected = sys.argv[2] +actual = "sha256:" + hashlib.sha256(target.read_bytes()).hexdigest() +if actual != expected: + raise SystemExit("snapshot copy source digest mismatch") +`.trim(); + export interface ManagedClusterExecutorStageTarget { readonly nodeId: string; readonly dockerEnv: Readonly>; @@ -466,6 +475,13 @@ function preparationCommand(rolePlan: ManagedClusterVllmRolePlan): string { if (preparation.ref === SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF) { command.push( `test -f ${shellQuote(preparation.snapshotCopy.sourcePath)}`, + [ + "python3", + "-c", + shellQuote(VERIFY_FILE_SHA256_SCRIPT), + shellQuote(preparation.snapshotCopy.sourcePath), + shellQuote(preparation.snapshotCopy.digest), + ].join(" "), `install -m 0644 -- ${shellQuote(preparation.snapshotCopy.sourcePath)} ${shellQuote(preparation.snapshotCopy.targetPath)}`, [ "python3", diff --git a/src/lib/inference/serving/managed-cluster-materialize.test.ts b/src/lib/inference/serving/managed-cluster-materialize.test.ts index 77c77991130..8e4c81b9ec2 100644 --- a/src/lib/inference/serving/managed-cluster-materialize.test.ts +++ b/src/lib/inference/serving/managed-cluster-materialize.test.ts @@ -7,14 +7,8 @@ import { NO_PREPARATION_REF, SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, } from "./adapter-registry.js"; -import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { managedInferenceDigest } from "./catalog-integrity.js"; -import type { - CompiledManagedInferenceCatalog, - ManagedInferenceServingPreset, - ManagedInferenceServingRecipe, - ResolvedManagedInferenceSelection, -} from "./types.js"; +import { loadManagedInferenceCatalog } from "./catalog-loader.js"; import { fixtureManagedClusterSelection } from "./managed-cluster-fixture.test-support.js"; import { MANAGED_CLUSTER_PRESET_LABEL, @@ -26,6 +20,12 @@ import { managedClusterTopologyOutputDigest, managedClusterTopologySubjectDigest, } from "./managed-cluster-topology.js"; +import type { + CompiledManagedInferenceCatalog, + ManagedInferenceServingPreset, + ManagedInferenceServingRecipe, + ResolvedManagedInferenceSelection, +} from "./types.js"; interface SyntheticProfile { readonly catalog: CompiledManagedInferenceCatalog; @@ -134,6 +134,7 @@ function syntheticSecondProfile( ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: "assets/synthetic_tokenizer.py", + digest: `sha256:${"4".repeat(64)}`, targetPath: "/opt/synthetic-vllm/tokenizers/copied.py", }, exactTextReplacement: { @@ -413,6 +414,7 @@ describe("managed-cluster vLLM materializer", () => { modelRevision: selection.recipe.spec.model.revision, modelDownloadSizeBytes: selection.recipe.spec.model.downloadSizeBytes, snapshotCopy: { + digest: boundedConfigured.snapshotCopy.digest, targetPath: boundedConfigured.snapshotCopy.targetPath, }, exactTextReplacement: boundedConfigured.exactTextReplacement, @@ -457,6 +459,7 @@ describe("managed-cluster vLLM materializer", () => { sourcePath: expect.stringContaining( "/models/cache/hub/models--example-org--Synthetic-Model/", ), + digest: `sha256:${"4".repeat(64)}`, targetPath: "/opt/synthetic-vllm/tokenizers/copied.py", }, exactTextReplacement: { diff --git a/src/lib/inference/serving/managed-cluster-preparation.test.ts b/src/lib/inference/serving/managed-cluster-preparation.test.ts index 7edbc6cb530..717cddbf4b9 100644 --- a/src/lib/inference/serving/managed-cluster-preparation.test.ts +++ b/src/lib/inference/serving/managed-cluster-preparation.test.ts @@ -40,6 +40,7 @@ describe("managed cluster vLLM preparation materializer", () => { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: "artifacts/tokenizer.py", + digest: `sha256:${"4".repeat(64)}`, targetPath: "/opt/alternate-vllm/tokenizers/model.py", }, exactTextReplacement: { @@ -58,6 +59,7 @@ describe("managed cluster vLLM preparation materializer", () => { modelDownloadSizeBytes: MODEL.downloadSizeBytes, snapshotCopy: { sourcePath: `/models/alternate-cache/hub/models--example-org--Synthetic-Model/snapshots/${MODEL.revision}/artifacts/tokenizer.py`, + digest: `sha256:${"4".repeat(64)}`, targetPath: "/opt/alternate-vllm/tokenizers/model.py", }, exactTextReplacement: { @@ -75,7 +77,11 @@ describe("managed cluster vLLM preparation materializer", () => { error: /snapshot copy source path must be a normalized relative POSIX path/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, - snapshotCopy: { sourcePath: "../escape.py", targetPath: "/opt/vllm/copied.py" }, + snapshotCopy: { + sourcePath: "../escape.py", + digest: `sha256:${"4".repeat(64)}`, + targetPath: "/opt/vllm/copied.py", + }, exactTextReplacement: { targetPath: "/opt/vllm/reasoning.py", expectedText: "before", @@ -88,7 +94,28 @@ describe("managed cluster vLLM preparation materializer", () => { error: /snapshot copy target path must be a normalized absolute container path/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, - snapshotCopy: { sourcePath: "safe.py", targetPath: "relative/copied.py" }, + snapshotCopy: { + sourcePath: "safe.py", + digest: `sha256:${"4".repeat(64)}`, + targetPath: "relative/copied.py", + }, + exactTextReplacement: { + targetPath: "/opt/vllm/reasoning.py", + expectedText: "before", + replacementText: "after", + }, + }, + }, + { + label: "invalid snapshot digest", + error: /snapshot copy digest must be an exact SHA-256 digest/u, + preparation: { + ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, + snapshotCopy: { + sourcePath: "safe.py", + digest: "sha256:not-a-digest", + targetPath: "/opt/vllm/copied.py", + }, exactTextReplacement: { targetPath: "/opt/vllm/reasoning.py", expectedText: "before", @@ -101,7 +128,11 @@ describe("managed cluster vLLM preparation materializer", () => { error: /exact-text replacement must change the matched text/u, preparation: { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, - snapshotCopy: { sourcePath: "safe.py", targetPath: "/opt/vllm/copied.py" }, + snapshotCopy: { + sourcePath: "safe.py", + digest: `sha256:${"4".repeat(64)}`, + targetPath: "/opt/vllm/copied.py", + }, exactTextReplacement: { targetPath: "/opt/vllm/reasoning.py", expectedText: "same", diff --git a/src/lib/inference/serving/managed-cluster-preparation.ts b/src/lib/inference/serving/managed-cluster-preparation.ts index 0d7418f78ce..a416031c81f 100644 --- a/src/lib/inference/serving/managed-cluster-preparation.ts +++ b/src/lib/inference/serving/managed-cluster-preparation.ts @@ -10,6 +10,7 @@ import { const MODEL_ID = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/u; const MODEL_REVISION = /^[0-9a-f]{40,64}$/u; +const SHA256_DIGEST = /^sha256:[0-9a-f]{64}$/u; const MAX_PATH_BYTES = 4_096; const MAX_REPLACEMENT_BYTES = 64 * 1_024; @@ -20,6 +21,8 @@ export type ManagedClusterVllmPreparationRecipe = readonly snapshotCopy: { /** Normalized path relative to the immutable model snapshot. */ readonly sourcePath: string; + /** Digest required before model-snapshot code can enter the runtime package. */ + readonly digest: string; /** Normalized absolute destination inside the pinned vLLM image. */ readonly targetPath: string; }; @@ -44,6 +47,7 @@ export type ManagedClusterVllmPreparationPlan = readonly ref: typeof SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF; readonly snapshotCopy: { readonly sourcePath: string; + readonly digest: string; readonly targetPath: string; }; readonly exactTextReplacement: { @@ -126,7 +130,11 @@ function preparationRecipe(value: unknown): ManagedClusterVllmPreparationRecipe throw new Error(`unsupported model preparation ${String(value.ref)}`); } if (!isRecord(value.snapshotCopy)) throw new Error("snapshot copy preparation is invalid"); - exactKeys(value.snapshotCopy, ["sourcePath", "targetPath"], "snapshot copy preparation"); + exactKeys( + value.snapshotCopy, + ["digest", "sourcePath", "targetPath"], + "snapshot copy preparation", + ); if (!isRecord(value.exactTextReplacement)) { throw new Error("exact-text replacement preparation is invalid"); } @@ -146,10 +154,17 @@ function preparationRecipe(value: unknown): ManagedClusterVllmPreparationRecipe if (expectedText === replacementText) { throw new Error("exact-text replacement must change the matched text"); } + if ( + typeof value.snapshotCopy.digest !== "string" || + !SHA256_DIGEST.test(value.snapshotCopy.digest) + ) { + throw new Error("snapshot copy digest must be an exact SHA-256 digest"); + } return { ref: SNAPSHOT_COPY_AND_EXACT_TEXT_REPLACEMENT_PREPARATION_REF, snapshotCopy: { sourcePath: snapshotRelativePath(value.snapshotCopy.sourcePath), + digest: value.snapshotCopy.digest, targetPath: containerPath(value.snapshotCopy.targetPath, "snapshot copy target path"), }, exactTextReplacement: { @@ -193,6 +208,7 @@ export function materializeManagedClusterVllmPreparation( ref: preparation.ref, snapshotCopy: { sourcePath: `${snapshotRoot}/${preparation.snapshotCopy.sourcePath}`, + digest: preparation.snapshotCopy.digest, targetPath: preparation.snapshotCopy.targetPath, }, exactTextReplacement: preparation.exactTextReplacement, diff --git a/src/lib/inference/serving/types.ts b/src/lib/inference/serving/types.ts index 8e7cd2ee322..d666260fb3b 100644 --- a/src/lib/inference/serving/types.ts +++ b/src/lib/inference/serving/types.ts @@ -37,6 +37,7 @@ export type ServingModelPreparation = readonly ref: "snapshot-copy-and-exact-text-replacement/v1"; readonly snapshotCopy: { readonly sourcePath: string; + readonly digest: string; readonly targetPath: string; }; readonly exactTextReplacement: { diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index f3804669628..42d9a3d31c2 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { readFileSync, readdirSync } from "node:fs"; +import { readdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -82,6 +82,16 @@ describe("managed inference YAML profile contract", () => { expect(catalog.presets.some(({ metadata }) => metadata.id === syntheticPresetId)).toBe(true); }); + it("does not enable arbitrary remote model code in shipped managed recipes (#8129)", () => { + const unsafeRecipes = compile(catalogSources()) + .recipes.filter((recipe) => + recipe.spec.serve?.arguments?.some(({ name }) => name === "--trust-remote-code"), + ) + .map(({ metadata }) => metadata.id); + + expect(unsafeRecipes).toEqual([]); + }); + it("keeps shipped profile identities out of production TypeScript (#8129)", () => { const servingRoot = path.join(REPOSITORY_ROOT, "src", "lib", "inference", "serving"); const productionSources = readdirSync(servingRoot) From 993486541cdccd79c081991c971259b1de7ce587 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 4 Aug 2026 00:15:18 -0700 Subject: [PATCH 26/27] test(inference): narrow managed recipe safety check Signed-off-by: Aaron Erickson --- test/managed-inference-catalog-compiler.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/managed-inference-catalog-compiler.test.ts b/test/managed-inference-catalog-compiler.test.ts index 42d9a3d31c2..907c002041a 100644 --- a/test/managed-inference-catalog-compiler.test.ts +++ b/test/managed-inference-catalog-compiler.test.ts @@ -84,9 +84,14 @@ describe("managed inference YAML profile contract", () => { it("does not enable arbitrary remote model code in shipped managed recipes (#8129)", () => { const unsafeRecipes = compile(catalogSources()) - .recipes.filter((recipe) => - recipe.spec.serve?.arguments?.some(({ name }) => name === "--trust-remote-code"), - ) + .recipes.filter((recipe) => { + const { serve } = recipe.spec; + return ( + serve !== undefined && + "arguments" in serve && + serve.arguments?.some(({ name }) => name === "--trust-remote-code") + ); + }) .map(({ metadata }) => metadata.id); expect(unsafeRecipes).toEqual([]); From 5cd60c077e16e4fb9ab928d12003ee94af7fe220 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 4 Aug 2026 00:47:47 -0700 Subject: [PATCH 27/27] fix(inference): validate managed catalog narrowing Signed-off-by: Aaron Erickson --- .../inference/serving/catalog-loader.test.ts | 70 +++++++++++++++++++ src/lib/inference/serving/catalog-loader.ts | 63 ++++++++++++++++- ...lm-managed-cluster-runtime-receipt.test.ts | 6 +- 3 files changed, 134 insertions(+), 5 deletions(-) create mode 100644 src/lib/inference/serving/catalog-loader.test.ts diff --git a/src/lib/inference/serving/catalog-loader.test.ts b/src/lib/inference/serving/catalog-loader.test.ts new file mode 100644 index 00000000000..5255c4197af --- /dev/null +++ b/src/lib/inference/serving/catalog-loader.test.ts @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + MANAGED_CLUSTER_VLLM_LIFECYCLE_REF, + MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, +} from "./adapter-registry"; +import { assertManagedInferenceCatalog } from "./catalog-loader"; +import type { CompiledServingCatalog, ServingPreset, ServingRecipe } from "./types"; + +const EMPTY_CATALOG: CompiledServingCatalog = { + schemaVersion: "1.0.0", + compilerVersion: "1.1.0", + sourceRevision: "a".repeat(40), + readinessSchemaRef: "https://github.com/NVIDIA/NemoClaw/schemas/system-readiness.schema.json", + recipes: [], + presets: [], + sources: [], + catalogDigest: `sha256:${"b".repeat(64)}`, +}; + +const INCOMPLETE_MANAGED_RECIPE: ServingRecipe = { + apiVersion: "nemoclaw.nvidia.com/managed-inference/v1", + kind: "ServingRecipe", + metadata: { id: "test.incomplete-managed-recipe" }, + spec: { + backend: "vllm", + model: { id: "test/model", revision: "c".repeat(40) }, + execution: { + materializerRef: MANAGED_CLUSTER_VLLM_MATERIALIZER_REF, + lifecycleRef: MANAGED_CLUSTER_VLLM_LIFECYCLE_REF, + }, + }, +}; + +const INCOMPLETE_MANAGED_PRESET: ServingPreset = { + apiVersion: "nemoclaw.nvidia.com/managed-inference/v1", + kind: "ServingPreset", + metadata: { id: "test.incomplete-managed-preset" }, + spec: { + selection: "explicit-only", + priority: 1, + plan: { backend: "vllm", recipeRef: INCOMPLETE_MANAGED_RECIPE.metadata.id }, + }, +}; + +function managedCatalogValidationError(catalog: CompiledServingCatalog): string | undefined { + try { + assertManagedInferenceCatalog(catalog); + return undefined; + } catch (error) { + return (error as Error).message; + } +} + +describe("managed inference catalog loader", () => { + it("accepts an empty managed catalog", () => { + assertManagedInferenceCatalog(EMPTY_CATALOG); + + expect(EMPTY_CATALOG.recipes).toHaveLength(0); + }); + + it.each([ + ["recipe", { ...EMPTY_CATALOG, recipes: [INCOMPLETE_MANAGED_RECIPE] }], + ["preset", { ...EMPTY_CATALOG, presets: [INCOMPLETE_MANAGED_PRESET] }], + ] as const)("rejects an incomplete managed %s", (_label, catalog) => { + expect(managedCatalogValidationError(catalog)).toMatch(/Managed inference (preset|recipe)/u); + }); +}); diff --git a/src/lib/inference/serving/catalog-loader.ts b/src/lib/inference/serving/catalog-loader.ts index 9a736acd478..c8e7ac78ab6 100644 --- a/src/lib/inference/serving/catalog-loader.ts +++ b/src/lib/inference/serving/catalog-loader.ts @@ -4,13 +4,17 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; -import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; +import { getManagedInferenceRecipeRegistrationError } from "./adapter-registry.js"; import { parseCompiledServingCatalogJson } from "./catalog.js"; +import { immutableManagedInferenceCopy } from "./catalog-integrity.js"; import type { CompiledManagedInferenceCatalog, + CompiledServingCatalog, ManagedInferenceServingPreset, ManagedInferenceServingRecipe, ServingCatalogSchemas, + ServingPreset, + ServingRecipe, } from "./types.js"; function readJson(path: string): object { @@ -32,13 +36,66 @@ function loadSchemas(rootDir: string): ServingCatalogSchemas { let loadedCatalog: CompiledManagedInferenceCatalog | undefined; +function assertManagedRecipe( + recipe: ServingRecipe, +): asserts recipe is ManagedInferenceServingRecipe { + let registrationError: string | undefined; + try { + registrationError = getManagedInferenceRecipeRegistrationError( + recipe as ManagedInferenceServingRecipe, + ); + } catch { + registrationError = "does not satisfy its registered adapter contract"; + } + if (registrationError) { + throw new Error(`Managed inference recipe ${recipe.metadata.id}: ${registrationError}`); + } +} + +function assertManagedPreset( + preset: ServingPreset, +): asserts preset is ManagedInferenceServingPreset { + if (!preset.spec.requirements || !preset.spec.plan.bindings) { + throw new Error( + `Managed inference preset ${preset.metadata.id} must declare requirements and topology bindings`, + ); + } +} + +/** Narrow a generic serving catalog to the currently supported managed runtime surface. */ +export function assertManagedInferenceCatalog( + catalog: CompiledServingCatalog, +): asserts catalog is CompiledManagedInferenceCatalog { + for (const recipe of catalog.recipes) assertManagedRecipe(recipe); + for (const preset of catalog.presets) { + assertManagedPreset(preset); + const recipes = catalog.recipes.filter( + ({ metadata }) => metadata.id === preset.spec.plan.recipeRef, + ); + if (recipes.length !== 1 || recipes[0]!.spec.backend !== preset.spec.plan.backend) { + throw new Error( + `Managed inference preset ${preset.metadata.id} does not resolve one matching recipe`, + ); + } + } +} + +export function parseCompiledManagedInferenceCatalogJson( + source: string, + schemas: ServingCatalogSchemas, +): CompiledManagedInferenceCatalog { + const catalog = parseCompiledServingCatalogJson(source, schemas); + assertManagedInferenceCatalog(catalog); + return catalog; +} + export function loadManagedInferenceCatalog(): CompiledManagedInferenceCatalog { if (loadedCatalog) return loadedCatalog; const rootDir = repositoryRoot(); const source = readFileSync(join(rootDir, "dist", "managed-inference", "catalog.json"), "utf8"); loadedCatalog = immutableManagedInferenceCopy( - parseCompiledServingCatalogJson(source, loadSchemas(rootDir)), - ) as CompiledManagedInferenceCatalog; + parseCompiledManagedInferenceCatalogJson(source, loadSchemas(rootDir)), + ); return loadedCatalog; } diff --git a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts index aea982ab04c..4ac23bd9723 100644 --- a/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts +++ b/src/lib/inference/vllm-managed-cluster-runtime-receipt.test.ts @@ -6,9 +6,8 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadManagedInferenceCatalog } from "./serving/catalog-loader"; import { managedInferenceDigest, managedInferenceHexDigest } from "./serving/catalog-integrity"; -import type { CompiledManagedInferenceCatalog } from "./serving/types"; +import { loadManagedInferenceCatalog } from "./serving/catalog-loader"; import { fixtureManagedClusterSelection } from "./serving/managed-cluster-fixture.test-support"; import { type ManagedClusterNodeSnapshot, @@ -42,6 +41,7 @@ import { type ManagedVllmSshBindingFixture, } from "./serving/managed-cluster-ssh-binding.test-support"; import { managedClusterTopologyOutputDigest } from "./serving/managed-cluster-topology"; +import type { CompiledManagedInferenceCatalog } from "./serving/types"; const API_KEY = "a".repeat(64); const HEAD_ID = "b".repeat(64); @@ -304,6 +304,8 @@ describe("managed cluster vLLM runtime receipt", () => { ({ metadata }) => metadata.id === source.plan.recipeId, ); + expect(currentPreset).toBeDefined(); + expect(currentRecipe).toBeDefined(); expect(loaded?.plan.catalogDigest).toBe(currentCatalog.catalogDigest); expect(loaded?.plan.presetDigest).toBe(managedInferenceDigest(currentPreset)); expect(loaded?.plan.recipeDigest).toBe(managedInferenceDigest(currentRecipe));