From ec6a5b61f664899f5df066cdf39a2affb0da2187 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:05 -0700 Subject: [PATCH 01/10] feat: add MTPLX as an engine type on Apple Silicon nodes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first cut of PAIR seeing an engine that is not a download. - launch_model declares a list of flags (--model picks the files to serve, --model-id fixes the id the server answers to) instead of one flag, so a later commit can stop writing a flag that pins nothing. A manifest naming no flag, repeating one, or listing a non-flag is now a manifest error; vllm.json moves to the list form, which behaves as the single flag did. - MTPLX is described through a manifest plus the per-engine tables that mirror nvpair-shared/engines, so nothing branches on its name: manifest for darwin/arm64 only, discovery key advertised only while a managed server answers /health, appleOnly catalog rows, pack ids matched exactly rather than by prefix, one model per process so Load rewrites launch arguments and restarts the server. Facade and managed server take 8100 and 8101 — its own default 8000 is already the vLLM facade's, and Apple Silicon is where both engines can run. - No install block and no Install button: the engine ships as an app that updates itself, a PAIR-installed second copy would be a second server and a second cache, and the pack cache stays in the user's own ~/.mtplx/models, surviving uninstall and data reset. - Desktop relays what a node reports: wire and display names, links, the disk-read model list (Add model, Delete and Load work while the engine is stopped), the load-pending timeout keyed on the loadRestartsEngine capability instead of the name "vLLM", and Partial records for the icon and welcome maps so an engine without a mark of its own reads as absent, not as an oversight. The mark is MTPLX's own unmodified AppIcon layer. - Docs carry the operational facts: the port map and why 8000 was left alone, no Install action anywhere, the catalog filtered locally because the pack list is not searchable, and that an engine the user installed is not a service PAIR runs. No behavior toward a live engine exists yet; that is the next commits. Signed-off-by: Steven Beverly --- README.md | 7 +- desktop/docs/services-parity.md | 83 ++++++- .../electron/service-bridge/empty-handlers.ts | 15 +- .../electron/service-bridge/model-catalog.ts | 5 + .../electron/service-bridge/modular-state.ts | 6 +- .../electron/service-bridge/proxy-engines.ts | 13 +- desktop/src/shared/constants/engines.ts | 27 ++- desktop/src/ui/assets/engine-icons/mtplx.png | Bin 0 -> 17906 bytes desktop/src/ui/components/EngineIcon.tsx | 8 +- .../src/ui/constants/engine-capabilities.ts | 35 +++ desktop/src/ui/constants/welcome.ts | 8 +- .../src/ui/stores/pending-actions.store.ts | 16 +- .../src/ui/utils/match-downloaded-model.ts | 5 +- desktop/tests/modular/engine-identity.test.ts | 36 ++- .../modular/inference-demo-lifecycle.test.ts | 10 +- .../modular/proxy-engine-identity.test.ts | 35 ++- .../tests/modular/unsupported-engine.test.ts | 14 +- docs/architecture.mdx | 19 +- docs/engine-lifecycle.mdx | 38 ++- docs/engine-settings.mdx | 22 +- docs/getting-started.mdx | 40 +++- docs/overview.mdx | 6 +- docs/terminal-interface.mdx | 29 ++- services/installer/macos/INSTALL.md | 14 +- services/nvpair-engine-manager/MANIFEST.md | 34 ++- services/nvpair-engine-manager/README.md | 85 ++++++- services/nvpair-engine-manager/catalog.go | 28 ++- .../nvpair-engine-manager/catalog_mtplx.go | 120 ++++++++++ .../catalog_mtplx_test.go | 223 ++++++++++++++++++ services/nvpair-engine-manager/hfcache.go | 13 +- .../nvpair-engine-manager/hfcache_test.go | 2 +- .../launch_controls_test.go | 10 +- services/nvpair-engine-manager/launchmodel.go | 58 ++++- .../nvpair-engine-manager/launchmodel_test.go | 109 +++++++-- services/nvpair-engine-manager/lifecycle.go | 4 +- .../nvpair-engine-manager/lifecycle_test.go | 2 +- .../manifests/mtplx.json | 63 +++++ .../nvpair-engine-manager/manifests/vllm.json | 2 +- .../nvpair-engine-manager/modelrequest.go | 6 +- services/nvpair-engine-manager/registry.go | 29 ++- .../nvpair-engine-manager/registry_test.go | 2 +- .../nvpair-engine-manager/remediation_test.go | 2 +- services/nvpair-engine-manager/spec.md | 37 +-- services/nvpair-job-scheduler/spec.md | 8 +- services/nvpair-node-scanner/README.md | 4 +- services/nvpair-node-scanner/spec.md | 4 +- services/nvpair-proxy/README.md | 52 ++-- services/nvpair-proxy/engines.go | 23 ++ services/nvpair-proxy/engines_test.go | 39 +++ services/nvpair-proxy/spec.md | 35 ++- services/nvpair-tui/README.md | 4 +- services/nvpair-tui/ui/engineswire.go | 19 +- services/nvpair-tui/ui/nodedetail.go | 4 +- services/nvpair-ui-broker/README.md | 33 ++- services/nvpair-ui-broker/engineproxy.go | 1 + services/nvpair-ui-broker/engineproxy_test.go | 2 +- .../nvpair-ui-broker/enginesettings_test.go | 16 +- services/nvpair-ui-broker/spec.md | 34 +-- services/readme.md | 30 ++- services/shared/engines/engines.go | 11 + services/shared/engines/engines_test.go | 2 +- services/shared/noderec/noderec.go | 5 +- 62 files changed, 1382 insertions(+), 264 deletions(-) create mode 100644 desktop/src/ui/assets/engine-icons/mtplx.png create mode 100644 services/nvpair-engine-manager/catalog_mtplx.go create mode 100644 services/nvpair-engine-manager/catalog_mtplx_test.go create mode 100644 services/nvpair-engine-manager/manifests/mtplx.json diff --git a/README.md b/README.md index d1bc38df7..48ae04ad8 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ one, and both report live GPU and memory use throughout. | **Architectures** | x64 and arm64 on all three. Windows on ARM is experimental. | | **Installers** | Windows `.exe`; Linux `.deb`; macOS `.dmg`. On other Linux distributions, [build from source](docs/building.mdx). | | **Mixing nodes** | Windows, Linux, and macOS nodes can all be paired with each other | -| **Inference engines** | Ollama, LM Studio, llama.cpp, and vLLM (Linux with an NVIDIA GPU, or Apple Silicon macOS) | +| **Inference engines** | Ollama, LM Studio, llama.cpp, and vLLM (Linux with an NVIDIA GPU, or Apple Silicon macOS), plus MTPLX (Apple Silicon macOS only, and only where you have installed it yourself) | **PAIR running on a machine does not mean an engine will.** PAIR itself runs on any supported Windows, Linux, or macOS machine. Each engine sets its own requirements @@ -101,7 +101,9 @@ you want by its full filename instead. - **Get an engine running.** On the node's card, open **Engine settings** and select **Install** next to Ollama, LM Studio, llama.cpp, or (on Linux or Apple Silicon macOS) vLLM. PAIR downloads and - sets the engine up for you, so nothing needs to be in place beforehand. + sets the engine up for you, so nothing needs to be in place beforehand. MTPLX is + the exception: on an Apple Silicon Mac PAIR drives a `mtplx` you installed + yourself and never installs one. ![The Install engines dialog with Ollama downloading, reporting progress as it installs.](docs/assets/onboarding/engine-lifecycle/01-engine-installing.png) @@ -287,6 +289,7 @@ feedback and contributions will help shape priorities. - [x] llama.cpp support. - [x] vLLM support. +- [x] MTPLX support on Apple Silicon macOS, from an existing install. - [ ] EXO support. - [ ] ComfyUI integration. - [ ] Unsloth support. diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index 5fd72a98f..fb592e7a5 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -26,6 +26,7 @@ history. | LM Studio routing | Complete | Parallel broker relay and scheduler path | | llama.cpp backend | Integrated | Desktop and TUI expose install, lifecycle, catalog pull, inventory, load/unload, endpoints, routing, and demo traffic | | vLLM engine | Integrated (Linux, macOS arm64) | Desktop and TUI expose install, lifecycle, the cached-model list, switching the served model (Load), Hugging Face catalog search and download, endpoints and routing; eject (stops the engine), delete of cached models; no demo traffic | +| MTPLX engine | Integrated (macOS arm64 only) | Desktop and TUI expose lifecycle, the pack-cache list, switching the served pack (Load restarts the engine), MTPLX's pack list and download, endpoints and routing, delete of cached packs; eject stops the engine; no demo traffic | | Local engine lifecycle | Complete | Install, start, stop, uninstall, update, and port configuration | | Remote engine lifecycle | Partial | Remote install, start, stop, status, and model pull are supported | | Engine models | Partial | Core list, pull, load, unload, and supported delete actions are wired | @@ -35,7 +36,7 @@ history. | Cluster pairing | Complete | PIN pairing, identity, membership, leave, and removal | | Cluster transport security | Backend-owned | Node-to-node transport security, including the proxies' cluster-mTLS inference ingress, is entirely backend; Personal AI Router implements none | | Settings | Partial | Cluster identity plus per-engine ports and engine arguments, local and remote; inert backend settings are not surfaced | -| Model catalog search | Backend-owned | `engine:catalog` serves the locked Ollama list and the cached LM Studio and llama.cpp catalogs, and searches Hugging Face for llama.cpp | +| Model catalog search | Backend-owned | `engine:catalog` serves the locked Ollama list and the cached LM Studio, llama.cpp and MTPLX catalogs, and searches Hugging Face for llama.cpp; MTPLX's is not searched, so clients filter it | ## Supervision @@ -234,7 +235,7 @@ engine), its switch stays on and usable: turning it off sends an explicit toggle reads the engine's status and an engine that is still starting reports not running. The engine-manager cancels the start in flight. Its safety net is the awaited lifecycle envelope (`MODULAR_ENGINE_LIFECYCLE_CALL_TIMEOUT_MS`, 34 minutes), which outlasts every -engine's readiness window (vLLM 30 minutes, Ollama 10), so a slow start is never +engine's readiness window (vLLM 30 minutes, Ollama and MTPLX 10), so a slow start is never shown as stopped while it is still loading. Weights live in the shared Hugging Face cache (`~/.cache/huggingface`), which uninstall and app-data reset never remove. @@ -243,6 +244,60 @@ Current limits are explicit: the manual-node worker does not probe vLLM, the Inference Demo does not use it, and the icon is a placeholder lettermark rather than the vLLM project logo. +### MTPLX support + +The bundled `mtplx` manifest covers Apple Silicon macOS and nothing else: its +`platforms` block declares only `darwin/arm64`, because MTPLX decodes on the Metal +path. That declaration is the whole platform gate. An engine manager on an Intel +Mac, on Linux, or on Windows leaves MTPLX out of `engine:get-installed`, so neither +the desktop engine list nor the terminal interface offers it, and the `8100` proxy +facade those hosts still enable has nothing to front. MTPLX itself runs on `8101`, +behind that facade; `8000` was not reused because it is already the vLLM facade's +port and MTPLX's own default. + +MTPLX is also detect-only: the manifest declares no install block, so there is no +Install action, an explicit uninstall answers that no uninstall is defined for this +platform, app-data reset skips the engine, and onboarding leaves it out rather than +showing an install row that cannot be fulfilled. PAIR launches the `mtplx` CLI of an +install the user made and leaves the engine, and the pack cache the user filled, +where they were. + +Like vLLM it serves one model pack per process, so Eject is a `stop_engine` action +and Load is a `launch_model` action: Load rewrites the saved launch arguments and +restarts the server on the new pack, restoring the previous one if it does not come +up. Two flags move together, `--model` and `--model-id`. The second fixes the id the +server answers to, which makes the served id, the name in the model list, and the +`model` field a client sends one string; started with `--model` alone, MTPLX derives +a name such as `mtplx-qwen38-27b-optimized-speed-fp16`, matching no cache entry and +no request. `loadRestartsEngine` is set for MTPLX as it is for vLLM, so the pending +Load in the renderer's pending-actions store covers it the same way. No pack is baked +into the launch arguments, and an engine with a `launch_model` action will not start +while none of its flags names a model, so a bare Start answers "MTPLX has no model +selected; load a model to start it". + +Its model list comes from `mtplx models --json`, which reads the pack cache, so the +list, Add model, Delete and Load all work while the engine is stopped, and only the +pack being served is advertised to peers and the proxy. Identifier matching is +byte-exact, as on LM Studio, llama.cpp and vLLM, rather than Ollama's implied +`:latest`. Pulls and deletes are CLI actions with no byte progress, so a pull shows +only that it is pulling. `mtplx remove` has no in-use guard and does not clear a +deleted pack from a stopped engine's launch arguments, so the desktop app blocks +Delete on the pack being served (`deleteBlockedWhileLoaded`). + +MTPLX's catalogue is MTPLX's own published pack list rather than a Hugging Face +browse, because the engine loads only packs rebuilt for its decode path and a general +browse would offer mostly packs it refuses. It is not searchable, so the desktop and +the terminal interface filter its couple-of-dozen entries locally, and it is the one +catalogue that is not warmed at startup: every pack there is Apple-Silicon-only, and +the list is reachable only from an MTPLX card, so prewarming would fetch it on hosts +that can never load from it. + +Current limits are explicit: the manual-node worker does not probe MTPLX, which +probes Ollama and LM Studio only, and the Inference Demo cannot reach it, because +its probe set and its dispatcher backends cover Ollama, LM Studio and llama.cpp. +Its row mark is the square tile the MTPLX app uses for the Dock, taken unmodified +from a 128 px layer of that bundle's `AppIcon.icns`. + ## Engine lifecycle `nvpair-engine-manager` is authoritative for installed, running, healthy, and @@ -659,20 +714,24 @@ safety-net timeout (`pending-actions.store.ts`). Loaded state carries no `sizeVram`/`expiresAt` — the backend delivers the simpler `loadedByEngine` name-set, not structured details. -vLLM advertises only the model it is serving, so its `modelsByEngine` entry is -that one name, for routing. Its whole downloaded list arrives as -`downloadedByEngine`, read even while it is stopped, and `modelsForEngine` -lists a node's vLLM rows from it. Its `loadedByEngine` uses the same names, so -a model served under `--served-model-name` still marks its row loaded. When a -peer's vLLM list was not read, `EngineModels.inventoryKnown` is false and the -model manager says the downloaded models are unavailable instead of claiming -none are downloaded. +vLLM and MTPLX advertise only the model they are serving, so each `modelsByEngine` +entry is that one name, for routing. The whole downloaded list arrives as +`downloadedByEngine`, read even while the engine is stopped, and `modelsForEngine` +lists a node's vLLM and MTPLX rows from it. Each one's `loadedByEngine` names models +the way that inventory does, so the served model still marks its row loaded: vLLM by +the `root` of its `/v1/models`, not a `--served-model-name` alias, and MTPLX by the +`data[].id` that `--model-id` pins to the cache id. When a peer's list was not read, +`EngineModels.inventoryKnown` is false and the model manager says the downloaded +models are unavailable instead of claiming none are downloaded. The model catalogue is owned by the backend: `engine:catalog` on -`nvpair-engine-manager` serves the curated Ollama, LM Studio, and llama.cpp +`nvpair-engine-manager` serves the curated Ollama, LM Studio, llama.cpp and MTPLX lists, and searches Hugging Face for llama.cpp, and both the desktop app and the terminal interface browse it. Electron only relays the call and maps rows -for the renderer. +for the renderer. MTPLX's list is MTPLX's own pack list rather than a Hugging Face +search, is not marked `searchable`, and is narrowed to the target's platform and +architecture, so a peer that is not Apple Silicon is handed none of it and the +clients filter the rest locally. ## Errors diff --git a/desktop/src/electron/service-bridge/empty-handlers.ts b/desktop/src/electron/service-bridge/empty-handlers.ts index e26c8ac62..6ec2b2b68 100644 --- a/desktop/src/electron/service-bridge/empty-handlers.ts +++ b/desktop/src/electron/service-bridge/empty-handlers.ts @@ -338,15 +338,18 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): // (`/api/generate`) with no prompt: Ollama loads the model into VRAM // and returns immediately (`done_reason: "load"`) without generating. // LM Studio and llama.cpp declare real `load_model` manifest actions. - // vLLM's `load_model` serves the model by restarting a running engine - // on it, or starting a stopped one, which takes minutes and can fail - // (the model may not fit), so like Ollama's its rejection is observed - // and attributed to the pending model row. + // vLLM's and MTPLX's `load_model` serve the model by restarting a + // running engine on it, or starting a stopped one, which takes minutes + // and can fail (the model may not fit), so like Ollama's its rejection + // is observed and attributed to the pending model row. // Ollama, LM Studio and llama.cpp require the engine running (HTTP/CLI - // action); enabled vLLM can load its first model before a server exists. + // action); enabled vLLM can load its first model before a server exists, + // and vLLM and MTPLX list their models from disk + // (`EnginesListingModelsWhenStopped`), so Load is offered while the + // engine is stopped. ModelRow.tsx applies the same rule. // See docs/services-parity.md#models. if (payload.model) { - if (payload.engineType === 'vllm') { + if (payload.engineType === 'vllm' || payload.engineType === 'mtplx') { // The reply arrives once the new model is serving, or the // previous one is restored. The renderer's pending Load shows // the engine as starting while it restarts. A Stop or Eject diff --git a/desktop/src/electron/service-bridge/model-catalog.ts b/desktop/src/electron/service-bridge/model-catalog.ts index 71519384c..18a5bebf4 100644 --- a/desktop/src/electron/service-bridge/model-catalog.ts +++ b/desktop/src/electron/service-bridge/model-catalog.ts @@ -163,6 +163,11 @@ export async function getEngineHubModels( * nothing. Fire-and-forget: failures are logged by the call itself and the modal * will simply fetch again. * + * MTPLX is deliberately not warmed. Every one of its packs is Apple Silicon only, + * so warming it means a startup fetch on the hosts that can never load those + * packs, and the list is only reachable from an MTPLX card — a couple dozen + * entries that fetch faster than it takes to open that modal. + * * Called once the Overview renderer reports ready, deliberately not on service * connect: a network fetch started before the window has painted competes with * the renderer's own load, and a hanging one leaves an unpainted window behind. diff --git a/desktop/src/electron/service-bridge/modular-state.ts b/desktop/src/electron/service-bridge/modular-state.ts index c873ccd17..4dd9a1fd1 100644 --- a/desktop/src/electron/service-bridge/modular-state.ts +++ b/desktop/src/electron/service-bridge/modular-state.ts @@ -194,7 +194,8 @@ function emptyEngines(): Record { ollama: emptyPresence(), 'lm-studio': emptyPresence(), 'llama-cpp': emptyPresence(), - vllm: emptyPresence() + vllm: emptyPresence(), + mtplx: emptyPresence() } } @@ -954,7 +955,8 @@ class ModularBridgeState { ollama: 0, 'lm-studio': 0, 'llama-cpp': 0, - vllm: 0 + vllm: 0, + mtplx: 0 } private selfId: string | null = null /** diff --git a/desktop/src/electron/service-bridge/proxy-engines.ts b/desktop/src/electron/service-bridge/proxy-engines.ts index 3be8fd0ec..4da44fafc 100644 --- a/desktop/src/electron/service-bridge/proxy-engines.ts +++ b/desktop/src/electron/service-bridge/proxy-engines.ts @@ -10,13 +10,22 @@ import { engineTypeFromManagerName } from '@/shared/utils/engines' * separate from the complete engine registry so an engine can be declared * before every proxy-state consumer is ready to handle it. */ -export type ProxyEngine = Extract +export type ProxyEngine = Extract< + EngineType, + 'ollama' | 'lm-studio' | 'llama-cpp' | 'vllm' | 'mtplx' +> /** A proxy's source name: the engine-manager's name for the engine, plus -proxy. */ export type ProxyNodeSource = `${(typeof EngineManagerNames)[ProxyEngine]}-proxy` const PROXY_SOURCE_SUFFIX = '-proxy' -export const PROXY_ENGINES: readonly ProxyEngine[] = ['ollama', 'lm-studio', 'llama-cpp', 'vllm'] +export const PROXY_ENGINES: readonly ProxyEngine[] = [ + 'ollama', + 'lm-studio', + 'llama-cpp', + 'vllm', + 'mtplx' +] export const PROXY_NODE_SOURCES: readonly ProxyNodeSource[] = PROXY_ENGINES.map(proxySourceForEngine) diff --git a/desktop/src/shared/constants/engines.ts b/desktop/src/shared/constants/engines.ts index 54c76f7d8..bb7ee619a 100644 --- a/desktop/src/shared/constants/engines.ts +++ b/desktop/src/shared/constants/engines.ts @@ -5,11 +5,17 @@ import { EngineType, ModelExpiry } from '@/shared/types/engines' // The engines `nvpair-engine-manager` ships a manifest for, and therefore the // only ones PAIR can install, run or route to. -export const EngineTypes = ['ollama', 'lm-studio', 'llama-cpp', 'vllm'] as const +export const EngineTypes = ['ollama', 'lm-studio', 'llama-cpp', 'vllm', 'mtplx'] as const // Kept as a distinct export so a future engine can ship behind it rather than // appearing the moment its type exists. -export const EnabledEngineTypes: EngineType[] = ['ollama', 'lm-studio', 'llama-cpp', 'vllm'] +export const EnabledEngineTypes: EngineType[] = [ + 'ollama', + 'lm-studio', + 'llama-cpp', + 'vllm', + 'mtplx' +] /** * Engines whose model list is read from disk, so it is available while the engine @@ -17,7 +23,7 @@ export const EnabledEngineTypes: EngineType[] = ['ollama', 'lm-studio', 'llama-c * cleared when it stops. Stopped engines keep that inventory internally; the UI * exposes model controls only while enabled. */ -export const EnginesListingModelsWhenStopped: readonly EngineType[] = ['vllm'] +export const EnginesListingModelsWhenStopped: readonly EngineType[] = ['vllm', 'mtplx'] /** * How `nvpair-engine-manager` spells each engine on the wire. This is the @@ -28,7 +34,8 @@ export const EngineManagerNames = { ollama: 'ollama', 'lm-studio': 'lmstudio', 'llama-cpp': 'llamacpp', - vllm: 'vllm' + vllm: 'vllm', + mtplx: 'mtplx' } as const satisfies Record export const EngineSources = ['bundled', 'detected', 'installed'] as const @@ -37,7 +44,8 @@ export const EngineDisplayNames: Record = { ollama: 'Ollama', 'lm-studio': 'LM Studio', 'llama-cpp': 'llama.cpp', - vllm: 'vLLM' + vllm: 'vLLM', + mtplx: 'MTPLX' } as const /** Default docs/install URLs for built-in backends. Single source of truth for UI and adapter buildInfo(). */ @@ -51,6 +59,12 @@ export const EngineDefaultLinks: Record&K}_tdSbW#L1e2n9I_ z_#Zew0002Il%%NAzwG~CKtulf4)PmL{!1WEN)p0=ni;&ae?Ouo8d9dRvH15{Y5;{hk01H?dZG#QaMU1qTz9xwOuj~7PZtj_(?DsC$N!Fsp$?emIvRtYU^L5q*6eHi ze9cx#=yCKl>;0DnvEo-S2{K&kt}hR%2#t=~^~u8`KEOw*r1$UzqW2EB_wJq)k>^sC z#dPMaIKMyNLhm7>yItw)+C2Vy72&i#aR0Y1x=yYf7`G#0L#i^7q z#Jc~n$k(0XT}1=Q2`A(JH8y@T|7{KvtBUDV8u44$n-1B7ePqdYgJj|5AXA2v)$jTki4yB9xf+nzke zl2?KqOzH}9j}(vM7Mh?x&IC@g?6f7I9Hk3SLj{${5?VJ)Her%jY;l8s&*w9x3yul^ zyvSuSbNwC&iJbWTiNOCtbmZ&2I)k73xi>2CHAdIE<;XML*;3RcplseKKsDjJet{_P zaZ9TAY^Ue;)DK1Q!oz$T)p^t2S*6!#3ap>j9(j(60#5p$7d3<@WJ`(5g+B)L-R+9Y z2r(5(KopA44vhPJp3g^!;>ReoUr+`NQn@-4ITfA$zz5yvn3ZD}j$B*$QG$U$xz8E^ ziB*nI79SS#xPa}NG;Us`@DUY_hyWLbZ{HW-6GpGgeLH1Fplmvu!_wt&7z*3#IL&sm z-ej?eQxZ~Y#0u>b@9<5w-YM^j#Zc>YW#xCGIg0GyF+nA&;W<24(T%>$`o zmUCwOV}?egR+`kXtL6lZkht(89a+t`&?9 z(L2v3AwV7M2a$U534XfI2B+r6j`{vyh$Td^HV&|`_)m+~$p42h_A!NKrOHVCptd2o>=<5KI%zqc|h1 zg@Cd}#4E7kV|jaS81T`!ZHO!s)*#wZe=1DJK?E$c4Q_ycm#qRp{k}Ed+xv*wOd8W$ zl~FF+OO+YEI)ShARY>ml$H{I*hweKI^qiAlk@HvJ?$;HE@0UN9lfLJqTW{w{e6tml zxP-*J_%mZ_fx*-TyX}>t8pd=oW5VQ-P56p`OC5aZIHM94?35&6z#S%t8dj(z=(2f= zvyW;Mq?yZGYAgbe6GEq!IPH**fwM_k#v~w7MXXasYL{CgXoGcQ^U=6cPKXel$XJ!O zvj|_m!};uVoWZ?+FNH3%_Wk7FwsG!fulV%Eh7rC<^4y&{`w;QH;P~#ff`kf{OL>rB zx7pxK62C<PbUQbvj`!8~-!Fcg}5{z&L)Kwcg3qF|t__=skDFN-}r0BVAWJ~=*9(Ucfw zfK*abke-9vCTjxQ<2&Mjiw=Xr6%h;l48sUKub+FqKjWiuo+OqJ6>#=iDm zhxRy`WqtY8PIHJ7VGe;g7raL#VsP_+Z&H$)8&9Z+tUqNWaWt?fHxZ@!$INMY_Kb_QO=ZoBoLeoh3GAu-OqT}z*BN` zS@jF$b&aJ%TEWCSF;D*Dxx2@cq^rRVCX)4HPGqDu5t<%SHrT!1?i`8bJP1Fb=W{;$ zsjlm?>}lKK^N_hK!(^FBA#gQV=Mb}r*XaGa>2|%v20SgaT80@}|AG}E>hcmBL$(hN z&%qwFf{UbtQM)Ww*Pq{M61HbdU>{+}-!BqroY}I}u1kRY=vah<>xU1E8w`pdK4jvLBJw9VA%CAW##9M^USFlpz{xYgkbqu*97E)oM2w8f}!> zYE7W!J~q&*+~{~bk@LC!3#BRd+?*|z`@HOx!E-T zmqNAs68c%tvzn6F1}AB`(NzdSF@#N3U^wnAm9GVPMoA&InyM{%7Cd-!U4sjyZNmO& zid~Sd)!ylczuP5Onjotv0S~(R*gk4Sg8>y?ZIHCh22O^C`33I6idJ@Cl)tqFxY06p zv`99$49sveQ;+lbLeB~Rb31M`B+pYQuC4o2I4YUUFE4>-G^UQD+oXK2_gX9hY`wgT zPemB|6Q@N6w2CiA4xZJK%qhHTku!7jx1&IMPnRbh%Anfsb=+-U&s;As`+9S6Fl~6r zOj_8PQO9N29k?6us*K3_R_x?b2|7?B|f#fA+0Igovn$lDb+eLFGyDi=-L9g?V zVFlbp*86K3(p6hGkY_8XD8nM1^JLJXKQm@0XnQ*1ydKomOQ9y9aX(Dfcw!S}G zy%>Sx)1%#5oe+!0cVrVZUKM{vAIawB)s`|qa1XdBFYt@QJ%#V<<&fH9rNyzj-y|b6 z7Co;=SeSaNq|~R4DhTC^0z58CBU>vO0&P&2lf^s`2c8+Qyj#F!Osm`qr53i_#|pn6 zFZ1*DE$gaqhjVT+4?~Wv>jfOaGv3B{@&`u=!dC$9t5)4lV~`xPxn6d(-@||?S6gk} z3}-=#SeU!vn(WRLzL&iqiT;oO9`3J`;~^5D?9?Ajj)aXif6>%ethM*3)f9B$Wszemp5)EJ1>fRntU5)9T@ zD&a%>ajsw|p3rwlADw3wh$bB6sdnLCzT?EX@atM;{V*De^SD5>c%4(YPGgYBXwGF1 znvK#l7J-`=mGV6~yVEu0Fjks0K!HWv|ZK03Ef1pg}dx-*}uU9vPP+Iy^)$E1U7 zmHy;(-%@Eo{V11uxUgP6WVxJ>V7=M>WG0(kxH%|<#GNGsxyZAbf*iYQ#&6n6PkV;{ z{j$Jjin*e>FSW;6)#H2j%Vr(8W`q!jEDpK9*@o04R0$;(;hMK)o143QGK+JSe1)R42MOe|BCB~I)mRYzi`+_kP&0W1;L8}cT#rl2 zlWh8*zcgK!=8vV-bu{TaferV2V2DWqp6{EJAWn$TCp_T^l1i|7ufN?sp&>7iMi-&p zPRReN%qk=JlW~e5Z}D>f>~;)T!2!?b#!w(IW47tKO;Rp84LUA$+tF;X-PF2n`;2j% zR_{^Dd5tMeeG5b4 z`#@Pq?i`uIM#2el2t6cj(ko3^)&s-oz6dPfsTzbkS z2<3Hbkf9K*PshGxz##Ma_Nd~#Tv0XGTVCP=4Y&*)$!GK!vZ^grrWCC^b0!lWZ9>2@ z&Ob;MbiLZqb-i9If3*+u-JIxt-qQX%ovF_Ml8=bd&HMX43fvQP$d<)G7S45k*?&X&X4`g z9X0+EfSaD9I0w4 z$?HI>Sw1L#9h-vvC+eu5<)F*RpaBCf#6b^%Oe#$J(NULo)M+{OHk(fkU-J@^D|E3| zFS)8a?>pamJ8vni<@;@+&FMJ&P<+&aFdcuhL;L8kbdOoXE2;hV^lGuza1zAZwbK+p zlfUH#qm|B z;2wN&f3@T(yCYy`dm9Xk=B3_q5;D64R|!SH(VF@pEBkBA(_GF;fo>qlb~FDn975}| zjb8~j(-pj#Gcp#FM@@dbSYdnddphyc`nr_=o>GSt!NKrQjZ`F(z{NRO4`3=3mcWG~3cw_Af98f_NzJk1YVn|HJ`bN9a3+|k;3 z?s;Hkm;sW*+$=z3|B{E0=VK!pj322BuqK5?erUp-)C<5InPEqr;pE2Ylv>)q_jfx3 zWf|pMzXS7>N7DTM+x0N9`E`ppNf7N?_?G`q0pVeNoIm_@x=H0zAqQkOg9B-KPN!VcKbS9m9T96JIY&t@t>lH6?@_b3C!A98CWIXDzMdP*@qk?h z+blNUy**w`7Fw-x_hAXQ+HI@t+}`Xc@ITe}(s-UO$<6zO!+@9%B)c8`M0M$BJA!shtmd@U-!v70ijc%og~D(gyy64r|9R7 zL;Dh*YsT6B%U5Jfjf)ku^gl(;$x=+R8QFqCL|QCmZeu;^Gv|_L` zZXCW6eo9Y<cF42gF^Jn zL4ooZ>-?D4wx?GIG(J}Q|6AFZJBjZnv-%|uQae(aY*wbn8~34hw+MEo{Cik*ezGHV zYik34(B)<{t0`V2l4sLPv!rfXX%zMyfb)|RrQc_{6Xm@h2Mt2ZvwV91y7M>Z&)#m{ zg4X|0TO8t^s_Q4#Bm~Y7z}2;ur&ZmMj*R$F_a4C(g27mEi~HJCYqA_ zbA4`qeb%=n>pS*%2vv^qf5(7j%z5|QL?NH{dzt7of%@t zL~W~BSSKw^h|U0g_Rm^Jz#tPE#X0Hyl{Z}elMZep*U)eKAkQgrAKt*=fh|5#ET97n z)YxGrAp_y(n8YN{ze_E-)g#Hk6Goy1WPFayDvL@VneFT7S$VzH#w~N}kSImR#Aj;@N`?j`H0-<1 zm$8kIpy8sue+EOKh-;VT3>Bk_7lpmEmw$vBwm&@Hp0jmiKIPo^KM3rdf#r+@c)e5^ zQMp6fMbdi2fz=nBu!3$NDxPRDQp?SSu=C}HTvYl#svaxnek5TI!#!~NBS*408U?vr z5U2{;EiLyURKKmi7M?tyqs3p(m7qmV#{J|$x4&f;>!c+X$QVVN6I5qyFP#GNn%+7T z`Yv()4p(0j^~L0Acw~j=4f;p=87I)FAT_LUGEDx zX>~#eZ+cXaWIR1l6yys=_GhqQf;ZsxL>?(U;ekGfPP%%u_VhTW(bwz&4%0;TR2UX6 zf>rL)YNtUtsf?;kYD{%&QqAcYjdq%F`h}I0HO_b%weJlQt^~Rysy|gJ_6?qa6L~CP zOuu_WMYI!UuOX4l*?<9E1t;Vd=39ys(Y=2ojUdUpoC64SreFwJ=M9Re2t5%2Y8g|? zzrzbSvy<2-9jS$NCsO1d*7@Q$kO&GHLE&fsZBoJWD>Xhtd~p2WfY85D`BLCW$6hx* zrFdRbER)OXx~e(P-@LJi^6jOeq)N;)W3ti+Fr`&wNWO!&V^--@7o%vR3O0*$mmIyv zbYga*sm+K2IxUmsw_!Ni%ixsVx%;_!ruc&v3eEO5ZaLBrN}4mI%qR~R>~z;y zAOwpm<+u}NaJ5x6OdXhxBz@CAL#N+w^i@qOuK&=~P}Y8O)GilTIZX|_D@c()af!i+ zxJF@{8`>E*_#bhJI2%yN?{ZLozsi3(z1C{ERrP#>REvbtK_M3)@{ZqmzeRgtI6Nl^ zt`utSY#p4FWBQ%lCQUf@CI7KhhqYAbQy|W&X)vjTQk_d5@U1z2oqK>5jPuM~s1nXg zp;3Au9Q<2b{S&H-WLQ%o$~vg*kEAJ?fwH7N_WX8Zm=6^M!iWpQ;NCfMUtX944D@xA zP13x8%Ra^A&G*+04RnjUB)R!C$OBxgt%4Li*fd%F#1^c##_Dpq^9%A zyC(337!|l)OQet&rla$8N5zZLBx9v_HMr@G1@aqh%%YD^qyI*cNE8%T(UK%c1=`w5 zQ_WrM4^=ZpiMOS?jIyl~Ll~_lb8R#oZA`2oYhE;@Yl0otu?(Qi?Ix`Y!+#ou3S`)~CPOr!yf5jWMcpy{{THSa-7OOCn z6cPUBvHe+Os%3M+t@pXxG17Ocm%)9XN{@13k;$EWambzo4^ai^VcYZgzRO_u zPkEeND3+e^dx`y??}8yX?E8_gB#4SScR!ki82wd&iwrB)lP*#^ha`0Nx*L|d(O3r&$Vi$IBBku+@W}y(xDYa3%znGx^Zzy%q zdpXX632PnTP8f0CGn+re4{Xj*mO>pd*nZ3GYTRXhEf6aiMY<$6zl7f`E+tBEY=CfuTFV@R zI6+=ZVcin#W$A-~4-t5RvTQWJvJDbXz&t857BY#KxX37CQz6macshh$(RN548zBSI15m{+4i=!2l zQxw7WN_4dp;R`i5<#*rdKb{jod_0KNE~(0q;&jfwhO}Ky?r*jIQu9dM`MLLWPBL97 z0|O4ymC(zfeZ=Ytx$ZY=U+J9gzRUNV^6-yN71&+Bu1ow2Q0{5#O*A|Mq z^i&~P@$(QP64{hOIkNBs4|wdpyl=D)K5G3wzn^0W)d6FHwmJ(a8oW1tYldN(t@gd+ z)EYOTN<{z7>CU}2%?ek$JswCk08j`dZG?f zp0SR>Z&_7;;o!RI{^TD$FDbpjPyXlbKI|O!zF&9pwX*0RqJgpp0w{(a`Guk%ZnT>x zo=Je3Zcr56_}E~(2k(96{Yk?(VV-stktvB2hNHIX`H;T*?uV*8uE*2+ zGfMbDmvG^XyzKKd{uqX56`WSRu1+XNtGCaz^aTXfgkPvKF7E;IvuAX69L7hpBI3zQ z;XrF1ZswzjS~Pb*uia9udY;(i@$Yzl%RtD0as9BTt3{;dfvoV!y)z~#O9NEDzV z{C>4zJN`F#CCHL;;#{9R6>b% zX_Db^X(?jL$!X&NupT;Mcu6JM(8X2_>*|_~lRmMy$Sh|qCP3;M5>nocFs)EHvaoG2 z3W8(tYZO3#N=0GJoM`Sb+H>Y|(^qN;Iqhgq5cTc3mA9gR6MoFS9>c2Zm9zDe;Bwe; zGSN18n$h)VbLDUu8@5Zy<8PN|O5!#xzK~yG@fR3+KL#OcvG1tgmgUa}I^l4!d%S>- z7TgCBe&luOs*`y`>JysT=Y{wh1~^+z%(4z914xDRo-znb@5V4@oI9I9%8PH2ZT2$o^q;SU)AF z=R5yxP^!E`gFu7V29tlN{jDh5;jQ*FBfDGIkvWXz;~{Sxp*vvcAnI!0>!wql!ThW8 z{^oJ)3DG5e>=?H@(_lQBG8VAR6(u9tEgCs9T_l)wc&_vJ9iYbn^ywT4MkMQB}4%oIxvy>=M@4s%OP!t zu1lE5juvg#egxb1$@gK*6k<@$4&H8l!?5z2amRP`>R8?Hak)e9d;7lo##j9!&~WzE z==?54B!H1D=jd~>Al5*q!&s{Qt^{{d-(tc;un;1$dqj%3{IQ=DLz59mimYQTn6JDw z87{yr#-|Rl2I|tq={hs*9R38kOv}bjD!6fRM5Q9sgvcUz#svrsbJM&VpCF|PEN&Em zSRx4l*0d`A78*52X8+>?l4^n#LE(EAAv-DPxQ;dmsu)^&?$Mhw*;8x5w@1YJ0Eg?< zX-j9ffl()&6v`OZk1( z`^{1PM)*{$J4#4w2H`BqmIbCg7X`ouoVml5$X99levCKy%Vw#J)YI~2f=|uIVW8Jw zGxHDgO9t@_%gll>8bSJn%HDLX3!?N1t8xvoLS$hPg+n1s>;t*s{)Daql(IZfN*fzT zG6ko390z_*NF5?P=dlFvhoTWYFo}FcbL^Cr+OH_LZOrXGq7Pf^@(;!J|_UyDb~4>bCpmL9n~SBJ0Q3{P>xNryyA1F{lg3U0?n z;CoUepdkDo_H5d#1g~*oUdX4rbHgh1rvR|hGI$=fI5~$iN>8o4=Zq3O0F7D|dG1_`8(_{Jdaj?+jqicy(VkREj3XjGkjJcxy_ zEHE2tggSS!d((FFN}}FF@JOioTC-l@hHI8;RXU8AZ(@2Pqqh|xFL~yGa5g+5Uxm+# z>4BSp%YEW^8{|t5a>DVEB=t(%CjjOzQn%tXa@W`edAh^0r=;axArc8PF4Jf&-8oLx z1izt(iF7ZB-=@fPe3%4AL=|I^e?;6!BcaxEj}<7qEJ1(h%;0=pAhE6Uqf(-b!ciO~ zi%}wzNrxE%8J|Ws3Jl&e4nG_Y9}}LwzbM^2X3sDM^Qh@awM-%Fb?6>!d3=9lA;ESP0ViZuITIp4Pneh;TU zFmvy!{?^7~)m@yCZe+~SAi^kczqM7+f}?W$8y^#y7(MlDv8QcBIWREQ=rbxo-;#+! z8|V8Ze!xTYGm!micPIDDv1P6=uB_LWiybCkl#?Xv^a9gzpIP_<?tV&6J==8>F8ilj`Cn(s;yT`g@x2GR8rLf#8Qb#+}Y z#KxWZ3SLBoUcw7O#&&5QQBh}cS|(|LCUMRPm z3wtE98p1PplNEGcYXBR&&cT%Id$q`b;l_b4nxpM@7^40l=??gSmvxDPvzDya<5Y0F zL*PF(*e?6Cx)3CR3z(0b)(cxAWE(0Yt2=f+eO(a#OW70##5G9h-{P! zm@~HQp0H(ECr8Z`uqZzP+;0DZ38Dp>&KNG!6K<(Bk0P)|-c?)Enelre0a4PqQA);% z>e4MY_h5xXGv^1z;~$ZO4&kn04ct#J>{f8tD<;XW1p^=2BN?bTw!KlommeIyXmXy6|h%D0q}9bt8@5SNe6acXqwT{$FH&=|M^&5L0i^(7DlS#nzg8kU!?9JU^pG4 zV@&I&iKkb^oW~gdPDy(wPw89PGhypMV$g!)1IID5JbZaC(NtzxO)^JwATL!`7bc)~ zf*4wYILiPBUFQrt*V~`(Myo}OTv!wQK!F~L;qzqn0%V5JoqECScKPCDMigTbA zTSNs|4LN}aXCetwp?~2O8C-F@kFiRs%i9MYM|e%o+oWgN5k(J>*Zqt4YISxc<|xiq zV)k(&*XsowJfL6XC)o>W?*son3^Pb0Dh1APM}8s$h)ZhXJN_krnHnNuZSz(|WAm+O z!T&igb4@p`aBQrkN}X()DjpH5{ZfUMi0C*G4|f z7bY@{%6ev+3-$tub{=5chrA7D2Ei`!VI^^*(H_^iI0WZcd^fqeI`nRdT5JFx-getP z)*gS$l+=5fe^|%d^XQ@A&HIg^8!*=D&7-u@&MWvQCl6`QL&}^t)J+2RDk#)uB@R&= zWHOKBrs4K;7QNSBj7S-fNyRi3+SMg8N-4?EsGvF#CxF&az?Lx&8X^KxE)yGvY!68o zVBj!9xj!T|q-%*NB!|YFp0nXbr1%qHcWy5`n<%Q^`J^Q<5%SOoAAW@W*P{z|Tkm7C z*SPeMmEiB*j-Mo2!waRq!k}3WqzV8=V<5S>6xF*2U8j`CpbHsZ-}Vq z!8dFI6Rc2u*F9zk*Q;&N-$~?vTmy$GL3x;UM*38H@9_J~RbBP#)kd(yY{XnvTGHXx z$1GwF-x>GM3%(7ZpvQo4$lYI=uGv*=Au+0mPk9=pZT;wWoSXBO;fqkCk9RiB?)^$}0RXVSG9Xdws&bv5ecM%45&G5V!Xr)LIHj)dKE@QLNtg;%zedobhr)qca*m zvaiw#G0horYJ*IFB!(9BElAGmSI|amWetM8HD2t1y}YgV>Zw(0HLIVPp`I@M&~$IU zAOyB^1Rg8!&B*=^hUJQf?tyF#(_%l7!xx%9ymo48Lj!>bb|r;4jQXmAp)7?@Fj&JF zfhXgZFI%}Cy>1!jhXeWdRG=Vu@hC27(kz*}FHpX$5@oV0-#3doiDviwvx{vo z2A43z*ezxW;SU{083-b@I*OFQ9#+D|@0qF?5A&qXK-wos_7o=vXwN6vIWnZBryZ{w zI>PTE3ShjLXBOboI&xNtD|M>2K)(6Qq4ddJ|n%8{-_>@OLZ`qN=ZnIHsz zqOEuYI_>R!kzZeIM!A=hnL^$2Al8K|l2#;$unKeED{ZO@(l{P?=zk{eT=s*I8Gj%K z-%>AgEGc_*Wgt=~C>dfZZE777G0Fp|EvSEUx&TNL7sTEQ(!M$@bR4Bd)cDn*#Efgp zD^c(7Y5U*5{&wBhs()C`?sF;JV6r^W-|!P?pOA*7BSRO{;Zb(PQJ21=HyawyZ4j z)l5Acj(BHR`K9z`1P}hZxAj?{l?PVl(m@N9Y0^5Jx3MA>`L9g?XBfn_{`u^&y~nr& zsYEf4oLSSslnCPvti2V!u;5u`RCuw@I3ay7b_CJyfE}xIK0r|~rbGYshj6f(A)KLM zdEbv^r=BnM0Pep6o_zYtd8KsvUs3l0yWhS7H?tf;noWjqp7B~L{5AxFPmC3VND*ev zMtzkIGJ!7aCFe3c86mov-jrz_f?@jP8=7|boZ8b9uv8$y-acOk>pqU$`n+6cMTryG zrM-HwDSrBoEI!KNVM0#GSW9~-j)M!<-D{O^9KTu9<7^1Yfj;Je;Y#iMvgF{6O!2x@ zdCOuEm8SKl#P^#gM|!t`m`OA)uunAlUwR4m?w~;Tkoma3 zW}LlR%fGP&>?t_89Gq=I%MR2^qGR&?LbOWkeZfQMMO@aWB!{5wzg|yLZ@iyV90y=1 zHqLlI0%g;1tQLuqerU<#@7csu$YBZn6;~CH2JJ4%0rQ9KF|EzA7CmN4Fj3qIwL3>8 zJu-caeQ2jQJ%0Z<5$M%%`-DFp#MIeK6?r8`@{^n9Xws)YkpeXy}q#jrX-($^sm)-^jv>(_1IMz?u z^t(s()5Fl-z`%j%reE-Iyr(A%&eixygbp6)%I${?LiB8vpByhfTS+~s5dAi>NlBa$ zqP*fH;Dn#atOL*c{mL-c>9b2k_2X_D-=94~b(T97o4myvWa%(Nu#O&@|HMO-ShxOuI;nRj-x z^LV-&tt7pz$`c3WOWrC9MIZ?qSu(Vnkc8KDK6=Int1Q_nsBx^4LVk+&% zpJ;U>j=dy(;~=2i8Zvq|8Dqf2ix>xUJFas7b4VsHu=az5OyUe%*o-j9Uf%PGE+QKQijv9Bwtt~DdIJk?+#U- zxBTPuX>&rr=Pft5EV*N6`Y=FxLxaxb1+zTIC!wC0;2SqcFxWLukaV^wOm3zg1anBz zqeONZw^KVbFu|gu* zXB7YX0Lw?EdhJsVCmn8gU=+MYCa9wD{<*d4T6_yg7-MLyB61%UUSvRlWX%BFA6{0e zb!sW>l>YsRiNUpUBeaYbI&}4>esp(a@ViGQJ*LCNHo~u4h-1a>dhd_MnCIV&IF4`? z(SM@#ges4*)2_1=*^Z6=X$ai>9oudrIM>D*f%mAKJUa(uD|u=77|7${$qX zWN|1=vrDkt^%{oxUQx!si}@g0qX&ksiEyM|A;wKbp1}e~cVPfw+$)-oFyQ_~-T?)&@CPByrkImLFRy zLvP|@anYe6fJEgVWO;;zVJq0+h!dsWcW@(EobakUQE0~v^|zHQA2on{;3@C8&#k@GSPhRY3_gqF z>d)5S%HKKY+`Q=DaW{RUhQ`t2%k(<%Lr!;fPbth<<7B8yO)hv5FXl&wLSi>`Tcvw%8$jiUpeI2;DiXGFfz;gFa^?0 z+$DkhY_r{vJZ&Ta&7y@umG@6)0!@Hu8r-#XortftJxxQ!F?<3D>r?r&(<5!L#gtbM zo)JO0^)aES;HbDLL!b&ai`n3qG+wf@$qkDB1Qf*tfo2A)U_lTMV^3gGLZmwj0)-}SWimiiogOm! z9V0?oH1N8|j(|Y`42-Qa$QOBjVqw%$LXUNq!2Po_na=5-*i>;U$PJIeMU`O*dPp0Z z@%4^Dt1-vH$#^IYSd>6T_H!*S1t{FC@@T)Ym}he66-pGbpNB+%(1HI9l{G3XV$vp6 z{~PdIMr3YBgf}#gIiVjOgL5h5o}Et3^&D8UfyXTs!RyFYSH;*|goz+sDPe{5ppJiD zPE%wKWcd+xPL#+hAw3$Ph2osuN{{}R_a3{yPtL_^QiUVqjM6s{MD2!f6?6HYS7e8m z!R8E4c}9A#EX4=m4;_>1x?vH-v1LDKVQcq1j2s^acC+GTFjhsJm$r(}LNU*VSYqaMCI(xjRjcR~6%!XpT zcR`LNzl2>tMb1inp;OahkC^1u?=>ixDZ#ottLA9p_rBlW-oUwH&n4^YtjNbyRl-4z ziW%_{?+TGx5Cyd=jeQ=W&Q|zbzp;;3(vJH1TBbbat1`oIa9NW|{3;P4dzQfm`*Z0Xu@1vpcRma zhHe1^l+A;Ul~b~%iOAxwKwcCrb?1UrN3~zlN`-i?ZP327BQF2g8^jDSO+iB>|9fl+rohp=u^nVxFLR7Si3( zMj+G#6qAEOA=Wv!S~1FM!ctTO9u=Yvf(wWVXW@Oz4xs)|b&-C1qAtfpfsd?NIw%|^ z6N&D|E~Et;l(p$@&j0)curNBlOJN`UD`5;jOdWfnosy8XB&AspfU1vV`%RY9%-JHL z%S%j7$EWW0Mb5O_OO>{U59kB?21JX)AUOZ8bXEnpXN#nW!2*~GEIE9m;C4oLGKB=& zJtb85L#$&+ibAzL^30*FhU`_AwE5Ef;cdm8UWrvppa?@bbLa;jQtX_`02SzBq7-_LM!7|To|HW-zypTYKEa!sg z1ti+)kYYh}Dgr*3fVN ziaPcl`?jCAd>%hM9@I}^H6|aSf#FdlX4*=`Fbs6o5;!5^N8D8Q6gc!aCU%YaZPwNs z>WhlxY;XnUi|lPMmD3b^RXa$%0000G0Nklk>1)g+(NY|PR#GsKa(YW0=*>A4SGA-fpews3Xq#r;hMDKwNh+pOZ5OJ1wGchM360b_ z@JE&`Su%9Q;fH^3+4AMD(9qAFHQT;Jx#z6Ml%88nY(NC|Yf9LpSI1wuWYOa5p0Rwn zUh)~#n!sjnvE7|JTB#Xm$|bj<@A0#1k|XjXVOsSiX! z%gIhu-bHW&(X=W*lQo!DwOzFClq+1PXj>5)Ji@MP2k<-2&niLHo}p%szEU=HK(B7Yq^bj@C(4XB$dYVaUYEITo@VWM{*ev`+s;mgOGQT(w?JgKVl*Mo z$Rer}_)X+xUv&|Li*^$lWwG)LIXjY8xX?syY*e@22aZ1K$bNmY_QK;&c=m5xeDTFw zalZEbf3BgwwM6Fj&$)?8{h74i*|vShd-X@47xNr|Ua8_LVZgS;ZlsPeZD0ebY>gjC z*}w?3HuBI2Cq}z~cJYH2CdRd4YOsQNK(cML>$b2gMylbPs9jou85|@V5t1V`GO&U} z25?FfP|GB@t2C;sszKf4;YHbX`ddoxy7}gtFATyz|FB=___V)9fTW2geQZkTZ~cA$ z+0TCV=k(mbTx}LTSKrGW(ib}V^m(*VLYrPuJ4@GWNvFCei?{@|Kurg^Xxr&v&Z;*` z;8B2wQ7WmHPB@{hqfNAH=r?6()Ow?EXj=wpVN``&77BD)R|9q9KyUQ7$3<*hn`vcS zFUR)JpEs{xf16-<>5|1CKlHFee{2sBsu^5oQ0 zPd#z_)~#>Zv2)iMniiJut$kkpi0}7}vXiXgEX?knf+a+E;u@_rdJM%~(bY-~!U5Ql z#(NPAIH^+??Yh830xb{&qGSAzzy+x4s8hDd2nNx~NuazfkX53uXH@#wL-F4eI!G^# z%$Ym)QB9wh&6_jtBj3338@GeowPm*5U+0b~_7}+sbfC|);6V7bm%VJkqdRuIeCw7i zuiCL=*DsCi8Cj;MjAsn%9sDtUzsI*$b?415p4eJxNXTHpO1sn3GTS<`IzYJbCNgE( z5hT$cfdh2e!4`zWadL}^CM;M`XE?=`}6d42SCb75WuV1u+Tzg@T#k> zI%;^wj%5mfBeXp zPK70py17#62abt}NI!px6M6J6@i_a7>6MN7TRdc~g4H@V&V1zyh5~HcK>yJC{-ORg zx{-7LYv#V@!E?WPu6I%^I*!NbjXD+nzx~PU18I@-+5h$m?MDR$80tmu7u6~Eqv-oa z3PtG<1E-bK22ax#H`|(=1>0{wXiuhB@0%N*yeH%Qta7*Q&%*gxaPvaP`V$@w_n@Hj zbegunv<0RuFl~Wp3rt&J+5*!Sn6|*Q1*R=9ZGmYEOj}^u0@D_lw!pLnrY-O^S>S&G XL@r?;NJ)r*00000NkvXXu0mjfk|&GJ literal 0 HcmV?d00001 diff --git a/desktop/src/ui/components/EngineIcon.tsx b/desktop/src/ui/components/EngineIcon.tsx index 2d34383b3..dc440b86e 100644 --- a/desktop/src/ui/components/EngineIcon.tsx +++ b/desktop/src/ui/components/EngineIcon.tsx @@ -8,17 +8,19 @@ import ollamaIcon from '@/ui/assets/engine-icons/ollama.png?inline' import lmStudioIcon from '@/ui/assets/engine-icons/lm-studio.png?inline' import llamaCppIcon from '@/ui/assets/engine-icons/llama-cpp.svg?inline' import vllmIcon from '@/ui/assets/engine-icons/vllm.svg?inline' +import mtplxIcon from '@/ui/assets/engine-icons/mtplx.png?inline' -const engineIcons: Record = { +const engineIcons: Partial> = { ollama: ollamaIcon, 'lm-studio': lmStudioIcon, 'llama-cpp': llamaCppIcon, - vllm: vllmIcon + vllm: vllmIcon, + mtplx: mtplxIcon } export default function EngineIcon({ type, size = 32 }: { type: EngineType; size?: number }) { - if (!Object.hasOwn(engineIcons, type)) return null const icon = engineIcons[type] + if (icon === undefined) return null const dimension = `${size}px` const imgStyle: CSSProperties = { diff --git a/desktop/src/ui/constants/engine-capabilities.ts b/desktop/src/ui/constants/engine-capabilities.ts index 40c7fe93f..d04f44791 100644 --- a/desktop/src/ui/constants/engine-capabilities.ts +++ b/desktop/src/ui/constants/engine-capabilities.ts @@ -87,5 +87,40 @@ export const EngineCapabilities: Record = { label: 'vLLM', url: 'https://huggingface.co/models?pipeline_tag=text-generation&library=safetensors&sort=trending' } + }, + mtplx: { + hasExpiry: false, + // MTPLX serves one pack per process and cannot drop it while running, so + // Eject stops the engine and Load starts it again on the chosen pack. + hasEject: true, + // Detect-only, and Apple Silicon only: PAIR drives the `mtplx` CLI of an + // install the user made themselves and never installs or uninstalls it. + // An empty list means no auto-install, and `getWelcomeEngineCandidates` + // leaves the engine out of onboarding rather than showing an install row + // that cannot be fulfilled. + hasInstall: [], + hasEnginePort: true, + hasInstallPath: false, + hasProxyWebUI: false, + hasPreferredNode: false, + hasCrashAlert: false, + // Packs live in MTPLX's own pack cache and its curated list is fetched, so + // the model list, Add model, Delete and Load all work while the engine is + // stopped (Load starts it): MTPLX is listed in `EnginesListingModelsWhenStopped` + // and its list comes from `mtplx models --json`, which answers offline. + hasModelSearchOnlyWhenRunning: false, + hasDeleteModel: true, + // `mtplx remove` has no in-use guard, and a stopped engine keeps the + // deleted pack in its launch arguments, so Delete is refused on the pack + // being served: eject first. + deleteBlockedWhileLoaded: true, + // Load rewrites the model launch flags and restarts MTPLX on them. + loadRestartsEngine: true, + // MTPLX only runs packs built for it, and that list is the only place + // they are named, so the hub lists those rather than any safetensors repo. + engineHub: { + label: 'MTPLX', + url: 'https://mtplx.com/releases/models.json' + } } } diff --git a/desktop/src/ui/constants/welcome.ts b/desktop/src/ui/constants/welcome.ts index d235f8d03..12a449510 100644 --- a/desktop/src/ui/constants/welcome.ts +++ b/desktop/src/ui/constants/welcome.ts @@ -11,7 +11,13 @@ export const WELCOME_STEP_HEADINGS = ["Welcome, let's get you set up", 'Install export const WELCOME_STEP_SUB_HEADINGS = ['', 'You can update later by clicking on a node'] as const -export const WELCOME_ENGINE_DEFAULT_SELECTED: Record = { +/** + * Which engines arrive preselected in the onboarding list. An engine that cannot + * be auto-installed is never offered there — `getWelcomeEngineCandidates` drops + * anything with no installable platform — so MTPLX needs no entry, and a missing + * entry reads as not selected. + */ +export const WELCOME_ENGINE_DEFAULT_SELECTED: Partial> = { ollama: true, 'lm-studio': true, 'llama-cpp': true, diff --git a/desktop/src/ui/stores/pending-actions.store.ts b/desktop/src/ui/stores/pending-actions.store.ts index fd2cbadc8..a094bcd5b 100644 --- a/desktop/src/ui/stores/pending-actions.store.ts +++ b/desktop/src/ui/stores/pending-actions.store.ts @@ -40,8 +40,12 @@ import { useEngineStatusStore } from '@/ui/stores/engine-status.store' const PENDING_TIMEOUT_MS = 60_000 /** Keep Ollama Load locked one safety-net interval beyond the longest (31m) backend path. */ const OLLAMA_LOAD_PENDING_TIMEOUT_MS = 32 * 60_000 -/** vLLM Load restarts the engine on the new model; keep the row locked as long as the app waits for it. */ -const VLLM_LOAD_PENDING_TIMEOUT_MS = MODEL_SWITCH_TIMEOUT_MS +/** + * Keep a Load locked as long as the app waits for it. This is the timeout of a + * Load that restarts the engine on the new model (`loadRestartsEngine`): vLLM and + * MTPLX both serve one model per process, so loading means restarting on it. + */ +const RESTART_LOAD_PENDING_TIMEOUT_MS = MODEL_SWITCH_TIMEOUT_MS /** * Safety net for a delete on an engine whose backend restarts to pick the * deletion up (`EngineCaps.restartsOnModelDelete` / the manifest's @@ -107,15 +111,15 @@ interface PendingAction { /** * How long the safety net waits for a command before re-enabling its control. - * Slow Ollama loads and restart-backed deletes outlast the default net; every - * other command keeps 60 seconds. + * Slow Ollama loads and restart-backed Loads or deletes outlast the default net; + * every other command keeps 60 seconds. */ function timeoutFor(command: EngineCommandType, engineType: EngineType): number { if (command === 'loadModel' && engineType === 'ollama') { return OLLAMA_LOAD_PENDING_TIMEOUT_MS } - if (command === 'loadModel' && engineType === 'vllm') { - return VLLM_LOAD_PENDING_TIMEOUT_MS + if (command === 'loadModel' && EngineCapabilities[engineType]?.loadRestartsEngine) { + return RESTART_LOAD_PENDING_TIMEOUT_MS } if (command === 'deleteModel' && EngineCapabilities[engineType]?.restartsOnModelDelete) { return RESTART_DELETE_TIMEOUT_MS diff --git a/desktop/src/ui/utils/match-downloaded-model.ts b/desktop/src/ui/utils/match-downloaded-model.ts index 57610cf15..0a371a503 100644 --- a/desktop/src/ui/utils/match-downloaded-model.ts +++ b/desktop/src/ui/utils/match-downloaded-model.ts @@ -19,6 +19,8 @@ import type { ModelEntry } from '@/ui/types/model-hub' * `//`); the hub id is `/`. * - llama.cpp: router inventory and catalog use the same complete * `/:` id, so only exact ids match. + * - MTPLX: a pack is a Hugging Face repo id and MTPLX serves that id + * verbatim, so only exact ids match. */ type DownloadedMatcher = (hubEntry: ModelEntry, downloaded: ModelItem) => boolean @@ -44,7 +46,8 @@ const MATCHERS: Partial> = { ollama: matchOllama, 'lm-studio': matchHfPullKeyOrName, 'llama-cpp': matchExactName, - vllm: matchExactName + vllm: matchExactName, + mtplx: matchExactName } export function isHubEntryDownloaded( diff --git a/desktop/tests/modular/engine-identity.test.ts b/desktop/tests/modular/engine-identity.test.ts index 2f400ac6d..5179fb007 100644 --- a/desktop/tests/modular/engine-identity.test.ts +++ b/desktop/tests/modular/engine-identity.test.ts @@ -16,8 +16,8 @@ import { gatewayEndpointDisplayUrl } from '@/ui/utils/gateway-inference-paths' describe('engine identity', () => { it('enables llama.cpp workflows on every platform', () => { - expect(EngineTypes).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm']) - expect(EnabledEngineTypes).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm']) + expect(EngineTypes).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm', 'mtplx']) + expect(EnabledEngineTypes).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm', 'mtplx']) expect(getWelcomeEngineCandidates('Windows')).toContain('llama-cpp') expect(getWelcomeEngineCandidates('MacOS')).toContain('llama-cpp') expect(getWelcomeEngineCandidates('Linux')).toContain('llama-cpp') @@ -58,6 +58,38 @@ describe('engine identity', () => { }) }) + it('maps MTPLX to its engine-manager wire id and one-pack-per-process capabilities', () => { + expect(EngineManagerNames.mtplx).toBe('mtplx') + expect(engineManagerName('mtplx')).toBe('mtplx') + expect(engineTypeFromManagerName('mtplx')).toBe('mtplx') + expect(isEngineType('mtplx')).toBe(true) + expect(EngineDisplayNames.mtplx).toBe('MTPLX') + // MTPLX serves one pack per process, the way vLLM serves one model: Eject + // stops the engine and Load starts it again on the chosen pack. Its manifest + // declares only darwin/arm64 and declares no installer, so PAIR drives an + // engine the user installed and never offers to install one. + expect(EngineCapabilities.mtplx).toMatchObject({ + hasEject: true, + hasModelSearchOnlyWhenRunning: false, + hasDeleteModel: true, + deleteBlockedWhileLoaded: true, + loadRestartsEngine: true, + hasInstall: [], + hasEnginePort: true, + engineHub: { label: 'MTPLX' } + }) + }) + + it('keeps MTPLX out of onboarding because nothing is installable for it', () => { + // A source with no installable platform is dropped from the onboarding list + // rather than shown as a row the user cannot act on, and nothing is + // preselected for it. + for (const platform of ['Windows', 'MacOS', 'Linux'] as const) { + expect(getWelcomeEngineCandidates(platform)).not.toContain('mtplx') + } + expect(WELCOME_ENGINE_DEFAULT_SELECTED.mtplx).toBeUndefined() + }) + it('maps the desktop id to the sole engine-manager wire id', () => { expect(EngineManagerNames['llama-cpp']).toBe('llamacpp') expect(engineManagerName('llama-cpp')).toBe('llamacpp') diff --git a/desktop/tests/modular/inference-demo-lifecycle.test.ts b/desktop/tests/modular/inference-demo-lifecycle.test.ts index f355a7663..9c2c0d75d 100644 --- a/desktop/tests/modular/inference-demo-lifecycle.test.ts +++ b/desktop/tests/modular/inference-demo-lifecycle.test.ts @@ -46,12 +46,18 @@ const POISONED_ENV: Record = { Inference_Dispatcher_Debug_Error_Log: '/tmp/leak.log' } -/** Proxy ports the fake broker reports. Mutable so a test can withhold one. */ +/** + * Proxy ports the fake broker reports. Mutable so a test can withhold one. + * `DEMO_ENGINE_PROBES` fixes which facades the demo may dial — vLLM and MTPLX + * report ports here, as a broker on Apple Silicon would, and the demo still + * never probes them. + */ const proxyPorts: Record = { ollama: 11434, 'lm-studio': 1234, 'llama-cpp': 8080, - vllm: 8000 + vllm: 8000, + mtplx: 8100 } /** Model inventory each probe returns. Mutable so a test can return none. */ diff --git a/desktop/tests/modular/proxy-engine-identity.test.ts b/desktop/tests/modular/proxy-engine-identity.test.ts index 5c4e75fbb..eb7d67d86 100644 --- a/desktop/tests/modular/proxy-engine-identity.test.ts +++ b/desktop/tests/modular/proxy-engine-identity.test.ts @@ -19,17 +19,19 @@ import { engineManagerName } from '@/shared/utils/engines' describe('proxy engine identity', () => { it('declares the complete proxy set in stable order', () => { - expect(PROXY_ENGINES).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm']) + expect(PROXY_ENGINES).toEqual(['ollama', 'lm-studio', 'llama-cpp', 'vllm', 'mtplx']) expect(PROXY_NODE_SOURCES).toEqual([ 'ollama-proxy', 'lmstudio-proxy', 'llamacpp-proxy', - 'vllm-proxy' + 'vllm-proxy', + 'mtplx-proxy' ]) expect(isProxyEngine('ollama')).toBe(true) expect(isProxyEngine('lm-studio')).toBe(true) expect(isProxyEngine('llama-cpp')).toBe(true) expect(isProxyEngine('vllm')).toBe(true) + expect(isProxyEngine('mtplx')).toBe(true) }) it('round-trips engine, manager, and relay source identities', () => { @@ -87,6 +89,22 @@ describe('proxy engine identity', () => { ip: '192.0.2.40' } }) + state.handleNotification({ + source: 'mtplx-proxy', + method: 'ready', + params: { port: 8100 } + }) + state.handleNotification({ + source: 'mtplx-proxy', + method: 'node/discovered', + params: { + id: nodeId, + host: 'proxy-identity-host', + port: 8100, + addresses: ['192.0.2.40'], + ip: '192.0.2.40' + } + }) state.handleNotification({ source: 'broker', method: 'discovery:nodes-changed', @@ -107,6 +125,8 @@ describe('proxy engine identity', () => { } }) // A peer lists every engine it can run; one it leaves out is unsupported. + // This peer is Apple Silicon, so it lists MTPLX too, running on 8101 + // behind the 8100 facade. state.applyRemoteEngineFacts(nodeId, { engines: [ { engine: 'ollama', installed: true, running: true, healthy: true, port: 11435 }, @@ -118,7 +138,8 @@ describe('proxy engine identity', () => { healthy: true, port: 8081 }, - { engine: 'vllm', installed: false, running: false, healthy: false, port: 0 } + { engine: 'vllm', installed: false, running: false, healthy: false, port: 0 }, + { engine: 'mtplx', installed: true, running: true, healthy: true, port: 8101 } ] }) @@ -142,7 +163,13 @@ describe('proxy engine identity', () => { enginePort: 8081, proxyPort: 8080 }), - expect.objectContaining({ engineType: 'vllm', processStatus: 'not-installed' }) + expect.objectContaining({ engineType: 'vllm', processStatus: 'not-installed' }), + expect.objectContaining({ + engineType: 'mtplx', + processStatus: 'running', + enginePort: 8101, + proxyPort: 8100 + }) ]) const llamaModels = state diff --git a/desktop/tests/modular/unsupported-engine.test.ts b/desktop/tests/modular/unsupported-engine.test.ts index b60ea23fe..c7e3970ac 100644 --- a/desktop/tests/modular/unsupported-engine.test.ts +++ b/desktop/tests/modular/unsupported-engine.test.ts @@ -11,7 +11,7 @@ import { getModularBridgeState } from '@/electron/service-bridge/modular-state' import { getEnginesForNode } from '@/ui/utils/get-engines-for-node' // An engine manager lists only the engines its host can run. On Windows the -// listing has no vLLM, the way these do. +// listing has no vLLM and no MTPLX, the way these do. const windowsListing = { engines: [ { engine: 'ollama', installed: true, running: true, healthy: true, port: 11434 }, @@ -44,6 +44,11 @@ describe('engines a node cannot run', () => { state.applyEngineManagerList(windowsListing) expect(statusOf('windows-self', 'vllm')).toMatchObject({ processStatus: 'unsupported' }) + // MTPLX declares only darwin/arm64, so a Windows host leaves it out of its + // listing the same way it leaves vLLM out. + expect(statusOf('windows-self', 'mtplx')).toMatchObject({ + processStatus: 'unsupported' + }) expect(statusOf('windows-self', 'lm-studio')).toMatchObject({ processStatus: 'not-installed' }) @@ -73,6 +78,7 @@ describe('engines a node cannot run', () => { state.applyRemoteEngineFacts(peerId, windowsListing) expect(statusOf(peerId, 'vllm')).toMatchObject({ processStatus: 'unsupported' }) + expect(statusOf(peerId, 'mtplx')).toMatchObject({ processStatus: 'unsupported' }) expect(statusOf(peerId, 'lm-studio')).toMatchObject({ processStatus: 'not-installed' }) }) @@ -100,6 +106,7 @@ describe('engines a node cannot run', () => { state.applyRemoteEngineFacts(peerId, { engines: [] }) expect(statusOf(peerId, 'vllm')).toBeUndefined() + expect(statusOf(peerId, 'mtplx')).toBeUndefined() }) it('gives an unsupported engine no row, and keeps one for an unreported engine', () => { @@ -123,10 +130,13 @@ describe('engines a node cannot run', () => { const rows = getEnginesForNode(nodeId, statuses).map(s => [s.engineType, s.processStatus]) + // vLLM is reported unsupported, so it gets no row. MTPLX is reported + // neither way here, which keeps a placeholder row until evidence arrives. expect(rows).toEqual([ ['ollama', 'running'], ['lm-studio', 'initializing'], - ['llama-cpp', 'initializing'] + ['llama-cpp', 'initializing'], + ['mtplx', 'initializing'] ]) }) }) diff --git a/docs/architecture.mdx b/docs/architecture.mdx index d066d723b..cb79af9a9 100644 --- a/docs/architecture.mdx +++ b/docs/architecture.mdx @@ -46,8 +46,8 @@ flowchart TB primary, and membership is symmetric. A node belongs to at most one cluster. - A **node** is one machine. Nodes are peers where each runs the same services, and each can both serve requests and route them elsewhere. -- An **engine** is an inference server on a node: Ollama, LM Studio, or - llama.cpp. A node can run any combination, and a node with no running engine +- An **engine** is an inference server on a node: Ollama, LM Studio, llama.cpp, + vLLM, or MTPLX. A node can run any combination, and a node with no running engine is not eligible to serve. - **Models** belong to an engine on a specific node. Nothing is shared. The same model on two nodes is two independent copies and that duplication is what makes @@ -478,10 +478,10 @@ sits one place lower in the order. to an engine's own port is absent from workload events. GPU-heavy external work can still raise pressure, but CPU-only work and queued demand remain invisible. -**All engines are counted as one pool.** Ollama, LM Studio, and llama.cpp load is -summed, and maximum GPU pressure applies node-wide. This is conservative on a -typical single-GPU machine and can underuse a multi-GPU node where the engines -occupy different devices. +**All engines are counted as one pool.** Ollama, LM Studio, llama.cpp, vLLM, and +MTPLX load is summed, and maximum GPU pressure applies node-wide. This is +conservative on a typical single-GPU machine and can underuse a multi-GPU node +where the engines occupy different devices. **Every node ranks from its own view, and views lag.** There is no shared schedule. Two nodes dispatching at the same moment can briefly steer work to the @@ -543,6 +543,11 @@ the engine moves behind it. Ollama moves to `11435` and upwards, and LM Studio moves to `1235` and upwards. The managed llama.cpp router stays on `8081` while its facade takes `8080`. Existing clients keep working untouched and transparently gain the cluster. +MTPLX has no compatibility port to inherit. Its facade takes `8100` and the +managed `mtplx serve` behind it listens on `8101`. That avoids `8000`, which is +MTPLX's own default but already the vLLM facade's port, on the one platform where +both engines can be installed. + This is also what makes the engine unreachable from outside. Engines PAIR starts bind to loopback, so the only network-facing listener is the proxy, which is where cluster authentication lives. @@ -581,6 +586,8 @@ A default installation listens on these ports: | `11434` | Ollama-compatible proxy (Ollama itself moves to `11435`+) | | `1234` | OpenAI-compatible proxy (LM Studio moves to `1235`+) | | `8080` | OpenAI-compatible llama.cpp proxy (managed router on `8081`) | +| `8000` | OpenAI-compatible vLLM proxy (managed vLLM on `8001`) | +| `8100` | OpenAI-compatible MTPLX proxy (managed `mtplx serve` on `8101`) | | `14318` | Public hardware displays and peer node inventory | | `14319` | Service-error synchronization between nodes | | `14320` | Workload propagation between nodes | diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index a6ef99675..216553f65 100644 --- a/docs/engine-lifecycle.mdx +++ b/docs/engine-lifecycle.mdx @@ -1,6 +1,6 @@ --- title: Managing Engines in NVIDIA PAIR -description: Install, start, stop, update, and remove the Ollama, LM Studio, and llama.cpp engines that NVIDIA PAIR uses to run models. +description: Install, start, stop, update, and remove the Ollama, LM Studio, llama.cpp, vLLM, and MTPLX engines that NVIDIA PAIR uses to run models. --- {/* @@ -9,7 +9,7 @@ SPDX-License-Identifier: Apache-2.0 */} An **engine** is the local inference runtime NVIDIA PAIR uses to -run models. Today that means Ollama, LM Studio, llama.cpp, or vLLM on a given machine. +run models. Today that means Ollama, LM Studio, llama.cpp, vLLM or MTPLX on a given machine. PAIR can install and run those engines for you, or work with a supported existing Ollama or LM Studio installation. This page explains what you can expect when you install, start, stop, or remove an engine, and how to move one @@ -146,6 +146,23 @@ When you install an engine, consider the following: does not unload automatically after inactivity. Use **Eject** to release its memory. +- MTPLX runs on Apple Silicon Macs only, and PAIR never installs it. Where a + `mtplx` install is found at a known location, PAIR drives it: it starts and stops + `mtplx serve`, lists the packs already in `~/.mtplx/models`, and downloads or + deletes packs with `mtplx pull` and `mtplx remove`. Nothing is installed, and an + uninstall or a data reset leaves MTPLX and its packs alone, so first-run setup + never offers it. Like vLLM it serves one pack per process, so **Load** restarts + the engine on the pack you pick and **Eject** stops it. A bare **Start** refuses + with a message to load a model, because nothing in the launch arguments names + one. **Add model** browses the pack list MTPLX publishes rather than searching + Hugging Face, because the engine runs only packs rebuilt for its own decode + path, and that short list is filtered on your machine instead of searched. A + download or a delete says only that it is running, with no percentage. + MTPLX has no in-use guard, so **Delete** is blocked while a pack is being + served: eject it first, or you are deleting weights the running server still + has mapped. Only the pack being served is advertised to other nodes, so a request + naming a different cached pack is refused until you load it. + PAIR-managed llama.cpp models sleep after five minutes without inference work. This releases model and KV-cache memory, and the next request wakes the model automatically. The llama.cpp worker remains running and can retain some GPU @@ -202,14 +219,13 @@ on the machine. Uninstalling an engine does **not** remove its models. Downloaded model files stay on disk in the engine's own storage (`~/.ollama`, `~/.llamacpp`, -`~/.cache/huggingface`, or `~/.lmstudio/models`), so uninstalling and -reinstalling does not cost you -re-downloading them. The same is true of removing PAIR itself, or of resetting -its data. Both remove the engines PAIR installed as far as they can, and never -your models. A reset stops and tells you if an engine cannot be removed, while -uninstalling PAIR leaves that engine in place and finishes. To reclaim that -space, use **Delete** on individual models, or remove the engine's storage -directory yourself. +`~/.cache/huggingface`, `~/.lmstudio/models`, or `~/.mtplx/models`), so uninstalling +and reinstalling does not cost you re-downloading them. The same is true of removing +PAIR itself, or of resetting its data. Both remove the engines PAIR installed as far +as they can, and never your models. A reset stops and tells you if an engine cannot +be removed, while uninstalling PAIR leaves that engine in place and finishes. To +reclaim that space, use **Delete** on individual models, or remove the engine's +storage directory yourself. PAIR keeps the model folder at the engine's default location. If you moved LM Studio's models folder somewhere else inside `~/.lmstudio`, removing an LM @@ -326,7 +342,7 @@ uninstalls every model at once. Applications need a **running** engine plus an available model. Copy API URLs from **Endpoints** after an engine is running. Do not assume a fixed port such as -`11434`, `1234`, or `8080`. +`11434`, `1234`, `8080`, `8000`, or `8100`. ## Tips diff --git a/docs/engine-settings.mdx b/docs/engine-settings.mdx index ec12adde9..9c0b71d38 100644 --- a/docs/engine-settings.mdx +++ b/docs/engine-settings.mdx @@ -1,6 +1,6 @@ --- title: Engine Settings in NVIDIA PAIR -description: Change the server port, proxy port, and launch arguments of an Ollama, LM Studio, or llama.cpp engine in NVIDIA PAIR. +description: Change the server port, proxy port, and launch arguments of an Ollama, LM Studio, llama.cpp, vLLM, or MTPLX engine in NVIDIA PAIR. --- {/* @@ -8,7 +8,7 @@ SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All SPDX-License-Identifier: Apache-2.0 */} -Open a device's Ollama, LM Studio, llama.cpp, or vLLM row and expand **Settings**. +Open a device's Ollama, LM Studio, llama.cpp, vLLM, or MTPLX row and expand **Settings**. Edit the server port, proxy port, and engine arguments, then select the green **Apply** button. A paired device that supports settings can be edited from another device in the cluster. @@ -110,6 +110,7 @@ configuration consistent: | LM Studio | `--port`, `-p` | `--bind`, `LMS_SERVER_HOST` | `--cors` | | llama.cpp | `--port` | `--host` | `--cors-origins` | | vLLM | `--port` | `--host` | Not managed | +| MTPLX | `--port` | `--host` | Not managed | For LM Studio, `--port 1235`, `--port=1235`, `-p 1235`, `-p1235`, and `-p=1235` all synchronize the same server-port field. Conflicting repetitions and invalid @@ -150,6 +151,23 @@ tool calling stays off and vLLM answers a request that asks for tool calls with error. To choose a parser yourself, add `--tool-call-parser ` to the launch text. +MTPLX also serves one model per process, and only an Apple Silicon Mac has one. +Its launch arguments name that model with `--model ` and repeat the +same id as `--model-id`, so the name the server answers to is the name the model +list shows, and choosing a different pack restarts `mtplx serve` on it. PAIR adds +no sizing flags for MTPLX: there is no managed context length, memory share, or +request limit, so the pack and the engine settle those. A `--model` or +`--model-id` you write yourself is replaced with the pack you load rather than +duplicated, and any other argument is left alone. A launch that names no pack is +refused, with a message to load a model, because MTPLX cannot pick one by itself. +**Add model** lists the packs MTPLX publishes for its own decode path instead of +searching Hugging Face, because only those packs run on it. + +MTPLX asks for an API key only where one is configured, and PAIR configures none, +so a managed MTPLX is unauthenticated on loopback like the other OpenAI-compatible +endpoints. If you add `--api-key` to the launch text or run PAIR with +`MTPLX_API_KEY` set, the server demands that key and PAIR does not supply one. + Changing the server-port field updates the port in the command. Editing the command's port updates the numeric field. If both are edited before validation finishes, the numeric field takes precedence. The server and proxy must use diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx index 65cf0e437..a918e4a1e 100644 --- a/docs/getting-started.mdx +++ b/docs/getting-started.mdx @@ -37,7 +37,8 @@ Nothing else has to be in place first: - **Engines.** PAIR installs and starts Ollama, LM Studio, llama.cpp, or (on Linux or Apple Silicon macOS) vLLM for you in step 4. Existing Ollama and LM Studio installations can also be detected - and used. + and used, as can an existing MTPLX install on an Apple Silicon Mac. MTPLX is + never installed for you; it is used where it is already present. - **Models.** PAIR downloads models for you in step 4. A request needs only one eligible node, so a single node holding the model is enough. Prepare the same model on additional nodes when you want any of them to be able to serve it. @@ -206,8 +207,8 @@ which machine ends up doing the work. ### Why the Port May Not Be the One You Expect -PAIR places a proxy in front of each engine. The proxy uses the port that the -engine would normally listen on: +PAIR places a proxy in front of each engine. Where an engine has a port it is +commonly found on, the proxy takes that port: - `11434` for Ollama. - `1234` for LM Studio. @@ -217,6 +218,11 @@ engine would normally listen on: Tools already pointed at those ports keep working without reconfiguration, and the engine moves to the next free port. +MTPLX has no such port to take. Its proxy listens on `8100` and the engine +behind it on `8101`, because `8000`, which MTPLX itself defaults to, already +belongs to the vLLM proxy, and an Apple Silicon Mac is the one machine where +both engines can be installed. + Your application connects to PAIR's proxy, not directly to the engine. A port from a standalone engine installation can now lead somewhere else. Copy the URL from **Endpoints** instead of typing a port from memory. @@ -243,6 +249,7 @@ The engine therefore has to understand the style you send. | LM Studio | Works | Not available | | llama.cpp | Works | Not available | | vLLM | Works | Not available | +| MTPLX | Works | Not available | **If you are unsure, send the OpenAI-style request.** It works with every supported engine, and most tools and SDKs use it. Use the Ollama style @@ -309,22 +316,29 @@ work across several nodes at once. Refer to ## 7. Connecting Your Agents and Port Information -An application talks to PAIR's compatible proxy, not directly to an engine. The -proxy takes the port the engine would normally use, so existing clients keep -working without reconfiguration, and PAIR moves the engine itself to the next -free port. +An application talks to PAIR's compatible proxy, not directly to an engine. Where +an engine has a port it is commonly found on, the proxy takes that port, so +existing clients keep working without reconfiguration, and PAIR moves the engine +itself to the next free port. | What an Application Connects To | Default Port | | --- | --- | | Ollama-compatible proxy | `11434` | | LM Studio / OpenAI-compatible proxy | `1234` | | llama.cpp / OpenAI-compatible proxy | `8080` | +| vLLM / OpenAI-compatible proxy | `8000` | +| MTPLX / OpenAI-compatible and Anthropic proxy | `8100` | When PAIR takes one of those ports, the engine behind it moves: - Ollama moves to `11435` or higher. - LM Studio moves to `1235` or higher. - PAIR's managed llama.cpp router runs on `8081`. +- PAIR's managed vLLM runs on `8001`. + +MTPLX has no compatibility port to take, so its proxy keeps a pair of its own: +`8100` in front and `8101` for `mtplx serve` behind it. Refer to +[Why the Port May Not Be the One You Expect](#why-the-port-may-not-be-the-one-you-expect). **Endpoints** is the authoritative source for the URL to use. @@ -459,8 +473,10 @@ relative to the proxy URL, before the `/v1` suffix: | Ollama | `http://127.0.0.1:11434` | Ollama's own API (`/api/chat`, `/api/generate`, `/api/embed`, and `/api/tags`), plus the OpenAI-compatible and Anthropic APIs listed below | | LM Studio | `http://127.0.0.1:1234` | The OpenAI-compatible and Anthropic APIs listed below | | llama.cpp | `http://127.0.0.1:8080` | The OpenAI-compatible API listed below, plus `/models` for model listings | +| vLLM | `http://127.0.0.1:8000` | The OpenAI-compatible API listed below, plus `/v1/models` for model listings | +| MTPLX | `http://127.0.0.1:8100` | The OpenAI-compatible and Anthropic APIs listed below, plus `/v1/models` for model listings and `/v1/messages/count_tokens` for token counts | -All three endpoints expose these OpenAI-compatible paths: +Every endpoint exposes these OpenAI-compatible paths: - `POST /v1/chat/completions` — [Conversations](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) - `POST /v1/completions` — [Completions](https://developers.openai.com/api/reference/resources/completions/methods/create) @@ -468,9 +484,11 @@ All three endpoints expose these OpenAI-compatible paths: - `POST /v1/responses` — [Responses](https://developers.openai.com/api/reference/resources/responses/methods/create) - `GET /v1/models` — [available models](https://developers.openai.com/api/reference/resources/models/methods/list) -Ollama and LM Studio support the following Anthropic APIs: +The Ollama, LM Studio, and MTPLX endpoints take the Anthropic Messages API: - `POST /v1/messages` — [Messages](https://platform.claude.com/docs/en/api/messages/create) +MTPLX also answers `POST /v1/messages/count_tokens` for the model it is serving. + **Endpoints** includes `/v1` in the displayed and copied URL, so you can paste it directly into Hermes or another client that expects an OpenAI-compatible base URL, such as `http://127.0.0.1:11434/v1`. The client appends the rest of the path. @@ -578,6 +596,10 @@ It needs what any request needs: an engine running with a text-generation model available. If nothing local qualifies, PAIR tells you to start an engine and try again rather than starting a run that cannot go anywhere. +It probes the Ollama, LM Studio, and llama.cpp endpoints only, so a vLLM or MTPLX +endpoint takes no part in the run even when it is up and serving. Point a real +application at those. + It is a traffic generator, not a benchmark. It does not produce a score, show prompts or responses, or log prompts or responses. The run is local to the machine that started it. In a cluster, start it from the node whose routing you diff --git a/docs/overview.mdx b/docs/overview.mdx index b2f1ed6e8..abcd018ea 100644 --- a/docs/overview.mdx +++ b/docs/overview.mdx @@ -42,8 +42,10 @@ These terms have specific meanings in PAIR: - **Cluster** — the set of nodes you have paired together. A node belongs to at most one cluster, and it must leave before it can join another. - **Engine** — the local inference server that runs models: Ollama, LM Studio, - llama.cpp, or vLLM. PAIR can install, start, stop, and uninstall these engines. It can - also adopt supported existing Ollama and LM Studio installations. + llama.cpp, or vLLM, plus MTPLX on an Apple Silicon Mac. PAIR can install, start, + stop, and uninstall these engines. It can + also adopt supported existing Ollama and LM Studio installations, and it drives an + existing MTPLX install without ever installing one. - **Model** — what you prepare on each node. Nodes do not share models, so a node can serve a request only for a model it already holds. Preparing the same model on several nodes is what makes those nodes interchangeable. diff --git a/docs/terminal-interface.mdx b/docs/terminal-interface.mdx index f7ebf0728..4d7d28a7d 100644 --- a/docs/terminal-interface.mdx +++ b/docs/terminal-interface.mdx @@ -339,6 +339,12 @@ configured, and says why. The `LOADED` column reads `?` for an engine that cannot report which models are in memory. +vLLM and MTPLX serve one model per process, so on those two `enter` restarts the +engine on the model you pick and `e` stops the engine outright rather than only +freeing memory. Their downloads also run while the engine is stopped. MTPLX +refuses to start with no pack named, so downloading is the first thing you do +there. + Pressing `p` opens the catalog of models this engine can download. Press `/` to filter by name, family, parameter size, or tag, so both `llama` and `8b` narrow the list. Press `c` to clear the filter, `o` to change the sort between @@ -352,14 +358,22 @@ publishers, but it can download any GGUF model on Hugging Face, so there `/` searches all of Hugging Face instead of filtering the list. Press `c` to go back to the starting list. +MTPLX's catalog is the short list of packs published for its own decode path, +because only those packs run on it. There is nothing wider behind it, so `/` +filters that list instead of searching. + Press `n` instead if you already know exactly what you want and would rather type it. Each engine names models its own way: an Ollama tag such as `llama3.2`, a Hugging Face repository for LM Studio, a repository with its quantization -for llama.cpp, such as `ggml-org/gemma-3-1b-it-GGUF:Q4_K_M`, and a Hugging Face -repository for vLLM, such as `Qwen/Qwen3.5-4B`. Either way, progress appears on -the status line. Downloading needs a running engine, except with vLLM, which -downloads into the Hugging Face cache without its server: highlight it in the -Engines pane to download into it while it is stopped. +for llama.cpp, such as `ggml-org/gemma-3-1b-it-GGUF:Q4_K_M`, a Hugging Face +repository for vLLM, such as `Qwen/Qwen3.5-4B`, and a repository with its pack +build for MTPLX, such as `Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16`. +Either way, progress appears on the status line. Downloading needs a running +engine, except with vLLM and MTPLX, whose own tools fetch into their caches +without a server: highlight one of them in the Engines pane to download into it +while it is stopped. The status line follows each download by stage, and shows a +percentage only where the engine reports one, so an MTPLX download stays a plain +running note until it finishes. In the Models pane, while a download is in progress, `c` cancels it. It picks the newest download into the engine highlighted in the Engines pane, or, when @@ -411,6 +425,11 @@ sent after 60 seconds. It needs at least one engine running with a model installed. If nothing is available, the tab says so rather than starting. +Only the Ollama, LM Studio, and llama.cpp endpoints are probed, because the +traffic generator speaks those three dialects and no other. A vLLM or MTPLX +endpoint is skipped, so no jobs appear for it even when it is up and serving. +Point a real application at those. + The test is local to the machine you run it on. Running it here does not start one anywhere else, and a peer running one does not show up as progress here, only as jobs. diff --git a/services/installer/macos/INSTALL.md b/services/installer/macos/INSTALL.md index 83d12c06a..a8825f8fc 100644 --- a/services/installer/macos/INSTALL.md +++ b/services/installer/macos/INSTALL.md @@ -52,7 +52,8 @@ rm -rf "$HOME/Library/Application Support/Nvidia Corporation/Personal AI Router" ``` Downloaded models are not in either directory. Each engine keeps them in its own -store — `~/.ollama`, `~/.lmstudio/models`, `~/.llamacpp`, and `~/.cache/huggingface` (vLLM) — so deleting the +store — `~/.ollama`, `~/.lmstudio/models`, `~/.llamacpp`, `~/.cache/huggingface` +(vLLM), and `~/.mtplx/models` (MTPLX) — so deleting the bundle or the configuration directory leaves them in place. ## Requirements @@ -60,7 +61,9 @@ bundle or the configuration directory leaves them in place. - macOS 12 (Monterey) or newer. - 64-bit Intel (`amd64`) or Apple Silicon (`arm64`). The tarball is built per arch; pick the one that matches your Mac. `uname -m` on the Mac tells you - which: `x86_64` → amd64, `arm64` → arm64. + which: `x86_64` → amd64, `arm64` → arm64. MTPLX is the one engine that needs + Apple Silicon, so on an Intel Mac it is not listed at all rather than listed and + unusable. - A working mDNS responder on UDP 5353. macOS's built-in `mDNSResponder` is fine; the discovery library coexists with it without configuration. @@ -81,9 +84,12 @@ xattr -dr com.apple.quarantine /path/to/NVIDIA-Personal-AI-Router- advertising. Run the broker with `--log-level debug` to see live discovery logs on stderr. - **"Bind: address already in use"**: the proxies listen on `11434` (Ollama), - `1234` (LM Studio), `8080` (llama.cpp), and `8000` (vLLM); another instance of the proxy or + `1234` (LM Studio), `8080` (llama.cpp), `8000` (vLLM), and `8100` (MTPLX); another instance of the proxy or another process is holding one of them. Find the offender with - `lsof -nP -iTCP:11434 -iTCP:1234 -iTCP:8080 -iTCP:8000 -sTCP:LISTEN` and stop it. + `lsof -nP -iTCP:11434 -iTCP:1234 -iTCP:8080 -iTCP:8000 -iTCP:8100 -sTCP:LISTEN` and stop it. + `8100` is there even on a Mac that cannot run MTPLX: the facade is enabled + whether or not anything is behind it, and a peer is only ever promoted while its + engine answers the health probe. Report issues at the project's tracker. Include the broker's `--log-level debug` output and your macOS version (`sw_vers`) and architecture (`uname -m`). diff --git a/services/nvpair-engine-manager/MANIFEST.md b/services/nvpair-engine-manager/MANIFEST.md index 3e078e9a1..fe1937b4b 100644 --- a/services/nvpair-engine-manager/MANIFEST.md +++ b/services/nvpair-engine-manager/MANIFEST.md @@ -246,7 +246,8 @@ probes. ### Actions Each action is a config-declared operation exposed over `engine:action`. -Exactly one of `http`, `cmd`, `remove_path`, `hf_cache`, or `launch_model`: +Exactly one of `http`, `cmd`, `remove_path`, `hf_cache`, `launch_model`, +`hf_pull`, or `stop_engine`: - **`http`** — call the engine's loopback control API. The caller's `params` are sent as the JSON request body by default. Set @@ -286,18 +287,25 @@ Exactly one of `http`, `cmd`, `remove_path`, `hf_cache`, or `launch_model`: refusing when it cannot tell, and holds the engine's operation lock until the removal and any rollback of the launch settings are done. - **`launch_model`** — switch the model an engine serves, for an engine with no - load call because the model is a launch argument (vLLM). `launch_model.flag` - names the flag (`"--model"`). The action takes `{"model": ""}` (a - Hugging Face id such as `org/name`; anything that could be read as a flag, a - path or a shell fragment is refused), writes it into the saved launch - settings exactly as the settings editor would, and restarts a running engine - on it. If the new model does not come up, the previous one is restored and the + load call because the model is a launch argument (vLLM, MTPLX). + `launch_model.flags` lists every flag that has to move together, which for + vLLM is just `["--model"]`. MTPLX also takes `--model-id`: a server started + with only `--model` answers to a derived id such as + `mtplx-qwen38-27b-optimized-speed-fp16`, which matches neither the cache + entry the user picked nor the id a client puts in its request. The action + takes `{"model": ""}` (a Hugging Face id such as `org/name`; anything + that could be read as a flag, a path or a shell fragment is refused), writes + that one value into each declared flag of the saved launch settings exactly + as the settings editor would, and restarts a running engine on it. An empty + flag list, a repeated flag, and an entry that is not a flag are manifest + errors. If the new model does not come up, the previous one is restored and the error says so; a stopped engine is started on it, and asking a running engine for the model already in the launch arguments restarts nothing. The engine's operation lock is held from reading the launch to the last restore. An engine - with a `launch_model` action will not start while its launch arguments lack - the flag: it has no model selected, and refusing beats letting the engine - pick and download a default of its own. The refusal is reported as a failed + with a `launch_model` action will not start while none of the declared flags + names a model: it has no model selected, and refusing beats letting the + engine pick and download a default of its own. The refusal is reported as a + failed start, like the other refusals before launch, so a client that does not wait for the reply still learns of it. Requires `runtime.editable_launch` and `runtime.ready` on every platform. @@ -537,8 +545,10 @@ path, an `uninstall` block sets neither `run` nor `remove`, `uninstall.remove` is present without a `models_dir` to preserve, an `uninstall.remove` target is the model store or inside it (whether spelled literally or as `{models_dir}`), an action sets none or more than one of -`http`/`cmd`/`remove_path`/`hf_cache`/`launch_model`, an `hf_cache` action omits -`dir` or sets only one of `delete` and `tool`, a `launch_model` flag is not a flag or a platform lacks +`http`/`cmd`/`remove_path`/`hf_cache`/`launch_model`/`hf_pull`/`stop_engine`, an +`hf_cache` action omits `dir` or sets only one of `delete` and `tool`, a +`launch_model` action names no flag, repeats one, or lists a non-flag, or a +platform lacks `editable_launch` or `ready`, `advertised_models` is unknown or `"loaded"` without a `loaded_models` action, `result.inventory_field` is set anywhere but the `loaded_models` action of an engine with `advertised_models` `"loaded"` or is diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 2f41e9393..ee3a02c3c 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -6,10 +6,10 @@ SPDX-License-Identifier: Apache-2.0 # nvpair-engine-manager A config-driven control plane for local inference engines. The bundled -manifests support Ollama, LM Studio, llama.cpp, and vLLM. It manages everything about -an engine **except serving inference**: detect, user-mode install, -start/stop/restart, health, and config-declared actions. Adding an engine -is a JSON manifest, not code. +manifests support Ollama, LM Studio, llama.cpp, vLLM, and MTPLX — the last one on +Apple Silicon only. It manages everything about an engine **except serving +inference**: detect, user-mode install, start/stop/restart, health, and +config-declared actions. Adding an engine is a JSON manifest, not code. The bundled manifests under `manifests/` are the working reference for manifest authoring. @@ -295,6 +295,79 @@ preserves it, including waiting for a choice. A failed first Load restores the previous model-free enabled state. Eject retains its existing behavior of stopping vLLM and releasing its model memory. This change adds no inactivity unload policy. +### MTPLX + +The `mtplx` manifest covers Apple Silicon macOS and nothing else: its `platforms` +block declares only `darwin/arm64`, because MTPLX decodes on the Metal path. An +engine manager on any other host therefore leaves MTPLX out of +`engine:get-installed` rather than reporting it as available, and no client offers +it there. + +It also declares no `install` block, so MTPLX is detected and never installed. +`~/.mtplx/bin/mtplx`, the MTPLX app's own runtime venv, `/opt/homebrew/bin/mtplx` +and `~/.local/bin/mtplx` are checked in that order and the first one found is +launched. An explicit `engine:uninstall` is an error for it ("no uninstall defined +for this platform") and "reset all data" skips it, because neither has a PAIR +install marker to work from: the engine, and the pack cache the user filled, stay +exactly where they were. + +`mtplx serve` runs in the foreground as one process, binding loopback `8101` while +the proxy facade owns `8100`. Port `8000` is deliberately not reused for it: that +is the vLLM facade's port, and MTPLX's own desktop GUI defaults to it, so a managed +server would be fighting the user's own daemon for the listener. `stop` signals the +process group `term` with fifteen seconds of grace, which takes the whole server +down rather than only the launcher. + +MTPLX serves **one model pack per process** and has no load, unload, pull or delete +API beyond its CLI, so the manifest provides them as manager actions, the way +`vllm.json` does. It is also a `launch_model` engine: Load writes the pack into the +saved launch arguments and restarts the server on it, restoring the previous pack if +the new one does not come up, and Eject is a `stop_engine` action, because MTPLX +cannot drop its model and keep running. + +The model is written into two flags, `["--model", "--model-id"]`. `--model` names +the files to serve; `--model-id` fixes the id the server answers to, which is what +routing keys on. Started with `--model` alone, MTPLX derives a name such as +`mtplx-qwen38-27b-optimized-speed-fp16`, matching neither the cache entry the user +picked nor the `model` field of a client request. Passing the pack id as `--model-id` +too makes the served id, what `mtplx models --json` reports as `repo_id`, and the +name in the model list one string. `load_model` rewrites both flags together, so +neither is ever left naming the previous pack, and a flag being cleared matches both +the spaced and the `=` form. + +There is no default pack in the launch arguments, and an engine with a +`launch_model` action will not start while none of its flags names a model: the +start is refused with "MTPLX has no model selected; load a model to start it" +instead of bringing up a server with nothing to serve. Load is what picks the first +pack. + +`list_models` is `mtplx models --json`, which reads the pack directory rather than +asking a running server, so it answers offline and while MTPLX is down; the model +list, Add model, Delete and Load all work against a stopped engine, and +`advertised_models: "loaded"` still limits what peers and the proxy hear about to +the pack being served. `loaded_models` asks the running server's `/v1/models`, and +both the readiness check and the five-second health probe read `/health`. + +`pull_model` is `mtplx pull --json` and needs no running engine; +neither it nor `mtplx remove --yes --json` reports byte progress, so a pull shows +only that it is pulling. MTPLX has no in-use guard, so `remove` will delete the pack +a running server has mapped, and it does not take a deleted pack out of a stopped +engine's launch arguments; the clients block Delete on the served pack instead. The +pack cache is `~/.mtplx/models`, a flat `org--Name` layout that is not a Hugging +Face hub cache, so the `hf_cache` actions do not apply. It is declared as the +platform's `models_dir` and stays outside PAIR's app data, out of reach of anything +this service removes, and no `--cache-dir` or `MTPLX_MODEL_DIR` override is passed: +MTPLX reads that directory whether or not PAIR started it, and a flag naming one +would defeat a store the user moved elsewhere. + +MTPLX loads only packs rebuilt for its own decode path, so its `engine:catalog` +source is `https://mtplx.com/releases/models.json` — MTPLX publishes its runnable +pack list there — rather than a Hugging Face search, which would offer mostly packs +this engine refuses to load. Keys that are not a Hugging Face repo id are dropped, +the entries come back sorted by repo id so a refresh does not reshuffle the list, +and every one is marked `appleOnly` and served without `searchable`: the whole list +is a couple of dozen entries, so clients filter it locally rather than fetching per +keystroke, and a target that is not Apple Silicon is handed an empty list. ## Communication @@ -326,8 +399,8 @@ Requests (caller → service): | `engine:cancel-pull` | `{ engine, model }` | `null`, once the transfer has stopped **and** its cleanup has settled — so a UI can hold "Canceling" until the backend is genuinely done. See "Cancelling a pull" below | | `engine:logs` | `{ engine }` | `{ lines: [LogLine] }` | | `engine:errors` | — | `{ errors: [ServiceError] }` | -| `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [{ id, name, author, url, size?, downloads, likes, updatedAt, tags, family?, parameterSize?, appleOnly? }], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**, as opposed to `engine:models`, which reports what is already installed. Ollama, LM Studio, and vLLM have fixed sources; llama.cpp uses its selected source. Ollama's has no public API, so it is a locked list compiled into this binary from `catalog/ollama-models.json`, regenerated on demand by a developer (`npm run scrape:ollama-models` in `desktop/`) who reviews the diff; serving it needs no network. LM Studio's catalog *is* the `lmstudio-community` Hugging Face org, whose repo ids are exactly what `lms get` accepts, so it is fetched live and cached for six hours, with concurrent callers coalesced onto one request, a failed attempt — with or without a list to fall back on — followed by a backoff before the next. vLLM serves Hugging Face repos by their repo id: its browse list is the open, text-generating safetensors repos of `Qwen`, `nvidia`, `mistralai`, `microsoft` and `ibm-granite` (both `text-generation` and `image-text-to-text`), with parameter count and size, and, like llama.cpp, a `query` searches all of Hugging Face under the same rules. llama.cpp downloads any GGUF repo as `repo:quantization`; its Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched and cached the same way, keeping only open, text-generating repos that ship a `Q4_K_M` file, each offered as `repo:Q4_K_M`. Both llama.cpp and vLLM are `searchable`. llama.cpp queries use its selected Hugging Face or ModelScope source; vLLM queries use Hugging Face. Each query is cached separately (the 20 most recently used are kept), and the reply echoes it. A query longer than 100 characters is refused rather than shortened, since a shortened one searches for something the operator did not type. Other sources ignore a query and return their whole list for the client to filter. `platform` and `arch` are the GOOS and GOARCH the models will be **installed on**, which is not always this host — a client driving a peer should name that peer. Omitting both means this host; naming a platform without an arch leaves the arch unknown rather than borrowing this host's. MLX quantizations only install on Apple Silicon, so they are marked `appleOnly` and kept only for a `darwin`/`arm64` target — an Intel Mac does not get them; the reply echoes the `platform` and `arch` it filtered for. `name` is pull-ready: it can be handed to `pull_model` verbatim. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame, so every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | -| `engine:models` | — | `{ models: [string], modelsByEngine: { : [string] }, loadedByEngine: { : [string] }, downloadedByEngine: { : [string] } }` — the flat de-duplicated union of every running engine's models, the per-engine breakdown keyed by engine name, and the per-engine set of models currently **loaded in memory** (all normalized from each engine's `list_models` / `loaded_models` action `result` spec). `modelsByEngine` carries a key for every running engine whose inventory was successfully queried, including an empty list = "running, no models available"; a missing key means not running / not queryable / invalid response. `loadedByEngine` uses the same known-empty distinction for residency and also omits engines with no loaded endpoint. For an engine with `advertised_models: "loaded"`, `modelsByEngine` holds only the served model's name, which is what a request may be routed to, and `downloadedByEngine` holds its `list_models` inventory, read whenever it is installed, running or not, so a model manager keeps its rows after an Eject. Its `loadedByEngine` names the served model by its `--model` (the `root` of vLLM's `/v1/models`), not a `--served-model-name` alias, so it matches the inventory, and is `[]` while it is stopped. A missing `downloadedByEngine` key means the inventory was not read. The `/v1/models` HTTP surface returns the same shape. | +| `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [{ id, name, author, url, size?, downloads, likes, updatedAt, tags, family?, parameterSize?, appleOnly? }], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**, as opposed to `engine:models`, which reports what is already installed. Ollama, LM Studio, vLLM, and MTPLX have fixed sources; llama.cpp uses its selected source. Ollama's has no public API, so it is a locked list compiled into this binary from `catalog/ollama-models.json`, regenerated on demand by a developer (`npm run scrape:ollama-models` in `desktop/`) who reviews the diff; serving it needs no network. LM Studio's catalog *is* the `lmstudio-community` Hugging Face org, whose repo ids are exactly what `lms get` accepts, so it is fetched live and cached for six hours, with concurrent callers coalesced onto one request, a failed attempt — with or without a list to fall back on — followed by a backoff before the next. vLLM serves Hugging Face repos by their repo id: its browse list is the open, text-generating safetensors repos of `Qwen`, `nvidia`, `mistralai`, `microsoft` and `ibm-granite` (both `text-generation` and `image-text-to-text`), with parameter count and size, and, like llama.cpp, a `query` searches all of Hugging Face under the same rules. MTPLX loads only packs rebuilt for its own decode path, so its source is MTPLX's own published pack list (`https://mtplx.com/releases/models.json`) rather than a Hugging Face search, which would offer mostly packs the engine refuses to load; it is not searched, so the reply is the whole list for the client to filter. llama.cpp downloads any GGUF repo as `repo:quantization`; its Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched and cached the same way, keeping only open, text-generating repos that ship a `Q4_K_M` file, each offered as `repo:Q4_K_M`. Both llama.cpp and vLLM are `searchable`. llama.cpp queries use its selected Hugging Face or ModelScope source; vLLM queries use Hugging Face. Each query is cached separately (the 20 most recently used are kept), and the reply echoes it. A query longer than 100 characters is refused rather than shortened, since a shortened one searches for something the operator did not type. Other sources ignore a query and return their whole list for the client to filter. `platform` and `arch` are the GOOS and GOARCH the models will be **installed on**, which is not always this host — a client driving a peer should name that peer. Omitting both means this host; naming a platform without an arch leaves the arch unknown rather than borrowing this host's. MLX quantizations and MTPLX packs only install on Apple Silicon, so they are marked `appleOnly` and kept only for a `darwin`/`arm64` target — an Intel Mac does not get them; the reply echoes the `platform` and `arch` it filtered for. `name` is pull-ready: it can be handed to `pull_model` verbatim. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame, so every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | +| `engine:models` | — | `{ models: [string], modelsByEngine: { : [string] }, loadedByEngine: { : [string] }, downloadedByEngine: { : [string] } }` — the flat de-duplicated union of every running engine's models, the per-engine breakdown keyed by engine name, and the per-engine set of models currently **loaded in memory** (all normalized from each engine's `list_models` / `loaded_models` action `result` spec). `modelsByEngine` carries a key for every running engine whose inventory was successfully queried, including an empty list = "running, no models available"; a missing key means not running / not queryable / invalid response. `loadedByEngine` uses the same known-empty distinction for residency and also omits engines with no loaded endpoint. For an engine with `advertised_models: "loaded"` (MTPLX, which serves one pack per process; vLLM advertises `"available"` and lists its complete cached models instead), `modelsByEngine` holds only the served model's name, which is what a request may be routed to, and `downloadedByEngine` holds its `list_models` inventory, read whenever it is installed, running or not, so a model manager keeps its rows after an Eject. Its `loadedByEngine` names the served model the way the inventory names it (MTPLX by the `data[].id` that its `--model-id` pins to the cache id), so the two lists agree, and is `[]` while the engine is stopped; vLLM, whose inventory is reported the same way, names the cached repository id rather than a `--served-model-name` alias. A missing `downloadedByEngine` key means the inventory was not read. The `/v1/models` HTTP surface returns the same shape. | | `engine:remote-get-installed` | `{ node }` | `{ engines: [EngineStatus] }` fetched from the remote node over `ec` mTLS | | `engine:remote-install` | `{ node, engine, start? }` | `{ opId, status: EngineStatus }` after the remote install (live progress via `engine:remote-progress`) | | `engine:remote-pull-model` | `{ node, engine, model?, params?, opId? }` | `{ opId, result }` after the remote pull (live progress via `engine:remote-progress`). An `opId`, under the same rules as `engine:action`'s, names the pull in place of a minted one: on its `engine:remote-progress` frames, in the reply, and to the peer. Held until every `engine:remote-cancel-pull` of that download sent before it has ended, so a retry cannot reach the peer ahead of the cancel it follows and be stopped by it | diff --git a/services/nvpair-engine-manager/catalog.go b/services/nvpair-engine-manager/catalog.go index 4589a6a1e..62ee34b5b 100644 --- a/services/nvpair-engine-manager/catalog.go +++ b/services/nvpair-engine-manager/catalog.go @@ -44,6 +44,11 @@ import ( // source as `repo:quantization`. // Hugging Face browses approved publishers; ModelScope browses popular // repositories. Both fetch live, with each source and search cached separately. +// - MTPLX loads packs rebuilt for its own decode path, so a Hugging Face browse +// would offer mostly weights it cannot run. Its list is the curated pack file +// the engine publishes, which is the only place its runnable packs are named. +// Fetched live and cached, and never searched: it holds a couple dozen +// entries, so a client filters them. // catalogSourceKind distinguishes how an engine's catalogue is obtained. type catalogSourceKind int @@ -245,6 +250,7 @@ type catalogService struct { lmStudio *listingCache llamaCPP *listingCache vllm *listingCache + mtplx *listingCache modelScope *listingCache // searchMu guards the llama.cpp searches, kept by lowercased query with @@ -258,7 +264,10 @@ type catalogService struct { // it cannot be exercised against the live API. baseURL string modelScopeEndpoint string - llamaSource func() (string, error) + // mtplxURL overrides MTPLX's pack list, which is its own endpoint rather than + // a Hugging Face listing, and so is not covered by baseURL. + mtplxURL string + llamaSource func() (string, error) } // errCatalogPartial marks a fetch that ended before it read the whole @@ -364,6 +373,7 @@ func newCatalogService() *catalogService { c.modelScope = &listingCache{label: "ModelScope catalog", fetch: func(ctx context.Context) ([]CatalogModel, error) { return c.fetchModelScope(ctx, "") }} + c.mtplx = &listingCache{label: "mtplx catalog", fetch: c.fetchMTPLX} return c } @@ -463,6 +473,22 @@ func (c *catalogService) Catalog(ctx context.Context, engine, platform, arch, qu Searchable: true, Query: query, }, nil + case "mtplx": + models, fetchedAt, err := c.mtplx.get(ctx) + if err != nil { + return CatalogResult{}, err + } + return CatalogResult{ + // Every pack is Apple Silicon only, so a target that is not one is + // handed an empty list rather than packs it cannot load. The list is + // still fetched first: the target names the machine the models go to, + // which is not always the machine asking. + Models: filterForTarget(models, platform, arch), + Source: mtplxCatalogURL, + Platform: platform, + Arch: arch, + FetchedAt: fetchedAt.UTC().Format(time.RFC3339), + }, nil default: return CatalogResult{}, fmt.Errorf("no model catalog for engine %q", engine) } diff --git a/services/nvpair-engine-manager/catalog_mtplx.go b/services/nvpair-engine-manager/catalog_mtplx.go new file mode 100644 index 000000000..758e5771f --- /dev/null +++ b/services/nvpair-engine-manager/catalog_mtplx.go @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "slices" + "strings" +) + +// The MTPLX catalogue: the pack list MTPLX publishes for Apple Silicon. +// +// This is the one catalogue here that is not a search of Hugging Face, and the +// reason is what MTPLX will actually load. It runs a pack rebuilt for its own MTP +// decode path, not arbitrary safetensors: a repo whose weights were written for +// llama.cpp or vLLM fails to load rather than falling back to a slower path. So a +// general Hugging Face browse would offer mostly packs this engine cannot serve, +// and the curated list is the only place its runnable packs are named. +// +// The download name is the pack's Hugging Face repo id, which is also what +// `mtplx models` reports and what the engine serves, so listing, pulling and +// loading all key off the same string. +const mtplxCatalogURL = "https://mtplx.com/releases/models.json" + +// mtplxCatalogFile is the whole published list. Its `models` entry is a map +// keyed by repo id, unlike every other source here, which returns an array. The +// value carries a revision pin, a minimum engine version and a note; none of them +// decide what is offered, so the payload is kept unread. The revision is not +// needed because the download resolves the pack by id, and the minimum engine +// version is not filtered on: a pack newer than the installed engine fails when +// it is loaded, which names the cause, rather than vanishing from the list +// without explanation. A fourth key, `not_yet_published`, is not decoded at all +// because those packs cannot be pulled yet, so listing them would offer downloads +// that fail. +type mtplxCatalogFile struct { + Schema int `json:"schema"` + GeneratedAt string `json:"generated_at"` + Models map[string]json.RawMessage `json:"models"` +} + +// mtplxCatalogSource is the list to fetch. catalogService.mtplxURL overrides it +// in tests, where there is no live publisher to read. +func (c *catalogService) mtplxCatalogSource() string { + if c.mtplxURL != "" { + return c.mtplxURL + } + return mtplxCatalogURL +} + +// fetchMTPLX reads the published pack list. +// +// It is not searched: the list is a couple dozen entries, so a query is answered +// from it by the client rather than by a fresh fetch per keystroke, and +// Searchable stays false in the reply. +func (c *catalogService) fetchMTPLX(ctx context.Context) ([]CatalogModel, error) { + ctx, cancel := context.WithTimeout(ctx, catalogHTTPTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.mtplxCatalogSource(), nil) + if err != nil { + return nil, fmt.Errorf("build mtplx catalog request: %w", withoutURL(err)) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", "PAIR/1.0") + + resp, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("mtplx catalog request failed: %w", withoutURL(err)) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("mtplx catalog returned %s", resp.Status) + } + + var file mtplxCatalogFile + if err := json.NewDecoder(io.LimitReader(resp.Body, maxCatalogBody)).Decode(&file); err != nil { + return nil, fmt.Errorf("decode mtplx catalog: %w", err) + } + return normalizeMTPLXPacks(file.Models), nil +} + +// normalizeMTPLXPacks turns the published map into catalog entries. +// +// A decoded Go map has no order, so the entries come out sorted by repo id: the +// list is near-static between publishes, and without this the same file renders +// differently on each refresh. Keys that are not a Hugging Face repo id are +// dropped rather than listed, because Name has to stay a string the engine's +// download accepts, and an id carrying a path separator or a leading dash reads +// as a flag or a path. +func normalizeMTPLXPacks(packs map[string]json.RawMessage) []CatalogModel { + out := make([]CatalogModel, 0, len(packs)) + for repo := range packs { + repo = strings.TrimSpace(repo) + if !hfRepoPattern.MatchString(repo) { + continue + } + owner, _, _ := strings.Cut(repo, "/") + out = append(out, CatalogModel{ + ID: repo, + Name: repo, + Author: owner, + URL: "https://huggingface.co/" + repo, + // Apple Silicon only, which is why this catalogue is still filtered + // for the target instead of only shown on a Mac: a client driving a + // peer that is not one must not be offered packs that peer cannot + // load. + AppleOnly: true, + }) + } + slices.SortFunc(out, func(a, b CatalogModel) int { + return cmp.Compare(a.ID, b.ID) + }) + return out +} diff --git a/services/nvpair-engine-manager/catalog_mtplx_test.go b/services/nvpair-engine-manager/catalog_mtplx_test.go new file mode 100644 index 000000000..3319b3878 --- /dev/null +++ b/services/nvpair-engine-manager/catalog_mtplx_test.go @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// mtplxPackFile is MTPLX's published pack list as the publisher serves it: one +// entry per pack keyed by its Hugging Face repo id, plus a `not_yet_published` +// section that names packs no download can resolve yet. +const mtplxPackFile = `{ + "schema": 1, + "generated_at": "2026-09-24T07:44:40Z", + "models": { + "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Quality": { + "revision": "470d66a5c53dd9f93e94f84e33b6227fb7959335", + "min_engine_version": "2.12.0", + "note": "Higher-fidelity Flash-Next build." + }, + "Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Balance-FP16": { + "revision": "0d0a99ba6c91169609572b225c5c4eef03693bb3", + "min_engine_version": "2.12.0", + "note": "Balance build: Q8_0 layers and MTP head." + }, + "Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16": { + "revision": "a6a715ff95a3c0a55629b1a465920e597798a111", + "min_engine_version": "2.12.0" + } + }, + "not_yet_published": [ + { "model": "Youssofal/Unreleased-32B", "size_bytes": 31000000000 } + ] +}` + +// catalogServingMTPLXPacks serves body as MTPLX's pack file and counts the +// requests it receives, which is how the tests below tell one catalogue read from +// a read per keystroke. +func catalogServingMTPLXPacks(t *testing.T, status int, body string) (*catalogService, *atomic.Int64) { + t.Helper() + var hits atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if status != http.StatusOK { + w.WriteHeader(status) + return + } + w.Header().Set("Content-Type", "application/json") + _, err := io.WriteString(w, body) + assert.NoError(t, err, "the fixture must reach the decoder") + })) + t.Cleanup(srv.Close) + + c := newCatalogService() + c.mtplxURL = srv.URL + "/releases/models.json" + return c, &hits +} + +func TestMTPLXCatalog_ListsEveryPublishedPackInRepoIDOrder(t *testing.T) { + c, hits := catalogServingMTPLXPacks(t, http.StatusOK, mtplxPackFile) + + res, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "", "") + + require.NoError(t, err) + var got []string + for _, m := range res.Models { + got = append(got, m.ID) + } + // Sorted, because a decoded Go map has no order and this list barely changes + // between publishes: the same file must render the same way every time. + assert.Equal(t, []string{ + "Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Balance-FP16", + "Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16", + "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Quality", + }, got) + assert.Equal(t, int64(1), hits.Load(), "one catalogue read serves the whole refresh") + + first := res.Models[0] + // A pack is pulled and served by its repo id, so that is its download name, + // and its page is the Hugging Face repo that id names. + assert.Equal(t, "Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Balance-FP16", first.Name) + assert.Equal(t, "Youssofal", first.Author) + assert.Equal(t, + "https://huggingface.co/Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Balance-FP16", first.URL) + assert.True(t, first.AppleOnly, "every MTPLX pack runs only on Apple Silicon") + assert.Empty(t, first.UpdatedAt, "the publisher gives no per-pack date") + + assert.False(t, res.Searchable, "the client filters this list; there is nothing to search") + assert.Empty(t, res.Query) + assert.Equal(t, mtplxCatalogURL, res.Source) + assert.Equal(t, "darwin", res.Platform) + assert.Equal(t, "arm64", res.Arch) + assert.NotEmpty(t, res.FetchedAt) +} + +func TestMTPLXCatalog_AnswersAQueryFromThePacksAlreadyListed(t *testing.T) { + c, hits := catalogServingMTPLXPacks(t, http.StatusOK, mtplxPackFile) + + browse, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "", "") + require.NoError(t, err) + require.Len(t, browse.Models, 3, "the pack list has to be read before a query answers itself") + + // How a source that cannot search is queried: the same whole list comes back + // and the client filters it, so the publisher is not read again per keystroke. + res, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "flash", "") + + require.NoError(t, err) + assert.Equal(t, browse.Models, res.Models, "a query must not narrow a list the client filters") + assert.False(t, res.Searchable) + assert.Empty(t, res.Query, "nothing was searched, so there is no query to echo") + assert.Equal(t, int64(1), hits.Load(), "the second call is served from the cached list") +} + +func TestMTPLXCatalog_DropsEntriesThatAreNotDownloadableRepoIDs(t *testing.T) { + body := `{"schema": 1, "models": { + "Youssofal/Real-Pack": {"revision": "abc"}, + "NoSlash": {}, + "../escape": {}, + "-flaglike": {}, + "": {} + }}` + c, _ := catalogServingMTPLXPacks(t, http.StatusOK, body) + + res, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "", "") + + require.NoError(t, err) + // Only a `/` id can be handed to `mtplx pull`. A key led by a + // path separator or a dash would read as a path or a flag, and one with no + // slash names no repo. + require.Len(t, res.Models, 1) + assert.Equal(t, "Youssofal/Real-Pack", res.Models[0].ID) +} + +func TestMTPLXCatalog_LeavesAPackOutOfAHostThatCannotRunIt(t *testing.T) { + c, _ := catalogServingMTPLXPacks(t, http.StatusOK, mtplxPackFile) + + res, err := c.Catalog(t.Context(), "mtplx", "linux", "x64", "", "") + + require.NoError(t, err) + assert.Empty(t, res.Models, + "an Apple Silicon pack is not offered to a machine that cannot load it") + assert.Equal(t, "linux", res.Platform) + assert.Equal(t, "x64", res.Arch) +} + +func TestMTPLXCatalog_ReportsAPublisherThatGivesNoList(t *testing.T) { + for _, tc := range []struct { + name string + status int + body string + wantErr string + }{ + { + name: "a server error", + status: http.StatusBadGateway, + body: "", + wantErr: "mtplx catalog returned 502 Bad Gateway", + }, + { + name: "an empty pack list", + status: http.StatusOK, + body: `{"schema": 1, "models": {}}`, + wantErr: "mtplx catalog returned no models", + }, + { + name: "something that is not the pack file", + status: http.StatusOK, + body: `sign in first`, + wantErr: "decode mtplx catalog", + }, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := catalogServingMTPLXPacks(t, tc.status, tc.body) + + _, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "", "") + + // No list is a failure rather than an empty catalogue: the model + // browser says the source could not be read, not that MTPLX has no + // packs. An empty answer also keeps its retry backoff, so a dead + // publisher is not re-read on every call. + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantErr) + }) + } +} + +func TestMTPLXCatalog_ParsesAPackEntryWhoseFieldsItDoesNotRead(t *testing.T) { + // The revision, minimum engine version and note decide nothing, so the entry + // payload is skipped whole: a publisher adding a field cannot break the parse, + // and none of that text reaches the wire. + body := `{"schema": 1, "models": {"Youssofal/Pack": { + "revision": "abc", "min_engine_version": "2.12.0", "note": "text", + "brand_new_field": {"nested": true} + }}}` + c, _ := catalogServingMTPLXPacks(t, http.StatusOK, body) + + res, err := c.Catalog(t.Context(), "mtplx", "darwin", "arm64", "", "") + + require.NoError(t, err) + require.Len(t, res.Models, 1) + encoded, err := json.Marshal(res.Models[0]) + require.NoError(t, err) + assert.JSONEq(t, `{ + "id": "Youssofal/Pack", + "name": "Youssofal/Pack", + "author": "Youssofal", + "url": "https://huggingface.co/Youssofal/Pack", + "downloads": 0, + "likes": 0, + "updatedAt": "", + "tags": null, + "appleOnly": true + }`, string(encoded)) +} diff --git a/services/nvpair-engine-manager/hfcache.go b/services/nvpair-engine-manager/hfcache.go index 83b7affee..96631e1a4 100644 --- a/services/nvpair-engine-manager/hfcache.go +++ b/services/nvpair-engine-manager/hfcache.go @@ -391,11 +391,11 @@ func (e *Executor) deleteHFModel(ctx context.Context, st *engineState, engine, d } unselected := false if selected == id { - flag := modelLaunchFlag(st.manifest) - if edit.before.Running || flag == "" || !edit.before.Editable { + flags := modelLaunchFlags(st.manifest) + if edit.before.Running || len(flags) == 0 || !edit.before.Editable { return refused } - text, _, err := withoutLaunchFlag(edit.before.LaunchText, flag) + text, _, err := withoutLaunchFlags(edit.before.LaunchText, flags) if err != nil { return err } @@ -463,10 +463,5 @@ func (e *Executor) selectedModelLocked(edit *launchEdit) (string, error) { if err != nil { return "", err } - flag := modelLaunchFlag(edit.st.manifest) - if flag == "" { - return "", nil - } - model, _ := launchFlagValue(tokens, flag) - return model, nil + return launchModelValue(tokens, modelLaunchFlags(edit.st.manifest)), nil } diff --git a/services/nvpair-engine-manager/hfcache_test.go b/services/nvpair-engine-manager/hfcache_test.go index 226144a56..eb4acd6dc 100644 --- a/services/nvpair-engine-manager/hfcache_test.go +++ b/services/nvpair-engine-manager/hfcache_test.go @@ -529,7 +529,7 @@ func TestDeleteHFModel_UsesTheCacheSavedBeforeItGetsTheOperationLock(t *testing. platform.Runtime.LaunchEnv = []string{"HF_HUB_CACHE=" + oldCache} } m.Platforms[runtime.GOOS+"/"+runtime.GOARCH] = platform - m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flag: "--model"}} + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}} m.Actions["delete_model"] = Action{HFCache: &ActionHFCache{Dir: "{hf_hub_cache}", Delete: true, Tool: toolName}} e := newTestExecutor(t, m) e.overrideDir = t.TempDir() diff --git a/services/nvpair-engine-manager/launch_controls_test.go b/services/nvpair-engine-manager/launch_controls_test.go index 2d2eac974..4d80f1e1c 100644 --- a/services/nvpair-engine-manager/launch_controls_test.go +++ b/services/nvpair-engine-manager/launch_controls_test.go @@ -112,7 +112,7 @@ func TestBundledLlamaCPP_DisablesCORSByDefault(t *testing.T) { func TestBundledManifests_DeclareReviewedNetworkingControls(t *testing.T) { reg := loadWithOverrides(t, t.TempDir()) // Adding a bundled engine requires an explicit networking review and cases. - wantEngines := []string{"llamacpp", "lmstudio", "ollama", "vllm"} + wantEngines := []string{"llamacpp", "lmstudio", "mtplx", "ollama", "vllm"} names := reg.Names() slices.Sort(names) assert.Equal(t, wantEngines, names, "review networking controls for every bundled engine") @@ -140,6 +140,14 @@ func TestBundledManifests_DeclareReviewedNetworkingControls(t *testing.T) { require.Equal(t, []LaunchControl{{Value: "{server.host}", Flags: []string{"--host"}}, {Value: "{server.port}", Flags: []string{"--port"}}}, policy.Controls, "incomplete vLLM controls") valid = []string{"--host 127.0.0.1 --port 23456", "--host=127.0.0.1 --port=23456", "--port 23456 --model Qwen/Qwen2.5-0.5B-Instruct"} invalid = []string{"--host 0.0.0.0", "--host=::", "--port 0", "--port 65536", "--port", "--port 23456 --port 23457", "-- --host 0.0.0.0"} + case "mtplx": + require.Equal(t, []string{"serve"}, policy.FixedArgs, "MTPLX startup subcommand is not fixed") + require.Equal(t, []LaunchControl{{Value: "{server.host}", Flags: []string{"--host"}}, {Value: "{server.port}", Flags: []string{"--port"}}}, policy.Controls, "incomplete MTPLX controls") + // The model flags are the launch_text form of what load_model + // writes: both must survive a settings round trip, and a + // "--model-id" must not be taken for a "--model". + valid = []string{"--host 127.0.0.1 --port 23456", "--host=127.0.0.1 --port=23456", "--port 23456 --model Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16 --model-id Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16"} + invalid = []string{"--host 0.0.0.0", "--host=::", "--port 0", "--port 65536", "--port", "--port 23456 --port 23457", "-- --host 0.0.0.0"} default: require.Equal(t, []LaunchControl{{Value: "{server.host}:{server.port}", Env: []string{"OLLAMA_HOST"}}, {Value: "{cors.origins}", Env: []string{"OLLAMA_ORIGINS"}}}, policy.Controls, "incomplete Ollama controls") valid = []string{`OLLAMA_HOST="127.0.0.1:23456"`, `OLLAMA_HOST='127.0.0.1:23456'`, "OLLAMA_HOST=127.0.0.1:23456"} diff --git a/services/nvpair-engine-manager/launchmodel.go b/services/nvpair-engine-manager/launchmodel.go index 3520dd4f1..da4e22aea 100644 --- a/services/nvpair-engine-manager/launchmodel.go +++ b/services/nvpair-engine-manager/launchmodel.go @@ -163,7 +163,7 @@ func (e *Executor) changeLaunchModel(ctx context.Context, engine string, spec *A if !current.Editable { return fmt.Errorf("the launch settings of engine %q cannot be changed: %s", engine, current.Reason) } - text, changed, err := withLaunchFlag(current.LaunchText, spec.Flag, model) + text, changed, err := withLaunchFlags(current.LaunchText, spec.Flags, model) if err != nil { return err } @@ -244,6 +244,39 @@ func withLaunchFlag(text, flag, value string) (result string, changed bool, err return result, !slices.Equal(tokens, out), err } +// withLaunchFlags sets one model in every flag an engine names it by, in the +// order the manifest declares them. An engine that also reads its served id +// from a second flag (MTPLX's --model-id) needs both moved at once: leave that +// one alone and the engine answers to a name derived from the model rather than +// the id its clients, its peers and its own model list already use. +func withLaunchFlags(text string, flags []string, value string) (string, bool, error) { + changed := false + for _, flag := range flags { + next, flagChanged, err := withLaunchFlag(text, flag, value) + if err != nil { + return "", false, err + } + text = next + changed = changed || flagChanged + } + return text, changed, nil +} + +// withoutLaunchFlags clears every flag in flags. See withLaunchFlags for why an +// engine can name its model in more than one place. +func withoutLaunchFlags(text string, flags []string) (string, bool, error) { + changed := false + for _, flag := range flags { + next, flagChanged, err := withoutLaunchFlag(text, flag) + if err != nil { + return "", false, err + } + text = next + changed = changed || flagChanged + } + return text, changed, nil +} + // withoutLaunchFlag returns launch text with every "flag value" and // "flag=value" before any "--" terminator removed, and whether any was. func withoutLaunchFlag(text, flag string) (result string, changed bool, err error) { @@ -289,12 +322,25 @@ func dropLaunchFlag(tokens []string, flag string) (rest []string, at int) { return rest, at } -// modelLaunchFlag is the flag an engine's launch_model action writes, or "" for -// an engine that does not choose its model by launch argument. -func modelLaunchFlag(m *Manifest) string { +// modelLaunchFlags returns the flags an engine's launch_model action writes, or +// nil for an engine that does not choose its model by launch argument. +func modelLaunchFlags(m *Manifest) []string { for _, act := range m.Actions { if act.LaunchModel != nil { - return act.LaunchModel.Flag + return act.LaunchModel.Flags + } + } + return nil +} + +// launchModelValue returns the model the arguments name, taken from the first +// model flag they carry. Every flag an engine names its model by says the same +// model, so any one answers the question; the first is the one it loads its +// weights from. +func launchModelValue(tokens []string, flags []string) string { + for _, flag := range flags { + if value, ok := launchFlagValue(tokens, flag); ok && value != "" { + return value } } return "" @@ -367,7 +413,7 @@ func (e *Executor) ejectByStopping(ctx context.Context, engine string, params js // so no start is needed to enter this state. Callers hold the operation lock and // retain their stop request until this transaction finishes. func (l *launchEdit) awaitModelAfterEject(ctx context.Context) error { - text, _, err := withoutLaunchFlag(l.before.LaunchText, modelLaunchFlag(l.st.manifest)) + text, _, err := withoutLaunchFlags(l.before.LaunchText, modelLaunchFlags(l.st.manifest)) if err != nil { return err } diff --git a/services/nvpair-engine-manager/launchmodel_test.go b/services/nvpair-engine-manager/launchmodel_test.go index 12208d094..85fea9403 100644 --- a/services/nvpair-engine-manager/launchmodel_test.go +++ b/services/nvpair-engine-manager/launchmodel_test.go @@ -154,15 +154,15 @@ func TestWithLaunchFlag_RejectsLaunchTextThatDoesNotParse(t *testing.T) { } // switchModelExecutor is a running fake engine with editable launch settings -// and a launch_model action. The fake ignores arguments it does not know, so -// the "model" flag is carried in the saved launch text without changing how it -// serves. -func switchModelExecutor(t *testing.T, flag string) *Executor { +// and a launch_model action that writes the model into every flag named here. +// The fake ignores arguments it does not know, so a model flag is carried in the +// saved launch text without changing how it serves. +func switchModelExecutor(t *testing.T, flags ...string) *Executor { t.Helper() e := settingsExecutor(t, false) m, ok := e.reg.Get("fake") require.True(t, ok, "fake manifest missing") - m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flag: flag}} + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: flags}} // Like vLLM, the engine answers which model it serves, under the name // requests use (id) and the model it loaded (root). m.AdvertisedModels = advertisedModelsLoaded @@ -174,7 +174,7 @@ func switchModelExecutor(t *testing.T, flag string) *Executor { // An engine that chooses its model by launch argument needs one to start. state, err := e.LaunchSettings("fake") require.NoError(t, err) - text, _, err := withLaunchFlag(state.LaunchText, flag, "org/initial") + text, _, err := withLaunchFlags(state.LaunchText, flags, "org/initial") require.NoError(t, err) _, err = e.ConfigureLaunch(t.Context(), settings.Configure{ Engine: "fake", @@ -221,6 +221,47 @@ func TestWithoutLaunchFlag_RemovesEveryFormOfTheFlag(t *testing.T) { test("absent", "--port 8001", "--port 8001", false) } +// MTPLX names the model it serves twice over: --model picks the weights, +// --model-id picks the id it answers to. Both have to move on a Load, so the +// helpers take the whole list a manifest declares. + +func TestWithLaunchFlags_SetsTheModelInEveryDeclaredFlag(t *testing.T) { + flags := []string{"--model", "--model-id"} + test := func(name, text, want string, wantChanged bool) { + t.Run(name, func(t *testing.T) { + got, changed, err := withLaunchFlags(text, flags, "org/new") + + require.NoError(t, err) + assert.Equal(t, want, got) + assert.Equal(t, wantChanged, changed, "changed") + }) + } + test("adds both to a launch that names no model", "--port 8101", "--port 8101 --model org/new --model-id org/new", true) + test("moves both, keeping their order", "--model org/old --model-id org/old --port 8101", "--model org/new --model-id org/new --port 8101", true) + // --model-id is its own flag, not a spelling of --model, so a launch whose + // two flags disagree is corrected rather than left half-replaced. + test("corrects a flag that disagrees with the other", "--model org/new --model-id org/old", "--model org/new --model-id org/new", true) + test("moves a pair written in the other order", "--model-id org/old --model org/old", "--model-id org/new --model org/new", true) + test("unchanged when both already say the model", "--model org/new --model-id org/new", "--model org/new --model-id org/new", false) +} + +func TestWithoutLaunchFlags_ClearsEveryDeclaredFlag(t *testing.T) { + flags := []string{"--model", "--model-id"} + test := func(name, text, want string, wantChanged bool) { + t.Run(name, func(t *testing.T) { + got, changed, err := withoutLaunchFlags(text, flags) + + require.NoError(t, err) + assert.Equal(t, want, got) + assert.Equal(t, wantChanged, changed, "changed") + }) + } + test("removes both", "--model org/a --model-id org/a --port 8101", "--port 8101", true) + test("removes the equals forms", "--model=org/a --model-id=org/a", "", true) + test("removes one", "--model-id org/a --port 8101", "--port 8101", true) + test("leaves a launch that names no model", "--port 8101", "--port 8101", false) +} + // loadReply is the load_model result. type loadReply struct { Model string `json:"model"` @@ -268,6 +309,39 @@ func TestLaunchModel_SwitchesAndRestartsARunningEngine(t *testing.T) { assert.Equal(t, gen, startGeneration(t, e), "a no-op switch restarted the engine") } +// MTPLX serves the id its --model-id says, not the id of the pack named by +// --model, so a manifest that declares both has to move them together: a Load +// that only repoints --model leaves the engine answering to a name derived from +// the weights, which no client, peer, or model list asks for. +func TestLaunchModel_SwitchesEveryFlagTheModelIsNamedBy(t *testing.T) { + e := switchModelExecutor(t, "--model", "--model-id") + // What each declared model flag says, so a lagging one shows up here rather + // than as a name mismatch somewhere else. + flagsSaying := func() map[string]string { + tokens := strings.Fields(launchTextOf(t, e)) + said := map[string]string{} + for _, flag := range []string{"--model", "--model-id"} { + if value, found := launchFlagValue(tokens, flag); found { + said[flag] = value + } + } + return said + } + const first = "Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16" + + _, err := loadModel(t, e, first) + + require.NoError(t, err) + assert.Equal(t, map[string]string{"--model": first, "--model-id": first}, flagsSaying()) + + // A second switch moves the pair again, with nothing of the first model + // left behind in either flag. + _, err = loadModel(t, e, "org/second") + + require.NoError(t, err) + assert.Equal(t, map[string]string{"--model": "org/second", "--model-id": "org/second"}, flagsSaying()) +} + // startGeneration counts how many times the engine has been started. func startGeneration(t *testing.T, e *Executor) int64 { t.Helper() @@ -438,28 +512,31 @@ func TestLaunchModel_RestoresThePreviousModelWhenTheCallerGivesUp(t *testing.T) assert.True(t, mustStatus(t, e).Running, "the engine was left down after the caller gave up") } -func TestLaunchModelAction_AcceptsOnlyALongOptionFlag(t *testing.T) { - accept := func(name, flag string) { +func TestLaunchModelAction_AcceptsOnlyAListOfLongOptionFlags(t *testing.T) { + accept := func(name string, flags ...string) { t.Run(name, func(t *testing.T) { - assert.NoError(t, (&Action{LaunchModel: &ActionLaunchModel{Flag: flag}}).validate("load_model")) + assert.NoError(t, (&Action{LaunchModel: &ActionLaunchModel{Flags: flags}}).validate("load_model")) }) } - reject := func(name, flag string) { + reject := func(name string, flags ...string) { t.Run(name, func(t *testing.T) { - assert.Error(t, (&Action{LaunchModel: &ActionLaunchModel{Flag: flag}}).validate("load_model")) + assert.Error(t, (&Action{LaunchModel: &ActionLaunchModel{Flags: flags}}).validate("load_model")) }) } - accept("a long option", "--model") + accept("one long option", "--model") + accept("a model pair that moves together", "--model", "--model-id") + reject("no flag at all") reject("no dashes", "model") - reject("a space in the flag", "--mod el") - reject("a value in the flag", "--model=x") - reject("empty", "") + reject("a space in a flag", "--mod el") + reject("a value in a flag", "--model=x") + reject("an empty flag", "") + reject("a flag listed twice", "--model", "--model") } // The restart needs editable launch settings and a readiness probe on every platform. func TestLaunchModelAction_RequiresEditableLaunch(t *testing.T) { m := testEngineManifest(fakeEngineBin) - m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flag: "--model"}} + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}} assert.ErrorContains(t, m.Validate(), "editable_launch") } diff --git a/services/nvpair-engine-manager/lifecycle.go b/services/nvpair-engine-manager/lifecycle.go index 336624376..d8f70a126 100644 --- a/services/nvpair-engine-manager/lifecycle.go +++ b/services/nvpair-engine-manager/lifecycle.go @@ -220,9 +220,9 @@ func (e *Executor) doStart(ctx context.Context, st *engineState, engine string, } // An engine whose model is a launch argument cannot start without one. vLLM // would serve, and first download, a default model of its own instead. - if flag := modelLaunchFlag(st.manifest); flag != "" { + if flags := modelLaunchFlags(st.manifest); len(flags) > 0 { tokens, err := parseLaunchText(e.launchStateLocked(engine, st).LaunchText) - if model, _ := launchFlagValue(tokens, flag); err == nil && model == "" { + if model := launchModelValue(tokens, flags); err == nil && model == "" { if rt.WaitForModel { st.mu.Lock() st.awaitingModel = true diff --git a/services/nvpair-engine-manager/lifecycle_test.go b/services/nvpair-engine-manager/lifecycle_test.go index 33a6f0525..f80f9cadd 100644 --- a/services/nvpair-engine-manager/lifecycle_test.go +++ b/services/nvpair-engine-manager/lifecycle_test.go @@ -22,7 +22,7 @@ func waitingModelExecutor(t *testing.T) *Executor { e := settingsExecutor(t, false) m, ok := e.reg.Get("fake") require.True(t, ok) - m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flag: "--model"}} + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}} key := runtime.GOOS + "/" + runtime.GOARCH p := m.Platforms[key] p.Runtime.WaitForModel = true diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json new file mode 100644 index 000000000..efaa10627 --- /dev/null +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -0,0 +1,63 @@ +{ + "$schema": "../manifest.schema.json", + "engine": "mtplx", + "display_name": "MTPLX", + "manifest_version": 1, + "advertised_models": "loaded", + "platforms": { + "darwin/arm64": { + "detect": [ + "~/.mtplx/bin/mtplx", + "~/Library/Application Support/MTPLX/runtime-venv/bin/mtplx", + "/opt/homebrew/bin/mtplx", + "~/.local/bin/mtplx" + ], + "runtime": { + "bin": "~/.mtplx/bin/mtplx", + "cli": "~/.mtplx/bin/mtplx", + "editable_launch": { + "fixed_args": ["serve"], + "controls": [ + { "flags": ["--host"], "value": "{server.host}" }, + { "flags": ["--port"], "value": "{server.port}" } + ] + }, + "args": ["serve", "--host", "{host}", "--port", "{port}"], + "bind": "127.0.0.1", + "port": 8101, + "ready": { "http": "http://127.0.0.1:{port}/health", "status": 200, "timeout_s": 600 }, + "stop": { "signal": "term", "grace_s": 15 }, + "health": { "http": "http://127.0.0.1:{port}/health", "status": 200, "interval_s": 5 } + }, + "models_dir": "~/.mtplx/models" + } + }, + "actions": { + "list_models": { + "description": "List the model packs in the local MTPLX cache (mtplx models). It reads the cache directory, so it needs no running engine. MTPLX serves one model per process, so the list is what could be loaded, not what is loaded. A pack with a missing runtime contract or required file still lists, and loading it fails and restores the previous model.", + "cmd": ["{cli}", "models", "--json"], + "result": { "array": "models", "field": "repo_id" } + }, + "loaded_models": { + "description": "List the model this MTPLX server serves (it serves exactly one). MTPLX is started with --model-id set to the cache id, so the name it answers to is the same string list_models reports and what a client puts in its request.", + "http": { "method": "GET", "path": "/v1/models" }, + "result": { "array": "data", "field": "id" } + }, + "load_model": { + "description": "Serve a different model pack (params: {\"model\": \"\"}). MTPLX serves one model per process, so this saves the model into the launch arguments and restarts the engine on it; if the new model does not start, the previous one is restored. --model-id is written beside --model so the served name stays the cache id.", + "launch_model": { "flags": ["--model", "--model-id"] } + }, + "unload_model": { + "description": "Eject the model MTPLX is serving (params: {\"model\": \"\"}). MTPLX cannot drop its model and keep running, so this stops the engine, which frees all of its memory. Load starts it again.", + "stop_engine": true + }, + "pull_model": { + "description": "Download a model pack into the local MTPLX cache (params: {\"model\": \"\"}). Needs no running engine, and the download runs in this process, so it is bounded by the action timeout. Once downloaded it appears in list_models and can be served with load_model.", + "cmd": ["{cli}", "pull", "{model}", "--json"] + }, + "delete_model": { + "description": "Delete a model pack from the local MTPLX cache (params: {\"model\": \"\"}). Eject it first: MTPLX has no in-use guard, so this deletes a pack the running server still has mapped, and it does not take the deleted pack out of the launch arguments of a stopped engine. Download it again to recover either way.", + "cmd": ["{cli}", "remove", "{model}", "--yes", "--json"] + } + } +} \ No newline at end of file diff --git a/services/nvpair-engine-manager/manifests/vllm.json b/services/nvpair-engine-manager/manifests/vllm.json index 0f3a95eae..4708e142f 100644 --- a/services/nvpair-engine-manager/manifests/vllm.json +++ b/services/nvpair-engine-manager/manifests/vllm.json @@ -88,7 +88,7 @@ }, "load_model": { "description": "Serve a different model (params: {\"model\": \"\"}). vLLM serves one model per process, so this saves the model into the launch arguments and restarts the engine on it; if the new model does not start, the previous one is restored.", - "launch_model": { "flag": "--model" } + "launch_model": { "flags": ["--model"] } }, "unload_model": { "description": "Eject the model vLLM is serving (params: {\"model\": \"\"}). This stops its serving process and frees its GPU memory while keeping the engine enabled. Load or an inference request for a cached model starts serving again.", diff --git a/services/nvpair-engine-manager/modelrequest.go b/services/nvpair-engine-manager/modelrequest.go index f6a2f8c1e..3a0f1edbb 100644 --- a/services/nvpair-engine-manager/modelrequest.go +++ b/services/nvpair-engine-manager/modelrequest.go @@ -34,8 +34,8 @@ func (e *Executor) prepareRequestedModel(ctx context.Context, engine, model stri st.mu.Lock() allowed := st.plat != nil && st.plat.Runtime.WaitForModel st.mu.Unlock() - flag := modelLaunchFlag(st.manifest) - if !allowed || flag == "" { + flags := modelLaunchFlags(st.manifest) + if !allowed || len(flags) == 0 { return 0, errors.New("this engine does not support request-triggered model loading") } if port, serving, err := e.servingRequestModel(ctx, st, engine, model); err != nil || serving { @@ -45,7 +45,7 @@ func (e *Executor) prepareRequestedModel(ctx context.Context, engine, model stri if err != nil { return 0, err } - if _, err := e.changeLaunchModel(ctx, engine, &ActionLaunchModel{Flag: flag}, params, true); err != nil { + if _, err := e.changeLaunchModel(ctx, engine, &ActionLaunchModel{Flags: flags}, params, true); err != nil { return 0, err } state, err := e.Status(engine) diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 8277e8322..6413d1fb1 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -433,11 +433,14 @@ type ActionHFPull struct { Dir string `json:"dir"` } -// ActionLaunchModel names the launch flag that selects the engine's model, such -// as "--model". The action takes {"model": ""}, writes it into the saved -// launch settings and restarts a running engine on it. +// ActionLaunchModel names the launch flags that select the engine's model, such +// as "--model". An engine that also names the model somewhere else lists every +// flag that has to move together: MTPLX serves whatever --model-id says, so a +// launch that rewrites only --model keeps answering to the derived id no client +// asks for. The action takes {"model": ""}, writes it into every declared +// flag of the saved launch settings and restarts a running engine on it. type ActionLaunchModel struct { - Flag string `json:"flag"` + Flags []string `json:"flags"` } // ActionHTTP is a templated call against the engine's loopback base URL. @@ -834,7 +837,7 @@ func (m *Manifest) Validate() error { } } for key, p := range m.Platforms { - if p.Runtime.WaitForModel && (p.Runtime.modeOrDefault() != "process" || modelLaunchFlag(m) == "") { + if p.Runtime.WaitForModel && (p.Runtime.modeOrDefault() != "process" || len(modelLaunchFlags(m)) == 0) { return fmt.Errorf("platform %q: wait_for_model requires process mode and a launch_model action", key) } } @@ -1156,9 +1159,19 @@ func (a *Action) validate(name string) error { } } if hasLaunchModel { - flag := a.LaunchModel.Flag - if !strings.HasPrefix(flag, "-") || strings.ContainsAny(flag, " \t=") { - return fmt.Errorf("action %q: launch_model.flag %q must be a flag such as \"--model\"", name, flag) + flags := a.LaunchModel.Flags + if len(flags) == 0 { + return fmt.Errorf("action %q: launch_model.flags needs at least one flag such as \"--model\"", name) + } + seen := make(map[string]bool, len(flags)) + for _, flag := range flags { + if !strings.HasPrefix(flag, "-") || strings.ContainsAny(flag, " \t=") { + return fmt.Errorf("action %q: launch_model.flags entry %q must be a flag such as \"--model\"", name, flag) + } + if seen[flag] { + return fmt.Errorf("action %q: launch_model.flags lists %q twice", name, flag) + } + seen[flag] = true } } if hasHFCache && strings.TrimSpace(a.HFCache.Dir) == "" { diff --git a/services/nvpair-engine-manager/registry_test.go b/services/nvpair-engine-manager/registry_test.go index 09a00be0b..ce10b7374 100644 --- a/services/nvpair-engine-manager/registry_test.go +++ b/services/nvpair-engine-manager/registry_test.go @@ -870,7 +870,7 @@ func TestBundledVLLMManifest_DeclaresTheModelActionsTheStackReliesOn(t *testing. // Switching the model is a launch-argument change plus a restart, since the // engine has no load call. if load := manifest.Actions["load_model"]; assert.NotNil(t, load.LaunchModel, "load_model must switch the model through a launch argument") { - assert.Equal(t, "--model", load.LaunchModel.Flag) + assert.Equal(t, []string{"--model"}, load.LaunchModel.Flags) } // vLLM cannot drop its model and keep running, so Eject stops the engine. assert.True(t, manifest.Actions["unload_model"].StopEngine, "unload_model must stop the engine") diff --git a/services/nvpair-engine-manager/remediation_test.go b/services/nvpair-engine-manager/remediation_test.go index f8e2ed49b..f31115f60 100644 --- a/services/nvpair-engine-manager/remediation_test.go +++ b/services/nvpair-engine-manager/remediation_test.go @@ -558,7 +558,7 @@ func TestStart_ReportsARefusalAsAFailedStart(t *testing.T) { test("an engine whose model is a launch argument, with no model selected", func(t *testing.T) *Executor { e := settingsExecutor(t, false) m, _ := e.reg.Get("fake") - m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flag: "--model"}} + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}} require.NoError(t, m.Validate()) return e }, "no model selected") diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index ad6b4213a..5ebb0d495 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -7,7 +7,8 @@ SPDX-License-Identifier: Apache-2.0 ## 1. Purpose A declarative, config-driven control plane for **local inference engines** -(currently Ollama, LM Studio, and llama.cpp). It owns an engine's entire +(currently Ollama, LM Studio, llama.cpp, vLLM, and MTPLX, the last of those +Apple Silicon only). It owns an engine's entire lifecycle *except serving inference* — locate, install, launch, stop, restart, health, and config-declared actions — so one uniform API manages any engine across OSes with no per-engine code. A third party drops in a JSON manifest and @@ -113,7 +114,12 @@ loading is provided by the PAIR proxy endpoint. `chat`, `unload_model`, and `delete_model` (`remove_path` with `lms-disk-path` resolution); llama.cpp declares list, loaded-list, pull, load, unload, and native cache - delete with exact model ids. `loaded_models` reports + delete with exact model ids. vLLM and MTPLX declare list, loaded-list, pull, + load, unload and delete as well, but serve **one model per process**: their + `load_model` is a `launch_model` action that rewrites the model in the launch + arguments and restarts the engine on it, and their `unload_model` is a + `stop_engine` action, because neither can release its model and keep serving. + MTPLX declares no install block, so it is only ever detected. `loaded_models` reports models currently resident in memory, name-extracted via the same declarative `result` spec with optional nested-path and row filters: Ollama uses `GET /api/ps`, LM Studio filters nonempty `loaded_instances` from @@ -134,17 +140,20 @@ loading is provided by the PAIR proxy endpoint. - A normalized node-level model list (`engine:models`): the union of each engine's advertised `modelsByEngine`, name-extracted through its declarative action result, plus the resident `loadedByEngine` from `loaded_models`. - Engines using `advertised_models: "loaded"` advertise only served names. - Enabled vLLM uses `advertised_models: "available"` to advertise complete cached - models for request-triggered loading, subject to the custom alias restriction - above. Its `list_models` disk inventory is also reported as - `downloadedByEngine`, including while disabled; its `loadedByEngine` uses those - cached repository IDs to identify resident rows. `requestableByEngine` carries - loader capability independently of ON/OFF intent for the broker's local route - updates. A successful empty inventory retains an engine key with `[]`; a - missing, malformed or failed inventory omits the key. A watcher polls these - lists and pushes `engine:models-changed` after load, unload, idle eviction, - download or deletion changes them. + Engines using `advertised_models: "loaded"` (MTPLX, which serves one pack per + process) advertise only served names. Enabled vLLM uses + `advertised_models: "available"` to advertise complete cached models for + request-triggered loading, subject to the custom alias restriction above. + Their `list_models` disk inventory is also reported as `downloadedByEngine`, + including while stopped or disabled; `loadedByEngine` names a resident model + the way that inventory names it — MTPLX by the `data[].id` that its + `--model-id` pins to the cache id, vLLM by the cached repository id, not a + `--served-model-name` alias. `requestableByEngine` carries loader capability + independently of ON/OFF intent for the broker's local route updates. A + successful empty inventory retains an engine key with `[]`; a missing, + malformed or failed inventory omits the key. A watcher polls these lists and + pushes `engine:models-changed` after load, unload, idle eviction, download or + deletion changes them. - Expose all of the above over the `engine:*` JSON-RPC surface to whatever orchestrates the service, plus an optional plain-HTTP LAN endpoint (`--http-port`, `GET /v1/models`) that serves the model list to a peer's discovery daemon (the list moved off the size-limited mDNS TXT onto HTTP). **Out of scope** @@ -327,7 +336,7 @@ Requests (caller → service): | `engine:logs` | `{ engine }` | `{ lines: [LogLine] }` | | `engine:errors` | — | `{ errors: [ServiceError] }` | | `engine:models` | — | `{ models: [string], modelsByEngine?, loadedByEngine?, downloadedByEngine? }` — advertised, loaded, and downloaded model lists | -| `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [CatalogModel], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**. Ollama, LM Studio, and vLLM have fixed sources; llama.cpp uses its selected source. Ollama's is compiled in (`catalog/ollama-models.json`, no network), LM Studio's is the `lmstudio-community` Hugging Face org fetched live and cached, and llama.cpp's Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched live and cached, offered as `repo:Q4_K_M`. vLLM offers open, text-generating safetensors repos from Hugging Face. Both llama.cpp and vLLM are `searchable`: a `query` searches llama.cpp's selected source for GGUF repos or Hugging Face for vLLM safetensors repos, each query cached on its own, and is echoed back; a query over 100 characters is an error rather than being shortened; other sources ignore it and return their whole list. `platform` and `arch` are the GOOS and GOARCH the models will be installed on; omitting both means this host, and naming a platform without an arch leaves the arch unknown rather than borrowing this host's. `appleOnly` rows (MLX) are kept only for a `darwin`/`arm64` target. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame — every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | +| `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [CatalogModel], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**. Ollama, LM Studio, vLLM, and MTPLX have fixed sources; llama.cpp uses its selected source. Ollama's is compiled in (`catalog/ollama-models.json`, no network), LM Studio's is the `lmstudio-community` Hugging Face org fetched live and cached, and llama.cpp's Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched live and cached, offered as `repo:Q4_K_M`. vLLM offers open, text-generating safetensors repos from Hugging Face. Both llama.cpp and vLLM are `searchable`: a `query` searches llama.cpp's selected source for GGUF repos or Hugging Face for vLLM safetensors repos, each query cached on its own, and is echoed back; a query over 100 characters is an error rather than being shortened; other sources ignore it and return their whole list. `platform` and `arch` are the GOOS and GOARCH the models will be installed on; omitting both means this host, and naming a platform without an arch leaves the arch unknown rather than borrowing this host's. `appleOnly` rows (MLX) are kept only for a `darwin`/`arm64` target. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame — every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | | `engine:remote-get-installed` | `{ node }` | `{ engines: [EngineStatus] }` from the remote node | | `engine:remote-install` | `{ node, engine, start? }` | `{ opId, status }` after the remote install | | `engine:remote-pull-model` | `{ node, engine, model?, params?, opId? }` | `{ opId, result }` after the remote pull; `opId` is the caller's, or one minted for it (§14) | diff --git a/services/nvpair-job-scheduler/spec.md b/services/nvpair-job-scheduler/spec.md index 1513e3a0e..ac8a61576 100644 --- a/services/nvpair-job-scheduler/spec.md +++ b/services/nvpair-job-scheduler/spec.md @@ -55,9 +55,9 @@ capacity, model locality, latency, and affinity can grow later behind the same - **Simultaneous local burst**: before each auto-routed inference forward, the proxy atomically increments a local reservation for its chosen node. Concurrent requests therefore see one another even before workload feedback completes. -- **Cross-engine contention**: Ollama, LM Studio, llama.cpp, and vLLM workloads all - consume the destination node's execution resources, so any one of them changes - every engine output. +- **Cross-engine contention**: Ollama, LM Studio, llama.cpp, vLLM and MTPLX workloads + all consume the destination node's execution resources, so any one of them + changes every engine output. - **Periodic reconciliation**: the runtime-adjustable timer recomputes the same order as a safety net even when no fresh event arrives. - **Load shifts**: as a node drains it rises toward the top; as it fills it sinks; a @@ -290,7 +290,7 @@ Let `D` = current discovered-node `hostUuid`s: `scheduledOn` (not `originatedFrom`) is the key: we care where work runs, not where it came from. Engine remains part of workload identity and selects the downstream proxy output, but it does not partition the load metric: Ollama, LM Studio, -llama.cpp, and vLLM normally contend for the same node-level GPU, VRAM, CPU, and memory. +llama.cpp, vLLM and MTPLX normally contend for the same node-level GPU, VRAM, CPU, and memory. Until resource affinity is observable, total node queue depth is the conservative signal. diff --git a/services/nvpair-node-scanner/README.md b/services/nvpair-node-scanner/README.md index 6de4ca950..e76cfc0ca 100644 --- a/services/nvpair-node-scanner/README.md +++ b/services/nvpair-node-scanner/README.md @@ -48,8 +48,8 @@ Concretely, the daemon: so an HTTP read cannot hold the lock needed by owned hardware notifications. Model inventory decoding reads at most 16 MiB. A JSON value that extends past that limit fails enrichment and leaves the last successful inventory intact. - `downloadedByEngine` retains downloaded models for engines such as vLLM even - while they are stopped; `modelsByEngine` records the models they serve. + `downloadedByEngine` retains downloaded models for engines such as vLLM and + MTPLX even while they are stopped; `modelsByEngine` records the models they serve. Queued and in-flight model results are discarded if the peer's authenticated address list changes, including a secondary address used for failover. - **Samples scheduling telemetry** from healthy nodes every two seconds with diff --git a/services/nvpair-node-scanner/spec.md b/services/nvpair-node-scanner/spec.md index aec4c59fc..5c6cc3328 100644 --- a/services/nvpair-node-scanner/spec.md +++ b/services/nvpair-node-scanner/spec.md @@ -423,8 +423,8 @@ Local publication uses retained models without waiting for HTTP while holding the local identity lock. A local registration also schedules the model sweep without waiting for its next periodic run. -`downloadedByEngine` carries downloaded inventory for engines such as vLLM that -advertise only their served model in `modelsByEngine`. It remains available while +`downloadedByEngine` carries downloaded inventory for engines such as vLLM and MTPLX +that advertise only their served model in `modelsByEngine`. It remains available while the engine is stopped, for example `{"downloadedByEngine":{"vllm":["Qwen/Qwen3.5-4B"]}}`. Scanner compares model lists without depending on their order. A present engine entry diff --git a/services/nvpair-proxy/README.md b/services/nvpair-proxy/README.md index 259d12e26..0bf65eb03 100644 --- a/services/nvpair-proxy/README.md +++ b/services/nvpair-proxy/README.md @@ -83,10 +83,10 @@ parameter, because one flag cannot carry multiple engines' plans. Everything engine-specific is one entry in `engines.go`, plus the shared identity in `nvpair-shared/engines`. -| | `"engine":"ollama"` | `"engine":"lmstudio"` | `"engine":"llamacpp"` | `"engine":"vllm"` | -|---|---|---|---|---| -| Facade id — error-ID prefix and broker relay namespace | `ollama-proxy` | `lmstudio-proxy` | `llamacpp-proxy` | `vllm-proxy` | -| Discovery service key | `ol` | `lm` | `lc` | `vl` | +| | `"engine":"ollama"` | `"engine":"lmstudio"` | `"engine":"llamacpp"` | `"engine":"vllm"` | `"engine":"mtplx"` | +|---|---|---|---|---|---| +| Facade id — error-ID prefix and broker relay namespace | `ollama-proxy` | `lmstudio-proxy` | `llamacpp-proxy` | `vllm-proxy` | `mtplx-proxy` | +| Discovery service key | `ol` | `lm` | `lc` | `vl` | `mx` | The **log component, supervisor label, and TUI health crash key are not in that table**: they name the process (`nvpair-proxy`), not a facade, because one @@ -95,17 +95,30 @@ Facade-scoped log records carry an `engine` field instead. The supervisor label and the health crash key are matched against each other, so they move together — see `nvpair-shared/engines` and `spec.md` §9. -| | `"engine":"ollama"` | `"engine":"lmstudio"` | `"engine":"llamacpp"` | `"engine":"vllm"` | -|---|---|---|---|---| -| Engine's own client-facing port | 11434 | 1234 | 8080 | 8000 | -| Where PAIR relocates the engine | 11435 | 1235 | 8081 | 8001 | -| Standalone port, used when `port` is omitted | 11435 | 1234 | 8080 | 8000 | -| Persisted-port file (declared, not derived) | `proxy-port.json` | `lmstudio-proxy-port.json` | `llamacpp-proxy-port.json` | `vllm-proxy-port.json` | -| Model-list routes | `GET /api/tags` (native), `GET /v1/models` (OpenAI) | `GET /v1/models` (OpenAI) | `GET /models`, `GET /v1/models` (OpenAI; both query upstream `/models`) | `GET /v1/models` (OpenAI) | -| Inference routes | `/api/generate`, `/api/chat`, `/api/embeddings`, `/api/embed`, plus the OpenAI and Anthropic Messages sets below | OpenAI and Anthropic Messages sets below | OpenAI set below | OpenAI set below | -| Model naming | untagged means `:latest`, so `llama3` and `llama3:latest` are one model | identifiers compared byte for byte | identifiers compared byte for byte | identifiers compared byte for byte | - -All four facades classify these OpenAI-compatible POST routes as inference: +| | `"engine":"ollama"` | `"engine":"lmstudio"` | `"engine":"llamacpp"` | `"engine":"vllm"` | `"engine":"mtplx"` | +|---|---|---|---|---|---| +| Engine's own client-facing port | 11434 | 1234 | 8080 | 8000 | 8000 | +| Where PAIR relocates the engine | 11435 | 1235 | 8081 | 8001 | 8101 | +| Standalone port, used when `port` is omitted | 11435 | 1234 | 8080 | 8000 | 8100 | +| Persisted-port file (declared, not derived) | `proxy-port.json` | `lmstudio-proxy-port.json` | `llamacpp-proxy-port.json` | `vllm-proxy-port.json` | `mtplx-proxy-port.json` | +| Model-list routes | `GET /api/tags` (native), `GET /v1/models` (OpenAI) | `GET /v1/models` (OpenAI) | `GET /models`, `GET /v1/models` (OpenAI; both query upstream `/models`) | `GET /v1/models` (OpenAI) | `GET /v1/models` (OpenAI) | +| Inference routes | `/api/generate`, `/api/chat`, `/api/embeddings`, `/api/embed`, plus the OpenAI and Anthropic Messages sets below | OpenAI and Anthropic Messages sets below | OpenAI set below | OpenAI set below | OpenAI and Anthropic Messages sets below | +| Model naming | untagged means `:latest`, so `llama3` and `llama3:latest` are one model | identifiers compared byte for byte | identifiers compared byte for byte | identifiers compared byte for byte | identifiers compared byte for byte | + +MTPLX's own default is `8000` too, the same number the vLLM facade already owns, +so the facade and the relocated engine move to `8100`/`8101` together: a managed +MTPLX started on `8000` would be fighting the vLLM facade, and a managed proxy +listening there would be fighting a MTPLX daemon the user started themselves. The +profile is built on every host but is inert off Apple Silicon, where nothing +detects the engine and a facade promotes an engine only while it answers its health +probe. + +MTPLX also classifies `POST /v1/messages/count_tokens` as a **model lookup** rather +than a workload: it is routed by the model named in its body, because an +unclassified POST would fan out to every node, but it stays out of the cluster's +workload stream. + +All five facades classify these OpenAI-compatible POST routes as inference: - `/v1/chat/completions` — [Chat Completions](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) - `/v1/completions` — [Completions](https://developers.openai.com/api/reference/resources/completions/methods/create) @@ -113,14 +126,17 @@ All four facades classify these OpenAI-compatible POST routes as inference: - `/v1/responses` — [Responses](https://developers.openai.com/api/reference/resources/responses/methods/create) The [Anthropic Messages](https://platform.claude.com/docs/en/api/messages/create) set is `POST /v1/messages`, classified as inference by -the Ollama and LM Studio facades. +the Ollama, LM Studio and MTPLX facades. MTPLX serves Anthropic-style traffic +itself, so on its facade that path is a workload, not one of the unlisted paths +forwarded verbatim. The route table is a **classifier, not an allowlist**. An unlisted path is forwarded verbatim, which is how `/api/show`, `/api/pull`, `/api/ps`, `/api/version` and `OPTIONS` preflights keep working. -The broker enables all four facades by default. Local llama.cpp-compatible -clients use `8080`, while the managed `llama-server` stays on `8081`. vLLM clients use `8000`, while the managed `vllm serve` stays on `8001`. +The broker enables all five facades by default. Local llama.cpp-compatible +clients use `8080`, while the managed `llama-server` stays on `8081`. vLLM clients use `8000`, while the managed `vllm serve` stays on `8001`. MTPLX +clients use `8100`, while the managed `mtplx serve` stays on `8101`. `--proxy-engines` can restrict a standalone broker or TUI to a subset. ### HTTP Reverse Proxy diff --git a/services/nvpair-proxy/engines.go b/services/nvpair-proxy/engines.go index 7a4c89d70..9660b8a29 100644 --- a/services/nvpair-proxy/engines.go +++ b/services/nvpair-proxy/engines.go @@ -158,6 +158,18 @@ var vllmBaseRoutes = []route{ {Path: "/v1/models", Role: roleModelListOpenAIGET}, } +// mtplxBaseRoutes is the engine-specific surface MTPLX exposes beyond the +// shared OpenAI/Anthropic ones. MTPLX serves one model per process, like vLLM. +// +// /v1/messages/count_tokens is a model lookup, not a workload: it answers a +// token count for the model named in its body, so it is routed by that model +// (an unclassified POST would fan out to every node) while staying out of the +// cluster's workload stream. +var mtplxBaseRoutes = []route{ + {Path: "/v1/models", Role: roleModelListOpenAIGET}, + {Path: "/v1/messages/count_tokens", Role: roleModelLookupPOST}, +} + // openAIInferenceRoutes is the OpenAI-compatible inference surface. var openAIInferenceRoutes = []route{ {Path: "/v1/chat/completions", Role: roleInferencePOST}, @@ -178,10 +190,12 @@ func buildProfiles() []engineProfile { lmstudio, _ := engines.ByName("lmstudio") llamacpp, _ := engines.ByName("llamacpp") vllm, _ := engines.ByName("vllm") + mtplx, _ := engines.ByName("mtplx") ollamaRoutes := slices.Concat(ollamaBaseRoutes, openAIInferenceRoutes, anthropicInferenceRoutes) lmStudioRoutes := slices.Concat(lmStudioBaseRoutes, openAIInferenceRoutes, anthropicInferenceRoutes) llamaCPPRoutes := slices.Concat(llamaCPPBaseRoutes, openAIInferenceRoutes) vllmRoutes := slices.Concat(vllmBaseRoutes, openAIInferenceRoutes) + mtplxRoutes := slices.Concat(mtplxBaseRoutes, openAIInferenceRoutes, anthropicInferenceRoutes) return []engineProfile{ { @@ -216,6 +230,15 @@ func buildProfiles() []engineProfile { ModelNaming: exactID, ReservedPersistedPort: 8001, }, + { + Engine: mtplx, + StandalonePort: 8100, + Routes: mtplxRoutes, + ModelNaming: exactID, + // 8101 is where engine-manager runs a managed MTPLX, so a proxy + // that restored it would sit on the engine's own port. + ReservedPersistedPort: 8101, + }, } } diff --git a/services/nvpair-proxy/engines_test.go b/services/nvpair-proxy/engines_test.go index e08f78d3e..7926ec916 100644 --- a/services/nvpair-proxy/engines_test.go +++ b/services/nvpair-proxy/engines_test.go @@ -60,6 +60,8 @@ func TestRoleFor_ClassifiesOnlyDeclaredRoutes(t *testing.T) { require.True(t, ok, "llamacpp profile missing") vllm, ok := profileFor("vllm") require.True(t, ok, "vllm profile missing") + mtplx, ok := profileFor("mtplx") + require.True(t, ok, "mtplx profile missing") accept := func(name string, profile engineProfile, method, path string, wantRole routeRole) { t.Run(name, func(t *testing.T) { @@ -116,6 +118,39 @@ func TestRoleFor_ClassifiesOnlyDeclaredRoutes(t *testing.T) { reject("vllm health passthrough", vllm, http.MethodGet, "/health") reject("vllm no native routes", vllm, http.MethodPost, "/api/chat") reject("vllm wrong method on list", vllm, http.MethodPost, "/v1/models") + + accept("mtplx chat", mtplx, http.MethodPost, "/v1/chat/completions", roleInferencePOST) + accept("mtplx completions", mtplx, http.MethodPost, "/v1/completions", roleInferencePOST) + accept("mtplx responses", mtplx, http.MethodPost, "/v1/responses", roleInferencePOST) + // MTPLX really serves the Anthropic surface, unlike vLLM, so it has to be + // classified: an unclassified POST would fan out instead of routing by model. + accept("mtplx anthropic messages", mtplx, http.MethodPost, "/v1/messages", roleInferencePOST) + accept("mtplx list", mtplx, http.MethodGet, "/v1/models", roleModelListOpenAIGET) + // count_tokens names a model in its body but is not a workload, so it routes + // by that model without entering the workload stream. + accept("mtplx count tokens", mtplx, http.MethodPost, "/v1/messages/count_tokens", roleModelLookupPOST) + reject("mtplx health passthrough", mtplx, http.MethodGet, "/health") + reject("mtplx settings passthrough", mtplx, http.MethodGet, "/v1/mtplx/settings") + reject("mtplx wrong method on list", mtplx, http.MethodPost, "/v1/models") +} + +// MTPLX's own default facade port is 8000, which vLLM's facade already claims, +// and its default server port is 8101 for a managed engine. The facade cannot +// sit on either. +func TestMTPLXProfile_KeepsTheFacadeOffTheEnginePorts(t *testing.T) { + profile, ok := profileFor("mtplx") + require.True(t, ok, "mtplx profile missing") + + require.Equal(t, 8100, profile.StandalonePort, "standalone facade port") + require.Equal(t, 8101, profile.ReservedPersistedPort, "reserved engine port") + require.Equal(t, "mtplx-proxy", profile.ComponentName(), "facade component name") + require.Equal(t, "mtplx-proxy-port.json", profile.PortFile, "persisted-port filename") + require.Equal(t, exactID, profile.ModelNaming, "MTPLX serves the cache id verbatim, so no tag is implied") + + assert.False(t, isInferenceRequest(profile, "POST", "/v1/messages/count_tokens"), + "a token count is a model lookup, so it must stay out of the workload stream") + assert.True(t, isInferenceRequest(profile, "POST", "/v1/messages"), + "MTPLX serves /v1/messages, so it must be routed as inference") } func TestIsInferenceRequest_FollowsTheProfile(t *testing.T) { @@ -223,6 +258,7 @@ func TestEngineProfiles_PreservePortFilesAndDeriveErrorIdentifiers(t *testing.T) func TestChooseStartupPort_RespectsOverridesAndReservedPorts(t *testing.T) { ollama, _ := profileFor("ollama") lmstudio, _ := profileFor("lmstudio") + mtplx, _ := profileFor("mtplx") for _, tc := range []struct { name string @@ -242,6 +278,9 @@ func TestChooseStartupPort_RespectsOverridesAndReservedPorts(t *testing.T) { {"lmstudio refuses the engine's port", lmstudio, 1234, false, 1235, true, 1234}, // Ollama reserves nothing, so the equivalent value is honoured. {"ollama reserves nothing", ollama, 11434, false, 11435, true, 11435}, + {"mtplx restores persisted", mtplx, 8100, false, 8150, true, 8150}, + // 8101 is where engine-manager runs a managed MTPLX. + {"mtplx refuses the engine's port", mtplx, 8100, false, 8101, true, 8100}, } { t.Run(tc.name, func(t *testing.T) { got := chooseStartupPort(tc.profile, tc.flagPort, tc.ignorePersisted, tc.persisted, tc.hasPersisted) diff --git a/services/nvpair-proxy/spec.md b/services/nvpair-proxy/spec.md index a4e5f591c..c90f6f2fc 100644 --- a/services/nvpair-proxy/spec.md +++ b/services/nvpair-proxy/spec.md @@ -107,8 +107,13 @@ The process starts with **no engine and no listener**. The broker then sends one A flag cannot express this. The broker plans a different port for each engine — Ollama's managed facade wants `:11434`, LM Studio's wants `:1234`, and -llama.cpp's managed facade wants `:8080`, and vLLM's wants `:8000`; any may be absent so the child keeps -its own persisted port — and a single-valued flag carries only one plan. +llama.cpp's managed facade wants `:8080`, and vLLM's wants `:8000`, while MTPLX's +wants `:8100`; any may be absent so the child keeps +its own persisted port — and a single-valued flag carries only one plan. MTPLX is +not given `8000` although that is its own default: `8000` already belongs to the +vLLM facade, and Apple Silicon macOS is the one host where both engines can be +installed, so the pair for MTPLX is `8100` for the facade and `8101` for the +managed server. ### 3.1 Why one process @@ -116,7 +121,7 @@ Between scheduler snapshots a facade takes short-lived **reservations** for work it has dispatched but that the scheduler has not yet observed. Those live in the process, and every facade shares them. If each engine had its own proxy process, none could see the others' reservations, so simultaneous bursts across -Ollama, LM Studio, llama.cpp, and vLLM could select the same node, each incorrectly +Ollama, LM Studio, llama.cpp, vLLM and MTPLX could select the same node, each incorrectly believing it was idle. Sharing the map is the reason the engines share a process. @@ -171,7 +176,7 @@ For a model-bearing inference request: 1. Filter a request-local discovery snapshot to nodes whose per-engine inventory advertises the requested model. Ollama normalizes the implicit `:latest` tag; - LM Studio, llama.cpp, and vLLM ids match exactly. An empty owner set returns a local + LM Studio, llama.cpp, vLLM and MTPLX ids match exactly. An empty owner set returns a local `502` without contacting an engine. 2. Order the eligible owners: explicit `node/select` pin, then the scheduler's priority list, then deterministic default ordering. @@ -686,12 +691,22 @@ untouched, the primary listener stays up, and a warning is reported. ## 8. Ports -| | Ollama | LM Studio | llama.cpp | vLLM | -| --- | --- | --- | --- | --- | -| Engine's own client-facing port | 11434 | 1234 | 8080 | 8000 | -| Where PAIR relocates the engine | 11435 | 1235 | 8081 | 8001 | -| Standalone port, when `port` is omitted | 11435 | 1234 | 8080 | 8000 | -| Persisted-port file | `proxy-port.json` | `lmstudio-proxy-port.json` | `llamacpp-proxy-port.json` | `vllm-proxy-port.json` | +| | Ollama | LM Studio | llama.cpp | vLLM | MTPLX | +| --- | --- | --- | --- | --- | --- | +| Engine's own client-facing port | 11434 | 1234 | 8080 | 8000 | 8000 | +| Where PAIR relocates the engine | 11435 | 1235 | 8081 | 8001 | 8101 | +| Standalone port, when `port` is omitted | 11435 | 1234 | 8080 | 8000 | 8100 | +| Persisted-port file | `proxy-port.json` | `lmstudio-proxy-port.json` | `llamacpp-proxy-port.json` | `vllm-proxy-port.json` | `mtplx-proxy-port.json` | + +MTPLX is the one engine whose own port is not a free facade slot. `8000` is +already the vLLM facade, so claiming it for MTPLX would make the two facades +compete for one listener on Apple Silicon, where both engines can be installed, and +would sit in front of MTPLX's own desktop daemon. MTPLX clients are pointed at +`8100` instead; a server the user started themselves on `8000` is left alone, which +also means it is not routed. MTPLX declares no platform other than Apple Silicon, so +everywhere else this facade is enabled with nothing behind it: it advertises no +service key while no engine answers its health probe, and a snapshot that reports no +owner for a model is a local `502`. A port chosen at runtime via `set-port` is persisted per engine and restored when that facade is enabled, taking precedence over the requested port, so the diff --git a/services/nvpair-tui/README.md b/services/nvpair-tui/README.md index 7c918daff..aa275cb8a 100644 --- a/services/nvpair-tui/README.md +++ b/services/nvpair-tui/README.md @@ -112,7 +112,9 @@ ships in `cli-bin` and the app's updater replaces it. `p` opens a catalog browser over the engine's downloadable models, served by the backend's `engine:catalog`. Sorting (`o`) is local. So is filtering (`/`) for a -source that cannot search, such as Ollama's list of thousands of entries. For +source that cannot search, such as Ollama's list of thousands of entries and +MTPLX's pack list — a couple of dozen entries, all Apple Silicon only, so a peer +that is not one is handed none of them. For one whose reply says it is `searchable` — llama.cpp's selected model source — `/` sends the query upstream instead, and `c` returns to the browse list. For a peer's llama.cpp engine, each browse/search reads that peer's saved diff --git a/services/nvpair-tui/ui/engineswire.go b/services/nvpair-tui/ui/engineswire.go index e052c411d..1749bdb8b 100644 --- a/services/nvpair-tui/ui/engineswire.go +++ b/services/nvpair-tui/ui/engineswire.go @@ -152,13 +152,25 @@ var modelWires = map[string]modelWire{ "delete": modelOnly("delete_model"), "pull": modelOnly("pull_model"), }, + // MTPLX is vLLM-shaped: one model per process, so load restarts the server + // on the pack and eject stops it. Its CLI takes the cache id under "model" + // alone, which is also the id the server answers to (--model-id) and the id + // `mtplx models --json` reports. + engines.NameMTPLX: { + "load": modelOnly("load_model"), + "unload": modelOnly("unload_model"), + "delete": modelOnly("delete_model"), + "pull": modelOnly("pull_model"), + }, } // pullsWhileStopped are the engines whose download does not go through their -// server: vLLM downloads into the Hugging Face cache with its own tool. It -// mirrors the desktop's modelOpsWhenStopped capability. +// server: vLLM downloads into the Hugging Face cache with its own tool, and +// MTPLX's `mtplx pull` writes to its own pack cache. It mirrors the desktop's +// modelOpsWhenStopped capability. var pullsWhileStopped = map[string]bool{ - engines.NameVLLM: true, + engines.NameVLLM: true, + engines.NameMTPLX: true, } // downloadExamples show what a download name looks like for each engine. The @@ -169,6 +181,7 @@ var downloadExamples = map[string]string{ engines.NameLMStudio: "lmstudio-community/Qwen3-8B-GGUF", engines.NameLlamaCPP: "ggml-org/gemma-3-1b-it-GGUF:Q4_K_M", engines.NameVLLM: "Qwen/Qwen3.5-4B", + engines.NameMTPLX: "Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16", } // downloadPrompt is the placeholder for the download-by-name field, with an diff --git a/services/nvpair-tui/ui/nodedetail.go b/services/nvpair-tui/ui/nodedetail.go index bd2d70966..2d33b3685 100644 --- a/services/nvpair-tui/ui/nodedetail.go +++ b/services/nvpair-tui/ui/nodedetail.go @@ -1897,8 +1897,8 @@ func (d *nodeDetail) uninstallEngine(engine *engineStatus) tea.Cmd { // the engine pane when it can download, else the only running engine. Most // engines download through their running server, so a stopped one is never // chosen silently. An engine that downloads without its server (vLLM, into the -// Hugging Face cache) can be chosen stopped when it is highlighted, as the -// desktop app allows. +// Hugging Face cache, and MTPLX, into its own pack cache) can be chosen stopped +// when it is highlighted, as the desktop app allows. func (d *nodeDetail) pullTargetEngine() string { if e := d.selectedEngine(); e != nil && (e.Running || e.Installed && pullsWhileStopped[e.Engine]) { return e.Engine diff --git a/services/nvpair-ui-broker/README.md b/services/nvpair-ui-broker/README.md index f7aee0a84..76791e21d 100644 --- a/services/nvpair-ui-broker/README.md +++ b/services/nvpair-ui-broker/README.md @@ -23,7 +23,7 @@ namespace: | --- | --- | --- | | `nvpair-node-scanner` | Discovery daemon: advertises this host's one `_nvpair-node._tcp` record and browses the LAN | `discovery:*` | | `nvpair-node-info` | Owned inventory IPC, public display HTTP, and peer node inventory over pinned mTLS at `/v1/node-info` | _internal_ | -| `nvpair-proxy` | One process hosting an inference proxy and router facade per enabled engine | `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, `vllm-proxy:*` | +| `nvpair-proxy` | One process hosting an inference proxy and router facade per enabled engine | `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, `vllm-proxy:*`, `mtplx-proxy:*` | | `nvpair-engine-manager` | Local engine and model control plane; also serves `GET /v1/models` to peers | `engine:*` | | `nvpair-cluster-manager` | Node identity, trusted-node store, PIN pairing | `cluster:*`, `nodes:*` | | `nvpair-workload-manager` | Cluster workload relay between this node and peers | `workloads:*` | @@ -40,8 +40,8 @@ lifecycle, and relay rules. Two responsibilities live in the broker itself rather than in a worker: - **Engine advertising.** The broker polls local Ollama, LM Studio, - llama.cpp, and vLLM every 5 s and registers each running engine's promoted facade port - (`ol` / `lm` / `lc` / `vl`) with the discovery daemon, so they are carried in this + llama.cpp, vLLM, and MTPLX every 5 s and registers each running engine's promoted facade port + (`ol` / `lm` / `lc` / `vl` / `mx`) with the discovery daemon, so they are carried in this host's single `_nvpair-node` record. The model list is not part of that record — it is served over HTTP by `nvpair-engine-manager` on the `em` service and fetched by a peer's daemon @@ -118,7 +118,7 @@ their age. Notifications from a previous worker cannot restore its records. | `--scanner-path ` | `./nvpair-node-scanner[.exe]` in the CWD | Explicit path to the `nvpair-node-scanner` binary the broker should spawn | | `--node-info-path ` | `./nvpair-node-info[.exe]` in the CWD | Explicit path to the `nvpair-node-info` binary the broker should spawn. When omitted and no default sibling exists, the broker runs without the local inventory server (non-fatal); when set to an invalid path, the broker exits with an error | | `--proxy-path ` | `./nvpair-proxy[.exe]` in the CWD | Explicit path to the `nvpair-proxy` binary. One process fronts every engine: the broker spawns it once and then sends a `facade/enable` per entry in `--proxy-engines`. Same optional semantics as `--node-info-path`: an absent default sibling means no local proxies (non-fatal); an invalid explicit path exits with an error | -| `--proxy-engines ` | `ollama,lmstudio,llamacpp,vllm` | Which engines to front with a proxy. An unrecognized name exits with an error rather than being skipped, so a typo cannot look like it worked. An engine left out is not started **and not prepared** — the broker will not relocate an engine whose facade nothing is going to claim | +| `--proxy-engines ` | `ollama,lmstudio,llamacpp,vllm,mtplx` | Which engines to front with a proxy. An unrecognized name exits with an error rather than being skipped, so a typo cannot look like it worked. An engine left out is not started **and not prepared** — the broker will not relocate an engine whose facade nothing is going to claim | | `--workload-manager-path ` | `./nvpair-workload-manager[.exe]` in the CWD | Explicit path to the `nvpair-workload-manager` binary the broker spawns for the cluster workload relay. Same optional semantics as `--node-info-path`: an absent default sibling means no workload relay (non-fatal); an invalid explicit path exits with an error | | `--errors-path ` | `./nvpair-errors[.exe]` in the CWD | Explicit path to the `nvpair-errors` binary the broker spawns (with `--peer-sync`) for the service-error pipeline. Same optional semantics as `--node-info-path`: an absent default sibling means the error pipeline is disabled — producers' errors are dropped (non-fatal); an invalid explicit path exits with an error | | `--engine-manager-path ` | `./nvpair-engine-manager[.exe]` in the CWD | Explicit path to the `nvpair-engine-manager` binary the broker spawns for engine management. Same optional semantics as `--node-info-path` | @@ -146,11 +146,12 @@ metadata back for peer node inventory responses. Spawning it is optional: if no is resolved and no explicit path was given, the broker continues without it. **Engine advertising.** The broker runs an internal 5 s poll loop against local -Ollama (`GET /`), LM Studio (`GET /v1/models`), llama.cpp (`GET /health`), and vLLM (`GET /health`) +Ollama (`GET /`), LM Studio (`GET /v1/models`), llama.cpp (`GET /health`), vLLM (`GET /health`), +and MTPLX (`GET /health`) at their configured backend ports and reconciles this node's engine registration with the scanner daemon: -- engine **up** and facade **ready** → register `ol` / `lm` / `lc` / `vl` at the +- engine **up** and facade **ready** → register `ol` / `lm` / `lc` / `vl` / `mx` at the promoted facade port, never the private backend port; - engine **down** → unregister it. @@ -175,6 +176,16 @@ vLLM is a managed engine handled exactly like llama.cpp below, with the `vllm serve` process on `:8001` and its default-enabled facade on `:8000` or a safe fallback. +MTPLX is a managed engine on the same shape, with the `mtplx serve` process on +`:8101` and its default-enabled facade on `:8100` or a safe fallback. Those two are +not `:8000` and `:8001`: `8000` is already the vLLM facade, and MTPLX's own default +is `8000` too, so a managed server started there would fight either the vLLM facade +or a MTPLX daemon the user launched. The engine is declared for Apple Silicon only; +the facade is enabled everywhere, because the broker's proxy set is a fixed list +rather than a per-host probe, and a facade promotes an engine only while that engine +answers `/health`. Off Apple Silicon it therefore fronts nothing, and no peer is +told MTPLX exists. + llama.cpp is a managed engine: engine-manager owns its lifecycle and starts it on its configured loopback port, `:8081` by default. The broker places its default-enabled facade on `:8080` or a safe fallback, without automatically @@ -218,7 +229,7 @@ Two classes of proxy notification are **not** re-emitted under any telemetry, and discovery snapshot. It smooths fresh utilization into pressure 0–3, uses neutral pressure 1 for invalid/missing/older-than-10-second samples, and orders by `pending + gpuPressure`, then pressure, then stable UUID. Load is -node-wide across Ollama, LM Studio, llama.cpp, and vLLM because they normally contend +node-wide across Ollama, LM Studio, llama.cpp, vLLM and MTPLX because they normally contend for the same resources. Each engine-specific `schedule:priority` carries `{engine,nodes,ranks}` and refreshes when order, pending counts, or pressure changes. The broker caches, generation-orders, and replays the full @@ -540,7 +551,7 @@ Two relay-specific error cases: - If no proxy is being supervised (or it has exited), the broker replies with error `-32000` `"ollama-proxy not available"`. - `ollama-proxy:shutdown` is **refused** with error `-32601` — the broker owns the proxy's lifecycle, so a client can't terminate it independently. Shut the broker down instead (which tears the proxy down with it). -#### `ollama-proxy:set-port` / `lmstudio-proxy:set-port` / `llamacpp-proxy:set-port` / `vllm-proxy:set-port` +#### `ollama-proxy:set-port` / `lmstudio-proxy:set-port` / `llamacpp-proxy:set-port` / `vllm-proxy:set-port` / `mtplx-proxy:set-port` **Intercepted, not relayed verbatim.** For every engine profile, a port-only caller (none in tree; `nvpair-tui` uses `engine:apply-settings`) gets to move a single port without rendering the whole launch settings form, but the change still runs through the same authoritative settings operation the desktop editor uses, so a port set from the terminal cannot diverge from one set from the UI. The namespace selects the engine. The broker reads that engine's current settings, substitutes the requested proxy port, and applies the result while preserving the server port and launch arguments. Accepted settings are saved in the settings journal. @@ -557,7 +568,7 @@ Automatic conflict resolution still exists, but only for a port the user did not The LM Studio counterpart of the `ollama-proxy:*` surface uses the LM Studio facade in the supervised `nvpair-proxy` process on compatibility port `:1234` and tracks the managed LM Studio engine on `:1235`. With managed port ownership enabled (the default), the broker identifies and moves an existing LM Studio server through engine-manager before allowing the proxy to claim `1234`; unknown owners are left untouched and force a warned proxy fallback. Disabling managed ownership preserves explicit custom engine and proxy ports. `lmstudio-proxy:get-status` reports the actual bound port; `lmstudio-proxy:subscribe` / `lmstudio-proxy:unsubscribe` opt into / out of its `lmstudio-proxy:` stream; `lmstudio-proxy:set-port` uses the settings operation described above; and other `lmstudio-proxy:` requests are relayed with the prefix translated (`nodes/list`, `node/select`, `node/add-manual`, `node/remove-manual`, ...). `lmstudio-proxy:shutdown` is refused because the broker owns lifecycle ordering. Workload and error events feed the shared streams exactly as Ollama's do. -The same broker-local status, subscription, and port-setting methods apply to `llamacpp-proxy:*` and `vllm-proxy:*`. llama.cpp port changes use the same validation, journal, and application path; remaining methods use the generic facade relay, with `llamacpp-proxy:shutdown` refused. +The same broker-local status, subscription, and port-setting methods apply to `llamacpp-proxy:*`, `vllm-proxy:*`, and `mtplx-proxy:*`. llama.cpp port changes use the same validation, journal, and application path; remaining methods use the generic facade relay, with `llamacpp-proxy:shutdown` refused. #### `ollama-proxy:subscribe` @@ -738,8 +749,8 @@ Attach to a pre-existing endpoint: ## Integration and configuration boundaries - **Engine-advertise control surface.** Engine registration is auto-driven only: - the broker tracks local Ollama, LM Studio, llama.cpp, and vLLM and registers `ol`, - `lm`, `lc`, or `vl` with the daemon while each is up. There's no manual-advertise + the broker tracks local Ollama, LM Studio, llama.cpp, vLLM and MTPLX and registers `ol`, + `lm`, `lc`, `vl`, or `mx` with the daemon while each is up. There's no manual-advertise RPC (custom service, port, name, or TXT), and no way to advertise anything other than the detected engines. - **Node-info integration.** The broker passes node-info its cluster directory diff --git a/services/nvpair-ui-broker/engineproxy.go b/services/nvpair-ui-broker/engineproxy.go index d3a6b63ad..00df77514 100644 --- a/services/nvpair-ui-broker/engineproxy.go +++ b/services/nvpair-ui-broker/engineproxy.go @@ -171,6 +171,7 @@ func buildEngineProxyProfiles() []engineProxyProfile { "lmstudio": {Ownership: managedEngine, HealthProbePath: "/v1/models"}, "llamacpp": {Ownership: managedEngine, HealthProbePath: "/health"}, "vllm": {Ownership: managedEngine, HealthProbePath: "/health"}, + "mtplx": {Ownership: managedEngine, HealthProbePath: "/health"}, } out := make([]engineProxyProfile, 0, len(engines.All())) for _, e := range engines.All() { diff --git a/services/nvpair-ui-broker/engineproxy_test.go b/services/nvpair-ui-broker/engineproxy_test.go index 665fc44dd..e45e88883 100644 --- a/services/nvpair-ui-broker/engineproxy_test.go +++ b/services/nvpair-ui-broker/engineproxy_test.go @@ -127,7 +127,7 @@ func TestParseProxyEngines_ValidatesSelectedEngineNames(t *testing.T) { require.Equal(t, append([]string{}, want...), append([]string{}, got...)) }) } - test("default set", "ollama,lmstudio,llamacpp,vllm", []string{"ollama", "lmstudio", "llamacpp", "vllm"}, false) + test("default set", "ollama,lmstudio,llamacpp,vllm,mtplx", []string{"ollama", "lmstudio", "llamacpp", "vllm", "mtplx"}, false) test("single engine", "lmstudio", []string{"lmstudio"}, false) test("whitespace and blanks are tolerated", " ollama , , lmstudio ", []string{"ollama", "lmstudio"}, false) test("duplicates collapse", "ollama,ollama", []string{"ollama"}, false) diff --git a/services/nvpair-ui-broker/enginesettings_test.go b/services/nvpair-ui-broker/enginesettings_test.go index 2421148f1..ebe58990e 100644 --- a/services/nvpair-ui-broker/enginesettings_test.go +++ b/services/nvpair-ui-broker/enginesettings_test.go @@ -64,7 +64,10 @@ func newSettingsHarness(t *testing.T) *settingsHarness { func newSettingsHarnessForEngine(t *testing.T, engine string) *settingsHarness { t.Helper() - ports := make([]int, 5) + // ports[0] is the fixture's engine-server port, and one further port is + // allocated for each facade, so adding an engine to the broker's proxy + // table needs no edit here. + ports := make([]int, len(engineProxyProfiles)+1) releases := make([]func(), len(ports)) for i := range ports { ports[i], releases[i] = reserveSettingsPort(t) @@ -76,12 +79,11 @@ func newSettingsHarnessForEngine(t *testing.T, engine string) *settingsHarness { worker, codec := newTestRPCWorkerPipe(t) h.b.setEngineMgr(worker) proxyWorker, proxyCodec := newTestRPCWorkerPipe(t) - proxy := &proxyProcess{peer: proxyWorker.peer, facadeState: map[string]proxyFacadeState{ - "ollama": {ready: true, port: ports[1]}, - "lmstudio": {ready: true, port: ports[2]}, - "llamacpp": {ready: true, port: ports[3]}, - "vllm": {ready: true, port: ports[4]}, - }} + facadeState := make(map[string]proxyFacadeState, len(engineProxyProfiles)) + for i, profile := range engineProxyProfiles { + facadeState[profile.Name] = proxyFacadeState{ready: true, port: ports[i+1]} + } + proxy := &proxyProcess{peer: proxyWorker.peer, facadeState: facadeState} for _, profile := range engineProxyProfiles { h.b.setEngineProxyHandle(profile, proxy) } diff --git a/services/nvpair-ui-broker/spec.md b/services/nvpair-ui-broker/spec.md index 679188cb2..c25cbff78 100644 --- a/services/nvpair-ui-broker/spec.md +++ b/services/nvpair-ui-broker/spec.md @@ -12,12 +12,12 @@ The single front door every PAIR client talks to, and the supervisor of every ot **In scope** - Process supervision: spawn each worker as a child with stdio JSON-RPC pipes, watch it, restart it on unexpected exit under a bounded backoff policy, and stop it in a defined order on shutdown within a bounded teardown budget. - Startup ordering and the `app:ready` gate — the one signal a client waits on before assuming the node's service tree is live. -- Namespace relay: forward `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, and `vllm-proxy:*` to that engine's `nvpair-proxy` facade, and `engine:*`, `settings/*`, `cluster:*`, `nodes:*`, and the manual-node methods to their owning worker verbatim, and map each worker's result or JSON-RPC error straight back. +- Namespace relay: forward `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, `vllm-proxy:*`, and `mtplx-proxy:*` to that engine's `nvpair-proxy` facade, and `engine:*`, `settings/*`, `cluster:*`, `nodes:*`, and the manual-node methods to their owning worker verbatim, and map each worker's result or JSON-RPC error straight back. - Engine settings operations: `engine:get-settings`, `engine:preview-settings`, and `engine:apply-settings` for this node or a pinned peer, revision-checked and journaled, with every port setter routed through the same operation (§7.10). - Notification projection: consume every worker's stdout notifications, route the error-pipeline ones into `nvpair-errors`, translate or re-emit the rest as the client-facing push stream, and drop what is internal. -- Opt-in subscription state per domain (`discovery:`, `ollama-proxy:`, `lmstudio-proxy:`, `llamacpp-proxy:`, `vllm-proxy:`, `engine:`, `workloads:`) so a client only receives the streams it asked for. +- Opt-in subscription state per domain (`discovery:`, `ollama-proxy:`, `lmstudio-proxy:`, `llamacpp-proxy:`, `vllm-proxy:`, `mtplx-proxy:`, `engine:`, `workloads:`) so a client only receives the streams it asked for. - The node's discovery service registration: registering each worker's LAN service key and port with the scanner daemon on behalf of the worker, and replaying the registration set across every scanner respawn. -- Proxy/engine port reconciliation for the Ollama and LM Studio compatibility ports, driven by the `settings/get-force-ports` policy and live `engine:status`, before each facade is enabled. llama.cpp and vLLM have no compatibility-port takeover; each facade is placed on its default port or a safe fallback without moving the engine (§7.7). +- Proxy/engine port reconciliation for the Ollama and LM Studio compatibility ports, driven by the `settings/get-force-ports` policy and live `engine:status`, before each facade is enabled. llama.cpp, vLLM and MTPLX have no compatibility-port takeover; each facade is placed on its default port or a safe fallback without moving the engine (§7.7). - Scheduling telemetry: a source-aware cache of compact GPU telemetry fed by the scanner and by `nvpair-manual-nodes`, aged locally and relayed to `nvpair-job-scheduler`, and replayed when the scheduler restarts. - Discovery evidence relay: forwarding each proxy's peer-activity reports and `nvpair-node-info`'s peer-observed addresses to `nvpair-node-scanner`. - Merging manual nodes into the same discovery snapshot the scanner feeds, so one node list answers `discovery:get-nodes`. @@ -132,7 +132,7 @@ The single front door every PAIR client talks to, and the supervisor of every ot when its source, proof, or target changes. Expose `info` only on client views. - Maintain the workload store from local-origin proxy events and peer-origin workload-manager events, persist its terminal history, load it on startup, and periodically retire remote-origin records whose origin has gone silent about them. - Register this node's LAN service keys with the scanner daemon and replay them on every scanner spawn. -- Reconcile the Ollama and LM Studio compatibility ports against the `force_ports` policy and live engine status before enabling each facade, and place the llama.cpp and vLLM facades on their default ports or a safe fallback with no compatibility-port gate. +- Reconcile the Ollama and LM Studio compatibility ports against the `force_ports` policy and live engine status before enabling each facade, and place the llama.cpp, vLLM and MTPLX facades on their default ports or a safe fallback with no compatibility-port gate. - Cache compact GPU telemetry from the scanner and `nvpair-manual-nodes` with the scanner taking precedence, relay it to `nvpair-job-scheduler`, and replay the cache when the scheduler respawns. - Forward a proxy's `node/activity` to the scanner as `discovery:node-activity`, and `nvpair-node-info`'s `nodeinfo:observed-addresses` to the scanner as `discovery:set-observed-addresses`. - Restore the persisted cluster id into `nvpair-cluster-manager` before `app:ready`, and persist a later `cluster:identity-changed` back into `nvpair-node-settings`. @@ -220,7 +220,7 @@ record IDs even when their announcements claim a known host UUID. { subscribed: boolean } ``` -`ProxyStatusResult` — the response to `ollama-proxy:get-status`, `lmstudio-proxy:get-status`, `llamacpp-proxy:get-status`, and `vllm-proxy:get-status`, answered per engine from the broker's captured facade state with no round-trip to the proxy. It is per engine because the facades bind different ports. The zero value is a valid "not available" answer, so none of these methods errors: +`ProxyStatusResult` — the response to `ollama-proxy:get-status`, `lmstudio-proxy:get-status`, `llamacpp-proxy:get-status`, `vllm-proxy:get-status`, and `mtplx-proxy:get-status`, answered per engine from the broker's captured facade state with no round-trip to the proxy. It is per engine because the facades bind different ports. The zero value is a valid "not available" answer, so none of these methods errors: ```json { ready: boolean, port: number } ``` @@ -272,10 +272,10 @@ Requests the broker answers itself (client → broker): | `ollama-proxy:subscribe` | — | `SubscriptionResult{subscribed:true}`, then a baseline `ollama-proxy:ready` if that facade has come up | | `ollama-proxy:unsubscribe` | — | `SubscriptionResult{subscribed:false}` | | `ollama-proxy:set-port` | `{ port }` | `{ port }`; runs `engine:apply-settings` with the new proxy port; `-32000` when the port is in use or the change fails | -| `lmstudio-proxy:get-status`, `llamacpp-proxy:get-status`, `vllm-proxy:get-status` | — | `ProxyStatusResult` | -| `lmstudio-proxy:subscribe`, `llamacpp-proxy:subscribe`, `vllm-proxy:subscribe` | — | `SubscriptionResult{subscribed:true}`, then a baseline `-proxy:ready` if that facade has come up | -| `lmstudio-proxy:unsubscribe`, `llamacpp-proxy:unsubscribe`, `vllm-proxy:unsubscribe` | — | `SubscriptionResult{subscribed:false}` | -| `lmstudio-proxy:set-port`, `llamacpp-proxy:set-port`, `vllm-proxy:set-port` | `{ port }` | same as `ollama-proxy:set-port`, for that engine | +| `lmstudio-proxy:get-status`, `llamacpp-proxy:get-status`, `vllm-proxy:get-status`, `mtplx-proxy:get-status` | — | `ProxyStatusResult` | +| `lmstudio-proxy:subscribe`, `llamacpp-proxy:subscribe`, `vllm-proxy:subscribe`, `mtplx-proxy:subscribe` | — | `SubscriptionResult{subscribed:true}`, then a baseline `-proxy:ready` if that facade has come up | +| `lmstudio-proxy:unsubscribe`, `llamacpp-proxy:unsubscribe`, `vllm-proxy:unsubscribe`, `mtplx-proxy:unsubscribe` | — | `SubscriptionResult{subscribed:false}` | +| `lmstudio-proxy:set-port`, `llamacpp-proxy:set-port`, `vllm-proxy:set-port`, `mtplx-proxy:set-port` | `{ port }` | same as `ollama-proxy:set-port`, for that engine | | `engine:get-settings` | `{ engine, nodeId? }` | the engine's full settings snapshot, local or from a pinned peer | | `engine:preview-settings` | `{ engine, nodeId?, expectedRevision, settings, resolution? }` | normalized settings, validation errors, conflicts, and a restart/rebind summary; changes nothing | | `engine:apply-settings` | the preview request plus `requestId` | `{ revision, phase }` receipt; progress arrives as `engine:settings-changed` | @@ -292,7 +292,7 @@ Requests the broker answers itself (client → broker): | `engine:set-reserved-port` | — | `-32601` — private engine-manager method, refused at the boundary | | `internal:set-reserved-port` | — | `-32601` — private engine-manager method, refused at the boundary | | `shutdown` | — | `null`, then the ordered teardown begins | -| `ollama-proxy:shutdown`, `lmstudio-proxy:shutdown`, `llamacpp-proxy:shutdown`, `vllm-proxy:shutdown` | — | `-32601` — the broker owns the proxy lifecycle and will not let a client kill it | +| `ollama-proxy:shutdown`, `lmstudio-proxy:shutdown`, `llamacpp-proxy:shutdown`, `vllm-proxy:shutdown`, `mtplx-proxy:shutdown` | — | `-32601` — the broker owns the proxy lifecycle and will not let a client kill it | The facade rows are one profile-driven handler applied to every engine in `nvpair-shared/engines`, so each `-proxy:` namespace has the same broker-local surface. @@ -300,7 +300,7 @@ Anything else is matched by namespace prefix and relayed verbatim: | Namespace | Owning worker | Relay shape | |-----------|---------------|-------------| -| `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, `vllm-proxy:*` | that engine's `nvpair-proxy` facade | bounded synchronous `Call`; the client prefix is replaced by the engine address (`ollama-proxy:nodes/list` → `ollama:nodes/list`) | +| `ollama-proxy:*`, `lmstudio-proxy:*`, `llamacpp-proxy:*`, `vllm-proxy:*`, `mtplx-proxy:*` | that engine's `nvpair-proxy` facade | bounded synchronous `Call`; the client prefix is replaced by the engine address (`ollama-proxy:nodes/list` → `ollama:nodes/list`) | | `engine:*` | `nvpair-engine-manager` | asynchronous, **no broker-imposed timeout**, method verbatim | | `settings/*` | `nvpair-node-settings` | bounded synchronous `Call`, method verbatim | | `cluster:*`, `nodes:*` | `nvpair-cluster-manager` | bounded synchronous `Call`, method verbatim | @@ -320,7 +320,7 @@ Notifications the broker emits to the client, and what produces each: | `app:ready{version}` | always | the broker itself, once, after the worker tree is started | | `discovery:nodes-changed` | `discovery:subscribe` | the merged discovery store (scanner + manual nodes); payload is a bare `AvailableNode[]` | | `discovery:node-info` | always | scanner full hardware event, accepted only for its current source record, including sanitized unverified previews | -| `ollama-proxy:`, `lmstudio-proxy:`, `llamacpp-proxy:`, `vllm-proxy:` (notably `…:ready`) | that namespace's `…:subscribe` | the facade's engine-addressed notification, with the engine address replaced by the client prefix | +| `ollama-proxy:`, `lmstudio-proxy:`, `llamacpp-proxy:`, `vllm-proxy:`, `mtplx-proxy:` (notably `…:ready`) | that namespace's `…:subscribe` | the facade's engine-addressed notification, with the engine address replaced by the client prefix | | `engine:ready`, `engine:state-changed`, `engine:models-changed`, `engine:install-progress`, `engine:pull-progress`, `engine:remote-progress` | `engine:subscribe` | `nvpair-engine-manager`, verbatim (already `engine:`-prefixed) | | `engine:settings-changed` | always | the broker itself, a full settings snapshot per engine on every settings change | | `workloads:upsert`, `workloads:remove` | `workloads:subscribe` | `nvpair-workload-manager` (peer-origin) and `nvpair-proxy` (local-origin), after the store accepts the transition | @@ -395,7 +395,7 @@ Each worker's reader goroutine invokes a forwarder. Every forwarder calls `dispa | `forwardEngineNotification` | `nvpair-engine-manager` | `engine:settings-request` / `engine:settings-cancel` carry a paired peer's settings operation into the broker (§7.10) — and a supervised worker's own `settings/*` read, such as the engine-manager's `settings/get-engine-allow-lan-bind` gate check, which the broker forwards verbatim to `nvpair-node-settings`; `engine:ready` also triggers LM Studio proxy reconciliation and re-sends the settings projection; `discovery:subscribe` is claimed as a worker relay subscription; everything else is re-emitted verbatim to `engine:subscribe`'d clients | | `forwardProxyProcessNotification` | `nvpair-proxy` | an engine-addressed notification goes to that engine's handler, with that engine's spawn generation for Ollama and LM Studio; an unaddressed one is process-scoped and handled once — `workload:*` is stamped and routed to the workload manager, and `node/activity` is forwarded to the scanner as `discovery:node-activity` | | `forwardProxyNotificationForGeneration` / `forwardLMStudioProxyNotificationForGeneration` | one facade | stale generations dropped; a `bind-failed` on the managed facade port blocks the facade, otherwise selects a fallback port unless the user set the port explicitly; `ready` triggers port reconciliation; the remainder is emitted as `-proxy:` to that namespace's subscribers | -| `forwardDefaultEngineProxyNotification` | the llama.cpp and vLLM facades | no port reconciliation and no generation check: error-pipeline frames are claimed, and the remainder is emitted as `llamacpp-proxy:` or `vllm-proxy:` to that namespace's subscribers | +| `forwardDefaultEngineProxyNotification` | the llama.cpp, vLLM and MTPLX facades | no port reconciliation and no generation check: error-pipeline frames are claimed, and the remainder is emitted as `llamacpp-proxy:`, `vllm-proxy:`, or `mtplx-proxy:` to that namespace's subscribers | | `handleManualNodesNotification` | `nvpair-manual-nodes` | source events upsert full authenticated hardware or separate display previews into `AvailableNode.info`; only pinned measurements feed scheduling; explicit reachable engine routes bridge independently; clients receive merged `discovery:nodes-changed` snapshots, not a separate manual `discovery:node-info` event | | `forwardSettingsNotification` | `nvpair-node-settings` | only `connection/cluster-identity` and `connection/cluster-auto-sync` are re-emitted, verbatim and unconditionally; everything else is debug-logged and dropped | | `forwardClusterManagerNotification` | `nvpair-cluster-manager` | notifications relayed verbatim; identity changes persist settings and reconverge advertisement; trust changes invalidate obsolete scanner/manual proofs and prompt scanner reauthentication; node-info follows live mesh membership | @@ -403,7 +403,7 @@ Each worker's reader goroutine invokes a forwarder. Every forwarder calls `dispa | `forwardSchedulerNotification` | `nvpair-job-scheduler` | `schedule:priority` is de-duplicated, cached, and delivered to the proxy (§7.5); everything else is dropped | | `onErrorsUpdate` | `nvpair-errors` | `errors:update` relayed verbatim and unconditionally | -The **generation** variants exist because a supervisor can replace the proxy process while its predecessor's frames are still in flight. Each spawn takes a monotonically increasing generation for Ollama and for LM Studio, and a forwarder invoked for an older generation returns before any side effect — so a dying process's `ready`, `bind-failed`, or error report can never be attributed to its successor, reconfigure the new process, or resurrect state the replacement has already moved past. The llama.cpp forwarder carries no generation. None of its notifications changes a port, so a stale one can reach only `llamacpp-proxy:` subscribers or the errors pipeline. +The **generation** variants exist because a supervisor can replace the proxy process while its predecessor's frames are still in flight. Each spawn takes a monotonically increasing generation for Ollama and for LM Studio, and a forwarder invoked for an older generation returns before any side effect — so a dying process's `ready`, `bind-failed`, or error report can never be attributed to its successor, reconfigure the new process, or resurrect state the replacement has already moved past. The default engine forwarder — llama.cpp, vLLM and MTPLX — carries no generation. None of those facades' notifications changes a port, so a stale one can reach only its own `-proxy:` subscribers or the errors pipeline. Workload events funnel through one serialized apply-then-fan-then-notify path regardless of origin, so the client-visible order matches the applied order, and a stale or regressive upsert is dropped at the store rather than resurrecting a finished workload on the client stream. @@ -442,12 +442,14 @@ llama.cpp has **no compatibility-port takeover**. `nvpair-engine-manager` owns i vLLM is placed the same way: `nvpair-engine-manager` starts `vllm serve` on its configured loopback port (`:8001` by default), and the broker requests the vLLM facade on `:8000` or a safe fallback, with no compatibility-port gate and no port-ownership block. +MTPLX is placed the same way on its own pair: the managed `mtplx serve` on `:8101` behind a facade on `:8100`, with no compatibility-port gate and no port-ownership block. It is not given `8000` even though that is MTPLX's own default, because `8000` is already the vLLM facade's port and Apple Silicon is the one host where both engines can be installed; a server the user started themselves on `8000` is likewise left untouched rather than fronted. The broker builds its proxy profile set from `engines.All()` rather than from what the host can run, so the MTPLX facade is enabled on every host; off Apple Silicon nothing is ever detected behind it. + A port the user chooses is never silently moved. `engine:set-port` and every `-proxy:set-port` are intercepted and run through `engine:apply-settings` (§7.10), which validates both of the engine's ports against registered services, aliases, other engines and facades, and occupied listeners. A port already in use is refused with `-32000`, and a collision with the `OLLAMA_HOST` alias is refused with a message naming it. Automatic steering remains only for a port the user did not just choose: when a facade announces a restored port a running engine has since taken, the broker moves the facade to a free port and surfaces the sticky warning `ollama-proxy:port-bumped`, never changing the engine's port. An `engine:*` request that depends on a facade port still being reconciled is parked on the corresponding gate and either replayed when the gate opens or answered with a retry-me error after 5 seconds. ### 7.8 Discovery registration and relay No worker registers itself. The broker holds a `relay.RegistrationCache` of this node's LAN services and pushes each entry into the scanner daemon on the worker's behalf, then **replays the whole cache on every scanner spawn** — so a scanner restart re-advertises the node's full service set with no reconnect logic in any worker. Registration is idempotent; only a real change is pushed. -The canonical service keys and the ports the broker registers are `ni` = 14318 (`nvpair-node-info`), `er` = 14319 (`nvpair-errors`), `wl` = 14320 (`nvpair-workload-manager`), `cl` = 14321 (`nvpair-cluster-manager`), `em` = 14322 (`nvpair-engine-manager`'s model-list HTTP endpoint), and `ec` = 14323 (`nvpair-engine-manager`'s cluster-scoped remote-control surface, registered only when a cluster directory is configured). These six are one block — contiguous from `ni` through `ec` — and the broker spawns every block worker on the block it resolved at construction: `--port-base` shifts the whole block together, but only for a coexistence caller such as the cross-process test harness; the shipped app runs flagless on the canonical block, and clients locate workers through discovery records rather than these numbers, so a shifted block changes no contract. `ol`, `lm`, `lc`, and `vl` are registered dynamically with that engine's **facade** listen port — not the engine's port — while the broker's 5-second health poll of the engine's backend port answers (`/` for Ollama, `/v1/models` for LM Studio, `/health` for llama.cpp and vLLM), and are unregistered whenever the engine or its facade goes away, so a peer never routes to a facade that has nothing behind it. +The canonical service keys and the ports the broker registers are `ni` = 14318 (`nvpair-node-info`), `er` = 14319 (`nvpair-errors`), `wl` = 14320 (`nvpair-workload-manager`), `cl` = 14321 (`nvpair-cluster-manager`), `em` = 14322 (`nvpair-engine-manager`'s model-list HTTP endpoint), and `ec` = 14323 (`nvpair-engine-manager`'s cluster-scoped remote-control surface, registered only when a cluster directory is configured). These six are one block — contiguous from `ni` through `ec` — and the broker spawns every block worker on the block it resolved at construction: `--port-base` shifts the whole block together, but only for a coexistence caller such as the cross-process test harness; the shipped app runs flagless on the canonical block, and clients locate workers through discovery records rather than these numbers, so a shifted block changes no contract. `ol`, `lm`, `lc`, `vl`, and `mx` are registered dynamically with that engine's **facade** listen port — not the engine's port — while the broker's 5-second health poll of the engine's backend port answers (`/` for Ollama, `/v1/models` for LM Studio, `/health` for llama.cpp, vLLM and MTPLX), and are unregistered whenever the engine or its facade goes away, so a peer never routes to a facade that has nothing behind it. The broker also relays two kinds of evidence into the scanner that it cannot gather itself. A proxy's `node/activity`, raised while a peer's engine streams response bytes back, becomes `discovery:node-activity`. The scanner uses that recent inference evidence when deciding whether to retain a verified peer independently of announcement expiry. `nvpair-node-info`'s `nodeinfo:observed-addresses`, the local addresses remote peers have actually reached, becomes `discovery:set-observed-addresses`, which the scanner uses to rank the addresses it publishes. Both are sent off the producing worker's reader goroutine. @@ -660,7 +662,7 @@ The broker is a single Go binary that runs as a child of its client and as the p | `--engine-manager-path` | `./nvpair-engine-manager` | engine lifecycle and model operations | | `--node-info-path` | `./nvpair-node-info` | local hardware advertisement | | `--proxy-path` | `./nvpair-proxy` | the one proxy process that hosts every engine's facade | -| `--proxy-engines` | every engine in `nvpair-shared/engines` (today `ollama,lmstudio,llamacpp,vllm`) | which engines to enable a facade for; an unrecognized name is fatal, and an engine left out is neither enabled nor prepared | +| `--proxy-engines` | every engine in `nvpair-shared/engines` (today `ollama,lmstudio,llamacpp,vllm,mtplx`) | which engines to enable a facade for; an unrecognized name is fatal, and an engine left out is neither enabled nor prepared | | `--workload-manager-path` | `./nvpair-workload-manager` | cluster workload relay | | `--manual-nodes-path` | `./nvpair-manual-nodes` | user-entered nodes | | `--cluster-manager-path` | `./nvpair-cluster-manager` | identity, pairing, membership | diff --git a/services/readme.md b/services/readme.md index 0cc8aa675..0fe3dcf40 100644 --- a/services/readme.md +++ b/services/readme.md @@ -12,9 +12,9 @@ node offers and where to reach them. What a discovered node can actually serve is a separate question, answered after discovery. A node may be running [Ollama](https://ollama.com/), LM Studio, -llama.cpp, vLLM, any combination, or none, and its model inventory is fetched over -HTTP from its engine-manager rather than crammed into mDNS TXT records, which -are too small to carry it. +llama.cpp, vLLM, MTPLX (Apple Silicon only), any combination, or none, and its +model inventory is fetched over HTTP from its engine-manager rather than crammed +into mDNS TXT records, which are too small to carry it. Locally, each node exposes compatibility proxies — Ollama-compatible and OpenAI-compatible — so an unmodified client on that machine can reach any capable @@ -28,14 +28,22 @@ can serve that loopback-only address from the same router when it is free — `localhost` is claimed on IPv4 and IPv6 together, and remote or HTTPS targets are never intercepted. -The llama.cpp and vLLM facades are enabled by default alongside Ollama and LM Studio. -The llama.cpp facade exposes OpenAI-compatible traffic on `http://localhost:8080` -while the managed router runs on `8081`. The vLLM facade (the engine itself runs on -Linux and Apple Silicon macOS) uses `http://localhost:8000` with its managed engine on `8001`. A safe fallback is reported when a facade port is +The llama.cpp, vLLM and MTPLX facades are enabled by default alongside Ollama and +LM Studio. The llama.cpp facade exposes OpenAI-compatible traffic on +`http://localhost:8080` while the managed router runs on `8081`. The vLLM facade +(the engine itself runs on Linux and Apple Silicon macOS) uses +`http://localhost:8000` with its managed engine on `8001`. The MTPLX facade uses +`http://localhost:8100` with its managed engine on `8101`; that pair is chosen +deliberately, because `8000` is both the vLLM facade's port and MTPLX's own GUI +default, and a managed server must not fight a daemon the user started. MTPLX +itself runs on Apple Silicon only, so on every other host that facade sits behind +nothing and advertises nothing: a facade promotes an engine only while that engine +answers its health probe. A safe fallback is reported when a facade port is occupied. The desktop and TUI expose each engine's managed lifecycle and -inventory, plus llama.cpp's downloads and load/unload actions; vLLM serves one -model per process, so loading another downloaded model restarts it on that model. `--proxy-engines` can still restrict the -facades a standalone broker or TUI starts. +inventory, plus llama.cpp's downloads and load/unload actions; vLLM and MTPLX +serve one model per process, so loading another downloaded model restarts them on +that model. `--proxy-engines` can still restrict the facades a standalone broker +or TUI starts. PAIR ships a graphical UI alongside these services. The UI launches **`nvpair-ui-broker`** from the same directory; the broker orchestrates the @@ -72,7 +80,7 @@ configuration. The broker feeds every accepted local or peer workload transition plus compact GPU telemetry to the scheduler. Queued and running work is counted by destination -node across Ollama, LM Studio, llama.cpp, and vLLM together. Fresh maximum-GPU +node across Ollama, LM Studio, llama.cpp, vLLM and MTPLX together. Fresh maximum-GPU utilization is smoothed into pressure 0–3; missing or stale telemetry is neutral. Rankings use `pending + gpuPressure`, and each facade adds local reservations before choosing, so bursts spread without waiting for workload diff --git a/services/shared/engines/engines.go b/services/shared/engines/engines.go index 4f1c7cbfb..c3c308dd3 100644 --- a/services/shared/engines/engines.go +++ b/services/shared/engines/engines.go @@ -135,6 +135,7 @@ const ( NameLMStudio = "lmstudio" NameLlamaCPP = "llamacpp" NameVLLM = "vllm" + NameMTPLX = "mtplx" ) // all is the ordered engine set. Ollama is first; see the package comment. @@ -172,6 +173,16 @@ var all = []Engine{ EnginePortBase: 8001, PortFile: "vllm-proxy-port.json", }, + { + // MTPLX's own default is also 8000, which vLLM's facade already claims. + // 8100/8101 are free in this table. + Name: NameMTPLX, + DisplayName: "MTPLX", + DiscoveryService: noderec.ServiceMTPLX, + FacadePort: 8100, + EnginePortBase: 8101, + PortFile: "mtplx-proxy-port.json", + }, } // All returns the engine set in preparation order. The result is a copy, so a diff --git a/services/shared/engines/engines_test.go b/services/shared/engines/engines_test.go index 1de832f86..7f0377220 100644 --- a/services/shared/engines/engines_test.go +++ b/services/shared/engines/engines_test.go @@ -23,7 +23,7 @@ func TestOllama_IsPreparedFirst(t *testing.T) { } func TestEngineNames_ReturnsCanonicalOrder(t *testing.T) { - assert.Equal(t, []string{"ollama", "lmstudio", "llamacpp", "vllm"}, Names()) + assert.Equal(t, []string{"ollama", "lmstudio", "llamacpp", "vllm", "mtplx"}, Names()) } // There are two proxy identities: ComponentName per facade, ProxyComponent per diff --git a/services/shared/noderec/noderec.go b/services/shared/noderec/noderec.go index 258aef709..d9091dc03 100644 --- a/services/shared/noderec/noderec.go +++ b/services/shared/noderec/noderec.go @@ -94,6 +94,7 @@ const ( ServiceLMStudio ServiceKey = "lm" ServiceLlamaCPP ServiceKey = "lc" ServiceVLLM ServiceKey = "vl" + ServiceMTPLX ServiceKey = "mx" ServiceErrors ServiceKey = "er" ServiceWorkload ServiceKey = "wl" ServiceCluster ServiceKey = "cl" @@ -112,8 +113,8 @@ const ( // serviceKeyOrder is the deterministic emit order for service ports in TXT. var serviceKeyOrder = []ServiceKey{ ServiceNodeInfo, ServiceOllama, ServiceLMStudio, ServiceLlamaCPP, ServiceVLLM, - ServiceErrors, ServiceWorkload, ServiceCluster, ServiceEngineManager, - ServiceEngineControl, + ServiceMTPLX, ServiceErrors, ServiceWorkload, ServiceCluster, + ServiceEngineManager, ServiceEngineControl, } // Transport is the connection policy for a service, derived (not advertised). From 4412beee144b6863efa970adf602ef0e63ebbb76 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:05 -0700 Subject: [PATCH 02/10] fix(engines): observe where engines live and what they serve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An MTPLX server the user started answers on the port MTPLX.app gave it — on one Mac 6666 because that is what the app's settings file keeps, on another 8001 after the vLLM facade took its own default. Probing only the configured port read an empty port while the real engine went unadopted and unrouted, and Start either did nothing useful or launched a second router beside the running one. - A manifest may declare a `port_source`: a settings file and the key in it naming the port the engine listens on, read fresh each round, so an engine moved in its own application takes effect on the next poll without restarting PAIR. Start adopts on whichever candidate answers as the engine, and the health loop, EngineStatus's port and the broker's advertiser follow it there instead of trusting a cached configured port. A facade is never handed its own listen port as a backend, which would loop a request back into the proxy. - A candidate port answering 401 or 403 is a service waiting for an API key PAIR never sends: neither adopted nor spawned over; Start fails naming the port and the status, and a standing `engine-manager:auth-blocked` warning covers the state until the port answers. Giving up an adopted service takes three rounds in which every candidate refuses, so a dropped request is not read as a stopped engine. - A stranger found while searching for the engine's real port does not block a start — PAIR hands the engine the port to bind, so a service on a search-only port was never in the way of a new copy. What blocks a start is what sits on the port a new copy would bind, plus credential refusals from anywhere. Uninstall keeps the wider rule (deleting an image cannot tell which of an engine's ports a service was using) and names the port the listener was really found on. Port observations file each answer under the port it came from. - Desktop: the model list becomes the union of what an engine has cached and what it has resident, read through the engine:models snapshot. The model an engine is serving is not necessarily in its cache listing — a pack served straight from a path is named by neither `mtplx models` nor the listing — so a running engine with a model under it would otherwise offer nothing. A snapshot naming no list is unknown, not empty: the refresh keeps its last-good list or falls back to discovery. Tests: the two cross-process drop-in manifests still declared the old single "flag" and were rejected as manifest errors before their engine was ever known; both now declare the flag list they mean to test. And the first render of the real MTPLX and vLLM cards pins that a detect-only engine never offers to install or uninstall what PAIR does not manage, and that the model list stays available while the engine is stopped — three facts that were each one edited constant away from changing. Signed-off-by: Steven Beverly --- desktop/docs/services-parity.md | 17 +- .../electron/service-bridge/modular-state.ts | 37 +- .../service-bridge/modular-supervisor.ts | 141 +++-- .../modular/lmstudio-stale-model.test.ts | 62 ++- .../modular/local-vllm-inventory.test.ts | 28 +- .../tests/modular/mtplx-card-actions.test.ts | 104 ++++ .../modular/mtplx-served-model-list.test.ts | 173 ++++++ docs/architecture.mdx | 22 + docs/engine-lifecycle.mdx | 11 + docs/engine-settings.mdx | 11 +- services/nvpair-engine-manager/MANIFEST.md | 1 + services/nvpair-engine-manager/README.md | 42 +- services/nvpair-engine-manager/executor.go | 16 +- services/nvpair-engine-manager/install.go | 10 +- services/nvpair-engine-manager/lifecycle.go | 135 +++-- .../manifests/mtplx.json | 1 + services/nvpair-engine-manager/portsource.go | 333 ++++++++++++ .../nvpair-engine-manager/portsource_test.go | 494 ++++++++++++++++++ services/nvpair-engine-manager/registry.go | 35 ++ services/nvpair-engine-manager/spec.md | 3 +- .../nvpair-engine-manager/startup_output.go | 19 + services/nvpair-engine-manager/status.go | 157 +++--- services/nvpair-errors/README.md | 10 +- services/nvpair-ui-broker/README.md | 5 +- services/nvpair-ui-broker/advertiser.go | 26 +- services/nvpair-ui-broker/advertiser_test.go | 164 ++++++ services/nvpair-ui-broker/spec.md | 2 +- services/tests/engine_model_request_test.go | 2 +- services/tests/engine_model_selection_test.go | 2 +- 29 files changed, 1866 insertions(+), 197 deletions(-) create mode 100644 desktop/tests/modular/mtplx-card-actions.test.ts create mode 100644 desktop/tests/modular/mtplx-served-model-list.test.ts create mode 100644 services/nvpair-engine-manager/portsource.go create mode 100644 services/nvpair-engine-manager/portsource_test.go diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index fb592e7a5..09f2ccd6b 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -255,6 +255,13 @@ facade those hosts still enable has nothing to front. MTPLX itself runs on `8101 behind that facade; `8000` was not reused because it is already the vLLM facade's port and MTPLX's own default. +A server the user started themselves keeps whatever port MTPLX.app gave it, which +PAIR reads from MTPLX's own settings file on every poll, so `8101` is what PAIR +configures rather than what an already-running MTPLX answers on. A server started +with `--api-key` (or `MTPLX_API_KEY`) refuses PAIR's health checks, so it is not +adopted and no second copy is launched over it; the engine stays offline with a +warning naming that port. + MTPLX is also detect-only: the manifest declares no install block, so there is no Install action, an explicit uninstall answers that no uninstall is defined for this platform, app-data reset skips the engine, and onboarding leaves it out rather than @@ -277,7 +284,11 @@ selected; load a model to start it". Its model list comes from `mtplx models --json`, which reads the pack cache, so the list, Add model, Delete and Load all work while the engine is stopped, and only the -pack being served is advertised to peers and the proxy. Identifier matching is +pack being served is advertised to peers and the proxy. The desktop does not call +that action itself: it reads the `engine:models` snapshot and shows the union of the +cached packs and what the server has resident, because a pack served straight from a +path is named by neither `mtplx models` nor the cache listing and would otherwise be +invisible while clearly running. Identifier matching is byte-exact, as on LM Studio, llama.cpp and vLLM, rather than Ollama's implied `:latest`. Pulls and deletes are CLI actions with no byte progress, so a pull shows only that it is pulling. `mtplx remove` has no in-use guard and does not clear a @@ -360,7 +371,9 @@ through literally, with no maintained catalog of engine options or variables. ## Models -Local model state comes from engine-manager actions. Remote model state comes +Local model state comes from engine-manager actions — one `engine:models` snapshot +for vLLM and MTPLX, whose own list need not name the pack they serve, and the +`list_models` action for the rest. Remote model state comes from node-scanner enrichment and is attributed per engine. Personal AI Router uses: diff --git a/desktop/src/electron/service-bridge/modular-state.ts b/desktop/src/electron/service-bridge/modular-state.ts index 4dd9a1fd1..9e4051b4a 100644 --- a/desktop/src/electron/service-bridge/modular-state.ts +++ b/desktop/src/electron/service-bridge/modular-state.ts @@ -1884,19 +1884,40 @@ class ModularBridgeState { /** * Cache and push the local node's model list for a non-discovery engine. - * Called by the supervisor after a `list_models` pull (or with an empty list - * when the engine is stopped, since its HTTP `list_models` is unreachable). + * Called by the supervisor after a model read (or with an empty list when the + * engine is stopped, since its own list is unreachable then). + * + * `loadedNames` is the set that read reported resident in memory; `null` + * means it reported none, so residency carries over from what the node last + * reported. A supplied set is written to the node as well: + * {@link discoveryModelsForNode} and {@link getEngineInitialState} re-stamp + * residency from the node, so a cache-only update would list the model being + * served as idle. */ - setLocalEngineModels(engineType: EngineType, modelNames: string[]): void { + setLocalEngineModels( + engineType: EngineType, + modelNames: string[], + loadedNames: readonly string[] | null = null + ): void { const nodeId = this.selfId - // Stamp `'loaded'` from the self node's loaded set so a `list_models` - // refresh (pull/lifecycle) preserves residency instead of resetting every - // row to idle. The loaded set is seeded by discovery self-enrichment and - // kept fresh by {@link applyLocalModelSnapshot}. - const loaded = loadedNamesForEngine(nodeId ? this.nodes.get(nodeId) : undefined, engineType) + const node = nodeId ? this.nodes.get(nodeId) : undefined + // Stamp `'loaded'` from the read's residency, falling back to the self + // node's loaded set so a refresh (pull/lifecycle) preserves residency + // instead of resetting every row to idle. That set is seeded by discovery + // self-enrichment and kept fresh by {@link applyLocalModelSnapshot}. + const loaded = loadedNames ? new Set(loadedNames) : loadedNamesForEngine(node, engineType) const items = modelNames.map(name => modelItem(name, loaded.has(name))) this.localManagerModels.set(engineType, items) if (!nodeId) return + if (node && loadedNames) { + this.nodes.set(nodeId, { + ...node, + loadedByEngine: { + ...node.loadedByEngine, + [engineManagerName(engineType)]: [...loadedNames] + } + }) + } emitBridgePush('engines:state-changed', { nodeId, engineType, diff --git a/desktop/src/electron/service-bridge/modular-supervisor.ts b/desktop/src/electron/service-bridge/modular-supervisor.ts index 8d23bae35..d3c74e662 100644 --- a/desktop/src/electron/service-bridge/modular-supervisor.ts +++ b/desktop/src/electron/service-bridge/modular-supervisor.ts @@ -194,6 +194,52 @@ export function parseListModelNames(result: JsonValue | undefined): string[] { return names } +/** + * One engine's model list as read from the engine side: the rows to show for it + * and which of those are resident in memory. A `null` `loaded` means the read + * reported no residency, so the reader keeps the one it already has. + */ +type EngineModelInventory = { + models: string[] + loaded: string[] | null +} + +/** + * Read one engine's name list out of an engine-keyed model map. `null` means the + * map holds no usable list for that engine, which is how `nvpair-engine-manager` + * says it did not read it. + */ +function namesForEngine(map: JsonValue | undefined, engine: string): string[] | null { + const entry = objectValue(map)?.[engine] + if (!Array.isArray(entry)) return null + return entry.filter((name): name is string => typeof name === 'string') +} + +/** + * Narrow an `engine:models` reply to one engine. `downloadedByEngine` holds that + * engine's on-disk inventory and `loadedByEngine` what it serves right now, and + * engine-manager omits both keys for an engine it did not read, so a missing key + * is not an empty list: `null` comes back and the caller keeps its last-good + * list. The rows are the union of the two, because what an engine serves is not + * always in its own inventory — MTPLX lists only the packs in its cache, and + * neither vLLM's cache list nor `mtplx models` can name a model served straight + * from a path. + */ +export function parseEngineModelSnapshot( + result: JsonValue | undefined, + engine: string +): EngineModelInventory | null { + const reply = objectValue(result) + if (!reply) return null + const downloaded = namesForEngine(reply.downloadedByEngine, engine) + const loaded = namesForEngine(reply.loadedByEngine, engine) + if (downloaded === null && loaded === null) return null + return { + models: [...new Set([...(downloaded ?? []), ...(loaded ?? [])])], + loaded: loaded ?? null + } +} + function normalizeLogLevel(value: string | undefined): ModularLogLevel { const lowered = value?.toLowerCase() if (lowered && isModularLogLevel(lowered)) return lowered @@ -2015,38 +2061,69 @@ class ModularSupervisor { } /** - * Re-pull an engine's authoritative `list_models` after a model op and push - * it. Awaitable (so {@link pullModel} can land the new model in the list - * before clearing its spinner) and never throws — a failed refresh just logs. + * Re-pull an engine's authoritative model list after a model op and push it. + * Awaitable (so {@link pullModel} can land the new model in the list before + * clearing its spinner) and never throws — a failed refresh just logs. */ private async refreshEngineModels(engine: string, engineType: EngineType): Promise { if (this.stoppedModelEngines.has(engineType)) return const generation = this.beginModelRefresh(engineType) try { - const result = await this.callProcess('broker', 'engine:action', { - engine, - action: 'list_models' - }) - const models = parseListModelNames(result) - this.commitModelInventory(engineType, models, generation) + const inventory = await this.fetchModelInventory(engine, engineType) + this.commitModelInventory(engineType, inventory, generation) } catch (err) { this.handleModelRefreshFailure(engineType, generation) log.verbose({ sublevel: 'engine-manager', - message: `list_models after pull for ${engine} failed: ${getErrorString(err)}` + message: `model list after pull for ${engine} failed: ${getErrorString(err)}` }) } } /** - * Pull the local node's model list for an engine via engine-manager's - * `list_models` action, then cache + push it. Runs for **every** engine - * including Ollama: the discovery plane (proxy mDNS) advertises no model list, - * so `/api/tags` is the only working source for the local node's models. + * Ask the engine side for one engine's model list, and what that engine has + * resident in memory. + * + * Most engines answer `list_models` from their running server, and that one + * call is their whole answer. vLLM and MTPLX build their list from disk + * instead, and the model they serve is not necessarily in it, so those two + * are read through one `engine:models` sweep — the same snapshot the + * `engine:models-changed` push carries — and narrowed to the engine here. + * That is also the only way a model served by path, which neither engine's + * own list can name, reaches the model list at all. + * + * A read that names no list for the engine — a failed sweep, or an engine + * engine-manager did not read — rejects, so the caller keeps its last-good + * list or falls back to discovery rather than caching an empty one. + */ + private fetchModelInventory( + engine: string, + engineType: EngineType + ): Promise { + if (!EnginesListingModelsWhenStopped.includes(engineType)) { + return this.callProcess('broker', 'engine:action', { + engine, + action: 'list_models' + }).then(result => ({ models: parseListModelNames(result), loaded: null })) + } + return this.callProcess('broker', 'engine:models').then(result => { + const snapshot = parseEngineModelSnapshot(result, engineManagerName(engineType)) + if (!snapshot) { + throw new Error(`engine:models reported no model list for ${engine}`) + } + return snapshot + }) + } + + /** + * Pull the local node's model list for an engine from engine-manager, then + * cache + push it. Runs for **every** engine including Ollama: the discovery + * plane (proxy mDNS) advertises no model list, so engine-manager is the only + * working source for the local node's models. * `setLocalEngineModels` scopes the result to the local node, so remote nodes - * keep their discovery-derived lists. The action is an HTTP GET against the - * engine's loopback API and only works while it is running, so we clear the - * list when the engine is stopped/uninstalled. + * keep their discovery-derived lists. A read that needs the engine's loopback + * API only works while it is running, so we clear the list when the engine is + * stopped/uninstalled. */ refreshManagedEngineModels(params: JsonValue | undefined): void { const obj = objectValue(params) @@ -2078,19 +2155,15 @@ class ModularSupervisor { if (!this.hasProcess('broker')) return this.stoppedModelEngines.delete(engineType) const generation = this.beginModelRefresh(engineType) - this.callProcess('broker', 'engine:action', { - engine, - action: 'list_models' - }) - .then(result => { - const models = parseListModelNames(result) - this.commitModelInventory(engineType, models, generation) + this.fetchModelInventory(engine, engineType) + .then(inventory => { + this.commitModelInventory(engineType, inventory, generation) }) .catch(err => { this.handleModelRefreshFailure(engineType, generation) log.verbose({ sublevel: 'engine-manager', - message: `list_models for ${engine} failed: ${getErrorString(err)}` + message: `model list for ${engine} failed: ${getErrorString(err)}` }) }) } @@ -2112,13 +2185,9 @@ class ModularSupervisor { return } const generation = this.beginModelRefresh(engine) - this.callProcess('broker', 'engine:action', { - engine: engineManagerName(engine), - action: 'list_models' - }) - .then(result => { - const models = parseListModelNames(result) - this.commitModelInventory(engine, models, generation) + this.fetchModelInventory(engineManagerName(engine), engine) + .then(inventory => { + this.commitModelInventory(engine, inventory, generation) }) .catch(() => { if (this.modelRefreshGenerations.get(engine) === generation) { @@ -2134,14 +2203,18 @@ class ModularSupervisor { return generation } - private commitModelInventory(engine: EngineType, models: string[], generation: number): void { + private commitModelInventory( + engine: EngineType, + inventory: EngineModelInventory, + generation: number + ): void { if (this.modelRefreshGenerations.get(engine) !== generation) return this.stoppedModelSentinels.delete(engine) this.successfulModelInventories.add(engine) if (isProxyEngine(engine)) { this.cancelDiscoveryModelRefreshRetry(engine) } - getModularBridgeState().setLocalEngineModels(engine, models) + getModularBridgeState().setLocalEngineModels(engine, inventory.models, inventory.loaded) } private scheduleDiscoveryModelRefreshRetry(engine: ProxyEngine): void { diff --git a/desktop/tests/modular/lmstudio-stale-model.test.ts b/desktop/tests/modular/lmstudio-stale-model.test.ts index a07032e67..9f9eb1750 100644 --- a/desktop/tests/modular/lmstudio-stale-model.test.ts +++ b/desktop/tests/modular/lmstudio-stale-model.test.ts @@ -12,6 +12,7 @@ vi.mock('@/electron/window', () => ({ createOverviewWindow: vi.fn() })) import { getModularBridgeState } from '@/electron/service-bridge/modular-state' import { getModularSupervisor, + parseEngineModelSnapshot, parseListModelNames, pullModelParams } from '@/electron/service-bridge/modular-supervisor' @@ -37,6 +38,55 @@ describe('engine model wire formats', () => { ).toThrow('missing its model array') }) + it("lists a served model the engine's own inventory cannot name", () => { + // MTPLX lists only the packs in ~/.mtplx/models, so a model served from a + // path appears nowhere in that list; the snapshot's loaded set is the only + // place it is named. + expect( + parseEngineModelSnapshot( + { + models: ['mtplx-flash-next-optimized-speed'], + modelsByEngine: { mtplx: ['mtplx-flash-next-optimized-speed'] }, + downloadedByEngine: { mtplx: [], vllm: ['Qwen/Qwen3-8B'] }, + loadedByEngine: { mtplx: ['mtplx-flash-next-optimized-speed'], vllm: [] } + }, + 'mtplx' + ) + ).toEqual({ + models: ['mtplx-flash-next-optimized-speed'], + loaded: ['mtplx-flash-next-optimized-speed'] + }) + }) + + it('keeps one row for a model that is both cached and served, and marks it loaded', () => { + expect( + parseEngineModelSnapshot( + { + downloadedByEngine: { vllm: ['Qwen/Qwen3-8B', 'Qwen/Qwen3-32B'] }, + loadedByEngine: { vllm: ['Qwen/Qwen3-8B'] } + }, + 'vllm' + ) + ).toEqual({ + models: ['Qwen/Qwen3-8B', 'Qwen/Qwen3-32B'], + loaded: ['Qwen/Qwen3-8B'] + }) + }) + + it('reports no list for an engine the model sweep did not read', () => { + // A missing key is not an empty list: the caller keeps its last-good rows. + expect( + parseEngineModelSnapshot( + { models: [], loadedByEngine: { vllm: ['Qwen/Qwen3-8B'] } }, + 'mtplx' + ) + ).toBeNull() + expect( + parseEngineModelSnapshot({ downloadedByEngine: { mtplx: 'not-a-list' } }, 'mtplx') + ).toBeNull() + expect(parseEngineModelSnapshot(undefined, 'mtplx')).toBeNull() + }) + it('uses the manifest model field for llama.cpp pulls', () => { expect(pullModelParams('ollama', 'demo')).toEqual({ name: 'demo' }) expect(pullModelParams('lmstudio', 'demo')).toEqual({ model: 'demo' }) @@ -551,19 +601,17 @@ describe('model list during a vLLM model switch', () => { const state = startVllmNode() const supervisor = getModularSupervisor() const hasProcess = vi.spyOn(supervisor, 'hasProcess').mockReturnValue(true) - const call = vi - .spyOn(supervisor, 'callProcess') - .mockResolvedValue({ data: [{ id: 'Qwen/Qwen3-8B' }, { id: 'org/new' }] }) + const call = vi.spyOn(supervisor, 'callProcess').mockResolvedValue({ + downloadedByEngine: { vllm: ['Qwen/Qwen3-8B', 'org/new'] }, + loadedByEngine: { vllm: [] } + }) supervisor.refreshManagedEngineModels({ engine: 'vllm', running: false }) expect(vllmModels()).toEqual(['Qwen/Qwen3-8B', 'Qwen/Qwen3-32B']) await Promise.resolve() await Promise.resolve() - expect(call).toHaveBeenCalledWith('broker', 'engine:action', { - engine: 'vllm', - action: 'list_models' - }) + expect(call).toHaveBeenCalledWith('broker', 'engine:models') expect(vllmModels()).toEqual(['Qwen/Qwen3-8B', 'org/new']) expect(state.getEngineInitialState().statuses.length).toBeGreaterThan(0) call.mockRestore() diff --git a/desktop/tests/modular/local-vllm-inventory.test.ts b/desktop/tests/modular/local-vllm-inventory.test.ts index cabd1c2da..bf3d7b0bc 100644 --- a/desktop/tests/modular/local-vllm-inventory.test.ts +++ b/desktop/tests/modular/local-vllm-inventory.test.ts @@ -17,6 +17,17 @@ const activeModel = 'org/active-model' const downloadedModel = 'org/downloaded-model' let nextNode = 0 +/** + * The `engine:models` reply vLLM answers with: the packs in the Hugging Face + * cache (`downloadedByEngine`) and the model the server is running + * (`loadedByEngine`). A vLLM that serves a model straight from a path names it + * only in the second one. + */ +const snapshot = (loaded: string[], downloaded: string[]): JsonValue => ({ + downloadedByEngine: { vllm: downloaded }, + loadedByEngine: { vllm: loaded } +}) + async function startOwner(running: boolean, downloaded: string[]) { const state = getModularBridgeState() const supervisor = getModularSupervisor() @@ -53,7 +64,7 @@ async function startOwner(running: boolean, downloaded: string[]) { const hasProcess = vi.spyOn(supervisor, 'hasProcess').mockReturnValue(true) const call = vi .spyOn(supervisor, 'callProcess') - .mockResolvedValue({ data: downloaded.map(id => ({ id })) }) + .mockResolvedValue(snapshot(running ? [activeModel] : [], downloaded)) supervisor.refreshManagedEngineModels({ engine: 'vllm', running }) const rows = () => state @@ -98,15 +109,12 @@ describe('local vLLM downloaded inventory', () => { } ])('$name', async ({ running, before, after }) => { const owner = await startOwner(running, before) - owner.call.mockResolvedValue({ data: after.map(id => ({ id })) }) + owner.call.mockResolvedValue(snapshot(running ? [activeModel] : [], after)) owner.publish(after) await vi.waitFor(() => expect(owner.call).toHaveBeenCalledOnce()) - expect(owner.call).toHaveBeenCalledWith('broker', 'engine:action', { - engine: 'vllm', - action: 'list_models' - }) + expect(owner.call).toHaveBeenCalledWith('broker', 'engine:models') await vi.waitFor(() => expect( owner.rows()?.models.map(model => ({ name: model.name, status: model.status })) @@ -144,7 +152,7 @@ describe('local vLLM downloaded inventory', () => { it('clears a stopped owner cache when an unknown inventory becomes known empty', async () => { const owner = await startOwner(false, [downloadedModel]) owner.publish(undefined) - owner.call.mockResolvedValue({ data: [] }) + owner.call.mockResolvedValue(snapshot([], [])) owner.publish([]) @@ -177,7 +185,7 @@ describe('local vLLM downloaded inventory', () => { const owner = await startOwner(false, [downloadedModel]) owner.call .mockRejectedValueOnce(new Error('temporary list failure')) - .mockResolvedValue({ data: [] }) + .mockResolvedValue(snapshot([], [])) owner.publish([]) @@ -191,7 +199,7 @@ describe('local vLLM downloaded inventory', () => { const pendingDownload = new Promise(resolve => { finishDownload = resolve }) - owner.call.mockReturnValueOnce(pendingDownload).mockResolvedValue({ data: [] }) + owner.call.mockReturnValueOnce(pendingDownload).mockResolvedValue(snapshot([], [])) owner.publish([downloadedModel]) owner.publish([]) @@ -199,7 +207,7 @@ describe('local vLLM downloaded inventory', () => { await vi.waitFor(() => expect(owner.call).toHaveBeenCalledTimes(2)) await vi.waitFor(() => expect(owner.rows()?.models).toEqual([])) if (!finishDownload) throw new Error('Download response resolver was not initialized') - finishDownload({ data: [{ id: downloadedModel }] }) + finishDownload(snapshot([], [downloadedModel])) await pendingDownload expect(owner.rows()?.models).toEqual([]) }) diff --git a/desktop/tests/modular/mtplx-card-actions.test.ts b/desktop/tests/modular/mtplx-card-actions.test.ts new file mode 100644 index 000000000..bfe28722e --- /dev/null +++ b/desktop/tests/modular/mtplx-card-actions.test.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import type { BackendInfo } from '@/ui/types/engine-info' +import type { EngineProcessStatus, EngineType } from '@/shared/types/engines' +import { EngineCapabilities } from '@/ui/constants/engine-capabilities' +import { + EnginesListingModelsWhenStopped, + EngineDefaultLinks, + EngineDisplayNames +} from '@/shared/constants/engines' +import { BackendHeader } from '@/ui/components/BackendRow/BackendHeader' +import { BackendFooter } from '@/ui/components/BackendRow/BackendFooter' + +/** + * Renders the two parts of an engine card that decide what the user is offered: + * the header row (its on/off control plus an Install affordance when the engine + * is not installed) and the footer (the Uninstall affordance). Both are rendered + * as the card renders them, with the links a real card is given, so a change to + * the capability table or to a button's condition shows up here rather than only + * in a person's window. + */ +function cardFor(engineType: EngineType, processStatus: EngineProcessStatus): BackendInfo { + return { + type: engineType, + displayName: EngineDisplayNames[engineType], + source: 'detected', + processStatus, + port: 8101, + proxyPort: 8100, + models: [], + modelsKnown: EnginesListingModelsWhenStopped.includes(engineType), + docsUrl: EngineDefaultLinks[engineType].docsUrl, + installUrl: EngineDefaultLinks[engineType].installUrl + } +} + +function headerMarkup(backend: BackendInfo): string { + return renderToStaticMarkup( + createElement(BackendHeader, { + backend, + isTransitioning: false, + isUnavailable: false, + disabled: false, + onToggle: () => {}, + onStop: () => {}, + onExpand: () => {}, + expanded: false, + isLocalNode: true, + targetOs: 'MacOS', + onInstall: () => {} + }) + ) +} + +function footerMarkup(backend: BackendInfo): string { + return renderToStaticMarkup( + createElement(BackendFooter, { + backend, + targetOs: 'MacOS', + showUninstall: true, + disabled: false, + onUninstall: () => {} + }) + ) +} + +describe('MTPLX engine card on Apple Silicon macOS', () => { + it('offers no install command for MTPLX, where vLLM on the same Mac gets one', () => { + const mtplx = headerMarkup(cardFor('mtplx', 'not-installed')) + const vllm = headerMarkup(cardFor('vllm', 'not-installed')) + + expect(vllm).toContain('Install') + expect(mtplx).not.toContain('>Install<') + expect(mtplx).not.toContain('Install all') + // Reading about MTPLX and getting it from its own distribution is still + // offered; it is only PAIR installing it that is not. + expect(mtplx).toContain('Download') + }) + + it('offers no uninstall for MTPLX, where vLLM on the same Mac gets one', () => { + const mtplx = footerMarkup(cardFor('mtplx', 'running')) + const vllm = footerMarkup(cardFor('vllm', 'running')) + + expect(vllm).toContain('Uninstall') + expect(mtplx).not.toContain('Uninstall') + // A server the user started is still theirs to stop: the card keeps its + // on/off control, which for a running engine reads as Stop. + expect(headerMarkup(cardFor('mtplx', 'running'))).toContain('Stop MTPLX') + }) + + it('keeps MTPLX model controls available while the engine is stopped', () => { + // The pack inventory and the resident set arrive on the `engine:models` + // snapshot, which is read while the engine is stopped, so a stopped + // engine is not shown as having nothing to load. + expect(EnginesListingModelsWhenStopped).toContain('mtplx') + expect(EngineCapabilities.mtplx.hasModelSearchOnlyWhenRunning).toBe(false) + expect(EngineCapabilities.mtplx.hasInstall).toEqual([]) + expect(EngineCapabilities.mtplx.hasEject).toBe(true) + }) +}) diff --git a/desktop/tests/modular/mtplx-served-model-list.test.ts b/desktop/tests/modular/mtplx-served-model-list.test.ts new file mode 100644 index 000000000..683d94060 --- /dev/null +++ b/desktop/tests/modular/mtplx-served-model-list.test.ts @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { isPackaged: false, getAppPath: () => process.cwd() }, + BrowserWindow: { getAllWindows: () => [] } +})) +vi.mock('@/electron/window', () => ({ createOverviewWindow: vi.fn() })) + +import { getModularBridgeState } from '@/electron/service-bridge/modular-state' +import { getModularSupervisor } from '@/electron/service-bridge/modular-supervisor' + +/** + * A custom model started from a folder. MTPLX serves it, but it is not a pack in + * the cache, so MTPLX's own model list cannot name it — only the resident set can. + */ +const servedModel = 'mtplx-flash-next-optimized-speed' +/** A model pack in `~/.mtplx/models`, which MTPLX's own model list does name. */ +const cachedPack = 'mtplx/mtplx-lite' +let nextNode = 0 + +/** + * A Mac that already runs MTPLX before PAIR starts: the engine-manager reports + * MTPLX online and the self node is known. `discoveryResident` is what the node's + * discovery record says MTPLX has in memory before any model sweep is read; each + * case then decides what `engine:models` answers. + */ +function startMTPLX(discoveryResident: string[]) { + const state = getModularBridgeState() + const supervisor = getModularSupervisor() + const nodeId = `mtplx-served-model-${++nextNode}` + + state.setLocalDiscoveryModelRefresher(() => {}) + state.setSelfId(nodeId) + state.handleNotification({ + source: 'broker', + method: 'discovery:nodes-changed', + params: { + nodes: [ + { + hostUuid: nodeId, + name: `${nodeId}-host`, + ipAddress: '192.0.2.10', + port: 14318, + models: discoveryResident, + modelsByEngine: { mtplx: discoveryResident }, + loadedByEngine: { mtplx: discoveryResident } + } + ] + } + }) + state.applyEngineManagerStatus({ + engine: 'mtplx', + installed: true, + running: true, + healthy: true + }) + + vi.spyOn(supervisor, 'hasProcess').mockReturnValue(true) + const call = vi.spyOn(supervisor, 'callProcess').mockResolvedValue({}) + const rows = () => + state + .getEngineInitialState() + .models.find(group => group.nodeId === nodeId && group.engineType === 'mtplx') + + return { state, supervisor, call, rows } +} + +afterEach(() => { + getModularBridgeState().setLocalDiscoveryModelRefresher(() => {}) + vi.restoreAllMocks() +}) + +describe('MTPLX model list', () => { + it('lists the model MTPLX serves although its own model list cannot name it', async () => { + const machine = startMTPLX([servedModel]) + machine.call.mockResolvedValue({ + models: [servedModel], + modelsByEngine: { mtplx: [servedModel] }, + downloadedByEngine: { mtplx: [cachedPack] }, + loadedByEngine: { mtplx: [servedModel] } + }) + + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + + await vi.waitFor(() => expect(machine.call).toHaveBeenCalledOnce()) + expect(machine.call).toHaveBeenCalledWith('broker', 'engine:models') + await vi.waitFor(() => + expect( + machine.rows()?.models.map(model => ({ name: model.name, status: model.status })) + ).toEqual([ + { name: cachedPack, status: 'idle' }, + { name: servedModel, status: 'loaded' } + ]) + ) + expect(machine.rows()?.inventoryKnown).toBe(true) + }) + + it('lists only MTPLX models although the model sweep covers every engine', async () => { + const machine = startMTPLX([]) + machine.call.mockResolvedValue({ + models: ['Qwen/Qwen3-8B', cachedPack, servedModel], + modelsByEngine: { vllm: ['Qwen/Qwen3-8B'], mtplx: [servedModel] }, + downloadedByEngine: { vllm: ['Qwen/Qwen3-8B'], mtplx: [cachedPack] }, + loadedByEngine: { vllm: ['Qwen/Qwen3-8B'], mtplx: [servedModel] } + }) + + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + + await vi.waitFor(() => + expect(machine.rows()?.models.map(model => model.name)).toEqual([ + cachedPack, + servedModel + ]) + ) + }) + + it('marks no model loaded once the sweep reports MTPLX serves nothing', async () => { + const machine = startMTPLX([servedModel]) + // First read: MTPLX serves the custom model. Discovery already said so, so + // a list that kept showing it loaded after the second read would be wrong. + machine.call.mockResolvedValue({ + downloadedByEngine: { mtplx: [cachedPack] }, + loadedByEngine: { mtplx: [servedModel] } + }) + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + await vi.waitFor(() => + expect(machine.rows()?.models.find(model => model.name === servedModel)?.status).toBe( + 'loaded' + ) + ) + machine.call.mockClear() + + // MTPLX quits: its cache is still on disk and nothing is in memory. + machine.call.mockResolvedValue({ + downloadedByEngine: { mtplx: [cachedPack] }, + loadedByEngine: { mtplx: [] } + }) + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: false }) + + await vi.waitFor(() => expect(machine.call).toHaveBeenCalledOnce()) + await vi.waitFor(() => + expect( + machine.rows()?.models.map(model => ({ name: model.name, status: model.status })) + ).toEqual([{ name: cachedPack, status: 'idle' }]) + ) + }) + + it('keeps the last model list when the sweep reports none for MTPLX', async () => { + const machine = startMTPLX([servedModel]) + machine.call.mockResolvedValue({ + downloadedByEngine: { mtplx: [cachedPack] }, + loadedByEngine: { mtplx: [servedModel] } + }) + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + await vi.waitFor(() => expect(machine.rows()?.models).toHaveLength(2)) + machine.call.mockClear() + + // A sweep that names no list for MTPLX is not a sweep that says MTPLX has + // no models: the rows stay rather than flashing empty until the next read. + machine.call.mockResolvedValue({ + models: ['Qwen/Qwen3-8B'], + modelsByEngine: { vllm: ['Qwen/Qwen3-8B'] }, + loadedByEngine: { vllm: [] } + }) + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + + await vi.waitFor(() => expect(machine.call).toHaveBeenCalledOnce()) + expect(machine.rows()?.models.map(model => model.name)).toEqual([cachedPack, servedModel]) + }) +}) diff --git a/docs/architecture.mdx b/docs/architecture.mdx index cb79af9a9..45777a40c 100644 --- a/docs/architecture.mdx +++ b/docs/architecture.mdx @@ -526,6 +526,28 @@ Starting is similarly deferential. If something is already serving the engine's port, PAIR **adopts** that instance instead of spawning a second copy, and reports it as running even though it did not start it. +An engine started that way does not always answer on the port PAIR configured for +it, so a manifest may declare a `port_source`: a settings file and the key in it +naming the port the engine really listens on. MTPLX declares one, because MTPLX.app +records its chosen port in `~/Library/Application Support/MTPLX/settings.json` and +that port is often neither `8101` nor MTPLX's own default. Every candidate port is +probed on each poll, and the file is read again each round, so moving an engine in +its own application takes effect on the next poll without restarting PAIR. A +manifest with no `port_source` probes the one configured port it probed before any +of this existed. + +A stranger on a search-only port does not stand in the way of a launch, because a +launch PAIR writes is given the configured port, so only something on that port — +or a credential refusal anywhere, which is the engine itself refusing PAIR — keeps +a second copy from starting. + +A port that answers the health check with 401 or 403 is a service expecting an API +key. PAIR never sends one, so that engine is neither adopted nor restarted: it +stays shown offline with one standing warning naming the port and its status, which +clears as soon as the port answers. Reporting that as an unrecognised service would +send the user looking for a different engine while the right one is already +running. + Adoption is a real distinction, not a label. PAIR does not kill a process it did not start, so it refuses operations that would need to rather than faking them. The exception is an engine with an official stop command: PAIR stops an adopted diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index 216553f65..df855afb7 100644 --- a/docs/engine-lifecycle.mdx +++ b/docs/engine-lifecycle.mdx @@ -163,6 +163,13 @@ When you install an engine, consider the following: has mapped. Only the pack being served is advertised to other nodes, so a request naming a different cached pack is refused until you load it. + An MTPLX server you started yourself, from MTPLX.app for example, is used rather + than duplicated. PAIR finds it on the port that app chose, read from MTPLX's own + settings file, and shows the engine online without starting a second router over + it. A server started with an API key refuses PAIR's health check, so it stays + offline with a warning naming that port: start it without a key, or on a port + nothing is listening on, if you want PAIR to route it. + PAIR-managed llama.cpp models sleep after five minutes without inference work. This releases model and KV-cache memory, and the next request wakes the model automatically. The llama.cpp worker remains running and can retain some GPU @@ -247,6 +254,10 @@ controlled: the engine in its own application first if you want PAIR to manage it fully. - **LM Studio** publishes an official stop command, so PAIR can stop an adopted instance that way and restart it on the port you chose. +- **MTPLX** has no stop command, so PAIR leaves an adopted server running: stop it + in MTPLX.app first, then start it again from PAIR to move it. A server that asks + for an API key is not adopted at all — its port refuses PAIR, so the engine stays + offline with a warning naming that port. Refer to [Engines and Ports](architecture.mdx#engines-and-ports) in the architecture guide. diff --git a/docs/engine-settings.mdx b/docs/engine-settings.mdx index 9c0b71d38..fb81a88b3 100644 --- a/docs/engine-settings.mdx +++ b/docs/engine-settings.mdx @@ -166,7 +166,16 @@ searching Hugging Face, because only those packs run on it. MTPLX asks for an API key only where one is configured, and PAIR configures none, so a managed MTPLX is unauthenticated on loopback like the other OpenAI-compatible endpoints. If you add `--api-key` to the launch text or run PAIR with -`MTPLX_API_KEY` set, the server demands that key and PAIR does not supply one. +`MTPLX_API_KEY` set, the server demands that key and PAIR never supplies one. It +refuses to start a second copy over your server, and while the key stays in place +the engine is shown offline with a warning naming the refusing port. Remove the key, +or choose a port nothing is listening on. + +A server you started yourself is found on the port it actually uses. PAIR asks both +the port set in **Server port** and the port named in MTPLX's own settings file at +`~/Library/Application Support/MTPLX/settings.json`, so an MTPLX.app server on a +port of your choosing shows as online with nothing to configure in PAIR. That file +only says where to look: a launch PAIR writes still uses **Server port**. Changing the server-port field updates the port in the command. Editing the command's port updates the numeric field. If both are edited before validation diff --git a/services/nvpair-engine-manager/MANIFEST.md b/services/nvpair-engine-manager/MANIFEST.md index fe1937b4b..1c3fc902e 100644 --- a/services/nvpair-engine-manager/MANIFEST.md +++ b/services/nvpair-engine-manager/MANIFEST.md @@ -228,6 +228,7 @@ applies to the host the test runs on. | `args` | string[] | no | Arguments (process mode). | | `env` | object | no | Extra environment (merged over the inherited env). Use `{host}`/`{port}` for the listen address, e.g. `"OLLAMA_HOST": "{host}:{port}"`. | | `port` | int | no | Fixed port, or `0` to auto-assign a free loopback port. | +| `port_source` | object | no | Where the engine keeps the port it really listens on: `{"file":"","field":""}`, `field` defaulting to `port`. PAIR probes that port beside `port`, so an engine the user started themselves is adopted wherever their own app put it instead of being read as an empty port. Read fresh each poll; a missing file or key tells PAIR nothing. Requires `ready`. | | `bind` | string | no | Listen address, substituted as `{host}`. Empty ⇒ `127.0.0.1` (the safe default); an inference engine that serves the cluster sets `"0.0.0.0"`. A per-call `bind` via `engine:start {bind}` overrides this for one call, but a non-loopback value is honored only when the `engine_allow_lan_bind` node setting is on — otherwise the start is rejected with `-32602` (`bind must be a loopback address`). Probes always target loopback. | | `start` | string[][] | command mode | Ordered bring-up commands (each an argv) for `command` mode, e.g. `[["{cli}","server","start","--port","{port}"]]`. | | `cli` | string | no | The engine's control-CLI path for this platform, referenced as `{cli}` by start/stop/actions so the manifest's **global** actions resolve to the correct per-OS binary. | diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index ee3a02c3c..fa3ec06b4 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -602,12 +602,16 @@ platform. Explicit custom stop commands are executed unchanged. ### Adoption — start may attach to an engine it didn't launch -Before spawning, `engine:start` **probes the chosen port's readiness -endpoint**, including any manifest-declared JSON identity. If a compatible -service answers there — the engine's own desktop -app (e.g. the Ollama tray app on `11434`), or an instance left running from a -previous session — the service **adopts** that instance: it marks the engine -`running` without launching its own, rather than spawning a duplicate that +Before spawning, `engine:start` **probes the readiness endpoint of every +candidate port for the engine**: the configured port, plus the port the engine +keeps in its own settings file when the manifest declares a `port_source`. +That file is re-read on every probe round, so an engine the user moved in +their own application is found where it actually is without restarting PAIR. +The probe includes any manifest-declared JSON identity. If a compatible +service answers on one of those ports — the engine's own desktop app (e.g. +the Ollama tray app on `11434`), or an instance left running from a previous +session — the service **adopts** that instance: it marks the engine `running` +on that port without launching its own, rather than spawning a duplicate that would only collide on the port. Consequences worth knowing: - **An adopted engine has no child process the service owns**, so `engine:stop` @@ -642,6 +646,32 @@ would only collide on the port. Consequences worth knowing: following `start:true` then adopts the running instance. - **Liveness reconciliation uses the same probe.** A fixed-port engine found already serving is reported `running: true` even though NVPAIR never started it. +- **A port that answers 401 or 403 is a service waiting for an API key**, which + PAIR never sends. That engine is neither adopted nor restarted: a `start` + there fails at once, naming the refusing port and its status, instead of + waiting out the readiness timeout. While the refusal holds the engine carries + one standing `engine-manager:auth-blocked:` warning naming that port + — only for an engine the user turned on, and only on the way into that state, + because re-reporting per poll re-raises a dialog the user has already + dismissed. The warning clears once the port answers. +- **Only the port a new copy would bind is blocked by a stranger.** A listener that + answers without identifying as this engine keeps `engine:start` and + `engine:install` off *that* port. On a candidate port that exists only to find + the engine — one named by `port_source` — it does not: PAIR hands the engine the + configured port when it launches one, so a stranger sitting on the searched port + is not in the way, and refusing over it left the engine offline because of a + service the user never asked PAIR about. A credential refusal is the exception, + because that one is the engine itself; it blocks from any candidate port. +- **`engine:uninstall` keeps the wider rule.** Deleting an image cannot tell which + of an engine's ports a service answering on one of them was using, so it declines + while any unidentified service or unreadable port is found, and its message names + the port the listener was actually found on rather than the configured one. +- **An adopted service is only given up after every candidate port refuses three + times in a row.** A timeout, or a listener that answers without identifying as + this engine, keeps the previous state rather than clearing it, so one dropped + request cannot flip a running engine to offline. When it does go, the port goes + back to the configured one instead of staying pinned where the adopted service + answered. `engine:status` and `engine:get-installed` check engines without holding the lock used by start, stop, and port changes. Overlapping requests for the same engine diff --git a/services/nvpair-engine-manager/executor.go b/services/nvpair-engine-manager/executor.go index a4073a7a3..0e6b3088a 100644 --- a/services/nvpair-engine-manager/executor.go +++ b/services/nvpair-engine-manager/executor.go @@ -78,9 +78,13 @@ type engineState struct { healthy bool stopping bool // starting is true while a start launches the engine and waits for readiness. - awaitingModel bool - starting bool - adopted bool // started externally; we can't stop it + awaitingModel bool + starting bool + adopted bool // started externally; we can't stop it + // authBlocked records that this engine's port refused PAIR's health check + // for credentials, so the notice is raised and cleared on the transition + // rather than on every poll. + authBlocked bool gen int64 // bumped each start; gates stale health loops port int binPath string @@ -438,4 +442,10 @@ func startFailedID(engine string) string { return "engine-manager:start-failed:" func unhealthyID(engine string) string { return "engine-manager:unhealthy:" + engine } +// authBlockedID names the standing notice that an engine's port refuses PAIR's +// health checks for credentials. It is reported on the transition into that +// state and cleared on the way out, because the error feed keeps one entry per +// id and a re-report re-raises a dialog the user has already dismissed. +func authBlockedID(engine string) string { return "engine-manager:auth-blocked:" + engine } + func exitedID(engine string) string { return "engine-manager:exited:" + engine } diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index 4c4c2b024..1bc962540 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -7,6 +7,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" "log/slog" @@ -47,8 +48,8 @@ func (e *Executor) Install(ctx context.Context, engine string) error { e.emitInstallProgress(engine, "already-installed", 100) return nil } - if presence.Occupied && st.plat.Runtime.modeOrDefault() == "process" { - err := fmt.Errorf("cannot install engine %q for port %d: the port is occupied by a service that did not identify as %s; use the existing service or choose another port", engine, port, st.manifest.DisplayName) + if presence.obs.spawnBlocked() && st.plat.Runtime.modeOrDefault() == "process" { + err := errors.New(presence.obs.installRefusal(engine, st.manifest.DisplayName)) e.reportInstallFailed(engine, err) return err } @@ -193,7 +194,10 @@ func (e *Executor) Uninstall(ctx context.Context, engine string) error { ownedProcess := st.proc != nil st.mu.Unlock() if presence.Occupied && !presence.Identified && !ownedProcess { - err := fmt.Errorf("cannot uninstall engine %q: port %d is occupied by an unidentified service", engine, port) + // Deleting the image is refused while anything PAIR cannot identify is + // answering on a port this engine uses, wherever that is, and the + // refusal names the port the service was found on. + err := fmt.Errorf("cannot uninstall engine %q: port %d is occupied by an unidentified service", engine, presence.obs.servicePort()) e.reporter.report(serviceError{ID: uninstallFailedID(engine), Message: err.Error(), Severity: "error", Action: "none", EngineType: engine, Operation: "uninstall"}) return err } diff --git a/services/nvpair-engine-manager/lifecycle.go b/services/nvpair-engine-manager/lifecycle.go index d8f70a126..d193a4ada 100644 --- a/services/nvpair-engine-manager/lifecycle.go +++ b/services/nvpair-engine-manager/lifecycle.go @@ -189,14 +189,18 @@ func (e *Executor) doStart(ctx context.Context, st *engineState, engine string, if opts.RequireOwned { return refuse(fmt.Errorf("cannot apply launch settings: another process already owns the server port")) } - slog.Info("adopting already-running external engine", "engine", engine, "port", port) + // The engine answers on presence.Port, which is wherever it really is + // rather than the port PAIR asked about, so the health loop follows it. + slog.Info("adopting already-running external engine", "engine", engine, "port", presence.Port) st.mu.Lock() st.gen++ gen := st.gen + st.authBlocked = false st.mu.Unlock() e.reporter.clear(startFailedID(engine)) e.reporter.clear(exitedID(engine)) e.reporter.clear(unhealthyID(engine)) + e.reporter.clear(authBlockedID(engine)) if rt.Health != nil { hctx, cancel := context.WithCancel(context.Background()) st.mu.Lock() @@ -205,12 +209,16 @@ func (e *Executor) doStart(ctx context.Context, st *engineState, engine string, } st.healthStop = cancel st.mu.Unlock() - go e.runHealth(hctx, st, engine, port, gen) + go e.runHealth(hctx, st, engine, presence.Port, gen) } return nil } - if presence.Occupied && rt.modeOrDefault() == "process" { - return refuse(fmt.Errorf("cannot start engine %q on port %d: the port is occupied by a service that did not identify as %s", engine, port, st.manifest.DisplayName)) + // Only what sits on the port a new copy would bind, or an engine that will + // not answer PAIR for credentials, keeps it from starting. A stranger on a + // port this engine merely searches is not in the way of a server bound + // somewhere else, and PAIR hands MTPLX the port to bind. + if presence.obs.spawnBlocked() && rt.modeOrDefault() == "process" { + return refuse(errors.New(presence.obs.startRefusal(engine, st.manifest.DisplayName))) } // Not reported: a client offers Install, not Start, for an engine that is // not installed, and an engine removed outside PAIR would otherwise raise an @@ -266,12 +274,14 @@ func (e *Executor) doStart(ctx context.Context, st *engineState, engine string, st.running = true st.healthy = true st.adopted = false + st.authBlocked = false st.gen++ gen := st.gen st.mu.Unlock() e.reporter.clear(startFailedID(engine)) e.reporter.clear(exitedID(engine)) e.reporter.clear(unhealthyID(engine)) + e.reporter.clear(authBlockedID(engine)) e.emitState(engine) st.mu.Lock() @@ -751,31 +761,7 @@ func (e *Executor) markStopped(st *engineState, engine string) { // live listener returning 503 is unhealthy, not stopped. A successful control // command is likewise not proof that its daemon actually exited. func (e *Executor) waitUnavailable(p *Probe, port int, timeout time.Duration) bool { - return e.waitUnavailableContext(context.Background(), p, port, timeout) -} - -func (e *Executor) waitUnavailableContext(parent context.Context, p *Probe, port int, timeout time.Duration) bool { - ctx, cancel := context.WithTimeout(parent, timeout) - defer cancel() - misses := 0 - for { - result := probeListener(ctx, p, port) - if result == listenerProbeRefused { - misses++ - if misses == unavailableConfirmations { - return true - } - } else { - // A reachable listener, timeout, or malformed/indeterminate target - // cannot prove shutdown. Require a fresh consecutive sequence. - misses = 0 - } - select { - case <-ctx.Done(): - return false - case <-time.After(100 * time.Millisecond): - } - } + return e.confirmPortsQuiet(context.Background(), p, []int{port}, timeout) } // probeListener reports whether the transport endpoint described by a @@ -1066,7 +1052,9 @@ func (e *Executor) runHealth(ctx context.Context, st *engineState, engine string } // waitReady polls the readiness probe until it passes or the manifest's -// allowance, counted from began, runs out. +// allowance, counted from began, runs out. A credential refusal ends the wait +// at once: that answer does not change with time, so spending the remaining +// window on it only delays telling the user. func (e *Executor) waitReady(ctx context.Context, p *Probe, port int, began time.Time) error { if p == nil { return nil @@ -1077,8 +1065,12 @@ func (e *Executor) waitReady(ctx context.Context, p *Probe, port int, began time } deadline := began.Add(timeout) for { - if e.probe(ctx, p, port) { + answer := e.probeIdentity(ctx, p, port) + switch { + case answer.outcome == probeIdentified: return nil + case answer.blocked(): + return &readyBlockedError{port: port, status: answer.status} } if time.Now().After(deadline) { return &readyTimeoutError{timeout: timeout} @@ -1091,68 +1083,119 @@ func (e *Executor) waitReady(ctx context.Context, p *Probe, port int, began time } } +// probeOutcome is what an identity probe learned, not merely whether PAIR was +// satisfied. "Not this engine" splits in two, because a service that refuses +// PAIR for credentials is this engine configured in a way PAIR cannot work with +// rather than somebody else's, and the two need different advice. +type probeOutcome uint8 + +const ( + // probeUnanswered covers every other answer: nothing listening, a service + // that answers something else, a status the manifest did not expect. + probeUnanswered probeOutcome = iota + // probeIdentified is the expected status and, where the manifest asks for + // one, a body that matches. + probeIdentified + // probeKeyProtected is HTTP 401: the service wants an API key. MTPLX answers + // every route but its dashboard bundle this way once one is configured. + probeKeyProtected + // probeRefusedAuth is HTTP 403: the service refuses requests that carry no + // credentials at all. + probeRefusedAuth +) + +type probeResult struct { + outcome probeOutcome + status int +} + +// blocked says the port refused PAIR for credentials. Nothing is gained by +// waiting for that to change. +func (r probeResult) blocked() bool { + return r.outcome == probeKeyProtected || r.outcome == probeRefusedAuth +} + +// probe is the yes/no form of the identity probe, for the health loop, where a +// credential refusal simply means the engine is not answering PAIR. func (e *Executor) probe(ctx context.Context, p *Probe, port int) bool { + return e.probeIdentity(ctx, p, port).outcome == probeIdentified +} + +func (e *Executor) probeIdentity(ctx context.Context, p *Probe, port int) probeResult { if p == nil { - return true + return probeResult{outcome: probeIdentified} } vars := map[string]string{"port": strconv.Itoa(port)} if p.HTTP != "" { u, err := resolvePlaceholders(p.HTTP, vars) if err != nil { - return false + return probeResult{} } pctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() req, err := http.NewRequestWithContext(pctx, http.MethodGet, u, nil) if err != nil { - return false + return probeResult{} } req.Header.Set(engineIdentityProbeHeader, "1") resp, err := e.client.Do(req) if err != nil { - return false + return probeResult{} } want := p.Status if want == 0 { want = 200 } - statusMatches := resp.StatusCode == want + if resp.StatusCode != want { + outcome := probeUnanswered + switch resp.StatusCode { + case http.StatusUnauthorized: + outcome = probeKeyProtected + case http.StatusForbidden: + outcome = probeRefusedAuth + } + httpcon.DrainAndClose(resp.Body) + return probeResult{outcome: outcome, status: resp.StatusCode} + } if p.JSONMatch == nil { httpcon.DrainAndClose(resp.Body) - return statusMatches + return probeResult{outcome: probeIdentified} } body, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeJSONBytes+1)) httpcon.DrainAndClose(resp.Body) - if !statusMatches || err != nil || len(body) > maxProbeJSONBytes { - return false + if err != nil || len(body) > maxProbeJSONBytes { + return probeResult{} } var obj map[string]json.RawMessage if err := json.Unmarshal(body, &obj); err != nil { - return false + return probeResult{} } value, ok := resolveObjectPath(obj, p.JSONMatch.Field) if !ok { - return false + return probeResult{} } var actual string - return json.Unmarshal(value, &actual) == nil && actual == p.JSONMatch.Value + if json.Unmarshal(value, &actual) == nil && actual == p.JSONMatch.Value { + return probeResult{outcome: probeIdentified} + } + return probeResult{} } if p.TCP != "" { addr, err := resolvePlaceholders(p.TCP, vars) if err != nil { - return false + return probeResult{} } pctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() conn, err := (&net.Dialer{}).DialContext(pctx, "tcp", addr) if err != nil { - return false + return probeResult{} } conn.Close() - return true + return probeResult{outcome: probeIdentified} } - return true + return probeResult{outcome: probeIdentified} } func (e *Executor) reportStartFailed(engine string, err error) { diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index efaa10627..ed73f288d 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -25,6 +25,7 @@ "args": ["serve", "--host", "{host}", "--port", "{port}"], "bind": "127.0.0.1", "port": 8101, + "port_source": { "file": "~/Library/Application Support/MTPLX/settings.json", "field": "port" }, "ready": { "http": "http://127.0.0.1:{port}/health", "status": 200, "timeout_s": 600 }, "stop": { "signal": "term", "grace_s": 15 }, "health": { "http": "http://127.0.0.1:{port}/health", "status": 200, "interval_s": 5 } diff --git a/services/nvpair-engine-manager/portsource.go b/services/nvpair-engine-manager/portsource.go new file mode 100644 index 000000000..21e26ade4 --- /dev/null +++ b/services/nvpair-engine-manager/portsource.go @@ -0,0 +1,333 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Package main — portsource.go is the port-candidate layer underneath the +// engine lifecycle: which loopback ports are worth asking, what asking them +// learned, and how to say what was found. +// +// It exists because a fixed configured port is not always where an engine is. +// An engine the user started themselves listens wherever their own app keeps +// it, which is often not PAIR's default, and it is the only copy that will ever +// answer there. Both jobs the lifecycle has — deciding whether to adopt what is +// already running, and deciding whether it is safe to start another copy — need +// the same round of asking, though they read different answers off it, so the +// round and what it learns live here. + +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "slices" + "strconv" + "strings" + "time" +) + +// maxPortFileBytes bounds the settings-file read that looks up an engine's own +// port. A real one is a few kilobytes; the cap keeps a pathological file, or a +// symlink to something enormous, from being pulled into memory on every poll. +const maxPortFileBytes = 64 << 10 + +// neverSendsKey is the half of every credential-refusal message that explains +// why a refusal is the right answer rather than a workaround PAIR could apply. +const neverSendsKey = "NVIDIA PAIR never sends an API key, so it can neither use that service nor start a second copy beside it." + +// portObservation is what one round of asking an engine's candidate ports +// learned about whatever is listening there. Each fact names the port it was +// found on instead of only saying that it was found somewhere, because the ports +// a round covers are not equal: one is the port PAIR would bind, and the rest +// are only places the engine might keep its real port. +type portObservation struct { + // bind is the port a copy of PAIR's own would use: the one the caller came + // to check, which candidatePorts lists first. A refusal that finds no + // credential refusal names this one, because it is the port the user was + // told to look at. + bind int + // identified is a candidate that answered exactly as this engine's manifest + // says its engine answers. It is the service to adopt, on that port. + identified int + // blocked is a candidate that refused PAIR for credentials: HTTP 401, which + // means it wants an API key, or HTTP 403, which means it refuses requests + // that carry none. It is still a live service, and PAIR can never become one + // with it, so neither adoption nor a second copy is correct. + blocked int + // blockedStatus is the 401 or 403 behind blocked. + blockedStatus int + // stranger is a candidate that took connections and answered the probe as + // something that is not this engine. + stranger int + // unsure names a candidate that could not be read at all — a dial that timed + // out or failed for a reason other than refusal. That proves nothing about + // whether anything listens, so it is never read as an empty port. + unsure int + // quiet says every candidate refused the connection: nothing is listening. + quiet bool +} + +// answered says the round found a live service that is not this engine. +func (o portObservation) answered() bool { return o.blocked != 0 || o.stranger != 0 } + +// occupied says the round heard something back anywhere: the engine answering as +// itself, a stranger, a credential refusal, or a port it could not read. Both of +// the callers that ask this question are about to act on the assumption that +// nothing is there — delete the engine's files, or call its service gone — and +// neither can tell which of the ports it asked was the one it needed, so none of +// them counts as empty. Whether a port stands in the way of a second copy is the +// narrower question, and spawnBlocked answers it. +func (o portObservation) occupied() bool { + return o.identified != 0 || o.answered() || o.unsure != 0 +} + +// spawnBlocked says a Start or Install must not bring up a second copy. +// +// Only the port that copy would bind is in its way. PAIR launches an engine on a +// port of its own — MTPLX is handed --port — so a stranger found while searching +// for the engine's real port is nowhere near the port a new copy needs, and +// refusing over it left the user with no engine at all because of a service they +// never asked PAIR about. +// +// A credential refusal blocks from any port, because that one is this engine, set +// up in a way PAIR cannot work with. A second copy beside it would be the +// duplicate router the user already has, on a model that is already served. +func (o portObservation) spawnBlocked() bool { + if o.blocked != 0 { + return true + } + return o.bind != 0 && (o.stranger == o.bind || o.unsure == o.bind) +} + +// servicePort names the port a service that is not this engine was found on, for +// a message that has to point at a listener that is really there rather than at +// the port PAIR happened to ask about. +func (o portObservation) servicePort() int { + switch { + case o.stranger != 0: + return o.stranger + case o.unsure != 0: + return o.unsure + } + return o.bind +} + +// credentialRefusalClause states a credential refusal as a clause about a +// service that has already been named. +func credentialRefusalClause(status int) string { + switch status { + case 401: + return "it requires an API key" + case 403: + return "it refuses requests that carry no credentials" + } + return "it will not answer NVIDIA PAIR's health check" +} + +// blockedAnswer states the refusal as a clause about the service, for a +// sentence that has already named it. +func (o portObservation) blockedAnswer() string { return credentialRefusalClause(o.blockedStatus) } + +// startRefusal is the whole reason a Start is refused: what was found on the +// port and what the user can do about it. The two shapes say different things, +// which is why they are not one sentence. A stranger on the port is somebody +// else's service and worth leaving alone; a credential refusal is this engine, +// set up in a way PAIR cannot work with, and telling the user to look elsewhere +// for a service that "did not identify as MTPLX" sends them hunting for a +// different engine while the right one is already running. +func (o portObservation) startRefusal(engine, displayName string) string { + if o.blocked != 0 { + return fmt.Sprintf("cannot start engine %q: %s %s Start %s without an API key, or choose a port nothing is listening on", + engine, o.credentialSummary(), neverSendsKey, displayName) + } + return fmt.Sprintf("cannot start engine %q on port %d: the port is occupied by a service that did not identify as %s", + engine, o.bind, displayName) +} + +// installRefusal is the same for an Install, which additionally has to say that +// fetching a second copy of the engine is off the table. +func (o portObservation) installRefusal(engine, displayName string) string { + if o.blocked != 0 { + return fmt.Sprintf("cannot install engine %q: %s %s Install %s on a port nothing is listening on, or start it without an API key", + engine, o.credentialSummary(), neverSendsKey, displayName) + } + return fmt.Sprintf("cannot install engine %q for port %d: the port is occupied by a service that did not identify as %s; use the existing service or choose another port", + engine, o.bind, displayName) +} + +// credentialSummary names the refusing port and its status, in a sentence that +// stands on its own before the advice. +func (o portObservation) credentialSummary() string { + return fmt.Sprintf("The service already listening on port %d answers NVIDIA PAIR's health check with HTTP %d because %s.", + o.blocked, o.blockedStatus, o.blockedAnswer()) +} + +// authBlockedNotice is the standing version of the same fact, for the error +// feed while a port stays in this state. It is reported once per episode, not +// once per poll: the feed holds one entry per id, and refreshing one re-raises +// a dialog the user has already dismissed. +func (o portObservation) authBlockedNotice(displayName string) string { + return fmt.Sprintf("%s on port %d answers NVIDIA PAIR's health check with HTTP %d because %s. %s Start it without an API key, or choose a port nothing is listening on", + displayName, o.blocked, o.blockedStatus, o.blockedAnswer(), neverSendsKey) +} + +// candidatePorts lists the loopback ports worth probing for one engine, in +// probe order: the port being watched, then the port the engine's own settings +// file names when that differs. +// +// The settings file is what lets an engine the user started themselves be found +// on whatever port their own app chose, which is the only port it will ever +// answer on. It is read fresh each round, so a port the user changes in their +// own app takes effect on the next poll without restarting PAIR. An engine whose +// manifest declares no port source gets exactly the one port it probed before +// any of this existed. +func (e *Executor) candidatePorts(st *engineState, watched int) []int { + // plat is fixed when the engine is registered, so no lock guards it. + source := st.plat.Runtime.PortSource + + var ports []int + add := func(port int) { + if port > 0 && port <= 65535 && !slices.Contains(ports, port) { + ports = append(ports, port) + } + } + add(watched) + if source != nil { + if port, ok := settingsPort(source, st.pathVars()); ok { + add(port) + } + } + return ports +} + +// settingsPort reads the port an engine keeps in its own settings file, from +// the path and key its manifest declares. A missing file, an unreadable one, +// and a key holding no usable port all mean "this engine tells us nothing", +// which is the ordinary case for every engine that serves on a fixed port. +func settingsPort(source *PortSource, vars map[string]string) (int, bool) { + path, err := resolvePlaceholders(source.File, vars) + if err != nil || strings.TrimSpace(path) == "" { + return 0, false + } + file, err := os.Open(expandPath(path)) + if err != nil { + return 0, false + } + defer file.Close() + body, err := io.ReadAll(io.LimitReader(file, maxPortFileBytes)) + if err != nil || len(body) == 0 { + return 0, false + } + + field := source.Field + if field == "" { + field = "port" + } + var obj map[string]json.RawMessage + if err := json.Unmarshal(body, &obj); err != nil { + return 0, false + } + value, ok := resolveObjectPath(obj, field) + if !ok { + return 0, false + } + // A port is normally a JSON number, but launchers have been known to write + // the same value as a string and the engine reading it accepts both. + // Neither form may be a reason to miss a server that is really there. + var port int + if err := json.Unmarshal(value, &port); err == nil { + return port, port > 0 && port <= 65535 + } + var text string + if err := json.Unmarshal(value, &text); err != nil { + return 0, false + } + port, err = strconv.Atoi(strings.TrimSpace(text)) + if err != nil { + return 0, false + } + return port, port > 0 && port <= 65535 +} + +// probePortObservation asks each candidate port, cheapest check first: a +// transport dial before an HTTP request. It stops at the first port that +// identifies, because one identified service is all an engine needs and every +// later port would only be asked the same question. Each answer is filed under +// the port it came from: whether one port counts against an operation depends on +// which port it is, and a refusal has to say where the service it names is. +func (e *Executor) probePortObservation(ctx context.Context, ready *Probe, ports []int) portObservation { + obs := portObservation{quiet: len(ports) > 0} + if len(ports) > 0 { + obs.bind = ports[0] + } + for _, port := range ports { + switch probeListener(ctx, ready, port) { + case listenerProbeRefused: + continue + case listenerProbeIndeterminate: + obs.quiet = false + if obs.unsure == 0 { + obs.unsure = port + } + continue + } + // The port takes connections, so what it answers says what is behind it. + obs.quiet = false + answer := e.probeIdentity(ctx, ready, port) + switch { + case answer.outcome == probeIdentified: + obs.identified = port + return obs + case answer.blocked(): + if obs.blocked == 0 { + obs.blocked = port + obs.blockedStatus = answer.status + } + default: + if obs.stranger == 0 { + obs.stranger = port + } + } + } + return obs +} + +// confirmPortsQuiet re-probes ports until every one of them refuses three times +// in a row. That is the evidence PAIR demands before it says a service it was +// watching has stopped — both when a stop command has just run against one port +// and when a passive status round finds nothing answering. A service that moved +// to another port still answers here, so it is not reported gone, and another +// engine's listener is never read as this one leaving. +func (e *Executor) confirmPortsQuiet(parent context.Context, ready *Probe, ports []int, timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(parent, timeout) + defer cancel() + misses := 0 + for { + if allPortsRefused(ctx, ready, ports) { + misses++ + if misses == unavailableConfirmations { + return true + } + } else { + // A reachable listener, a timeout, or a malformed probe target + // cannot prove shutdown. Require a fresh consecutive sequence. + misses = 0 + } + select { + case <-ctx.Done(): + return false + case <-time.After(100 * time.Millisecond): + } + } +} + +// allPortsRefused reports whether every port explicitly refused a connection. +func allPortsRefused(ctx context.Context, ready *Probe, ports []int) bool { + for _, port := range ports { + if probeListener(ctx, ready, port) != listenerProbeRefused { + return false + } + } + return len(ports) > 0 +} diff --git a/services/nvpair-engine-manager/portsource_test.go b/services/nvpair-engine-manager/portsource_test.go new file mode 100644 index 000000000..e0ea3da38 --- /dev/null +++ b/services/nvpair-engine-manager/portsource_test.go @@ -0,0 +1,494 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// mtplxTestManifest describes the parts of MTPLX's real manifest these tests +// depend on: a default port, a /health readiness probe, and a settings file that +// may name the port the engine really listens on. The binary is a path that does +// not exist, so a second copy launched beside a running server would fail with +// "start mtplx" rather than silently passing. +func mtplxTestManifest(t *testing.T, port int, source *PortSource) *Manifest { + t.Helper() + key := runtime.GOOS + "/" + runtime.GOARCH + missing := filepath.Join(t.TempDir(), "mtplx"+exeExt()) + return &Manifest{ + Engine: "mtplx", DisplayName: "MTPLX", ManifestVersion: 1, + Platforms: map[string]Platform{key: { + Detect: []string{missing}, + Runtime: Runtime{ + Bin: missing, + Port: port, + PortSource: source, + Ready: &Probe{HTTP: "http://127.0.0.1:{port}/health", Status: 200, TimeoutS: 5}, + }, + }}, + } +} + +// mtplxLaunchManifest is mtplxTestManifest with a binary that can actually run: +// the package's fake engine, which answers 200 on any path. A test that has to +// show whether PAIR would bring up a second copy needs a second copy that could +// really come up, so it cannot use a manifest whose binary does not exist. +func mtplxLaunchManifest(t *testing.T, port int, source *PortSource) *Manifest { + t.Helper() + key := runtime.GOOS + "/" + runtime.GOARCH + return &Manifest{ + Engine: "mtplx", DisplayName: "MTPLX", ManifestVersion: 1, + Platforms: map[string]Platform{key: { + Detect: []string{fakeEngineBin}, + Runtime: Runtime{ + Bin: fakeEngineBin, + Env: map[string]string{"OLLAMA_HOST": "127.0.0.1:{port}"}, + Port: port, + PortSource: source, + Ready: &Probe{HTTP: "http://127.0.0.1:{port}/health", Status: 200, TimeoutS: 10}, + Stop: &StopSpec{Signal: "term", GraceS: 3}, + }, + }}, + } +} + +// writePortSettings puts a settings body where a manifest's port_source can find +// it and returns the path. +func writePortSettings(t *testing.T, body string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "settings.json") + require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) + return path +} + +// keyGatedServer stands in for an engine started with an API key: every route, +// its own health endpoint included, answers a request that carries no +// credentials with the given status. +func keyGatedServer(status int) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("WWW-Authenticate", "Bearer") + w.WriteHeader(status) + })) +} + +// answerWith replaces a server's behaviour, standing in for the user changing +// their engine's settings and restarting it. +func answerWith(srv *httptest.Server, status int) { + srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + }) +} + +// noticeFor returns the entry the error feed holds for id, if any. +func noticeFor(errors []serviceError, id string) (serviceError, bool) { + for _, e := range errors { + if e.ID == id { + return e, true + } + } + return serviceError{}, false +} + +// lockedBuffer records the codec frames a test produces, so it can count them +// while a status poll may still be writing. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) Read([]byte) (int, error) { return 0, io.EOF } + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// framesFor counts wire frames of one method that name an error id. The feed +// keeps one entry per id, so a repeated notice is only visible on the wire. +func framesFor(t *testing.T, buf *lockedBuffer, method, id string) int { + t.Helper() + frames := 0 + for line := range strings.SplitSeq(buf.String(), "\n") { + if strings.Contains(line, `"`+method+`"`) && strings.Contains(line, id) { + frames++ + } + } + return frames +} + +// An engine the user started themselves answers on whatever port their own app +// chose, so the port PAIR configured for that engine may be empty while the real +// one sits beside it. A manifest's port_source names where to look. +func TestCandidatePorts_AddsThePortTheEngineKeepsInItsOwnSettingsFile(t *testing.T) { + const watched = 8101 + + tests := []struct { + name string + // settings is the contents of the settings file; empty stands for no + // file at the declared path at all. + settings string + field string + want []int + }{ + { + name: "names the port the user picked", + settings: `{"host":"127.0.0.1","port":6666}`, + want: []int{watched, 6666}, + }, + { + // Launchers have written the same value both ways and the engine + // reading it accepts both, so neither may be a reason to miss it. + name: "accepts a port written as text", + settings: `{"port":"6666"}`, + want: []int{watched, 6666}, + }, + { + name: "follows a dotted object path", + settings: `{"server":{"port":6666}}`, + field: "server.port", + want: []int{watched, 6666}, + }, + { + name: "skips the port already being watched", + settings: fmt.Sprintf(`{"port":%d}`, watched), + want: []int{watched}, + }, + { + name: "says nothing without a settings file", + want: []int{watched}, + }, + { + name: "says nothing about a file it cannot read", + settings: `{"port":`, + want: []int{watched}, + }, + { + name: "says nothing about a port that cannot exist", + settings: `{"port":70000}`, + want: []int{watched}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + file := filepath.Join(t.TempDir(), "missing.json") + if tc.settings != "" { + file = writePortSettings(t, tc.settings) + } + ex := newTestExecutor(t, mtplxTestManifest(t, watched, &PortSource{File: file, Field: tc.field})) + st, err := ex.state("mtplx") + require.NoError(t, err) + + assert.Equal(t, tc.want, ex.candidatePorts(st, watched)) + }) + } +} + +// Every other engine serves on the port PAIR configures. Nothing is asked about +// any other port, so the candidate list stays what it was before any of this. +func TestCandidatePorts_WithoutAPortSource_JustWatchesTheConfiguredPort(t *testing.T) { + const watched = 8101 + ex := newTestExecutor(t, mtplxTestManifest(t, watched, nil)) + st, err := ex.state("mtplx") + require.NoError(t, err) + + assert.Equal(t, []int{watched}, ex.candidatePorts(st, watched)) +} + +// A status check has to ask about every candidate port, or an engine running +// right now is reported as absent because it happens to run on 6666 instead of +// PAIR's default. +func TestStatus_FindsTheEngineOnThePortFromItsOwnSettingsFile(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + servedPort := portOf(t, srv.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, servedPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"host":"127.0.0.1","port": %d}`, servedPort))} + ex := newTestExecutor(t, mtplxTestManifest(t, configured, source)) + + st, err := ex.Status("mtplx") + + require.NoError(t, err) + assert.True(t, st.Installed, "a running MTPLX on its own port reported as not installed (%v)", st) + assert.True(t, st.Running, "a running MTPLX on its own port reported as offline (%v)", st) + assert.True(t, st.Healthy, "a running MTPLX on its own port reported as unhealthy (%v)", st) + assert.Equal(t, servedPort, st.Port, "PAIR must report where the engine really answers") +} + +// Finding the engine is only half of it: Start must join the copy that is +// already running. A second MTPLX beside the user's own would fail to bind its +// port anyway, and would leave two routers for one model. +func TestStart_AdoptsTheEngineOnItsOwnPort_WithoutLaunchingASecondCopy(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + servedPort := portOf(t, srv.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, servedPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, servedPort))} + ex := newTestExecutor(t, mtplxTestManifest(t, configured, source)) + + require.NoError(t, ex.Start(t.Context(), "mtplx"), "Start refused although the engine is answering") + + state, err := ex.state("mtplx") + require.NoError(t, err) + state.mu.Lock() + defer state.mu.Unlock() + assert.True(t, state.adopted, "Start did not adopt the running engine") + assert.Nil(t, state.proc, "Start launched a second MTPLX beside the running one") + assert.Equal(t, servedPort, state.port, "the adopted engine is tracked at the wrong port") +} + +// Once the user quits their own engine, its port was never PAIR's to keep: the +// next start goes back to the port PAIR configured for this engine rather than +// relaunching on a stranger's. +func TestStatus_DroppedExternalService_GivesUpTheStrangersPort(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + servedPort := portOf(t, srv.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, servedPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, servedPort))} + ex := newTestExecutor(t, mtplxTestManifest(t, configured, source)) + st, err := ex.Status("mtplx") + require.NoError(t, err) + require.True(t, st.Running, "the external engine was never adopted (%v)", st) + + srv.Close() + st, err = ex.Status("mtplx") + + require.NoError(t, err) + assert.False(t, st.Running, "an engine that exited is still shown running (%v)", st) + assert.False(t, st.Healthy, "an engine that exited is still shown healthy (%v)", st) + assert.Equal(t, configured, st.Port, "PAIR kept holding the port of a service that is gone (%v)", st) +} + +// A port that refuses PAIR's health check for credentials is this engine, set up +// in a way PAIR cannot work with: it is not offline, and it is not somebody +// else's service. The engine stays shown offline, with one standing notice that +// says why, for as long as the port behaves that way. +func TestStatus_KeyProtectedPort_StaysOfflineWithOneStandingNotice(t *testing.T) { + srv := keyGatedServer(http.StatusUnauthorized) + defer srv.Close() + gatedPort := portOf(t, srv.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, gatedPort, "the test needs an empty configured port") + + // The codec sink lets the test see each errors:report frame, which is the + // only place a repeated notice would show up. + var frames lockedBuffer + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, gatedPort))} + manifest := mtplxTestManifest(t, configured, source) + reg := NewRegistry() + reg.engines[manifest.Engine] = manifest + ex := NewExecutor(reg, NewReporter(NewCodec(&frames)), func(string, any) {}, t.TempDir()) + // Only an engine the user turned on deserves a notice about it. + require.NoError(t, ex.desired.set("mtplx", true)) + + st, err := ex.Status("mtplx") + + require.NoError(t, err) + assert.False(t, st.Running, "a key-gated port must not be reported as a working engine (%v)", st) + assert.False(t, st.Healthy, "a key-gated port must not be reported as healthy (%v)", st) + + notice, listed := noticeFor(ex.Errors(), "engine-manager:auth-blocked:mtplx") + require.True(t, listed, "a key-gated port reported no notice") + assert.Contains(t, notice.Message, fmt.Sprintf("port %d", gatedPort), "the notice named the wrong port") + assert.Contains(t, notice.Message, "HTTP 401") + assert.Contains(t, notice.Message, "requires an API key") + assert.Contains(t, notice.Message, "never sends an API key") + assert.Equal(t, "warning", notice.Severity) + assert.Equal(t, "none", notice.Action, "there is nothing for the user to retry") + assert.Equal(t, "mtplx", notice.EngineType) + + // The next poll sees the same refusal. It must not re-report it: the feed + // keeps one entry per id and a refresh re-raises a dialog already dismissed. + _, err = ex.Status("mtplx") + require.NoError(t, err) + require.Equal(t, 1, framesFor(t, &frames, "errors:report", "engine-manager:auth-blocked:mtplx"), + "every poll re-reported the standing notice") + + // The user removes the key: the same port now answers, so the engine is + // adopted and the notice goes away with the condition that raised it. + answerWith(srv, http.StatusOK) + st, err = ex.Status("mtplx") + + require.NoError(t, err) + assert.True(t, st.Running, "the engine started answering and is still shown offline (%v)", st) + assert.Equal(t, gatedPort, st.Port) + _, stillListed := noticeFor(ex.Errors(), "engine-manager:auth-blocked:mtplx") + assert.False(t, stillListed, "a port that no longer refuses still holds its notice") + assert.Contains(t, frames.String(), `"errors:clear"`, "the cleared notice was never taken off the feed") +} + +// Starting over a credential refusal has to say so, and name the port the +// refusal was found on. Telling the user to look elsewhere for a service that +// "did not identify as MTPLX" sends them hunting for a different engine while +// the right one is already running. +func TestStart_KeyProtectedPort_RefusesWithoutLaunchingASecondCopy(t *testing.T) { + tests := []struct { + name string + status int + wantReason string + }{ + { + name: "a port that requires an API key", + status: http.StatusUnauthorized, + wantReason: "it requires an API key", + }, + { + name: "a port that refuses requests carrying no credentials", + status: http.StatusForbidden, + wantReason: "it refuses requests that carry no credentials", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := keyGatedServer(tc.status) + defer srv.Close() + gatedPort := portOf(t, srv.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, gatedPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, gatedPort))} + ex := newTestExecutor(t, mtplxTestManifest(t, configured, source)) + + err = ex.Start(t.Context(), "mtplx") + + require.Error(t, err, "Start accepted a port that refuses PAIR for credentials") + require.ErrorContains(t, err, "cannot start engine") + require.ErrorContains(t, err, fmt.Sprintf("port %d", gatedPort), "the refusal named the wrong port") + require.ErrorContains(t, err, tc.wantReason) + require.ErrorContains(t, err, "never sends an API key") + require.NotContains(t, err.Error(), "did not identify as", + "a credential refusal is this engine, not somebody else's service") + require.NotContains(t, err.Error(), "start mtplx", + "Start launched a second copy beside the refusing service") + + state, err := ex.state("mtplx") + require.NoError(t, err) + state.mu.Lock() + defer state.mu.Unlock() + assert.Nil(t, state.proc, "Start launched a second copy beside the refusing service") + assert.False(t, state.running, "a refused start left the engine marked running") + }) + } +} + +// A service that answers on the port named in the engine's settings file, but +// does not answer as that engine, is somebody else's listener on a port PAIR +// would never bind: an MTPLX launched from PAIR takes the port PAIR gives it. +// Refusing the start over it left the user with no engine at all because of a +// service they never asked PAIR about, so the start must go ahead on the empty +// configured port and stay there. +func TestStart_ForeignServiceOnTheSearchPort_StartsOnTheConfiguredPort(t *testing.T) { + foreign := httptest.NewServer(http.NotFoundHandler()) + defer foreign.Close() + foreignPort := portOf(t, foreign.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, foreignPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, foreignPort))} + ex := newTestExecutor(t, mtplxLaunchManifest(t, configured, source)) + t.Cleanup(func() { _ = ex.Stop("mtplx") }) + + require.NoError(t, ex.Start(t.Context(), "mtplx"), + "Start refused although the port it would bind was empty") + + st, err := ex.Status("mtplx") + require.NoError(t, err) + assert.True(t, st.Running, "no engine came up on the configured port (%v)", st) + assert.Equal(t, configured, st.Port, "the engine PAIR started is tracked at the stranger's port") + + state, err := ex.state("mtplx") + require.NoError(t, err) + state.mu.Lock() + defer state.mu.Unlock() + require.NotNil(t, state.proc, "Start launched no engine") + assert.False(t, state.adopted, "PAIR adopted a service that never answered as this engine") +} + +// Uninstall deletes files, so it still declines while a service PAIR cannot +// identify is answering on a port this engine uses. That refusal has to name +// where the service really is: naming PAIR's own configured port, which is +// empty, sends the user looking for a listener that is not there. +func TestUninstall_ForeignServiceOnTheSearchPort_NamesThePortHoldingTheService(t *testing.T) { + baseDir := t.TempDir() + managedBin := filepath.Join(baseDir, "mtplx", "mtplx"+exeExt()) + require.NoError(t, os.MkdirAll(filepath.Dir(managedBin), 0o755)) + copyFile(t, fakeEngineBin, managedBin) + + foreign := httptest.NewServer(http.NotFoundHandler()) + defer foreign.Close() + foreignPort := portOf(t, foreign.URL) + + configured, err := freePort() + require.NoError(t, err) + require.NotEqual(t, configured, foreignPort, "the test needs an empty configured port") + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, foreignPort))} + manifest := mtplxLaunchManifest(t, configured, source) + key := runtime.GOOS + "/" + runtime.GOARCH + p := manifest.Platforms[key] + // The managed copy is what Uninstall would delete, and it is inside PAIR's + // managed install directory, so the only thing refusing the job is the port. + p.Detect = []string{managedBin} + p.Runtime.Bin = managedBin + p.Uninstall = &Uninstall{Run: rmCmd(managedBin)} + manifest.Platforms[key] = p + + reg := NewRegistry() + reg.engines[manifest.Engine] = manifest + ex := NewExecutor(reg, NewReporter(nil), func(string, any) {}, baseDir) + + err = ex.Uninstall(t.Context(), "mtplx") + + require.ErrorContains(t, err, fmt.Sprintf("port %d is occupied by an unidentified service", foreignPort), + "the refusal did not name the port the service answers on") + require.NotContains(t, err.Error(), fmt.Sprintf("port %d is occupied", configured), + "the refusal named PAIR's configured port, which is empty") + require.True(t, portServing(foreignPort), "uninstall stopped a service PAIR does not own") + require.FileExists(t, managedBin, "uninstall deleted managed files while a service was answering") +} diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 6413d1fb1..786fefa17 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -207,6 +207,12 @@ type Runtime struct { // Port is the configured service port; zero requests an available loopback // port. Port int `json:"port"` + // PortSource names a file where the engine keeps the port it really listens + // on, for engines whose own application lets the user pick one. PAIR probes + // that port beside its configured one, so an instance the user started + // themselves is found wherever their app happens to keep it instead of being + // mistaken for an empty port. + PortSource *PortSource `json:"port_source,omitempty"` // Bind is the default listener address, used as the value of {host}. // Empty defaults to loopback; a per-call bind can override it. Bind string `json:"bind,omitempty"` @@ -224,6 +230,16 @@ type Runtime struct { Health *Probe `json:"health,omitempty"` } +// PortSource points at an engine's own settings file for the port it listens +// on. File is a path template with the same ~ and OS environment expansion as +// detect paths; Field is a dotted object path into that JSON file and defaults +// to "port". A file that is missing, unreadable, or holds no usable port simply +// tells PAIR nothing, which is the ordinary case. +type PortSource struct { + File string `json:"file"` + Field string `json:"field,omitempty"` +} + // AutoLaunch configures start-time launch arguments. The only kind is // "hf_context": read the model's config.json from the Hugging Face cache and // set the context length, any rope scaling it needs, and the GPU memory share. @@ -1006,6 +1022,25 @@ func (p *Platform) validate(key string) error { default: return fmt.Errorf("platform %q: runtime.mode %q invalid (want \"process\" or \"command\")", key, p.Runtime.Mode) } + if ps := p.Runtime.PortSource; ps != nil { + // An engine's own port is only worth hunting for when there is a probe + // to aim at it: the port read from the settings file widens the set of + // targets the readiness probe is asked about. + if p.Runtime.Ready == nil { + return fmt.Errorf("platform %q: runtime.port_source requires runtime.ready, whose probes the extra port would widen", key) + } + // Each rule here catches a declaration that can never find a port, which + // would read as an engine that simply does not publish one. + if strings.TrimSpace(ps.File) == "" { + return fmt.Errorf("platform %q: runtime.port_source file is required when port_source is declared", key) + } + if err := validatePlaceholderStrings([]string{ps.File}, allowedPlaceholders); err != nil { + return fmt.Errorf("platform %q: %w", key, err) + } + if ps.Field != "" && !resultMatchFieldPathRe.MatchString(ps.Field) { + return fmt.Errorf("platform %q: runtime.port_source field %q is not a valid object path", key, ps.Field) + } + } if p.Install != nil { hasArtifacts := len(p.Install.Artifacts) > 0 if len(p.Install.Script) > 0 && (p.Install.Fetch != nil || hasArtifacts || len(p.Install.Run) > 0) { diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index 5ebb0d495..0f64fc504 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -164,7 +164,7 @@ loading is provided by the PAIR proxy endpoint. ## 3. Key Use Cases - **Install an engine, user-mode**: `engine:install {engine:"ollama"}` downloads the per-OS user-scoped package (Windows/Linux standalone archive extracted into a user dir; macOS app bundle — never an elevated `Setup.exe` or `curl | sh`), checksum-verifies, extracts, re-detects. -- **Run lifecycle**: `engine:start` / `engine:stop` / `engine:restart` / `engine:status`, with readiness and health probes against the engine's loopback port. +- **Run lifecycle**: `engine:start` / `engine:stop` / `engine:restart` / `engine:status`, with readiness and health probes against the engine's loopback port — the configured port, plus the port the engine records for itself when the manifest declares `runtime.port_source`. - **Run a declared action**: `engine:action {engine, action, params}` → the manifest-declared HTTP call to the engine's loopback control API (e.g. `127.0.0.1:{port}/api/pull`). (Methods, notifications, and UI events all use the colon form `engine:*`, matching the POC UI and the `errors:*` notifications.) - **Onboard a new engine (no code)**: a vendor adds `engines/.json`; the generic runner exposes their lifecycle + actions immediately. - **Edge case — already installed**: detect short-circuits install (idempotent). @@ -453,6 +453,7 @@ fails it with the peer's error message. ## 12. Failure Modes and Mitigations - **Download / checksum failure on install**: engine stays NotInstalled. → Fail fast before `run`; `engine:install-progress` error + `errors:report` (`engine-manager:install-failed:`); never execute an unverified payload. - **Engine fails its readiness probe**: start never reaches Running. → Bounded ready timeout → back to Stopped; structured error; no half-started state. +- **Port answers the readiness probe with 401 or 403**: it is the engine, configured to require an API key PAIR never sends. → Neither adopted nor spawned over; start fails at once naming the port, and the engine carries one `engine-manager:auth-blocked:` warning while the refusal holds, so it reads as blocked rather than silently offline. - **Engine process crashes**: engine unavailable. → A watcher flips state, emits `engine:state-changed` + `errors:report` (`engine-manager:exited:`); the parent's supervisor reports if the *manager itself* dies. (Automatic restart is planned — see §4 — not yet implemented.) - **A status check overlaps a stop or port change**: an old result could restore the previous state. → Ignore the result when engine state has changed since diff --git a/services/nvpair-engine-manager/startup_output.go b/services/nvpair-engine-manager/startup_output.go index a9f90b769..1f5541c70 100644 --- a/services/nvpair-engine-manager/startup_output.go +++ b/services/nvpair-engine-manager/startup_output.go @@ -113,6 +113,19 @@ type readyTimeoutError struct{ timeout time.Duration } func (e *readyTimeoutError) Error() string { return fmt.Sprintf("not ready after %s", e.timeout) } +// readyBlockedError reports that the engine answered its own health endpoint +// with a credential refusal. It is not a timeout: the engine is up and will +// answer exactly this way forever, because PAIR never sends an API key. +type readyBlockedError struct { + port int + status int +} + +func (e *readyBlockedError) Error() string { + return fmt.Sprintf("it answers its own health checks with HTTP %d because %s. %s Start it without an API key, or choose a port nothing is listening on", + e.status, credentialRefusalClause(e.status), neverSendsKey) +} + const ( readyTimeoutDetailLines = 12 readyTimeoutLineWidth = 240 @@ -198,6 +211,12 @@ func (o *startupOutput) failure(ctx context.Context, err error) error { if errors.As(err, &timedOut) { return fmt.Errorf("%w\n\nLast engine output:\n%s", err, recentLines(text, readyTimeoutDetailLines, readyTimeoutLineWidth)) } + // A credential refusal is already a complete explanation, and the tail of a + // log from an engine that is serving happily behind a key adds nothing. + var blocked *readyBlockedError + if errors.As(err, &blocked) { + return err + } return fmt.Errorf("%w: %s", err, text) } diff --git a/services/nvpair-engine-manager/status.go b/services/nvpair-engine-manager/status.go index 26508bd98..164a79a9c 100644 --- a/services/nvpair-engine-manager/status.go +++ b/services/nvpair-engine-manager/status.go @@ -29,12 +29,21 @@ type statusProbeRun struct { } // presenceResult distinguishes a positively identified engine from an -// occupied/indeterminate target. Callers that might spawn or install must fail -// closed when Occupied is true: a listener that did not pass the identity probe -// is not permission to overwrite it. +// occupied/indeterminate target. Callers that delete files must fail closed when +// Occupied is true: a listener that did not pass the identity probe is not +// permission to overwrite it. Whether a port is in the way of a second copy is a +// narrower question, and the observation answers it — see +// portObservation.spawnBlocked. type presenceResult struct { Identified bool - Occupied bool + // Port is the candidate that answered as this engine. It is not the port the + // caller asked about whenever the engine keeps its own port in a settings + // file, which is why the answer carries it instead of assuming. + Port int + Occupied bool + // obs is the round's observation, so a refusal can name the port and the + // answer that was found there rather than describing the configured one. + obs portObservation } // Detect updates and returns whether the engine is installed, based on @@ -258,19 +267,16 @@ func (e *Executor) refreshPassiveStatus(engine string, st *engineState, key stat pathInstalled, binPath := detectPath(st) checkPresence := pathInstalled || mode == "process" checkPresence = checkPresence && key.port != 0 && ready != nil && proc == nil && (!running || adopted) - var listener listenerProbeResult - var identified, refusedConfirmed bool + var obs portObservation + var refusedConfirmed bool if checkPresence { - probeCtx, stopProbe := context.WithTimeout(ctx, presenceRefusalWindow) - listener = probeListener(probeCtx, ready, key.port) - stopProbe() - switch listener { - case listenerProbeRefused: - if running && adopted { - refusedConfirmed = e.waitUnavailableContext(ctx, ready, key.port, presenceRefusalWindow) - } - case listenerProbeReachable: - identified = e.probe(ctx, ready, key.port) + // Every candidate port is asked, not only the one being watched. An + // engine the user started themselves answers on whatever port their own + // app chose, and that is the only place it will ever answer. + ports := e.candidatePorts(st, key.port) + obs = e.probePortObservation(ctx, ready, ports) + if obs.quiet && running && adopted { + refusedConfirmed = e.confirmPortsQuiet(ctx, ready, ports, presenceRefusalWindow) } } if ctx.Err() != nil { @@ -294,7 +300,7 @@ func (e *Executor) refreshPassiveStatus(engine string, st *engineState, key stat } if checkPresence { switch { - case listener == listenerProbeRefused && refusedConfirmed: + case obs.quiet && refusedConfirmed: emit = before.Running || before.Healthy || oldAdopted || before.Installed != pathInstalled if st.healthStop != nil { st.healthStop() @@ -303,39 +309,56 @@ func (e *Executor) refreshPassiveStatus(engine string, st *engineState, key stat st.running = false st.healthy = false st.adopted = false + // An adopted service's port was never PAIR's to keep. Once it is + // gone, the next start goes back to the port PAIR configured for + // this engine instead of launching a duplicate on the stranger's. + st.port = st.plat.Runtime.Port if !pathInstalled { st.binPath = "" } - case listener == listenerProbeRefused || listener == listenerProbeIndeterminate: - // A single refusal or an uncertain transport result cannot prove - // an adopted service stopped. + case !obs.occupied(): + // A single unconfirmed round, or an uncertain transport result, + // cannot prove an adopted service stopped. if running && adopted { st.installed = true if !pathInstalled { st.binPath = "" } } - case identified && !st.stopping: - emit = !before.Running || !before.Healthy || !oldAdopted || before.Port != key.port + case obs.identified != 0 && !st.stopping: + emit = !before.Running || !before.Healthy || !oldAdopted || before.Port != obs.identified st.installed = true st.running = true st.healthy = true st.adopted = true - st.port = key.port + st.port = obs.identified if !pathInstalled { st.binPath = "" } - case !identified && listener == listenerProbeReachable && running && adopted: - emit = before.Healthy - // A live listener that no longer identifies as this engine is - // unhealthy, but its port must not be treated as free. + case obs.identified == 0 && running && adopted: + // The port holds something that is not this engine, or could not be + // read. Neither proves the adopted service stopped, so it keeps its + // installation; only a listener answering something else is called + // unhealthy, and its port must not be treated as free. A stop that + // is still in flight is not a health failure, and an engine that + // still identifies itself during that stop is not unhealthy either. + if obs.answered() { + emit = before.Healthy + st.healthy = false + } st.installed = true - st.healthy = false if !pathInstalled { st.binPath = "" } } } + // A port that answers PAIR's health check with a credential refusal is this + // engine, set up in a way PAIR cannot work with, and the state alone would + // read as "offline". Say so, but only for an engine the user turned on, and + // only while that is what the port does. + blocked := enabled && obs.blocked != 0 + notice := blocked != st.authBlocked + st.authBlocked = blocked after := statusLocked(engine, st, enabled) if before != after || oldBinPath != st.binPath || oldAdopted != st.adopted { st.revision++ @@ -344,14 +367,24 @@ func (e *Executor) refreshPassiveStatus(engine string, st *engineState, key stat if emit { e.emitState(engine) } + switch { + case blocked && notice: + e.reporter.report(serviceError{ + ID: authBlockedID(engine), Message: obs.authBlockedNotice(st.manifest.DisplayName), + Severity: "warning", Action: "none", EngineType: engine, + }) + case notice: + e.reporter.clear(authBlockedID(engine)) + } } // reconcilePresence reconciles filesystem detection with a fixed-port engine // service. A successful engine-specific readiness probe is authoritative even // when the binary lives outside NVPAIR's managed paths. Conversely, readiness // failure is not proof of shutdown: an HTTP 503 still has a live listener. -// An adopted service is only marked stopped after repeated explicit connection -// refusals, preventing a transient failed readiness response from clearing it. +// An adopted service is only marked stopped after every candidate port refuses +// repeatedly, so a transient failed readiness response cannot clear it and a +// service that moved to another port is not reported gone. // // allowWhileStopping is true only for an explicit Start. Passive status checks // must not undo a deliberate OFF by re-adopting a service behind st.stopping. @@ -371,15 +404,20 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng } if port == 0 || ready == nil || proc != nil || (running && !adopted) { - return presenceResult{Identified: running, Occupied: running} + return presenceResult{ + Identified: running, + Port: port, + Occupied: running, + obs: portObservation{bind: port}, + } } - probeCtx, cancel := context.WithTimeout(ctx, presenceRefusalWindow) - listener := probeListener(probeCtx, ready, port) - cancel() - if listener == listenerProbeRefused { - if !running || !adopted || !e.waitUnavailable(ready, port, presenceRefusalWindow) { - return presenceResult{} + ports := e.candidatePorts(st, port) + obs := e.probePortObservation(ctx, ready, ports) + identified := obs.identified + if obs.quiet { + if !running || !adopted || !e.confirmPortsQuiet(ctx, ready, ports, presenceRefusalWindow) { + return presenceResult{obs: obs} } st.mu.Lock() changed := st.running || st.healthy || st.adopted || st.installed != pathInstalled @@ -392,6 +430,9 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng st.healthy = false st.adopted = false st.proc = nil + // The stranger's port is not PAIR's to keep: a later start goes back to + // the port PAIR configured for this engine. + st.port = st.plat.Runtime.Port if !pathInstalled { // A service-only adoption has no managed image. Never leave a stale // path that orphan reclamation could terminate. @@ -401,29 +442,16 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng if changed { e.emitState(engine) } - return presenceResult{} + return presenceResult{obs: obs} } - if listener == listenerProbeIndeterminate { - // DNS/routing/resource failures cannot prove the port is free. Preserve - // existing state and prevent install/start from writing over it. + if identified == 0 { if running && adopted { st.mu.Lock() - st.installed = true - if !pathInstalled { - st.binPath = "" - } - st.mu.Unlock() - } - return presenceResult{Occupied: true} - } - - identified := e.probe(ctx, ready, port) - if !identified { - if running && adopted { - st.mu.Lock() - changed := st.healthy + changed := obs.answered() && st.healthy st.installed = true // previously identified external service - st.healthy = false + if obs.answered() { + st.healthy = false + } if !pathInstalled { st.binPath = "" } @@ -431,28 +459,29 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng if changed { e.emitState(engine) } - return presenceResult{Occupied: true} } - // A listener is present but did not identify as this engine. Do not - // adopt it, spawn over it, or download a second copy for this port. - return presenceResult{Occupied: true} + // A listener is present but did not identify as this engine, so it is + // never adopted. Whether it also stands in the way of a second copy is a + // narrower question, answered by spawnBlocked at the callers that would + // bring one up: only a port that copy needs counts against them. + return presenceResult{Occupied: true, obs: obs} } st.mu.Lock() if st.stopping && !allowWhileStopping { st.mu.Unlock() - return presenceResult{Identified: true, Occupied: true} + return presenceResult{Identified: true, Port: identified, Occupied: true, obs: obs} } // Detect resets installed=false on every path-miss. Do not treat that // internal refresh as a state transition for an already-adopted service, // or every status poll would emit a duplicate state-changed event. - changed := !st.running || !st.healthy || !st.adopted || st.port != port + changed := !st.running || !st.healthy || !st.adopted || st.port != identified st.installed = true st.running = true st.awaitingModel = false st.healthy = true st.adopted = true - st.port = port + st.port = identified if allowWhileStopping { st.stopping = false } @@ -465,7 +494,7 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng if changed { e.emitState(engine) } - return presenceResult{Identified: true, Occupied: true} + return presenceResult{Identified: true, Port: identified, Occupied: true, obs: obs} } func (e *Executor) emitState(engine string) { diff --git a/services/nvpair-errors/README.md b/services/nvpair-errors/README.md index 2a91518b1..21eb018d2 100644 --- a/services/nvpair-errors/README.md +++ b/services/nvpair-errors/README.md @@ -90,13 +90,20 @@ Two channels: ## ID namespace convention -`:[:]`. Convention only — +`:[:]`. `` is the +subject the error is about — a node, an engine, and for +`pull-failed` also a ``. Convention only — nvpair-errors keys by composite `(nodeId, id)` and **highest-timestamp-wins on upsert**. A later report with the same id but an OLDER timestamp is dropped. Equal-timestamp reports overwrite (a producer re-emitting a steady-state error refreshes the message). +Because one id holds one entry, a producer that watches a condition +reports it on the transition into that state and clears the id on the +way out, rather than re-reporting per poll: a re-report re-raises a +dialog the user has already dismissed. + Starter ids: | id | emitter | meaning | @@ -108,6 +115,7 @@ Starter ids: | `engine-manager:install-failed:` | nvpair-engine-manager | installing the engine failed | | `engine-manager:pull-failed::` | nvpair-engine-manager | pulling a model for the engine failed | | `engine-manager:start-failed:` | nvpair-engine-manager | starting the engine failed | +| `engine-manager:auth-blocked:` | nvpair-engine-manager | the engine's port refuses PAIR's health checks because it requires an API key; reported once while that holds | | `supervisor:subprocess-crashed:` | broker | any spawned subprocess exited unexpectedly | ## JSON-RPC methods (broker → nvpair-errors) diff --git a/services/nvpair-ui-broker/README.md b/services/nvpair-ui-broker/README.md index 76791e21d..1c09d9bd8 100644 --- a/services/nvpair-ui-broker/README.md +++ b/services/nvpair-ui-broker/README.md @@ -148,7 +148,10 @@ is resolved and no explicit path was given, the broker continues without it. **Engine advertising.** The broker runs an internal 5 s poll loop against local Ollama (`GET /`), LM Studio (`GET /v1/models`), llama.cpp (`GET /health`), vLLM (`GET /health`), and MTPLX (`GET /health`) -at their configured backend ports and reconciles this node's engine registration +at the backend port `nvpair-engine-manager` reports for them (`engine:status`, so an +engine the user started themselves is found on the port their own app chose rather +than the configured one), falling back to the configured backend port only when +there is no engine-manager answer, and reconciles this node's engine registration with the scanner daemon: - engine **up** and facade **ready** → register `ol` / `lm` / `lc` / `vl` / `mx` at the diff --git a/services/nvpair-ui-broker/advertiser.go b/services/nvpair-ui-broker/advertiser.go index fb8af818a..581d04300 100644 --- a/services/nvpair-ui-broker/advertiser.go +++ b/services/nvpair-ui-broker/advertiser.go @@ -174,8 +174,9 @@ func (b *Broker) reconcileAdvertiseLMStudio(client *http.Client) { } } -// runAutoAdvertiseEngine reconciles an engine using the configured port -// recorded in its runtime profile, without compatibility-port reconciliation. +// runAutoAdvertiseEngine reconciles an engine that has no compatibility-port +// reconciliation, asking engine-manager where it is serving rather than +// trusting the port PAIR configured for it. func (b *Broker) runAutoAdvertiseEngine(ctx context.Context, profile engineProxyProfile) { client := &http.Client{Timeout: 2 * time.Second} ticker := time.NewTicker(autoAdvertiseInterval) @@ -200,12 +201,23 @@ func (b *Broker) reconcileAdvertiseEngine(profile engineProxyProfile, client *ht b.reconcileRequestedModelEngine(profile) return } - enginePort := int(b.engineProxy(profile).backendPort.Load()) + // Ask where the engine actually is instead of trusting the port PAIR + // configured for it. An engine the user started themselves answers on the + // port their own app chose, and a cached port then probes a stranger's + // listener — or nothing — while the real engine goes unrouted. The cached + // port stays the fallback for the one case where there is nothing to ask: + // no engine-manager, or no answer from it. + cached := int(b.engineProxy(profile).backendPort.Load()) + enginePort, probe := b.localEnginePort(profile.Name, cached) proxyPort := b.engineProxyListenPort(profile) - up := enginePort > 0 && - proxyPort > 0 && - enginePort != proxyPort && - checkEngineHealth(profile, client, enginePort) + if proxyPort != 0 && enginePort == proxyPort { + // A facade is never its own backend. This also covers an + // engine-manager that is slow to come up: a port resolved from a + // guess can land on the proxy, and forwarding a request to the proxy + // loops it. + enginePort, probe = 0, false + } + up := enginePort > 0 && probe && proxyPort > 0 && checkEngineHealth(profile, client, enginePort) if up { b.registerService(noderec.RegisterParams{Service: profile.DiscoveryService, Port: proxyPort}) b.setProxyLocalBackend(b.engineProxyHandle(profile), profile.Name, enginePort, true) diff --git a/services/nvpair-ui-broker/advertiser_test.go b/services/nvpair-ui-broker/advertiser_test.go index 4ecf4ec11..c07fd816f 100644 --- a/services/nvpair-ui-broker/advertiser_test.go +++ b/services/nvpair-ui-broker/advertiser_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "strconv" + "sync/atomic" "testing" "time" @@ -222,3 +223,166 @@ func TestOllamaFacade_IsPendingBackend(t *testing.T) { }) require.True(t, b.ollamaFacadeIsPendingBackend(), "recovery must keep probes blocked until the proxy vacates 11434") } + +// advertiserMTPLXProfile is MTPLX's real broker profile, read from the same table +// the running broker builds, so these tests cannot quietly drift onto a profile +// that no longer exists. +func advertiserMTPLXProfile(t *testing.T) engineProxyProfile { + t.Helper() + for _, profile := range buildEngineProxyProfiles() { + if profile.Name == "mtplx" { + require.False(t, profile.LoadOnRequest, + "MTPLX is not a model-on-request engine, so its reconcile takes the backend-resolution path") + return profile + } + } + t.Fatal("the broker has no MTPLX proxy profile") + return engineProxyProfile{} +} + +// listenerAnsweringHealth puts a live service on a real port: it answers any +// request, PAIR's health probe included, with 200. Which service it stands for — +// MTPLX, or some stranger that happens to hold MTPLX's configured port, or the +// compatibility proxy itself — is told by the test, because a 200 on its own says +// nothing about who answered. +func listenerAnsweringHealth(t *testing.T) int { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + _, portText, err := net.SplitHostPort(srv.Listener.Addr().String()) + require.NoError(t, err, "read the fixture listener's port") + port, err := strconv.Atoi(portText) + require.NoError(t, err, "read the fixture listener's port") + return port +} + +// fakeEngineManagerFor stands in for a supervised engine-manager: it answers +// every request with whatever the test is serving at that moment, so one broker +// can be polled twice with the engine in two different places. +func fakeEngineManagerFor(t *testing.T, answer func() string) *rpcWorker { + t.Helper() + brokerSide, workerSide := net.Pipe() + t.Cleanup(func() { + _ = brokerSide.Close() + _ = workerSide.Close() + }) + worker := &rpcWorker{peer: NewPeer(NewCodec(brokerSide))} + go worker.peer.Serve(nil, nil) + go func() { + codec := NewCodec(workerSide) + for { + msg, err := codec.Read() + if !assertRPCRead(t, err) { + return + } + assert.NoError(t, codec.Respond(msg.ID, json.RawMessage(answer()))) + } + }() + return worker +} + +// MTPLX answers on whatever port the user's own application chose, which is +// rarely the port PAIR configured for it, and that configured port may well hold +// a live service that is not MTPLX. Resolving the backend from the cached port +// forwards inference to that stranger and never reaches the running engine. +func TestEngineAdvertiser_TracksThePortEngineManagerReports(t *testing.T) { + profile := advertiserMTPLXProfile(t) + // Three loopback services, each answering 200: the stranger holding PAIR's + // configured port for MTPLX, MTPLX itself on the port the user gave it, and + // MTPLX again after the user restarts it somewhere else. + strangerPort := listenerAnsweringHealth(t) + servingPort := listenerAnsweringHealth(t) + movedPort := listenerAnsweringHealth(t) + + // Where MTPLX is serving, answered on the wire as engine-manager answers it. + var reported atomic.Int64 + reported.Store(int64(servingPort)) + + client := &http.Client{Timeout: 2 * time.Second} + b := brokerWithEngineProxyProfile(profile) + b.regCache = relay.NewRegistrationCache() + b.setEngineMgr(fakeEngineManagerFor(t, func() string { + return `{"running":true,"port":` + strconv.FormatInt(reported.Load(), 10) + `}` + })) + b.engineProxy(profile).backendPort.Store(int32(strangerPort)) + proxyPort, _ := reserveSettingsPort(t) + updates := attachAdvertiserProxy(t, b, profile, proxyPort) + + b.reconcileAdvertiseEngine(profile, client) + + update := <-updates + require.True(t, update.Healthy, "MTPLX running on its own port was routed as offline: %+v", update) + assert.Equal(t, servingPort, update.Port, + "the proxy was left pointing at PAIR's configured port %d instead of where MTPLX answers", strangerPort) + registrations := b.regCache.Snapshot() + require.Len(t, registrations, 1, "a running engine was not advertised") + assert.Equal(t, proxyPort, registrations[0].Port) + + // The user restarts MTPLX on another port. The next poll follows it rather + // than holding on to the address that used to work. + reported.Store(int64(movedPort)) + b.reconcileAdvertiseEngine(profile, client) + + update = <-updates + require.True(t, update.Healthy, "MTPLX moved and the proxy did not follow: %+v", update) + assert.Equal(t, movedPort, update.Port, "the proxy kept forwarding to the port MTPLX left") + require.Len(t, b.regCache.Snapshot(), 1, "an engine that is still running was unadvertised") +} + +// A quit MTPLX leaves no port behind. The answer engine-manager gives is +// authoritative even though something is still listening on the cached port: +// keeping that listener as the backend routes requests to a stranger, and +// advertising it invites other nodes to send their traffic there too. +func TestEngineAdvertiser_StopsAdvertisingAfterEngineManagerReportsStopped(t *testing.T) { + profile := advertiserMTPLXProfile(t) + strangerPort := listenerAnsweringHealth(t) + + client := &http.Client{Timeout: 2 * time.Second} + b := brokerWithEngineProxyProfile(profile) + b.regCache = relay.NewRegistrationCache() + b.setEngineMgr(fakeEngineManagerFor(t, func() string { + return `{"running":false,"port":` + strconv.Itoa(strangerPort) + `}` + })) + b.engineProxy(profile).backendPort.Store(int32(strangerPort)) + proxyPort, _ := reserveSettingsPort(t) + updates := attachAdvertiserProxy(t, b, profile, proxyPort) + b.regCache.Register(noderec.RegisterParams{Service: profile.DiscoveryService, Port: proxyPort}) + require.Len(t, b.regCache.Snapshot(), 1, "the fixture starts advertised") + + b.reconcileAdvertiseEngine(profile, client) + + assert.Empty(t, b.regCache.Snapshot(), "an engine reported stopped was still advertised") + update := <-updates + assert.False(t, update.Healthy, "a stopped engine was still routed: %+v", update) + assert.Equal(t, 0, update.Port, "PAIR kept holding the port of a service it never owned") +} + +// A 200 from a port is not proof of the right service: the compatibility proxy +// answers /health on its own listener, so a backend resolved onto the proxy's own +// port would forward every request back into the proxy that received it. A +// resolved port equal to the proxy's own is dropped rather than probed. +func TestEngineAdvertiser_NeverRoutesAnEngineThroughItsOwnProxy(t *testing.T) { + profile := advertiserMTPLXProfile(t) + // The listener standing on the facade port is the proxy itself, and it + // answers the health probe, so only the collision check can stop this. + facadePort := listenerAnsweringHealth(t) + + client := &http.Client{Timeout: 2 * time.Second} + b := brokerWithEngineProxyProfile(profile) + b.regCache = relay.NewRegistrationCache() + b.setEngineMgr(fakeEngineManagerFor(t, func() string { + return `{"running":true,"port":` + strconv.Itoa(facadePort) + `}` + })) + updates := attachAdvertiserProxy(t, b, profile, facadePort) + b.regCache.Register(noderec.RegisterParams{Service: profile.DiscoveryService, Port: facadePort}) + require.Len(t, b.regCache.Snapshot(), 1, "the fixture starts advertised") + + b.reconcileAdvertiseEngine(profile, client) + + assert.Empty(t, b.regCache.Snapshot(), "a self-forwarding facade remained advertised") + update := <-updates + assert.False(t, update.Healthy, "the proxy was named as its own backend: %+v", update) + assert.Equal(t, 0, update.Port, "the proxy was named as its own backend: %+v", update) +} diff --git a/services/nvpair-ui-broker/spec.md b/services/nvpair-ui-broker/spec.md index c25cbff78..604e93579 100644 --- a/services/nvpair-ui-broker/spec.md +++ b/services/nvpair-ui-broker/spec.md @@ -449,7 +449,7 @@ A port the user chooses is never silently moved. `engine:set-port` and every ` Date: Tue, 24 Nov 2026 14:22:05 -0700 Subject: [PATCH 03/10] feat(engines): install MTPLX through Homebrew, and let the card ask its node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An Apple Silicon Mac with no MTPLX could only ever be shown a Download button, while the one way to get the engine that is not a GUI — brew install youssofal/mtplx/mtplx — went unused. - A manifest can declare an `install.pkg` mode: tap the formula, trust it, install it, then run the installed command with --version and only call the install done when that answers. The proof is the point: MTPLX's own launcher builds its Python runtime inside the first launch, and a start would pay several hundred megabytes of downloading inside its 600-second readiness window, where the same work inside an install has thirty minutes. - `conflicts` names paths whose presence means the engine is already here by a route PAIR does not own: an MTPLX.app in /Applications stops an install, because fetching a second copy beside it is not an improvement. - {cli} resolves from the binary detection actually found rather than the manifest's literal path — a Homebrew MTPLX puts no ~/.mtplx/bin/mtplx anywhere, so every model command was being sent to a file that does not exist. - EngineStatus reports can_install and owner, the same facts the service weighs before installing or refusing an uninstall; the desktop's Install and Uninstall buttons read those two facts instead of a hand-maintained table of operating systems, which on a peer described the wrong machine. No default when the facts are absent: an older or unclustered peer offers nothing rather than guessing, a card for a machine that is not this one never offers a Download that would land here, and Uninstall no longer appears for copies PAIR only found and would refuse to remove. - The model picker generalizes past vLLM: any engine that names its model at launch opens it on first enable and on needsModelSelection, while only vLLM claims request-triggered loading — MTPLX advertises only the pack it is serving, so its banner must not promise otherwise. The setup intent carries the engine type with the node id, so a picker cannot open naming the wrong engine. The three install modes, the manifest keys and the new status fields are written up in spec.md and README.md. Signed-off-by: Steven Beverly --- .../electron/service-bridge/modular-state.ts | 42 +- desktop/src/shared/constants/engines.ts | 5 +- desktop/src/shared/types/engines.ts | 18 + desktop/src/shared/utils/engines.ts | 21 + desktop/src/ui/api/engine-api.ts | 14 +- .../components/BackendRow/BackendFooter.tsx | 22 +- .../components/BackendRow/BackendHeader.tsx | 4 - .../ui/components/BackendRow/BackendRow.tsx | 6 - .../components/BackendRow/InstallButton.tsx | 26 +- desktop/src/ui/components/MainApp/MainApp.tsx | 9 +- .../EngineModelSelectionModal.tsx | 59 ++- .../components/ModelManager/ModelManager.tsx | 8 +- .../NodeList/NodeEngineSettings.tsx | 7 +- .../src/ui/constants/engine-capabilities.ts | 21 +- desktop/src/ui/constants/welcome.ts | 8 + desktop/src/ui/stores/overview-ui.store.ts | 25 +- desktop/src/ui/types/engine-info.ts | 11 + desktop/src/ui/types/engine-manifest.ts | 22 +- desktop/src/ui/utils/backend-target-os.ts | 17 - .../modular/engine-install-button.test.ts | 83 +++- .../engine-model-selection-action.test.ts | 96 +++- .../modular/model-manager-transitions.test.ts | 13 + .../tests/modular/mtplx-card-actions.test.ts | 113 +++-- docs/engine-lifecycle.mdx | 46 +- docs/getting-started.mdx | 6 +- services/nvpair-engine-manager/README.md | 45 +- .../nvpair-engine-manager/actioncli_test.go | 115 +++++ services/nvpair-engine-manager/actions.go | 9 +- services/nvpair-engine-manager/enginecli.go | 42 ++ services/nvpair-engine-manager/executor.go | 12 + services/nvpair-engine-manager/install.go | 55 ++- .../nvpair-engine-manager/install_pkg_test.go | 455 ++++++++++++++++++ .../nvpair-engine-manager/installfacts.go | 122 +++++ .../installfacts_test.go | 231 +++++++++ services/nvpair-engine-manager/lifecycle.go | 8 +- .../manifests/mtplx.json | 11 + services/nvpair-engine-manager/pkginstall.go | 276 +++++++++++ services/nvpair-engine-manager/registry.go | 60 ++- services/nvpair-engine-manager/settings.go | 18 +- services/nvpair-engine-manager/spec.md | 47 +- services/nvpair-engine-manager/status.go | 23 +- 41 files changed, 2011 insertions(+), 220 deletions(-) delete mode 100644 desktop/src/ui/utils/backend-target-os.ts create mode 100644 services/nvpair-engine-manager/actioncli_test.go create mode 100644 services/nvpair-engine-manager/enginecli.go create mode 100644 services/nvpair-engine-manager/install_pkg_test.go create mode 100644 services/nvpair-engine-manager/installfacts.go create mode 100644 services/nvpair-engine-manager/installfacts_test.go create mode 100644 services/nvpair-engine-manager/pkginstall.go diff --git a/desktop/src/electron/service-bridge/modular-state.ts b/desktop/src/electron/service-bridge/modular-state.ts index 9e4051b4a..eeb0d2a10 100644 --- a/desktop/src/electron/service-bridge/modular-state.ts +++ b/desktop/src/electron/service-bridge/modular-state.ts @@ -81,6 +81,8 @@ interface RemoteEngineFacts { awaitingModel: boolean healthy: boolean port: number + canInstall: boolean + owner: string } /** @@ -100,6 +102,20 @@ function factsProcessStatus(facts: { return facts.installed ? 'stopped' : 'not-installed' } +/** + * The two install facts an engine-manager `EngineStatus` carries, read the same way + * for a local engine and for a peer's: whether there is an install this node's + * service could perform, and who owns the copy that is already there. A node that + * reports neither — an older peer, or a status that came from discovery rather than + * from an engine manager — reads as nothing installable and nothing owned, which is + * the safe answer: PAIR's services refuse both operations in exactly the cases + * these facts describe, so a card built on a guess would offer buttons that can only + * end in a refusal. + */ +function readInstallFacts(status: JsonObject): { canInstall: boolean; owner: string } { + return { canInstall: booleanValue(status.can_install), owner: stringValue(status.owner) } +} + interface NodeHardware { gpus: ModularGpu[] cpu: ModularCpu | null @@ -973,6 +989,8 @@ class ModularBridgeState { starting: boolean awaitingModel: boolean port: number + canInstall: boolean + owner: string } >() /** @@ -1400,7 +1418,8 @@ class ModularBridgeState { running: booleanValue(obj.running), starting: booleanValue(obj.starting), awaitingModel: booleanValue(obj.awaiting_model), - port: numberValue(obj.port) + port: numberValue(obj.port), + ...readInstallFacts(obj) }) // A fresh authoritative state is the resolution of whatever op was in // flight (start/stop done, install `done`+installed, uninstall removed). @@ -1762,7 +1781,11 @@ class ModularBridgeState { // it for the engine port. enginePort: facts.installed && facts.port > 0 ? facts.port : null, // The peer's promoted proxy port, when its engine is advertised. - proxyPort: presence?.up && presence.port > 0 ? presence.port : null + proxyPort: presence?.up && presence.port > 0 ? presence.port : null, + // What the peer could do about the engine, from the peer: its own + // package manager, its own copy of an engine already in a folder. + canInstall: facts.canInstall, + owner: facts.owner } } else if (node && presence?.up && !node.clustered && !node.trusted) { // A live advertisement means the engine is reachable and serving, so @@ -1811,7 +1834,8 @@ class ModularBridgeState { starting: booleanValue(engineObj.starting), awaitingModel: booleanValue(engineObj.awaiting_model), healthy: booleanValue(engineObj.healthy), - port: numberValue(engineObj.port) + port: numberValue(engineObj.port), + ...readInstallFacts(engineObj) }) seen.add(engineType) } @@ -1844,7 +1868,10 @@ class ModularBridgeState { starting: booleanValue(obj.starting), awaitingModel: booleanValue(obj.awaiting_model), healthy: booleanValue(obj.healthy), - port: numberValue(obj.port) + port: numberValue(obj.port), + // A start/stop answer is a full `EngineStatus`, so it restates the + // install facts too; read them or the toggle would quietly drop them. + ...readInstallFacts(obj) }) this.emitRemoteEngineStatus(nodeId, engineType) } @@ -2166,7 +2193,12 @@ class ModularBridgeState { // Each proxy-fronted engine has its own broker proxy // (mapped in proxy-engines.ts); report that engine's bound // proxy port. Loopback-only engines get null. - proxyPort: isProxyEngine(engineType) ? this.getProxyPort(engineType) : null + proxyPort: isProxyEngine(engineType) ? this.getProxyPort(engineType) : null, + // The engine card's Install and Uninstall buttons come from these, + // so an engine this machine has no way to install — and a copy that + // belongs to somebody else's installer — show neither. + canInstall: facts.canInstall, + owner: facts.owner } } diff --git a/desktop/src/shared/constants/engines.ts b/desktop/src/shared/constants/engines.ts index bb7ee619a..d66272073 100644 --- a/desktop/src/shared/constants/engines.ts +++ b/desktop/src/shared/constants/engines.ts @@ -60,8 +60,9 @@ export const EngineDefaultLinks: Record = new Set(['pair', 'other']) + +/** + * True when the copy of an engine on a node is the one PAIR installed — the only + * copy PAIR may remove, so the only one worth offering Uninstall for. + */ +export function isPairManagedInstall(owner: string | undefined): boolean { + return owner === 'pair' +} + +/** + * The tool to name for a copy PAIR must not remove, which is the package manager + * that owns it. Null for a copy PAIR made itself, one that was merely found, and + * for a node where nothing is installed: none of those have a tool to name. + */ +export function engineOwnerTool(owner: string | undefined): string | null { + if (!owner || OWNERS_WITHOUT_A_TOOL.has(owner)) return null + return owner +} + /** * Shallow placeholder when no model list has been pushed for this node/engine * yet. For an engine whose list is read from disk and shown while it is stopped, diff --git a/desktop/src/ui/api/engine-api.ts b/desktop/src/ui/api/engine-api.ts index 0c1e42854..3fe37ceda 100644 --- a/desktop/src/ui/api/engine-api.ts +++ b/desktop/src/ui/api/engine-api.ts @@ -15,6 +15,7 @@ import type { EngineCommandPayload } from '@/shared/types/engine-api' import type { EngineProgress, EngineType } from '@/shared/types/engines' +import { EngineCapabilities } from '@/ui/constants/engine-capabilities' import { usePendingActionsStore } from '@/ui/stores/pending-actions.store' import { useEngineStatusStore } from '@/ui/stores/engine-status.store' import { useOverviewUiStore } from '@/ui/stores/overview-ui.store' @@ -91,15 +92,18 @@ function fireCommand(transport: ServiceTransport, payload: EngineCommandPayload) // Remember the user's setup interaction across the backend's install/start // reports. Only an awaiting-model report opens the picker; a saved model // resuming normally needs no intervention. This covers onboarding and Retry - // as well as both engine switches. + // as well as both engine switches, and it names the engine so a picker offer + // reads that engine's state rather than always vLLM's. if ( - payload.engineType === 'vllm' && + EngineCapabilities[payload.engineType].needsModelSelection && (payload.command === 'install' || (payload.command === 'toggle' && - useEngineStatusStore.getState().statusByNode.get(payload.nodeId)?.get('vllm') - ?.processStatus === 'stopped')) + useEngineStatusStore + .getState() + .statusByNode.get(payload.nodeId) + ?.get(payload.engineType)?.processStatus === 'stopped')) ) { - useOverviewUiStore.getState().requestModelSelection(payload.nodeId) + useOverviewUiStore.getState().requestModelSelection(payload.nodeId, payload.engineType) } // Optimistically flip the clicked control to a "working"/disabled state so // the user gets immediate feedback even when the backend push lags (esp. diff --git a/desktop/src/ui/components/BackendRow/BackendFooter.tsx b/desktop/src/ui/components/BackendRow/BackendFooter.tsx index fc7ece399..af11cd38b 100644 --- a/desktop/src/ui/components/BackendRow/BackendFooter.tsx +++ b/desktop/src/ui/components/BackendRow/BackendFooter.tsx @@ -6,8 +6,7 @@ import type { CSSProperties } from 'react' import { Button, Flex, Stack, Text } from '@nvidia/foundations-react-core' import { OpenInNew } from '@/ui/components/icons' import type { BackendInfo } from '@/ui/types/engine-info' -import type { PlatformDisplayName } from '@/shared/types/platform' -import { canAutoInstallBackendForOs } from '@/ui/utils/backend-target-os' +import { engineOwnerTool, isPairManagedInstall } from '@/shared/utils/engines' const INLINE_LINK_STYLE: CSSProperties = { alignItems: 'center', @@ -22,23 +21,29 @@ function displayVersion(version: string): string { export function BackendFooter({ backend, - targetOs, showUninstall, disabled, onUninstall }: { backend: BackendInfo - targetOs: PlatformDisplayName showUninstall: boolean disabled: boolean onUninstall: () => void }) { - const autoInstall = canAutoInstallBackendForOs(backend.type, targetOs) const isTransitioning = backend.processStatus === 'installing' || backend.processStatus === 'uninstalling' const isNotInstalled = backend.processStatus === 'not-installed' const isInstalled = !isNotInstalled && !isTransitioning + // Uninstall appears only for the copies NVPAIR is allowed to remove. Who owns + // the copy that is here is the owning node's engine manager's answer, reported + // with its state, and it is the same answer the service would give if the + // button were clicked: it refuses to remove a package manager's install and a + // copy it merely found. A copy owned by a tool gets that tool named instead, + // because the command that removes it is the user's to run. + const ownerTool = engineOwnerTool(backend.owner) + const canUninstall = isPairManagedInstall(backend.owner) + const missingPrereqs = (backend.prerequisites ?? []).filter(p => !p.installed) const openLink = useCallback((e: React.MouseEvent, url: string) => { @@ -97,9 +102,14 @@ export function BackendFooter({ {installedVersion} )} + {ownerTool && ( + + Installed with {ownerTool} + + )} - {autoInstall && showUninstall && isInstalled && ( + {canUninstall && showUninstall && isInstalled && ( diff --git a/desktop/src/ui/components/BackendRow/BackendHeader.tsx b/desktop/src/ui/components/BackendRow/BackendHeader.tsx index 4237c647e..53d6902a5 100644 --- a/desktop/src/ui/components/BackendRow/BackendHeader.tsx +++ b/desktop/src/ui/components/BackendRow/BackendHeader.tsx @@ -5,7 +5,6 @@ import { useCallback, useMemo, useState } from 'react' import { Button, Flex, Stack, Switch, Text } from '@nvidia/foundations-react-core' import { Check, ContentCopy, ExpandMore, OpenInNew } from '@/ui/components/icons' import type { BackendInfo } from '@/ui/types/engine-info' -import type { PlatformDisplayName } from '@/shared/types/platform' import { InstallButton } from './InstallButton' import { DismissibleTooltip } from '@/ui/components/DismissibleTooltip/DismissibleTooltip' import { gatewayEndpointDisplayUrl } from '@/ui/utils/gateway-inference-paths' @@ -29,7 +28,6 @@ export function BackendHeader({ onExpand, expanded, isLocalNode, - targetOs, onInstall }: { backend: BackendInfo @@ -43,7 +41,6 @@ export function BackendHeader({ onExpand: () => void expanded: boolean isLocalNode: boolean - targetOs: PlatformDisplayName onInstall: () => void }) { const caps = EngineCapabilities[backend.type] @@ -279,7 +276,6 @@ export function BackendHeader({ {!isUnavailable && !isTransitioning && backend.processStatus === 'not-installed' && ( state.nodes.get(nodeId)?.os) - const targetOs = nodeOs ?? window.windowApi.platform - const handleToggle = useCallback(() => { window.pairApi.engines.toggle(backend.type, nodeId) }, [backend.type, nodeId]) @@ -212,7 +208,6 @@ export function BackendRow({ {expanded && } diff --git a/desktop/src/ui/components/BackendRow/InstallButton.tsx b/desktop/src/ui/components/BackendRow/InstallButton.tsx index ede974071..d3741dde3 100644 --- a/desktop/src/ui/components/BackendRow/InstallButton.tsx +++ b/desktop/src/ui/components/BackendRow/InstallButton.tsx @@ -5,30 +5,36 @@ import { useCallback } from 'react' import { Button, Flex, Stack, Text } from '@nvidia/foundations-react-core' import { OpenInNew } from '@/ui/components/icons' import type { BackendInfo } from '@/ui/types/engine-info' -import type { PlatformDisplayName } from '@/shared/types/platform' -import { canAutoInstallBackendForOs } from '@/ui/utils/backend-target-os' import { DismissibleTooltip } from '@/ui/components/DismissibleTooltip/DismissibleTooltip' import { useDismissibleTooltipTrigger } from '@/ui/hooks/use-dismissible-tooltip-trigger' export function InstallButton({ backend, - targetOs, isLocalNode, disabled, onInstall }: { backend: BackendInfo - targetOs: PlatformDisplayName isLocalNode: boolean disabled: boolean onInstall: () => void }) { - // A remote not-installed status means the peer's engine manager lists this - // engine as supported. Its OS is a placeholder, so only local installs use it. - const autoInstall = !isLocalNode || canAutoInstallBackendForOs(backend.type, targetOs) + // Whether NVPAIR can obtain the engine is the owning node's engine manager's + // answer, reported with its state: only it knows whether that platform declares + // an install at all, and whether the tool that install runs through is on that + // machine. A missing answer means no button. The alternative is a button whose + // only outcome is a refusal naming a missing package manager, by which point + // the user has already decided they want the engine. + const canInstall = backend.canInstall === true const isNotInstalled = backend.processStatus === 'not-installed' const missingPrereqs = (backend.prerequisites ?? []).filter(p => !p.installed) const prereqsMet = missingPrereqs.length === 0 + // Where NVPAIR cannot fetch the engine itself, the vendor's own download page + // takes its place — for an engine like MTPLX, whose only other source is the + // vendor's installer. Remote cards get no link: a download started here lands + // here, not on the machine the card describes. + const downloadUrl = + !canInstall && isLocalNode && isNotInstalled ? backend.installUrl : undefined const openLink = useCallback((e: React.MouseEvent, url: string) => { e.preventDefault() @@ -40,10 +46,10 @@ export function InstallButton({ return ( <> - {!autoInstall && isLocalNode && isNotInstalled && backend.installUrl && ( + {downloadUrl && ( )} - {autoInstall && + {canInstall && isNotInstalled && (!prereqsMet ? ( state) const { fetchedNodes, clearNodes } = useNodesStore(state => state) const activeTab = useOverviewUiStore(state => state.activeTab) - const modelSelectionNodeId = useOverviewUiStore(state => state.modelSelectionNodeId) + const modelSelection = useOverviewUiStore(state => state.modelSelection) const settingsSubTab = useOverviewUiStore(state => state.settingsSubTab) const serviceSettingsOpen = activeTab === 'settings' && settingsSubTab === 'service' const serviceStatus = useServiceStatusStore(state => state.status) @@ -138,10 +138,11 @@ function MainApp() { {/* Keep setup intent in sync while Overview's node controls are unmounted. */} - {modelSelectionNodeId && ( + {modelSelection && ( )} diff --git a/desktop/src/ui/components/ModelManager/EngineModelSelectionModal.tsx b/desktop/src/ui/components/ModelManager/EngineModelSelectionModal.tsx index 800f8d589..a9a11675f 100644 --- a/desktop/src/ui/components/ModelManager/EngineModelSelectionModal.tsx +++ b/desktop/src/ui/components/ModelManager/EngineModelSelectionModal.tsx @@ -21,14 +21,36 @@ import { useNodesStore } from '@/ui/stores/nodes.store' import { useConnectionStore } from '@/ui/stores/connection.store' import { useErrorsStore } from '@/ui/stores/errors.store' import { formatModelDisplayName } from '@/ui/utils/format-model-display-name' +import { EngineDisplayNames } from '@/shared/constants/engines' +import { engineManagerName } from '@/shared/utils/engines' +import type { EngineType } from '@/shared/types/engines' import type { ModelEntry } from '@/ui/types/model-hub' -/** Mounted only for an explicit turn-on/install, never for Eject or restored idle state. */ -export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { +/** + * Mounted only for an explicit turn-on/install, never for Eject or restored idle + * state, and only for one engine on one node: the app keeps a single setup + * interaction alive, so a second one replaces the first rather than stacking a + * second dialog over it. + * + * It names the engine because a model-selecting engine has to be told which model + * to serve. vLLM and MTPLX both take theirs as a launch argument and both refuse + * to come up without one, so the picker offers whatever each of them has already + * downloaded and searches that engine's own catalog. + */ +export function EngineModelSelectionModal({ + nodeId, + engineType +}: { + nodeId: string + engineType: EngineType +}) { const dialogId = useId() - const status = useEngineStatusStore(s => s.statusByNode.get(nodeId)?.get('vllm')?.processStatus) - const inventory = useEngineModelsStore(s => s.models.get(`${nodeId}:vllm`)) - const pending = usePendingActionsStore(s => s.getLifecyclePending(nodeId, 'vllm')) + const displayName = EngineDisplayNames[engineType] + const status = useEngineStatusStore( + s => s.statusByNode.get(nodeId)?.get(engineType)?.processStatus + ) + const inventory = useEngineModelsStore(s => s.models.get(`${nodeId}:${engineType}`)) + const pending = usePendingActionsStore(s => s.getLifecyclePending(nodeId, engineType)) const isRemote = useConnectionStore(s => s.selfId !== nodeId) const isDisconnected = useNodesStore(s => isRemote && s.nodes.get(nodeId)?.status === 'offline') const [addingModel, setAddingModel] = useState(false) @@ -38,16 +60,19 @@ export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { const waiting = status === 'awaiting-model' && !pending && !isDisconnected useEffect(() => { + // A failed start also lands as the toggle command's own error, which + // names the engine the way the engine manager spells it. const failed = errors.some( error => initialErrors.get(error.id) !== error.timestamp && error.severity !== 'info' && error.severity !== 'warning' && - (error.engineType === 'vllm' || error.id === 'engine-cmd:toggle:vllm') && + (error.engineType === engineType || + error.id === `engine-cmd:toggle:${engineManagerName(engineType)}`) && (error.nodeId ? error.nodeId === nodeId : !isRemote) ) if (failed) useOverviewUiStore.getState().dismissModelSelection() - }, [errors, initialErrors, nodeId, isRemote]) + }, [errors, initialErrors, nodeId, engineType, isRemote]) useEffect(() => { const ui = useOverviewUiStore.getState() @@ -73,23 +98,23 @@ export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { // Read current service state so a request that has already started // loading a model is never canceled by a stale dialog close event. if ( - useEngineStatusStore.getState().statusByNode.get(nodeId)?.get('vllm')?.processStatus === - 'awaiting-model' + useEngineStatusStore.getState().statusByNode.get(nodeId)?.get(engineType) + ?.processStatus === 'awaiting-model' ) { - window.pairApi.engines.stop('vllm', nodeId) + window.pairApi.engines.stop(engineType, nodeId) } } const loadModel = (name: string) => { useOverviewUiStore.getState().dismissModelSelection() - window.pairApi.engines.loadModel('vllm', nodeId, name) + window.pairApi.engines.loadModel(engineType, nodeId, name) } const downloadModels = (entries: ModelEntry[]) => { if (entries.length === 0) return useOverviewUiStore.getState().dismissModelSelection() for (const entry of entries) { - window.pairApi.engines.pullModel('vllm', nodeId, entry.name) + window.pairApi.engines.pullModel(engineType, nodeId, entry.name) } } @@ -98,7 +123,7 @@ export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { if (addingModel) { return ( { if (!open) setAddingModel(false) @@ -123,11 +148,11 @@ export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { maxHeight: 'calc(100vh - 32px)' }} > - Choose a model for vLLM + Choose a model for {displayName} - vLLM needs a loaded model, please click on an existing model below to - load or add one. + {displayName} needs a loaded model, please click on an existing model + below to load or add one. {models.length > 0 ? ( @@ -140,7 +165,7 @@ export function EngineModelSelectionModal({ nodeId }: { nodeId: string }) { aria-label={`Load ${model.name}`} onClick={() => loadModel(model.name)} > - {formatModelDisplayName(model.name, 'vllm')} + {formatModelDisplayName(model.name, engineType)} ))} diff --git a/desktop/src/ui/components/ModelManager/ModelManager.tsx b/desktop/src/ui/components/ModelManager/ModelManager.tsx index 757459a64..dd649ab78 100644 --- a/desktop/src/ui/components/ModelManager/ModelManager.tsx +++ b/desktop/src/ui/components/ModelManager/ModelManager.tsx @@ -201,7 +201,7 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId return ( - {backend.type === 'vllm' && + {caps?.needsModelSelection && backend.processStatus === 'awaiting-model' && !modelLoadPending && !models.some(model => model.status === 'loading') && ( @@ -213,8 +213,10 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId > No model loaded. Load a downloaded model from the list - below, or add one. Requests to the PAIR vLLM endpoint can also load - downloaded models. + below, or add one. + {caps?.loadsModelOnRequest + ? ` Requests to the PAIR ${backend.displayName} endpoint can also load downloaded models.` + : ''} )} diff --git a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx index 37ef126ae..a7d733233 100644 --- a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx +++ b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx @@ -36,8 +36,11 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { if (!nodeStatuses) return '' const parts: string[] = [] for (const [type, s] of nodeStatuses) { + // The two install facts are part of the fingerprint: an install that + // finishes, or a copy that turns out to belong to Homebrew, changes + // which buttons the card may offer. parts.push( - `${type}:${s.processStatus}:${s.enginePort ?? ''}:${s.proxyPort ?? ''}:${s.installedVersion ?? ''}` + `${type}:${s.processStatus}:${s.enginePort ?? ''}:${s.proxyPort ?? ''}:${s.installedVersion ?? ''}:${s.canInstall ? 'installable' : ''}:${s.owner ?? ''}` ) } return parts.join('|') @@ -104,6 +107,8 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { docsUrl: EngineDefaultLinks[type]?.docsUrl, installUrl: EngineDefaultLinks[type]?.installUrl, installedVersion: status.installedVersion, + canInstall: status.canInstall, + owner: status.owner, updateAvailable }, statusKnown diff --git a/desktop/src/ui/constants/engine-capabilities.ts b/desktop/src/ui/constants/engine-capabilities.ts index d04f44791..5764bba72 100644 --- a/desktop/src/ui/constants/engine-capabilities.ts +++ b/desktop/src/ui/constants/engine-capabilities.ts @@ -83,6 +83,12 @@ export const EngineCapabilities: Record = { deleteBlockedWhileLoaded: true, // Load writes the model into the launch arguments and restarts vLLM on it. loadRestartsEngine: true, + // vLLM takes its model as a launch argument and will not start without + // one, so turning it on offers the picker. + needsModelSelection: true, + // A request naming a cached model prepares it first, which is why the + // waiting banner can say a request may load it. + loadsModelOnRequest: true, engineHub: { label: 'vLLM', url: 'https://huggingface.co/models?pipeline_tag=text-generation&library=safetensors&sort=trending' @@ -93,11 +99,13 @@ export const EngineCapabilities: Record = { // MTPLX serves one pack per process and cannot drop it while running, so // Eject stops the engine and Load starts it again on the chosen pack. hasEject: true, - // Detect-only, and Apple Silicon only: PAIR drives the `mtplx` CLI of an - // install the user made themselves and never installs or uninstalls it. - // An empty list means no auto-install, and `getWelcomeEngineCandidates` - // leaves the engine out of onboarding rather than showing an install row - // that cannot be fulfilled. + // Apple Silicon only, and obtained through Homebrew rather than a copy PAIR + // downloads, so an empty list here does not mean "cannot be installed": the + // engine card asks the owning node (`canInstall`, which needs a Homebrew + // prefix on that machine) and offers the vendor's download page where brew + // is missing. The empty list is only what keeps MTPLX out of the onboarding + // picker, which would otherwise offer a default install whose tool most + // fresh Macs do not have. hasInstall: [], hasEnginePort: true, hasInstallPath: false, @@ -116,6 +124,9 @@ export const EngineCapabilities: Record = { deleteBlockedWhileLoaded: true, // Load rewrites the model launch flags and restarts MTPLX on them. loadRestartsEngine: true, + // Like vLLM, MTPLX takes its pack as a launch argument and PAIR will not + // start it without one, so turning it on offers the picker too. + needsModelSelection: true, // MTPLX only runs packs built for it, and that list is the only place // they are named, so the hub lists those rather than any safetensors repo. engineHub: { diff --git a/desktop/src/ui/constants/welcome.ts b/desktop/src/ui/constants/welcome.ts index 12a449510..fe57ed7b6 100644 --- a/desktop/src/ui/constants/welcome.ts +++ b/desktop/src/ui/constants/welcome.ts @@ -24,6 +24,14 @@ export const WELCOME_ENGINE_DEFAULT_SELECTED: Partial { diff --git a/desktop/src/ui/stores/overview-ui.store.ts b/desktop/src/ui/stores/overview-ui.store.ts index 29262949e..9fad92d2d 100644 --- a/desktop/src/ui/stores/overview-ui.store.ts +++ b/desktop/src/ui/stores/overview-ui.store.ts @@ -4,8 +4,15 @@ import { create } from 'zustand' import type { SettingsWindowTab } from '@/ui/types/settings-window' import type { OverviewTab } from '@/shared/types/overview' +import type { EngineType } from '@/shared/types/engines' import { useErrorsStore } from '@/ui/stores/errors.store' +/** Which engine's model picker a setup interaction is waiting to offer. */ +interface ModelSelectionRequest { + nodeId: string + engineType: EngineType +} + interface OverviewUiStore { /** Which top-level Overview tab is showing the content area. */ activeTab: OverviewTab @@ -13,8 +20,12 @@ interface OverviewUiStore { settingsSubTab: SettingsWindowTab /** One-shot request to expand a node card's inline engine settings. */ focusNodeId: string | null - /** Turn-on/install interaction waiting to offer vLLM model selection. */ - modelSelectionNodeId: string | null + /** + * Turn-on/install interaction waiting to offer model selection, for the engine + * the user acted on. One slot, not a list: a second setup interaction + * replaces the first, which is what the app does with two dialogs anyway. + */ + modelSelection: ModelSelectionRequest | null /** Error identities at the start of setup, retained across tab navigation. */ modelSelectionErrorBaseline: ReadonlyMap setActiveTab: (tab: OverviewTab) => void @@ -25,7 +36,7 @@ interface OverviewUiStore { focusNodeEngineSettings: (nodeId: string) => void /** Clear a pending focus request once a card has consumed it. */ consumeFocusNode: () => void - requestModelSelection: (nodeId: string) => void + requestModelSelection: (nodeId: string, engineType: EngineType) => void dismissModelSelection: () => void } @@ -33,7 +44,7 @@ export const useOverviewUiStore = create(set => ({ activeTab: 'overview', settingsSubTab: 'cluster', focusNodeId: null, - modelSelectionNodeId: null, + modelSelection: null, modelSelectionErrorBaseline: new Map(), setActiveTab: tab => set({ activeTab: tab }), @@ -50,13 +61,13 @@ export const useOverviewUiStore = create(set => ({ consumeFocusNode: () => set({ focusNodeId: null }), - requestModelSelection: nodeId => + requestModelSelection: (nodeId, engineType) => set({ - modelSelectionNodeId: nodeId, + modelSelection: { nodeId, engineType }, modelSelectionErrorBaseline: new Map( useErrorsStore.getState().errors.map(error => [error.id, error.timestamp]) ) }), - dismissModelSelection: () => set({ modelSelectionNodeId: null }) + dismissModelSelection: () => set({ modelSelection: null }) })) diff --git a/desktop/src/ui/types/engine-info.ts b/desktop/src/ui/types/engine-info.ts index b9d820c23..f37c9cf64 100644 --- a/desktop/src/ui/types/engine-info.ts +++ b/desktop/src/ui/types/engine-info.ts @@ -110,6 +110,17 @@ export interface BackendInfo { docsUrl?: string /** URL to download/install the backend */ installUrl?: string + /** + * Whether the node that owns this backend can install it on request, as + * that node's engine manager reports it. See `EngineStatusData.canInstall`. + */ + canInstall?: boolean + /** + * Who owns the copy of the backend on its owning node. See + * `EngineStatusData.owner`. Read it with `isPairManagedInstall` / + * `engineOwnerTool`. + */ + owner?: string /** User-configured path to the backend installation directory */ installPath?: string /** True when the backend was stopped by user action (not a crash) */ diff --git a/desktop/src/ui/types/engine-manifest.ts b/desktop/src/ui/types/engine-manifest.ts index eec7a1fc3..f75c9f522 100644 --- a/desktop/src/ui/types/engine-manifest.ts +++ b/desktop/src/ui/types/engine-manifest.ts @@ -18,7 +18,12 @@ export interface EngineHubConfig { export interface EngineCaps { hasExpiry: boolean hasEject: boolean - /** Platforms where PAIR can auto-install this engine. Empty = no auto-install. */ + /** + * Platforms where the onboarding picker offers this engine, on the machine + * running the app. It is no longer what the engine card asks: there the + * owning node reports `EngineStatusData.canInstall`, which knows whether the + * tool an install runs through is on that machine. Empty = never offered. + */ hasInstall: SupportedPlatform[] /** Whether the engine has its own server port (vs CLI-per-request). */ hasEnginePort: boolean @@ -40,6 +45,21 @@ export interface EngineCaps { * stopped and is shown as starting. */ loadRestartsEngine?: boolean + /** + * When true, the engine serves one model chosen when it is launched, so an + * enabled engine without one cannot serve anything and the model picker is + * offered as soon as it is installed or turned on. Mirrors the manifest's + * `wait_for_model`, which is what makes the engine manager report + * `awaiting_model` rather than starting a server with nothing to serve. + */ + needsModelSelection?: boolean + /** + * When true, a request to PAIR's endpoint for this engine can load a + * downloaded model by itself, so the waiting banner may promise it. Only vLLM + * has that path: MTPLX needs an explicit Load, and it advertises only the pack + * it is serving, so a request for another is not routed to it at all. + */ + loadsModelOnRequest?: boolean /** * When true, the engine restarts as part of deleting a model, so Delete asks * for confirmation first. The engine manager owns the restart; this flag only diff --git a/desktop/src/ui/utils/backend-target-os.ts b/desktop/src/ui/utils/backend-target-os.ts deleted file mode 100644 index d25b35112..000000000 --- a/desktop/src/ui/utils/backend-target-os.ts +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import type { PlatformDisplayName } from '@/shared/types/platform' -import { displayNameToPlatform } from '@/shared/utils/platform' -import type { EngineType } from '@/shared/types/engines' -import { EngineCapabilities } from '@/ui/constants/engine-capabilities' - -/** Whether PAIR can auto-install this backend on the given cluster OS. */ -export function canAutoInstallBackendForOs( - backendType: EngineType, - targetOs: PlatformDisplayName -): boolean { - const targetPlatform = displayNameToPlatform(targetOs) - const platforms = EngineCapabilities[backendType].hasInstall - return platforms.includes(targetPlatform) -} diff --git a/desktop/tests/modular/engine-install-button.test.ts b/desktop/tests/modular/engine-install-button.test.ts index c798af79f..3ab8128d8 100644 --- a/desktop/tests/modular/engine-install-button.test.ts +++ b/desktop/tests/modular/engine-install-button.test.ts @@ -5,25 +5,39 @@ import { createElement } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it } from 'vitest' import type { EngineProcessStatus } from '@/shared/types/engines' +import type { BackendInfo } from '@/ui/types/engine-info' import { InstallButton } from '@/ui/components/BackendRow/InstallButton' -// Render the real control without a browser so the regression catches an omitted button. -function buttonMarkup(processStatus: EngineProcessStatus, isLocalNode: boolean): string { +const VLLM_INSTALL_URL = 'https://docs.vllm.ai/en/latest/getting_started/installation.html' + +/** + * Render the real control without a browser so a regression catches an omitted + * button. The only thing about a machine the control is told is what the node that + * owns the engine reports with its state: whether it could install this engine if + * asked. Nothing here works that out on its own any more, so each case names its + * own fact — including the cases that name none, which is what an unclustered peer, + * a peer without an engine manager, or an older peer's status reads as. + */ +function buttonMarkup( + facts: { canInstall?: boolean }, + processStatus: EngineProcessStatus, + isLocalNode: boolean +): string { + const backend: BackendInfo = { + type: 'vllm', + displayName: 'vLLM', + source: 'detected', + processStatus, + port: null, + proxyPort: null, + models: [], + modelsKnown: false, + installUrl: VLLM_INSTALL_URL, + ...facts + } return renderToStaticMarkup( createElement(InstallButton, { - backend: { - type: 'vllm', - displayName: 'vLLM', - source: 'detected', - processStatus, - port: null, - proxyPort: null, - models: [], - modelsKnown: false, - installUrl: 'https://docs.vllm.ai/en/latest/getting_started/installation.html' - }, - // Discovery supplies Windows as the placeholder OS for every peer. - targetOs: 'Windows', + backend, isLocalNode, disabled: false, onInstall: () => {} @@ -32,22 +46,43 @@ function buttonMarkup(processStatus: EngineProcessStatus, isLocalNode: boolean): } describe('engine installation availability', () => { - it('offers Install when a peer reports vLLM as supported but not installed', () => { - const markup = buttonMarkup('not-installed', false) + it('offers Install on a peer that reports the engine as installable', () => { + // Discovery gives every peer Windows as a placeholder OS, so an operating + // system looked up on this side hid the button for Linux and Apple Silicon + // peers. The peer's own engine manager answers for itself now. + expect(buttonMarkup({ canInstall: true }, 'not-installed', false)).toContain('>Install<') + }) - expect(markup).toContain('Install') - expect(markup).not.toContain('Download') + it('offers no install for a peer that reports no install fact at all', () => { + // A guess here would put a button on the card of any machine whose answer + // has not arrived, and the most that button can do is refuse. + expect(buttonMarkup({}, 'not-installed', false)).toBe('') + expect(buttonMarkup({ canInstall: false }, 'not-installed', false)).toBe('') }) - it('does not offer installation before a peer reports vLLM support', () => { - expect(buttonMarkup('initializing', false)).toBe('') - expect(buttonMarkup('unsupported', false)).toBe('') + it('offers nothing before the engine reports, once it is installed, or while it changes', () => { + for (const status of ['initializing', 'unsupported', 'stopped', 'running'] as const) { + expect(buttonMarkup({ canInstall: true }, status, true)).toBe('') + } }) - it('retains the platform-specific Download action on the local Windows node', () => { - const markup = buttonMarkup('not-installed', true) + it('keeps the vendor download page for an engine this machine cannot install', () => { + const markup = buttonMarkup({}, 'not-installed', true) expect(markup).toContain('Download') expect(markup).not.toContain('>Install<') }) + + it('does not offer a download for a remote engine', () => { + // A download started from this window lands on this machine, not on the + // one the card describes. + expect(buttonMarkup({}, 'not-installed', false)).toBe('') + }) + + it('prefers installing over the download page where both are possible', () => { + const markup = buttonMarkup({ canInstall: true }, 'not-installed', true) + + expect(markup).toContain('>Install<') + expect(markup).not.toContain('Download') + }) }) diff --git a/desktop/tests/modular/engine-model-selection-action.test.ts b/desktop/tests/modular/engine-model-selection-action.test.ts index 04256c34b..b572bf719 100644 --- a/desktop/tests/modular/engine-model-selection-action.test.ts +++ b/desktop/tests/modular/engine-model-selection-action.test.ts @@ -12,7 +12,7 @@ import { type ReactNode } from 'react' import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ButtonProps, ModalHeadingProps, @@ -22,6 +22,7 @@ import type { import NodeEnginesInline from '@/ui/components/NodeList/NodeEnginesInline' import { EngineModelSelectionModal } from '@/ui/components/ModelManager/EngineModelSelectionModal' import type { ModelHubModal } from '@/ui/components/ModelHub/ModelHubModal' +import { EngineDisplayNames } from '@/shared/constants/engines' import type { EngineProcessStatus, EngineStatusData, @@ -164,34 +165,35 @@ afterEach(async () => { useOverviewUiStore.setState({ activeTab: 'overview', focusNodeId: null, - modelSelectionNodeId: null + modelSelection: null }) useErrorsStore.setState({ errors: [] }) Reflect.deleteProperty(window, 'pairApi') Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT') }) -async function reportStatus(processStatus: EngineProcessStatus) { +/** Report one engine's state for the fixture node, keeping other engines' state. */ +async function reportStatus(processStatus: EngineProcessStatus, engineType: EngineType = 'vllm') { const status: EngineStatusData = { - engineType: 'vllm', + engineType, nodeId, processStatus, enginePort: 8001, proxyPort: 8000 } await act(() => { - useEngineStatusStore.setState({ - statusByNode: new Map([ - [nodeId, new Map([['vllm', status]])] - ]) + useEngineStatusStore.setState(state => { + const engines = new Map(state.statusByNode.get(nodeId)) + engines.set(engineType, status) + return { statusByNode: new Map(state.statusByNode).set(nodeId, engines) } }) // A service lifecycle report also supersedes the optimistic command. usePendingActionsStore.setState({ pending: new Map() }) }) } -async function render(processStatus: EngineProcessStatus) { - await reportStatus(processStatus) +async function render(processStatus: EngineProcessStatus, engineType: EngineType = 'vllm') { + await reportStatus(processStatus, engineType) await act(() => root.render(createElement(SelectionTestApp))) } @@ -199,15 +201,16 @@ async function render(processStatus: EngineProcessStatus) { // during a tab change. Keep those lifetimes separate in this focused fixture. function SelectionTestApp() { const activeTab = useOverviewUiStore(state => state.activeTab) - const selectionNodeId = useOverviewUiStore(state => state.modelSelectionNodeId) + const selection = useOverviewUiStore(state => state.modelSelection) return createElement( Fragment, null, activeTab === 'overview' ? createElement(NodeEnginesInline, { nodeId }) : null, - selectionNodeId + selection ? createElement(EngineModelSelectionModal, { - key: selectionNodeId, - nodeId: selectionNodeId + key: `${selection.nodeId}:${selection.engineType}`, + nodeId: selection.nodeId, + engineType: selection.engineType }) : null ) @@ -225,10 +228,11 @@ async function click(text: string) { await act(() => button(text).click()) } -async function turnOn() { - await render('stopped') - const control = host.querySelector('[aria-label="Start vLLM"]') - if (!control) throw new Error('Missing Start vLLM switch') +async function turnOn(engineType: EngineType = 'vllm') { + await render('stopped', engineType) + const label = `Start ${EngineDisplayNames[engineType]}` + const control = host.querySelector(`[aria-label="${label}"]`) + if (!control) throw new Error(`Missing ${label} switch`) await act(() => control.click()) } @@ -249,10 +253,10 @@ function cachedModel(name: string, downloaded = true): ModelItem { } } -function reportModels(models: ModelItem[]) { +function reportModels(models: ModelItem[], engineType: EngineType = 'vllm') { useEngineModelsStore.setState({ models: new Map([ - [`${nodeId}:vllm`, { engineType: 'vllm', nodeId, models, inventoryKnown: true }] + [`${nodeId}:${engineType}`, { engineType, nodeId, models, inventoryKnown: true }] ]) }) } @@ -342,7 +346,7 @@ it('skips model selection when a saved selection starts normally', async () => { await reportStatus('running') expect(host.querySelector('[role="dialog"]')).toBeNull() - expect(useOverviewUiStore.getState().modelSelectionNodeId).toBeNull() + expect(useOverviewUiStore.getState().modelSelection).toBeNull() expect(commands.stop).not.toHaveBeenCalled() }) @@ -412,7 +416,7 @@ it('forgets selection after a failed start so later idle state cannot reopen it' await reportStatus('awaiting-model') expect(host.querySelector('[role="dialog"]')).toBeNull() - expect(useOverviewUiStore.getState().modelSelectionNodeId).toBeNull() + expect(useOverviewUiStore.getState().modelSelection).toBeNull() expect(commands.stop).not.toHaveBeenCalled() }) @@ -458,7 +462,7 @@ it('remembers a failed start while engine controls are unmounted so returning ca await act(() => useOverviewUiStore.getState().setActiveTab('overview')) await render('stopped') - expect(useOverviewUiStore.getState().modelSelectionNodeId).toBeNull() + expect(useOverviewUiStore.getState().modelSelection).toBeNull() await reportStatus('awaiting-model') expect(host.querySelector('[role="dialog"]')).toBeNull() @@ -472,7 +476,7 @@ it('forgets a saved-model start while Overview is absent so Eject cannot reopen await reportStatus('starting') await reportStatus('running') - expect(useOverviewUiStore.getState().modelSelectionNodeId).toBeNull() + expect(useOverviewUiStore.getState().modelSelection).toBeNull() await reportStatus('awaiting-model') await act(() => useOverviewUiStore.getState().setActiveTab('overview')) @@ -481,3 +485,47 @@ it('forgets a saved-model start while Overview is absent so Eject cannot reopen expect(host.querySelector('[role="dialog"]')).toBeNull() expect(commands.stop).not.toHaveBeenCalled() }) + +describe('MTPLX model selection', () => { + it('names MTPLX in the picker and loads the chosen pack on MTPLX', async () => { + const pack = 'mtplx-community/Qwen2.5-7B-Instruct-4bit' + reportModels([cachedModel(pack)], 'mtplx') + await turnOn('mtplx') + + expect(commands.toggle).toHaveBeenCalledExactlyOnceWith('mtplx', nodeId) + + await reportStatus('awaiting-model', 'mtplx') + + expect(host.querySelector('h2')?.textContent).toBe('Choose a model for MTPLX') + expect(host.textContent).toContain('MTPLX needs a loaded model') + const load = host.querySelector(`[aria-label="Load ${pack}"]`) + if (!load) throw new Error('The downloaded pack was not offered') + + await act(() => load.click()) + + expect(commands.loadModel).toHaveBeenCalledExactlyOnceWith('mtplx', nodeId, pack) + expect(commands.stop).not.toHaveBeenCalled() + }) + + it('searches MTPLX own catalog and pulls the pack onto MTPLX', async () => { + await turnOn('mtplx') + await reportStatus('awaiting-model', 'mtplx') + await click('Add model') + + expect(host.querySelector('[aria-label="Model catalog"]')).not.toBeNull() + await click('Download selected model') + + expect(commands.pullModel).toHaveBeenCalledExactlyOnceWith('mtplx', nodeId, 'org/new-model') + expect(commands.stop).not.toHaveBeenCalled() + }) + + it('offers no picker for an engine that takes its model per request', async () => { + await turnOn('ollama') + + expect(useOverviewUiStore.getState().modelSelection).toBeNull() + + await reportStatus('awaiting-model', 'ollama') + + expect(host.querySelector('[role="dialog"]')).toBeNull() + }) +}) diff --git a/desktop/tests/modular/model-manager-transitions.test.ts b/desktop/tests/modular/model-manager-transitions.test.ts index 8c7951a70..037fa89b3 100644 --- a/desktop/tests/modular/model-manager-transitions.test.ts +++ b/desktop/tests/modular/model-manager-transitions.test.ts @@ -382,3 +382,16 @@ describe('vLLM model controls', () => { expect(commands.deleteModel).not.toHaveBeenCalled() }) }) + +describe('MTPLX model controls', () => { + it('warns that no pack is loaded without promising a request loads one', async () => { + await render('mtplx', 'awaiting-model') + + const banner = host.querySelector('[role="status"]') + expect(banner?.textContent).toContain('No model loaded') + expect(banner?.textContent).toContain( + 'Load a downloaded model from the list below, or add one.' + ) + expect(banner?.textContent).not.toContain('Requests to the PAIR') + }) +}) diff --git a/desktop/tests/modular/mtplx-card-actions.test.ts b/desktop/tests/modular/mtplx-card-actions.test.ts index bfe28722e..8739d2a67 100644 --- a/desktop/tests/modular/mtplx-card-actions.test.ts +++ b/desktop/tests/modular/mtplx-card-actions.test.ts @@ -17,13 +17,19 @@ import { BackendFooter } from '@/ui/components/BackendRow/BackendFooter' /** * Renders the two parts of an engine card that decide what the user is offered: - * the header row (its on/off control plus an Install affordance when the engine - * is not installed) and the footer (the Uninstall affordance). Both are rendered - * as the card renders them, with the links a real card is given, so a change to - * the capability table or to a button's condition shows up here rather than only - * in a person's window. + * the header row (its on/off control plus an Install affordance when the engine is + * not installed) and the footer (the Uninstall affordance). Both are rendered as + * the card renders them, with the links a real card is given, and with the two + * install facts a real node reports — whether it could install the engine, and who + * owns the copy that is there. Those facts, not a per-engine list of operating + * systems, are what the two buttons read, so a card built from a machine that has + * no way to obtain an engine is a different card from one that does. */ -function cardFor(engineType: EngineType, processStatus: EngineProcessStatus): BackendInfo { +function cardFor( + engineType: EngineType, + processStatus: EngineProcessStatus, + facts: { canInstall?: boolean; owner?: string } = {} +): BackendInfo { return { type: engineType, displayName: EngineDisplayNames[engineType], @@ -34,11 +40,12 @@ function cardFor(engineType: EngineType, processStatus: EngineProcessStatus): Ba models: [], modelsKnown: EnginesListingModelsWhenStopped.includes(engineType), docsUrl: EngineDefaultLinks[engineType].docsUrl, - installUrl: EngineDefaultLinks[engineType].installUrl + installUrl: EngineDefaultLinks[engineType].installUrl, + ...facts } } -function headerMarkup(backend: BackendInfo): string { +function headerMarkup(backend: BackendInfo, isLocalNode = true): string { return renderToStaticMarkup( createElement(BackendHeader, { backend, @@ -49,8 +56,7 @@ function headerMarkup(backend: BackendInfo): string { onStop: () => {}, onExpand: () => {}, expanded: false, - isLocalNode: true, - targetOs: 'MacOS', + isLocalNode, onInstall: () => {} }) ) @@ -60,7 +66,6 @@ function footerMarkup(backend: BackendInfo): string { return renderToStaticMarkup( createElement(BackendFooter, { backend, - targetOs: 'MacOS', showUninstall: true, disabled: false, onUninstall: () => {} @@ -69,27 +74,70 @@ function footerMarkup(backend: BackendInfo): string { } describe('MTPLX engine card on Apple Silicon macOS', () => { - it('offers no install command for MTPLX, where vLLM on the same Mac gets one', () => { - const mtplx = headerMarkup(cardFor('mtplx', 'not-installed')) - const vllm = headerMarkup(cardFor('vllm', 'not-installed')) + it('offers to install MTPLX through Homebrew where Homebrew is', () => { + // The engine card stops guessing. An Apple Silicon Mac with brew can have + // MTPLX put in the prefix brew owns, so that card carries the same Install + // affordance a vLLM card does — which is how an engine that installs + // through a package manager gets offered at all, an OS list could not tell + // the two Macs apart. + const withBrew = headerMarkup(cardFor('mtplx', 'not-installed', { canInstall: true })) + const withoutBrew = headerMarkup(cardFor('mtplx', 'not-installed')) - expect(vllm).toContain('Install') - expect(mtplx).not.toContain('>Install<') - expect(mtplx).not.toContain('Install all') - // Reading about MTPLX and getting it from its own distribution is still - // offered; it is only PAIR installing it that is not. - expect(mtplx).toContain('Download') + expect(withBrew).toContain('>Install<') + // Where there is no brew, reading about MTPLX and getting it from its own + // distribution is what is offered instead. + expect(withoutBrew).not.toContain('>Install<') + expect(withoutBrew).toContain('Download') }) - it('offers no uninstall for MTPLX, where vLLM on the same Mac gets one', () => { - const mtplx = footerMarkup(cardFor('mtplx', 'running')) - const vllm = footerMarkup(cardFor('vllm', 'running')) + it('offers Install on a remote card only when that node reports it can install', () => { + // Installing on a clustered peer is a real action, so a remote card is not + // blanketed off; what it refuses to do is assume. An unclustered peer never + // reports these facts and an older peer's status carries neither field, so + // both read as nothing installable rather than as something to try, and a + // download started from a remote card would land on this machine anyway. + const reporting = headerMarkup( + cardFor('mtplx', 'not-installed', { canInstall: true }), + false + ) + const silent = headerMarkup(cardFor('mtplx', 'not-installed'), false) - expect(vllm).toContain('Uninstall') - expect(mtplx).not.toContain('Uninstall') - // A server the user started is still theirs to stop: the card keeps its - // on/off control, which for a running engine reads as Stop. - expect(headerMarkup(cardFor('mtplx', 'running'))).toContain('Stop MTPLX') + expect(reporting).toContain('>Install<') + expect(silent).not.toContain('>Install<') + expect(silent).not.toContain('Download') + }) + + it('offers no uninstall for a Homebrew MTPLX, where a PAIR install gets one', () => { + // Installing through brew puts MTPLX in the prefix brew owns, beside the + // model library the user's own copy of MTPLX shares. PAIR refuses to remove + // that, and a button for a refusal the service has already made is not + // worth clicking. + const brew = footerMarkup(cardFor('mtplx', 'running', { owner: 'Homebrew' })) + const pairManaged = footerMarkup(cardFor('vllm', 'running', { owner: 'pair' })) + + expect(brew).not.toContain('Uninstall') + expect(pairManaged).toContain('Uninstall') + // Instead the card names the tool that does own it. + expect(brew).toContain('Installed with Homebrew') + expect(pairManaged).not.toContain('Installed with') + }) + + it('offers no uninstall for a copy that was merely found, either', () => { + // MTPLX.app brings its own runtime and PAIR only drives the command it + // finds: nothing on this machine was installed by PAIR, so nothing here is + // PAIR's to take back out. + const found = footerMarkup(cardFor('mtplx', 'running', { owner: 'other' })) + + expect(found).not.toContain('Uninstall') + expect(found).not.toContain('Installed with') + }) + + it('keeps the on/off control for a server the user started themselves', () => { + // A running MTPLX the user started is still theirs to stop: the card keeps + // its switch, which for a running engine reads as Stop. + expect(headerMarkup(cardFor('mtplx', 'running', { owner: 'Homebrew' }))).toContain( + 'Stop MTPLX' + ) }) it('keeps MTPLX model controls available while the engine is stopped', () => { @@ -98,7 +146,14 @@ describe('MTPLX engine card on Apple Silicon macOS', () => { // engine is not shown as having nothing to load. expect(EnginesListingModelsWhenStopped).toContain('mtplx') expect(EngineCapabilities.mtplx.hasModelSearchOnlyWhenRunning).toBe(false) - expect(EngineCapabilities.mtplx.hasInstall).toEqual([]) expect(EngineCapabilities.mtplx.hasEject).toBe(true) }) + + it('keeps MTPLX out of the onboarding picker, which is a choice about first run', () => { + // An empty `hasInstall` no longer decides the engine card — brew or no brew + // does — so the picker's own exclusion needs pinning on its own terms: it + // would otherwise default-select an engine whose install most fresh Macs + // cannot run. + expect(EngineCapabilities.mtplx.hasInstall).toEqual([]) + }) }) diff --git a/docs/engine-lifecycle.mdx b/docs/engine-lifecycle.mdx index df855afb7..7079b398f 100644 --- a/docs/engine-lifecycle.mdx +++ b/docs/engine-lifecycle.mdx @@ -146,13 +146,36 @@ When you install an engine, consider the following: does not unload automatically after inactivity. Use **Eject** to release its memory. -- MTPLX runs on Apple Silicon Macs only, and PAIR never installs it. Where a - `mtplx` install is found at a known location, PAIR drives it: it starts and stops - `mtplx serve`, lists the packs already in `~/.mtplx/models`, and downloads or - deletes packs with `mtplx pull` and `mtplx remove`. Nothing is installed, and an - uninstall or a data reset leaves MTPLX and its packs alone, so first-run setup - never offers it. Like vLLM it serves one pack per process, so **Load** restarts - the engine on the pack you pick and **Eject** stops it. A bare **Start** refuses +- MTPLX runs on Apple Silicon Macs only, and nowhere else: an Intel Mac, a + Linux machine, or a Windows machine never shows an MTPLX card. Where a + `mtplx` command is already found at a known location, PAIR drives it: it + starts and stops `mtplx serve`, lists the packs already in `~/.mtplx/models`, + and downloads or deletes packs with `mtplx pull` and `mtplx remove`. Where + none is found and the Mac has Homebrew, **Install** installs it through + Homebrew: PAIR adds the `youssofal/mtplx` tap, trusts the formula, and runs + `brew install youssofal/mtplx/mtplx`, then runs the command that Homebrew + installed to check that MTPLX actually answers before calling the install + done. That check is the point of the order: the Python runtime MTPLX runs on + is built as part of this, either by the formula's own install step or, if + that skipped it, by MTPLX's launcher inside the first start. Doing it during + the install, which allows half an hour, keeps a several-hundred megabyte + build out of a start, which only allows ten minutes, and a start is otherwise + where you would find out the engine does not work. Without Homebrew there is + nothing for PAIR to install with, so the local card offers **Download** in + place of **Install** and opens MTPLX's own download page. A remote card + offers neither: a download started here would land here, not on the machine + the card describes. Anywhere there is no way to obtain the engine, the card + shows nothing rather than a button whose only outcome is a refusal. + Installing MTPLX opens **Choose a model for MTPLX** first, because nothing + in the launch arguments names a pack until you pick one. + + Because those files live in Homebrew's tree and not in a folder PAIR owns, + there is no **Uninstall** button for a Homebrew MTPLX — the card says + **Installed with Homebrew** instead, and removing it means + `brew uninstall youssofal/mtplx/mtplx`. A data reset leaves MTPLX and its + packs alone for the same reason, so first-run setup never offers it. Like + vLLM it serves one pack per process, so **Load** restarts the engine on the + pack you pick and **Eject** stops it. A bare **Start** refuses with a message to load a model, because nothing in the launch arguments names one. **Add model** browses the pack list MTPLX publishes rather than searching Hugging Face, because the engine runs only packs rebuilt for its own decode @@ -218,11 +241,16 @@ PAIR does not currently offer to update an engine, because it does not yet detec newer engine versions. To move an NVPAIR-installed Ollama or LM Studio to the vendor's current release, uninstall it and install it again, which keeps your models as described below. llama.cpp installs the build pinned by your version of -PAIR. Update an engine you installed yourself with its own installer. +PAIR. Update a Homebrew MTPLX with `brew upgrade mtplx`. Update an engine you +installed yourself with its own installer. **Uninstall** removes the NVPAIR-installed copy of an engine, and applies only to an engine PAIR installed. Use it when you no longer want PAIR to own that engine -on the machine. +on the machine. A MTPLX obtained through Homebrew is the one exception: PAIR ran +the install, but the files are Homebrew's, so no card offers **Uninstall** for it +and an explicit uninstall request is refused with the command that works. Removing +that copy means `brew uninstall youssofal/mtplx/mtplx`, which also leaves +`~/.mtplx/models` where it is. Uninstalling an engine does **not** remove its models. Downloaded model files stay on disk in the engine's own storage (`~/.ollama`, `~/.llamacpp`, diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx index a918e4a1e..a64e1b7a2 100644 --- a/docs/getting-started.mdx +++ b/docs/getting-started.mdx @@ -37,8 +37,10 @@ Nothing else has to be in place first: - **Engines.** PAIR installs and starts Ollama, LM Studio, llama.cpp, or (on Linux or Apple Silicon macOS) vLLM for you in step 4. Existing Ollama and LM Studio installations can also be detected - and used, as can an existing MTPLX install on an Apple Silicon Mac. MTPLX is - never installed for you; it is used where it is already present. + and used, as can an existing MTPLX install on an Apple Silicon Mac. MTPLX is not + offered during setup: add it afterwards in **Engine settings**, where it installs + through Homebrew on an Apple Silicon Mac that already has Homebrew, and is + otherwise only used where it is already present. - **Models.** PAIR downloads models for you in step 4. A request needs only one eligible node, so a single node holding the model is enough. Prepare the same model on additional nodes when you want any of them to be able to serve it. diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index fa3ec06b4..98f5555f5 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -286,7 +286,10 @@ The status has `installed:true`, `awaiting_model:true`, `running:false`, and `healthy:false`; no vLLM serving process or loaded model is advertised. The optional `awaiting_model` field is false or omitted in other lifecycle states. The desktop shows **Select a model**, keeps the switch on, and offers **Add model** -and **Load** for downloaded models. A stopped engine hides its model controls. +and **Load** for downloaded models. A stopped engine hides its model controls. The +same flow covers any engine whose platform sets `wait_for_model` and declares a +`launch_model` action — today vLLM and MTPLX — so MTPLX gets the same picker, +titled **Choose a model for MTPLX**, and the same orange **No model loaded** banner. An explicit Load saves the chosen model and performs the normal readiness-probed start. Existing saved model arguments remain in effect, so upgrading preserves @@ -303,13 +306,39 @@ engine manager on any other host therefore leaves MTPLX out of `engine:get-installed` rather than reporting it as available, and no client offers it there. -It also declares no `install` block, so MTPLX is detected and never installed. -`~/.mtplx/bin/mtplx`, the MTPLX app's own runtime venv, `/opt/homebrew/bin/mtplx` -and `~/.local/bin/mtplx` are checked in that order and the first one found is -launched. An explicit `engine:uninstall` is an error for it ("no uninstall defined -for this platform") and "reset all data" skips it, because neither has a PAIR -install marker to work from: the engine, and the pack cache the user filled, stay -exactly where they were. +Its `install` block is a `pkg` install, so on a Mac with no `mtplx` anywhere PAIR +installs one: it finds `brew` in `/opt/homebrew/bin` or `/usr/local/bin` (PATH is +never consulted), and runs `brew tap youssofal/mtplx`, +`brew trust --formula youssofal/mtplx/mtplx` — tolerated, because a brew older than +the trust gate has no such command and installs anyway — and +`brew install youssofal/mtplx/mtplx`, with `HOMEBREW_NO_AUTO_UPDATE` and +`HOMEBREW_NO_ENV_HINTS` set so the install spends its budget on this formula. Each +command's output is kept and the tail of it reaches the failure message, because +"Refusing to load formula … from untrusted tap" names the fix and "exit status 1" +does not. Whatever brew reports, the install is only done once +`/opt/homebrew/bin/mtplx --version` answers, run from the same bin directory. That +check is not decoration: brew can exit 0 with MTPLX's Python runtime still unbuilt, +because the launcher would build the venv inside the first launch, and paying for +that inside a start — which has 600 seconds, not the install's 30 minutes, and shows +a spinner instead of a progress line — is how an install that "succeeded" turns out +to never work. With no brew on the machine the install is refused with a pointer to +brew.sh, and `can_install` is reported false, so no card offers the button. + +`detect` checks `~/.mtplx/bin/mtplx`, the MTPLX app's own runtime venv, +`/opt/homebrew/bin/mtplx` and `~/.local/bin/mtplx` in that order and the first one +found is launched, and every `{cli}` action runs that same binary rather than the +manifest's `cli` path — a Homebrew or app-venv `mtplx` found there is the one this +machine has. `/Applications/MTPLX.app` is declared under `conflicts`, so a brew +install is refused while the desktop app is installed, and the card shows no Install +button: the two share `~/.mtplx/models`, and a second copy beside it is a second set +of files in the user's model library that PAIR could not take back out. + +Either way there is nothing for `engine:uninstall` to remove. A `pkg` install +records no PAIR ownership marker, and an explicit uninstall of a `pkg` platform is +refused as "it was installed through Homebrew, which owns where it lives", naming +`brew uninstall youssofal/mtplx/mtplx`; "reset all data" skips it for the same +reason. The engine, and the pack cache the user filled, stay exactly where they +were. `mtplx serve` runs in the foreground as one process, binding loopback `8101` while the proxy facade owns `8100`. Port `8000` is deliberately not reused for it: that diff --git a/services/nvpair-engine-manager/actioncli_test.go b/services/nvpair-engine-manager/actioncli_test.go new file mode 100644 index 000000000..af78701fd --- /dev/null +++ b/services/nvpair-engine-manager/actioncli_test.go @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +// {cli} names the engine's own command line tool, and a manifest can only write +// that path as a guess: where the tool ends up depends on how the engine reached +// the machine. MTPLX's manifest names ~/.mtplx/bin/mtplx, which is where the +// vendor's own installer puts it, while a Homebrew install puts it in Homebrew's +// bin directory and a downloaded app keeps it inside the app bundle. So the +// placeholder follows what the last detect actually found, and the manifest's +// literal is the fallback for a manifest that declares no detect paths and so has +// nothing to have found. +// +// These tests stand the tool up as a shell script that answers with the file that +// ran, so a failure names the path that was chosen rather than only saying that +// something went wrong. + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// writeEngineCLI puts an executable stand-in engine tool at dir/name. It answers +// with the label it was given and the arguments it received, which is how the +// test below reads which command ran. +func writeEngineCLI(t *testing.T, dir, name, label string) string { + t.Helper() + skipWithoutShell(t) + path := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(dir, 0o755)) + body := "#!/bin/sh\nprintf '{\"ran\":\"" + label + "\",\"args\":\"%s\"}' \"$*\"\n" + require.NoError(t, os.WriteFile(path, []byte(body), 0o755)) + return path +} + +// cliActionManifest describes an engine whose only action is a CLI call, with the +// tool found at `detected` (empty for none) and the manifest naming `literal`. +func cliActionManifest(engine, detected, literal string) *Manifest { + platform := Platform{ + Runtime: Runtime{CLI: literal}, + } + if detected != "" { + platform.Detect = []string{detected} + } + return &Manifest{ + Engine: engine, + DisplayName: "CLI Fixture", + ManifestVersion: 1, + Platforms: map[string]Platform{hostKey(): platform}, + Actions: map[string]Action{"probe": {Cmd: []string{"{cli}", "models", "--json"}}}, + } +} + +// TestAction_CliPlaceholderRunsTheCommandThatWasFound is the Homebrew case: the +// engine is installed, its command is in the package manager's bin directory, and +// the manifest's literal names a place that was never filled. +func TestAction_CliPlaceholderRunsTheCommandThatWasFound(t *testing.T) { + root := t.TempDir() + detected := writeEngineCLI(t, filepath.Join(root, "homebrew", "bin"), "mtplx", "found") + literal := filepath.Join(root, "mtplx-home", "bin", "mtplx") + + executor := newTestExecutor(t, cliActionManifest("cli-found", detected, literal)) + installed, err := executor.Detect("cli-found") + require.NoError(t, err) + require.True(t, installed, "the fixture engine should read as installed") + + result, err := executor.Action(context.Background(), "cli-found", "probe", nil) + + require.NoError(t, err, "the action had a working engine command to run") + assert.Contains(t, string(result), `"ran":"found"`, "the action ran the wrong command: %s", result) + assert.Contains(t, string(result), "models --json", "the action lost its own arguments: %s", result) +} + +// TestAction_CliPlaceholderFallsBackToTheManifestLiteral is the LM Studio case, +// which declares no detect paths at all: with nothing observed, the path the +// manifest names is the only one there can be, and the engine's actions have to +// still run. +func TestAction_CliPlaceholderFallsBackToTheManifestLiteral(t *testing.T) { + root := t.TempDir() + literal := writeEngineCLI(t, filepath.Join(root, "bin"), "lms", "literal") + + executor := newTestExecutor(t, cliActionManifest("cli-literal", "", literal)) + + result, err := executor.Action(context.Background(), "cli-literal", "probe", nil) + + require.NoError(t, err, "a manifest that names its CLI can still run it") + assert.Contains(t, string(result), `"ran":"literal"`, "the action ran the wrong command: %s", result) +} + +// TestAction_CliPlaceholderCannotBeSuppliedByTheCaller keeps the new resolution +// on the same side of the line as the old one: {cli} is runner-owned, so a params +// key of that name is dropped rather than becoming argv[0]. +func TestAction_CliPlaceholderCannotBeSuppliedByTheCaller(t *testing.T) { + root := t.TempDir() + detected := writeEngineCLI(t, filepath.Join(root, "bin"), "mtplx", "found") + + executor := newTestExecutor(t, cliActionManifest("cli-caller", detected, "")) + installed, err := executor.Detect("cli-caller") + require.NoError(t, err) + require.True(t, installed) + + result, err := executor.Action(context.Background(), "cli-caller", "probe", + json.RawMessage(`{"cli":"/bin/sh","model":"qwen"}`)) + + require.NoError(t, err) + assert.Contains(t, string(result), `"ran":"found"`, "a caller param reached argv[0]: %s", result) + assert.NotContains(t, string(result), "literal", "a caller param replaced the engine command: %s", result) +} diff --git a/services/nvpair-engine-manager/actions.go b/services/nvpair-engine-manager/actions.go index 8c67a01c1..1eef34bfa 100644 --- a/services/nvpair-engine-manager/actions.go +++ b/services/nvpair-engine-manager/actions.go @@ -259,8 +259,9 @@ func (e *Executor) runCmdAction(ctx context.Context, st *engineState, act Action // A caller param can never override a runner-owned placeholder // ({bin},{cli},{port},{download},{install_dir}): those keys are dropped // from params, then seeded from trusted values — so a malicious param - // can't hijack argv[0]. Param values are also not env-expanded (only - // the manifest-authored {cli} value is). + // can't hijack argv[0]. Param values are also not env-expanded (only the + // manifest-authored {cli} value is, and that is either a detect path or the + // manifest's CLI literal, expanded exactly once). vars := map[string]string{} if len(params) > 0 { var pm map[string]any @@ -275,8 +276,8 @@ func (e *Executor) runCmdAction(ctx context.Context, st *engineState, act Action } vars["port"] = strconv.Itoa(port) maps.Copy(vars, st.pathVars()) - if cli := st.plat.Runtime.CLI; cli != "" { - vars["cli"] = expandPath(cli) + if cli := observedEngineCLI(st); cli != "" { + vars["cli"] = cli } // Most cmd actions run once with the params as given. An action that diff --git a/services/nvpair-engine-manager/enginecli.go b/services/nvpair-engine-manager/enginecli.go new file mode 100644 index 000000000..2730f5dea --- /dev/null +++ b/services/nvpair-engine-manager/enginecli.go @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +// {cli} names the engine's own command line tool, and it is the one placeholder +// whose value depends on how the engine reached the machine. A manifest can only +// write that path as a guess: MTPLX's names the private copy its own installer +// makes, while the same tool arrives in Homebrew's bin directory from a package +// install, inside the downloaded app, or in whatever prefix another user's install +// chose. Resolving it from the manifest literal therefore breaks every route that +// was not the one the manifest imagined, and it breaks the route the manifest did +// imagine as soon as a second one is present and shadows it in the detect list. +// +// So {cli} follows what is actually on disk, exactly as {bin} already does, and +// the literal is the fallback for a manifest that declares no detect paths and so +// has nothing to have found. The three places that run a command and the two that +// display or validate one all resolve it from the same observation, so a custom +// launch string is checked against the command that would really be run. + +// engineCLI resolves {cli} from an observation. `found` is the engine's command as +// it exists on this machine; when nothing was found, the manifest's literal is +// used, which is also how a manifest with no detect paths reaches its tool. +func engineCLI(rt Runtime, found string) string { + if found != "" { + return found + } + if rt.CLI == "" { + return "" + } + return expandPath(rt.CLI) +} + +// observedEngineCLI answers {cli} for one operation, from the engine's detect +// paths. It re-reads them instead of taking the engine's cached binary because +// that may have been filled by a port probe with the executable of whatever was +// found serving the engine's port. {cli} is a command this service runs as itself, +// so it has to be the engine's own tool, from a path the manifest lists. +func observedEngineCLI(st *engineState) string { + _, found := detectPath(st) + return engineCLI(st.plat.Runtime, found) +} diff --git a/services/nvpair-engine-manager/executor.go b/services/nvpair-engine-manager/executor.go index 0e6b3088a..e0b814a6f 100644 --- a/services/nvpair-engine-manager/executor.go +++ b/services/nvpair-engine-manager/executor.go @@ -47,6 +47,18 @@ type EngineStatus struct { AwaitingModel bool `json:"awaiting_model,omitempty"` Healthy bool `json:"healthy"` Port int `json:"port,omitempty"` + // CanInstall reports that this machine has a way for NVPAIR to obtain the + // engine, for an engine that is not already here: the platform declares an + // install, anything it needs is present, and no copy of the engine sits in a + // folder the platform named as already having it. The engine card's Install + // button comes from this, so a card never offers an install this service + // would refuse. See installfacts.go. + CanInstall bool `json:"can_install,omitempty"` + // Owner names whose copy of the engine is here: "pair" for an NVPAIR-managed + // install, a package manager's name for its install, "other" for a copy that + // was merely found, and "" when nothing is. Uninstall is offered only for + // "pair", because it is refused for anything else. See installfacts.go. + Owner string `json:"owner,omitempty"` } // engineState is the per-engine runtime state. diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index 1bc962540..5b3d3f123 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -21,8 +21,9 @@ import ( "time" ) -// Install obtains the engine in user mode: download (checksum-verified) -// then run the declared command. No-op if already detected. +// Install obtains the engine in user mode: download (checksum-verified) then run +// the declared command, or ask a package manager the machine already has to do +// both. No-op if already detected. func (e *Executor) Install(ctx context.Context, engine string) error { st, err := e.state(engine) if err != nil { @@ -57,11 +58,32 @@ func (e *Executor) Install(ctx context.Context, engine string) error { if inst == nil { return fmt.Errorf("engine %q has no install block for this platform", engine) } + if here := conflictingEnginePath(st); here != "" { + // The engine is on this machine, just not somewhere PAIR can run from. + // Installing a second copy would give it a second set of files beside the + // model library it already shares with the first, and PAIR could not take + // the extra copy back out. + err := fmt.Errorf("%s is already installed at %s. PAIR will not install a second copy: run it from there, or remove that copy and install again.", + st.manifest.DisplayName, here) + e.reportInstallFailed(engine, err) + return err + } if inst.ModeOrDefault() == "admin" { err := fmt.Errorf("engine %q declares an admin install, which is refused (engine-manager is user-mode only)", engine) e.reportInstallFailed(engine, err) return err } + if inst.Pkg != nil { + // A package-mode install needs no PAIR install directory: the package + // manager decides where its files go, so PAIR neither owns them nor + // claims to, which is why this path closes the install unclaimed. + err := e.installWithPackageManager(ctx, engine, st.manifest.DisplayName, inst.Pkg) + if err != nil { + e.reportInstallFailed(engine, err) + return err + } + return e.completeInstall(st, engine, false) + } if err := os.MkdirAll(st.installDir, 0o755); err != nil { return fmt.Errorf("create install dir: %w", err) } @@ -126,15 +148,26 @@ func (e *Executor) Install(ctx context.Context, engine string) error { } } + return e.completeInstall(st, engine, true) +} + +// completeInstall closes out an install this service performed. The engine has to +// be detectable, otherwise nothing was installed, and PAIR records ownership +// only of installs it put into its own directory: a package manager's files are +// not PAIR's to remove, and a claim here would let a later reset delete them. +func (e *Executor) completeInstall(st *engineState, engine string, claim bool) error { if !e.waitDetect(engine, true, e.detectTimeout) { err := fmt.Errorf("engine %q was not detected after install", engine) e.reportInstallFailed(engine, err) return err } - // Claim the install now that it is real and detected. A failure to record it - // only costs the ability to uninstall later, so it must not fail the install. - if err := writeInstallMarker(st.installDir, engine); err != nil { - slog.Warn("could not record that PAIR installed this engine; uninstall will decline it", "engine", engine, "err", err) + if claim { + // Claim the install now that it is real and detected. A failure to record + // it only costs the ability to uninstall later, so it must not fail the + // install. + if err := writeInstallMarker(st.installDir, engine); err != nil { + slog.Warn("could not record that PAIR installed this engine; uninstall will decline it", "engine", engine, "err", err) + } } e.reporter.clear(installFailedID(engine)) e.emitInstallProgress(engine, "done", 100) @@ -162,6 +195,16 @@ func (e *Executor) Uninstall(ctx context.Context, engine string) error { e.emitState(engine) return e.setDesiredEnabled(engine, false) } + if pkg := st.plat.pkgInstall(); pkg != nil { + // Nothing here can be uninstalled, because nothing here was installed: + // the package manager put its own files in its own tree. Running the + // manifest's removal list against that tree would take the model library + // sitting beside it, and there is no ownership claim to check either — a + // package-mode install never writes one. + err := errors.New(packageManagerOwnershipRefusal(engine, pkg)) + e.reporter.report(serviceError{ID: uninstallFailedID(engine), Message: err.Error(), Severity: "error", Action: "none", EngineType: engine, Operation: "uninstall"}) + return err + } un := st.plat.Uninstall if un == nil || (len(un.Run) == 0 && len(un.Remove) == 0) { return fmt.Errorf("engine %q has no uninstall defined for this platform", engine) diff --git a/services/nvpair-engine-manager/install_pkg_test.go b/services/nvpair-engine-manager/install_pkg_test.go new file mode 100644 index 000000000..1df71bd00 --- /dev/null +++ b/services/nvpair-engine-manager/install_pkg_test.go @@ -0,0 +1,455 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +// A package-manager install has no artifact for PAIR to download and no +// checksum to verify: Homebrew fetches its own formula, its Python, and the MLX +// stack, and the only evidence of a good install is that the installed command +// then runs. These tests stand Homebrew up as a shell script in a throwaway +// prefix, so the whole flow travels through a real command with no real package +// manager. Every test replaces pkgManagerPrefixes rather than adding to it, so +// one can never reach the Homebrew installed on the machine running the tests. + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testMtplxTap = "youssofal/mtplx" + testMtplxFormula = "mtplx" +) + +// brewRecordArgs logs one transcript line per call, holding the arguments brew +// was given. $TRANSCRIPT is set by the test and reaches the script because the +// runner passes the parent environment through. +const brewRecordArgs = `printf 'brew %s\n' "$*" >> "$TRANSCRIPT"` + +// brewRecordArgsAndEnv also logs the Homebrew settings it was handed and +// whether it had a terminal, which is how the test below reads what the runner +// set up rather than trusting that it did. +const brewRecordArgsAndEnv = `printf 'brew %s | %s | tty=%s\n' "$*" "$(env | grep '^HOMEBREW' | sort | tr '\n' ' ')" "$([ -t 0 ] && echo yes || echo no)" >> "$TRANSCRIPT"` + +// brewLeavesWorkingMtplx is the fake's answer to a finished install: it puts an +// `mtplx` command in the same bin directory, and that command logs its own +// arguments, so a test can see whether the runner ran it afterwards. This is +// what Homebrew's own post_install step produces. +const brewLeavesWorkingMtplx = `if [ "$1" = install ]; then + bindir=$(dirname "$0") + printf '%s\n' '#!/bin/sh' 'echo "mtplx $*" >> "$TRANSCRIPT"' > "$bindir/mtplx" + chmod +x "$bindir/mtplx" +fi +exit 0` + +// brewLeavesRuntimeToFirstLaunch is the other answer a real Homebrew can give: +// it reports success while leaving an `mtplx` that still has to download its +// Python stack, which fails here because the fixture has no network. The +// launcher's deferred bootstrap and this are the same shape to PAIR — exit 0 +// from brew, a command that cannot run yet. +const brewLeavesRuntimeToFirstLaunch = `if [ "$1" = install ]; then + bindir=$(dirname "$0") + printf '%s\n' '#!/bin/sh' 'echo "MTPLX runtime is not installed. Bootstrapping with pip..."' 'echo "ERROR: Could not find a version that satisfies the requirement mlx==0.32.2"' 'exit 1' > "$bindir/mtplx" + chmod +x "$bindir/mtplx" +fi +exit 0` + +// skipWithoutShell skips a test whose stand-ins are shell scripts: Windows CI +// has no /bin/sh to run them with, and no Homebrew to stand in for. +func skipWithoutShell(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the stand-in package manager and engine commands are shell scripts") + } +} + +// writeFakeBrew puts a stand-in brew at /bin/brew. body is the whole +// script body; it runs with no arguments of its own beyond what the runner +// passes, exactly as the real command would. +func writeFakeBrew(t *testing.T, prefix, body string) { + t.Helper() + skipWithoutShell(t) + path := filepath.Join(prefix, "bin", "brew") + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte("#!/bin/sh\n"+body+"\n"), 0o755)) +} + +// useFakeHomebrew restricts the package-manager search to the throwaway prefix. +func useFakeHomebrew(t *testing.T, prefix string) { + t.Helper() + skipWithoutShell(t) + original := pkgManagerPrefixes + pkgManagerPrefixes = []string{prefix} + t.Cleanup(func() { pkgManagerPrefixes = original }) +} + +// mtplxLikeManifest describes an engine whose only install path is Homebrew: +// nothing is detected until the install puts the command in the fixture prefix, +// and the manifest's own CLI literal names a different place entirely, as the +// real MTPLX manifest does. +func mtplxLikeManifest(t *testing.T, engine, prefix string) *Manifest { + t.Helper() + manifest := testEngineManifest(fakeEngineBin) + manifest.Engine = engine + manifest.DisplayName = "MTPLX-like" + platform := manifest.Platforms[hostKey()] + platform.Detect = []string{filepath.Join(prefix, "bin", testMtplxFormula)} + platform.Install = &Install{Pkg: &PkgInstall{ + Manager: "homebrew", + Tap: testMtplxTap, + Formula: testMtplxFormula, + }} + manifest.Platforms[hostKey()] = platform + require.NoError(t, manifest.Validate(), "validate the package-install fixture") + return manifest +} + +func readTranscript(t *testing.T, path string) []string { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err, "nothing was recorded, so nothing ran") + lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n") + for i := range lines { + lines[i] = strings.TrimSpace(lines[i]) + } + return lines +} + +func brewCalls(lines []string) []string { + var calls []string + for _, line := range lines { + if strings.HasPrefix(line, "brew ") { + calls = append(calls, line) + } + } + return calls +} + +// TestInstall_PackageModeRunsTapThenTrustThenInstallThenProvesTheCommand is the +// shape of a Homebrew install: the tap has to exist, the formula has to be +// trusted, only then can it install, and PAIR checks the installed command +// answers instead of reading brew's exit code as proof. +func TestInstall_PackageModeRunsTapThenTrustThenInstallThenProvesTheCommand(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+"\n"+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-fixture", prefix)) + progress := &installProgressRecorder{} + executor.emit = progress.emit + + require.NoError(t, executor.Install(context.Background(), "mtplx-fixture"), "package-mode install") + progress.assertSingleTerminal(t, "done") + + assert.Equal(t, []string{ + "brew tap youssofal/mtplx", + "brew trust --formula youssofal/mtplx/mtplx", + "brew install youssofal/mtplx/mtplx", + "mtplx --version", + }, readTranscript(t, transcript), "the commands the install ran, in order") +} + +// TestInstall_PackageModeGivesBrewNoAutoUpdateAndNoTerminal keeps a brew +// auto-update from spending the install's 30-minute budget on other formulas, +// and keeps a command that wants a password or a confirmation from waiting on a +// terminal nobody is watching. +func TestInstall_PackageModeGivesBrewNoAutoUpdateAndNoTerminal(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgsAndEnv+"\n"+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-env", prefix)) + + require.NoError(t, executor.Install(context.Background(), "mtplx-env"), "package-mode install") + + calls := brewCalls(readTranscript(t, transcript)) + require.Len(t, calls, 3, "recorded Homebrew calls: %v", readTranscript(t, transcript)) + for _, call := range calls { + assert.Contains(t, call, "HOMEBREW_NO_AUTO_UPDATE=1", "auto-update stayed on for %q", call) + assert.Contains(t, call, "HOMEBREW_NO_ENV_HINTS=1", "environment hints stayed on for %q", call) + assert.Contains(t, call, "tty=no", "brew was given a terminal it might wait on: %q", call) + } +} + +// TestInstall_PackageMode_ReportsMissingPackageManager is the reason a package +// mode exists rather than a one-line script: without a package manager there is +// nothing to run, and the user needs to be told that, not handed a shell error. +func TestInstall_PackageMode_ReportsMissingPackageManager(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + useFakeHomebrew(t, filepath.Join(prefix, "empty")) + t.Setenv("PATH", t.TempDir()) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-nobrew", prefix)) + progress := &installProgressRecorder{} + executor.emit = progress.emit + + err := executor.Install(context.Background(), "mtplx-nobrew") + + require.Error(t, err, "an install with no package manager must not report success") + assert.Contains(t, err.Error(), "Homebrew", "the error should name what is missing: %v", err) + assert.Contains(t, err.Error(), "https://brew.sh", "the error should point at the fix: %v", err) + assert.NotContains(t, err.Error(), "no such file or directory", "the user should not be handed a shell error: %v", err) + progress.assertSingleTerminal(t, "failed") + _, statErr := os.Stat(filepath.Join(prefix, "bin", testMtplxFormula)) + assert.ErrorIs(t, statErr, os.ErrNotExist, "nothing should have been installed") +} + +// TestInstall_PackageMode_FailsWhenTheInstalledCommandCannotRun covers the +// deferred-runtime case: brew finishes, so a runner that trusts exit 0 declares +// victory, and the same minutes of downloading then fail inside a 600-second +// Start instead. The real reason also has to reach the user. +func TestInstall_PackageMode_FailsWhenTheInstalledCommandCannotRun(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+"\n"+brewLeavesRuntimeToFirstLaunch) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-deferred", prefix)) + progress := &installProgressRecorder{} + executor.emit = progress.emit + + err := executor.Install(context.Background(), "mtplx-deferred") + + require.Error(t, err, "a command that cannot run is not an installed engine") + assert.Contains(t, err.Error(), "Could not find a version that satisfies the requirement mlx==0.32.2", + "the installer's own reason must reach the user: %v", err) + progress.assertSingleTerminal(t, "failed") + assert.False(t, installedByPAIR(filepath.Join(executor.baseDir, "mtplx-deferred")), + "a Homebrew install is not PAIR's to remove") +} + +// TestInstall_PackageMode_ContinuesWhenBrewHasNoTrustCommand: a Homebrew older +// than the trust gate has no trust subcommand at all, and its formulae load +// without one. Failing there would refuse a Mac that needs nothing. +func TestInstall_PackageMode_ContinuesWhenBrewHasNoTrustCommand(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+` +if [ "$1" = trust ]; then + echo "Error: Unknown command: trust" + exit 1 +fi +`+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-oldbrew", prefix)) + + require.NoError(t, executor.Install(context.Background(), "mtplx-oldbrew"), + "a missing trust command means no trust is needed, not a failed install") + + assert.Equal(t, []string{ + "brew tap youssofal/mtplx", + "brew trust --formula youssofal/mtplx/mtplx", + "brew install youssofal/mtplx/mtplx", + "mtplx --version", + }, readTranscript(t, transcript), "the refused trust step must not stop the install") +} + +// TestInstall_PackageMode_ReportsBrewRefusalOnAnUntrustedTap is the other half +// of tolerating the trust step: when the grant does not take, brew still refuses +// to install, and that refusal is the message the user needs. +func TestInstall_PackageMode_ReportsBrewRefusalOnAnUntrustedTap(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+` +if [ "$1" = install ]; then + echo "Error: Refusing to load formula youssofal/mtplx/mtplx from untrusted tap youssofal/mtplx" + exit 1 +fi +exit 0`) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-refused", prefix)) + progress := &installProgressRecorder{} + executor.emit = progress.emit + + err := executor.Install(context.Background(), "mtplx-refused") + + require.Error(t, err, "a refused formula is not an installed engine") + assert.Contains(t, err.Error(), "Refusing to load formula", "brew's own reason must be reported: %v", err) + progress.assertSingleTerminal(t, "failed") +} + +// TestInstall_PackageMode_LeavesTheInstallOwnedByHomebrew: the installed engine +// lives in Homebrew's tree, so PAIR neither records ownership nor offers to +// remove it. A marker here would let a later reset delete files PAIR does not +// own, next to the model library that lives beside them. +func TestInstall_PackageMode_LeavesTheInstallOwnedByHomebrew(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+"\n"+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-owned", prefix)) + require.NoError(t, executor.Install(context.Background(), "mtplx-owned"), "package-mode install") + installDir := filepath.Join(executor.baseDir, "mtplx-owned") + require.True(t, fileExists(filepath.Join(prefix, "bin", testMtplxFormula)), "the engine should still be installed") + + assert.False(t, installedByPAIR(installDir), "PAIR claimed ownership of a Homebrew-owned install") + + err := executor.Uninstall(context.Background(), "mtplx-owned") + require.ErrorContains(t, err, "installed through Homebrew", "PAIR must not remove what Homebrew owns") + require.ErrorContains(t, err, "brew uninstall youssofal/mtplx/mtplx", + "the refusal has to leave the user a way to do it: %v", err) + _, statErr := os.Stat(filepath.Join(prefix, "bin", testMtplxFormula)) + assert.NoError(t, statErr, "the engine survived an uninstall PAIR refused") +} + +// TestManifestValidate_PackageModeDeclinesUninstall keeps the refusal at load +// rather than at the click: a manifest that names removal paths for a +// package-managed engine would point them at Homebrew's own tree, which is where +// the engine's shared model library lives too. +func TestManifestValidate_PackageModeDeclinesUninstall(t *testing.T) { + prefix := t.TempDir() + manifest := mtplxLikeManifest(t, "pkg-uninstall", prefix) + platform := manifest.Platforms[hostKey()] + platform.Uninstall = &Uninstall{Remove: []string{filepath.Join(prefix, "bin")}} + manifest.Platforms[hostKey()] = platform + + err := manifest.Validate() + + require.ErrorContains(t, err, "uninstall is not allowed with install.pkg") +} + +func TestManifestValidate_RejectsUnusablePackageInstall(t *testing.T) { + prefix := t.TempDir() + newManifest := func(pkg *PkgInstall, mutate func(*Install)) *Manifest { + manifest := mtplxLikeManifest(t, "pkg-fixture", prefix) + platform := manifest.Platforms[hostKey()] + platform.Install = &Install{Pkg: pkg} + if mutate != nil { + mutate(platform.Install) + } + manifest.Platforms[hostKey()] = platform + return manifest + } + usable := &PkgInstall{Manager: "homebrew", Tap: testMtplxTap, Formula: testMtplxFormula} + + require.NoError(t, newManifest(usable, nil).Validate(), "the declared package install should be accepted") + + for _, reject := range []struct { + name string + pkg *PkgInstall + mutate func(*Install) + wantText string + }{ + {name: "unknown manager", pkg: &PkgInstall{Manager: "apt", Formula: "mtplx"}, wantText: `unknown install package manager "apt"`}, + {name: "missing formula", pkg: &PkgInstall{Manager: "homebrew", Tap: testMtplxTap}, wantText: "install.pkg.formula"}, + {name: "malformed tap", pkg: &PkgInstall{Manager: "homebrew", Tap: "youssofal", Formula: "mtplx"}, wantText: "install.pkg.tap"}, + {name: "with a fetch", pkg: usable, mutate: func(i *Install) { + i.Fetch = &Fetch{URL: "https://example.com/mtplx.tar.gz", SHA256: strings.Repeat("a", 64)} + }, wantText: "mutually exclusive"}, + {name: "with a run command", pkg: usable, mutate: func(i *Install) { + i.Run = []string{"/bin/sh", "-c", "brew install mtplx"} + }, wantText: "mutually exclusive"}, + } { + t.Run(reject.name, func(t *testing.T) { + err := newManifest(reject.pkg, reject.mutate).Validate() + assert.ErrorContains(t, err, reject.wantText) + }) + } +} + +// TestInstall_PackageMode_LeavesTheVendorsOwnCopyAlone is the reason a conflict +// path is not just another detect path: the application bundle is MTPLX, but it is +// not a command PAIR can run, so the engine reads as not installed and the card +// offers an install. Running Homebrew there would put a second MTPLX beside the +// first, in a tree PAIR cannot clean up, sharing the model library the first one +// already uses. +func TestInstall_PackageMode_LeavesTheVendorsOwnCopyAlone(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+"\n"+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + app := filepath.Join(t.TempDir(), "Applications", "MTPLX.app") + require.NoError(t, os.MkdirAll(app, 0o755)) + + manifest := mtplxLikeManifest(t, "mtplx-gui", prefix) + platform := manifest.Platforms[hostKey()] + platform.Conflicts = []string{app} + manifest.Platforms[hostKey()] = platform + + executor := newTestExecutor(t, manifest) + progress := &installProgressRecorder{} + executor.emit = progress.emit + + err := executor.Install(context.Background(), "mtplx-gui") + + require.Error(t, err, "a second copy beside the user's own MTPLX is not an install") + assert.Contains(t, err.Error(), app, "the refusal has to name what it found: %v", err) + progress.assertSingleTerminal(t, "failed") + assert.Empty(t, brewCalls(readTranscript(t, transcript)), "Homebrew ran beside the user's own copy") + _, statErr := os.Stat(filepath.Join(prefix, "bin", testMtplxFormula)) + assert.ErrorIs(t, statErr, os.ErrNotExist, "nothing should have been installed") +} + +// TestManifestValidate_RejectsUnusableConflictPaths keeps a conflict list that +// cannot mean anything out of a shipped manifest. A blank path matches nothing, and +// a path already in detect makes the engine read as installed — where no install is +// offered — so neither entry could ever do the one job a conflict is for. +func TestManifestValidate_RejectsUnusableConflictPaths(t *testing.T) { + prefix := t.TempDir() + detected := filepath.Join(prefix, "bin", testMtplxFormula) + for _, reject := range []struct{ name, conflict, wantText string }{ + {name: "already a detect path", conflict: detected, wantText: "which detect already answers for"}, + {name: "blank", conflict: " ", wantText: "blank path"}, + } { + t.Run(reject.name, func(t *testing.T) { + manifest := mtplxLikeManifest(t, "pkg-conflict", prefix) + platform := manifest.Platforms[hostKey()] + platform.Conflicts = []string{reject.conflict} + manifest.Platforms[hostKey()] = platform + + assert.ErrorContains(t, manifest.Validate(), reject.wantText) + }) + } +} + +// TestMtplxManifest_InstallsThroughHomebrewOnAppleSilicon pins the shipped +// manifest: the vendor's own non-GUI channel, the trust grant that Homebrew 7 +// requires first, the app bundle that means MTPLX is already here, and a start +// that waits for a model because a freshly installed MTPLX has none. +func TestMtplxManifest_InstallsThroughHomebrewOnAppleSilicon(t *testing.T) { + registry := loadWithOverrides(t, t.TempDir()) + manifest, ok := registry.Get("mtplx") + require.True(t, ok, "mtplx manifest not loaded") + platform, ok := manifest.Platforms["darwin/arm64"] + require.True(t, ok, "mtplx manifest has no darwin/arm64 platform") + + require.NotNil(t, platform.Install, "mtplx should declare an install for Apple Silicon Macs") + assert.Equal(t, &PkgInstall{Manager: "homebrew", Tap: "youssofal/mtplx", Formula: "mtplx"}, platform.Install.Pkg) + assert.True(t, platform.Runtime.WaitForModel, + "a new MTPLX install has no model, so a start must not fail for that reason") + assert.Equal(t, []string{"/Applications/MTPLX.app"}, platform.Conflicts, + "a downloaded MTPLX should stop PAIR installing a second one") + // The app bundle is a folder, not a command: it has to stay out of detect, + // whose first hit becomes the binary PAIR launches and owns. + assert.NotContains(t, platform.Detect, "/Applications/MTPLX.app") +} diff --git a/services/nvpair-engine-manager/installfacts.go b/services/nvpair-engine-manager/installfacts.go new file mode 100644 index 000000000..340cb0d58 --- /dev/null +++ b/services/nvpair-engine-manager/installfacts.go @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "path/filepath" + "strings" +) + +// Install facts: what this service is able to do about an engine on this machine, +// reported with its state. +// +// The engine card offers an Install button, an Uninstall button, or neither, and +// each of those is only worth offering when it can actually succeed. A button that +// can only produce a refusal is worse than no button, because by the time it is +// clicked the user has already decided what they want. Neither answer is something +// the interface can work out: whether a platform has a way to obtain an engine, and +// who owns the copy that is already here, both live in the manifest and in the +// filesystem. So they are computed here, beside the code that would have performed +// the two operations, and travels with the state. +// +// Both answers are deliberately recomputed from the filesystem rather than cached. +// They are read a few times per engine per status check, which is the same handful +// of stat calls that detecting the engine already costs. + +// The owners `installOwner` reports. "pair" is an install this service put where +// it can remove it again; "other" is a copy it merely found, whatever made it. +// Anything else is a named package manager, which is also how its own removal +// command is spelled. +const ( + installOwnerPAIR = "pair" + installOwnerOther = "other" +) + +// installOwner says whose copy of the engine is on this machine, and "" when +// nothing is. It answers the same question Uninstall asks before it removes +// anything — is this ours to remove? — so the interface that reads this field hides +// exactly the buttons that would refuse. +// +// An engine found only by its port has no path to inspect and is reported as +// "other": whatever is answering there, PAIR did not install it, and it cannot be +// taken back out either way. +func installOwner(st *engineState) string { + if !st.installed || st.plat == nil { + return "" + } + binPath := st.binPath + if binPath == "" { + return installOwnerOther + } + if isManagedInstallPath(binPath, st.installDir) { + return installOwnerPAIR + } + if manager := packageManagerOwning(st, binPath); manager != "" { + return manager + } + if st.plat.Runtime.modeOrDefault() == "command" && installedByPAIR(st.installDir) { + // A command-mode engine picks its own destination, so the directory check + // above cannot vouch for one and the install marker is the only record. + return installOwnerPAIR + } + return installOwnerOther +} + +// canInstallHere reports whether there is an install this service could carry out +// for an engine that is not here: a platform that declares one, a package manager +// to do the work if it needs one, and no copy of the engine already sitting in a +// folder it named. +func canInstallHere(st *engineState) bool { + if st.installed || st.plat == nil { + return false + } + install := st.plat.Install + if install == nil || install.ModeOrDefault() == "admin" { + // No declared way in, or a way this user-mode service refuses. + return false + } + if conflictingEnginePath(st) != "" { + // The engine is already here by a route PAIR does not own, and a second + // copy beside it is not an improvement. + return false + } + if pkg := st.plat.pkgInstall(); pkg != nil { + kind, known := packageManagerKinds[pkg.Manager] + if !known { + return false + } + // A package mode with no package manager is not an install; it is a + // message about a missing command. Offer nothing instead. + return findPackageManagerBinary(kind) != "" + } + return len(install.Script) > 0 || install.Fetch != nil || + len(install.Artifacts) > 0 || len(install.Run) > 0 +} + +// packageManagerOwning names the package manager whose tree a detected engine +// binary sits in, or "" when no known manager owns that path. A package manager +// installs into its own prefix and nowhere else, so the prefix is what its +// ownership looks like on disk. +func packageManagerOwning(st *engineState, binPath string) string { + pkg := st.plat.pkgInstall() + if pkg == nil { + return "" + } + kind, known := packageManagerKinds[pkg.Manager] + if !known { + return "" + } + clean := filepath.Clean(binPath) + for _, prefix := range pkgManagerPrefixes { + rel, err := filepath.Rel(prefix, clean) + if err != nil { + continue + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + continue + } + return kind.label + } + return "" +} diff --git a/services/nvpair-engine-manager/installfacts_test.go b/services/nvpair-engine-manager/installfacts_test.go new file mode 100644 index 000000000..dfd8af67e --- /dev/null +++ b/services/nvpair-engine-manager/installfacts_test.go @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +// The engine card decides what to offer from two facts this service reports: where +// the copy that is already here came from, and whether there is any way to obtain +// one where there is nothing. Both are answers about the machine, not about the +// interface, so these tests stand the machine up: a throwaway package-manager +// prefix holding a shell-script `brew`, a fake application bundle, and engine +// binaries placed in the two places that matter — inside NVPAIR's own install +// directory, and outside it. + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newEngineState builds the state the install facts read. The platform is copied, +// so a table of cases never shares one through the back door. +func newEngineState(t *testing.T, installed bool, binPath, installDir, mode string, plat *Platform) *engineState { + t.Helper() + platform := *plat + platform.Runtime.Mode = mode + return &engineState{ + installed: installed, + binPath: binPath, + installDir: installDir, + plat: &platform, + } +} + +// homebrewPlatform is a platform whose only way in is Homebrew, and whose formula +// would land under the prefix the test names. +func homebrewPlatform() *Platform { + plat := &Platform{} + plat.Install = &Install{Pkg: &PkgInstall{Manager: "homebrew", Formula: testMtplxFormula}} + return plat +} + +// downloadPlatform is a platform PAIR installs itself: it downloads a verified +// archive and unpacks it into its own install directory. +func downloadPlatform() *Platform { + plat := &Platform{} + plat.Install = &Install{Fetch: &Fetch{URL: "https://example.invalid/thing.tar.gz"}} + return plat +} + +func TestInstallOwner_NamesWhoOwnsTheCopyThatIsHere(t *testing.T) { + // Each case gets its own install directory: the install marker that makes an + // engine PAIR's own is a file, and one case writing it would otherwise be + // the next case's answer. + brewPrefix := t.TempDir() + home := t.TempDir() + managedDir := filepath.Join(home, "managed") + unmanagedDir := filepath.Join(home, "elsewhere") + commandOwnedDir := filepath.Join(home, "command-owned") + commandPlainDir := filepath.Join(home, "command-plain") + for _, dir := range []string{managedDir, unmanagedDir, commandOwnedDir, commandPlainDir} { + require.NoError(t, os.MkdirAll(dir, 0o755)) + } + + useFakeHomebrew(t, brewPrefix) + + for _, claim := range []struct { + name string + pairMade bool // NVPAIR recorded an install marker in its own directory + state *engineState + wantOwner string + }{ + { + name: "nothing is installed", + state: newEngineState(t, false, "", "", "process", downloadPlatform()), + wantOwner: "", + }, + { + name: "NVPAIR put this copy in its own install directory", + state: newEngineState(t, true, filepath.Join(managedDir, testMtplxFormula), managedDir, "process", downloadPlatform()), + wantOwner: installOwnerPAIR, + }, + { + name: "Homebrew put this copy in its own prefix", + state: newEngineState(t, true, filepath.Join(brewPrefix, "bin", testMtplxFormula), managedDir, "process", homebrewPlatform()), + wantOwner: "Homebrew", + }, + { + name: "the user made this copy themselves, outside any prefix", + state: newEngineState(t, true, filepath.Join(home, ".mtplx", "bin", testMtplxFormula), managedDir, "process", homebrewPlatform()), + wantOwner: installOwnerOther, + }, + { + name: "a command-mode engine NVPAIR installed still carries its marker", + pairMade: true, + state: newEngineState(t, true, filepath.Join(unmanagedDir, testMtplxFormula), commandOwnedDir, "command", downloadPlatform()), + // A command-mode engine picks its own destination, so the marker is + // the only record of who put it there. + wantOwner: installOwnerPAIR, + }, + { + name: "a command-mode engine with no marker was not installed here", + state: newEngineState(t, true, filepath.Join(unmanagedDir, testMtplxFormula), commandPlainDir, "command", downloadPlatform()), + wantOwner: installOwnerOther, + }, + { + name: "only a process answering on the port is here", + state: newEngineState(t, true, "", unmanagedDir, "process", downloadPlatform()), + wantOwner: installOwnerOther, + }, + } { + t.Run(claim.name, func(t *testing.T) { + if claim.pairMade { + require.NoError(t, writeInstallMarker(claim.state.installDir, "mtplx-fixture")) + } + assert.Equal(t, claim.wantOwner, installOwner(claim.state), + "Uninstall is offered only where Uninstall would work") + }) + } +} + +func TestCanInstallHere_OffersOnlyAnInstallThatCouldSucceed(t *testing.T) { + brewPrefix := t.TempDir() + appBundle := filepath.Join(t.TempDir(), "Applications", "MTPLX.app") + require.NoError(t, os.MkdirAll(appBundle, 0o755)) + + useFakeHomebrew(t, brewPrefix) + withBrew := func() *Platform { + writeFakeBrew(t, brewPrefix, brewRecordArgs) + return homebrewPlatform() + } + + for _, claim := range []struct { + name string + state *engineState + want bool + }{ + { + name: "nothing on this platform can install it", + state: newEngineState(t, false, "", "", "process", &Platform{}), + want: false, + }, + { + name: "a verified download PAIR can fetch itself", + state: newEngineState(t, false, "", "", "process", downloadPlatform()), + want: true, + }, + { + name: "Homebrew is here to install the formula", + state: newEngineState(t, false, "", "", "process", withBrew()), + want: true, + }, + { + name: "the engine is already here, in the vendor's own application", + state: newEngineState(t, false, "", "", "process", func() *Platform { + plat := withBrew() + plat.Conflicts = []string{appBundle} + return plat + }()), + want: false, + }, + { + name: "an admin install, which this user-mode service refuses", + state: newEngineState(t, false, "", "", "process", func() *Platform { + plat := downloadPlatform() + plat.Install.Mode = "admin" + return plat + }()), + want: false, + }, + { + name: "the engine is already installed", + state: newEngineState(t, true, "", "", "process", downloadPlatform()), + want: false, + }, + } { + t.Run(claim.name, func(t *testing.T) { + assert.Equal(t, claim.want, canInstallHere(claim.state)) + }) + } +} + +func TestCanInstallHere_RefusesWithoutThePackageManager(t *testing.T) { + brewPrefix := t.TempDir() // a prefix with no brew in it + useFakeHomebrew(t, brewPrefix) + + state := newEngineState(t, false, "", "", "process", homebrewPlatform()) + + assert.False(t, canInstallHere(state), + "an install that can only end in \"this Mac does not have Homebrew\" is not an install") +} + +// TestStatus_ReportsTheInstallFactsForThisMachine walks one engine from nothing +// installed, through a Homebrew install, to a copy the machine owns. It also pins +// the names the desktop reads, because a renamed field reads as a missing one. +func TestStatus_ReportsTheInstallFactsForThisMachine(t *testing.T) { + prefix := t.TempDir() + transcript := filepath.Join(t.TempDir(), "transcript.txt") + require.NoError(t, os.WriteFile(transcript, nil, 0o644)) + t.Setenv("TRANSCRIPT", transcript) + writeFakeBrew(t, prefix, brewRecordArgs+"\n"+brewLeavesWorkingMtplx) + useFakeHomebrew(t, prefix) + + executor := newTestExecutor(t, mtplxLikeManifest(t, "mtplx-fixture", prefix)) + + before, err := executor.Status("mtplx-fixture") + require.NoError(t, err) + assert.False(t, before.Installed) + assert.True(t, before.CanInstall, + "Homebrew is in the fixture prefix, so this engine is installable here") + assert.Empty(t, before.Owner, "nothing is installed, so nobody owns anything yet") + rawBefore, err := json.Marshal(before) + require.NoError(t, err) + assert.Contains(t, string(rawBefore), `"can_install":true`) + + require.NoError(t, executor.Install(context.Background(), "mtplx-fixture")) + + after, err := executor.Status("mtplx-fixture") + require.NoError(t, err) + require.True(t, after.Installed, "the fixture installs into the detected path") + assert.Equal(t, "Homebrew", after.Owner, + "the files are Homebrew's, so PAIR must not offer to remove them") + assert.False(t, after.CanInstall, "it is installed") + rawAfter, err := json.Marshal(after) + require.NoError(t, err) + assert.Contains(t, string(rawAfter), `"owner":"Homebrew"`) +} diff --git a/services/nvpair-engine-manager/lifecycle.go b/services/nvpair-engine-manager/lifecycle.go index d193a4ada..112e38e35 100644 --- a/services/nvpair-engine-manager/lifecycle.go +++ b/services/nvpair-engine-manager/lifecycle.go @@ -246,8 +246,8 @@ func (e *Executor) doStart(ctx context.Context, st *engineState, engine string, vars := st.pathVars() vars["host"] = effectiveBind(rt.Bind, opts.Bind) vars["port"] = strconv.Itoa(port) - if rt.CLI != "" { - vars["cli"] = expandPath(rt.CLI) + if cli := observedEngineCLI(st); cli != "" { + vars["cli"] = cli } // Report the start while it runs, which for vLLM can be minutes of @@ -656,8 +656,8 @@ func (e *Executor) runCommandStop(st *engineState, engine string, rt Runtime, po } vars := st.pathVars() vars["port"] = strconv.Itoa(port) - if rt.CLI != "" { - vars["cli"] = expandPath(rt.CLI) + if cli := observedEngineCLI(st); cli != "" { + vars["cli"] = cli } argv, err := resolveArgs(sp.Cmd, vars) if err != nil { diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index ed73f288d..41cf5e09a 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -12,9 +12,20 @@ "/opt/homebrew/bin/mtplx", "~/.local/bin/mtplx" ], + "conflicts": [ + "/Applications/MTPLX.app" + ], + "install": { + "pkg": { + "manager": "homebrew", + "tap": "youssofal/mtplx", + "formula": "mtplx" + } + }, "runtime": { "bin": "~/.mtplx/bin/mtplx", "cli": "~/.mtplx/bin/mtplx", + "wait_for_model": true, "editable_launch": { "fixed_args": ["serve"], "controls": [ diff --git a/services/nvpair-engine-manager/pkginstall.go b/services/nvpair-engine-manager/pkginstall.go new file mode 100644 index 000000000..8a565432b --- /dev/null +++ b/services/nvpair-engine-manager/pkginstall.go @@ -0,0 +1,276 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "fmt" + "log/slog" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" +) + +// A package-manager install is a different problem from a fetch-and-run install. +// There is no artifact here for PAIR to download and checksum: the package +// manager fetches its own formula, its own Python, and its own dependency +// stack, and it can report success while the engine it installed still cannot +// run. So this file locates the package manager, refuses plainly when the machine +// has none, and only calls an install done once the installed command actually +// answers. +// +// Homebrew installs also stay outside PAIR's ownership: the files land in +// Homebrew's tree, not in a PAIR install directory, so PAIR neither records an +// install marker nor offers an uninstall for them. Removing them means +// `brew uninstall`, which is the user's command to run. + +// pkgManagerPrefixes are the prefixes searched for a package manager, in order. +// PATH is deliberately not consulted: a `brew` found on PATH is not necessarily +// one that can fetch prebuilt packages, and a Finder-launched PAIR may not have +// /opt/homebrew/bin on its PATH at all. It is a var so a test can replace the +// whole list with a fixture prefix and never reach the package manager really +// installed on the machine running the tests. +var pkgManagerPrefixes = []string{"/opt/homebrew", "/usr/local"} + +// pkgNameRe accepts a package name only. A path or URL is the mistake worth +// rejecting at load: the runner passes this value as one argument to the package +// manager, so anything else resolves to a different command than the manifest +// declares. +var pkgNameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$`) + +// pkgTapRe accepts a package repository written "/", which is +// how both a tap and its full formula names are spelled. +var pkgTapRe = regexp.MustCompile(`^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$`) + +// packageManagerKind is one supported package manager: what to call it, where its +// command lives, and what to ask it for. +type packageManagerKind struct { + // label names the manager in the refusal and the log. + label string + // binary is the command's file name under each prefix. + binary string + // docsURL is where someone with no package manager is pointed. + docsURL string + // env is added to every command this manager runs. + env map[string]string + // steps is what an install asks the manager to do, in order, before the + // installed engine is checked. + steps func(pkg *PkgInstall) []pkgStep + // checkArgs runs the installed formula afterwards, from the same bin + // directory the manager put its own command in. + checkArgs []string + // removeCmd is the command that would undo the install. PAIR never runs it; + // it is named to the user, because this is the one case where declining to + // remove something is the right answer and they still need a way to do it. + removeCmd string +} + +// pkgStep is one command in a package-mode install. +type pkgStep struct { + // argv follows the manager binary, so {"tap","x"} runs `brew tap x`. + argv []string + // tolerated means a non-zero exit here does not end the install. Only the + // trust grant is: a package manager older than the trust gate has no trust + // command at all and installs anyway, and where the grant does matter the + // install step then refuses, so nothing is quietly skipped. + tolerated bool +} + +// fullFormulaName is how a package manager addresses the formula. A tap +// qualifies it; a formula from the manager's own repository does not. +func fullFormulaName(pkg *PkgInstall) string { + if pkg.Tap == "" { + return pkg.Formula + } + return pkg.Tap + "/" + pkg.Formula +} + +// homebrewSteps is one Homebrew install. Homebrew 7 will not load a formula from +// a tap the user has not trusted, and a trusted formula is keyed by its full +// name, so the tap has to exist before either later step means anything. +func homebrewSteps(pkg *PkgInstall) []pkgStep { + name := fullFormulaName(pkg) + if pkg.Tap == "" { + return []pkgStep{{argv: []string{"install", name}}} + } + return []pkgStep{ + {argv: []string{"tap", pkg.Tap}}, + {argv: []string{"trust", "--formula", name}, tolerated: true}, + {argv: []string{"install", name}}, + } +} + +var packageManagerKinds = map[string]packageManagerKind{ + "homebrew": { + label: "Homebrew", + binary: "brew", + docsURL: "https://brew.sh", + env: map[string]string{ + // An auto-update would spend the install's budget refreshing every + // other formula on the machine first, and the environment hints brew + // prints are noise nobody reads out of a progress notification. + "HOMEBREW_NO_AUTO_UPDATE": "1", + "HOMEBREW_NO_ENV_HINTS": "1", + }, + steps: homebrewSteps, + checkArgs: []string{"--version"}, + removeCmd: "brew uninstall", + }, +} + +// pkgInstall reports the package mode of a platform, if it has one. Installing +// an engine and removing it both ask the same question, so the answer is taken +// from one place: what installed an engine also says who owns it. +func (p *Platform) pkgInstall() *PkgInstall { + if p == nil || p.Install == nil { + return nil + } + return p.Install.Pkg +} + +// packageManagerOwnershipRefusal explains that an engine installed through a +// package manager is not PAIR's to remove, and names the command that is. The +// alternative is PAIR deleting files it never created, out of a tree that also +// holds the model library the engine shares with the user's own copy of it. +func packageManagerOwnershipRefusal(engine string, pkg *PkgInstall) string { + label, removal := pkg.Manager, pkg.Manager+" uninstall "+fullFormulaName(pkg) + if kind, known := packageManagerKinds[pkg.Manager]; known { + label, removal = kind.label, kind.removeCmd+" "+fullFormulaName(pkg) + } + return fmt.Sprintf("cannot uninstall engine %q: it was installed through %s, which owns where it lives. Remove it with \"%s\".", + engine, label, removal) +} + +// findPackageManagerBinary looks for the manager command in each known prefix, +// and only there. +func findPackageManagerBinary(kind packageManagerKind) string { + for _, prefix := range pkgManagerPrefixes { + candidate := filepath.Join(prefix, "bin", kind.binary) + if info, err := os.Stat(candidate); err == nil && + info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0 { + return candidate + } + } + return "" +} + +// installWithPackageManager performs a package-mode install: locate the package +// manager, run its steps, then prove that the engine it installed can run. +func (e *Executor) installWithPackageManager(ctx context.Context, engine, displayName string, pkg *PkgInstall) error { + kind, known := packageManagerKinds[pkg.Manager] + if !known { + return fmt.Errorf("install.pkg.manager %q is not a package manager this build can run", pkg.Manager) + } + manager := findPackageManagerBinary(kind) + if manager == "" { + // Naming what is missing and where to get it is the whole reason a + // package mode exists; the alternative is a shell error about a command + // that was never there to find. + return fmt.Errorf("%s installs through %s, which this Mac does not have. Install %s from %s and start again.", + displayName, kind.label, kind.label, kind.docsURL) + } + + e.emitInstallProgress(engine, "installing", 0) + for _, step := range kind.steps(pkg) { + out, err := runPackageManagerCommand(ctx, append([]string{manager}, step.argv...), kind.env) + if err == nil { + continue + } + if step.tolerated { + slog.Info("the optional package-manager step failed; continuing", + "engine", engine, "step", strings.Join(step.argv, " "), "output", messageTail(out, 400)) + continue + } + // The message carries the manager's own words: "Refusing to load formula + // … from untrusted tap" names the real fix, "exit status 1" does not. + return fmt.Errorf("%s %s: %s", kind.label, strings.Join(step.argv, " "), messageTail(out, 400)) + } + return e.checkInstalledPackageManagerResult(ctx, engine, displayName, kind, manager, pkg) +} + +// checkInstalledPackageManagerResult proves the install instead of accepting the +// package manager's exit code. A formula can finish successfully while leaving +// the engine's Python runtime to be built by its own launcher on first use; the +// alternative to checking here is paying for that inside a Start, which has 600 +// seconds rather than the install's thirty minutes. +func (e *Executor) checkInstalledPackageManagerResult(ctx context.Context, engine, displayName string, kind packageManagerKind, manager string, pkg *PkgInstall) error { + installed := filepath.Join(filepath.Dir(manager), pkg.Formula) + if info, err := os.Stat(installed); err != nil || !info.Mode().IsRegular() { + return fmt.Errorf("%s was installed by %s, but there is no %s command to check", displayName, kind.label, pkg.Formula) + } + out, err := runPackageManagerCommand(ctx, append([]string{installed}, kind.checkArgs...), nil) + if err != nil { + return fmt.Errorf("%s was installed but cannot run yet: %s", displayName, messageTail(out, 400)) + } + slog.Info("package-manager install verified by running the installed engine command", "engine", engine) + return nil +} + +// runPackageManagerCommand runs one package-manager command and keeps its +// combined output. The output is drained into memory rather than piped onward: a +// reader that stops early takes the install down with it, and a package manager +// that wants a password or a confirmation must find no terminal rather than wait +// on one nobody is watching. +func runPackageManagerCommand(ctx context.Context, argv []string, env map[string]string) (string, error) { + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) + cmd.Env = os.Environ() + for key, value := range env { + cmd.Env = append(cmd.Env, key+"="+value) + } + configureSysProcAttr(cmd) // hide the console window on Windows + out, err := cmd.CombinedOutput() + return string(out), err +} + +// messageTail keeps the end of a command's output for a message to the user. +// Package managers and pip print thousands of lines; a notification needs the +// reason, which lands at the end, not a transcript. It cuts on runes so a +// truncated tail cannot begin mid-character. +func messageTail(out string, limit int) string { + trimmed := strings.TrimSpace(out) + runes := []rune(trimmed) + if len(runes) <= limit { + return trimmed + } + return "…" + string(runes[len(runes)-limit:]) +} + +// validatePkgInstall rejects a package-mode install the runner could not +// perform: a package mode declared alongside a download it would not use, an +// unknown manager, or a formula and tap the manager cannot resolve. +func validatePkgInstall(key string, install *Install) error { + pkg := install.Pkg + if len(install.Script) > 0 || install.Fetch != nil || len(install.Artifacts) > 0 || len(install.Run) > 0 { + return fmt.Errorf("platform %q: install.pkg is mutually exclusive with script/fetch/artifacts/run (a package manager does its own downloading)", key) + } + kind, known := packageManagerKinds[pkg.Manager] + if !known { + return fmt.Errorf("platform %q: unknown install package manager %q (this build can run %s)", + key, pkg.Manager, strings.Join(knownPackageManagerNames(), ", ")) + } + if !pkgNameRe.MatchString(pkg.Formula) { + return fmt.Errorf("platform %q: install.pkg.formula %q must be a package name, not a path or URL", key, pkg.Formula) + } + if pkg.Tap != "" && !pkgTapRe.MatchString(pkg.Tap) { + return fmt.Errorf("platform %q: install.pkg.tap %q must be written \"/\"", key, pkg.Tap) + } + if len(kind.steps(pkg)) == 0 { + return fmt.Errorf("platform %q: install.pkg declares no command to run", key) + } + return nil +} + +// knownPackageManagerNames lists the managers this build can drive, for the +// message shown when a manifest names another. Sorted so the message is stable. +func knownPackageManagerNames() []string { + names := make([]string, 0, len(packageManagerKinds)) + for name := range packageManagerKinds { + names = append(names, name) + } + slices.Sort(names) + return names +} diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 786fefa17..b5d4855c1 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -91,11 +91,20 @@ type Platform struct { // InstallDir overrides the default app-data-root engine directory. It is a // literal user path with the same ~ and OS environment expansion as detect // paths; its resolved value is exposed to the manifest as {install_dir}. - InstallDir string `json:"install_dir,omitempty"` - Detect []string `json:"detect,omitempty"` - Install *Install `json:"install,omitempty"` - Uninstall *Uninstall `json:"uninstall,omitempty"` - Runtime Runtime `json:"runtime"` + InstallDir string `json:"install_dir,omitempty"` + Detect []string `json:"detect,omitempty"` + // Conflicts lists paths whose presence means the engine is already on this + // machine by a route PAIR does not own — the vendor's own application bundle, + // most often. A hit here does not make the engine read as installed, the way + // detect does: PAIR cannot start what it only found a folder of. It stops an + // install, because a second copy of an engine that shares one model library + // and one port is worse than no install at all, and a package manager would + // otherwise write it without being asked to. Paths get the same ~ and OS + // environment expansion as detect paths. + Conflicts []string `json:"conflicts,omitempty"` + Install *Install `json:"install,omitempty"` + Uninstall *Uninstall `json:"uninstall,omitempty"` + Runtime Runtime `json:"runtime"` // ModelsDir is the engine's on-disk model store, referenced elsewhere as // {models_dir}. Nothing this service removes may delete it: Uninstall skips // it, validation keeps it outside an explicit managed install directory, and @@ -118,12 +127,31 @@ type Install struct { // and logged as unpinned. Prefer fetch+run whenever the vendor publishes // a script or artifact so remote content is downloaded before execution. Script []string `json:"script,omitempty"` + // Pkg installs through a package manager the machine already has, which is + // how a vendor that ships no installer is still installable. It is + // exclusive with Script/Fetch/Artifacts/Run: the package manager does its + // own fetching, so there is nothing for PAIR to download or verify, and it + // chooses where its files go, so the install stays outside PAIR's ownership. + Pkg *PkgInstall `json:"pkg,omitempty"` // Mode defaults to "user" (user-scoped, no elevation). "admin" is // an explicit, rarely-used exception the runner surfaces loudly // rather than silently escalating. Mode string `json:"mode,omitempty"` } +// PkgInstall names the package manager and the package to install through it. +// Manager must be one of the managers this build can drive (see +// packageManagerKinds); Formula is the package name, which a tap qualifies; Tap +// is "/" when the package does not come from the manager's own +// repository. There is deliberately no version field: a package manager resolves +// its own dependencies, so pinning one package name would still leave two Macs +// building different things from the same manifest. +type PkgInstall struct { + Manager string `json:"manager"` + Tap string `json:"tap,omitempty"` + Formula string `json:"formula"` +} + // Uninstall removes a user-mode install. Run is for work only a command can do // — stopping the engine's own daemon, or invoking a vendor uninstaller. Remove // lists the trees this service deletes itself, which is how model weights @@ -926,6 +954,18 @@ func (p *Platform) validate(key string) error { if source := p.Runtime.ModelSource; source != "" && source != "huggingface" && source != "modelscope" { return fmt.Errorf("platform %q: invalid model_source", key) } + for _, conflict := range p.Conflicts { + if strings.TrimSpace(conflict) == "" { + return fmt.Errorf("platform %q: conflicts lists a blank path", key) + } + // Listing a detect path twice means the author did not know detect already + // reads it, and a path that makes the engine read as installed can never + // be reached as a conflict: an install is not offered for an installed + // engine, so the entry would only ever look like it was doing something. + if slices.Contains(p.Detect, conflict) { + return fmt.Errorf("platform %q: conflicts lists %q, which detect already answers for", key, conflict) + } + } if p.InstallDir != "" { if strings.TrimSpace(p.InstallDir) == "" { return fmt.Errorf("platform %q: install_dir cannot be blank", key) @@ -1042,6 +1082,16 @@ func (p *Platform) validate(key string) error { } } if p.Install != nil { + // Checked first so a package mode declared beside a download reports as + // the contradiction it is, not as a missing install.run. + if p.Install.Pkg != nil { + if err := validatePkgInstall(key, p.Install); err != nil { + return err + } + if p.Uninstall != nil { + return fmt.Errorf("platform %q: uninstall is not allowed with install.pkg — %s owns the files it installs, so PAIR neither removes them nor offers to", key, p.Install.Pkg.Manager) + } + } hasArtifacts := len(p.Install.Artifacts) > 0 if len(p.Install.Script) > 0 && (p.Install.Fetch != nil || hasArtifacts || len(p.Install.Run) > 0) { return fmt.Errorf("platform %q: install.script is mutually exclusive with fetch/artifacts/run (a script install cannot also be checksum-pinned)", key) diff --git a/services/nvpair-engine-manager/settings.go b/services/nvpair-engine-manager/settings.go index 68525dfcc..e216cbd44 100644 --- a/services/nvpair-engine-manager/settings.go +++ b/services/nvpair-engine-manager/settings.go @@ -99,16 +99,18 @@ func launchForState(st *engineState, port int, allowLanBind bool) (launchCommand rt := st.plat.Runtime bin := st.binPath st.mu.Unlock() - return resolveSettingsLaunch(rt, bin, port, st.pathVars(), allowLanBind) + return resolveSettingsLaunch(rt, bin, observedEngineCLI(st), port, st.pathVars(), allowLanBind) } // resolveSettingsLaunch uses captured values so a status update cannot change -// the executable halfway through assembling a settings response. -func resolveSettingsLaunch(rt Runtime, bin string, port int, vars map[string]string, allowLanBind bool) (launchCommand, error) { +// the executable halfway through assembling a settings response. The engine +// command is the observed one rather than the manifest's literal, for the reason +// engineCLI gives. +func resolveSettingsLaunch(rt Runtime, bin, cli string, port int, vars map[string]string, allowLanBind bool) (launchCommand, error) { vars["host"] = effectiveBind(rt.Bind, "") vars["port"] = strconv.Itoa(port) - if rt.CLI != "" { - vars["cli"] = expandPath(rt.CLI) + if cli != "" { + vars["cli"] = cli } if rt.modeOrDefault() == "process" { return resolveProcessLaunch(rt, bin, vars, allowLanBind) @@ -128,7 +130,7 @@ func (e *Executor) launchStateLocked(engine string, st *engineState) settings.La rt, bin := st.plat.Runtime, st.binPath result := settings.LaunchState{Engine: engine, ServerPort: rt.Port, EffectivePort: st.port, Running: st.running, Adopted: st.adopted, Format: launchTextFormat} st.mu.Unlock() - command, err := resolveSettingsLaunch(rt, bin, result.ServerPort, st.pathVars(), false) + command, err := resolveSettingsLaunch(rt, bin, observedEngineCLI(st), result.ServerPort, st.pathVars(), false) if engine == "llamacpp" { result.ModelSource = modelSource(st.plat.Runtime) } @@ -285,7 +287,9 @@ func (e *Executor) previewLaunchLocked(st *engineState, request settings.Request vars["host"] = host vars["port"] = strconv.Itoa(request.Settings.ServerPort) vars["bin"] = base.Bin - vars["cli"] = expandPath(rt.CLI) + if cli := observedEngineCLI(st); cli != "" { + vars["cli"] = cli + } if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { return fail("PAIR-managed launch settings require a loopback bind.") } diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index 0f64fc504..e1a33d253 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -91,7 +91,12 @@ loading is provided by the PAIR proxy endpoint. The normative operation and failure contract is [ENGINE_SETTINGS.md](../nvpair-ui-broker/ENGINE_SETTINGS.md); launch grammar is [LAUNCH_TEXT.md](LAUNCH_TEXT.md). -- Detect installation; **user-mode** install (HTTPS download + checksum-verify-when-pinned + run) per OS/arch. +- Detect installation; **user-mode** install per OS/arch, in one of three modes: a + fetch (HTTPS download + checksum-verify-when-pinned + run), a vendor `script`, or + a `pkg` install run through a package manager found in `/opt/homebrew` or + `/usr/local` (PATH is never consulted), which is then proved by running the + installed command. A `pkg` install writes no install marker and is never + uninstalled by this service: the package manager owns where the files live. - Lifecycle: start (with readiness probe), stop, restart, status, periodic health. - The bundled LM Studio stop policy reads `lms daemon status --json`: a headless host uses `lms daemon down` to release its daemon and loaded models; a GUI host @@ -119,7 +124,13 @@ loading is provided by the PAIR proxy endpoint. `load_model` is a `launch_model` action that rewrites the model in the launch arguments and restarts the engine on it, and their `unload_model` is a `stop_engine` action, because neither can release its model and keep serving. - MTPLX declares no install block, so it is only ever detected. `loaded_models` reports + MTPLX declares a `pkg` install (`youssofal/mtplx`, Apple Silicon macOS only) and a + `conflicts` path (`/Applications/MTPLX.app`), so it is installed through Homebrew + on a Mac with neither, and never beside one. vLLM and MTPLX both set + `wait_for_model`, so a start whose launch arguments name no model is refused and + the clients open the model picker first. Only vLLM also loads a cached model on + request: MTPLX advertises just the pack it serves, so a request naming another + cached pack is refused until it is loaded. `loaded_models` reports models currently resident in memory, name-extracted via the same declarative `result` spec with optional nested-path and row filters: Ollama uses `GET /api/ps`, LM Studio filters nonempty `loaded_instances` from @@ -164,6 +175,18 @@ loading is provided by the PAIR proxy endpoint. ## 3. Key Use Cases - **Install an engine, user-mode**: `engine:install {engine:"ollama"}` downloads the per-OS user-scoped package (Windows/Linux standalone archive extracted into a user dir; macOS app bundle — never an elevated `Setup.exe` or `curl | sh`), checksum-verifies, extracts, re-detects. +- **Install an engine through a package manager**: a platform whose `install` block + declares `pkg` fetches nothing. The service finds the manager in + `/opt/homebrew/bin` or `/usr/local/bin` (PATH is not consulted, because a + Finder-launched host may not have it and a `brew` found there may not fetch + prebuilt packages), runs the manager's own steps, then runs the command the + manager installed with `--version` and only calls the install done when that + answers. A machine with no package manager gets a refusal naming the manager and + its site, and `can_install` stays absent, so no client offers the button. +- **Edge case — a `pkg` install is never a PAIR-owned install**: it writes no + install marker, `engine:uninstall` refuses it by name, and + `engine:uninstall-managed` skips it, because the files are the manager's and + sit beside a model store the user filled. - **Run lifecycle**: `engine:start` / `engine:stop` / `engine:restart` / `engine:status`, with readiness and health probes against the engine's loopback port — the configured port, plus the port the engine records for itself when the manifest declares `runtime.port_source`. - **Run a declared action**: `engine:action {engine, action, params}` → the manifest-declared HTTP call to the engine's loopback control API (e.g. `127.0.0.1:{port}/api/pull`). (Methods, notifications, and UI events all use the colon form `engine:*`, matching the POC UI and the `errors:*` notifications.) - **Onboard a new engine (no code)**: a vendor adds `engines/.json`; the generic runner exposes their lifecycle + actions immediately. @@ -261,7 +284,7 @@ implementation is used. ## 6. Inputs and Outputs -**Inputs** — from the orchestrator (`nvpair-ui-broker`) over stdio / `--ipc`, plus engine manifests from disk. Newline-delimited JSON-RPC 2.0 `engine:*` requests; manifest JSON (`engine`, `display_name`, `manifest_version`, `platforms{{detect, install, runtime}}`, `actions`). Every manifest is validated on load and rejected with a specific, human-readable error if malformed; manifests are read-only to this service. +**Inputs** — from the orchestrator (`nvpair-ui-broker`) over stdio / `--ipc`, plus engine manifests from disk. Newline-delimited JSON-RPC 2.0 `engine:*` requests; manifest JSON (`engine`, `display_name`, `manifest_version`, `platforms{{detect, conflicts, install, runtime}}`, `actions`). Every manifest is validated on load and rejected with a specific, human-readable error if malformed; manifests are read-only to this service. `EngineStatus` object (returned by `engine:status` and `engine:get-installed`): ```json @@ -274,9 +297,22 @@ implementation is used. awaiting_model?: boolean healthy: boolean port: number + can_install?: boolean + owner?: string } ``` +`can_install` is present only when it is true: an engine that is already here, or +one this machine has no way to obtain (no `install` block, an admin install, a +`pkg` install with no package manager on the machine, or a `conflicts` path that +exists) simply omits it. `owner` is `"pair"` for an install this service made, a +package manager's name (`"Homebrew"`) for one it ran through a manager, `"other"` +for a copy it merely found, and omitted when nothing is installed. Both are +recomputed from the filesystem on each status, and a client that hides an Install +or Uninstall button on them is hiding exactly the buttons this service would +refuse. A remote `engine:remote-start` / `:stop` answer is a full `EngineStatus`, +so it restates both. + `LogLine` object (entry in `engine:logs`): ```json { time: string, stream: "stdout" | "stderr", text: string } @@ -428,7 +464,10 @@ fails it with the peer's error message. One persisted file: `installed-by-pair.json` in the engine's managed install directory (normally `engine-bin/` under app data, or the platform's - explicit `install_dir`), written after an install this service performed. It is the only record distinguishing an + explicit `install_dir`), written after an install this service performed, except + a `pkg` install, which deliberately writes none: a package manager put its files + in its own tree, where a removal list built from the manifest would take the + model store beside them. It is the only record distinguishing an install PAIR made from one the user made themselves, which an engine whose vendor script chooses its own destination cannot be told apart any other way, and it gates both `engine:uninstall` for such an engine and diff --git a/services/nvpair-engine-manager/status.go b/services/nvpair-engine-manager/status.go index 164a79a9c..bac69efb4 100644 --- a/services/nvpair-engine-manager/status.go +++ b/services/nvpair-engine-manager/status.go @@ -86,6 +86,24 @@ func detectPath(st *engineState) (bool, string) { return installed, binPath } +// conflictingEnginePath answers whether the engine is already on this machine by a +// route PAIR does not own. It reads the manifest's conflict paths the way +// detectPath reads its detect paths, and names the first that exists, so a refusal +// can point at the folder the user would have to open instead of describing a +// condition nobody can see. +func conflictingEnginePath(st *engineState) string { + for _, p := range st.plat.Conflicts { + r, err := resolvePlaceholders(p, st.pathVars()) + if err != nil { + continue // conflict path references something other than a known directory + } + if ep := expandPath(r); fileExists(ep) { + return ep + } + } + return "" +} + // Status refreshes installation and fixed-port presence when no lifecycle // operation is active. During an operation it returns the current snapshot. func (e *Executor) Status(engine string) (EngineStatus, error) { @@ -224,7 +242,7 @@ func statusLocked(engine string, st *engineState, enabled bool) EngineStatus { // Enabled model-selecting engines remain available for another Load or // request after their serving process exits unexpectedly. awaitingModel := st.awaitingModel || (enabled && st.plat != nil && st.plat.Runtime.WaitForModel) - return EngineStatus{ + status := EngineStatus{ Engine: engine, DisplayName: st.manifest.DisplayName, Installed: st.installed, @@ -234,7 +252,10 @@ func statusLocked(engine string, st *engineState, enabled bool) EngineStatus { AwaitingModel: st.installed && awaitingModel && !st.running && !st.starting && !st.modelSwitching, Healthy: st.healthy, Port: st.port, + Owner: installOwner(st), } + status.CanInstall = canInstallHere(st) + return status } // refreshPassiveStatus stages filesystem and network observations without an From 6453fb22568df87e399902362eb7dce11f9d0ee5 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 04/10] fix(engines): observe where an engine is and what it answers as MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two assumptions were carrying the work, and both came from an engine that picks its own port. Where to look: one configured port, plus one settings file. What a live engine sounds like: any HTTP 200 on that port. MTPLX breaks both. It moves upward until it can bind, so on one Mac its server sat on 8001 after PAIR's proxy took 8000, and on another it sat on 6666 because that is the port the user's own app keeps in its settings file. Neither is the port PAIR configures for MTPLX, and on one of the two the settings read was 3911 bytes of a stale answer. It also identifies itself on /health with "ok": true, while vLLM answers that path with a bare 200 and llama.cpp with {"status":"ok"}: three engines, one path, no engine naming itself. Both halves failed together, which is how they were seen. A MTPLX pushed onto the port PAIR reserves for probing a vLLM was reported as an installed, running, healthy vLLM, so a chat kept getting confident answers from a router the user never chose; a Start of MTPLX would launch a second copy beside the user's own, which could not bind anything and left two routers for one model. A probe now reads its body, for every engine, because a status code is not evidence about who answered. A body that answers another engine's declared identity, a body that is not a JSON object, and a body too large for PAIR to have read all count as a foreign service. An empty 200 keeps the meaning its manifest gives it: vLLM's /health really has no body, and demanding a key from it would trade one mis-read for a running engine reported offline. json_match can now name a value that is not a string, which is the only way MTPLX can say what it actually answers, and it does so on both of its probes. The keys worth yielding to are collected from every loaded manifest, so no engine has to list the routers it might be confused with, and a router nobody has heard of gets caught as soon as its own manifest declares how it identifies itself. Where to look became a search. It starts from anchors — the port being watched, the port a settings file names, and the ports the engine's own software probes or lands on — and walks upward from each, capped at 40 ports and one second for the round. The cap is not a speed concession: a range PAIR could not finish reads as unknown, never as empty, so a service that moved to another port cannot be mistaken for gone, and confirming a quit engine is silent re-runs the whole round rather than only the dial. PAIR's own compatibility facade answers a marked check with 409 proxy-facade and is read as an empty port, which is what keeps a quit engine from staying lit and blocking every uninstall; a blanket "any 409 is occupied" would have let a web app that 409s unknown paths block an install instead. A Start joins what it finds. An engine observed on another port is adopted there and the health loop follows that port, and a Start onto a port a stranger is serving is refused before anything is launched, naming the port the listener is really on rather than the one PAIR meant to use. Tests are split by the question they answer: identity_test.go holds who answered, with fixtures at the size and keys measured off running servers, and portsweep_test.go holds which ports get asked and what a status or Start concludes from the round. The relocation pair stages both engines' real manifests on three reserved ports and skips where an engine has no platform block for the host running it, since MTPLX is Apple Silicon only. The probe fields and the identity and facade rules are written up in MANIFEST.md. Signed-off-by: Steven Beverly --- services/nvpair-engine-manager/MANIFEST.md | 18 + services/nvpair-engine-manager/executor.go | 14 +- .../health_connections_test.go | 13 +- .../nvpair-engine-manager/identity_test.go | 415 +++++++++++++ services/nvpair-engine-manager/lifecycle.go | 186 +++++- .../manifests/mtplx.json | 6 +- services/nvpair-engine-manager/portsource.go | 264 +++++--- .../nvpair-engine-manager/portsource_test.go | 4 +- .../nvpair-engine-manager/portsweep_test.go | 563 ++++++++++++++++++ services/nvpair-engine-manager/registry.go | 72 ++- services/nvpair-engine-manager/status.go | 12 +- 11 files changed, 1463 insertions(+), 104 deletions(-) create mode 100644 services/nvpair-engine-manager/identity_test.go create mode 100644 services/nvpair-engine-manager/portsweep_test.go diff --git a/services/nvpair-engine-manager/MANIFEST.md b/services/nvpair-engine-manager/MANIFEST.md index 1c3fc902e..cbf4d8144 100644 --- a/services/nvpair-engine-manager/MANIFEST.md +++ b/services/nvpair-engine-manager/MANIFEST.md @@ -229,6 +229,8 @@ applies to the host the test runs on. | `env` | object | no | Extra environment (merged over the inherited env). Use `{host}`/`{port}` for the listen address, e.g. `"OLLAMA_HOST": "{host}:{port}"`. | | `port` | int | no | Fixed port, or `0` to auto-assign a free loopback port. | | `port_source` | object | no | Where the engine keeps the port it really listens on: `{"file":"","field":""}`, `field` defaulting to `port`. PAIR probes that port beside `port`, so an engine the user started themselves is adopted wherever their own app put it instead of being read as an empty port. Read fresh each poll; a missing file or key tells PAIR nothing. Requires `ready`. | +| `probe_ports` | int[] | no | Loopback ports worth probing beside `port`, because the engine's own software either looks there for a server that is already up, or lands there when its preferred port is taken. PAIR does not invent these: they are the ports the engine itself keeps, which is why a hand-started instance is found instead of read as an empty port. Requires `ready`. | +| `probe_run` | int | no | How many ports a search walks upward from each port it asks, counting the port it starts from (`0`/`1` ask the declared ports alone). An engine that relocates when its port is taken takes the next bindable port, so one pushed off the port it wanted leaves a run of listeners behind it, and its real port is somewhere inside that run. A round asks at most 40 ports; a range it could not finish reads as unknown, never as empty. Requires `ready`. | | `bind` | string | no | Listen address, substituted as `{host}`. Empty ⇒ `127.0.0.1` (the safe default); an inference engine that serves the cluster sets `"0.0.0.0"`. A per-call `bind` via `engine:start {bind}` overrides this for one call, but a non-loopback value is honored only when the `engine_allow_lan_bind` node setting is on — otherwise the start is rejected with `-32602` (`bind must be a loopback address`). Probes always target loopback. | | `start` | string[][] | command mode | Ordered bring-up commands (each an argv) for `command` mode, e.g. `[["{cli}","server","start","--port","{port}"]]`. | | `cli` | string | no | The engine's control-CLI path for this platform, referenced as `{cli}` by start/stop/actions so the manifest's **global** actions resolve to the correct per-OS binary. | @@ -244,6 +246,22 @@ string at that dotted object path. Missing, malformed, oversized, or wrong-typed response data fails the probe. `json_match` is invalid on TCP probes. +A probe answers two questions at once: whether an engine is up, and whether the +thing answering *is* that engine. A status code is not evidence about who is +listening — on one Mac's loopback, vLLM answers `/health` with a bare `200`, +llama.cpp with `200 {"status":"ok"}`, and MTPLX with `200 {"ok":true,…}` — so +the body is read for every HTTP probe. A body naming another engine's declared +identity, a body that is not a JSON object, or a body PAIR could not read +counts as a foreign service rather than as this engine. A `409` whose body +carries the `proxy-facade` error code is NVIDIA PAIR's own compatibility facade +answering, which counts as an empty port: the facade fronts ports, it does not +serve models, and a marked request is answered before it is ever forwarded. +Declare `json_match` on `ready` and `health` wherever a bare success would +identify the wrong process: MTPLX asks for `"ok": "true"` because another +engine on the same machine answers `/health` with `{"status":"ok"}` and a third +answers it with nothing at all, while llama.cpp separates itself on `/props` +with `"role": "router"`. + ### Actions Each action is a config-declared operation exposed over `engine:action`. diff --git a/services/nvpair-engine-manager/executor.go b/services/nvpair-engine-manager/executor.go index e0b814a6f..3cb02de6e 100644 --- a/services/nvpair-engine-manager/executor.go +++ b/services/nvpair-engine-manager/executor.go @@ -137,6 +137,12 @@ func (st *engineState) unlockOperation() { // layer runs the long ones (install, start) in goroutines so the read // loop stays responsive. type Executor struct { + // identityAnswers are the identity probes the loaded manifests declare. They + // let a probe that asks no question of its own tell "nothing answered" from + // "somebody else's engine answered". Written once, when the registry is + // already complete, and read-only afterwards, so no lock guards it. + identityAnswers []identityAnswer + pullMu sync.Mutex pulls map[pullKey]*activePull // downloads counts the downloads registered so far, so each has an ID of @@ -218,8 +224,12 @@ type Executor struct { func NewExecutor(reg *Registry, reporter *Reporter, emit func(string, any), baseDir string) *Executor { return &Executor{ - reg: reg, - reporter: reporter, + reg: reg, + reporter: reporter, + // The registry is loaded before an Executor is built, in every entry + // point, so what its manifests declare about their engines is settled + // here and fixed for the life of the process. + identityAnswers: reg.declaredIdentityAnswers(), emit: emit, client: newEngineHTTPClient(engineResponseHeaderTimeout), ollamaLoadClient: newEngineHTTPClient(ollamaLoadResponseHeaderTimeout), diff --git a/services/nvpair-engine-manager/health_connections_test.go b/services/nvpair-engine-manager/health_connections_test.go index a780745da..e892663e0 100644 --- a/services/nvpair-engine-manager/health_connections_test.go +++ b/services/nvpair-engine-manager/health_connections_test.go @@ -74,15 +74,24 @@ func TestProbeHTTP_MatchesJSONIdentity(t *testing.T) { test("malformed JSON", `{"service":`, false) } +// What a probe does with a body it cannot finish reading used to be "assume it is +// the engine asked about". That assumption is what reported a relocated MTPLX, whose +// health answer is 51 KB, as a running vLLM, so an unreadable body now counts as +// somebody else being there. The bound itself is unchanged and is still the point of +// this test: PAIR stops at maxProbeJSONBytes and closes the body, so a 4 MiB answer +// cannot park the health loop. TestProbeHTTP_RejectsOversizedJSONIdentityBody +// covers a probe that declares an identity key; this one declares none. func TestProbeHTTP_BoundsBodyDrain(t *testing.T) { body := &healthProbeBody{reader: strings.NewReader(strings.Repeat("x", 4<<20))} ex := &Executor{client: &http.Client{Transport: healthProbeTransport(func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: http.StatusAccepted, Body: body, Header: make(http.Header)}, nil })}} probe := &Probe{HTTP: "http://127.0.0.1:{port}/", Status: http.StatusAccepted} - require.True(t, ex.probe(context.Background(), probe, 1), "body drain changed the configured HTTP status health result") + require.False(t, ex.probe(context.Background(), probe, 1), "a body PAIR could not read was taken as proof of the engine being probed") require.NotEqual(t, 0, body.read, "body read") - require.LessOrEqual(t, body.read, 1<<20, "body read") + // One pass reads the body up to maxProbeJSONBytes, the drain then takes what + // it needs to try to reuse the connection, so the ceiling is both passes. + require.LessOrEqual(t, body.read, 2*maxProbeJSONBytes+1, "body read") require.True(t, body.closed, "body read") } diff --git a/services/nvpair-engine-manager/identity_test.go b/services/nvpair-engine-manager/identity_test.go new file mode 100644 index 000000000..42e518abf --- /dev/null +++ b/services/nvpair-engine-manager/identity_test.go @@ -0,0 +1,415 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// This file is about one question: when PAIR asks a port "are you ?", +// what counts as an answer? +// +// A status code alone cannot answer it. Three engines collide on /health on one +// Mac and each answers that endpoint differently, and none of the three says its +// own name. Captured from running servers, not read out of a README: +// +// vLLM -> 200, no body +// llama.cpp -> 200, {"status":"ok"} +// MTPLX -> 200, {"ok":true, "model":..., "model_path":...}, 51,354 bytes +// +// So "got a 200 on /health" is not evidence about which engine answered, and PAIR +// treating it as such is what reported a relocated MTPLX as a running vLLM. The +// rule the tests below hold is the narrow one that fixes that: a port may still +// answer "this is my engine" when its body proves nothing, because that is what a +// real vLLM answers; it may not answer that when its body proves somebody else is +// there, either by carrying a key another engine declares as its identity or by +// being too large for PAIR to have read at all. +// +// The MTPLX fixtures are deliberately not smaller than the real body. A matcher +// tested only against a 30-byte stub has not been tested, because the real body is +// 51 KB and its identifying keys sit inside that. + +const ( + // mtplxServedModel and mtplxServedPath are the name and folder one real + // MTPLX reports for the pack it was launched with. + mtplxServedModel = "mtplx-flash-next-optimized-speed" + mtplxServedPath = "/Users/Shared/mtplx/models/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" + + // realMTPLXHealthBytes is the size of the /health body captured from a + // running MTPLX. A fixture smaller than this would let a truncated read pass. + realMTPLXHealthBytes = 51354 + + // vllmHealthBody is vLLM's whole /health answer: a 200 and nothing else. + vllmHealthBody = "" + + // llamaCPPHealthBody is llama.cpp's. It has no key in common with MTPLX's, + // which is why the two need different identity declarations. + llamaCPPHealthBody = `{"status":"ok"}` +) + +// hostPlatformKey is the key every manifest indexes its platform blocks under. +func hostPlatformKey() string { return runtime.GOOS + "/" + runtime.GOARCH } + +// mtplxHealthBody builds MTPLX's /health body: the identifying keys in the places +// the real one puts them, then enough filler to reach the size the real one is. +// The filler lives under its own key so it cannot be mistaken for a second copy of +// an identifying key. +func mtplxHealthBody(t *testing.T, model, modelPath string) string { + t.Helper() + + // The real body reports per-kernel dispatch ledgers. Only their size matters + // to these tests: they are what pushes the response past every assumption a + // reader might make about a health check being short. + filler := make(map[string]any, 2600) + for i := range 2600 { + filler[fmt.Sprintf("sdpa_nax_flash_%04d", i)] = []any{ + "engaged", i, "cache_bank", "resident", + fmt.Sprintf("kernel_selfcheck_line_%d", i), + } + } + body, err := json.Marshal(map[string]any{ + "ok": true, + "model": model, + "model_path": modelPath, + "machine_model": "Mac16,7", + "generation_mode": "mtp", + "api_key_required": false, + "kernel_ledger": filler, + "available_modes": []string{"mtp", "ar"}, + "idle_seconds": 0.13, + "active_requests": 0, + "foreground_active": 0, + }) + require.NoError(t, err, "the health fixture must be constructible") + require.GreaterOrEqual(t, len(body), realMTPLXHealthBytes, + "the fixture must be at least as large as the real %d-byte body, or a truncated read passes for a full one", + realMTPLXHealthBytes) + return string(body) +} + +// servesBody answers `status` with `body` on every path, which is how a foreign +// server behaves toward a probe that asks it the wrong question. +func servesBody(t *testing.T, status int, body string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if body == "" { + w.WriteHeader(status) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = fmt.Fprint(w, body) + })) + t.Cleanup(srv.Close) + return srv +} + +// probeOnlyEngine builds a manifest whose only claim about the world is the +// identity question its probe asks. The other engines have to be in the registry +// for these tests because that is where a probe learns what "somebody else" looks +// like: the real registry holds every manifest, so a probe that yields to foreign +// evidence has somewhere to find it, and no engine has to be hand-named by another +// engine's manifest. +func probeOnlyEngine(name string, ready *Probe) *Manifest { + return &Manifest{ + Engine: name, DisplayName: strings.ToUpper(name), ManifestVersion: 1, + Platforms: map[string]Platform{ + hostPlatformKey(): {Runtime: Runtime{Ready: ready}}, + }, + } +} + +// executorAsking builds an executor over several engines at once, which is the +// only way to test what one engine's probe concludes about another's server. +func executorAsking(t *testing.T, manifests ...*Manifest) *Executor { + t.Helper() + reg := NewRegistry() + for _, m := range manifests { + reg.engines[m.Engine] = m + } + return NewExecutor(reg, NewReporter(nil), func(string, any) {}, t.TempDir()) +} + +// healthProbe is the shape every one of the colliding engines shares: a GET on +// /health satisfied by any 200. +func healthProbe() *Probe { + return &Probe{HTTP: "http://127.0.0.1:{port}/health", Status: 200, TimeoutS: 60} +} + +// healthProbeAskingForMTPLXsKey is what MTPLX's manifest must declare once a +// probe can express a value that is not a string: /health answers, and it answers +// with MTPLX's own key. This is the same test MTPLX applies to itself — its own +// client counts a port as one of MTPLX's only when /health answers "ok": true. +func healthProbeAskingForMTPLXsKey() *Probe { + return &Probe{ + HTTP: "http://127.0.0.1:{port}/health", + Status: 200, + TimeoutS: 60, + JSONMatch: &ProbeJSONMatch{Field: "ok", Value: "true"}, + } +} + +// A relocated MTPLX landing on vLLM's probe port is how a Mac with no vLLM came to +// report "vllm running:true port:8001". The status code matched, so PAIR believed +// it, and from there PAIR sent that router a model name it does not serve and got +// confident wrong answers. Every body here is one a real server gives back. +func TestProbeIdentity_VLLMRejectsAHealthAnswerThatNamesAnotherEngine(t *testing.T) { + const oversizedNote = "a body larger than PAIR's read limit was read as vLLM anyway" + + tests := []struct { + name string + // foreign is an extra engine whose declared identity the body answers. + foreign *Manifest + body func(t *testing.T) string + why string + }{ + { + name: "the whole MTPLX health body", + foreign: probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey()), + body: func(t *testing.T) string { + return mtplxHealthBody(t, mtplxServedModel, mtplxServedPath) + }, + why: "MTPLX answers /health with its own keys and no vLLM does", + }, + { + // Not a fixture from the field: a made-up engine, to pin where the + // knowledge comes from. If the rule were hand-written per manifest, + // this body would read as vLLM and only MTPLX would be caught. + name: "a made-up engine's own identity key", + foreign: probeOnlyEngine("otherfake", &Probe{HTTP: "http://127.0.0.1:{port}/health", JSONMatch: &ProbeJSONMatch{Field: "mystery_ready", Value: "true"}}), + body: func(*testing.T) string { + return `{"mystery_ready":true,"note":"some service of somebody else's"}` + }, + why: "a body answering another manifest's declared identity is not this engine, whoever wrote that manifest", + }, + { + name: "a web app's HTML, larger than the read limit", + foreign: probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey()), + body: func(*testing.T) string { + // A dev server with history-api fallback answers every path, + // including /health, with its app shell. + return "" + strings.Repeat(`
app shell
`, 40_000) + "" + }, + why: oversizedNote + ", and an unreadable body proves nobody", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + body := tc.body(t) + srv := servesBody(t, http.StatusOK, body) + probe := healthProbe() + ex := executorAsking(t, probeOnlyEngine("vllm", probe), tc.foreign) + + answer := ex.probeIdentity(t.Context(), probe, portOf(t, srv.URL)) + + assert.NotEqual(t, probeIdentified, answer.outcome, + "%s, yet the port was accepted as vLLM (%+v)", tc.why, answer) + assert.False(t, answer.blocked(), + "a stranger is not a credential refusal, so it must not be reported as one (%+v)", answer) + }) + } +} + +// The other half of the same rule, and the reason it is not simply "distrust every +// body": a real vLLM's /health has no body to identify with, and a real llama.cpp +// answers a key that belongs to neither. Both must still be detectable, or the fix +// for one mis-read becomes a new way to lose a running engine. +func TestProbeIdentity_VLLMStillAcceptsAHealthAnswerThatProvesNothing(t *testing.T) { + tests := []struct { + name string + body string + why string + }{ + {name: "vLLM answers nothing", body: vllmHealthBody, why: "an empty 200 is what vLLM really returns"}, + {name: "a service answers a key nobody claims", body: `{"models":[]}`, why: "a key no manifest declares as an identity proves nothing either way"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := servesBody(t, http.StatusOK, tc.body) + probe := healthProbe() + ex := executorAsking(t, + probeOnlyEngine("vllm", probe), + probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey()), + probeOnlyEngine("llamacpp", &Probe{HTTP: "http://127.0.0.1:{port}/props", JSONMatch: &ProbeJSONMatch{Field: "role", Value: "router"}}), + ) + + answer := ex.probeIdentity(t.Context(), probe, portOf(t, srv.URL)) + + require.Equal(t, probeIdentified, answer.outcome, + "%s, and this machine really runs one: refusing it would report a working engine as offline", tc.why) + }) + } +} + +// Read from the other engine: MTPLX's manifest asks only for a 200 today, so it +// accepts vLLM's empty body and llama.cpp's {"status":"ok"} as proof of MTPLX. The +// mistake runs both ways until each engine is asked about a key it owns. +func TestProbeIdentity_MTPLXRequiresItsOwnKey(t *testing.T) { + tests := []struct { + name string + body string + why string + }{ + {name: "vLLM answers nothing", body: vllmHealthBody, why: "vLLM's /health is an empty 200"}, + {name: "llama.cpp answers its own key", body: llamaCPPHealthBody, why: "llama.cpp reports status, not ok"}, + {name: "a stranger answers an empty object", body: `{}`, why: "a 200 with no keys proves nothing"}, + {name: "the keys are there with the wrong values", body: `{"ok":false,"model_path":""}`, + why: "a false ok and an absent model folder are not a running MTPLX"}, + { + name: "a model folder without MTPLX's liveness key", + body: `{"model":"someone-elses-model","model_path":"/opt/someone/models/thing"}`, + why: "a path key is shared with other routers, so it cannot be how MTPLX is recognised", + }, + } + + probe := healthProbeAskingForMTPLXsKey() + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := servesBody(t, http.StatusOK, tc.body) + ex := executorAsking(t, + probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey()), + probeOnlyEngine("vllm", healthProbe()), + ) + + answer := ex.probeIdentity(t.Context(), probe, portOf(t, srv.URL)) + + assert.NotEqual(t, probeIdentified, answer.outcome, + "%s, yet the port was accepted as MTPLX (%+v)", tc.why, answer) + }) + } +} + +// A model-less MTPLX is still MTPLX and still must not be duplicated: the server +// fills model and model_path from its launch arguments, so they say what it was +// pointed at, not whether it is here. A user who starts MTPLX with no pack has one +// router; PAIR adopting it keeps that true. +func TestProbeIdentity_MTPLXRequiresItsOwnKey_ModellessMTPLXStillCounts(t *testing.T) { + srv := servesBody(t, http.StatusOK, `{"ok":true,"model":"","model_path":"","api_key_required":false}`) + ex := executorAsking(t, probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey())) + + answer := ex.probeIdentity(t.Context(), healthProbeAskingForMTPLXsKey(), portOf(t, srv.URL)) + + require.Equal(t, probeIdentified, answer.outcome, + "a MTPLX with no pack loaded was not recognised as MTPLX, so PAIR would start a second one beside it") +} + +// The requirement only means something if the real body satisfies it, at its real +// size and with its real keys. +func TestProbeIdentity_MTPLXRequiresItsOwnKey_TheRealHealthBodyPasses(t *testing.T) { + srv := servesBody(t, http.StatusOK, mtplxHealthBody(t, mtplxServedModel, mtplxServedPath)) + ex := executorAsking(t, probeOnlyEngine("mtplx", healthProbeAskingForMTPLXsKey())) + + answer := ex.probeIdentity(t.Context(), healthProbeAskingForMTPLXsKey(), portOf(t, srv.URL)) + + require.Equal(t, probeIdentified, answer.outcome, + "a real MTPLX health body did not read as MTPLX, so a user's own engine would be invisible to PAIR") +} + +// End to end, the shape seen on two Macs: no vLLM installed anywhere, a user's +// MTPLX relocated onto the port PAIR reserves for probing vLLM, and both engines' +// real manifests loaded. A bare 200 on that port used to read as a vLLM that was +// installed, running and healthy, which is how a chat kept getting confident answers +// from an engine the user never chose. +func TestStatus_VLLM_ARelocatedMTPLXOnItsProbePortIsNotARunningVLLM(t *testing.T) { + srv := servesBody(t, http.StatusOK, mtplxHealthBody(t, mtplxServedModel, mtplxServedPath)) + servedPort := portOf(t, srv.URL) + + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + require.Contains(t, reg.Names(), "mtplx", + "MTPLX must be in the registry for its declared identity to be readable there") + + vllm, ok := reg.Get("vllm") + require.True(t, ok, "vllm manifest not loaded") + key := hostPlatformKey() + plat, ok := vllm.Platforms[key] + if !ok { + // vLLM does not run on every platform, and where it cannot be installed + // there is no vLLM card to mis-read. + t.Skipf("vLLM has no block for %s, so no relocated MTPLX can land on its probe port here", key) + } + require.NotNil(t, plat.Runtime.Ready, "the collision happens on vLLM's readiness probe") + + // No vLLM installed on this Mac: the mis-read did not depend on one. A test + // server stands in for MTPLX on vLLM's probe port, which is where MTPLX's + // own relocation rule puts it after PAIR's facade takes 8000. + plat.Detect = nil + plat.Runtime.Bin = "" + plat.Runtime.Port = servedPort + vllm.Platforms[key] = plat + + ex := NewExecutor(reg, NewReporter(nil), func(string, any) {}, t.TempDir()) + + st, err := ex.Status("vllm") + + require.NoError(t, err) + assert.False(t, st.Running, "a relocated MTPLX was reported as a running vLLM (%v)", st) + assert.False(t, st.Healthy, "a relocated MTPLX was reported as a healthy vLLM (%v)", st) + assert.False(t, st.Installed, "a relocated MTPLX made vLLM look installed (%v)", st) +} + +// The shipped manifest is where the identity answer has to live, so the manifest is +// what gets pinned. Two things must hold and only one of them is visible by reading +// the JSON: the key it declares has to be the key a real MTPLX sends, at its real +// size, and it has to refuse the routers that share /health. Every platform block is +// checked, so a manifest for another architecture cannot ship the loose probe, and +// the probes are read back from the loaded registry, so it is the edited JSON that is +// under test rather than a copy of it. +func TestMTPLXManifest_DeclaresItsOwnIdentityOnBothProbes(t *testing.T) { + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + m, ok := reg.Get("mtplx") + require.True(t, ok, "mtplx manifest not loaded") + + ex := NewExecutor(reg, NewReporter(nil), func(string, any) {}, t.TempDir()) + + // What the three routers that collide on /health really answer. + answers := []struct { + who string + body string + isMTPLX bool + }{ + {who: "a running MTPLX", body: mtplxHealthBody(t, mtplxServedModel, mtplxServedPath), isMTPLX: true}, + {who: "a MTPLX with no pack loaded", body: `{"ok":true,"model":"","model_path":"","api_key_required":false}`, isMTPLX: true}, + {who: "vLLM", body: vllmHealthBody, isMTPLX: false}, + {who: "llama.cpp", body: llamaCPPHealthBody, isMTPLX: false}, + } + + for key, plat := range m.Platforms { + for which, probe := range map[string]*Probe{"ready": plat.Runtime.Ready, "health": plat.Runtime.Health} { + require.NotNil(t, probe, "%s: runtime.%s is missing", key, which) + match := probe.JSONMatch + require.NotNil(t, match, + "%s: runtime.%s is satisfied by any 200, so any router answering /health reads as MTPLX", + key, which) + assert.Equal(t, "ok", match.Field, "%s: runtime.%s asks about the wrong key", key, which) + assert.Equal(t, "true", match.Value, "%s: runtime.%s expects the wrong value", key, which) + + for _, answer := range answers { + t.Run(key+"/"+which+"/"+answer.who, func(t *testing.T) { + srv := servesBody(t, http.StatusOK, answer.body) + got := ex.probe(t.Context(), probe, portOf(t, srv.URL)) + if answer.isMTPLX { + require.True(t, got, + "%s is a MTPLX, and a manifest that cannot see it leaves the user's own router invisible to be started a second time beside", + answer.who) + return + } + assert.False(t, got, "%s is not MTPLX, yet the manifest accepted its health answer", answer.who) + }) + } + } + } +} diff --git a/services/nvpair-engine-manager/lifecycle.go b/services/nvpair-engine-manager/lifecycle.go index 112e38e35..a2ce3fd79 100644 --- a/services/nvpair-engine-manager/lifecycle.go +++ b/services/nvpair-engine-manager/lifecycle.go @@ -4,6 +4,7 @@ package main import ( + "bytes" "context" "encoding/json" "errors" @@ -759,9 +760,10 @@ func (e *Executor) markStopped(st *engineState, engine string) { // waitUnavailable confirms that an engine's listener is gone before reporting // it stopped. Readiness and reachability are deliberately separate here: a // live listener returning 503 is unhealthy, not stopped. A successful control -// command is likewise not proof that its daemon actually exited. +// command is likewise not proof that its daemon actually exited. The port a stop +// was carried out against has no relocation to follow, so this asks that one port. func (e *Executor) waitUnavailable(p *Probe, port int, timeout time.Duration) bool { - return e.confirmPortsQuiet(context.Background(), p, []int{port}, timeout) + return e.confirmPortsQuiet(context.Background(), p, singlePortSweep(port), timeout) } // probeListener reports whether the transport endpoint described by a @@ -1084,14 +1086,16 @@ func (e *Executor) waitReady(ctx context.Context, p *Probe, port int, began time } // probeOutcome is what an identity probe learned, not merely whether PAIR was -// satisfied. "Not this engine" splits in two, because a service that refuses -// PAIR for credentials is this engine configured in a way PAIR cannot work with -// rather than somebody else's, and the two need different advice. +// satisfied. "Not this engine" splits in three, because a service that refuses +// PAIR for credentials is this engine configured in a way PAIR cannot work with, +// a service that answers another engine's identity question is somebody else's, and +// a port PAIR could not read proves nothing — and the three need different advice. type probeOutcome uint8 const ( - // probeUnanswered covers every other answer: nothing listening, a service - // that answers something else, a status the manifest did not expect. + // probeUnanswered covers the answers that say nothing about who is listening: + // nothing listening, a status the manifest did not expect, a body that names no + // engine either. probeUnanswered probeOutcome = iota // probeIdentified is the expected status and, where the manifest asks for // one, a body that matches. @@ -1102,6 +1106,25 @@ const ( // probeRefusedAuth is HTTP 403: the service refuses requests that carry no // credentials at all. probeRefusedAuth + // probeOtherService is a listener that answered and, by what it answered, said + // it is not this engine: it replied to an identity question some other engine + // declares as its own, or its body was too large for PAIR to have read at all. + // Both mean somebody is listening who is not this engine, which is why they + // share an outcome. Whether that somebody stands in the way of a second copy is + // answered later, by portObservation, against the port a copy would need. + probeOtherService + + // probePairFacade is HTTP 409 carrying PAIR's own `proxy-facade` error code: + // NVIDIA PAIR's compatibility personality answering that it is not an inference + // engine. The facade listens on every port it fronts, so it is the ordinary + // thing a search finds on loopback, and it is not somebody to leave alone. It + // is read as an empty port, which is why it is not filed with probeOtherService: + // a rule that called any 409 "somebody else is here" would let a web app that + // 409s /health block an install, and a rule that called it "this engine" would + // send a model name to a process that only forwards it. The 409 is only read + // this way because the request carries PAIR's probe marker; an unmarked request + // would have been forwarded to whatever engine is behind the facade. + probePairFacade ) type probeResult struct { @@ -1148,38 +1171,76 @@ func (e *Executor) probeIdentity(ctx context.Context, p *Probe, port int) probeR want = 200 } if resp.StatusCode != want { + // readProbeBody drains and closes on every path here, so a refused + // answer still returns its connection to the pool. + body := readProbeBody(resp.Body) outcome := probeUnanswered switch resp.StatusCode { case http.StatusUnauthorized: outcome = probeKeyProtected case http.StatusForbidden: outcome = probeRefusedAuth + case http.StatusConflict: + // A 409 has to be read before it is filed, because two very + // different things answer it: NVIDIA PAIR's own compatibility + // facade, which is not an inference engine and has none behind it, + // and a web app that 409s a path it does not serve, which is + // somebody else's live service. Only the body tells them apart. + if isPairFacadeAnswer(body) { + outcome = probePairFacade + } } - httpcon.DrainAndClose(resp.Body) return probeResult{outcome: outcome, status: resp.StatusCode} } - if p.JSONMatch == nil { - httpcon.DrainAndClose(resp.Body) - return probeResult{outcome: probeIdentified} - } - body, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeJSONBytes+1)) + // What happens to the status code now decides the rest. The body is read + // for every probe, not only for one that asks for a key, because a status + // code is not evidence about which engine answered: on one Mac's loopback, + // vLLM answers /health with 200 and no body, llama.cpp with 200 and + // {"status":"ok"}, and MTPLX with 200 and {"ok":true,...}. A probe satisfied + // by any 200 reports all three as the engine it asked about, and PAIR then + // sends the wrong router a model name and gets confident wrong answers. + body, readErr := io.ReadAll(io.LimitReader(resp.Body, maxProbeJSONBytes+1)) httpcon.DrainAndClose(resp.Body) - if err != nil || len(body) > maxProbeJSONBytes { - return probeResult{} + if len(bytes.TrimSpace(body)) == 0 { + // Nothing arrived to identify with, and an empty answer is how one of + // these engines really behaves: vLLM's /health is a bare 200. A probe + // that asks no question of its own therefore still takes that as its + // engine, because the alternative is reporting a working vLLM offline. + // A probe that does ask for a key has nothing to compare, so it cannot + // claim to have found the engine. + return probeEmptyBodyResult(p) + } + if len(body) > maxProbeJSONBytes || readErr != nil { + // A body that never finished arriving, or was larger than PAIR reads, + // says nothing about who is listening, so it is never taken as proof of + // this engine. It is also not how any of these engines answer a health + // check, which is why the port is called somebody else's rather than + // empty: a truncated read must not become a reason to launch a second + // router onto a port that is already serving. + return probeResult{outcome: probeOtherService} } var obj map[string]json.RawMessage if err := json.Unmarshal(body, &obj); err != nil { - return probeResult{} + // A body that is not a JSON object answers no identity question. This + // is how a web app with history-api fallback replies to every path + // including /health, and believing such an answer is how a front-end + // dev server came to be reported as a running inference engine. + return probeResult{outcome: probeOtherService} + } + if p.JSONMatch == nil { + if e.bodyNamesAnotherEngine(obj) { + return probeResult{outcome: probeOtherService} + } + return probeResult{outcome: probeIdentified} } value, ok := resolveObjectPath(obj, p.JSONMatch.Field) if !ok { - return probeResult{} + return probeResult{outcome: probeUnanswered} } - var actual string - if json.Unmarshal(value, &actual) == nil && actual == p.JSONMatch.Value { + if jsonIdentityMatches(value, p.JSONMatch.Value) { return probeResult{outcome: probeIdentified} } - return probeResult{} + return probeResult{outcome: probeUnanswered} } if p.TCP != "" { addr, err := resolvePlaceholders(p.TCP, vars) @@ -1198,6 +1259,91 @@ func (e *Executor) probeIdentity(ctx context.Context, p *Probe, port int) probeR return probeResult{outcome: probeIdentified} } +// proxyFacadeCode is the error code NVIDIA PAIR's compatibility facade gives a +// marked identity check, written by writeIngressError in nvpair-proxy/ingress.go. +// It is the one code only PAIR writes, which is what makes it usable as evidence: +// a status code alone cannot tell PAIR's own plumbing from a stranger. +const proxyFacadeCode = "proxy-facade" + +// readProbeBody reads a bounded response body and closes it. The cap is the one +// every probe answer is read under, because a body too large for PAIR to have read +// is not an engine's health answer either way. +func readProbeBody(body io.ReadCloser) string { + raw, err := io.ReadAll(io.LimitReader(body, maxProbeJSONBytes+1)) + httpcon.DrainAndClose(body) + if err != nil || len(raw) > maxProbeJSONBytes { + return "" + } + return string(raw) +} + +// isPairFacadeAnswer says a body carries PAIR's own facade code. It is keyed on that +// code rather than on the 409 status alone because a status code is not evidence +// about who answered: a blanket "any 409 is an empty port" would let a web app that +// answers 409 for unknown paths pass as nobody being there, and PAIR would then +// launch a second engine onto the port it occupies. +func isPairFacadeAnswer(body string) bool { + var answer struct { + Code string `json:"code"` + } + if err := json.Unmarshal([]byte(body), &answer); err != nil { + return false + } + return answer.Code == proxyFacadeCode +} + +// probeEmptyBodyResult answers a response that carried no body to identify with. +// Where the manifest declares an identity key, an empty body cannot answer it. +// Where it declares none, the manifest is asserting that a bare success is its +// engine's behaviour, and for vLLM that assertion is true: its /health is a 200 +// with no body. The empty case therefore keeps the manifest's answer instead of +// being lumped in with bodies that name somebody else. +func probeEmptyBodyResult(p *Probe) probeResult { + if p.JSONMatch != nil { + return probeResult{outcome: probeUnanswered} + } + return probeResult{outcome: probeIdentified} +} + +// bodyNamesAnotherEngine asks whether the answer a port gave belongs to some other +// engine. It is asked only by a probe that declares no identity of its own, and it +// is answered from the identity keys every loaded manifest declares, so knowing +// that MTPLX reports "ok": true is enough on its own: no manifest has to list the +// routers it might be confused with, and a router nobody has heard of still gets +// caught as soon as its own manifest declares how it identifies itself. +// +// The asking probe never appears in this comparison as a claim against itself: the +// index is consulted only by a probe that declares no identity key, and a probe that +// declares one is answered by that key alone. +func (e *Executor) bodyNamesAnotherEngine(obj map[string]json.RawMessage) bool { + for _, declared := range e.identityAnswers { + value, ok := resolveObjectPath(obj, declared.field) + if !ok { + continue + } + if jsonIdentityMatches(value, declared.value) { + return true + } + } + return false +} + +// jsonIdentityMatches compares a probe key with the value the manifest expects. +// +// A key holding a string is decoded first, which is how llama.cpp's router marker +// and every action result filter are written. Anything else is compared as the JSON +// text it holds, which is how a manifest can name a boolean: MTPLX's health answer +// identifies it with "ok": true, and a matcher limited to strings could not express +// that, leaving MTPLX with no way to be recognised as itself and every engine +// sharing /health indistinguishable from every other. +func jsonIdentityMatches(value json.RawMessage, want string) bool { + var asString string + if err := json.Unmarshal(value, &asString); err == nil { + return asString == want + } + return string(value) == strings.TrimSpace(want) +} + func (e *Executor) reportStartFailed(engine string, err error) { e.reporter.report(serviceError{ ID: startFailedID(engine), Message: err.Error(), diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index 41cf5e09a..678d7c58e 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -37,9 +37,11 @@ "bind": "127.0.0.1", "port": 8101, "port_source": { "file": "~/Library/Application Support/MTPLX/settings.json", "field": "port" }, - "ready": { "http": "http://127.0.0.1:{port}/health", "status": 200, "timeout_s": 600 }, + "probe_ports": [8000, 18083, 18084, 18085], + "probe_run": 8, + "ready": { "http": "http://127.0.0.1:{port}/health", "status": 200, "timeout_s": 600, "json_match": { "field": "ok", "value": "true" } }, "stop": { "signal": "term", "grace_s": 15 }, - "health": { "http": "http://127.0.0.1:{port}/health", "status": 200, "interval_s": 5 } + "health": { "http": "http://127.0.0.1:{port}/health", "status": 200, "interval_s": 5, "json_match": { "field": "ok", "value": "true" } } }, "models_dir": "~/.mtplx/models" } diff --git a/services/nvpair-engine-manager/portsource.go b/services/nvpair-engine-manager/portsource.go index 21e26ade4..2c2ef194c 100644 --- a/services/nvpair-engine-manager/portsource.go +++ b/services/nvpair-engine-manager/portsource.go @@ -61,25 +61,39 @@ type portObservation struct { // something that is not this engine. stranger int // unsure names a candidate that could not be read at all — a dial that timed - // out or failed for a reason other than refusal. That proves nothing about - // whether anything listens, so it is never read as an empty port. + // out or failed for a reason other than refusal, or a port the round gave up + // on once it ran out of ports or time. That proves nothing about whether + // anything listens, so it is never read as an empty port. unsure int - // quiet says every candidate refused the connection: nothing is listening. + // incomplete says the round stopped before it finished looking: it ran out of + // ports or out of time. Nothing is proved about the ports it never reached, so + // an unfinished search is never read as an empty port range. + incomplete bool + // quiet says nothing that could be an inference engine is listening anywhere + // the round looked: every port it asked either refused the connection or + // answered as NVIDIA PAIR's own compatibility facade. quiet bool + // asked records every port the round dialed, in the order it dialed them. It + // is how a round spends its budget and how it refuses to ask the same port + // twice, and it is the record of ground a search covered: a search that + // stopped short has to stay distinguishable from one that covered the range + // and found nobody, or a quiet status round is only a search that gave up. + asked []int } // answered says the round found a live service that is not this engine. func (o portObservation) answered() bool { return o.blocked != 0 || o.stranger != 0 } -// occupied says the round heard something back anywhere: the engine answering as -// itself, a stranger, a credential refusal, or a port it could not read. Both of -// the callers that ask this question are about to act on the assumption that +// occupied says the round heard something back anywhere, or could not finish +// telling: the engine answering as itself, a stranger, a credential refusal, a port +// it could not read, or ports it never reached because it ran out of ground or time. +// Both of the callers that ask this question are about to act on the assumption that // nothing is there — delete the engine's files, or call its service gone — and // neither can tell which of the ports it asked was the one it needed, so none of // them counts as empty. Whether a port stands in the way of a second copy is the // narrower question, and spawnBlocked answers it. func (o portObservation) occupied() bool { - return o.identified != 0 || o.answered() || o.unsure != 0 + return o.identified != 0 || o.answered() || o.unsure != 0 || o.incomplete } // spawnBlocked says a Start or Install must not bring up a second copy. @@ -172,9 +186,53 @@ func (o portObservation) authBlockedNotice(displayName string) string { displayName, o.blocked, o.blockedStatus, o.blockedAnswer(), neverSendsKey) } -// candidatePorts lists the loopback ports worth probing for one engine, in -// probe order: the port being watched, then the port the engine's own settings -// file names when that differs. +// portSweep is one round of asking: which loopback ports are worth a probe, and +// how far the search may travel from each of them. It is built once per round, +// because how much ground a round may cover is a property of the round rather +// than of any one port inside it. +type portSweep struct { + // anchors lists the ports worth probing wherever they came from: the port + // being watched, the port an engine's own settings file names, and the ports + // the engine's own software looks at. + anchors []int + // run bounds how many ports one walk covers, counting the port it starts + // from. One asks the anchors alone, which is every engine that serves on the + // port it is given; more follows an engine that had to move. + run int + // budget bounds how many ports the whole round may ask, so a machine with a + // wide field of listeners does not turn one status check into a port scan. + budget int +} + +const ( + // portSweepBudget is the most ports one round will ask, counting the anchors + // and every walk. The ports a MTPLX-style search covers are its configured + // port, its settings-file port, four ports the engine probes itself, and the + // run above each, which fits inside this with room to spare; past it the + // round gives up and says it is unsure. + portSweepBudget = 40 + + // portSweepRoundTime bounds one whole round, so that a listener which accepts + // connections and never answers cannot make a status check spend its every + // probe's full wait against every port in range: stalled listeners cost this + // much in total, not three seconds times forty ports. A machine with nothing + // listening finishes a round in milliseconds, and a caller's own deadline (the + // quiet check gives itself less than this) still cuts it shorter. A round that + // hits the bound is marked unsure rather than quiet, because ports never asked + // prove nobody is home. + portSweepRoundTime = time.Second +) + +// singlePortSweep asks one port with no walk beside it: the port a stop was +// carried out against, where there is no relocation to follow. +func singlePortSweep(port int) portSweep { + return portSweep{anchors: []int{port}, run: 1} +} + +// candidatePorts lists the loopback ports worth probing for one engine, in probe +// order: the port being watched, then the port the engine's own settings file +// names when that differs, then the ports the engine's own software looks at, +// with how far the search may walk upward from any of them. // // The settings file is what lets an engine the user started themselves be found // on whatever port their own app chose, which is the only port it will ever @@ -182,9 +240,15 @@ func (o portObservation) authBlockedNotice(displayName string) string { // own app takes effect on the next poll without restarting PAIR. An engine whose // manifest declares no port source gets exactly the one port it probed before // any of this existed. -func (e *Executor) candidatePorts(st *engineState, watched int) []int { +// +// The declared probe ports, and the walk above them, are for the other way an +// engine ends up away from its configured port: it cannot bind it. An engine that +// finds its preferred port taken moves to the next bindable one, so a server that +// had to move leaves a run of listeners behind it, and the one place PAIR knows to +// look — the port it would have used — is exactly the place that was already taken. +func (e *Executor) candidatePorts(st *engineState, watched int) portSweep { // plat is fixed when the engine is registered, so no lock guards it. - source := st.plat.Runtime.PortSource + rt := st.plat.Runtime var ports []int add := func(port int) { @@ -193,12 +257,15 @@ func (e *Executor) candidatePorts(st *engineState, watched int) []int { } } add(watched) - if source != nil { + if source := rt.PortSource; source != nil { if port, ok := settingsPort(source, st.pathVars()); ok { add(port) } } - return ports + for _, port := range rt.ProbePorts { + add(port) + } + return portSweep{anchors: ports, run: max(rt.ProbeRun, 1), budget: portSweepBudget} } // settingsPort reads the port an engine keeps in its own settings file, from @@ -250,68 +317,141 @@ func settingsPort(source *PortSource, vars map[string]string) (int, bool) { return port, port > 0 && port <= 65535 } -// probePortObservation asks each candidate port, cheapest check first: a -// transport dial before an HTTP request. It stops at the first port that -// identifies, because one identified service is all an engine needs and every -// later port would only be asked the same question. Each answer is filed under -// the port it came from: whether one port counts against an operation depends on -// which port it is, and a refusal has to say where the service it names is. -func (e *Executor) probePortObservation(ctx context.Context, ready *Probe, ports []int) portObservation { - obs := portObservation{quiet: len(ports) > 0} - if len(ports) > 0 { - obs.bind = ports[0] +// probePortObservation asks the ports a sweep covers, cheapest check first: a +// transport dial before an HTTP request. Each ladder walks upward only while its +// ports take connections, and the round returns at the first port that identifies, +// because one identified service is all an engine needs and every later port would +// only be asked the same question. +// +// Each answer is filed under the port it came from: whether one port counts against +// an operation depends on which port it is, and a refusal has to say where the +// service it names is. +func (e *Executor) probePortObservation(ctx context.Context, ready *Probe, sweep portSweep) portObservation { + run := max(sweep.run, 1) + budget := max(sweep.budget, 1) + + // A round with no port to ask says nothing at all. It stays not-quiet, so a + // caller about to delete an engine's files, or to call its service gone, keeps + // failing closed instead of reading an empty question as an empty port. + obs := portObservation{} + if len(sweep.anchors) == 0 { + return obs } - for _, port := range ports { - switch probeListener(ctx, ready, port) { - case listenerProbeRefused: - continue - case listenerProbeIndeterminate: - obs.quiet = false - if obs.unsure == 0 { - obs.unsure = port - } - continue + obs.bind = sweep.anchors[0] + obs.quiet = true + + // asked is the round's ledger: it spends the budget, it keeps the search from + // asking one port twice, and it is the only record that a range was covered + // rather than skipped. + asked := make(map[int]bool, budget) + deadline := time.Now().Add(portSweepRoundTime) + // roundOver ends the whole sweep at once: either an engine answered as itself, + // or the round ran out of ports or time and did not finish looking. + roundOver := false + for _, anchor := range sweep.anchors { + if roundOver { + break } - // The port takes connections, so what it answers says what is behind it. - obs.quiet = false - answer := e.probeIdentity(ctx, ready, port) - switch { - case answer.outcome == probeIdentified: - obs.identified = port - return obs - case answer.blocked(): - if obs.blocked == 0 { - obs.blocked = port - obs.blockedStatus = answer.status + // One ladder per anchor, walked upward while the ports stay busy. The way + // an engine ends up away from the port it wanted is that the ports above it + // were taken too, so a run of listeners is the trail to follow and an empty + // port is the end of it. A busy port is only a reason to stop looking when + // what lives there is a service PAIR could have used: a stranger, or PAIR's + // own facade, says nothing about where this engine is. + portRange: + for step := 0; step < run; step++ { + port := anchor + step + if port > 65535 { + break } - default: - if obs.stranger == 0 { - obs.stranger = port + // One ask per port: a declared probe port can fall inside a ladder that + // has already covered it. + if asked[port] { + continue + } + if len(obs.asked) >= budget || time.Now().After(deadline) { + // Stopping short is not the same as having looked, and a quiet round + // unblocks an uninstall and reports an engine stopped, so a round + // that gave up claims nothing. + obs.incomplete = true + obs.quiet = false + roundOver = true + break + } + asked[port] = true + obs.asked = append(obs.asked, port) + + switch probeListener(ctx, ready, port) { + case listenerProbeRefused: + break portRange + case listenerProbeIndeterminate: + // A dial that timed out, or failed for a reason other than refusal, + // does not prove the port is empty either. + obs.quiet = false + if obs.unsure == 0 { + obs.unsure = port + } + break portRange + } + + // The port takes connections, so what it answers says what is behind + // it — except for PAIR's own facade, which is not a place an inference + // engine lives. See probePairFacade. + answer := e.probeIdentity(ctx, ready, port) + if answer.outcome != probePairFacade { + obs.quiet = false + } + switch { + case answer.outcome == probeIdentified: + obs.identified = port + roundOver = true + break portRange + case answer.outcome == probePairFacade: + // NVIDIA PAIR's compatibility facade answering that it is not an + // inference engine. There is nothing behind it to adopt and nobody + // to leave alone, so it neither fills a port range nor keeps a + // quit engine marked running. + case answer.blocked(): + if obs.blocked == 0 { + obs.blocked = port + obs.blockedStatus = answer.status + } + default: + if obs.stranger == 0 { + obs.stranger = port + } } } } return obs } -// confirmPortsQuiet re-probes ports until every one of them refuses three times -// in a row. That is the evidence PAIR demands before it says a service it was +// confirmPortsQuiet re-runs the whole port round until it comes back quiet three +// times in a row. That is the evidence PAIR demands before it says a service it was // watching has stopped — both when a stop command has just run against one port -// and when a passive status round finds nothing answering. A service that moved -// to another port still answers here, so it is not reported gone, and another -// engine's listener is never read as this one leaving. -func (e *Executor) confirmPortsQuiet(parent context.Context, ready *Probe, ports []int, timeout time.Duration) bool { +// and when a passive status round finds nothing answering. +// +// It re-runs the round rather than just dialing the ports again because being quiet +// now includes what a port answers. NVIDIA PAIR's own facade takes connections on +// every port it fronts, so a dial-only check could never go quiet while PAIR's proxy +// runs: a MTPLX the user quit would stay lit forever and every uninstall would be +// refused, over a listener that is PAIR's own plumbing. A service that moved to +// another port still answers here, so it is not reported gone, and another engine's +// listener is never read as this one leaving. +func (e *Executor) confirmPortsQuiet(parent context.Context, ready *Probe, sweep portSweep, timeout time.Duration) bool { ctx, cancel := context.WithTimeout(parent, timeout) defer cancel() misses := 0 for { - if allPortsRefused(ctx, ready, ports) { + if e.probePortObservation(ctx, ready, sweep).quiet { misses++ if misses == unavailableConfirmations { return true } } else { - // A reachable listener, a timeout, or a malformed probe target - // cannot prove shutdown. Require a fresh consecutive sequence. + // A reachable listener, a timeout, a malformed probe target, or a round + // that stopped short cannot prove shutdown. Require a fresh consecutive + // sequence. misses = 0 } select { @@ -321,13 +461,3 @@ func (e *Executor) confirmPortsQuiet(parent context.Context, ready *Probe, ports } } } - -// allPortsRefused reports whether every port explicitly refused a connection. -func allPortsRefused(ctx context.Context, ready *Probe, ports []int) bool { - for _, port := range ports { - if probeListener(ctx, ready, port) != listenerProbeRefused { - return false - } - } - return len(ports) > 0 -} diff --git a/services/nvpair-engine-manager/portsource_test.go b/services/nvpair-engine-manager/portsource_test.go index e0ea3da38..a4b76d70e 100644 --- a/services/nvpair-engine-manager/portsource_test.go +++ b/services/nvpair-engine-manager/portsource_test.go @@ -200,7 +200,7 @@ func TestCandidatePorts_AddsThePortTheEngineKeepsInItsOwnSettingsFile(t *testing st, err := ex.state("mtplx") require.NoError(t, err) - assert.Equal(t, tc.want, ex.candidatePorts(st, watched)) + assert.Equal(t, tc.want, ex.candidatePorts(st, watched).anchors) }) } } @@ -213,7 +213,7 @@ func TestCandidatePorts_WithoutAPortSource_JustWatchesTheConfiguredPort(t *testi st, err := ex.state("mtplx") require.NoError(t, err) - assert.Equal(t, []int{watched}, ex.candidatePorts(st, watched)) + assert.Equal(t, []int{watched}, ex.candidatePorts(st, watched).anchors) } // A status check has to ask about every candidate port, or an engine running diff --git a/services/nvpair-engine-manager/portsweep_test.go b/services/nvpair-engine-manager/portsweep_test.go new file mode 100644 index 000000000..ab336120b --- /dev/null +++ b/services/nvpair-engine-manager/portsweep_test.go @@ -0,0 +1,563 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// This file is about the other half of the same failure: not what a port says when +// PAIR asks it a question, but which ports PAIR asks at all, and what PAIR +// concludes when one of them answers as NVIDIA PAIR itself. +// +// Both come from the same two Macs. A MTPLX that finds its own port taken moves +// upward until it can bind, so on one machine the user's server sat on 8001 after +// PAIR's proxy took 8000, and on the other it sat on 6666 because that is the port +// the user's own app keeps in its settings file. Neither place is the port PAIR +// configures for MTPLX, and PAIR's settings-file read was 3911 bytes of a stale +// answer on one of them, so a single port and a single file are not enough to find +// a running engine. +// +// Widening the search has a cost that has to be paid in the same change: the extra +// ports are not empty. 8000 is PAIR's own vLLM facade, and PAIR's proxy answers a +// marked health check with 409 to say it is a facade and not an engine. Filed as +// "somebody else is here", that answer refuses uninstalls, keeps a quit engine +// marked running, and generally makes PAIR's own plumbing look like a foreign +// service. So the two rules below belong together: look in more places, and read +// PAIR's own facade as an empty port rather than as a squatter. + +// portRun reserves n consecutive loopback ports and returns the numbers with +// nothing listening on any of them. Consecutive is the point: the tests below are +// about a search that walks upward from a port, so they need a run they can lay +// servers into, and a run with a hole in it would prove nothing about that walk. +func portRun(t *testing.T, n int) []int { + t.Helper() + + for { + // One listener per port, all held at once, so a port PAIR has already + // proved free cannot be taken by another process between two of them. + listeners := make([]net.Listener, 0, n) + try := func() ([]int, bool) { + first, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return nil, false + } + listeners = append(listeners, first) + base := first.Addr().(*net.TCPAddr).Port + ports := []int{base} + for port := base + 1; len(ports) < n; port++ { + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + return nil, false + } + listeners = append(listeners, ln) + ports = append(ports, port) + } + return ports, true + } + + ports, ok := try() + for _, ln := range listeners { + _ = ln.Close() + } + if ok { + return ports + } + // The OS would not hand over a contiguous run that starts here; ask + // again rather than build a test whose walk has a hole in it. + } +} + +// serveOnPort puts a server up on a port the test already reserved. +// +// It builds the server around the listener rather than calling +// httptest.NewUnstartedServer, because that helper binds a listener of its own +// first — one that replacing it never closes. A fixture that leaks a bound port +// into the range the test is measuring turns an empty port into something that +// answers, which is exactly the distinction these tests are about. +func serveOnPort(t *testing.T, port int, handler http.HandlerFunc) *httptest.Server { + t.Helper() + + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + require.NoError(t, err, "port %d was taken between reserving it and filling it", port) + srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: handler}} + srv.Start() + t.Cleanup(srv.Close) + return srv +} + +// answersJSON replies to every path with a JSON body, which is how a foreign +// router behaves toward a probe that asks it the wrong question. +func answersJSON(status int, body string) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = fmt.Fprint(w, body) + } +} + +// pairFacade answers the way NVIDIA PAIR's own compatibility facade answers a +// marked health check: HTTP 409 and the one error code only PAIR writes. It notes +// whether the marker arrived, because that marker is the only reason a facade can +// be told apart from the engine it fronts — an unmarked request would have been +// forwarded, and a fixture that ignored the header would pass even if PAIR stopped +// sending it. +func pairFacade(sawMarker *atomic.Bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(engineIdentityProbeHeader) == "1" { + sawMarker.Store(true) + } + // The body and header are the ones nvpair-proxy actually writes for a + // marked request (writeIngressError in ingress.go), read off a live + // facade on this machine rather than written to match the parser. + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(http.StatusConflict) + _, _ = fmt.Fprint(w, `{"code":"proxy-facade","error":"the compatibility facade is not the MTPLX engine"}`) + } +} + +// sweepManifest builds the manifest these tests need: a readiness probe that asks +// about a key only MTPLX answers, a settings file that may name where the user's +// copy really is, and a declared set of extra ports with how far to walk up from +// each. The binary is a path that does not exist, so a second copy cannot quietly +// come up beside whatever the fixture put on a port. +func sweepManifest(t *testing.T, probe *Probe, configuredPort int, probePorts []int, walk int, source *PortSource) *Manifest { + t.Helper() + + missing := filepath.Join(t.TempDir(), "mtplx"+exeExt()) + return &Manifest{ + Engine: "mtplx", DisplayName: "MTPLX", ManifestVersion: 1, + Platforms: map[string]Platform{hostPlatformKey(): { + Detect: []string{missing}, + Runtime: Runtime{ + Bin: missing, + Port: configuredPort, + PortSource: source, + Ready: probe, + ProbePorts: probePorts, + ProbeRun: walk, + }, + }}, + } +} + +// A user's MTPLX answers on a port their own software chose, and that is the only +// port it will ever answer on. PAIR's configured port is where PAIR would put its +// own copy, not where the engine already running keeps itself, so the search has to +// cover the ports the engine itself looks at. +func TestCandidatePorts_AddsThePortsTheEnginesOwnSoftwareKeeps(t *testing.T) { + const watched = 8101 + + tests := []struct { + name string + settings string + probePorts []int + want []int + }{ + { + name: "adds the ports MTPLX probes and lands on", + probePorts: []int{8000, 18083, 18084, 18085}, + want: []int{watched, 8000, 18083, 18084, 18085}, + }, + { + // Where the file and the port list disagree, both are asked: the + // file is what a user's own app wrote, and it can be stale. + name: "asks the settings-file port and the declared ports", + settings: `{"port":6666}`, + probePorts: []int{8000, 18083}, + want: []int{watched, 6666, 8000, 18083}, + }, + { + name: "asks a declared port once", + probePorts: []int{8000, 8000}, + want: []int{watched, 8000}, + }, + { + // The watched port stays first: it is the port a second copy would + // bind, and what PAIR concludes about it decides whether one starts. + name: "skips a declared port that is the port already watched", + probePorts: []int{watched, 8000}, + want: []int{watched, 8000}, + }, + { + name: "says nothing about ports that cannot exist", + probePorts: []int{0, -1, 70000, 8000}, + want: []int{watched, 8000}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + file := filepath.Join(t.TempDir(), "missing.json") + if tc.settings != "" { + file = writePortSettings(t, tc.settings) + } + manifest := sweepManifest(t, healthProbeAskingForMTPLXsKey(), watched, tc.probePorts, 4, + &PortSource{File: file}) + ex := newTestExecutor(t, manifest) + st, err := ex.state("mtplx") + require.NoError(t, err) + + assert.Equal(t, tc.want, ex.candidatePorts(st, watched).anchors) + }) + } +} + +// The four numbers are not PAIR's invention: they are the ports MTPLX's own client +// probes, taken out of the software, plus the port it defaults to. 8000 is also +// PAIR's vLLM facade port, which is why this set is only safe together with the +// rule that a facade answer reads as an empty port. +func TestMTPLXManifest_NamesThePortsMTPLXItselfLooksAt(t *testing.T) { + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + m, ok := reg.Get("mtplx") + require.True(t, ok, "mtplx manifest not loaded") + + for key, plat := range m.Platforms { + assert.Equal(t, []int{8000, 18083, 18084, 18085}, plat.Runtime.ProbePorts, + "%s: MTPLX must be looked for on the ports MTPLX's own software probes and relocates onto", key) + assert.Greater(t, plat.Runtime.ProbeRun, 1, + "%s: a MTPLX pushed off its port moves upward, so the search has to walk with it", key) + } +} + +// The relocation case, which is what two Macs actually produced: the user's MTPLX +// wanted 8000, found PAIR's facade there, and moved. Neither the configured port +// nor the settings file said where it landed, and MTPLX's own CLI missed it for the +// same reason. +func TestPortSweep_FindsTheEngineOnThePortsItWasPushedOffTo(t *testing.T) { + t.Run("walks past the ports it had to leave behind", func(t *testing.T) { + // One reserved run of ports, laid end to end, so the walk has real + // ground to cover: PAIR's own empty port, then the listeners a MTPLX + // that could not bind its preferred port had to leave behind it. + ports := portRun(t, 4) + configured, facadePort, llamaPort, mtplxPort := ports[0], ports[1], ports[2], ports[3] + + var sawMarker atomic.Bool + facade := serveOnPort(t, facadePort, pairFacade(&sawMarker)) + defer facade.Close() + // llama.cpp on a port of its own: a real router, and not MTPLX. A walk + // that stopped at the first non-matching answer would end here. + llama := serveOnPort(t, llamaPort, answersJSON(http.StatusOK, llamaCPPHealthBody)) + defer llama.Close() + mtplx := serveOnPort(t, mtplxPort, answersJSON(http.StatusOK, mtplxHealthBody(t, mtplxServedModel, mtplxServedPath))) + defer mtplx.Close() + + probe := healthProbeAskingForMTPLXsKey() + ex := newTestExecutor(t, sweepManifest(t, probe, configured, []int{facadePort}, 4, nil)) + st, err := ex.state("mtplx") + require.NoError(t, err) + sweep := ex.candidatePorts(st, configured) + + obs := ex.probePortObservation(t.Context(), probe, sweep) + + require.True(t, sawMarker.Load(), + "a probe that does not carry the marker would have been forwarded through the facade to an engine behind it") + require.Equal(t, mtplxPort, obs.identified, + "a user's MTPLX on a port it had to move to was not found, so PAIR would start a second one (%+v)", obs) + // The ground one round covers, in the order it covered it: PAIR's own + // empty port, then straight up the run of occupied ports the engine left + // behind it. That the facade and llama.cpp are on the way is why the walk + // keeps going; neither is a reason to treat the range as somebody else's, + // and neither is anywhere a second copy would be launched onto. + assert.Equal(t, []int{configured, facadePort, llamaPort, mtplxPort}, obs.asked, + "the search did not walk from the declared port up to the one that answered") + }) + + t.Run("stops a walk that goes on longer than the search is allowed to", func(t *testing.T) { + // Six reserved ports: PAIR's own empty port, and a run of five listeners + // long enough that the walk has to stop inside it. Every one of them + // answers, and none of them is MTPLX. The search has to stop somewhere; + // what matters is that stopping is not reported as having found nobody, + // because a second copy onto a busy port is a second router for one model. + ports := portRun(t, 6) + configured := ports[5] + for _, port := range ports[:5] { + srv := serveOnPort(t, port, answersJSON(http.StatusOK, llamaCPPHealthBody)) + defer srv.Close() + } + + probe := healthProbeAskingForMTPLXsKey() + ex := newTestExecutor(t, sweepManifest(t, probe, configured, []int{ports[0]}, 4, nil)) + st, err := ex.state("mtplx") + require.NoError(t, err) + + obs := ex.probePortObservation(t.Context(), probe, ex.candidatePorts(st, configured)) + + assert.Zero(t, obs.identified, "a llama.cpp router was taken for MTPLX (%+v)", obs) + assert.False(t, obs.quiet, "a run full of listeners was reported as an empty port range (%+v)", obs) + assert.True(t, obs.occupied(), "a port range full of listeners counted as empty (%+v)", obs) + // One dial for PAIR's own empty port, then the four ports a walk of four + // is allowed to cover. The fifth port of the run is left alone: a search + // with no bound is not an answer either, and stopping short costs a lookup, + // not a second router, because the ports a copy might bind were empty. + assert.Equal(t, []int{configured, ports[0], ports[1], ports[2], ports[3]}, obs.asked, + "the walk ran past its bound (%v)", obs.asked) + }) +} + +// A facade is not a place an inference engine lives. It answers for whichever +// engine holds the model, which is exactly the ambiguity that made a relocated +// MTPLX read as a running vLLM, and it is NVIDIA PAIR's own process. Treating it +// as "somebody else is here" would make PAIR's plumbing block its own work, so the +// answer is filed as no service at all. +func TestPortSweep_DoesNotCountPAIRsOwnFacadeAsAnotherService(t *testing.T) { + // Three reserved ports: PAIR's own empty port, the facade, and the port the + // walk reaches one step past it, so everything the round asks is ground known + // to be empty before the fixture starts. + ports := portRun(t, 3) + configured, facadePort, walkedPort := ports[0], ports[1], ports[2] + + var sawMarker atomic.Bool + facade := serveOnPort(t, facadePort, pairFacade(&sawMarker)) + defer facade.Close() + + probe := healthProbeAskingForMTPLXsKey() + ex := newTestExecutor(t, sweepManifest(t, probe, configured, []int{facadePort}, 2, nil)) + st, err := ex.state("mtplx") + require.NoError(t, err) + + obs := ex.probePortObservation(t.Context(), probe, ex.candidatePorts(st, configured)) + + assert.Zero(t, obs.identified, "PAIR's own facade was taken for the engine (%+v)", obs) + assert.Zero(t, obs.stranger, "PAIR's own facade was filed as a service that is not this engine (%+v)", obs) + assert.False(t, obs.answered(), "a facade kept the port range from counting as empty (%+v)", obs) + assert.True(t, obs.quiet, "an empty port range was reported as occupied (%+v)", obs) + assert.False(t, obs.spawnBlocked(), "a facade away from the bind port stopped a start (%+v)", obs) + assert.False(t, obs.occupied(), "a facade was treated as somebody to leave alone (%+v)", obs) + assert.Equal(t, []int{configured, facadePort, walkedPort}, obs.asked, + "the round did not cover the range the manifest declared (%+v)", obs) +} + +// The consequence that matters while a user is trying to get rid of an engine: the +// facade is up whenever PAIR's proxy runs, so a facade on a probe port would refuse +// every uninstall, on every Mac, forever. +func TestUninstall_PAIRsOwnFacadeOnAProbePort_StillDeletesTheEngine(t *testing.T) { + baseDir := t.TempDir() + managedBin := filepath.Join(baseDir, "mtplx", "mtplx"+exeExt()) + require.NoError(t, os.MkdirAll(filepath.Dir(managedBin), 0o755)) + copyFile(t, fakeEngineBin, managedBin) + + // The facade sits on the probe port, and the walk of two it triggers reaches + // the next port, which is empty: none of this is a service, and none of it is + // anywhere a MTPLX would be launched onto. + ports := portRun(t, 3) + configured, facadePort := ports[0], ports[1] + facade := serveOnPort(t, facadePort, pairFacade(new(atomic.Bool))) + defer facade.Close() + + manifest := sweepManifest(t, healthProbeAskingForMTPLXsKey(), configured, []int{facadePort}, 2, nil) + key := hostPlatformKey() + p := manifest.Platforms[key] + p.Detect = []string{managedBin} + p.Runtime.Bin = managedBin + p.Uninstall = &Uninstall{Run: rmCmd(managedBin)} + manifest.Platforms[key] = p + + reg := NewRegistry() + reg.engines[manifest.Engine] = manifest + ex := NewExecutor(reg, NewReporter(nil), func(string, any) {}, baseDir) + + err := ex.Uninstall(t.Context(), "mtplx") + + require.NoError(t, err, "uninstall was refused because PAIR's own proxy answered a probe port") + assert.NoFileExists(t, managedBin, "the refusal left the engine's files in place") +} + +// The other consequence: while a facade answers a probe port, a MTPLX the user +// started themselves and then quit would never be allowed to read as stopped. The +// card would stay lit, and PAIR would keep waiting on a server that is gone. +func TestStatus_PAIRsOwnFacadeOnAProbePort_KeepsReportingAQuitedEngineAsStopped(t *testing.T) { + ports := portRun(t, 3) + configured, facadePort, servedPort := ports[0], ports[1], ports[2] + + var sawMarker atomic.Bool + facade := serveOnPort(t, facadePort, pairFacade(&sawMarker)) + defer facade.Close() + engine := serveOnPort(t, servedPort, answersJSON(http.StatusOK, mtplxHealthBody(t, mtplxServedModel, mtplxServedPath))) + defer engine.Close() + + source := &PortSource{File: writePortSettings(t, fmt.Sprintf(`{"port": %d}`, servedPort))} + ex := newTestExecutor(t, sweepManifest(t, healthProbeAskingForMTPLXsKey(), configured, []int{facadePort}, 2, source)) + + st, err := ex.Status("mtplx") + require.NoError(t, err) + require.True(t, st.Running, "the user's own MTPLX was never seen (%v)", st) + require.Equal(t, servedPort, st.Port, "the engine was tracked at the wrong port (%v)", st) + + // The user quits their engine. The facade stays up, as it does whenever + // PAIR's proxy runs. + engine.Close() + + st, err = ex.Status("mtplx") + + require.NoError(t, err) + assert.False(t, st.Running, "a MTPLX that exited is still shown running while PAIR's facade answers a probe port (%v)", st) + assert.False(t, st.Healthy, "a MTPLX that exited is still shown healthy (%v)", st) + assert.Equal(t, configured, st.Port, "PAIR kept holding the port of a service that is gone (%v)", st) +} + +// relocationShape is the two-Mac failure laid out on one machine, using three +// consecutive reserved ports. The lowest stays empty, because that is the port a +// second copy would be launched onto. The middle one carries PAIR's own +// compatibility facade, which is a port MTPLX asks at and therefore an anchor a +// search starts from. The top one carries the user's MTPLX, after it failed to +// bind the port it wanted — which, at the default numbers, is also the port PAIR +// reserves for a vLLM. That is how one engine's hiding place became the other +// engine's identity. +type relocationShape struct { + emptyPort int + facadePort int + relocatedPort int + sawMarker atomic.Bool +} + +// stageRelocation puts those two listeners up. Both are asked the marked health +// check, and sawMarker records whether the marker actually arrived: it is the only +// reason a facade can be told apart from whatever it happens to front. +func stageRelocation(t *testing.T) *relocationShape { + t.Helper() + + ports := portRun(t, 3) + layout := &relocationShape{emptyPort: ports[0], facadePort: ports[1], relocatedPort: ports[2]} + serveOnPort(t, layout.facadePort, pairFacade(&layout.sawMarker)) + serveOnPort(t, layout.relocatedPort, + answersJSON(http.StatusOK, mtplxHealthBody(t, mtplxServedModel, mtplxServedPath))) + return layout +} + +// hostPlatformBlock reads a shipped manifest back for the machine running the +// test, because these tests are about the search a manifest declares: they take it +// as declared and change only the ports. Where a host has no block for an engine +// there is no pair to stage, and MTPLX is Apple Silicon only, so this skips rather +// than fails. +func hostPlatformBlock(t *testing.T, reg *Registry, engine string) (*Manifest, Platform) { + t.Helper() + + m, ok := reg.Get(engine) + require.True(t, ok, "%s must be in the registry for its ports to be tested", engine) + key := hostPlatformKey() + p, ok := m.Platforms[key] + if !ok { + t.Skipf("%s has no block for %s, so this host stages neither engine", engine, key) + } + return m, p +} + +// relocationRegistry takes the shipped pair of manifests and moves only their +// ports onto the reserved run: MTPLX looks first at an empty port and then upward +// from a facade, and vLLM is pointed at the port the MTPLX had to move to. Neither +// engine keeps a binary that could really be launched here, and vLLM keeps no +// detect path this machine could have, so the fixture says what the two Macs said — +// no vLLM anywhere, and a MTPLX that had to move. +func relocationRegistry(t *testing.T, layout *relocationShape) *Registry { + t.Helper() + + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + + mtplxManifest, mtplxPlat := hostPlatformBlock(t, reg, "mtplx") + require.NotEmpty(t, mtplxPlat.Runtime.ProbePorts, "MTPLX must search the ports MTPLX keeps") + require.Greater(t, mtplxPlat.Runtime.ProbeRun, 1, + "a MTPLX pushed off its port moves upward, so the search has to walk with it") + + // A port round only runs for an engine PAIR thinks is present, so the detect + // path is pinned to a file that exists on every machine rather than to whatever + // MTPLX.app this one happens to have. The settings-file read goes for the same + // reason: without it, a test could find a MTPLX that happens to be running on + // the machine running it and pass for the wrong reason. + mtplxPlat.Detect = []string{os.DevNull} + mtplxPlat.Runtime.Bin = filepath.Join(t.TempDir(), "mtplx"+exeExt()) + mtplxPlat.Runtime.Port = layout.emptyPort + mtplxPlat.Runtime.PortSource = nil + mtplxPlat.Runtime.ProbePorts = []int{layout.facadePort} + mtplxPlat.Runtime.ProbeRun = 2 + mtplxManifest.Platforms[hostPlatformKey()] = mtplxPlat + + vllmManifest, vllmPlat := hostPlatformBlock(t, reg, "vllm") + vllmPlat.Detect = nil + vllmPlat.Runtime.Bin = filepath.Join(t.TempDir(), "vllm"+exeExt()) + vllmPlat.Runtime.Port = layout.relocatedPort + vllmManifest.Platforms[hostPlatformKey()] = vllmPlat + + return reg +} + +// The pair as one machine, which is what both Macs produced at the default ports: +// MTPLX wanted 8000, PAIR's proxy was holding it, and the MTPLX moved to 8001 — +// the port PAIR reserves for meeting a vLLM. Neither the port PAIR configures for +// MTPLX nor its settings file says where that is, so the search has to start from a +// declared probe port and keep walking over a facade and a foreign router. What each +// answer means is identity_test.go's business; this file is about which ports get +// asked and what PAIR concludes from the round. +func TestStatus_ARelocatedMTPLXBehindTheFacade_IsFoundOnThePortItMovedTo(t *testing.T) { + layout := stageRelocation(t) + ex := NewExecutor(relocationRegistry(t, layout), NewReporter(nil), func(string, any) {}, t.TempDir()) + + m, err := ex.Status("mtplx") + + require.NoError(t, err) + require.True(t, m.Running, "the relocated MTPLX was not found, so PAIR would start a second one (%v)", m) + assert.Equal(t, layout.relocatedPort, m.Port, "the found engine is tracked at the wrong port (%v)", m) + require.True(t, layout.sawMarker.Load(), + "a probe that did not carry the marker would have been forwarded through the facade") +} + +// Status is only how PAIR knows. The second copy that must not appear arrives +// through Start, and Start is also where an adopted engine's real port has to +// travel: the health loop and every later request follow the port the engine was +// joined at, so finding a MTPLX on the port it moved to and then watching PAIR's +// own port finds nobody. +func TestStart_ARelocatedMTPLX_IsAdoptedOnThePortItMovedTo(t *testing.T) { + layout := stageRelocation(t) + ex := NewExecutor(relocationRegistry(t, layout), NewReporter(nil), func(string, any) {}, t.TempDir()) + + require.NoError(t, ex.Start(t.Context(), "mtplx"), "Start refused although the engine is answering") + + state, err := ex.state("mtplx") + require.NoError(t, err) + state.mu.Lock() + defer state.mu.Unlock() + assert.True(t, state.adopted, "Start did not join the MTPLX that was already running") + assert.Nil(t, state.proc, "Start launched a second MTPLX beside the running one") + assert.Equal(t, layout.relocatedPort, state.port, "the adopted engine is tracked at the wrong port") +} + +// vLLM's half of the same pair. Its probe asks one port and reads no key of its +// own, which is exactly how a relocated MTPLX came to be read as a running vLLM, +// and a vLLM launched onto that port could not have bound it either. The refusal +// has to name the port the listener is really on, because the advice that goes with +// it is "choose a port nothing is listening on". +func TestStart_VLLMsPortHeldByARelocatedMTPLX_RefusesWithoutLaunchingASecondCopy(t *testing.T) { + layout := stageRelocation(t) + ex := NewExecutor(relocationRegistry(t, layout), NewReporter(nil), func(string, any) {}, t.TempDir()) + + require.NoError(t, ex.Start(t.Context(), "mtplx"), + "a MTPLX answering on another port is not vLLM's to refuse") + + err := ex.Start(t.Context(), "vllm") + + require.Error(t, err, "vLLM accepted a port a relocated MTPLX is serving on") + require.ErrorContains(t, err, fmt.Sprintf("port %d", layout.relocatedPort), + "the refusal named a port that is not where the listener is") + require.ErrorContains(t, err, "did not identify as vLLM") + + state, err := ex.state("vllm") + require.NoError(t, err) + state.mu.Lock() + defer state.mu.Unlock() + assert.Nil(t, state.proc, "Start launched a vLLM onto the port a MTPLX is serving on") + assert.False(t, state.running, "a refused start left vLLM marked running") +} diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index b5d4855c1..1f40530bd 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -241,6 +241,18 @@ type Runtime struct { // themselves is found wherever their app happens to keep it instead of being // mistaken for an empty port. PortSource *PortSource `json:"port_source,omitempty"` + // ProbePorts lists loopback ports worth probing beside the configured one, + // because the engine's own software either looks there for a server that is + // already up or lands there when its preferred port is taken. The configured + // port is where a copy PAIR launches would go, which is not the same question + // as where an engine already running keeps itself. + ProbePorts []int `json:"probe_ports,omitempty"` + // ProbeRun bounds how far the search walks upward from a port that answers, + // counting the port it starts from. An engine that relocates when its port is + // taken takes the next bindable port, so a server pushed off the port it + // wanted leaves a run of listeners behind it, and the port it ended on is + // somewhere inside that run. Zero asks the declared ports alone. + ProbeRun int `json:"probe_run,omitempty"` // Bind is the default listener address, used as the value of {host}. // Empty defaults to loopback; a per-call bind can override it. Bind string `json:"bind,omitempty"` @@ -337,14 +349,68 @@ func (r *Runtime) hasCustomLaunch() bool { return len(r.LaunchArgs) > 0 || len(r.LaunchEnv) > 0 } -// ProbeJSONMatch optionally identifies an HTTP service by a string field in -// its JSON response body. Field supports the same validated dotted object path -// syntax as action result filters. +// ProbeJSONMatch optionally identifies an HTTP service by a field in its JSON +// response body. Field supports the same validated dotted object path syntax as +// action result filters. +// +// Value names the field's value the way the service writes it, not the way Go +// would spell it: "router" is the string router, "true" the boolean true, "8" the +// number 8. A field holding a string is compared after decoding, anything else by +// the JSON text it holds. This exists because the engines that collide on /health +// identify themselves with non-strings — MTPLX answers "ok": true — and a matcher +// that could only compare strings left such an engine with no way to be recognised +// as itself. type ProbeJSONMatch struct { Field string `json:"field"` Value string `json:"value"` } +// identityAnswer is one manifest's claim about how its engine answers an identity +// probe: this field holding this value means the service on that port is that +// engine. +type identityAnswer struct { + field string + value string +} + +// declaredIdentityAnswers collects the identity claims of every loaded manifest, +// read from each platform block's readiness and ongoing-health probes. +// +// A probe that declares no identity of its own consults this, which is how a port +// answering somebody else's question stops being read as an answer to PAIR's. The +// knowledge lives here rather than in the manifest that gets it wrong so that +// declaring "MTPLX answers ok:true" is enough on its own: no engine has to name +// the engines it might be confused with, and that list would have been out of date +// the moment someone added another router. +// +// Every platform block is read, not only the host's. The question a probe asks is +// about a port, and what answers there does not depend on which platforms the other +// engine's manifest happens to describe. +func (r *Registry) declaredIdentityAnswers() []identityAnswer { + var out []identityAnswer + add := func(p *Probe) { + if p == nil || p.JSONMatch == nil { + return + } + answer := identityAnswer{field: p.JSONMatch.Field, value: p.JSONMatch.Value} + if !slices.Contains(out, answer) { + out = append(out, answer) + } + } + for _, name := range r.Names() { + m, ok := r.Get(name) + if !ok { + continue + } + for _, key := range slices.Sorted(maps.Keys(m.Platforms)) { + platform := m.Platforms[key] + add(platform.Runtime.Ready) + add(platform.Runtime.Health) + } + } + return out +} + // Probe is an HTTP or TCP reachability check. Exactly one of HTTP/TCP should be // set; HTTP wins if both are. JSONMatch is valid only for HTTP probes. type Probe struct { diff --git a/services/nvpair-engine-manager/status.go b/services/nvpair-engine-manager/status.go index bac69efb4..67b9d3cbe 100644 --- a/services/nvpair-engine-manager/status.go +++ b/services/nvpair-engine-manager/status.go @@ -294,10 +294,10 @@ func (e *Executor) refreshPassiveStatus(engine string, st *engineState, key stat // Every candidate port is asked, not only the one being watched. An // engine the user started themselves answers on whatever port their own // app chose, and that is the only place it will ever answer. - ports := e.candidatePorts(st, key.port) - obs = e.probePortObservation(ctx, ready, ports) + sweep := e.candidatePorts(st, key.port) + obs = e.probePortObservation(ctx, ready, sweep) if obs.quiet && running && adopted { - refusedConfirmed = e.confirmPortsQuiet(ctx, ready, ports, presenceRefusalWindow) + refusedConfirmed = e.confirmPortsQuiet(ctx, ready, sweep, presenceRefusalWindow) } } if ctx.Err() != nil { @@ -433,11 +433,11 @@ func (e *Executor) reconcilePresence(ctx context.Context, engine string, st *eng } } - ports := e.candidatePorts(st, port) - obs := e.probePortObservation(ctx, ready, ports) + sweep := e.candidatePorts(st, port) + obs := e.probePortObservation(ctx, ready, sweep) identified := obs.identified if obs.quiet { - if !running || !adopted || !e.confirmPortsQuiet(ctx, ready, ports, presenceRefusalWindow) { + if !running || !adopted || !e.confirmPortsQuiet(ctx, ready, sweep, presenceRefusalWindow) { return presenceResult{obs: obs} } st.mu.Lock() From 234c0100fe4a2ce00feab8922cb75d1f3211b4e0 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 05/10] feat(engines): carry the pack inventory as rows, and answer which pack is resident MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One MTPLX pack has three names: the directory it loads from, the served name it answers /v1/models with, and the cache id its listing calls it by. Consumers that asked what an engine serves got a name and had to guess which pack it belonged to — the way a request for any model sharing a prefix can read as the model being served. This makes "what is resident" an observed answer, and keeps the three ways of failing to observe it from turning into a wrong fact. - packInventory reads the cache the way the engine lists it and keeps the repo id and the directory together in a row; the residency join is string-exact on purpose, with no case folding, separator rewriting or symlink resolution, because normalising would merge rows the engine itself keeps apart on a filesystem that already folds case. Two test fixtures stage reported paths that are exactly one redundant separator from a cached row, so an extraction that tidies what it reads fails instead of joining a near miss in silence. - The empty-versus-unknown split is kept, not collapsed. An empty listing means the inventory was read and nothing is cached. An engine that answered nothing, answered with something that is not a listing, or answered with a body larger than PAIR reads (1 MiB, drained and closed) means nothing was read — and "nothing was read" never becomes "nothing is resident", because it is exactly the state in which a pack a server holds could otherwise be deleted. - The residency read runs under the probe's 3-second bound and the body cap, asked through the marker header so PAIR's own facade answers it rather than forwarding it. The fixture transport records target, marker and deadline; the relocated-server test asserts all three, because a stubbed answer cannot otherwise tell a bounded read from an unbounded one. A manifest whose residency block names a mutating action — a stop, a restart, a relaunch of the engine being asked — is rejected at load; that question does not get to change what it asks about. - A residency answer reaches users in the spelling their rows already carry. An MTPLX serving the Qwen3.8 pack names itself "mtplx-flash-next-optimized-speed" while its listing calls the same pack by its cache id; unioned naively that is two rows for one pack, the cached one offering Load for a model already being served. Residency therefore joins to the inventory row and reports by its key, which is also the handle the load, eject and delete actions take; the advertised list keeps the served name, because that is what a request routes by. Where the join cannot say which row is resident — no answer, an engine that says nothing about its own model, a directory no row names — the served names stay the loaded list: "I cannot tell which cached row this is" is not the statement "nothing is loaded". - Cost is stated where it is paid: one join is a bounded GET plus an inventory read that for MTPLX is a real `mtplx models --json` subprocess carrying the 30-minute action timeout. A sweep that has read the inventory hands it to the join rather than making the engine run the CLI twice per round; a one-click eject pays at most the two reads, and none at all when the engine says nothing about its own model. Tests are built from the measured bodies and stay hermetic: fixtures stage through a stubbed transport on a port with nothing listening, the relocated-server case uses an OS-assigned port in place of the 6666 that is somebody's live session on the machine the captures came from, the transport errors on any path it was not told about, and the cases whose right answer is to ask nothing assert that nothing was asked. Signed-off-by: Steven Beverly --- .../manifests/mtplx.json | 13 +- services/nvpair-engine-manager/models.go | 127 +- services/nvpair-engine-manager/models_test.go | 154 +++ services/nvpair-engine-manager/registry.go | 107 ++ services/nvpair-engine-manager/residency.go | 367 ++++++ .../nvpair-engine-manager/residency_test.go | 1097 +++++++++++++++++ services/nvpair-tui/ui/nodedetail_test.go | 49 + 7 files changed, 1896 insertions(+), 18 deletions(-) create mode 100644 services/nvpair-engine-manager/residency.go create mode 100644 services/nvpair-engine-manager/residency_test.go diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index 678d7c58e..c22e9540c 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -53,9 +53,18 @@ "result": { "array": "models", "field": "repo_id" } }, "loaded_models": { - "description": "List the model this MTPLX server serves (it serves exactly one). MTPLX is started with --model-id set to the cache id, so the name it answers to is the same string list_models reports and what a client puts in its request.", + "description": "List the model this MTPLX server serves (it serves exactly one). The name it answers with is not the cache id: a machine serving the Qwen3.5 pack answered \"youssofal-qwen3.5-4b-mtplx-optimized-speed\" while its cache lists that pack as \"Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed\", so no spelling of the served name can be matched to a pack by eye. /health reports the directory the pack was loaded from, and that is what residency joins to the listing.", "http": { "method": "GET", "path": "/v1/models" }, - "result": { "array": "data", "field": "id" } + "result": { + "array": "data", + "field": "id", + "residency": { + "source": "list_models", + "read": { "method": "GET", "path": "/health" }, + "path_field": "model_path", + "row_path_field": "path" + } + } }, "load_model": { "description": "Serve a different model pack (params: {\"model\": \"\"}). MTPLX serves one model per process, so this saves the model into the launch arguments and restarts the engine on it; if the new model does not start, the previous one is restored. --model-id is written beside --model so the served name stays the cache id.", diff --git a/services/nvpair-engine-manager/models.go b/services/nvpair-engine-manager/models.go index 33fc9f9ac..417a428e1 100644 --- a/services/nvpair-engine-manager/models.go +++ b/services/nvpair-engine-manager/models.go @@ -231,14 +231,24 @@ func (e *Executor) modelsResult(ctx context.Context) (ModelsResult, error) { // it reports nothing loaded. While it runs, one // loaded_models response gives both the names it answers to (result.field, // such as vLLM's served name) and, when result.inventory_field is set, the same -// models in the inventory's terms (vLLM's --model). +// models in the inventory's terms (vLLM's --model). Where a manifest declares +// result.residency instead — for an engine that answers with a name it invented +// for the pack it mapped — the loaded marker comes from joining the engine's own +// loaded-path answer onto the inventory rows, in the rows' spelling, and that +// join reuses the inventory read above rather than reading the engine again. func (e *Executor) loadedOnlyEngineModels(ctx context.Context, name string, st EngineStatus, listSpec, loadedSpec *ActionResult) engineModels { var r engineModels if !st.Installed { return r } + // The inventory is read once and kept whole, because two questions get answered + // from it: which rows this engine has, and which of those rows the running server + // has mapped. For MTPLX that read is a subprocess, so the second question has to + // be asked of the same answer rather than of the engine again. + var inventory inventoryAnswer if listSpec != nil { - r.downloaded, r.downloadedOK = e.queryModelList(ctx, name, "list_models", listSpec) + inventory = e.readInventory(ctx, name, "list_models", listSpec) + r.downloaded, r.downloadedOK = inventory.names, inventory.namesOK } if !st.Running { // A stopped engine of this kind has nothing loaded, which is known, not @@ -261,22 +271,51 @@ func (e *Executor) loadedOnlyEngineModels(ctx context.Context, name string, st E if !r.advertisedOK || !r.loadedOK { slog.Debug("engine:models loaded_models returned an invalid inventory", "engine", name) } + // A manifest that declares the join gets to answer the residency question in the + // inventory's own terms, which is the only spelling the rows this list is unioned + // onto are keyed by. MTPLX names the model it serves + // "mtplx-flash-next-optimized-speed" and calls the same pack + // "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" when it lists the cache, so + // reporting the served name here shows one resident pack as two rows — the cached + // one idle, with Load, Eject and Delete aimed by a lookup that never finds it, and + // the served name loaded. A row offering Load on an engine already serving it + // restarts that engine. + // + // The join's other answers are left alone. Where it cannot say which row is + // resident — the read did not arrive, the engine says nothing about its own model, + // or the directory it mapped is one no row names — the names it serves stay as the + // loaded list, because "I cannot tell which cached row this is" is not the statement + // "nothing is loaded". What that leaves is one loaded row that no cached row names, + // which is what a pack handed to the server as a pair bundle really is. + if loadedSpec.Residency != nil { + if row, ok := e.residentPackFrom(ctx, name, inventory); ok { + r.loaded, r.loadedOK = []string{row.repoID}, true + } + } return r } -// queryModelList runs one model-list action and extracts its names. ok is -// false when the action failed or its response was not a valid list. -func (e *Executor) queryModelList(ctx context.Context, name, action string, spec *ActionResult) ([]string, bool) { +// readInventory runs one inventory action once and keeps the answer whole, so a caller +// that needs two things out of one listing can take both from the read rather than make +// it twice. queryModelList is the same read for a caller that only wants the names. +func (e *Executor) readInventory(ctx context.Context, name, action string, spec *ActionResult) inventoryAnswer { raw, err := e.Action(ctx, name, action, nil) if err != nil { slog.Debug("engine:models action failed", "engine", name, "action", action, "err", err) - return nil, false + return inventoryAnswer{action: action} } models, ok := extractStringsResult(raw, spec) if !ok { slog.Debug("engine:models action returned an invalid inventory", "engine", name, "action", action) } - return models, ok + return inventoryAnswer{action: action, raw: raw, names: models, namesOK: ok, read: true} +} + +// queryModelList runs one model-list action and extracts its names. ok is +// false when the action failed or its response was not a valid list. +func (e *Executor) queryModelList(ctx context.Context, name, action string, spec *ActionResult) ([]string, bool) { + answer := e.readInventory(ctx, name, action, spec) + return answer.names, answer.namesOK } // withModels records one engine's list in a per-engine map, creating the map on @@ -304,19 +343,22 @@ func extractStrings(raw json.RawMessage, spec *ActionResult) []string { return out } -// extractStringsResult pulls spec.Field from each element of the required -// top-level spec.Array. A present empty array is a successful, authoritative -// empty inventory. A missing, null, or wrong-typed array is unknown and returns -// ok=false so callers do not label it authoritative empty. Malformed rows -// inside a valid array are skipped, preserving additive response compatibility. For an -// unfiltered inventory, however, a non-empty array with no usable names is -// malformed rather than authoritative empty. -func extractStringsResult(raw json.RawMessage, spec *ActionResult) ([]string, bool) { +// inventoryArray decides what counts as an inventory answer at all: the body has to +// be a JSON object carrying arrayField as an array of objects. A present empty +// array was read and is authoritative empty; anything else — a missing or null +// array, a wrong-typed one, a body that is not an object (which is how a cmd action +// hands on stdout that is not JSON, and how empty stdout arrives) — was not read. +// +// Both extractors below start with this because they answer the same question about +// the same kind of answer, and a caller that mistakes "could not read" for "nothing +// cached" gives the wrong advice either way. Keeping one copy is also the point: the +// rules are a contract between the two, so they must not be able to drift. +func inventoryArray(raw json.RawMessage, arrayField string) ([]map[string]json.RawMessage, bool) { var obj map[string]json.RawMessage if err := json.Unmarshal(raw, &obj); err != nil { return nil, false } - arrRaw, ok := obj[spec.Array] + arrRaw, ok := obj[arrayField] if !ok || bytes.Equal(bytes.TrimSpace(arrRaw), []byte("null")) { return nil, false } @@ -324,6 +366,21 @@ func extractStringsResult(raw json.RawMessage, spec *ActionResult) ([]string, bo if err := json.Unmarshal(arrRaw, &arr); err != nil { return nil, false } + return arr, true +} + +// extractStringsResult pulls spec.Field from each element of the required +// top-level spec.Array, read through inventoryArray. A present empty array is a +// successful, authoritative empty inventory. A missing, null, or wrong-typed array +// is unknown and returns ok=false so callers do not label it authoritative empty. +// Malformed rows inside a valid array are skipped, preserving additive response +// compatibility. For an unfiltered inventory, however, a non-empty array with no +// usable names is malformed rather than authoritative empty. +func extractStringsResult(raw json.RawMessage, spec *ActionResult) ([]string, bool) { + arr, ok := inventoryArray(raw, spec.Array) + if !ok { + return nil, false + } out := make([]string, 0) for _, el := range arr { if spec.Match != nil && !matchRow(el, spec.Match) { @@ -344,6 +401,44 @@ func extractStringsResult(raw json.RawMessage, spec *ActionResult) ([]string, bo return out, true } +// extractPackRows reads an inventory as packs rather than as names: every element +// of arrayField that carries a non-empty keyField and a non-empty pathField +// becomes one row, and anything else is skipped. A row PAIR cannot both name and +// locate is not a pack it can act on, so dropping it keeps a partially readable +// listing from being read as a list of packs. +// +// The empty-versus-unknown rules are extractStringsResult's, through inventoryArray, +// because they answer the same question: a present empty array was read and is +// authoritative, a missing, null or wrong-typed array was not read, and a non-empty +// array with nothing usable in it is malformed. That distinction is the whole point +// of returning ok — a listing that arrived broken must not be reported as "nothing +// cached". +func extractPackRows(raw json.RawMessage, arrayField, keyField, pathField string) ([]packRow, bool) { + arr, ok := inventoryArray(raw, arrayField) + if !ok { + return nil, false + } + field := func(el map[string]json.RawMessage, name string) string { + var value string + if err := json.Unmarshal(el[name], &value); err != nil { + return "" + } + return value + } + rows := make([]packRow, 0, len(arr)) + for _, el := range arr { + key, path := field(el, keyField), field(el, pathField) + if key == "" || path == "" { + continue + } + rows = append(rows, packRow{repoID: key, path: path}) + } + if len(arr) > 0 && len(rows) == 0 { + return nil, false + } + return rows, true +} + // matchRow reports whether an element passes an ActionResult row filter. // Match.Field is a validated dot-separated object path. With Match.In set, the // resolved value must decode as a JSON string equal to one of In. With diff --git a/services/nvpair-engine-manager/models_test.go b/services/nvpair-engine-manager/models_test.go index 49528d9ba..42a20bbf9 100644 --- a/services/nvpair-engine-manager/models_test.go +++ b/services/nvpair-engine-manager/models_test.go @@ -128,6 +128,109 @@ func TestExtractStringsResult_DistinguishesEmptyFromUnknown(t *testing.T) { test("invalid JSON", `not-json`) } +// TestInventoryArray_KeepsTheEmptyAndUnknownSplitForBothExtractors pins the shapes +// where the two inventory extractors must agree: whether the body is an inventory +// answer at all. They differ on purpose about what happens inside a valid array — +// extractStringsResult skips rows missing its field, extractPackRows needs two +// fields per row — so only the shapes where neither could read a row are compared. +// A change to the shared preamble has to keep all of these reading as "not read", +// which is the reason they are one helper rather than two copies. +func TestInventoryArray_KeepsTheEmptyAndUnknownSplitForBothExtractors(t *testing.T) { + spec := &ActionResult{Array: "models", Field: "name"} + + t.Run("a present empty array is known empty for both", func(t *testing.T) { + names, namesOK := extractStringsResult(json.RawMessage(`{"models":[]}`), spec) + rows, rowsOK := extractPackRows(json.RawMessage(`{"models":[]}`), "models", "repo_id", "path") + + require.True(t, namesOK, "names: an empty inventory was still read") + assert.NotNil(t, names, "names: an empty inventory serialises as []") + assert.Empty(t, names, "names") + require.True(t, rowsOK, "rows: an empty inventory was still read") + assert.NotNil(t, rows, "rows: an empty inventory serialises as []") + assert.Empty(t, rows, "rows") + }) + + asBoth := func(name, body string) { + t.Run(name, func(t *testing.T) { + names, ok := extractStringsResult(json.RawMessage(body), spec) + assert.False(t, ok, "names: this body carries no inventory (%s)", body) + assert.Nil(t, names, "names") + + rows, ok := extractPackRows(json.RawMessage(body), "models", "repo_id", "path") + assert.False(t, ok, "rows: the same body has to read the same way (%s)", body) + assert.Nil(t, rows, "rows") + }) + } + asBoth("no answer", ``) + asBoth("empty command stdout", `null`) + asBoth("no models array", `{"other":[]}`) + asBoth("null models array", `{"models":null}`) + asBoth("models as a string", `{"models":"llama3:8b"}`) + asBoth("models as an object", `{"models":{"name":"llama3:8b"}}`) + asBoth("the whole answer is an array", `["llama3:8b"]`) + asBoth("a listing wrapped as command output", `"mtplx: warning: stale venv\n{\"models\":[]}"`) + asBoth("a listing wrapped and cut off", `"mtplx: warning: stale venv\n{\"models\":[{\"repo_id\":\"o"`) +} + +// TestExtractPackRows_ReadsCmdStdoutAsUnreadUnlessItIsOneWholeListing covers the +// shapes a cmd-sourced inventory read arrives in, which is how the shipped MTPLX +// manifest reads its cache. When stdout is not valid JSON, runCmdAction hands the +// trimmed stdout to the reader as one JSON string; these are the shapes that +// produces for a model listing. The transport itself is not exercised — a test +// cannot shell out to a real `mtplx`, which is why the fixture in residency_test.go +// stages the same body through an HTTP action (see residencyInventoryPath). A +// truncated listing is the case that matters: read charitably it names the packs +// above the cut, and a partially readable cache must not be reported as the whole +// cache. +func TestExtractPackRows_ReadsCmdStdoutAsUnreadUnlessItIsOneWholeListing(t *testing.T) { + const wholeListing = `{"cache_dir":"/Users/Shared/mtplx/models","models":[{"path":"/Users/Shared/mtplx/models/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed","repo_id":"Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed"}]}` + + // asStdout is the dispatcher's wrap: a stdout that json.Valid rejects is + // quoted, so the reader sees one JSON string, not a body. + asStdout := func(t *testing.T, stdout string) json.RawMessage { + t.Helper() + + require.False(t, json.Valid([]byte(stdout)), "the fixture has to be a stdout the dispatcher would wrap") + body, err := json.Marshal(stdout) + require.NoError(t, err) + return body + } + + t.Run("a whole listing arrives as rows", func(t *testing.T) { + rows, ok := extractPackRows(json.RawMessage(wholeListing), "models", "repo_id", "path") + + require.True(t, ok, "valid JSON passes through the dispatcher unchanged") + require.Len(t, rows, 1, "that listing holds one pack") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", rows[0].repoID) + }) + + t.Run("a listing with a log line in front of it is unread", func(t *testing.T) { + rows, ok := extractPackRows(asStdout(t, "mtplx: warning: runtime venv is out of date\n"+wholeListing), "models", "repo_id", "path") + + assert.False(t, ok, "log noise around a listing is not a partial cache") + assert.Nil(t, rows) + }) + + t.Run("a listing cut off mid-body is unread", func(t *testing.T) { + // The second pack's name is there and its path is cut mid-string, so a + // reader that looked only at what decoded would report one and a half + // packs, and then be asked to choose a model from that. + rows, ok := extractPackRows(asStdout(t, `{"models":[{"repo_id":"Youssofal/Gemma4-MTPLX-Optimized-Speed","path":"/Users/steven/.mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed"},{"repo_id":"Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed","path":"/Users/steven/.mtplx/mo`), "models", "repo_id", "path") + + assert.False(t, ok, "a truncated listing must not report the packs above the cut") + assert.Nil(t, rows) + }) + + t.Run("a command that printed nothing is unread", func(t *testing.T) { + // Empty stdout is reported as JSON null, which is not the same answer as + // a cache that printed an empty models array. + rows, ok := extractPackRows(json.RawMessage("null"), "models", "repo_id", "path") + + assert.False(t, ok, "no output did not report an empty cache") + assert.Nil(t, rows) + }) +} + // TestModels drives Models() against the running fake engine: a running engine // with a Result-bearing list_models action contributes its models; a stopped // engine contributes nothing. @@ -481,6 +584,57 @@ func TestModelsResult_MarksTheCachedModelLoadedWhenServedUnderAnAlias(t *testing assert.Equal(t, map[string][]string{"fake": {"llama3.2:1b"}}, res.LoadedByEngine, "loaded") } +// Reporting a resident pack as the inventory row it belongs to is something only a +// manifest that declares the join can ask for, and this is the gate that says nothing +// else moved: vLLM, which answers the inventory terms of its loaded model through +// result.inventory_field, and an engine like Ollama, whose advertised list is its +// inventory and whose loaded list is read apart from it, produce this payload +// byte for byte. Both strings are the answer those engines give today, so a residency +// join that leaked into a shared code path — or a runtime branch on which engine is +// being asked — shows up here rather than in someone's model list. +func TestLoadedModels_LeavesOtherEnginesComparingNames(t *testing.T) { + t.Run("vLLM answers its loaded model in the inventory terms it declared", func(t *testing.T) { + ex := newTestExecutor(t, loadedOnlyManifest(t, fakeEngineBin)) + ctx := t.Context() + t.Cleanup(func() { _ = ex.Stop("fake") }) + require.NoError(t, ex.Start(ctx, "fake")) + + res := ex.ModelsResult(ctx) + require.Equal(t, map[string][]string{"fake": {"llama3.2:1b"}}, res.LoadedByEngine, + "the loaded marker comes from result.inventory_field, which is this engine's own row key") + assert.JSONEq(t, `{"models":["llama3.2:1b"], + "modelsByEngine":{"fake":["llama3.2:1b"]}, + "loadedByEngine":{"fake":["llama3.2:1b"]}, + "downloadedByEngine":{"fake":["other/cached-model"]}}`, string(mustMarshal(t, res)), + "the whole payload for an engine that declares no residency join") + }) + + t.Run("an engine whose advertised list is its inventory compares names as before", func(t *testing.T) { + ex := newTestExecutor(t, loadedActionManifest()) + ctx := t.Context() + t.Cleanup(func() { _ = ex.Stop("fake") }) + require.NoError(t, ex.Start(ctx, "fake")) + + res := ex.ModelsResult(ctx) + require.Equal(t, map[string][]string{"fake": {"llama3.2:1b"}}, res.LoadedByEngine, + "loaded_models is read for its names, with no inventory to join them onto") + assert.JSONEq(t, `{"models":["llama3.2:1b"], + "modelsByEngine":{"fake":["llama3.2:1b"]}, + "loadedByEngine":{"fake":["llama3.2:1b"]}}`, string(mustMarshal(t, res)), + "and no downloaded key appears for an engine that advertises its inventory") + }) +} + +// mustMarshal is the payload as it goes on the wire, for a case whose whole point is +// that the whole payload has not moved. +func mustMarshal(t *testing.T, value any) []byte { + t.Helper() + + body, err := json.Marshal(value) + require.NoError(t, err) + return body +} + // An engine whose advertised list is its inventory reports nothing apart. func TestModelsResult_OmitsDownloadedForAnEngineThatAdvertisesItsList(t *testing.T) { ex := newTestExecutor(t, loadedActionManifest()) diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 1f40530bd..27ac5c32f 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -499,6 +499,12 @@ type ActionResult struct { // model it loaded as "root" (its --model): peers and the proxy are told the // id, and the loaded marker on the model list uses the root. InventoryField string `json:"inventory_field,omitempty"` + // Residency, when set, declares how to join the answer this spec extracts + // onto the pack that answer sits in. Only loaded_models may declare it: the + // join starts from what is being served, and it is only worth making for an + // engine that serves one whole pack at a time, where "what is served" and + // "what is cached" are two different questions with two different answers. + Residency *ActionResidency `json:"residency,omitempty"` } // ResultMatch is the optional row filter on an ActionResult. Exactly one of @@ -513,6 +519,44 @@ type ResultMatch struct { Nonempty bool `json:"nonempty,omitempty"` // true → Field must be a nonempty JSON array } +// ActionResidency is the residency-declaration block inside an ActionResult (see +// ActionResult.Residency, which a manifest writes as `result.residency`): where PAIR +// reads the engine's pack inventory, where it reads what the engine is serving, and +// which field carries the path in each. +// +// A loaded answer is only a name until something joins it to a place. MTPLX names +// the model it serves "mtplx-flash-next-optimized-speed", keeps that pack in a +// directory called Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed, and calls +// the same thing Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed when it lists +// the cache; the /health answer carries the directory under "model_path". With +// those three names treated as one, a request for any model sharing a prefix reads +// as the model being served, so the join is declared per engine and checked at +// manifest load rather than guessed from a name at request time. +type ActionResidency struct { + // Source names the action whose response carries the pack rows. For MTPLX + // that is list_models, which reads the cache directory and needs no running + // engine. + Source string `json:"source"` + // Read, when set, is where the loaded model's path is answered, for an engine + // that reports it separately from the name it serves. It is declared apart + // from the action's own HTTP call because the two are different questions: + // loaded_models asks what is served, this is where the answer says it lives. + // Left unset, there is no declared place to ask, and residentPack answers + // unknown rather than going looking anyway. + Read *ActionHTTP `json:"read,omitempty"` + // PathField is the field in the read answer that names the loaded pack's + // directory, and RowPathField is the field on each inventory row that names + // the directory that pack sits in. The two are joined by exact string + // comparison (see packRowForKey), so both have to be named rather than + // inferred from whatever else the response happens to carry. + PathField string `json:"path_field"` + RowPathField string `json:"row_path_field"` + // RowKeyField names the field on each inventory row that keys it, for an + // engine whose rows are not keyed on the inventory's own field. Empty means + // the source action's result.field is the key. + RowKeyField string `json:"row_key_field,omitempty"` +} + // ActionRemovePath deletes a filesystem path declared in the manifest. // Path and Root are templated; the resolved target must stay under Root. type ActionRemovePath struct { @@ -982,6 +1026,29 @@ func (m *Manifest) Validate() error { } } } + if a.Result != nil && a.Result.Residency != nil { + // Both halves of the join have to exist. A residency block naming an + // action this manifest does not declare, or one whose answer carries no + // declared field to read rows out of, reads as an engine with nothing + // cached — the exact wrong answer the block is here to prevent. + source, ok := m.Actions[a.Result.Residency.Source] + if !ok { + return fmt.Errorf("action %q: result.residency.source %q is not an action this manifest declares", name, a.Result.Residency.Source) + } + if source.Result == nil { + return fmt.Errorf("action %q: result.residency.source %q declares no result, so there are no pack rows to read from it", name, a.Result.Residency.Source) + } + // A residency source is read every time PAIR asks what an engine is + // serving, including while that engine is running, so it has to be + // something that only looks. stop_engine, restart_after and launch_model + // each take the engine down or re-tune it, and any of them on the source + // would make answering a question about a pack stop, restart or re-launch + // the engine that holds it. Nothing bundled does that today; the rule is + // here so a manifest cannot add the path later. + if source.StopEngine || source.RestartAfter || source.LaunchModel != nil { + return fmt.Errorf("action %q: result.residency.source %q stops, restarts or relaunches the engine, and a residency lookup must only read", name, a.Result.Residency.Source) + } + } } if m.AdvertisedModels == advertisedModelsAvailable { action, ok := m.Actions["list_models"] @@ -1381,6 +1448,11 @@ func (a *Action) validate(name string) error { return fmt.Errorf("action %q: result.match requires exactly one of a non-empty in or nonempty=true", name) } } + if a.Result != nil && a.Result.Residency != nil { + if err := a.Result.Residency.validate(name); err != nil { + return err + } + } if a.ModelResolution != "" { switch a.ModelResolution { case modelResolutionLMSGet: @@ -1401,6 +1473,41 @@ func (a *Action) validate(name string) error { return nil } +// validate checks a residency declaration that can be judged from the declaring +// action alone: which action may carry one, and whether the three names the join +// needs are actually there. Whether Source names an action this manifest declares, +// and whether that action has rows to read, is checked by Manifest.Validate, where +// both actions are visible. +func (r *ActionResidency) validate(name string) error { + if name != "loaded_models" { + return fmt.Errorf("action %q: result.residency belongs to loaded_models, which is the action that answers what is being served", name) + } + if strings.TrimSpace(r.Source) == "" { + return fmt.Errorf("action %q: result.residency.source is required: it names the action whose answer carries the pack rows", name) + } + if r.Source == name { + return fmt.Errorf("action %q: result.residency.source must name another action: the one that says what is served has no rows to look a pack up in", name) + } + if r.Read != nil && (strings.TrimSpace(r.Read.Method) == "" || strings.TrimSpace(r.Read.Path) == "") { + return fmt.Errorf("action %q: result.residency.read must give both a method and a path", name) + } + for _, field := range []struct{ key, value string }{ + {"path_field", r.PathField}, + {"row_path_field", r.RowPathField}, + } { + if strings.TrimSpace(field.value) == "" { + return fmt.Errorf("action %q: result.residency.%s is required, and must name a field rather than be guessed from the answer", name, field.key) + } + if !resultFieldNameRe.MatchString(field.value) { + return fmt.Errorf("action %q: result.residency.%s %q is not a valid field name", name, field.key, field.value) + } + } + if r.RowKeyField != "" && !resultFieldNameRe.MatchString(r.RowKeyField) { + return fmt.Errorf("action %q: result.residency.row_key_field %q is not a valid field name", name, r.RowKeyField) + } + return nil +} + // validatePlaceholders rejects any `{token}` outside the placeholders // available to the platform or manifest-global action that contains it. func (m *Manifest) validatePlaceholders() error { diff --git a/services/nvpair-engine-manager/residency.go b/services/nvpair-engine-manager/residency.go new file mode 100644 index 000000000..175db215d --- /dev/null +++ b/services/nvpair-engine-manager/residency.go @@ -0,0 +1,367 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "strconv" + "strings" + "time" +) + +// packRow is one model pack as the engine's own inventory reports it: the name it +// calls the pack, and the directory that holds it. +// +// Both are carried because neither one alone identifies a pack. One MTPLX answers +// /health with "mtplx-flash-next-optimized-speed" while its own listing calls the +// same pack "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" and keeps it in a +// directory spelled with a double dash; a second machine caches three packs under a +// different root, with the first machine's root sitting there empty. A name alone +// cannot tell those apart, and a path alone cannot be checked against what a request +// named, so a lookup that keeps only one of them eventually has to guess. +type packRow struct { + repoID string + path string +} + +// residencyDeclaration is the join a manifest declared on its loaded_models action, +// or nil when the manifest declares no join at all — which is the same as an engine +// whose packs PAIR cannot identify, not an engine with nothing cached. +// +// It hangs off loaded_models because that is the only action a manifest may declare a +// residency on: ActionResidency.validate refuses it elsewhere, on the grounds that the +// residency question is about whatever is being served. +func residencyDeclaration(st *engineState) *ActionResidency { + loaded, ok := st.manifest.Actions["loaded_models"] + if !ok || loaded.Result == nil { + return nil + } + return loaded.Result.Residency +} + +// inventoryAnswer is one read of an engine's inventory, kept whole and named by the +// action it came from, so a caller that needs two things out of one listing — the names +// it carries and the one row a running engine has mapped — asks the engine once. +// +// Naming the action is what keeps the reuse honest: an answer is reusable for a join +// only when it is the answer that join was declared against. +type inventoryAnswer struct { + action string + raw json.RawMessage + // names and namesOK are what one spec found in raw, for a reader that asked for + // names on its way through. A reader that only has the body leaves them zero. + names []string + namesOK bool + // read says there is an answer here at all, which is the question a join asks + // before it reuses a body instead of reading the engine again. + read bool +} + +// packInventory reads what an engine holds on disk, in the engine's terms, for an +// engine that serves one model at a time and can only be asked what it is running. +// It is how PAIR finds out which pack a running engine loaded: the answer to the +// engine's own loaded-path question is joined onto the rows read here (see +// residentPack), so a model name is not mistaken for a model just because they are +// spelled alike. +// +// The second result separates what an engine's cache holds from what PAIR managed to +// find out, because they lead to different advice. ok=false means the inventory was +// not read: the source action failed, its answer was not a listing, or it was larger +// than the body PAIR reads. ok=true with no rows is the answer "nothing is cached", so +// the two are never collapsed into each other. +// +// A caller that has already read the listing this join is declared against hands it in +// rather than running it a second time: see packInventoryFrom and inventoryAnswer. +func (e *Executor) packInventory(ctx context.Context, engine string) ([]packRow, bool) { + return e.packInventoryFrom(ctx, engine, inventoryAnswer{}) +} + +// packRowLookup is where one action's answer keeps its pack rows: which array holds +// them, which field keys a row, and which field says where that pack sits. It is a +// recipe rather than three loose arguments because two of the three are field names in +// the same answer, and a join that read a row's key out of its path field would fail as +// quietly as it succeeded. +type packRowLookup struct { + array string + keyField string + pathField string +} + +// packRowLookupFor reads that recipe off the action carrying the rows and the join +// declared on it. +func packRowLookupFor(listing *ActionResult, residency *ActionResidency) packRowLookup { + keyField := residency.RowKeyField + if keyField == "" { + // The rows are keyed on whatever the listing is keyed on, which is why + // row_key_field is usually not written at all. + keyField = listing.Field + } + return packRowLookup{array: listing.Array, keyField: keyField, pathField: residency.RowPathField} +} + +// rowsFrom turns one action's answer into rows, or says it could not. +// +// The size limit is checked on every answer, including one handed over by a caller, +// because the action machinery lets a bigger body through (8 MiB for an HTTP action, +// all of stdout for a cmd one), and a listing that was cut off names some of the packs +// and silently omits the rest — including, possibly, the one being asked about. +func (l packRowLookup) rowsFrom(engine, action string, raw json.RawMessage) ([]packRow, bool) { + if len(raw) > maxProbeJSONBytes { + slog.Debug("engine:residency inventory was larger than PAIR reads", "engine", engine, "action", action, "bytes", len(raw)) + return nil, false + } + rows, ok := extractPackRows(raw, l.array, l.keyField, l.pathField) + if !ok { + slog.Debug("engine:residency inventory was not a readable listing", "engine", engine, "action", action) + } + return rows, ok +} + +// packInventoryFrom reads the pack rows packInventory reads, reusing an answer the +// caller has already got when it came from the action this join was declared against, +// and reading that action itself otherwise. +// +// Reuse is not a shortcut past a read the engine would rather not do twice: it is one +// question about one fact, and for MTPLX the read is `mtplx models --json` — a +// subprocess, carrying the action timeout with it, rather than a request bounded by the +// residency probe's 3 s. Rows from any other action are not the rows the join was +// declared against, so a join that names another source gets its own read, and the +// listing the sweep read is still read only once. +// +// The read runs through the action machinery, so it takes the action timeout with +// it. Whether an engine answers at all is the source action's business: HTTP actions +// are gated on a running engine and cmd actions deliberately are not (see +// dispatchAction), which is why MTPLX's manifest describes its `mtplx models --json` +// read as needing no running engine. So "the read failed" is not the same statement +// as "the engine is down" — and the fixture's HTTP stand-in answers less than a +// stopped MTPLX would. +// +// What is this function's business is keeping the lookup a lookup: a residency +// source that also declared stop_engine, restart_after or launch_model would turn a +// read into a stop, a restart or a launch-settings rewrite, so Manifest.Validate +// rejects that manifest at load instead of a runtime branch declining to obey it. +func (e *Executor) packInventoryFrom(ctx context.Context, engine string, already inventoryAnswer) ([]packRow, bool) { + st, err := e.state(engine) + if err != nil { + return nil, false + } + residency := residencyDeclaration(st) + if residency == nil { + return nil, false + } + source, ok := st.manifest.Actions[residency.Source] + if !ok || source.Result == nil { + return nil, false + } + rows := packRowLookupFor(source.Result, residency) + if already.read && already.action == residency.Source { + return rows.rowsFrom(engine, residency.Source, already.raw) + } + + raw, err := e.Action(ctx, engine, residency.Source, nil) + if err != nil { + slog.Debug("engine:residency inventory read failed", "engine", engine, "action", residency.Source) + return nil, false + } + return rows.rowsFrom(engine, residency.Source, raw) +} + +// packRowForKey finds the row holding the pack at exactly this path. +// +// The comparison is exact: no case folding, no separator rewriting, no stripping a +// leading /private, no symlink resolution. That is deliberate. MTPLX keys its own +// records by more than one spelling of the same pack — the served name, the repo id, +// and the directory name differ on a single machine — and the two Macs measured keep +// their packs under different roots, one of them with the other's root present and +// empty. Normalising a path here would merge rows the engine itself keeps apart, on +// a filesystem that already folds case and would let the wrong one read as found. +func packRowForKey(rows []packRow, path string) (packRow, bool) { + for _, row := range rows { + if row.path == path { + return row, true + } + } + return packRow{}, false +} + +// residentPack answers which pack a running engine has mapped, as the inventory row +// the engine itself gives for it. +// +// It is a join rather than a read, because the two halves answer different questions +// in different spellings and only one of them needs a running server: packInventory +// reads what the cache holds, which for MTPLX is a CLI read that works with the +// engine stopped, and the residency read says which directory the running server +// loaded. Where those agree — one directory, string for string — PAIR has a pack it +// can name, locate and act on. Where they do not, it has one or the other and has to +// say so rather than choose. +// +// The second result is false for every case where PAIR does not know, and it is never +// the answer "nothing is resident". Nothing here could mean that: an engine that +// serves exactly one pack has to be running to have one, and each false case — no +// engine running, no read declared to ask it by, an answer that never arrived or was +// larger than PAIR reads, an answer from something that is not the engine, a directory +// no row holds — leaves what is loaded genuinely open. Reporting the empty answer +// would move a pack from loaded to not loaded on the strength of a request that +// failed, which is the same mistake as naming the wrong row, travelling the other +// way. +// +// Nothing is cached: each half is read once per call, which makes a call two reads +// rather than the one its signature suggests. They are not alike in what they cost, +// and the difference is what a caller has to plan around. The first is the probe read +// — 3 s, against a server that is answering — for where the model was loaded from. +// The second is the inventory that answer joins against: it runs through the action +// machinery, so it carries the action timeout with it (30 minutes, not 3 s), and for +// MTPLX it is a `mtplx models --json` subprocess rather than a request. That is why the +// join takes an inventory answer it did not read itself (see residentPackFrom): the +// model sweep has that listing in hand for its rows, and one sweep should run the CLI +// once. A caller that wants the row together with the served names it pairs with is +// paying three reads, not the two this join makes: asked once per row of a listing, +// this starts one CLI run per row. Re-reading is correct because an engine changes what +// it has mapped only across a load or an eject — both of which PAIR drives itself. +// Correct is not the same as cheap. +func (e *Executor) residentPack(ctx context.Context, engine string) (packRow, bool) { + return e.residentPackFrom(ctx, engine, inventoryAnswer{}) +} + +// residentPackFrom is residentPack for a caller that has already read the inventory the +// join joins against. The answer is reused only when it came from the action the join +// names; anything else, including no answer at all, reads that action once. +func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventory inventoryAnswer) (packRow, bool) { + st, err := e.state(engine) + if err != nil { + return packRow{}, false + } + residency := residencyDeclaration(st) + if residency == nil { + return packRow{}, false + } + if residency.Read == nil { + // The manifest has not said where this engine answers where its model lives, + // so it cannot be asked, and there is no second place worth guessing at. An + // engine that carried the path inside its loaded_models answer would need + // that declared, not inferred from whatever that answer happens to hold. + slog.Debug("engine:residency no loaded-path read declared", "engine", engine) + return packRow{}, false + } + st.mu.Lock() + running, port := st.running, st.port + st.mu.Unlock() + if !running { + // A clean unknown, not an error, and nothing asked. The join's second half + // needs a server; the first half is readable right now, which is exactly why + // the answer cannot be read off it — rows that exist on disk say nothing + // about which of them a stopped process has mapped. + return packRow{}, false + } + + // The loaded path is asked first: one bounded GET against the server that is + // answering, while the inventory may be a CLI run. Finding out that an engine + // says nothing about its own model should not cost a subprocess. + loadedPath, ok := e.loadedPackPath(ctx, engine, port, residency) + if !ok { + return packRow{}, false + } + rows, ok := e.packInventoryFrom(ctx, engine, inventory) + if !ok { + return packRow{}, false + } + row, found := packRowForKey(rows, loadedPath) + if !found { + // The engine has a directory mapped that its own listing does not name: a + // pack handed over as a pair bundle, a cache that moved, a pack deleted from + // under a server still serving it. That is a real served thing, and no row + // here may stand in for it — the pack this machine does cache, shown as + // loaded, is how an eject or a delete ends up aimed at the wrong directory. + slog.Debug("engine:residency loaded path matched no cached pack", "engine", engine, "rows", len(rows)) + return packRow{}, false + } + return row, true +} + +// loadedPackPath asks a running engine which directory it loaded its model from, at +// the answer its manifest named (ActionResidency.Read) and in the field it named +// there (PathField). +// +// The read is the one every probe answer is read under — 3 s bound, the +// maxProbeJSONBytes cap, drain-and-close on every path — because this is a health +// check being asked one more question, and two bounds on the same request are two +// chances to disagree about whether an engine is answering. The cap is why a body +// bigger than PAIR reads answers unknown rather than half-parsed: readProbeBody +// returns no body at all for an answer it could not read whole, so there is nothing +// here to mistake for a partial answer. +// +// No status code is consulted, deliberately: the field is the evidence, and an answer +// that names a loaded path is an engine talking about its model whatever it arrived +// with. An error answer that names none is unknown like every other non-answer. +func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, residency *ActionResidency) (string, bool) { + path, err := resolvePlaceholders(residency.Read.Path, map[string]string{"port": strconv.Itoa(port)}) + if err != nil { + slog.Debug("engine:residency loaded-path read names an unresolvable path", "engine", engine, "path", residency.Read.Path) + return "", false + } + requestURL := fmt.Sprintf("http://127.0.0.1:%d%s", port, path) + pctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(pctx, strings.ToUpper(residency.Read.Method), requestURL, nil) + if err != nil { + return "", false + } + // The probe marker, so PAIR's own facade answers this itself instead of + // forwarding a residency read through to whatever it fronts. + req.Header.Set(engineIdentityProbeHeader, "1") + resp, err := e.client.Do(req) + if err != nil { + slog.Debug("engine:residency loaded-path read failed", "engine", engine, "path", path) + return "", false + } + body := readProbeBody(resp.Body) + if body == "" { + // Either nothing arrived or more arrived than PAIR reads; readProbeBody + // answers both with no body, and the join does not care which it was. + slog.Debug("engine:residency loaded-path answer was empty or larger than PAIR reads", "engine", engine, "path", path) + return "", false + } + var obj map[string]json.RawMessage + if err := json.Unmarshal([]byte(body), &obj); err != nil { + slog.Debug("engine:residency loaded-path answer was not a JSON object", "engine", engine, "path", path, "bytes", len(body)) + return "", false + } + value, ok := resolveObjectPath(obj, residency.PathField) + if !ok { + slog.Debug("engine:residency loaded-path answer named no loaded path", "engine", engine, "path", path, "field", residency.PathField) + return "", false + } + var loaded string + if err := json.Unmarshal(value, &loaded); err != nil || loaded == "" { + slog.Debug("engine:residency loaded-path answer held no path PAIR can read", "engine", engine, "path", path, "field", residency.PathField) + return "", false + } + return loaded, true +} + +// servedNames answers what an engine answers requests as, in the names a request +// would use: for MTPLX "mtplx-flash-next-optimized-speed", where its own inventory +// calls the same pack Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed. +// +// It is the read the model list already makes, offered next to residentPack for a +// caller that needs both halves of one answer: the row is what a cached pack's eject +// or delete acts on, and the served name is what a request has to be routed by, so +// neither can be derived from the other and a caller showing both has to have both. +// ok is false when the engine did not answer or answered with something that is not +// a listing — which, like residentPack's false, is not "it serves nothing". +func (e *Executor) servedNames(ctx context.Context, engine string) ([]string, bool) { + st, err := e.state(engine) + if err != nil { + return nil, false + } + loaded, ok := st.manifest.Actions["loaded_models"] + if !ok || loaded.Result == nil { + return nil, false + } + return e.queryModelList(ctx, engine, "loaded_models", loaded.Result) +} diff --git a/services/nvpair-engine-manager/residency_test.go b/services/nvpair-engine-manager/residency_test.go new file mode 100644 index 000000000..8c1f01c50 --- /dev/null +++ b/services/nvpair-engine-manager/residency_test.go @@ -0,0 +1,1097 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The bodies in this file are measurements, not hand-written examples. +// +// sagittariusModelsBody is the `mtplx models --json` answer captured on the Mac +// that runs these tests: one cache root, /Users/Shared/mtplx/models, and one pack +// in it. A /health answer from the same round of probing reported that pack's +// directory verbatim while calling the served model +// "mtplx-flash-next-optimized-speed", and that pair is what the first test pins: +// the listing's `path` and the served model's `model_path` are one string, and the +// served name matches neither. bellatrixModelsBody is the second Mac's cache, +// re-expressed as a JSON body in the same envelope because that capture is a +// digest of its listing; its values (three packs, all under +// /Users/steven/.mtplx/models, one of them with no runtime contract and +// four-and-a-bit required files missing) are the measured ones. Nothing here is +// read from disk at test time and nothing here reaches a port, so both bodies keep +// working on a machine that never had MTPLX on it — which matters most for the +// path joins, since APFS is case-insensitive by default and a join that leaned on +// the filesystem would pass here for the wrong reason. + +const sagittariusModelsBody = `{ + "cache_dir": "/Users/Shared/mtplx/models", + "model_roots": ["/Users/Shared/mtplx/models"], + "models": [ + { + "delete_command": "mtplx remove Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", + "has_config": true, + "has_runtime_contract": true, + "is_primary": true, + "path": "/Users/Shared/mtplx/models/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", + "recommended_profile": "turbo", + "repo_id": "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", + "root": "/Users/Shared/mtplx/models", + "size_bytes": 115061262324, + "validation": { + "contract_present": true, + "missing_files": [], + "ok": true + } + } + ] +}` + +const bellatrixModelsBody = `{ + "cache_dir": "/Users/steven/.mtplx/models", + "model_roots": ["/Users/steven/.mtplx/models"], + "models": [ + { + "delete_command": "mtplx remove Youssofal/Gemma4-MTPLX-Optimized-Speed", + "has_runtime_contract": false, + "path": "/Users/steven/.mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed", + "repo_id": "Youssofal/Gemma4-MTPLX-Optimized-Speed", + "validation": { + "contract_present": false, + "missing_files": ["config.json", "tokenizer.json", "model.safetensors.index.json", "mtplx_runtime.json", "mtp sidecar"], + "ok": false + } + }, + { + "delete_command": "mtplx remove Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed", + "has_runtime_contract": true, + "path": "/Users/steven/.mtplx/models/Youssofal--Qwen3.5-4B-MTPLX-Optimized-Speed", + "recommended_profile": "sustained", + "repo_id": "Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed", + "validation": {"contract_present": true, "missing_files": [], "ok": true} + }, + { + "delete_command": "mtplx remove Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Speed-FP16", + "has_runtime_contract": true, + "path": "/Users/steven/.mtplx/models/Youssofal--Qwen3.6-35B-A3B-MTPLX-Optimized-Speed-FP16", + "recommended_profile": "sustained", + "repo_id": "Youssofal/Qwen3.6-35B-A3B-MTPLX-Optimized-Speed-FP16", + "validation": {"contract_present": true, "missing_files": [], "ok": true} + } + ] +}` + +// residencyInventoryPath is where the fixture's inventory read points. It is not +// a path MTPLX serves: the shipped manifest reads the cache with +// `mtplx models --json`, and a test cannot run that, so the same body arrives +// through an HTTP action. What is under test is the join, which does not care how +// the body arrived, only that it arrived whole. +const residencyInventoryPath = "/fixture/models" + +// residencyHealthPath and residencyServedPath are where the fixture answers the +// two questions about a running server: which directory it mapped, and what it +// answers to. Both are the paths the shipped manifest names. +const ( + residencyHealthPath = "/health" + residencyServedPath = "/v1/models" +) + +// residencyHealthBody is one MTPLX's /health answer, trimmed to the keys the join +// reads. The measured answer runs to 51,354 bytes, and what is missing here is +// machine telemetry — per-kernel ledgers, thermal history, environment reports — +// that PAIR never reads. Of the three keys, `ok` is how MTPLX says it is itself, +// `model` is the name it answers requests as, and `model_path` is the directory it +// loaded the pack from. Only the last joins to anything, and it joins because it is +// the same string the cache listing carries as a row path: one directory, two +// answers, and a served name that matches neither spelling. +// +// The measured size belongs to mtplxHealthBody in identity_test.go, which these +// cases do not need: what is under test here is which key the join reads, and the +// cases that turn on it differ only in the directory named. +func residencyHealthBody(modelPath string) string { + return `{"ok":true,"model":"` + mtplxServedModel + `","model_path":"` + modelPath + `"}` +} + +// residencyOversizedHealthBody is that same answer wearing a filler field large +// enough that PAIR cannot read it whole. The action machinery lets an 8 MiB HTTP +// body through, so a two-megabyte answer arrives intact at the reader's door: the +// only thing standing between it and a half-parsed pack identity is the cap the +// probe read puts on a body. +func residencyOversizedHealthBody(t *testing.T) string { + t.Helper() + + pad := strings.Repeat("f", 2*maxProbeJSONBytes) + body := strings.TrimSuffix(residencyHealthBody(mtplxServedPath), "}") + `,"filler":"` + pad + `"}` + require.Greater(t, len(body), 2*maxProbeJSONBytes, + "the case has to be a body larger than PAIR reads, or it proves nothing about the cap") + return body +} + +// residencyServedBody is the same server's answer to its loaded_models read: the +// served name in the array and field the manifest declares. The name is not a pack, +// not a row key and not a path, which is the whole reason residency is declared +// rather than guessed from the answer this body carries. +const residencyServedBody = `{"data":[{"id":"` + mtplxServedModel + `"}]}` + +// residencyForeignBody is what a web app with history-api fallback answers every +// path with, /health included: its own bundle. The identity probe already refuses to +// call such a listener this engine; the join has to refuse to read a loaded path out +// of it as well, rather than finding `model_path` wherever a parser might. +const residencyForeignBody = `MTPLX
` + +// residencyPairBundlePath is a directory the server really has mapped and really is +// serving, sitting under a root the cache listing never walks — where a pair bundle +// handed straight to the server lands — and its last element is the folder name of +// the pack the listing does hold. Those two together are why the case is worth +// having: a join that fell back on the served name, on a path prefix, or on "there is +// only one row" answers it with the wrong pack, and every other case here would still +// pass. +const residencyPairBundlePath = "/Users/Shared/mtplx/pairs/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" + +// residencyStubTransport answers the fixture's reads. Anything it was not told +// about is an error rather than a real request, because the machine running these +// tests may have a live MTPLX on some port, and no test may ask it a question and +// then take the answer as a fact about the fixture. +func residencyStubTransport(bodies map[string]string) http.RoundTripper { + return roundTripFunc(func(r *http.Request) (*http.Response, error) { + body, ok := bodies[r.URL.Path] + if !ok { + return nil, fmt.Errorf("residency fixture got a request for %s, which it did not declare", r.URL.Path) + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + }, nil + }) +} + +// residencyAsking builds an engine that is running on a port with nothing behind +// it and answers exactly the reads named in bodies. An empty map is how "the +// engine answered nothing" is staged. +func residencyAsking(t *testing.T, manifest *Manifest, bodies map[string]string) *Executor { + t.Helper() + + ex := newTestExecutor(t, manifest) + residencyMarkRunning(t, ex, manifest.Engine) + ex.client.Transport = residencyStubTransport(bodies) + return ex +} + +// residencyMarkRunning says the engine is up. It is separate from residencyAsking +// because two cases set the transport themselves — one because it has to record the +// questions, one because the whole point is that the engine is *not* running — and a +// residency answer that quietly defaulted to "stopped" would make every unknown in +// this file pass for the wrong reason. +func residencyMarkRunning(t *testing.T, ex *Executor, engine string) { + t.Helper() + + st, err := ex.state(engine) + require.NoError(t, err) + st.mu.Lock() + st.running = true + st.mu.Unlock() +} + +// residencyAskedAbout is residencyAsking plus the record of every question that was +// really asked, for the cases whose answer has to be reached without asking: an +// engine that cannot be asked is answered by not asking it. +func residencyAskedAbout(t *testing.T, manifest *Manifest, bodies map[string]string, asked *[]residencyAsk) *Executor { + t.Helper() + + ex := residencyAsking(t, manifest, bodies) + ex.client.Transport = residencyRecordingTransport(bodies, asked) + return ex +} + +// residencyAsk is one question PAIR really put to an engine: the host:port and path +// it asked, how long it gave the answer, and whether the identity-probe marker went +// with it. All three are needed, because each is a mistake that still produces an +// answer that looks right. The target shows a server met on a port PAIR did not +// choose being asked there rather than at the port the manifest would have preferred. +// The marker shows the question went as a probe, which is how PAIR's own facade knows +// to answer for itself instead of forwarding the read to whatever it fronts. And the +// bound is the only part of "this read cannot hang a status refresh" that a stubbed +// answer cannot show on its own: a stub answers instantly, so the request has to +// carry the deadline. +type residencyAsk struct { + target string + probe string + bound time.Duration +} + +func (a residencyAsk) String() string { + return fmt.Sprintf("%s probe=%q bound=%s", a.target, a.probe, a.bound) +} + +func residencyRecordingTransport(bodies map[string]string, asked *[]residencyAsk) http.RoundTripper { + inner := residencyStubTransport(bodies) + return roundTripFunc(func(r *http.Request) (*http.Response, error) { + ask := residencyAsk{ + target: r.URL.Host + r.URL.Path, + probe: r.Header.Get(engineIdentityProbeHeader), + } + if deadline, ok := r.Context().Deadline(); ok { + ask.bound = time.Until(deadline) + } + *asked = append(*asked, ask) + return inner.RoundTrip(r) + }) +} + +// residencyManifest mirrors what manifests/mtplx.json declares about a MTPLX, +// with the two paths the fixture answers. The real manifest reads the cache with +// a CLI action; a hand-built manifest says "an HTTP GET" instead so the test runs +// on a host with no MTPLX, and its port is one nothing is listening on because +// the fixture answers without dialling. +func residencyManifest(t *testing.T) *Manifest { + t.Helper() + + return &Manifest{ + Engine: "mtplx", + DisplayName: "MTPLX (fixture)", + ManifestVersion: ManifestSchemaVersion, + AdvertisedModels: advertisedModelsLoaded, + Platforms: map[string]Platform{ + hostPlatformKey(): { + Detect: []string{os.DevNull}, + Runtime: Runtime{ + // A path need not exist to be a legal manifest, and nothing here + // launches it. It is set because Manifest.Validate checks the + // platform before the actions, and a fixture that stops there + // would never reach the residency rules it is meant to be + // testing. + Bin: filepath.Join(t.TempDir(), "mtplx"+exeExt()), + Port: portRun(t, 1)[0], + }, + }, + }, + Actions: map[string]Action{ + "list_models": { + HTTP: &ActionHTTP{Method: "GET", Path: residencyInventoryPath}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + }, + "loaded_models": { + HTTP: &ActionHTTP{Method: "GET", Path: residencyServedPath}, + Result: &ActionResult{ + Array: "data", + Field: "id", + Residency: &ActionResidency{ + Source: "list_models", + Read: &ActionHTTP{Method: "GET", Path: residencyHealthPath}, + PathField: "model_path", + RowPathField: "path", + }, + }, + }, + }, + } +} + +// residencyManifestWithRestart is the fixture with the runtime keys that +// restart_after and launch_model each demand on their own: a readiness probe, and +// editable launch settings. The mutating-source test needs them. Without them +// Manifest.Validate fails on the platform first, and a case would pass without ever +// reaching the residency rule it is there to pin down. +func residencyManifestWithRestart(t *testing.T) *Manifest { + t.Helper() + + manifest := residencyManifest(t) + platform := manifest.Platforms[hostPlatformKey()] + platform.Runtime.Ready = &Probe{HTTP: "http://127.0.0.1:{port}/health", Status: 200} + platform.Runtime.EditableLaunch = &EditableLaunch{ + FixedArgs: []string{"serve"}, + Controls: []LaunchControl{ + {Flags: []string{"--host"}, Value: "{server.host}"}, + {Flags: []string{"--port"}, Value: "{server.port}"}, + }, + } + manifest.Platforms[hostPlatformKey()] = platform + return manifest +} + +func TestPackInventory_ReadsRowsFromTheMeasuredModelsListing(t *testing.T) { + ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: sagittariusModelsBody}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + require.True(t, ok, "the listing arrived whole, so the inventory is known") + require.Len(t, rows, 1, "that capture holds one pack") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", rows[0].repoID, "repo id") + assert.Equal(t, "/Users/Shared/mtplx/models/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", rows[0].path, "pack directory") + + const servedPath = "/Users/Shared/mtplx/models/Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" + row, found := packRowForKey(rows, servedPath) + require.True(t, found, "the path this MTPLX answered with its /health must join to its own row") + assert.Equal(t, rows[0].repoID, row.repoID, "a join that lands on the wrong row is worse than no join") + + // The same engine spells one pack three ways: /health says it serves + // "mtplx-flash-next-optimized-speed", the inventory names the pack + // "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", and the directory + // holds a third spelling. Only the second is a row key and only the third is + // a path, so the other two have to find nothing here. + _, found = packRowForKey(rows, "mtplx-flash-next-optimized-speed") + assert.False(t, found, "a served name is not a pack path") + + // Case only matters because the filesystem under it ignores it: a join that + // folded case would find this pack on a Mac and then look in the wrong place, + // which is how a pack that is merely cached starts being reported as the one + // being served. + _, found = packRowForKey(rows, strings.ToUpper(servedPath)) + assert.False(t, found, "the join is exact, so an upper-cased spelling finds nothing") +} + +func TestPackInventory_KeepsTwoRootsApartAndNeverGuessesASymlink(t *testing.T) { + ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: bellatrixModelsBody}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + require.True(t, ok, "the listing arrived whole, so the inventory is known") + require.Len(t, rows, 3, "that machine caches three packs") + require.Equal(t, "/Users/steven/.mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed", rows[0].path, "Gemma4") + assert.Equal(t, "Youssofal/Gemma4-MTPLX-Optimized-Speed", rows[0].repoID, "Gemma4") + + // Gemma4 is in the listing with no runtime contract, no config.json, no + // tokenizer.json, no weights index and no MTP sidecar, so loading it fails. + // It is still a row: residency answers where a pack sits, and a cache entry + // that fails its own check is a fact about the disk, not a gap in the + // inventory. + row, found := packRowForKey(rows, "/Users/steven/.mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed") + require.True(t, found, "an unloadable pack is still cached, so it is still a row") + assert.Equal(t, "Youssofal/Gemma4-MTPLX-Optimized-Speed", row.repoID) + + const servedQwen35 = "/Users/steven/.mtplx/models/Youssofal--Qwen3.5-4B-MTPLX-Optimized-Speed" + _, found = packRowForKey(rows, servedQwen35) + require.True(t, found, "this is the pack that machine was serving") + + // Two roots, kept apart. The machine that caches these packs keeps everything + // under the first one and reports the second as holding nothing, so both + // prefixes look plausible on that host. A join that trimmed the root, or tried + // "the other root" when a path missed, would answer a query about a directory + // holding no pack with the pack sitting in the one that does. + for _, other := range []string{ + "/Users/Shared/mtplx/models/Youssofal--Qwen3.5-4B-MTPLX-Optimized-Speed", + "/Users/Shared/mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed", + } { + _, found := packRowForKey(rows, other) + assert.False(t, found, "a query under the other root must not land on a pack in this one (%s)", other) + } + + // macOS answers /var and /tmp under /private as well, so a path can reach + // PAIR spelled either way. Nothing here resolves that: a query with the + // prefix is a different string from the row, and guessing that the two name + // the same file is how one pack gets credited for another. + _, found = packRowForKey(rows, "/private"+servedQwen35) + assert.False(t, found, "a leading /private is not trimmed") + + _, found = packRowForKey(rows, servedQwen35+"/") + assert.False(t, found, "a trailing separator is not trimmed either") +} + +func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *testing.T) { + manifest := residencyManifest(t) + + t.Run("an empty cache is an answer", func(t *testing.T) { + ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: `{"models":[]}`}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + require.True(t, ok, "a listing that says nothing cached was still read") + assert.Empty(t, rows, "nothing cached has to stay distinguishable from nothing read") + }) + + t.Run("a listing with no usable row is not an empty cache", func(t *testing.T) { + // A non-empty `models` array whose rows name nothing is a listing PAIR + // cannot read, not a cache full of packs that went missing. + ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: `{"models":[{"foo":1},{"bar":2}]}`}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "a malformed inventory must not become authoritative empty") + assert.Nil(t, rows) + }) + + t.Run("no models array at all was not read", func(t *testing.T) { + for _, body := range []string{`{}`, `{"models":null}`, `{"models":"Youssofal/Gemma4-MTPLX-Optimized-Speed"}`} { + ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: body}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "a body that carries no inventory is unknown (%s)", body) + assert.Nil(t, rows) + } + }) + + t.Run("a body larger than PAIR reads is not a partial list", func(t *testing.T) { + pad := strings.Repeat("f", 4096) + body := `{"models":[` + strings.Repeat(`{"repo_id":"org/pad","path":"/var/folders/pad","filler":"`+pad+`"},`, 300) + `{"repo_id":"Youssofal/Gemma4-MTPLX-Optimized-Speed","path":"/Users/steven/.mtplx/models/Youssofal--Gemma4-MTPLX-Optimized-Speed"}]}` + require.Greater(t, len(body), maxProbeJSONBytes, "the fixture has to be past the cap to test it") + + ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: body}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "a truncated listing must not report the packs it happened to hold") + assert.Nil(t, rows) + }) + + t.Run("an engine that answers nothing was not read", func(t *testing.T) { + // The stub errors on any path it was not told about, which is how + // "the read did not happen" is staged. + ex := residencyAsking(t, manifest, map[string]string{}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "no answer is not an empty cache") + assert.Nil(t, rows) + }) + + t.Run("a fixture whose inventory read is refused while the engine is stopped", func(t *testing.T) { + // No running engine means the read is never attempted here: the shared + // dispatcher refuses an HTTP action while the engine is down, and this + // fixture carries its inventory read as an HTTP action. That is the fixture + // talking, not MTPLX: the shipped manifest reads the cache with + // `mtplx models --json`, a cmd action the dispatcher deliberately does not + // gate on a running engine, so a stopped MTPLX is expected to answer and a + // stopped fixture is not. What both agree on is the answer PAIR gives when + // the read does not happen: unknown, not empty. + ex := newTestExecutor(t, manifest) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "a refused read cannot have produced rows") + assert.Nil(t, rows) + }) + + t.Run("an engine that declares no join has no rows", func(t *testing.T) { + withoutResidency := residencyManifest(t) + loaded := withoutResidency.Actions["loaded_models"] + loaded.Result.Residency = nil + withoutResidency.Actions["loaded_models"] = loaded + ex := residencyAsking(t, withoutResidency, map[string]string{residencyInventoryPath: sagittariusModelsBody}) + + rows, ok := ex.packInventory(t.Context(), "mtplx") + + assert.False(t, ok, "no declared join means nothing was read, not that nothing is cached") + assert.Nil(t, rows) + }) +} + +func TestResidentPack_JoinsHealthModelPathWithTheCacheRow(t *testing.T) { + // One running server, three questions: what does your cache hold, which + // directory did you map, and what do you answer requests as. The join is the + // first two meeting, and the third must not be folded in with them: the row is + // the spelling a cached pack's eject or delete can act on, and the served name + // is what a request still has to be routed by. + ex := residencyAsking(t, residencyManifest(t), map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + residencyServedPath: residencyServedBody, + }) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + require.True(t, ok, "the directory this server mapped is a pack the cache lists, so the resident pack is known") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", row.repoID, + "the answer is the cache's own spelling of the pack, not the name the server answers to") + assert.Equal(t, mtplxServedPath, row.path, + "the row comes back whole: a caller that has to show or remove the directory needs it") + + names, namesOK := ex.servedNames(t.Context(), "mtplx") + + require.True(t, namesOK, "the same server also answers what it answers to") + assert.Equal(t, []string{"mtplx-flash-next-optimized-speed"}, names, + "the wire name survives the join; reporting only the repo id would leave PAIR with a name no request uses") + require.NotEmpty(t, row.repoID) + assert.NotEqual(t, row.repoID, names[0], + "had the two come back the same, one of them would have been guessed from the other rather than read") +} + +func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) { + // Every case here is answered `false`, and `false` is the only right answer for + // four quite different reasons: nothing to ask, an answer too big to have read, + // an answer that is not the engine, and an answer that names a pack no row + // holds. They agree on one thing, which is what these subtests pin — none of + // them may mark a row loaded. For an engine that serves exactly one pack, the + // first wrong row is not a miss but a confident claim about a pack that is + // merely cached, and that is the mistake residency exists to prevent. + manifest := residencyManifest(t) + + t.Run("a stopped engine is answered without asking it anything", func(t *testing.T) { + // The fixture answers both reads, so a `false` here cannot come from + // nothing being there to find. It has to come from PAIR knowing a stopped + // engine answers neither, and asking nothing rather than collecting a + // refused dial as though it were an answer. + var asked []residencyAsk + ex := newTestExecutor(t, manifest) + ex.client.Transport = residencyRecordingTransport(map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + }, &asked) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "nothing is running, so which pack it would have mapped is unknown") + assert.Equal(t, packRow{}, row, "unknown must not arrive as an empty row that some caller reads as nothing resident") + assert.Empty(t, asked, "a stopped engine is not asked") + }) + + t.Run("a health answer bigger than PAIR reads was not read", func(t *testing.T) { + // The action machinery lets an 8 MiB HTTP body through, so a two-megabyte + // /health answer arrives whole at the reader's door. Reading the first + // megabyte of it and parsing what happened to land is how a pack that is + // only partly described starts being reported as the resident one, and + // there is nothing to crash on either: the answer is simply unknown. + ex := residencyAsking(t, manifest, map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyOversizedHealthBody(t), + }) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "a truncated health answer identifies no pack") + assert.Equal(t, packRow{}, row, "no row may be marked loaded from a body that was never read") + + rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + require.True(t, inventoryOK, "the cache listing still arrived, so the unknown answer is the health read's own") + assert.Len(t, rows, 1, "and it is not the unknown that emptied it") + }) + + t.Run("a health answer that is not a JSON object was not read", func(t *testing.T) { + // `residencyForeignBody` is a web app with history-api fallback answering + // every path, /health included, with its own bundle. The identity probe + // already refuses to call such a listener this engine; the join has to + // refuse to read a loaded path out of it as well, rather than finding + // `model_path` wherever a parser might. + ex := residencyAsking(t, manifest, map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyForeignBody, + }) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "an HTML body is not an engine's answer about its model") + assert.Equal(t, packRow{}, row, "no row may be marked loaded from a body that is not the engine's") + }) + + t.Run("a loaded path under no cache root matches no row", func(t *testing.T) { + // `residencyPairBundlePath` is a directory the server really has mapped and + // really is serving, sitting under a root the listing never walks — a pair + // bundle handed straight to the server — and its last element is the cached + // pack's own folder name. That combination is why this is the case no + // shortcut survives: a join that matched on the served name, on a path + // prefix, or on "there is only one row" answers here with the pack this + // machine caches, shown as loaded, and an eject or a delete aimed at it goes + // after the wrong directory. Unknown costs the user a loaded marker; a guess + // costs them their other pack. + ex := residencyAsking(t, manifest, map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(residencyPairBundlePath), + }) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "a path no row holds has no row to return") + assert.Equal(t, packRow{}, row, "the pack this machine does cache must not stand in for the one it is serving") + + rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + require.True(t, inventoryOK, "the listing was read, so the miss is the path's and not a failed read") + require.Len(t, rows, 1, "the one pack it holds is the pack this answer is not about") + }) +} + +func TestResidentPack_ReportsUnknownWhenOnlyATidiedPathWouldMatch(t *testing.T) { + // The join is exact string equality, and this pins it where the engine's answer + // arrives rather than only at the comparison. Every other path in these fixtures + // is already clean and single-slashed, so an extraction that tidied separators on + // its way to the comparison — `filepath.Clean`, or a trailing separator trimmed — + // would leave the whole suite passing while turning a near-miss into a join. A + // near-miss join is not a harmless loosening: the row it finds is the directory a + // later eject or delete acts on, and the pack a model list marks loaded. Folding + // the case is caught from the other side, by the join that has to succeed on the + // measured mixed-case path; what these two cases pin is that no separator is + // tidied away. + // + // Each case is staged so the tidied spelling really does find the row, because a + // reported path that missed under a normalising join as well would answer `false` + // for the wrong reason and pin nothing. + cases := []struct { + name string + // reported is the directory the running server answers with: the cached + // pack's own path, written with one piece of separator redundancy. + reported string + // tidied is what taking that redundancy back off leaves, which is exactly the + // row the cache holds. It is written out per case so the bite of each one is + // visible without reasoning about what a path routine does. + tidied string + }{ + { + name: "a reported path with one more trailing separator than the cached row", + reported: mtplxServedPath + "/", + tidied: mtplxServedPath, + }, + { + name: "a reported path with a doubled separator inside the cached row", + reported: strings.Replace(mtplxServedPath, "/models/", "/models//", 1), + tidied: mtplxServedPath, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.NotEqual(t, tc.tidied, tc.reported, "the case stages a spelling the cache holds no row for") + + ex := residencyAsking(t, residencyManifest(t), map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(tc.reported), + }) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "the path this server named is not any row's path, so no pack is known") + assert.Equal(t, packRow{}, row, "a path that joins only after tidying must not mark the row it tidies to as loaded") + + rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + require.True(t, inventoryOK, "the listing arrived, so the miss belongs to the reported path") + require.Len(t, rows, 1, "the cache holds exactly the pack this answer is one separator away from") + require.Equal(t, tc.tidied, rows[0].path, "separator redundancy is the only difference between the two spellings") + + _, foundByTidying := packRowForKey(rows, tc.tidied) + require.True(t, foundByTidying, + "with that redundancy removed the same rows do hold this pack, so the answer above is exactness and not an unrelated miss") + }) + } +} + +func TestResidentPack_WithoutADeclaredReadAnswersUnknown(t *testing.T) { + // A residency block that names no read has not said where the loaded path is + // answered, so there is nothing to ask and no guessing where to ask it anyway. + // The fixture still answers the inventory, so the `false` cannot be blamed on a + // listing that failed to arrive: it comes from having no declared question to + // ask, and the answer must be "unknown", never the empty answer some caller + // would render as "this engine has nothing loaded". + manifest := residencyManifest(t) + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency.Read = nil + manifest.Actions["loaded_models"] = loaded + var asked []residencyAsk + ex := residencyAskedAbout(t, manifest, map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + }, &asked) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + assert.False(t, ok, "a manifest that names no read cannot be asked what it loaded") + assert.Equal(t, packRow{}, row, "and not being able to ask is not the same as nothing being resident") + assert.Empty(t, asked, "so the engine is not asked") +} + +func TestResidentPack_ReadsAnExternallyStartedServerOnPort6666(t *testing.T) { + // Review Focus 1: a MTPLX PAIR never started, on a port PAIR never chose. The + // name keeps the measurement — this is the server found on port 6666 on the Mac + // these fixtures came from, kept in a settings file rather than in PAIR. The + // staged port is one the OS assigned, because 6666 on the machine running this + // test is somebody's live session and no test may bind it, read it or disturb + // it. The health answer is at the measured size all the same: a join proven + // against a 30-byte stub has not been proven against a real MTPLX. + skipWithoutShell(t) + + // Nothing here reaches this user's MTPLX. The detect path is a script this test + // wrote rather than any path the manifest names, the binary is a name in a + // directory nothing is in, and the settings-file port source is dropped — that + // file is this machine's real `~/Library/Application Support/MTPLX/settings.json`, + // and reading it would both make the test depend on it and point the read at a + // live server. So the only port in the test is the one the OS handed over. + // relocationRegistry pins the same things for the same reason. + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + manifest, platform := hostPlatformBlock(t, reg, "mtplx") + + port := portRun(t, 1)[0] + + // The shipped inventory read is `mtplx models --json`, and no test may run a + // real MTPLX, so a script answers the same body from a file. This is also the + // only place the cmd half of the join is driven end to end: Task 1 pinned the + // cmd shapes at the extractor because no binary could be staged there. + dir := t.TempDir() + listing := filepath.Join(dir, "models.json") + require.NoError(t, os.WriteFile(listing, []byte(sagittariusModelsBody), 0o600)) + cli := filepath.Join(dir, "mtplx"+exeExt()) + require.NoError(t, os.WriteFile(cli, []byte("#!/bin/sh\ncat '"+listing+"'\n"), 0o755)) + listModels := manifest.Actions["list_models"] + listModels.Cmd = []string{cli, "models", "--json"} + manifest.Actions["list_models"] = listModels + + platform.Detect = []string{cli} + platform.Runtime.Bin = filepath.Join(dir, "mtplx-started-by-nobody"+exeExt()) + platform.Runtime.PortSource = nil + platform.Runtime.Port = port + manifest.Platforms[hostPlatformKey()] = platform + + ex := newTestExecutor(t, manifest) + st, err := ex.state("mtplx") + require.NoError(t, err) + st.mu.Lock() + st.running = true + st.mu.Unlock() + require.Equal(t, port, st.port, + "the engine is met on the port it was found on: not the 8101 the manifest configures, and not the 6666 that Mac's settings file named") + + var asked []residencyAsk + ex.client.Transport = residencyRecordingTransport(map[string]string{ + residencyHealthPath: mtplxHealthBody(t, mtplxServedModel, mtplxServedPath), + residencyServedPath: residencyServedBody, + }, &asked) + + row, ok := ex.residentPack(t.Context(), "mtplx") + + require.True(t, ok, "the pack a server PAIR did not start has mapped has to be answerable, or the card says nothing true about it") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", row.repoID, + "a relocated server's answer joins to the same row a locally started one would") + require.Len(t, asked, 1, "one question per call, and of the server that is running") + assert.Equal(t, fmt.Sprintf("127.0.0.1:%d%s", port, residencyHealthPath), asked[0].target, + "the read went to the port this server was met on, not the 6666 the manifest's settings file prefers") + assert.Equal(t, "1", asked[0].probe, + "and it went as a probe, so PAIR's own facade answers for itself instead of forwarding the question to whatever it fronts") + + names, namesOK := ex.servedNames(t.Context(), "mtplx") + + require.True(t, namesOK, "an adopted server answers what it answers to just the same") + assert.Equal(t, []string{mtplxServedModel}, names) + + // The one question this join puts to the server is bounded the way every probe + // answer is bounded, which is the rule that keeps a status refresh from waiting on + // a wedged engine. A stubbed answer arrives instantly, so the request carrying the + // deadline is the only evidence there is — and a bound widened to the action + // timeout, which is what the ordinary model-list read uses, would otherwise look + // like the same passing test. + assert.LessOrEqual(t, asked[0].bound, 3*time.Second, + "the residency read is bounded by the probe's bound, not the 30-minute action timeout a model read inherits") + assert.Greater(t, asked[0].bound, 2*time.Second, + "and it is that bound being applied, not an already-expired context answering for it") +} + +// mtplxPackRepoID is what the cache listing calls the one pack the Mac these +// fixtures came from holds. It is the key every consumer of the model payload +// matches rows by, because that listing's field is what the model manager lists, +// and the loaded list is unioned onto those rows and looked up by exact string. +// The pack has three other spellings — the folder it sits in, which writes the +// separator twice; the name the running server answers requests as; and, for a +// pair bundle, a directory no listing names — and only this one joins. +const mtplxPackRepoID = "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" + +// asksForPath is the questions PAIR really put to one path. A case counts the reads +// of one action this way rather than assuming nothing else in the sweep asked +// anything, which is what makes "this action ran once" a fact about that action. +func asksForPath(asked []residencyAsk, path string) []residencyAsk { + var got []residencyAsk + for _, ask := range asked { + if strings.HasSuffix(ask.target, path) { + got = append(got, ask) + } + } + return got +} + +func TestLoadedModels_ForMTPLXMarksTheCacheRowNotTheServedName(t *testing.T) { + // A running MTPLX, the cache listing it gives for itself, and the directory it + // mapped: the model list has to report which pack is resident in the spelling its + // own rows already carry. It is not a cosmetic choice. The model manager unions + // this loaded list onto the cached rows by exact string and marks a row loaded by + // looking a row name up in it, so a resident pack named any other way shows as two + // rows — the cached one idle, the served name loaded — and the cached row's + // Eject, Delete and Load buttons are aimed by that same lookup. A row that is + // merely cached offering Load restarts an engine that is already serving it. + ex := residencyAsking(t, residencyManifest(t), map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + residencyServedPath: residencyServedBody, + }) + + res := ex.ModelsResult(t.Context()) + + require.Equal(t, []string{mtplxServedModel}, res.Models, "the node-level advertised list") + require.Equal(t, map[string][]string{"mtplx": {mtplxServedModel}}, res.ByEngine, + "what a request has to be routed by is the served name, and this task leaves it there") + require.Equal(t, map[string][]string{"mtplx": {mtplxPackRepoID}}, res.LoadedByEngine, + "residency is the cache's own key for the pack, not a fourth spelling nothing matches") + require.Equal(t, map[string][]string{"mtplx": {mtplxPackRepoID}}, res.DownloadedByEngine, + "and it is the key the cached rows already carry, so the union of the two is one row") + assert.NotContains(t, res.LoadedByEngine["mtplx"], mtplxServedModel, + "the served name stays out of the loaded list, or this payload names the pack twice") +} + +func TestLoadedModels_KeepsTheServedNameAsARowWhenNoPackMatches(t *testing.T) { + // A pair bundle handed straight to the server is really mapped and really is not + // in the cache listing, and the join refuses to answer rather than name the cached + // pack whose folder name it shares. The model list then has to report what it does + // know — the served name is loaded — instead of nothing at all. This is the + // deliberate half of a behaviour the desktop pins at + // tests/modular/lmstudio-stale-model.test.ts: a served thing no cached row names + // keeps a loaded row of its own. "I cannot tell which cached row this is" is not + // the statement "nothing is loaded", which is the same mistake as naming the wrong + // row, travelling the other way. + ex := residencyAsking(t, residencyManifest(t), map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(residencyPairBundlePath), + residencyServedPath: residencyServedBody, + }) + + res := ex.ModelsResult(t.Context()) + + require.Equal(t, map[string][]string{"mtplx": {mtplxServedModel}}, res.LoadedByEngine, + "the served name is still reported as loaded, because it is a real served thing") + require.Equal(t, map[string][]string{"mtplx": {mtplxPackRepoID}}, res.DownloadedByEngine, + "the pack this machine does cache is still listed, and stays not loaded") + assert.Equal(t, map[string][]string{"mtplx": {mtplxServedModel}}, res.ByEngine, "advertised") +} + +func TestLoadedModels_ReadsThePackInventoryOncePerSweep(t *testing.T) { + // The join reads the same action the model list reads for its rows, so a sweep + // that asks the engine for that listing twice pays for it twice. For MTPLX the + // listing is `mtplx models --json`: a subprocess that carries the action timeout + // with it, not a request bounded by the probe's 3 s. One sweep, one run. + var asked []residencyAsk + ex := residencyAskedAbout(t, residencyManifest(t), map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + residencyServedPath: residencyServedBody, + }, &asked) + + res := ex.ModelsResult(t.Context()) + + require.Equal(t, map[string][]string{"mtplx": {mtplxPackRepoID}}, res.LoadedByEngine, + "the answer has to come from the join, or counting the reads proves nothing about it") + assert.Len(t, asksForPath(asked, residencyInventoryPath), 1, + "one inventory read per sweep, whichever half needed it: %v", asked) + assert.Len(t, asksForPath(asked, residencyHealthPath), 1, "one question to the running server: %v", asked) + assert.Len(t, asksForPath(asked, residencyServedPath), 1, "one served-name read: %v", asked) +} + +func TestLoadedModels_ReadsAResidencySourceActionTheSweepDidNotAlreadyRead(t *testing.T) { + // A join may name any action for its rows. When it names one the sweep has no + // other reason to read, reusing the listing the sweep did read would be answering + // the join from rows it was never declared against, so that action is read — once, + // and without reading the listing a second time either. + manifest := residencyManifest(t) + manifest.Actions["pack_rows"] = Action{ + HTTP: &ActionHTTP{Method: "GET", Path: "/fixture/pack-rows"}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + } + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency.Source = "pack_rows" + manifest.Actions["loaded_models"] = loaded + + var asked []residencyAsk + ex := residencyAskedAbout(t, manifest, map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + "/fixture/pack-rows": sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + residencyServedPath: residencyServedBody, + }, &asked) + + res := ex.ModelsResult(t.Context()) + + require.Equal(t, map[string][]string{"mtplx": {mtplxPackRepoID}}, res.LoadedByEngine, + "the join reads the rows from the action that was declared, not the one that was handy") + assert.Len(t, asksForPath(asked, "/fixture/pack-rows"), 1, "the declared read, once: %v", asked) + assert.Len(t, asksForPath(asked, residencyInventoryPath), 1, "and the listing is still read once: %v", asked) +} + +func TestManifest_TheBundledMTPLXManifestDeclaresThePackJoin(t *testing.T) { + raw, err := fs.ReadFile(bundledManifests, "manifests/mtplx.json") + require.NoError(t, err) + var mf Manifest + require.NoError(t, json.Unmarshal(raw, &mf), "the shipped manifest has to parse into the same shape a test builds") + require.NoError(t, mf.Validate()) + + loaded := mf.Actions["loaded_models"] + require.NotNil(t, loaded.Result, "loaded_models names its array and field before anything else") + residency := loaded.Result.Residency + require.NotNil(t, residency, "MTPLX answers for exactly one pack, so the join has to be declared") + assert.Equal(t, "list_models", residency.Source, "the pack rows come from the cache listing") + require.NotNil(t, residency.Read) + assert.Equal(t, "GET", residency.Read.Method, "read method") + assert.Equal(t, "/health", residency.Read.Path, "that is where MTPLX reports the path it loaded") + assert.Equal(t, "model_path", residency.PathField, "that is the field it reports it in") + assert.Equal(t, "path", residency.RowPathField, "that is the field each cached pack carries") + + source := mf.Actions[residency.Source] + require.NotNil(t, source.Result, "the listing has to name a field before residency can key on it") + assert.Equal(t, "repo_id", source.Result.Field, "a listing keyed on anything else would key the join on nothing") + assert.Empty(t, residency.RowKeyField, "the row key is the listing's own field, not a second spelling") +} + +func TestManifestValidate_RejectsAResidencyThatCouldNeverResolve(t *testing.T) { + // Each case is a residency block that would leave PAIR looking for a pack + // with the wrong recipe: no rows to look in, nothing to look the path up + // with, or the join declared on an action that never joins anything. They are + // manifest-load failures, which is why they are rejected before an engine is + // ever started rather than discovered as a wrong answer later. + cases := []struct { + name string + resident *ActionResidency + want string + }{ + { + name: "names no inventory to read", + resident: &ActionResidency{Read: &ActionHTTP{Method: "GET", Path: "/health"}, PathField: "model_path", RowPathField: "path"}, + want: "source", + }, + { + name: "names an inventory that this manifest has no such field in", + resident: &ActionResidency{Source: "list_models", Read: &ActionHTTP{Method: "GET", Path: "/health"}, PathField: "model_path"}, + want: "row_path_field", + }, + { + name: "names no field to read the loaded path from", + resident: &ActionResidency{Source: "list_models", Read: &ActionHTTP{Method: "GET", Path: "/health"}, RowPathField: "path"}, + want: "path_field", + }, + { + name: "reads its own action for the loaded path", + resident: &ActionResidency{Source: "loaded_models", Read: &ActionHTTP{Method: "GET", Path: "/v1/models"}, PathField: "id", RowPathField: "path"}, + want: "source", + }, + { + name: "keys the row on a field name its reader cannot follow", + resident: &ActionResidency{Source: "list_models", Read: &ActionHTTP{Method: "GET", Path: "/health"}, PathField: "model_path", RowPathField: "path", RowKeyField: "validation.missing_files"}, + want: "row_key_field", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifest := residencyManifest(t) + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency = tc.resident + manifest.Actions["loaded_models"] = loaded + + err := manifest.Validate() + + require.Error(t, err, "a join that cannot resolve has to fail at load") + assert.Contains(t, err.Error(), "residency") + assert.Contains(t, err.Error(), tc.want) + }) + } + + t.Run("the inventory itself has to carry a key field", func(t *testing.T) { + manifest := residencyManifest(t) + list := manifest.Actions["list_models"] + list.Result = nil + manifest.Actions["list_models"] = list + + err := manifest.Validate() + + require.Error(t, err, "residency keyed on a field nobody declares is no join") + assert.Contains(t, err.Error(), "residency") + }) + + t.Run("only loaded_models may declare a join", func(t *testing.T) { + manifest := residencyManifest(t) + listed := manifest.Actions["list_models"] + listed.Result.Residency = &ActionResidency{Source: "loaded_models", Read: &ActionHTTP{Method: "GET", Path: "/health"}, PathField: "id", RowPathField: "path"} + manifest.Actions["list_models"] = listed + + err := manifest.Validate() + + require.Error(t, err, "the listing action does not serve a model, so it has nothing to join") + assert.Contains(t, err.Error(), "loaded_models") + }) + + t.Run("a read block needs a method and a path", func(t *testing.T) { + manifest := residencyManifest(t) + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency.Read = &ActionHTTP{} + manifest.Actions["loaded_models"] = loaded + + err := manifest.Validate() + + require.Error(t, err, "a residency read has to say where the loaded path is answered") + assert.Contains(t, err.Error(), "residency") + }) +} + +func TestManifestValidate_RejectsAResidencySourceThatStopsOrRestartsTheEngine(t *testing.T) { + // A residency lookup runs while an engine is serving, and it runs often, so a + // source action that also takes the engine down would make answering "what is + // this engine serving?" stop, restart or relaunch the thing being asked. PAIR + // never does that to a running engine on its own, which is why this is checked + // when the manifest loads rather than at the moment of the read. Each case is + // written the way a manifest would write it, with the source still carrying a + // result so the only thing wrong with it is what else it does. + cases := []struct { + name string + source string + action Action + }{ + { + name: "a source that restarts the engine after it answers", + source: "list_models", + action: Action{ + Cmd: []string{"mtplx", "models", "--json"}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + RestartAfter: true, + }, + }, + { + name: "a source that rewrites the launch settings and relaunches", + source: "list_models", + action: Action{ + LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + }, + }, + { + name: "a source that stops the engine", + source: "unload_model", + action: Action{ + StopEngine: true, + Result: &ActionResult{Array: "data", Field: "id"}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + manifest := residencyManifestWithRestart(t) + manifest.Actions[tc.source] = tc.action + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency.Source = tc.source + manifest.Actions["loaded_models"] = loaded + + err := manifest.Validate() + + require.Error(t, err, "a residency lookup must only read") + // The wording is the point: a failure naming the platform instead would + // mean the case tripped some other rule and proved nothing here. + assert.Contains(t, err.Error(), "a residency lookup must only read", "which rule fired: %v", err) + assert.Contains(t, err.Error(), tc.source) + }) + } + + t.Run("a cmd source that only reads still validates", func(t *testing.T) { + // The rule is about what a source does, not how it is carried. MTPLX reads + // its cache with a cmd action, so a manifest that stages the same shape has + // to pass: a rule that rejected cmd sources would reject the one manifest + // this whole file is about. + manifest := residencyManifestWithRestart(t) + manifest.Actions["list_models"] = Action{ + Cmd: []string{"mtplx", "models", "--json"}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + } + + require.NoError(t, manifest.Validate()) + }) +} diff --git a/services/nvpair-tui/ui/nodedetail_test.go b/services/nvpair-tui/ui/nodedetail_test.go index 440465ff0..78b9ee5ec 100644 --- a/services/nvpair-tui/ui/nodedetail_test.go +++ b/services/nvpair-tui/ui/nodedetail_test.go @@ -215,6 +215,55 @@ func TestModelRows_ListAServedModelThatIsNotInTheDownloadedList(t *testing.T) { assert.Equal(t, map[string]string{"/models/qwen": "yes", "Qwen/Qwen3.5-4B": "no"}, modelRowStates(d)) } +// The two names one MTPLX pack carries on the machine these measurements came from: +// what its server answers requests as, and what its own cache listing calls it. The +// engine manager reports residency by the second, because that is the name the +// engine's rows carry, and the terminal is a second client of that same payload — it +// de-dupes and marks loaded by its own exact-string comparison over it. +const ( + mtplxServedName = "mtplx-flash-next-optimized-speed" + mtplxCachedRow = "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed" +) + +func TestManagedModels_ListsOneRowPerPackInTheSpellingTheRowsCarry(t *testing.T) { + t.Run("a resident pack named by its cached row adds no second row", func(t *testing.T) { + d := localDetail() + d.models = modelsResult{ + Models: []string{mtplxServedName}, + ModelsByEngine: map[string][]string{"mtplx": {mtplxServedName}}, + LoadedByEngine: map[string][]string{"mtplx": {mtplxCachedRow}}, + DownloadedByEngine: map[string][]string{"mtplx": {mtplxCachedRow}}, + } + + assert.Equal(t, []string{mtplxCachedRow}, managedModels(d.models, "mtplx"), + "one pack on disk and one resident pack is one row, not a row and its alias") + + d.refreshModels() + assert.Equal(t, map[string]string{mtplxCachedRow: "yes"}, modelRowStates(d), + "and that row says loaded, which is what keeps a serving engine's row offering Load rather than Eject") + }) + + t.Run("a resident pack no cached row names still gets a row", func(t *testing.T) { + // A pair bundle handed straight to the server is really being served and really + // is not in the cache listing, so the engine manager leaves the join unanswered + // and the served name keeps a loaded row of its own. Dropping it would hide a + // model that is answering requests, and marking the cached pack in its place + // would point Eject and Delete at a directory nobody is serving. + d := localDetail() + d.models = modelsResult{ + Models: []string{mtplxServedName}, + ModelsByEngine: map[string][]string{"mtplx": {mtplxServedName}}, + LoadedByEngine: map[string][]string{"mtplx": {mtplxServedName}}, + DownloadedByEngine: map[string][]string{"mtplx": {mtplxCachedRow}}, + } + + assert.Equal(t, []string{mtplxCachedRow, mtplxServedName}, managedModels(d.models, "mtplx")) + + d.refreshModels() + assert.Equal(t, map[string]string{mtplxCachedRow: "no", mtplxServedName: "yes"}, modelRowStates(d)) + }) +} + // "Nothing downloaded" is said only when an engine read its inventory and found // it empty. A peer whose inventory could not be read is not described that way. func TestEmptyModelsHint_SaysNothingIsDownloadedOnlyWhenTheInventoryWasRead(t *testing.T) { From 35eefe23f98118d7bd6014ebbc3e95ba1b3c528f Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 06/10] fix(engines): let eject name the resident pack, bounded and on evidence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The residency answer from the previous commit becomes something the interface acts on, and both ways it could waste or hang a click are closed. - Ejecting the pack an MTPLX served was refused by the engine serving it: the guard compared the request against loaded_models, which answers the served name, while the model list — and so the Eject a user clicks — carries the cache listing's spelling of that same pack. Honest and useless. The guard now gets the question the caller has, whether this name may be ejected from this engine, and answers with both spellings: the names the engine reports for what it serves, plus the cache id of the row the residency join says is mapped. The accepted set stays exactly what PAIR can prove is resident; matching is string for string, so a wrong case, a doubled separator, or the bare directory is still refused; and a refusal can finally name the spelling that does work. - Where the join cannot resolve — the read did not arrive, was bigger than PAIR reads, or came from a web app — the guard stops the engine as it always has, because eject is the recoverable half: it frees the memory, the model loads again. What it does not do is hang: the residency half gets one probe read's time (the 3 s, named as probeReadTimeout) instead of the action timeout, and an unreadable residency is reported as an incomplete answer rather than as a list of one served name to refuse on. - The wedge that made those timeouts real: a context bounds a process, not the wait for its output. A listing whose CLI printed its answer, exited and left a grandchild holding the output pipes kept the read waiting on the leftover's schedule. runCommandOutput gains a commandDrainTimeout after the command is seen to exit, and takes the body the tool already wrote when exec reports ErrWaitDelay — a command the caller's deadline killed still reports its own status, not laundered into a success or a hang. The drain times a tool demonstrably done, not one still downloading; those stay separate. - residentPack and packInventory stop being test-only wrappers: their 20 call sites take the real functions, the eject path pays the cache listing once per click rather than per row, and the port-6666 join test drives the fake engine directly instead of a shell script, so it no longer skips. Signed-off-by: Steven Beverly --- services/nvpair-engine-manager/actions.go | 36 ++ services/nvpair-engine-manager/launchmodel.go | 65 +- .../nvpair-engine-manager/launchmodel_test.go | 558 ++++++++++++++++++ services/nvpair-engine-manager/lifecycle.go | 13 +- services/nvpair-engine-manager/registry.go | 2 +- services/nvpair-engine-manager/residency.go | 201 ++++--- .../nvpair-engine-manager/residency_test.go | 182 +++--- .../testdata/fakeengine/main.go | 30 + 8 files changed, 920 insertions(+), 167 deletions(-) diff --git a/services/nvpair-engine-manager/actions.go b/services/nvpair-engine-manager/actions.go index 1eef34bfa..57f33900a 100644 --- a/services/nvpair-engine-manager/actions.go +++ b/services/nvpair-engine-manager/actions.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "log/slog" @@ -334,6 +335,27 @@ func (e *Executor) runCmdAction(ctx context.Context, st *engineState, act Action return wrapped, nil } +// commandDrainTimeout is how long the output of a manifest command is waited on +// after the command itself has stopped answering. +// +// A context bounds a process, not the wait for its output: exec ends a command when +// the caller's deadline passes but ends the read only when the output pipes close, +// and a process the command started inherits them and outlives it. A tool that +// prints its answer, exits, and leaves something behind holding stdout therefore +// leaves the read sitting on a pipe nobody is going to close — measured with a +// helper that sleeps a minute, cmd.Output came back when the helper went away, a +// minute after a deadline that had nothing to say about the wait. Every action that +// runs a command is exposed this way, and for the eject's residency read that is +// 30 minutes of a dead button holding the engine's operation lock, not the 3 s the +// read was given. +// +// A second is enough because the answer is already in the pipe by the time the tool +// is seen to exit: what the remaining window can hold is whatever a leftover helper +// has to add, and that is not what the caller is waiting for. It is not +// downloadWaitDelay, which is how long a tool that is still transferring gets before +// PAIR gives up on it; this times a tool that is demonstrably done. +const commandDrainTimeout = time.Second + // runCommandOutput runs argv and returns its stdout; on failure it // returns the error with stderr attached for diagnostics. func (e *Executor) runCommandOutput(ctx context.Context, argv []string) (string, error) { @@ -345,7 +367,21 @@ func (e *Executor) runCommandOutput(ctx context.Context, argv []string) (string, } cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) configureSysProcAttr(cmd) + cmd.WaitDelay = commandDrainTimeout out, err := cmd.Output() + if errors.Is(err, exec.ErrWaitDelay) { + // The command answered and exited on its own terms; the drain was cut off by + // something that inherited the output and never wrote to it. The exit status is + // the fact callers act on, and out holds what the tool wrote, so this read is + // the answer rather than a failure — the residency join needs those rows. + // + // This cannot hide a read that ran out of time: exec documents ErrWaitDelay as + // what a process that exited successfully gets when its pipes outlive the delay, + // and reports the exit status instead for a command that failed or was killed — + // confirmed against a killed command whose helper was still holding the pipe, + // which came back as its own signal error with what it had written so far. + return string(out), nil + } if err != nil { if ee, ok := err.(*exec.ExitError); ok { return "", fmt.Errorf("%v: %s", err, strings.TrimSpace(string(ee.Stderr))) diff --git a/services/nvpair-engine-manager/launchmodel.go b/services/nvpair-engine-manager/launchmodel.go index da4e22aea..175c7291b 100644 --- a/services/nvpair-engine-manager/launchmodel.go +++ b/services/nvpair-engine-manager/launchmodel.go @@ -8,9 +8,11 @@ import ( "encoding/json" "errors" "fmt" + "log/slog" "regexp" "slices" "strings" + "time" settings "nvpair-shared/enginesettings" ) @@ -353,6 +355,9 @@ func launchModelValue(tokens []string, flags []string) string { // wrong one. // The served model is asked of the engine itself, not read from the saved // launch arguments, because an adopted engine may have been started on another. +// The names it may be asked under are the engine's answer plus the resident +// pack's cache id, which for these engines is the spelling the caller has: see +// ejectableNames. func (e *Executor) ejectByStopping(ctx context.Context, engine string, params json.RawMessage) (json.RawMessage, error) { var request struct { Model string `json:"model"` @@ -385,9 +390,11 @@ func (e *Executor) ejectByStopping(ctx context.Context, engine string, params js return nil } // When the engine cannot say what it serves, it is stopped anyway: Eject - // exists to free the GPU, and stopping the engine is all it can do. + // exists to free the GPU, and stopping the engine is all it can do. The + // residency join being unreadable is that same case (see ejectableNames): the + // only name it could have added is the one the user is holding. if model != "" { - if serving, err := e.servingModels(ctx, edit.st, engine); err == nil && !slices.Contains(serving, model) { + if serving, complete, err := e.ejectableNames(ctx, edit.st, engine); err == nil && complete && !slices.Contains(serving, model) { return fmt.Errorf("%s is not the model %s is serving (%s)", model, engine, strings.Join(serving, ", ")) } } @@ -459,3 +466,57 @@ func (e *Executor) servingModels(ctx context.Context, st *engineState, engine st } return names, nil } + +// ejectableNames is what one eject may be asked for: every name the engine reports for +// the models it serves, plus the cache id of the pack the residency join says it has +// mapped. The join is here because the two spellings are not alike for an engine that +// serves one pack per process — MTPLX answers requests as +// "mtplx-flash-next-optimized-speed" while its own cache listing, and so PAIR's model +// list, calls the same pack by its repo id — and a guard that reads only the served +// names refuses the pack that really is resident while serving the eject of a name no +// listing carries. +// +// The second result is whether these names are worth refusing on. A join that never +// answered adds nothing to them and rules nothing out, and for these engines the name the +// user has is exactly the one that read would have produced: the model list, and so the +// eject button, carries the cache id. So an unreadable residency is reported as +// incomplete rather than as a list of one served name, and the eject goes ahead — as it +// always has on an engine that cannot say what it serves, and with the same result as the +// Stop button beside it. A join that answered and named another pack, including one whose +// directory no row holds, is a complete answer and the guard refuses on it, and so is a +// manifest that declares no residency read at all: that engine has never had a second +// spelling to offer, which is why its guard refuses exactly as it did before the join. +// +// The join gets one probe read's time. Its second half runs through the action machinery, +// which hands the caller's context to whatever the manifest declared: a request is bound by +// it, and a `mtplx models --json` subprocess is killed at it — and a CLI that answered and +// left something behind holding its output is given up on one commandDrainTimeout later, +// rather than whenever that leftover process decides to exit. An eject is a click, so PAIR +// stops the engine on the served names rather than leave the user waiting on a listing that +// is not coming; unbounded, that wait is the action timeout, 30 minutes of a dead button +// holding the engine's operation lock. The served-names read keeps the bound the action +// machinery gives it. The join is asked only of an engine that has answered that read, so a +// stopped engine and one that declares no loaded_models action cost no inventory run at all. +func (e *Executor) ejectableNames(ctx context.Context, st *engineState, engine string) (names []string, complete bool, err error) { + names, err = e.servingModels(ctx, st, engine) + if err != nil { + return nil, false, err + } + bound, cancel := context.WithTimeout(ctx, probeReadTimeout) + defer cancel() + began := time.Now() + answer := e.residentJoin(bound, engine, inventoryAnswer{}) + if !answer.complete { + elapsed := time.Since(began).Round(time.Millisecond) + if errors.Is(bound.Err(), context.DeadlineExceeded) { + slog.Debug("engine:eject gave up waiting for what the engine has mapped", "engine", engine, "action", "unload_model", "elapsed", elapsed) + } else { + slog.Debug("engine:eject could not read what the engine has mapped", "engine", engine, "action", "unload_model", "elapsed", elapsed) + } + return names, false, nil + } + if answer.named { + names = append(names, answer.row.repoID) + } + return names, true, nil +} diff --git a/services/nvpair-engine-manager/launchmodel_test.go b/services/nvpair-engine-manager/launchmodel_test.go index 85fea9403..c2ca5a3b2 100644 --- a/services/nvpair-engine-manager/launchmodel_test.go +++ b/services/nvpair-engine-manager/launchmodel_test.go @@ -7,7 +7,12 @@ import ( "bytes" "context" "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" "strings" + "sync" "testing" "time" @@ -425,6 +430,559 @@ func TestEject_StopsTheEngineAndKeepsItsModelChoice(t *testing.T) { assert.Equal(t, ejectReply{Stopped: false}, eject("org/served"), "ejecting from a stopped engine is a no-op") } +// The cases below are the eject guard's, and they come from the residency +// fixtures because that is where the pack this guard has to recognise is measured: +// one MTPLX answers a request as "mtplx-flash-next-optimized-speed", its own cache +// listing calls the same pack "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", +// and the directory holding it is spelled with a double dash. The manifest tells the +// user to eject by cache id, and the model list it builds reports the listing's +// spelling, so a guard that reads only the served names refuses the pack that really +// is resident. The answers here are those measurements; the engine they are staged on +// is one this machine never had. + +// ejectableMTPLX is that engine: up, stoppable for real, and asked only the questions +// a fixture declared the answers to. +type ejectableMTPLX struct { + ex *Executor + asked []residencyAsk + process *managedProc + stalled *stalledResidencyTransport +} + +// stalledResidencyTransport is an engine that is up on its port and stuck inside one of +// its answers: the reads named in stalled are held until the test lets them go, and the +// rest are answered from bodies. A missing key cannot stand in for this, because a +// missing key fails the moment it is asked and says nothing about what a caller does with +// a read it is still waiting for. +type stalledResidencyTransport struct { + inner http.RoundTripper + stalled map[string]bool + release chan struct{} + once sync.Once +} + +func (s *stalledResidencyTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if !s.stalled[req.URL.Path] { + return s.inner.RoundTrip(req) + } + select { + case <-s.release: + return nil, fmt.Errorf("the fixture answered %s only after PAIR stopped waiting for it", req.URL.Path) + case <-req.Context().Done(): + return nil, req.Context().Err() + } +} + +func (s *stalledResidencyTransport) letGo() { + s.once.Do(func() { close(s.release) }) +} + +// ejectableMTPLXStalledOn is the resident engine whose answer to `stalled` never comes +// back, for the cases about how long an eject is willing to wait for one. Those cases +// lower the bound they are waiting out, so they stay about the waiting rather than about +// how long production is willing to wait. +func ejectableMTPLXStalledOn(t *testing.T, bodies map[string]string, stalled ...string) *ejectableMTPLX { + t.Helper() + + probeReadTimeoutGiven(t, 250*time.Millisecond) + paths := make(map[string]bool, len(stalled)) + for _, path := range stalled { + paths[path] = true + } + transport := &stalledResidencyTransport{ + inner: residencyStubTransport(bodies), + stalled: paths, + release: make(chan struct{}), + } + t.Cleanup(transport.letGo) + return ejectableMTPLXStaged(t, func(f *ejectableMTPLX) { + f.ex.client.Transport = transport + f.stalled = transport + }) +} + +// ejectableMTPLXAsking stages that engine answering exactly bodies. +func ejectableMTPLXAsking(t *testing.T, bodies map[string]string) *ejectableMTPLX { + t.Helper() + + return ejectableMTPLXStaged(t, func(f *ejectableMTPLX) { + f.ex.client.Transport = residencyRecordingTransport(bodies, &f.asked) + }) +} + +// ejectableMTPLXListingRunByCLI is the resident engine with its cache listing read the +// way the shipped manifest reads MTPLX's — as a cmd action, the engine's own control tool +// rather than the fixture's HTTP stand-in. That difference is the whole case: a subprocess +// is bounded by different machinery from a request. +func ejectableMTPLXListingRunByCLI(t *testing.T, cmd []string, bodies map[string]string) *ejectableMTPLX { + t.Helper() + + return ejectableMTPLXStagedManifest(t, func(manifest *Manifest) { + platform := manifest.Platforms[hostPlatformKey()] + // {cli} follows the tool the platform is observed to have, so the residency read + // would run the fixture's Detect entry rather than anything the case asked for. + // With nothing observed, the literal is the only candidate, and the literal is the + // fake engine: the guard runs a real subprocess of a real manifest-shaped argv. + platform.Detect = nil + platform.Runtime.CLI = fakeEngineBin + manifest.Platforms[hostPlatformKey()] = platform + manifest.Actions["list_models"] = Action{ + Cmd: cmd, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + } + }, func(f *ejectableMTPLX) { + f.ex.client.Transport = residencyRecordingTransport(bodies, &f.asked) + }) +} + +// ejectableMTPLXStaged is the engine every eject-guard case shares: a MTPLX running on a +// port with nothing behind it, with the launch controls that make eject a stop, and with +// a process that really exits when the stop comes. It takes the answers as a function +// rather than a map because the cases differ in how much of an answer ever arrives, and +// one of them is "none of it, ever". +func ejectableMTPLXStaged(t *testing.T, answers func(f *ejectableMTPLX)) *ejectableMTPLX { + t.Helper() + + return ejectableMTPLXStagedManifest(t, nil, answers) +} + +// ejectableMTPLXStagedManifest is ejectableMTPLXStaged for a case that has to change the +// manifest it stages on. The change runs before the manifest is validated, so a fixture +// that edits itself into an illegal shape fails there rather than quietly never reaching +// the guard it is meant to be exercising. +func ejectableMTPLXStagedManifest(t *testing.T, changeManifest func(manifest *Manifest), answers func(f *ejectableMTPLX)) *ejectableMTPLX { + t.Helper() + + manifest := residencyManifestWithRestart(t) + platform := manifest.Platforms[hostPlatformKey()] + // The four keys the shipped manifest declares for an engine that serves one pack per + // process: it waits for a model, it serves on a host and port it is told, it names + // the pack to serve with --model, and ejecting that model stops the engine rather + // than dropping it. Without them the eject these cases are about is a different + // action, and an engine with no launch arguments has no launch to keep. + platform.Runtime.WaitForModel = true + platform.Runtime.Args = []string{"serve", "--host", "{host}", "--port", "{port}"} + manifest.Platforms[hostPlatformKey()] = platform + manifest.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model", "--model-id"}}} + manifest.Actions["unload_model"] = Action{StopEngine: true} + if changeManifest != nil { + changeManifest(manifest) + } + require.NoError(t, manifest.Validate(), "a manifest that is not legal never reaches the guard") + + fixture := &ejectableMTPLX{} + fixture.ex = newTestExecutor(t, manifest) + residencyMarkRunning(t, fixture.ex, manifest.Engine) + answers(fixture) + // Ejecting the pack keeps the launch it was served on, and keeping that is a write to + // the engine's settings override — a directory only settingsExecutor hands out, and + // one an eject needs whether or not the case is about settings. + fixture.ex.overrideDir = t.TempDir() + // The stop has to be a stop. Marking the engine running is enough to reach the + // guard, but not enough to tell an eject that stopped something from one that + // stopped nothing, so the state carries a process that really is running and + // really does exit. It binds no port, so no case here meets a listener it did not + // declare. + process, err := startManagedProc(fakeEngineBin, []string{"noserve"}, nil, nil) + require.NoError(t, err, "the engine being ejected has to be a live process") + t.Cleanup(func() { process.stop(2 * time.Second) }) + fixture.process = process + st, err := fixture.ex.state("mtplx") + require.NoError(t, err) + st.mu.Lock() + st.proc = process + st.mu.Unlock() + return fixture +} + +// residentMTPLXAnswers is one running MTPLX's three answers about the pack it serves: +// the listing its cache gives, the directory it loaded that pack from, and the name it +// answers requests as. Each case gets its own copy because each changes one entry. +func residentMTPLXAnswers() map[string]string { + return map[string]string{ + residencyInventoryPath: sagittariusModelsBody, + residencyHealthPath: residencyHealthBody(mtplxServedPath), + residencyServedPath: residencyServedBody, + } +} + +// probeReadTimeoutGiven gives every read of the engine a shorter bound than it is really +// given, and puts the real one back when the case ends. The bound being a var is what +// lets a case watch a caller stop waiting for a read without the case being about how +// long a stalled engine can hold up a suite. +func probeReadTimeoutGiven(t *testing.T, bound time.Duration) { + t.Helper() + + was := probeReadTimeout + probeReadTimeout = bound + t.Cleanup(func() { probeReadTimeout = was }) +} + +func (f *ejectableMTPLX) eject(t *testing.T, model string) (json.RawMessage, error) { + t.Helper() + return f.ex.Action(t.Context(), "mtplx", "unload_model", json.RawMessage(`{"model":`+quoteJSON(model)+`}`)) +} + +// requireEjected asserts the eject of this name was carried out end to end: the engine +// stopped, the process PAIR was handed gone with it, and what is left is what ejecting a +// pack leaves on an engine that serves one model per process — enabled, and waiting for +// the next model to be chosen. +func (f *ejectableMTPLX) requireEjected(t *testing.T, model, why string) { + t.Helper() + + raw, err := f.eject(t, model) + f.requireEjectionOf(t, raw, err, model, why) +} + +// requireEjectedWithin is requireEjected for the eject that has to stop waiting for +// something: it runs the eject on its own goroutine and the case fails if the eject is +// still running when limit passes. The waiting is what those cases are about, and an +// eject that waits for the read rather than for the bound it set would otherwise hold the +// suite for the whole action timeout — which is the same thing it does to the click. +func (f *ejectableMTPLX) requireEjectedWithin(t *testing.T, model string, limit time.Duration, why string) { + t.Helper() + + type ejection struct { + raw json.RawMessage + err error + } + finished := make(chan ejection, 1) + eject := t.Context() + go func() { + raw, err := f.ex.Action(eject, "mtplx", "unload_model", json.RawMessage(`{"model":`+quoteJSON(model)+`}`)) + finished <- ejection{raw, err} + }() + select { + case got := <-finished: + f.requireEjectionOf(t, got.raw, got.err, model, why) + case <-time.After(limit): + if f.stalled != nil { + f.stalled.letGo() + } + require.FailNow(t, "the eject is still waiting on a read that never answers", "%s: ejecting %s waited %s for it", why, model, limit) + } +} + +func (f *ejectableMTPLX) requireEjectionOf(t *testing.T, raw json.RawMessage, err error, model, why string) { + t.Helper() + + require.NoError(t, err, "%s: ejecting %s", why, model) + var reply struct { + Model string `json:"model"` + Stopped bool `json:"stopped"` + } + require.NoError(t, json.Unmarshal(raw, &reply)) + assert.Equal(t, model, reply.Model, "the reply names the model it ejected") + assert.True(t, reply.Stopped, "%s: the reply says stopped", why) + select { + case <-f.process.done: + case <-time.After(5 * time.Second): + require.FailNow(t, "the engine process is still running", why) + } + f.requireState(t, false, true, why) +} + +// requireRefusedWithin is requireRefused for a case measuring the waiting: the refusal has +// to arrive within limit, because a refusal that spent the whole action timeout getting +// there is the same stall with a message on it. It hands back the error so the case can +// say which refusal it saw. +func (f *ejectableMTPLX) requireRefusedWithin(t *testing.T, model string, limit time.Duration, why string) error { + t.Helper() + + eject := t.Context() + finished := make(chan error, 1) + go func() { + _, err := f.ex.Action(eject, "mtplx", "unload_model", json.RawMessage(`{"model":`+quoteJSON(model)+`}`)) + finished <- err + }() + + var err error + select { + case err = <-finished: + case <-time.After(limit): + if f.stalled != nil { + f.stalled.letGo() + } + require.FailNow(t, "the eject is still waiting on a read that never answers", + "%s: refusing to eject %s waited %s for the read to answer", why, model, limit) + } + + require.Error(t, err, "%s: ejecting %s must be refused", why, model) + select { + case <-f.process.done: + require.FailNow(t, "a refused eject stopped the engine", why) + default: + } + f.requireState(t, true, false, why) + return err +} + +// requireRefused asserts the eject of this name was refused and the engine was left +// serving: an eject that refuses must not have stopped anything. +func (f *ejectableMTPLX) requireRefused(t *testing.T, model, why string) error { + t.Helper() + + _, err := f.eject(t, model) + require.Error(t, err, "%s: ejecting %s must be refused", why, model) + select { + case <-f.process.done: + require.FailNow(t, "a refused eject stopped the engine", why) + default: + } + f.requireState(t, true, false, why) + return err +} + +// requireState reads back the fact the guard is gated on: it only asks an engine what +// it has resident when the executor believes that engine is up. A case that never +// reached the guard would otherwise pass against an engine that was never running. +func (f *ejectableMTPLX) requireState(t *testing.T, wantRunning, wantAwaitingModel bool, why string) { + t.Helper() + + st, err := f.ex.state("mtplx") + require.NoError(t, err) + st.mu.Lock() + running, awaiting := st.running, st.awaitingModel + st.mu.Unlock() + assert.Equal(t, wantRunning, running, "%s: running", why) + assert.Equal(t, wantAwaitingModel, awaiting, "%s: awaiting a model", why) +} + +func TestEjectByStopping_ServesTheEjectForTheResidentPackUnderItsServedName(t *testing.T) { + // The same pack, resident on the same engine, named both ways a user can have it: + // the name the engine answers requests as, which the guard has always known, and the + // cache id the manifest and PAIR's own model list use, which is the one that was + // refused. + for _, asked := range []struct{ name, model string }{ + {"the name the engine answers requests as", mtplxServedModel}, + {"the cache id the model list carries", mtplxPackRepoID}, + } { + t.Run(asked.name, func(t *testing.T) { + fixture := ejectableMTPLXAsking(t, residentMTPLXAnswers()) + fixture.requireState(t, true, false, "the engine starts up") + + fixture.requireEjected(t, asked.model, "the resident pack is ejectable however this MTPLX spells it") + }) + } +} + +func TestEjectByStopping_StillRefusesAPackThatIsNotResident(t *testing.T) { + // The other side of the same join. The server says it loaded from a directory its + // own listing holds no row for — where a pack handed over as a pair bundle lands — + // while that listing does hold a pack whose folder ends with the same name. So which + // pack is resident is genuinely open, and the pack the cache names is not the one + // this server is running off. A guard that joined loosely enough to let this eject + // through is a guard that stops the engine to eject a pack nobody is serving, on the + // strength of a folder name. + answers := residentMTPLXAnswers() + answers[residencyHealthPath] = residencyHealthBody(residencyPairBundlePath) + fixture := ejectableMTPLXAsking(t, answers) + + err := fixture.requireRefused(t, mtplxPackRepoID, "a cached pack this engine did not load") + assert.ErrorContains(t, err, mtplxPackRepoID+" is not the model mtplx is serving") + assert.Contains(t, err.Error(), mtplxServedModel, "the refusal names what the engine does serve, in the spelling that would work") + assert.NotContains(t, err.Error(), residencyPairBundlePath, "a refusal quotes names, never the directory a model was loaded from") + require.Len(t, asksForPath(fixture.asked, residencyInventoryPath), 1, + "the refusal came from asking the engine and the cache, not from skipping the join") +} + +// TestEjectByStopping_StopsTheEngineThatCannotSayWhatIsResident is the half of the guard +// with nothing to refuse on. `TestEjectByStopping_StillRefusesAPackThatIsNotResident` is +// the other half and keeps refusing: the engine answered where it loaded from, the +// listing answered what it holds, and the name the user gave matches neither, so the +// refusal is evidence and it quotes the name that would work. Every stage here is a way +// that join fails to produce evidence at all — an answer that is not the engine's, an +// answer bigger than PAIR reads, no answer, and an answer that arrives after PAIR stopped +// waiting — and what is left in those cases is the served names alone, which for an +// engine that serves one pack per process is a spelling no model list and no listing ever +// showed the user. The eject button carries the cache id this join produces; refuse here +// and the click does nothing, the model stays resident, and the message names a string +// nobody can type, to prevent an outcome the Stop button beside it reaches unasked. +func TestEjectByStopping_StopsTheEngineThatCannotSayWhatIsResident(t *testing.T) { + stages := []struct { + name string + fixture func(t *testing.T) *ejectableMTPLX + }{ + {"answers with a web app's bundle", func(t *testing.T) *ejectableMTPLX { + answers := residentMTPLXAnswers() + answers[residencyHealthPath] = residencyForeignBody + return ejectableMTPLXAsking(t, answers) + }}, + {"answers with more than PAIR reads", func(t *testing.T) *ejectableMTPLX { + answers := residentMTPLXAnswers() + answers[residencyHealthPath] = residencyOversizedHealthBody(t) + return ejectableMTPLXAsking(t, answers) + }}, + {"says nothing about its own model", func(t *testing.T) *ejectableMTPLX { + answers := residentMTPLXAnswers() + delete(answers, residencyHealthPath) + return ejectableMTPLXAsking(t, answers) + }}, + // The two reads of the join held open one at a time, because they are two + // different reads and only one of them was ever unbounded: the loaded path is a + // probe read of a server that is answering, and the listing the answer joins + // against runs through the action machinery, where the eject's own bound is all + // it gets — left to that machinery's own budget, the read has the action timeout + // instead. + {"takes longer than the eject will wait for the loaded path", func(t *testing.T) *ejectableMTPLX { + return ejectableMTPLXStalledOn(t, residentMTPLXAnswers(), residencyHealthPath) + }}, + {"takes longer than the eject will wait for the cache listing", func(t *testing.T) *ejectableMTPLX { + return ejectableMTPLXStalledOn(t, residentMTPLXAnswers(), residencyInventoryPath) + }}, + } + for _, stage := range stages { + t.Run(stage.name, func(t *testing.T) { + // An eject that does not wait for a stalled read is done in milliseconds; + // one that waits for the read is waiting for the action timeout, which is + // 30 minutes. Three seconds tells those apart without leaning on the + // machine the test runs on. + const limit = 3 * time.Second + for _, named := range []struct{ label, model string }{ + {"the name the engine answers requests as", mtplxServedModel}, + {"the cache id the model list carries", mtplxPackRepoID}, + } { + t.Run("it ejects "+named.label, func(t *testing.T) { + fixture := stage.fixture(t) + fixture.requireState(t, true, false, "the engine starts up") + + fixture.requireEjectedWithin(t, named.model, limit, + "an engine that cannot say what it has mapped does not get to hold its model hostage") + }) + } + }) + } +} + +func TestEjectByStopping_RefusesANearMissSpellingOfTheResidentPack(t *testing.T) { + // Joining the two halves is a comparison, so what it must not accept is part of the + // contract. The same pack has other spellings nearby: the folder its files sit in, + // differing from the cache id by a doubled separator; that folder's full directory, + // which is what the join reads rather than a name; and the cache id with its org + // dropped or its case changed. A guard that folded case, rewrote separators, settled + // for a substring or read a path as a name would let all of them through, and then an + // eject typed as a typo stops the engine on the grounds that some part of the request + // looks like what is resident. + for _, asked := range []struct{ name, model string }{ + {"the cache id in another case", strings.ToUpper(mtplxPackRepoID)}, + {"the folder the pack sits in", filepath.Base(mtplxServedPath)}, + {"the cache id without its org", strings.SplitN(mtplxPackRepoID, "/", 2)[1]}, + {"the directory the pack sits in", mtplxServedPath}, + } { + t.Run(asked.name, func(t *testing.T) { + fixture := ejectableMTPLXAsking(t, residentMTPLXAnswers()) + + err := fixture.requireRefused(t, asked.model, "what is resident is ejectable under its two names and no other") + assert.ErrorContains(t, err, asked.model+" is not the model mtplx is serving") + assert.ErrorContains(t, err, mtplxPackRepoID, "the refusal gives the spelling that does work") + }) + } +} + +func TestEjectByStopping_ReadsThePackInventoryNoMoreThanOnce(t *testing.T) { + // For this engine the inventory is a `mtplx models --json` subprocess rather than a + // request, so what the guard pays for its answer is worth a case of its own: a + // second read per eject is invisible in a stubbed transport unless the transport + // counts. + t.Run("once, when the engine says where its model came from", func(t *testing.T) { + fixture := ejectableMTPLXAsking(t, residentMTPLXAnswers()) + + fixture.requireEjected(t, mtplxPackRepoID, "the eject runs the join") + + require.Len(t, asksForPath(fixture.asked, residencyInventoryPath), 1, + "one eject runs the cache listing once") + require.Len(t, asksForPath(fixture.asked, residencyHealthPath), 1, + "one eject asks where the model was loaded from once") + }) + t.Run("not at all, when the engine cannot say", func(t *testing.T) { + answers := residentMTPLXAnswers() + delete(answers, residencyHealthPath) + fixture := ejectableMTPLXAsking(t, answers) + + fixture.requireEjected(t, mtplxServedModel, "the eject of a served name runs without the inventory") + + require.Empty(t, asksForPath(fixture.asked, residencyInventoryPath), + "an engine that says nothing about its own pack must not cost a cache listing run") + }) +} + +// TestEjectByStopping_BoundsACacheListingRunAsASubprocess is the eject's bound on the +// transport the shipped manifest actually uses. +// +// Every case above stages the cache listing as an HTTP action, because that is how the +// fixture delivers a measured body without a real MTPLX. manifests/mtplx.json runs it as +// `mtplx models --json` instead, and a subprocess is not bounded the way a request is: +// exec.CommandContext signals the CLI when the caller's deadline passes, but Wait ends +// only when the command's output pipes reach EOF — and a process the CLI started inherits +// those pipes and outlives it. Measured on this machine against a helper that sleeps a +// minute, the read came back when the helper finally went away, and the deadline had +// nothing to say about the wait. For an eject that means the action timeout: 30 minutes of +// an eject button that does nothing while it holds the engine's operation lock. +// +// The limit below is not a tightened copy of the bound: the read gets probeReadTimeout, +// the 3 s every other case here pays for, and a bounded read of this fixture's shape is +// done about a sixth of the way in (measured: 1.02 s of the 6 s, the drain timeout being +// what it waits on). A case that goes past this limit is waiting on the action timeout +// instead. +func TestEjectByStopping_BoundsACacheListingRunAsASubprocess(t *testing.T) { + const limit = 6 * time.Second + + dir := t.TempDir() + listing := filepath.Join(dir, "models.json") + require.NoError(t, os.WriteFile(listing, []byte(sagittariusModelsBody), 0o600)) + pidFile := filepath.Join(dir, "listing-helper.pid") + + t.Run("a listing whose CLI leaves a helper holding its output is not waited on", func(t *testing.T) { + // The finding. The CLI prints the listing and exits 0 while something it started + // keeps the pipe the listing came down open, so the wait never sees EOF and the + // read runs to the helper's schedule instead of the eject's bound. This fails + // before the fix by still being in flight at the limit: the helper goes away a + // minute later, and the read returns then, which is the same class of stall the + // guard is not allowed to put a click through. + fixture := ejectableMTPLXListingRunByCLI(t, + []string{"{cli}", "listleavesahelper", listing, pidFile}, residentMTPLXAnswers()) + t.Cleanup(func() { killFakeHelper(pidFile) }) + fixture.requireState(t, true, false, "the engine starts up") + + fixture.requireEjectedWithin(t, mtplxPackRepoID, limit, + "an eject is a click, and a listing whose CLI stopped answering a second ago is not a reason to keep waiting") + + // The other direction on the same run: if the CLI had never got as far as leaving + // a helper, this case would pass on a read that was never wedged and pin nothing. + require.FileExists(t, pidFile, "the listing's CLI never left a helper holding its output") + }) + + t.Run("a listing a helper is still holding is the listing the guard refuses on", func(t *testing.T) { + // Bounding the wait must not throw the answer away. The CLI exited of its own + // accord, so the listing arrived whole, and what the join does with the rows in + // front of it is refuse — an eject that proceeded here stopped an engine serving + // a different pack. Before the fix this case parks exactly as long as the one + // above; a fix that gave up the listing to get the timing right turns it into an + // engine stopped in error. + fixture := ejectableMTPLXListingRunByCLI(t, + []string{"{cli}", "listleavesahelper", listing, pidFile}, residentMTPLXAnswers()) + t.Cleanup(func() { killFakeHelper(pidFile) }) + + err := fixture.requireRefusedWithin(t, "Youssofal/Gemma4-MTPLX-Optimized-Speed", limit, + "the pack this MTPLX's own listing does not hold") + assert.ErrorContains(t, err, "is not the model mtplx is serving") + }) + + t.Run("a listing whose CLI never answers is stopped at the bound", func(t *testing.T) { + // A pin, not a fix: this one already came back inside the bound, because the CLI + // is still the only writer on its output when the deadline kills it and the pipe + // closes with it. It is here so that a fix which dropped the caller's context into + // the command, or gave the read a budget of its own — which is what the action + // timeout already is, and the thing this is meant to shorten — fails something + // rather than quietly putting the eject back on 30 minutes. + fixture := ejectableMTPLXListingRunByCLI(t, []string{"{cli}", "holdoutput"}, residentMTPLXAnswers()) + fixture.requireState(t, true, false, "the engine starts up") + + fixture.requireEjectedWithin(t, mtplxPackRepoID, limit, + "a CLI that never answers gets killed at the bound the eject set, not waited out") + }) +} + func TestLaunchModel_RefusesAnythingThatIsNotAModelID(t *testing.T) { e := switchModelExecutor(t, "--model") before := launchTextOf(t, e) diff --git a/services/nvpair-engine-manager/lifecycle.go b/services/nvpair-engine-manager/lifecycle.go index a2ce3fd79..6de146cc4 100644 --- a/services/nvpair-engine-manager/lifecycle.go +++ b/services/nvpair-engine-manager/lifecycle.go @@ -33,6 +33,15 @@ const ( maxProbeJSONBytes = 1 << 20 ) +// probeReadTimeout is how long one read of an engine that may not be answering gets: +// the identity probe, over HTTP or over a socket; the read of where a running engine +// loaded its model from; and the residency join an eject guard asks for. They share a +// bound because they are the same kind of question — put to a process PAIR does not own, +// on the way to saying something true about it — and a caller that waited longer than +// this for one of them would be waiting, not asking. Var, not const, so a case can watch +// a caller give up on a read that never comes back without waiting out the real bound. +var probeReadTimeout = 3 * time.Second + type listenerProbeResult uint8 const ( @@ -1154,7 +1163,7 @@ func (e *Executor) probeIdentity(ctx context.Context, p *Probe, port int) probeR if err != nil { return probeResult{} } - pctx, cancel := context.WithTimeout(ctx, 3*time.Second) + pctx, cancel := context.WithTimeout(ctx, probeReadTimeout) defer cancel() req, err := http.NewRequestWithContext(pctx, http.MethodGet, u, nil) if err != nil { @@ -1247,7 +1256,7 @@ func (e *Executor) probeIdentity(ctx context.Context, p *Probe, port int) probeR if err != nil { return probeResult{} } - pctx, cancel := context.WithTimeout(ctx, 3*time.Second) + pctx, cancel := context.WithTimeout(ctx, probeReadTimeout) defer cancel() conn, err := (&net.Dialer{}).DialContext(pctx, "tcp", addr) if err != nil { diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 27ac5c32f..00faa37a1 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -541,7 +541,7 @@ type ActionResidency struct { // that reports it separately from the name it serves. It is declared apart // from the action's own HTTP call because the two are different questions: // loaded_models asks what is served, this is where the answer says it lives. - // Left unset, there is no declared place to ask, and residentPack answers + // Left unset, there is no declared place to ask, and residentJoin answers // unknown rather than going looking anyway. Read *ActionHTTP `json:"read,omitempty"` // PathField is the field in the read answer that names the loaded pack's diff --git a/services/nvpair-engine-manager/residency.go b/services/nvpair-engine-manager/residency.go index 175db215d..d49ba81c0 100644 --- a/services/nvpair-engine-manager/residency.go +++ b/services/nvpair-engine-manager/residency.go @@ -11,7 +11,6 @@ import ( "net/http" "strconv" "strings" - "time" ) // packRow is one model pack as the engine's own inventory reports it: the name it @@ -62,25 +61,6 @@ type inventoryAnswer struct { read bool } -// packInventory reads what an engine holds on disk, in the engine's terms, for an -// engine that serves one model at a time and can only be asked what it is running. -// It is how PAIR finds out which pack a running engine loaded: the answer to the -// engine's own loaded-path question is joined onto the rows read here (see -// residentPack), so a model name is not mistaken for a model just because they are -// spelled alike. -// -// The second result separates what an engine's cache holds from what PAIR managed to -// find out, because they lead to different advice. ok=false means the inventory was -// not read: the source action failed, its answer was not a listing, or it was larger -// than the body PAIR reads. ok=true with no rows is the answer "nothing is cached", so -// the two are never collapsed into each other. -// -// A caller that has already read the listing this join is declared against hands it in -// rather than running it a second time: see packInventoryFrom and inventoryAnswer. -func (e *Executor) packInventory(ctx context.Context, engine string) ([]packRow, bool) { - return e.packInventoryFrom(ctx, engine, inventoryAnswer{}) -} - // packRowLookup is where one action's answer keeps its pack rows: which array holds // them, which field keys a row, and which field says where that pack sits. It is a // recipe rather than three loose arguments because two of the three are field names in @@ -122,24 +102,37 @@ func (l packRowLookup) rowsFrom(engine, action string, raw json.RawMessage) ([]p return rows, ok } -// packInventoryFrom reads the pack rows packInventory reads, reusing an answer the -// caller has already got when it came from the action this join was declared against, -// and reading that action itself otherwise. +// packInventoryFrom reads what an engine holds on disk, in the engine's terms, reusing an +// answer the caller has already got when it came from the action this join was declared +// against, and reading that action itself otherwise. It is how PAIR finds out which packs +// a machine has; which one a running engine has loaded is found by joining the engine's own +// loaded-path answer onto these rows (see residentJoin), so a model name is not mistaken +// for a model just because they are spelled alike. +// +// The second result separates what an engine's cache holds from what PAIR managed to find +// out, because they lead to different advice. ok=false means the inventory was not read: the +// source action failed, its answer was not a listing, or it was larger than the body PAIR +// reads. ok=true with no rows is the answer "nothing is cached", so the two are never +// collapsed into each other. // // Reuse is not a shortcut past a read the engine would rather not do twice: it is one -// question about one fact, and for MTPLX the read is `mtplx models --json` — a -// subprocess, carrying the action timeout with it, rather than a request bounded by the -// residency probe's 3 s. Rows from any other action are not the rows the join was -// declared against, so a join that names another source gets its own read, and the -// listing the sweep read is still read only once. +// question about one fact, and for MTPLX the read is `mtplx models --json` — a subprocess, +// whose cost is decided by how long its output is waited on, rather than a request with a +// bound on it. Rows from any other action are not the rows the join was declared against, so +// a join that names another source gets its own read, and the listing the sweep read is +// still read only once. // -// The read runs through the action machinery, so it takes the action timeout with -// it. Whether an engine answers at all is the source action's business: HTTP actions -// are gated on a running engine and cmd actions deliberately are not (see -// dispatchAction), which is why MTPLX's manifest describes its `mtplx models --json` -// read as needing no running engine. So "the read failed" is not the same statement -// as "the engine is down" — and the fixture's HTTP stand-in answers less than a -// stopped MTPLX would. +// The read runs through the action machinery, so the caller's context is what bounds it: +// one probe read for the eject (see ejectableNames), the caller's whole request for the +// model sweep. A command that has stopped answering is ended at that bound — killed if it +// is still running, and given up on one commandDrainTimeout after it exits if it left +// something behind holding its output — so "the read failed" arrives within the time the +// caller set instead of on the schedule of whatever the engine left running. Whether an +// engine answers at all is the source action's business: HTTP actions are gated on a running +// engine and cmd actions deliberately are not (see dispatchAction), which is why MTPLX's +// manifest describes its `mtplx models --json` read as needing no running engine. So "the +// read failed" is not the same statement as "the engine is down" — and the fixture's HTTP +// stand-in answers less than a stopped MTPLX would. // // What is this function's business is keeping the lookup a lookup: a residency // source that also declared stop_engine, restart_after or launch_model would turn a @@ -189,56 +182,90 @@ func packRowForKey(rows []packRow, path string) (packRow, bool) { return packRow{}, false } -// residentPack answers which pack a running engine has mapped, as the inventory row -// the engine itself gives for it. -// -// It is a join rather than a read, because the two halves answer different questions -// in different spellings and only one of them needs a running server: packInventory -// reads what the cache holds, which for MTPLX is a CLI read that works with the -// engine stopped, and the residency read says which directory the running server -// loaded. Where those agree — one directory, string for string — PAIR has a pack it -// can name, locate and act on. Where they do not, it has one or the other and has to -// say so rather than choose. +// residentPackFrom answers which pack a running engine has mapped, as the inventory row +// the engine itself gives for it, for a caller that has already read the inventory the join +// joins against. The answer is reused only when it came from the action the join names; +// anything else, including no answer at all, reads that action once. // -// The second result is false for every case where PAIR does not know, and it is never -// the answer "nothing is resident". Nothing here could mean that: an engine that -// serves exactly one pack has to be running to have one, and each false case — no -// engine running, no read declared to ask it by, an answer that never arrived or was -// larger than PAIR reads, an answer from something that is not the engine, a directory -// no row holds — leaves what is loaded genuinely open. Reporting the empty answer -// would move a pack from loaded to not loaded on the strength of a request that -// failed, which is the same mistake as naming the wrong row, travelling the other -// way. +// The false this returns is residentJoin's "not named", which covers both "that pack is not +// the resident one" and "PAIR could not ask". A caller that only needs a name can take that +// at face value; a caller about to act on the difference, like an eject weighing whether to +// refuse, asks residentJoin, which keeps the two apart. Everything the join reads, and what +// each read costs, is on residentJoin. +func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventory inventoryAnswer) (packRow, bool) { + answer := e.residentJoin(ctx, engine, inventory) + return answer.row, answer.named +} + +// residencyAnswer is one residency join's finding, keeping apart the two things a +// caller cannot tell from a pack row alone. // -// Nothing is cached: each half is read once per call, which makes a call two reads -// rather than the one its signature suggests. They are not alike in what they cost, -// and the difference is what a caller has to plan around. The first is the probe read -// — 3 s, against a server that is answering — for where the model was loaded from. -// The second is the inventory that answer joins against: it runs through the action -// machinery, so it carries the action timeout with it (30 minutes, not 3 s), and for -// MTPLX it is a `mtplx models --json` subprocess rather than a request. That is why the -// join takes an inventory answer it did not read itself (see residentPackFrom): the -// model sweep has that listing in hand for its rows, and one sweep should run the CLI -// once. A caller that wants the row together with the served names it pairs with is -// paying three reads, not the two this join makes: asked once per row of a listing, -// this starts one CLI run per row. Re-reading is correct because an engine changes what -// it has mapped only across a load or an eject — both of which PAIR drives itself. -// Correct is not the same as cheap. -func (e *Executor) residentPack(ctx context.Context, engine string) (packRow, bool) { - return e.residentPackFrom(ctx, engine, inventoryAnswer{}) +// "No row" is not one answer. It is what PAIR says when the engine told it where the +// model was loaded from and the cache listing held no row for that directory — a real +// fact about a real pack, which rules the listing's own packs out — and it is also what +// PAIR says when it never got an answer at all, which rules nothing out. Callers that +// only want a name can take (row, named) from residentPackFrom; a caller about to act on +// the difference, like an eject that is weighing refusing, has to look at complete. +type residencyAnswer struct { + // row is the cached pack the engine says it has mapped, when it named one this + // machine has a row for. + row packRow + // named says row is that pack: the engine answered, the listing answered, and a + // row in it holds the directory in the answer. + named bool + // complete says this is all PAIR could learn from this engine about what it has + // mapped: either both halves of the join answered, or the manifest declares no + // residency read to answer with. It is false only where there was a read to make + // and no answer came — the one case in which "that pack is not the resident one" + // is a statement PAIR has no evidence for. + complete bool } -// residentPackFrom is residentPack for a caller that has already read the inventory the -// join joins against. The answer is reused only when it came from the action the join -// names; anything else, including no answer at all, reads that action once. -func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventory inventoryAnswer) (packRow, bool) { +// residentJoin answers which pack a running engine has mapped, as the inventory row the +// engine itself gives for it, keeping apart the cases a caller cannot tell from a row alone. +// +// It is a join rather than a read, because the two halves answer different questions in +// different spellings and only one of them needs a running server: packInventoryFrom reads +// what the cache holds, which for MTPLX is a CLI read that works with the engine stopped, +// and the residency read says which directory the running server loaded. Where those agree — +// one directory, string for string — PAIR has a pack it can name, locate and act on. Where +// they do not, it has one or the other and has to say so rather than choose. +// +// The row is empty for every case where PAIR does not know, and that is never the answer +// "nothing is resident". Nothing here could mean that: an engine that serves exactly one +// pack has to be running to have one, and each empty case — no engine running, no read +// declared to ask it by, an answer that never arrived or was larger than PAIR reads, an +// answer from something that is not the engine, a directory no row holds — leaves what is +// loaded genuinely open. Reading the empty row as "nothing is resident" would move a pack +// from loaded to not loaded on the strength of a request that failed, which is the same +// mistake as naming the wrong row, travelling the other way. Those cases are not alike in +// what they rule out, and complete is what keeps them apart: see residencyAnswer, and +// residentPackFrom for a caller that only wants a name. +// +// Nothing here is cached: each half is read once per call, which makes a call two reads +// rather than the one its signature suggests. They are not alike in what they cost, and the +// difference is what a caller has to plan around. The first is the probe read — 3 s, against +// a server that is answering — for where the model was loaded from. The second is the +// inventory that answer joins against: it runs through the action machinery, so the bound on +// it is the caller's own rather than the 3 s, and for MTPLX it is a `mtplx models --json` +// subprocess rather than a request. That is why the join takes an inventory answer it did not +// read itself: the model sweep has that listing in hand for its rows, and one sweep should +// run the CLI once. A caller that wants the row together with the served names it pairs with +// is paying three reads, not the two this join makes: asked once per row of a listing, this +// starts one CLI run per row. Re-reading is correct because an engine changes what it has +// mapped only across a load or an eject — both of which PAIR drives itself. Correct is not +// the same as cheap, and a caller that cannot spend that on a name — an eject, which is a +// click — bounds the join itself. See ejectableNames. +func (e *Executor) residentJoin(ctx context.Context, engine string, inventory inventoryAnswer) residencyAnswer { st, err := e.state(engine) if err != nil { - return packRow{}, false + return residencyAnswer{} } residency := residencyDeclaration(st) if residency == nil { - return packRow{}, false + // Nothing is declared to ask about what is mapped, so there is nothing here + // left unanswered: the answer is complete, and empty. + return residencyAnswer{complete: true} } if residency.Read == nil { // The manifest has not said where this engine answers where its model lives, @@ -246,7 +273,7 @@ func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventor // engine that carried the path inside its loaded_models answer would need // that declared, not inferred from whatever that answer happens to hold. slog.Debug("engine:residency no loaded-path read declared", "engine", engine) - return packRow{}, false + return residencyAnswer{complete: true} } st.mu.Lock() running, port := st.running, st.port @@ -255,8 +282,9 @@ func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventor // A clean unknown, not an error, and nothing asked. The join's second half // needs a server; the first half is readable right now, which is exactly why // the answer cannot be read off it — rows that exist on disk say nothing - // about which of them a stopped process has mapped. - return packRow{}, false + // about which of them a stopped process has mapped. Nothing was asked, so + // nothing is ruled out. + return residencyAnswer{} } // The loaded path is asked first: one bounded GET against the server that is @@ -264,12 +292,13 @@ func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventor // says nothing about its own model should not cost a subprocess. loadedPath, ok := e.loadedPackPath(ctx, engine, port, residency) if !ok { - return packRow{}, false + return residencyAnswer{} } rows, ok := e.packInventoryFrom(ctx, engine, inventory) if !ok { - return packRow{}, false + return residencyAnswer{} } + // Both halves have answered from here, so what follows is evidence. row, found := packRowForKey(rows, loadedPath) if !found { // The engine has a directory mapped that its own listing does not name: a @@ -278,9 +307,9 @@ func (e *Executor) residentPackFrom(ctx context.Context, engine string, inventor // here may stand in for it — the pack this machine does cache, shown as // loaded, is how an eject or a delete ends up aimed at the wrong directory. slog.Debug("engine:residency loaded path matched no cached pack", "engine", engine, "rows", len(rows)) - return packRow{}, false + return residencyAnswer{complete: true} } - return row, true + return residencyAnswer{row: row, named: true, complete: true} } // loadedPackPath asks a running engine which directory it loaded its model from, at @@ -305,7 +334,7 @@ func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, return "", false } requestURL := fmt.Sprintf("http://127.0.0.1:%d%s", port, path) - pctx, cancel := context.WithTimeout(ctx, 3*time.Second) + pctx, cancel := context.WithTimeout(ctx, probeReadTimeout) defer cancel() req, err := http.NewRequestWithContext(pctx, strings.ToUpper(residency.Read.Method), requestURL, nil) if err != nil { @@ -348,12 +377,12 @@ func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, // would use: for MTPLX "mtplx-flash-next-optimized-speed", where its own inventory // calls the same pack Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed. // -// It is the read the model list already makes, offered next to residentPack for a +// It is the read the model list already makes, offered next to residentJoin for a // caller that needs both halves of one answer: the row is what a cached pack's eject // or delete acts on, and the served name is what a request has to be routed by, so // neither can be derived from the other and a caller showing both has to have both. // ok is false when the engine did not answer or answered with something that is not -// a listing — which, like residentPack's false, is not "it serves nothing". +// a listing — which, like an empty residentJoin, is not "it serves nothing". func (e *Executor) servedNames(ctx context.Context, engine string) ([]string, bool) { st, err := e.state(engine) if err != nil { diff --git a/services/nvpair-engine-manager/residency_test.go b/services/nvpair-engine-manager/residency_test.go index 8c1f01c50..96d79872b 100644 --- a/services/nvpair-engine-manager/residency_test.go +++ b/services/nvpair-engine-manager/residency_test.go @@ -323,10 +323,10 @@ func residencyManifestWithRestart(t *testing.T) *Manifest { return manifest } -func TestPackInventory_ReadsRowsFromTheMeasuredModelsListing(t *testing.T) { +func TestPackInventoryFrom_ReadsRowsFromTheMeasuredModelsListing(t *testing.T) { ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: sagittariusModelsBody}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, ok, "the listing arrived whole, so the inventory is known") require.Len(t, rows, 1, "that capture holds one pack") @@ -354,10 +354,10 @@ func TestPackInventory_ReadsRowsFromTheMeasuredModelsListing(t *testing.T) { assert.False(t, found, "the join is exact, so an upper-cased spelling finds nothing") } -func TestPackInventory_KeepsTwoRootsApartAndNeverGuessesASymlink(t *testing.T) { +func TestPackInventoryFrom_KeepsTwoRootsApartAndNeverGuessesASymlink(t *testing.T) { ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: bellatrixModelsBody}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, ok, "the listing arrived whole, so the inventory is known") require.Len(t, rows, 3, "that machine caches three packs") @@ -401,13 +401,13 @@ func TestPackInventory_KeepsTwoRootsApartAndNeverGuessesASymlink(t *testing.T) { assert.False(t, found, "a trailing separator is not trimmed either") } -func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *testing.T) { +func TestPackInventoryFrom_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *testing.T) { manifest := residencyManifest(t) t.Run("an empty cache is an answer", func(t *testing.T) { ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: `{"models":[]}`}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, ok, "a listing that says nothing cached was still read") assert.Empty(t, rows, "nothing cached has to stay distinguishable from nothing read") @@ -418,7 +418,7 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes // cannot read, not a cache full of packs that went missing. ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: `{"models":[{"foo":1},{"bar":2}]}`}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "a malformed inventory must not become authoritative empty") assert.Nil(t, rows) @@ -428,7 +428,7 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes for _, body := range []string{`{}`, `{"models":null}`, `{"models":"Youssofal/Gemma4-MTPLX-Optimized-Speed"}`} { ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: body}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "a body that carries no inventory is unknown (%s)", body) assert.Nil(t, rows) @@ -442,7 +442,7 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes ex := residencyAsking(t, manifest, map[string]string{residencyInventoryPath: body}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "a truncated listing must not report the packs it happened to hold") assert.Nil(t, rows) @@ -453,7 +453,7 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes // "the read did not happen" is staged. ex := residencyAsking(t, manifest, map[string]string{}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "no answer is not an empty cache") assert.Nil(t, rows) @@ -470,7 +470,7 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes // the read does not happen: unknown, not empty. ex := newTestExecutor(t, manifest) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "a refused read cannot have produced rows") assert.Nil(t, rows) @@ -483,14 +483,14 @@ func TestPackInventory_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *tes withoutResidency.Actions["loaded_models"] = loaded ex := residencyAsking(t, withoutResidency, map[string]string{residencyInventoryPath: sagittariusModelsBody}) - rows, ok := ex.packInventory(t.Context(), "mtplx") + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) assert.False(t, ok, "no declared join means nothing was read, not that nothing is cached") assert.Nil(t, rows) }) } -func TestResidentPack_JoinsHealthModelPathWithTheCacheRow(t *testing.T) { +func TestResidentJoin_JoinsHealthModelPathWithTheCacheRow(t *testing.T) { // One running server, three questions: what does your cache hold, which // directory did you map, and what do you answer requests as. The join is the // first two meeting, and the third must not be folded in with them: the row is @@ -502,12 +502,12 @@ func TestResidentPack_JoinsHealthModelPathWithTheCacheRow(t *testing.T) { residencyServedPath: residencyServedBody, }) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - require.True(t, ok, "the directory this server mapped is a pack the cache lists, so the resident pack is known") - assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", row.repoID, + require.True(t, answer.named, "the directory this server mapped is a pack the cache lists, so the resident pack is known") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", answer.row.repoID, "the answer is the cache's own spelling of the pack, not the name the server answers to") - assert.Equal(t, mtplxServedPath, row.path, + assert.Equal(t, mtplxServedPath, answer.row.path, "the row comes back whole: a caller that has to show or remove the directory needs it") names, namesOK := ex.servedNames(t.Context(), "mtplx") @@ -515,19 +515,26 @@ func TestResidentPack_JoinsHealthModelPathWithTheCacheRow(t *testing.T) { require.True(t, namesOK, "the same server also answers what it answers to") assert.Equal(t, []string{"mtplx-flash-next-optimized-speed"}, names, "the wire name survives the join; reporting only the repo id would leave PAIR with a name no request uses") - require.NotEmpty(t, row.repoID) - assert.NotEqual(t, row.repoID, names[0], + require.NotEmpty(t, answer.row.repoID) + assert.NotEqual(t, answer.row.repoID, names[0], "had the two come back the same, one of them would have been guessed from the other rather than read") } -func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) { - // Every case here is answered `false`, and `false` is the only right answer for - // four quite different reasons: nothing to ask, an answer too big to have read, - // an answer that is not the engine, and an answer that names a pack no row - // holds. They agree on one thing, which is what these subtests pin — none of - // them may mark a row loaded. For an engine that serves exactly one pack, the - // first wrong row is not a miss but a confident claim about a pack that is - // merely cached, and that is the mistake residency exists to prevent. +func TestResidentJoin_AnswersEmptyForFourReasonsAndKeepsEvidenceApart(t *testing.T) { + // No row comes back for four quite different reasons: nothing to ask, an answer + // too big to have read, an answer that is not the engine, and an answer that + // names a pack no row holds. They agree on one thing, which is what these + // subtests have always pinned — none of them may mark a row loaded. For an + // engine that serves exactly one pack, the first wrong row is not a miss but a + // confident claim about a pack that is merely cached, and that is the mistake + // residency exists to prevent. + // + // They are not alike in what they rule out, and that is what complete is for. An + // eject weighing whether to refuse has to know whether an empty answer is + // evidence or the absence of any, so each case below says which it is, and the + // last is the one that is evidence: both halves answered, and the directory the + // engine named is one no row holds. That distinction is more than a bare `false` + // could carry, which is why these cases read the join rather than a name. manifest := residencyManifest(t) t.Run("a stopped engine is answered without asking it anything", func(t *testing.T) { @@ -542,10 +549,11 @@ func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) residencyHealthPath: residencyHealthBody(mtplxServedPath), }, &asked) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "nothing is running, so which pack it would have mapped is unknown") - assert.Equal(t, packRow{}, row, "unknown must not arrive as an empty row that some caller reads as nothing resident") + assert.False(t, answer.named, "nothing is running, so which pack it would have mapped is unknown") + assert.Equal(t, packRow{}, answer.row, "unknown must not arrive as an empty row that some caller reads as nothing resident") + assert.False(t, answer.complete, "nothing was asked, so this emptiness rules nothing out") assert.Empty(t, asked, "a stopped engine is not asked") }) @@ -560,12 +568,13 @@ func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) residencyHealthPath: residencyOversizedHealthBody(t), }) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "a truncated health answer identifies no pack") - assert.Equal(t, packRow{}, row, "no row may be marked loaded from a body that was never read") + assert.False(t, answer.named, "a truncated health answer identifies no pack") + assert.Equal(t, packRow{}, answer.row, "no row may be marked loaded from a body that was never read") + assert.False(t, answer.complete, "the half that names the directory never answered, so what is loaded stays open") - rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + rows, inventoryOK := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, inventoryOK, "the cache listing still arrived, so the unknown answer is the health read's own") assert.Len(t, rows, 1, "and it is not the unknown that emptied it") }) @@ -581,10 +590,11 @@ func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) residencyHealthPath: residencyForeignBody, }) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "an HTML body is not an engine's answer about its model") - assert.Equal(t, packRow{}, row, "no row may be marked loaded from a body that is not the engine's") + assert.False(t, answer.named, "an HTML body is not an engine's answer about its model") + assert.Equal(t, packRow{}, answer.row, "no row may be marked loaded from a body that is not the engine's") + assert.False(t, answer.complete, "an answer from something that is not this engine leaves what is loaded open") }) t.Run("a loaded path under no cache root matches no row", func(t *testing.T) { @@ -602,18 +612,25 @@ func TestResidentPack_TreatsAnUnreadableOrMatchlessHealthAsUnknown(t *testing.T) residencyHealthPath: residencyHealthBody(residencyPairBundlePath), }) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "a path no row holds has no row to return") - assert.Equal(t, packRow{}, row, "the pack this machine does cache must not stand in for the one it is serving") + assert.False(t, answer.named, "a path no row holds has no row to return") + assert.Equal(t, packRow{}, answer.row, "the pack this machine does cache must not stand in for the one it is serving") + // Where complete earns its keep. Every case above answered this same empty + // pair, and this one is the opposite of all of them: the engine said where it + // loaded and the listing said what it holds, so the emptiness is a fact about + // the pack rather than a failure to look. An eject guard may refuse on this one + // and may not refuse on any of the others, and no bare `false` said which was + // which. + assert.True(t, answer.complete, "both halves answered, so this emptiness is evidence") - rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + rows, inventoryOK := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, inventoryOK, "the listing was read, so the miss is the path's and not a failed read") require.Len(t, rows, 1, "the one pack it holds is the pack this answer is not about") }) } -func TestResidentPack_ReportsUnknownWhenOnlyATidiedPathWouldMatch(t *testing.T) { +func TestResidentJoin_JoinsNoRowWhenOnlyATidiedPathWouldMatch(t *testing.T) { // The join is exact string equality, and this pins it where the engine's answer // arrives rather than only at the comparison. Every other path in these fixtures // is already clean and single-slashed, so an extraction that tidied separators on @@ -658,12 +675,17 @@ func TestResidentPack_ReportsUnknownWhenOnlyATidiedPathWouldMatch(t *testing.T) residencyHealthPath: residencyHealthBody(tc.reported), }) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "the path this server named is not any row's path, so no pack is known") - assert.Equal(t, packRow{}, row, "a path that joins only after tidying must not mark the row it tidies to as loaded") + assert.False(t, answer.named, "the path this server named is not any row's path, so no pack is known") + assert.Equal(t, packRow{}, answer.row, "a path that joins only after tidying must not mark the row it tidies to as loaded") + // The join is exact, and it is not silent about having read: both halves + // answered, so this is an emptiness an eject refuses on rather than one it + // has to stop for. "Unknown" is the wrong word for it, and the one bool + // these cases had before complete could not tell the two apart. + assert.True(t, answer.complete, "the engine answered, the listing answered, and the miss between them is the finding") - rows, inventoryOK := ex.packInventory(t.Context(), "mtplx") + rows, inventoryOK := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) require.True(t, inventoryOK, "the listing arrived, so the miss belongs to the reported path") require.Len(t, rows, 1, "the cache holds exactly the pack this answer is one separator away from") require.Equal(t, tc.tidied, rows[0].path, "separator redundancy is the only difference between the two spellings") @@ -675,13 +697,16 @@ func TestResidentPack_ReportsUnknownWhenOnlyATidiedPathWouldMatch(t *testing.T) } } -func TestResidentPack_WithoutADeclaredReadAnswersUnknown(t *testing.T) { +func TestResidentJoin_WithoutADeclaredReadAnswersNothingWasAsked(t *testing.T) { // A residency block that names no read has not said where the loaded path is - // answered, so there is nothing to ask and no guessing where to ask it anyway. - // The fixture still answers the inventory, so the `false` cannot be blamed on a - // listing that failed to arrive: it comes from having no declared question to - // ask, and the answer must be "unknown", never the empty answer some caller - // would render as "this engine has nothing loaded". + // answered, so there is nothing to ask and no guessing where to ask it anyway. The + // fixture still answers the inventory, so an empty answer here cannot be blamed on a + // listing that failed to arrive: it comes from having no declared question to ask. + // Complete is the word for that — there is nothing this engine could still tell PAIR + // about what it has mapped — and it is still not the answer "this engine has nothing + // loaded", which is the reading a caller has to be kept off either way. It is what + // lets a guard refuse on this emptiness when it cannot refuse on the emptiness of a + // read that never came: see residencyAnswer. manifest := residencyManifest(t) loaded := manifest.Actions["loaded_models"] loaded.Result.Residency.Read = nil @@ -692,14 +717,15 @@ func TestResidentPack_WithoutADeclaredReadAnswersUnknown(t *testing.T) { residencyHealthPath: residencyHealthBody(mtplxServedPath), }, &asked) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - assert.False(t, ok, "a manifest that names no read cannot be asked what it loaded") - assert.Equal(t, packRow{}, row, "and not being able to ask is not the same as nothing being resident") + assert.False(t, answer.named, "a manifest that names no read cannot be asked what it loaded") + assert.Equal(t, packRow{}, answer.row, "and not being able to ask is not the same as nothing being resident") + assert.True(t, answer.complete, "there is no read left to make, so this emptiness is all there is to know") assert.Empty(t, asked, "so the engine is not asked") } -func TestResidentPack_ReadsAnExternallyStartedServerOnPort6666(t *testing.T) { +func TestResidentJoin_ReadsAnExternallyStartedServerOnPort6666(t *testing.T) { // Review Focus 1: a MTPLX PAIR never started, on a port PAIR never chose. The // name keeps the measurement — this is the server found on port 6666 on the Mac // these fixtures came from, kept in a settings file rather than in PAIR. The @@ -707,35 +733,39 @@ func TestResidentPack_ReadsAnExternallyStartedServerOnPort6666(t *testing.T) { // test is somebody's live session and no test may bind it, read it or disturb // it. The health answer is at the measured size all the same: a join proven // against a 30-byte stub has not been proven against a real MTPLX. - skipWithoutShell(t) - - // Nothing here reaches this user's MTPLX. The detect path is a script this test - // wrote rather than any path the manifest names, the binary is a name in a - // directory nothing is in, and the settings-file port source is dropped — that - // file is this machine's real `~/Library/Application Support/MTPLX/settings.json`, - // and reading it would both make the test depend on it and point the read at a - // live server. So the only port in the test is the one the OS handed over. - // relocationRegistry pins the same things for the same reason. + // Nothing here reaches this user's MTPLX. The tool the manifest's {cli} resolves + // to is the fake engine rather than any path the manifest names, the binary is a + // name in a directory nothing is in, and the settings-file port source is dropped + // — that file is this machine's real + // `~/Library/Application Support/MTPLX/settings.json`, and reading it would both + // make the test depend on it and point the read at a live server. So the only + // port in the test is the one the OS handed over. relocationRegistry pins the same + // things for the same reason. reg := NewRegistry() require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) manifest, platform := hostPlatformBlock(t, reg, "mtplx") port := portRun(t, 1)[0] - // The shipped inventory read is `mtplx models --json`, and no test may run a - // real MTPLX, so a script answers the same body from a file. This is also the - // only place the cmd half of the join is driven end to end: Task 1 pinned the - // cmd shapes at the extractor because no binary could be staged there. + // The shipped inventory read is `mtplx models --json`, and no test may run a real + // MTPLX, so the fake engine's CLI answers the measured body from a file: {cli} and + // a listing-answering subcommand, in place of the shipped subcommand and nothing + // else. This is also the only place the cmd half of the join is driven end to end: + // Task 1 pinned the cmd shapes at the extractor because no binary could be staged + // there. dir := t.TempDir() listing := filepath.Join(dir, "models.json") require.NoError(t, os.WriteFile(listing, []byte(sagittariusModelsBody), 0o600)) - cli := filepath.Join(dir, "mtplx"+exeExt()) - require.NoError(t, os.WriteFile(cli, []byte("#!/bin/sh\ncat '"+listing+"'\n"), 0o755)) listModels := manifest.Actions["list_models"] - listModels.Cmd = []string{cli, "models", "--json"} + listModels.Cmd = []string{"{cli}", "listfrom", listing} manifest.Actions["list_models"] = listModels - platform.Detect = []string{cli} + // {cli} follows the tool the platform is observed to have, and nothing is observed + // here: with no detect path, the manifest's own literal is the only candidate, so + // the literal is the fake engine. Staging a detect path instead would leave this + // action running a tool other than the one it wrote. + platform.Detect = nil + platform.Runtime.CLI = fakeEngineBin platform.Runtime.Bin = filepath.Join(dir, "mtplx-started-by-nobody"+exeExt()) platform.Runtime.PortSource = nil platform.Runtime.Port = port @@ -756,10 +786,10 @@ func TestResidentPack_ReadsAnExternallyStartedServerOnPort6666(t *testing.T) { residencyServedPath: residencyServedBody, }, &asked) - row, ok := ex.residentPack(t.Context(), "mtplx") + answer := ex.residentJoin(t.Context(), "mtplx", inventoryAnswer{}) - require.True(t, ok, "the pack a server PAIR did not start has mapped has to be answerable, or the card says nothing true about it") - assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", row.repoID, + require.True(t, answer.named, "the pack a server PAIR did not start has mapped has to be answerable, or the card says nothing true about it") + assert.Equal(t, "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed", answer.row.repoID, "a relocated server's answer joins to the same row a locally started one would") require.Len(t, asked, 1, "one question per call, and of the server that is running") assert.Equal(t, fmt.Sprintf("127.0.0.1:%d%s", port, residencyHealthPath), asked[0].target, diff --git a/services/nvpair-engine-manager/testdata/fakeengine/main.go b/services/nvpair-engine-manager/testdata/fakeengine/main.go index 5d0f6c875..8df58af38 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -270,6 +270,36 @@ func main() { case "holdoutput": // the helper downloadleavesahelper starts time.Sleep(time.Minute) os.Exit(2) + case "listfrom": // stand in for `mtplx models --json` answering: print the + // listing held in the named file and exit. This is a cache listing run as + // a command rather than a request, with no shell between the two. + // args: listfrom + if len(os.Args) < 3 { + os.Exit(2) + } + body, err := os.ReadFile(os.Args[2]) + if err != nil { + os.Exit(2) + } + os.Stdout.Write(body) + return + case "listleavesahelper": // stand in for `mtplx models --json` printing its + // listing and exiting while a process it started keeps that output open. + // args: listleavesahelper + if len(os.Args) < 4 { + os.Exit(2) + } + body, err := os.ReadFile(os.Args[2]) + if err != nil { + os.Exit(2) + } + helper := exec.Command(os.Args[0], "holdoutput") + helper.Stdout, helper.Stderr = os.Stdout, os.Stderr + if helper.Start() != nil || os.WriteFile(os.Args[3], []byte(strconv.Itoa(helper.Process.Pid)), 0o644) != nil { + os.Exit(2) + } + os.Stdout.Write(body) + return case "daemon", "server": if strings.Join(os.Args[1:], " ") == "daemon status --json" { if os.Getenv("PAIR_TEST_LMS_STATUS") == "command-error" { From 5729a4d141c5db7536a72f184f6c3cecfae6fc17 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 07/10] fix(engine-manager): launch MTPLX at the directory its own listing gives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MTPLX was launched with `--model ` and `--model-id `, on the understanding that the second fixed the id the server answers to. It does not: the server this Mac's MTPLX app started carries no --model-id in its arguments at all and still answers as a name that comes out of the pack, and routing keys on the pack's cache id, which PAIR gets from the residency join. A launch argument that pinned nothing while naming whichever pack was selected when it was last written is worse than nothing, so it is now removed rather than written. launch_model therefore gains two keys. `clear_flags` names a flag the engine still takes that PAIR has stopped writing; it is emptied at every change of model, on the load that replaces it and the eject that gives it back alike, and a leftover there no longer reads as a selection. `resolve: "pack-path"` looks the value up in the engine's own pack listing — the same rows the residency join reads, so a manifest that asks for the lookup must declare that join — and writes the directory the listing keeps the pack in, which is what MTPLX's app launches with. The lookup fails open: a model no listing holds, and a listing that did not arrive, are launched under the name they were given, and nothing checks whether the resulting path exists. `prepareRequestedModel` now passes the manifest's own launch_model action to changeLaunchModel instead of rebuilding one from its flags, so a manifest that declares clear_flags or resolve means it on that path too. No engine can reach it with either today, so no behaviour changes. Prose in the engine-manager README, MANIFEST.md, spec.md, services-parity.md and engine-settings.mdx, and one comment in nvpair-tui, said the cleared flag fixed the served name; they now say what the captures show. Tests are fixture-driven and run on any host: nothing reads a real pack cache, shells out to mtplx, or touches a live port. The fake engine now records what --model named and answers /health with it under model_path, as MTPLX does, so the join, the eject guard and the stale-flag repair are exercised against a server that really reports a path. Signed-off-by: Steven Beverly --- desktop/docs/services-parity.md | 17 +- .../src/ui/constants/engine-capabilities.ts | 3 +- .../modular/delete-model-restart.test.ts | 3 +- docs/engine-settings.mdx | 17 +- services/nvpair-engine-manager/MANIFEST.md | 47 +- services/nvpair-engine-manager/README.md | 33 +- services/nvpair-engine-manager/hfcache.go | 11 +- services/nvpair-engine-manager/launchmodel.go | 99 ++++- .../nvpair-engine-manager/launchmodel_test.go | 408 ++++++++++++++++-- .../manifests/mtplx.json | 8 +- .../nvpair-engine-manager/modelrequest.go | 12 +- services/nvpair-engine-manager/registry.go | 78 +++- services/nvpair-engine-manager/residency.go | 21 + .../nvpair-engine-manager/residency_test.go | 135 ++++++ services/nvpair-engine-manager/spec.md | 5 +- .../testdata/fakeengine/main.go | 12 + services/nvpair-tui/ui/engineswire.go | 7 +- 17 files changed, 812 insertions(+), 104 deletions(-) diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index 09f2ccd6b..9481d6aea 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -272,14 +272,16 @@ where they were. Like vLLM it serves one model pack per process, so Eject is a `stop_engine` action and Load is a `launch_model` action: Load rewrites the saved launch arguments and restarts the server on the new pack, restoring the previous one if it does not come -up. Two flags move together, `--model` and `--model-id`. The second fixes the id the -server answers to, which makes the served id, the name in the model list, and the -`model` field a client sends one string; started with `--model` alone, MTPLX derives -a name such as `mtplx-qwen38-27b-optimized-speed-fp16`, matching no cache entry and -no request. `loadRestartsEngine` is set for MTPLX as it is for vLLM, so the pending +up. The flag it writes is `--model`, with the directory the engine's own listing +keeps the chosen pack in, which is what MTPLX's app launches it with. `--model-id`, +written beside it until now, is declared in `clear_flags` instead: a server that +machine's MTPLX app started has no such flag in its arguments and still answers as a +name that comes out of the pack, so it pinned nothing, while a value left in it names +whichever pack was selected when it was last written. It is removed at every change of +model, the eject included. `loadRestartsEngine` is set for MTPLX as it is for vLLM, so the pending Load in the renderer's pending-actions store covers it the same way. No pack is baked into the launch arguments, and an engine with a `launch_model` action will not start -while none of its flags names a model, so a bare Start answers "MTPLX has no model +while none of the flags PAIR writes names a model, so a bare Start answers "MTPLX has no model selected; load a model to start it". Its model list comes from `mtplx models --json`, which reads the pack cache, so the @@ -733,7 +735,8 @@ entry is that one name, for routing. The whole downloaded list arrives as lists a node's vLLM and MTPLX rows from it. Each one's `loadedByEngine` names models the way that inventory does, so the served model still marks its row loaded: vLLM by the `root` of its `/v1/models`, not a `--served-model-name` alias, and MTPLX by the -`data[].id` that `--model-id` pins to the cache id. When a peer's list was not read, +residency join — the directory its `/health` reports, matched against that same +listing, since the launch carries a directory and no flag carries the id. When a peer's list was not read, `EngineModels.inventoryKnown` is false and the model manager says the downloaded models are unavailable instead of claiming none are downloaded. diff --git a/desktop/src/ui/constants/engine-capabilities.ts b/desktop/src/ui/constants/engine-capabilities.ts index 5764bba72..b6e17b0d8 100644 --- a/desktop/src/ui/constants/engine-capabilities.ts +++ b/desktop/src/ui/constants/engine-capabilities.ts @@ -122,7 +122,8 @@ export const EngineCapabilities: Record = { // deleted pack in its launch arguments, so Delete is refused on the pack // being served: eject first. deleteBlockedWhileLoaded: true, - // Load rewrites the model launch flags and restarts MTPLX on them. + // Load writes the pack's directory into MTPLX's launch arguments and + // restarts the engine on them. loadRestartsEngine: true, // Like vLLM, MTPLX takes its pack as a launch argument and PAIR will not // start it without one, so turning it on offers the picker too. diff --git a/desktop/tests/modular/delete-model-restart.test.ts b/desktop/tests/modular/delete-model-restart.test.ts index fbdcef4fe..4e8614d96 100644 --- a/desktop/tests/modular/delete-model-restart.test.ts +++ b/desktop/tests/modular/delete-model-restart.test.ts @@ -28,7 +28,8 @@ const MANIFEST_DIR = path.resolve(process.cwd(), '../services/nvpair-engine-mana const ENGINE_TYPE_BY_MANIFEST_ID: Record = { ollama: 'ollama', lmstudio: 'lm-studio', - llamacpp: 'llama-cpp' + llamacpp: 'llama-cpp', + mtplx: 'mtplx' } interface ManifestAction { diff --git a/docs/engine-settings.mdx b/docs/engine-settings.mdx index fb81a88b3..fd589c7f6 100644 --- a/docs/engine-settings.mdx +++ b/docs/engine-settings.mdx @@ -152,13 +152,18 @@ error. To choose a parser yourself, add `--tool-call-parser ` to the launch text. MTPLX also serves one model per process, and only an Apple Silicon Mac has one. -Its launch arguments name that model with `--model ` and repeat the -same id as `--model-id`, so the name the server answers to is the name the model -list shows, and choosing a different pack restarts `mtplx serve` on it. PAIR adds +Its launch arguments name that model with `--model `: PAIR writes +the directory the engine's own listing keeps the pack you chose in, which is the +spelling MTPLX's app launches with, and choosing a different pack restarts +`mtplx serve` on it. PAIR adds no sizing flags for MTPLX: there is no managed context length, memory share, or -request limit, so the pack and the engine settle those. A `--model` or -`--model-id` you write yourself is replaced with the pack you load rather than -duplicated, and any other argument is left alone. A launch that names no pack is +request limit, so the pack and the engine settle those. `--model` is replaced with +the pack you load rather than duplicated, and a pack its listing does not hold is +written as it was named, not guessed at. `--model-id` is no longer written, and one +the launch +text still carries from an older PAIR is removed whenever the model changes, +because it names whichever pack was selected when it was last written. Any other +argument is left alone. A launch that names no pack is refused, with a message to load a model, because MTPLX cannot pick one by itself. **Add model** lists the packs MTPLX publishes for its own decode path instead of searching Hugging Face, because only those packs run on it. diff --git a/services/nvpair-engine-manager/MANIFEST.md b/services/nvpair-engine-manager/MANIFEST.md index cbf4d8144..4644ad72d 100644 --- a/services/nvpair-engine-manager/MANIFEST.md +++ b/services/nvpair-engine-manager/MANIFEST.md @@ -307,23 +307,44 @@ Exactly one of `http`, `cmd`, `remove_path`, `hf_cache`, `launch_model`, removal and any rollback of the launch settings are done. - **`launch_model`** — switch the model an engine serves, for an engine with no load call because the model is a launch argument (vLLM, MTPLX). - `launch_model.flags` lists every flag that has to move together, which for - vLLM is just `["--model"]`. MTPLX also takes `--model-id`: a server started - with only `--model` answers to a derived id such as - `mtplx-qwen38-27b-optimized-speed-fp16`, which matches neither the cache - entry the user picked nor the id a client puts in its request. The action - takes `{"model": ""}` (a Hugging Face id such as `org/name`; anything - that could be read as a flag, a path or a shell fragment is refused), writes - that one value into each declared flag of the saved launch settings exactly - as the settings editor would, and restarts a running engine on it. An empty + `launch_model.flags` lists the flags PAIR writes, which for vLLM is just + `["--model"]`. The first is the flag the engine loads its weights from, and + these flags alone answer which model is selected: an engine launched without + any of them has nothing to load. `launch_model.clear_flags` names a flag the + engine still takes that PAIR has stopped writing, such as MTPLX's + `--model-id`. It is not simply left alone: a value sitting there names + whichever pack was selected when it was last written, so it is removed at + every change of model — on the load that replaces it and the eject that gives + it back alike. A flag in both lists is a manifest error, since that would + write a model into a flag and empty the same flag in one transaction, in an + order nothing in the manifest states. `launch_model.resolve: "pack-path"` + looks the value up before writing it, for an engine whose launch does not take + the name its caller uses: the pack named is replaced by the directory that + pack's own listing keeps it in, read from the `loaded_models` + `result.residency` the manifest must also declare. MTPLX wants it because its + own app launches `serve --model `, and a pack handed over that + way is loaded without the completeness checks a cache id goes through first. A + value the listing holds no row for, and a listing that could not be read, are + written as they were given: a launch argument a user typed is theirs to keep, + and a failed lookup is no licence to invent a path. + The action takes `{"model": ""}` (a Hugging Face id such as `org/name`; + anything that could be read as a flag, a path or a shell fragment is refused), + writes the value it settled on into each flag it writes, of the saved launch + settings exactly as the settings editor would, empties the flags it clears, + and restarts a running engine on the result. An empty flag list, a repeated flag, and an entry that is not a flag are manifest errors. If the new model does not come up, the previous one is restored and the error says so; a stopped engine is started on it, and asking a running engine - for the model already in the launch arguments restarts nothing. The engine's - operation lock is held from reading the launch to the last restore. An engine - with a `launch_model` action will not start while none of the declared flags + for the model already in the launch arguments restarts nothing — unless a flag + it clears still holds a value, since starting the engine on the arguments just + saved is the only way to take that model away. The engine's + operation lock is held from reading the launch to the last restore, and the + lookup included, so the launch is written against the listing read under that + lock. An engine + with a `launch_model` action will not start while none of the flags it writes names a model: it has no model selected, and refusing beats letting the - engine pick and download a default of its own. The refusal is reported as a + engine pick and download a default of its own. A leftover in a flag it only + clears is not a selection, so it does not change that. The refusal is reported as a failed start, like the other refusals before launch, so a client that does not wait for the reply still learns of it. Requires `runtime.editable_launch` diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 98f5555f5..4c05f7cfc 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -354,20 +354,29 @@ saved launch arguments and restarts the server on it, restoring the previous pac the new one does not come up, and Eject is a `stop_engine` action, because MTPLX cannot drop its model and keep running. -The model is written into two flags, `["--model", "--model-id"]`. `--model` names -the files to serve; `--model-id` fixes the id the server answers to, which is what -routing keys on. Started with `--model` alone, MTPLX derives a name such as -`mtplx-qwen38-27b-optimized-speed-fp16`, matching neither the cache entry the user -picked nor the `model` field of a client request. Passing the pack id as `--model-id` -too makes the served id, what `mtplx models --json` reports as `repo_id`, and the -name in the model list one string. `load_model` rewrites both flags together, so -neither is ever left naming the previous pack, and a flag being cleared matches both -the spaced and the `=` form. +`--model` is written with the directory the pack's own listing keeps it in, which +is what MTPLX's own app launches with, and a pack handed over that way is loaded +without the completeness checks a cache id goes through first. `--model-id` used +to be written beside it, on the understanding that it fixed the id the server +answers to. It does not: the server this machine's MTPLX app started carries no +`--model-id` anywhere in its arguments and still answers as a name that comes out +of the pack — `mtplx-flash-next-optimized-speed`, for a cache entry called +`Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed`. The id routing keys on is +the pack's cache id, which PAIR gets from the residency join — the directory +`/health` reports, matched against that same listing — and not from a launch flag. +So `launch_model` writes `--model` and declares `--model-id` in `clear_flags`: a +value left in that flag names whichever pack was selected when it was last +written, so it is removed at every change of model, on the load that replaces it +and the eject that gives the model back alike, in the spaced and the `=` form +alike. A launch argument PAIR does not manage is left exactly where it was. There is no default pack in the launch arguments, and an engine with a -`launch_model` action will not start while none of its flags names a model: the +`launch_model` action will not start while none of the flags it writes names a +model: the start is refused with "MTPLX has no model selected; load a model to start it" -instead of bringing up a server with nothing to serve. Load is what picks the first +instead of bringing up a server with nothing to serve. A name left in a flag the +action only clears is the leftover of a selection, not one, so it does not change +that. Load is what picks the first pack. `list_models` is `mtplx models --json`, which reads the pack directory rather than @@ -429,7 +438,7 @@ Requests (caller → service): | `engine:logs` | `{ engine }` | `{ lines: [LogLine] }` | | `engine:errors` | — | `{ errors: [ServiceError] }` | | `engine:catalog` | `{ engine, platform?, arch?, query?, modelSource? }` | `{ models: [{ id, name, author, url, size?, downloads, likes, updatedAt, tags, family?, parameterSize?, appleOnly? }], source, platform?, arch?, fetchedAt?, searchable?, query? }` — the models an engine can **download**, as opposed to `engine:models`, which reports what is already installed. Ollama, LM Studio, vLLM, and MTPLX have fixed sources; llama.cpp uses its selected source. Ollama's has no public API, so it is a locked list compiled into this binary from `catalog/ollama-models.json`, regenerated on demand by a developer (`npm run scrape:ollama-models` in `desktop/`) who reviews the diff; serving it needs no network. LM Studio's catalog *is* the `lmstudio-community` Hugging Face org, whose repo ids are exactly what `lms get` accepts, so it is fetched live and cached for six hours, with concurrent callers coalesced onto one request, a failed attempt — with or without a list to fall back on — followed by a backoff before the next. vLLM serves Hugging Face repos by their repo id: its browse list is the open, text-generating safetensors repos of `Qwen`, `nvidia`, `mistralai`, `microsoft` and `ibm-granite` (both `text-generation` and `image-text-to-text`), with parameter count and size, and, like llama.cpp, a `query` searches all of Hugging Face under the same rules. MTPLX loads only packs rebuilt for its own decode path, so its source is MTPLX's own published pack list (`https://mtplx.com/releases/models.json`) rather than a Hugging Face search, which would offer mostly packs the engine refuses to load; it is not searched, so the reply is the whole list for the client to filter. llama.cpp downloads any GGUF repo as `repo:quantization`; its Hugging Face browse list is the GGUF repos of `ggml-org`, `bartowski`, and `unsloth`, fetched and cached the same way, keeping only open, text-generating repos that ship a `Q4_K_M` file, each offered as `repo:Q4_K_M`. Both llama.cpp and vLLM are `searchable`. llama.cpp queries use its selected Hugging Face or ModelScope source; vLLM queries use Hugging Face. Each query is cached separately (the 20 most recently used are kept), and the reply echoes it. A query longer than 100 characters is refused rather than shortened, since a shortened one searches for something the operator did not type. Other sources ignore a query and return their whole list for the client to filter. `platform` and `arch` are the GOOS and GOARCH the models will be **installed on**, which is not always this host — a client driving a peer should name that peer. Omitting both means this host; naming a platform without an arch leaves the arch unknown rather than borrowing this host's. MLX quantizations and MTPLX packs only install on Apple Silicon, so they are marked `appleOnly` and kept only for a `darwin`/`arm64` target — an Intel Mac does not get them; the reply echoes the `platform` and `arch` it filtered for. `name` is pull-ready: it can be handed to `pull_model` verbatim. An engine with no curated source is an error, not an empty list. The Ollama reply is a single multi-megabyte frame, so every hop on its path must allow `jsonrpc.WorkerFrameBytes`. | -| `engine:models` | — | `{ models: [string], modelsByEngine: { : [string] }, loadedByEngine: { : [string] }, downloadedByEngine: { : [string] } }` — the flat de-duplicated union of every running engine's models, the per-engine breakdown keyed by engine name, and the per-engine set of models currently **loaded in memory** (all normalized from each engine's `list_models` / `loaded_models` action `result` spec). `modelsByEngine` carries a key for every running engine whose inventory was successfully queried, including an empty list = "running, no models available"; a missing key means not running / not queryable / invalid response. `loadedByEngine` uses the same known-empty distinction for residency and also omits engines with no loaded endpoint. For an engine with `advertised_models: "loaded"` (MTPLX, which serves one pack per process; vLLM advertises `"available"` and lists its complete cached models instead), `modelsByEngine` holds only the served model's name, which is what a request may be routed to, and `downloadedByEngine` holds its `list_models` inventory, read whenever it is installed, running or not, so a model manager keeps its rows after an Eject. Its `loadedByEngine` names the served model the way the inventory names it (MTPLX by the `data[].id` that its `--model-id` pins to the cache id), so the two lists agree, and is `[]` while the engine is stopped; vLLM, whose inventory is reported the same way, names the cached repository id rather than a `--served-model-name` alias. A missing `downloadedByEngine` key means the inventory was not read. The `/v1/models` HTTP surface returns the same shape. | +| `engine:models` | — | `{ models: [string], modelsByEngine: { : [string] }, loadedByEngine: { : [string] }, downloadedByEngine: { : [string] } }` — the flat de-duplicated union of every running engine's models, the per-engine breakdown keyed by engine name, and the per-engine set of models currently **loaded in memory** (all normalized from each engine's `list_models` / `loaded_models` action `result` spec). `modelsByEngine` carries a key for every running engine whose inventory was successfully queried, including an empty list = "running, no models available"; a missing key means not running / not queryable / invalid response. `loadedByEngine` uses the same known-empty distinction for residency and also omits engines with no loaded endpoint. For an engine with `advertised_models: "loaded"` (MTPLX, which serves one pack per process; vLLM advertises `"available"` and lists its complete cached models instead), `modelsByEngine` holds only the served model's name, which is what a request may be routed to, and `downloadedByEngine` holds its `list_models` inventory, read whenever it is installed, running or not, so a model manager keeps its rows after an Eject. Its `loadedByEngine` names the served model the way the inventory names it (MTPLX by the residency join, which matches the directory its `/health` reports against that same listing; the launched arguments carry that directory, and no flag carries the id), so the two lists agree, and is `[]` while the engine is stopped; vLLM, whose inventory is reported the same way, names the cached repository id rather than a `--served-model-name` alias. A missing `downloadedByEngine` key means the inventory was not read. The `/v1/models` HTTP surface returns the same shape. | | `engine:remote-get-installed` | `{ node }` | `{ engines: [EngineStatus] }` fetched from the remote node over `ec` mTLS | | `engine:remote-install` | `{ node, engine, start? }` | `{ opId, status: EngineStatus }` after the remote install (live progress via `engine:remote-progress`) | | `engine:remote-pull-model` | `{ node, engine, model?, params?, opId? }` | `{ opId, result }` after the remote pull (live progress via `engine:remote-progress`). An `opId`, under the same rules as `engine:action`'s, names the pull in place of a minted one: on its `engine:remote-progress` frames, in the reply, and to the peer. Held until every `engine:remote-cancel-pull` of that download sent before it has ended, so a retry cannot reach the peer ahead of the cancel it follows and be stopped by it | diff --git a/services/nvpair-engine-manager/hfcache.go b/services/nvpair-engine-manager/hfcache.go index 96631e1a4..db76737b5 100644 --- a/services/nvpair-engine-manager/hfcache.go +++ b/services/nvpair-engine-manager/hfcache.go @@ -391,11 +391,16 @@ func (e *Executor) deleteHFModel(ctx context.Context, st *engineState, engine, d } unselected := false if selected == id { - flags := modelLaunchFlags(st.manifest) - if edit.before.Running || len(flags) == 0 || !edit.before.Editable { + if len(modelLaunchFlags(st.manifest)) == 0 { return refused } - text, _, err := withoutLaunchFlags(edit.before.LaunchText, flags) + if edit.before.Running || !edit.before.Editable { + return refused + } + // The model is being taken out of the launch, so every flag that can carry + // one goes, including a flag this engine's action no longer writes: leaving + // a second flag holding this id would put the selection right back. + text, _, err := withoutLaunchFlags(edit.before.LaunchText, modelClearFlags(st.manifest)) if err != nil { return err } diff --git a/services/nvpair-engine-manager/launchmodel.go b/services/nvpair-engine-manager/launchmodel.go index 175c7291b..f9fd42964 100644 --- a/services/nvpair-engine-manager/launchmodel.go +++ b/services/nvpair-engine-manager/launchmodel.go @@ -82,6 +82,43 @@ func (l *launchEdit) start(ctx context.Context) error { return l.e.setDesiredEnabled(l.engine, true) } +// launchModelResolvePackPath is the one lookup a manifest can ask ActionLaunchModel to +// run on the model its caller named: replace the pack with the directory that pack's own +// listing keeps it in. MTPLX needs it because `serve --model ` runs a +// completeness gate before loading, including a Qwen-specific one, while +// `serve --model ` does not — and the directory is what its own app +// launches with, what /health reports back, and the only one of its three spellings that +// says which machine's cache the pack sits in. +const launchModelResolvePackPath = "pack-path" + +// launchModelValueFor returns the value to write into the launch for the model the caller +// named, as spec.Resolve asks. +// +// It fails open, always returning something to write rather than an error: the value the +// lookup cannot place is one PAIR does not know, and the alternatives are worse than +// writing what the user typed — inventing a path, or refusing to load an engine the user +// can start by hand. The lookup being unavailable counts as not knowing: a cache listing +// that did not arrive says nothing about whether this pack has a directory, not that it has +// none. Callers hold the engine's operation lock, so the listing is read here rather than +// before it: a pack that moved or was deleted while the caller waited is answered with the +// listing the launch is written against, not one from before the lock. +func (e *Executor) launchModelValueFor(ctx context.Context, engine string, spec *ActionLaunchModel, model string) string { + if spec.Resolve != launchModelResolvePackPath { + return model + } + rows, ok := e.packInventoryFrom(ctx, engine, inventoryAnswer{}) + if !ok { + slog.Debug("engine:pack listing unreadable, launching the model as it was named", "engine", engine) + return model + } + row, found := packRowForRepoID(rows, model) + if !found { + slog.Debug("engine:pack listing holds no row for this model, launching it as it was named", "engine", engine, "rows", len(rows)) + return model + } + return row.path +} + // switchLaunchModel is the launch_model action. An engine that serves one model // per process has no load call: the model it serves is a launch argument, so // loading a model means writing that argument into the saved launch settings @@ -165,10 +202,24 @@ func (e *Executor) changeLaunchModel(ctx context.Context, engine string, spec *A if !current.Editable { return fmt.Errorf("the launch settings of engine %q cannot be changed: %s", engine, current.Reason) } - text, changed, err := withLaunchFlags(current.LaunchText, spec.Flags, model) + // The model is written where the engine will read it, which for an engine that + // takes a directory rather than a name is not the string the caller sent. + value := e.launchModelValueFor(ctx, engine, spec, model) + text, set, err := withLaunchFlags(current.LaunchText, spec.Flags, value) + if err != nil { + return err + } + // A flag this action stopped writing is emptied alongside the change, so a name + // for some other pack cannot outlive the pack it was written for. Writing first + // matters: clearing the flags the write manages would undo it. + text, cleared, err := withoutLaunchFlags(text, spec.ClearFlags) if err != nil { return err } + // Repairing a leftover is a change of its own: an engine running on arguments + // that name a second pack has to be started on the ones just saved, however + // correct the flag it loads from already is. + changed := set || cleared if !changed && current.Running { return nil } @@ -246,11 +297,10 @@ func withLaunchFlag(text, flag, value string) (result string, changed bool, err return result, !slices.Equal(tokens, out), err } -// withLaunchFlags sets one model in every flag an engine names it by, in the -// order the manifest declares them. An engine that also reads its served id -// from a second flag (MTPLX's --model-id) needs both moved at once: leave that -// one alone and the engine answers to a name derived from the model rather than -// the id its clients, its peers and its own model list already use. +// withLaunchFlags sets one model in every flag an engine's action writes, in the +// order the manifest declares them. Each flag it manages is left holding exactly +// this value, so a flag the same transaction also has to empty is emptied after +// this rather than before: see ActionLaunchModel.ClearFlags. func withLaunchFlags(text string, flags []string, value string) (string, bool, error) { changed := false for _, flag := range flags { @@ -324,17 +374,44 @@ func dropLaunchFlag(tokens []string, flag string) (rest []string, at int) { return rest, at } -// modelLaunchFlags returns the flags an engine's launch_model action writes, or -// nil for an engine that does not choose its model by launch argument. -func modelLaunchFlags(m *Manifest) []string { +// modelLaunchSpec returns the launch_model action an engine's manifest declares, or nil +// for an engine that does not choose its model by launch argument. The manifest declares +// at most one, so which one does not have to be worked out. +func modelLaunchSpec(m *Manifest) *ActionLaunchModel { for _, act := range m.Actions { if act.LaunchModel != nil { - return act.LaunchModel.Flags + return act.LaunchModel } } return nil } +// modelLaunchFlags returns the flags an engine's launch_model action writes, or +// nil for an engine that does not choose its model by launch argument. This is the +// answer for a reader asking which model is selected, so it names only the flags +// that carry a model the engine will load: see modelClearFlags for a reader that is +// taking the model away. +func modelLaunchFlags(m *Manifest) []string { + spec := modelLaunchSpec(m) + if spec == nil { + return nil + } + return spec.Flags +} + +// modelClearFlags returns every flag that has to be left without a model when the +// engine stops serving one: the ones the action writes, and the ones it declares it no +// longer writes but the engine still takes. A leftover in the second kind is a model name +// still being handed to the engine at the next start, which for a launch-flag engine is +// how an engine comes back with a pack no list and no user named. +func modelClearFlags(m *Manifest) []string { + spec := modelLaunchSpec(m) + if spec == nil { + return nil + } + return spec.clearedFlags() +} + // launchModelValue returns the model the arguments name, taken from the first // model flag they carry. Every flag an engine names its model by says the same // model, so any one answers the question; the first is the one it loads its @@ -420,7 +497,7 @@ func (e *Executor) ejectByStopping(ctx context.Context, engine string, params js // so no start is needed to enter this state. Callers hold the operation lock and // retain their stop request until this transaction finishes. func (l *launchEdit) awaitModelAfterEject(ctx context.Context) error { - text, _, err := withoutLaunchFlags(l.before.LaunchText, modelLaunchFlags(l.st.manifest)) + text, _, err := withoutLaunchFlags(l.before.LaunchText, modelClearFlags(l.st.manifest)) if err != nil { return err } diff --git a/services/nvpair-engine-manager/launchmodel_test.go b/services/nvpair-engine-manager/launchmodel_test.go index c2ca5a3b2..014c452aa 100644 --- a/services/nvpair-engine-manager/launchmodel_test.go +++ b/services/nvpair-engine-manager/launchmodel_test.go @@ -226,9 +226,10 @@ func TestWithoutLaunchFlag_RemovesEveryFormOfTheFlag(t *testing.T) { test("absent", "--port 8001", "--port 8001", false) } -// MTPLX names the model it serves twice over: --model picks the weights, -// --model-id picks the id it answers to. Both have to move on a Load, so the -// helpers take the whole list a manifest declares. +// An engine's model can be named in more than one launch flag, and PAIR has to move +// or clear every one of them: a name left in a flag PAIR stopped writing is a second +// pack's name still being handed to the engine. So both helpers take the whole list +// a manifest declares rather than one flag. func TestWithLaunchFlags_SetsTheModelInEveryDeclaredFlag(t *testing.T) { flags := []string{"--model", "--model-id"} @@ -314,37 +315,377 @@ func TestLaunchModel_SwitchesAndRestartsARunningEngine(t *testing.T) { assert.Equal(t, gen, startGeneration(t, e), "a no-op switch restarted the engine") } -// MTPLX serves the id its --model-id says, not the id of the pack named by -// --model, so a manifest that declares both has to move them together: a Load -// that only repoints --model leaves the engine answering to a name derived from -// the weights, which no client, peer, or model list asks for. -func TestLaunchModel_SwitchesEveryFlagTheModelIsNamedBy(t *testing.T) { - e := switchModelExecutor(t, "--model", "--model-id") - // What each declared model flag says, so a lagging one shows up here rather - // than as a name mismatch somewhere else. - flagsSaying := func() map[string]string { - tokens := strings.Fields(launchTextOf(t, e)) - said := map[string]string{} - for _, flag := range []string{"--model", "--model-id"} { - if value, found := launchFlagValue(tokens, flag); found { - said[flag] = value - } +// flagsSaying is what each of flags says in the engine's saved launch text. A list +// rather than a count, so a model left behind in one flag shows up here rather than +// as a name mismatch somewhere else. +func flagsSaying(t *testing.T, e *Executor, flags ...string) map[string]string { + t.Helper() + tokens, err := parseLaunchText(launchTextOf(t, e)) + require.NoError(t, err) + said := make(map[string]string, len(flags)) + for _, flag := range flags { + if value, found := launchFlagValue(tokens, flag); found { + said[flag] = value } - return said } - const first = "Youssofal/Qwen3.8-27B-MTPLX-Optimized-Speed-FP16" + return said +} + +// inventoryRow is one pack as an engine's own listing carries it: the name it calls +// the pack and the directory that holds it. +type inventoryRow struct { + repoID string + path string +} - _, err := loadModel(t, e, first) +// packListingFixture stages an engine's pack listing in a temporary directory and +// returns the file the fake engine prints as its listing. The directories it names are +// never created: the listing is text a lookup reads, and a case that put real ones on +// disk would pass on the machine it was written on rather than on the answer. +func packListingFixture(t *testing.T, rows ...inventoryRow) string { + t.Helper() + + entries := make([]string, 0, len(rows)) + for _, row := range rows { + entries = append(entries, `{"repo_id":`+quoteJSON(row.repoID)+`,"path":`+quoteJSON(row.path)+`}`) + } + file := filepath.Join(t.TempDir(), "models.json") + require.NoError(t, os.WriteFile(file, []byte(`{"models":[`+strings.Join(entries, ",")+`]}`), 0o600)) + return file +} + +// mtplxPackListing is the listing the residency fixtures measured on one Mac: the one +// pack it caches, named by its repo id and kept in a directory spelled with a double +// dash. +func mtplxPackListing(t *testing.T) string { + t.Helper() + return packListingFixture(t, inventoryRow{repoID: mtplxPackRepoID, path: mtplxServedPath}) +} + +// packServingExecutor is a stopped fake engine on a manifest that selects its pack the +// way the shipped MTPLX manifest does: the launch flag carries the pack's directory, +// the model the caller names is looked up in the engine's own listing to find that +// directory, and --model-id is a flag PAIR clears rather than writes. The listing is +// the fixture's, staged in a temporary directory and printed by the fake engine as a +// cmd action, so the lookup runs the real action machinery with a real subprocess +// behind it and no case here asks a real MTPLX anything or reads a real cache. +func packServingExecutor(t *testing.T, listing string, launchText string) *Executor { + t.Helper() + + e := settingsExecutor(t, false) + m, ok := e.reg.Get("fake") + require.True(t, ok, "fake manifest missing") + platform := m.Platforms[hostPlatformKey()] + // An engine that serves one pack per process waits for a model and gives it back by + // stopping, which is what makes clearing a model flag a step the user can see. + platform.Runtime.WaitForModel = true + platform.Runtime.CLI = fakeEngineBin + m.Platforms[hostPlatformKey()] = platform + m.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{ + Flags: []string{"--model"}, + ClearFlags: []string{"--model-id"}, + Resolve: launchModelResolvePackPath, + }} + m.Actions["unload_model"] = Action{StopEngine: true} + m.Actions["list_models"] = Action{ + Cmd: []string{"{cli}", "listfrom", listing}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + } + // The residency block is what the lookup reads its rows from, and what says which pack + // a running server holds: the listing action it names carries the rows, and /health + // says the directory the server mapped. Where a case's eject names the pack by its + // cache id and the engine was launched by directory, that join is the only thing that + // can tell them they mean the same pack. + m.Actions["loaded_models"] = Action{ + HTTP: &ActionHTTP{Method: "GET", Path: "/v1/models"}, + Result: &ActionResult{Array: "data", Field: "id", Residency: &ActionResidency{ + Source: "list_models", Read: &ActionHTTP{Method: "GET", Path: "/health"}, + PathField: "model_path", RowPathField: "path", + }}, + } + require.NoError(t, m.Validate(), "a manifest that is not legal never reaches the code under test") + // A running engine reads the platform it was loaded with, not the manifest, so an + // engine that waits for a pack has to be told so where it will actually look. + st, err := e.state("fake") require.NoError(t, err) - assert.Equal(t, map[string]string{"--model": first, "--model-id": first}, flagsSaying()) + st.plat.Runtime.WaitForModel = true - // A second switch moves the pair again, with nothing of the first model - // left behind in either flag. - _, err = loadModel(t, e, "org/second") + state, err := e.LaunchSettings("fake") + require.NoError(t, err) + _, err = e.ConfigureLaunch(t.Context(), settings.Configure{ + Engine: "fake", + Settings: settings.Config{ServerPort: state.ServerPort, LaunchText: launchText}, + }, func() error { return nil }) + require.NoError(t, err) + return e +} + +// MTPLX answers requests as a name that comes out of the pack, not as whatever --model-id +// says: its own app runs `serve` with the pack's directory and no --model-id anywhere in +// its arguments, and that server answered +// "youssofal-qwen3.5-4b-mtplx-optimized-speed" for +// Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed, on two machines whose packs sit under +// different roots. So a launched server's name is no handle on the flag, while a value +// left in saved launch text is a name for whichever pack was selected when it was last +// written. What has to hold, at every change of model, is that no model name survives in +// a flag PAIR manages. +func TestLaunchModel_ClearsTheFlagItNoLongerWrites(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --model-id "+mtplxPackRepoID) + require.NoError(t, e.Start(t.Context(), "fake"), "start") + require.Equal(t, map[string]string{"--model-id": mtplxPackRepoID}, + flagsSaying(t, e, "--model", "--model-id"), "the case is about a launch with a stale name in it") + + _, err := loadModel(t, e, mtplxPackRepoID) + + require.NoError(t, err) + assert.Equal(t, map[string]string{"--model": mtplxServedPath}, flagsSaying(t, e, "--model", "--model-id"), + "a Load moved --model to the pack's directory and left the stale name in --model-id") +} + +// The pack PAIR launches is named by the directory its engine's own listing gives, +// because that is the spelling the app launches with, the spelling /health answers +// under, and the only one of MTPLX's three spellings that says which of two machines' +// caches a pack sits in. +func TestLaunchModel_ServesThePackAtThePathItsOwnListingGives(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101") + require.NoError(t, e.Start(t.Context(), "fake"), "start") + + raw, err := loadModel(t, e, mtplxPackRepoID) require.NoError(t, err) - assert.Equal(t, map[string]string{"--model": "org/second", "--model-id": "org/second"}, flagsSaying()) + assert.Equal(t, loadReply{Model: mtplxPackRepoID, Restarted: true}, decodeLoadReply(t, raw), + "the reply keeps naming the pack the caller asked for, not the directory PAIR wrote") + assert.Equal(t, map[string]string{"--model": mtplxServedPath}, flagsSaying(t, e, "--model", "--model-id"), + "the launch names the pack by the directory its own listing gives") + + // The pack is already the one being served, so nothing restarts: the check is + // against what is in the launch, which is a directory, not against the name the + // caller used. + gen := startGeneration(t, e) + raw, err = loadModel(t, e, mtplxPackRepoID) + require.NoError(t, err) + assert.False(t, decodeLoadReply(t, raw).Restarted, "a load of the pack already served restarted the engine") + assert.Equal(t, gen, startGeneration(t, e), "a load of the pack already served restarted the engine") +} + +// A model that is neither a pack in the listing nor a directory one of them sits in is +// left exactly as it was typed. PAIR does not know what it is, and a launch argument a +// user wrote is theirs to keep: the alternative is a lookup failure turning into a +// wrong path, or into a refused Load for an engine the user can start by hand. +func TestLaunchModel_LeavesAModelNoListingHoldsExactlyAsTyped(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --model-id "+mtplxPackRepoID) + require.NoError(t, e.Start(t.Context(), "fake"), "start") + const handTyped = "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed-Experimental" + + _, err := loadModel(t, e, handTyped) + + require.NoError(t, err, "a model PAIR cannot place must still be loadable") + said := flagsSaying(t, e, "--model", "--model-id") + assert.Equal(t, handTyped, said["--model"], "the name was rewritten, not left alone") + assert.NotContains(t, said, "--model-id", "and the flag PAIR only clears was not left holding another pack's name") +} + +// The other way a lookup comes back knowing nothing: the listing itself did not arrive. +// That is not the statement that this pack has no directory, and a user who chose a pack +// should not be refused a load because a helper command failed — so the pack is launched +// under the name it was given, exactly as a name no listing holds is. +func TestLaunchModel_NamesThePackAsGivenWhenItsListingDoesNotArrive(t *testing.T) { + missingListing := filepath.Join(t.TempDir(), "models-that-never-came.json") + e := packServingExecutor(t, missingListing, "serve --host 127.0.0.1 --port 8101") + require.NoError(t, e.Start(t.Context(), "fake"), "start") + + _, err := loadModel(t, e, mtplxPackRepoID) + + require.NoError(t, err, "a listing that did not arrive refused the load the user asked for") + assert.Equal(t, map[string]string{"--model": mtplxPackRepoID}, flagsSaying(t, e, "--model", "--model-id"), + "the pack was launched under the name it was given, which is all PAIR knows about it") +} + +// Clearing is not only a Load's job: ejecting is the other way a model stops being the +// selected one, and a name left in any flag PAIR manages comes back as the selected +// model the next time the engine starts. +func TestEjectByStopping_ClearsEveryFlagTheModelWasNamedIn(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --model-id Youssofal/SomeOtherPack") + require.NoError(t, e.Start(t.Context(), "fake"), "start") + _, err := loadModel(t, e, mtplxPackRepoID) + require.NoError(t, err) + require.Equal(t, map[string]string{"--model": mtplxServedPath}, flagsSaying(t, e, "--model", "--model-id")) + + _, err = ejectEngine(t, e, mtplxPackRepoID) + + require.NoError(t, err) + assert.Empty(t, flagsSaying(t, e, "--model", "--model-id"), + "an eject left a model selected in a flag the engine still gets") + assert.True(t, mustStatus(t, e).AwaitingModel, "an engine with no model selected is waiting for one") + assert.False(t, mustStatus(t, e).Running, "the eject did not stop the engine") +} + +// An engine whose model is a launch argument cannot start without one, and a name in a +// flag PAIR only ever clears is not a selection: it is the leftover of one. Reading it +// as a selection starts the engine with no pack to load, which is worse than leaving it +// waiting for the user to choose. +func TestStart_KeepsAnEngineWaitingWhenOnlyAClearedFlagNamesAModel(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --model-id "+mtplxPackRepoID) + + require.NoError(t, e.Start(t.Context(), "fake")) + + status := mustStatus(t, e) + assert.True(t, status.AwaitingModel, "an engine with no pack flag started anyway: %v", launchTextOf(t, e)) + assert.False(t, status.Running, "an engine with no pack flag was launched") + assert.Equal(t, map[string]string{"--model-id": mtplxPackRepoID}, flagsSaying(t, e, "--model", "--model-id"), + "waiting for a model must not rewrite the user's launch text") +} + +// A model flag left behind gets into saved launch text more than one way — PAIR wrote +// it when it was the flag it wrote, a user typed it, or a user copied a launch line from +// somewhere — so the clear is tried against each spelling rather than the one this +// machine happens to have. Each spelling is checked at both jobs that end a model: the +// load that replaces it and the eject that gives it back. The eject case starts with the +// pack flag already holding the right directory, so what is left for the eject to do about +// the other flag is its own, not something the load did first. +func TestLaunchModel_ClearsAStaleModelFlagHoweverItIsWritten(t *testing.T) { + const base = "serve --host 127.0.0.1 --port 8101" + for _, spelling := range []struct{ name, stale string }{ + {"named after the flag", "--model-id " + mtplxPackRepoID}, + {"joined to it by an equals sign", "--model-id=" + mtplxPackRepoID}, + {"quoted after the equals sign", `--model-id="` + mtplxPackRepoID + `"`}, + } { + t.Run(spelling.name, func(t *testing.T) { + t.Run("when a load takes the model's place", func(t *testing.T) { + e := packServingExecutor(t, mtplxPackListing(t), base+" "+spelling.stale) + require.NoError(t, e.Start(t.Context(), "fake"), "start") + require.Equal(t, map[string]string{"--model-id": mtplxPackRepoID}, + flagsSaying(t, e, "--model", "--model-id"), "the launch has the stale name to begin with") + + _, err := loadModel(t, e, mtplxPackRepoID) + + require.NoError(t, err) + assert.Equal(t, map[string]string{"--model": mtplxServedPath}, + flagsSaying(t, e, "--model", "--model-id")) + }) + t.Run("when an eject gives the model back", func(t *testing.T) { + e := packServingExecutor(t, mtplxPackListing(t), base+" --model "+mtplxServedPath+" "+spelling.stale) + require.NoError(t, e.Start(t.Context(), "fake"), "start") + + _, err := ejectEngine(t, e, mtplxPackRepoID) + + require.NoError(t, err) + assert.Empty(t, flagsSaying(t, e, "--model", "--model-id")) + assert.True(t, mustStatus(t, e).AwaitingModel, "an eject that cleared the model left the engine not waiting for one") + }) + }) + } +} + +// The whole reason for clearing a second flag is that PAIR does not otherwise touch the +// launch it is given, so an argument it does not manage has to come through a load and an +// eject exactly as it went in — including the ones that look like they belong to a model. +func TestLaunchModel_LeavesUnmanagedArgumentsWhereTheyWere(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --unsafe-force-unverified --yes --memory-limit 48g --model-id "+mtplxPackRepoID) + require.NoError(t, e.Start(t.Context(), "fake"), "start") + + _, err := loadModel(t, e, mtplxPackRepoID) + require.NoError(t, err) + _, err = ejectEngine(t, e, mtplxPackRepoID) + require.NoError(t, err) + + text := launchTextOf(t, e) + for _, kept := range []string{"--unsafe-force-unverified", "--yes", "--memory-limit 48g"} { + assert.Contains(t, text, kept, "an argument PAIR does not manage did not survive the model changing") + } + assert.NotContains(t, text, "model-id", "a flag PAIR clears left a trace") + assert.Empty(t, flagsSaying(t, e, "--model", "--model-id")) +} + +// The other half of reading a selection from the load flag: text that names a pack the +// engine can load, beside a cleared flag holding another pack's name, is a selected model, +// and the directory is what answers for it. The running engine's own arguments named a +// different pack than the launch PAIR saves, so the load has to start it again on the +// saved ones — the name it carried is the mis-identification this clears. +func TestStart_TakesTheLoadFlagAsTheSelectedModelBesideAClearedFlag(t *testing.T) { + listing := mtplxPackListing(t) + e := packServingExecutor(t, listing, "serve --host 127.0.0.1 --port 8101 --model "+mtplxServedPath+" --model-id Youssofal/SomeOtherPack") + + require.NoError(t, e.Start(t.Context(), "fake"), "an engine with a load flag started") + + status := mustStatus(t, e) + assert.False(t, status.AwaitingModel, "an engine with a pack selected was left waiting for one") + assert.True(t, status.Running, "an engine with a pack selected was not started") + + raw, err := loadModel(t, e, mtplxPackRepoID) + + require.NoError(t, err) + reply := decodeLoadReply(t, raw) + assert.Equal(t, mtplxPackRepoID, reply.Model, "the reply names the pack the caller asked for, not the directory") + assert.True(t, reply.Restarted, "an engine started on arguments naming another pack kept them") + assert.Equal(t, map[string]string{"--model": mtplxServedPath}, flagsSaying(t, e, "--model", "--model-id"), + "the pack flag kept the directory it already held, and the other flag's name for another pack is gone") +} + +// The manifest is where this answer has to live, so the shipped one is pinned, not a +// fixture's copy: the launch names the pack by the directory its own listing gives, the +// flag PAIR no longer writes is named as one it clears, and the lookup it asks for is one +// the residency declaration can actually answer. +func TestMTPLXManifest_NamesItsPackByTheDirectoryItsOwnListingGives(t *testing.T) { + reg := NewRegistry() + require.NoError(t, reg.LoadFS(bundledManifests, "manifests")) + m, ok := reg.Get("mtplx") + require.True(t, ok, "mtplx manifest not loaded") + + load := m.Actions["load_model"] + require.NotNil(t, load.LaunchModel, "load_model must switch the pack through a launch argument") + assert.Equal(t, []string{"--model"}, load.LaunchModel.Flags, + "the flag that picks the weights is the only one PAIR writes") + assert.Equal(t, []string{"--model-id"}, load.LaunchModel.ClearFlags, + "--model-id has to be cleared wherever the model changes, not merely stopped being written") + assert.Equal(t, launchModelResolvePackPath, load.LaunchModel.Resolve, + "the caller names a pack, and the engine has to be given the directory that pack sits in") + + loaded := m.Actions["loaded_models"] + require.NotNil(t, loaded.Result, "loaded_models has to say which pack the server serves") + residency := loaded.Result.Residency + require.NotNil(t, residency, + "resolving a pack to its directory reads the same listing residency reads, so it has to be declared") + assert.Equal(t, "list_models", residency.Source) + assert.Equal(t, "path", residency.RowPathField, + "the launch gets the directory the listing itself gives, not one derived from a name") + + assert.True(t, m.Actions["unload_model"].StopEngine, + "ejecting is the other way a model stops being selected, and it is the one that clears") +} + +func TestLaunchModelAction_ClearFlagsAreFlagsPAIRStopsWriting(t *testing.T) { + accept := func(name string, spec ActionLaunchModel) { + t.Run(name, func(t *testing.T) { + assert.NoError(t, (&Action{LaunchModel: &spec}).validate("load_model")) + }) + } + reject := func(name string, spec ActionLaunchModel) { + t.Run(name, func(t *testing.T) { + assert.Error(t, (&Action{LaunchModel: &spec}).validate("load_model")) + }) + } + with := func(clearFlags []string, resolve string) ActionLaunchModel { + return ActionLaunchModel{Flags: []string{"--model"}, ClearFlags: clearFlags, Resolve: resolve} + } + accept("a flag to clear alongside the flag it writes", with([]string{"--model-id"}, "")) + accept("clearing several flags", with([]string{"--model-id", "--served-model-name"}, "")) + accept("resolving the model through the engine's pack listing", with([]string{"--model-id"}, launchModelResolvePackPath)) + accept("no extra flags at all", with(nil, "")) + reject("a clear flag that is not a flag", with([]string{"model-id"}, "")) + reject("a clear flag with a value in it", with([]string{"--model-id=x"}, "")) + reject("a clear flag listed twice", with([]string{"--model-id", "--model-id"}, "")) + // A flag in both lists is a manifest that both writes a model into a flag and + // removes it, in the same transaction, in an order nothing in the manifest says. + reject("a flag both written and cleared", with([]string{"--model"}, "")) + reject("a resolution no lookup implements", with(nil, "public-model-id")) } // startGeneration counts how many times the engine has been started. @@ -555,15 +896,20 @@ func ejectableMTPLXStagedManifest(t *testing.T, changeManifest func(manifest *Ma manifest := residencyManifestWithRestart(t) platform := manifest.Platforms[hostPlatformKey()] - // The four keys the shipped manifest declares for an engine that serves one pack per + // The five keys the shipped manifest declares for an engine that serves one pack per // process: it waits for a model, it serves on a host and port it is told, it names - // the pack to serve with --model, and ejecting that model stops the engine rather - // than dropping it. Without them the eject these cases are about is a different - // action, and an engine with no launch arguments has no launch to keep. + // the pack to serve with the directory its own listing gives, it clears a flag it no + // longer writes, and ejecting that model stops the engine rather than dropping it. + // Without them the eject these cases are about is a different action, and an engine + // with no launch arguments has no launch to keep. platform.Runtime.WaitForModel = true platform.Runtime.Args = []string{"serve", "--host", "{host}", "--port", "{port}"} manifest.Platforms[hostPlatformKey()] = platform - manifest.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model", "--model-id"}}} + manifest.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{ + Flags: []string{"--model"}, + ClearFlags: []string{"--model-id"}, + Resolve: launchModelResolvePackPath, + }} manifest.Actions["unload_model"] = Action{StopEngine: true} if changeManifest != nil { changeManifest(manifest) diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index c22e9540c..2afdd342d 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -53,7 +53,7 @@ "result": { "array": "models", "field": "repo_id" } }, "loaded_models": { - "description": "List the model this MTPLX server serves (it serves exactly one). The name it answers with is not the cache id: a machine serving the Qwen3.5 pack answered \"youssofal-qwen3.5-4b-mtplx-optimized-speed\" while its cache lists that pack as \"Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed\", so no spelling of the served name can be matched to a pack by eye. /health reports the directory the pack was loaded from, and that is what residency joins to the listing.", + "description": "List the model this MTPLX server serves (it serves exactly one). The name it answers with is not the cache id: a machine serving the Qwen3.5 pack answered \"youssofal-qwen3.5-4b-mtplx-optimized-speed\" while its cache lists that pack as \"Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed\", so no spelling of the served name can be matched to a pack by eye. /health reports the directory the pack was loaded from, and that is what residency joins to the listing. The same listing is where load_model reads a pack's directory from.", "http": { "method": "GET", "path": "/v1/models" }, "result": { "array": "data", @@ -67,11 +67,11 @@ } }, "load_model": { - "description": "Serve a different model pack (params: {\"model\": \"\"}). MTPLX serves one model per process, so this saves the model into the launch arguments and restarts the engine on it; if the new model does not start, the previous one is restored. --model-id is written beside --model so the served name stays the cache id.", - "launch_model": { "flags": ["--model", "--model-id"] } + "description": "Serve a different model pack (params: {\"model\": \"\"}). MTPLX serves one model per process, so this saves the model into the launch arguments and restarts the engine on it; if the new model does not start, the previous one is restored. The argument written is --model with the directory the pack's own listing keeps it in, which is what MTPLX's own app launches with, and a pack given that way is loaded without the completeness checks a cache id goes through first. --model-id is not written: an MTPLX answers as a name that lives inside the pack however it was launched, so the flag pinned nothing, and a value already sitting there is removed, because it names whichever pack was selected when it was last written.", + "launch_model": { "flags": ["--model"], "clear_flags": ["--model-id"], "resolve": "pack-path" } }, "unload_model": { - "description": "Eject the model MTPLX is serving (params: {\"model\": \"\"}). MTPLX cannot drop its model and keep running, so this stops the engine, which frees all of its memory. Load starts it again.", + "description": "Eject the model MTPLX is serving (params: {\"model\": \"\"}). MTPLX cannot drop its model and keep running, so this stops the engine, which frees all of its memory, and takes the pack out of the launch arguments so the engine waits for a model to be chosen instead of coming back on the last one. Load starts it again.", "stop_engine": true }, "pull_model": { diff --git a/services/nvpair-engine-manager/modelrequest.go b/services/nvpair-engine-manager/modelrequest.go index 3a0f1edbb..0154164a3 100644 --- a/services/nvpair-engine-manager/modelrequest.go +++ b/services/nvpair-engine-manager/modelrequest.go @@ -34,8 +34,8 @@ func (e *Executor) prepareRequestedModel(ctx context.Context, engine, model stri st.mu.Lock() allowed := st.plat != nil && st.plat.Runtime.WaitForModel st.mu.Unlock() - flags := modelLaunchFlags(st.manifest) - if !allowed || len(flags) == 0 { + spec := modelLaunchSpec(st.manifest) + if !allowed || spec == nil || len(spec.Flags) == 0 { return 0, errors.New("this engine does not support request-triggered model loading") } if port, serving, err := e.servingRequestModel(ctx, st, engine, model); err != nil || serving { @@ -45,7 +45,13 @@ func (e *Executor) prepareRequestedModel(ctx context.Context, engine, model stri if err != nil { return 0, err } - if _, err := e.changeLaunchModel(ctx, engine, &ActionLaunchModel{Flags: flags}, params, true); err != nil { + // The manifest's own action, not one rebuilt from its flags: a manifest that asks + // for a lookup or names a flag to clear means it for every launch, and dropping + // either here would make this path launch differently from a Load. Nothing reaches + // here except an engine set to load on request, which is a property of the engine + // type rather than of its manifest — declaring launch_model.resolve does not open + // this path, and no manifest that has it can arrive by it today. + if _, err := e.changeLaunchModel(ctx, engine, spec, params, true); err != nil { return 0, err } state, err := e.Status(engine) diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index 00faa37a1..cd4240925 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -587,14 +587,47 @@ type ActionHFPull struct { Dir string `json:"dir"` } -// ActionLaunchModel names the launch flags that select the engine's model, such -// as "--model". An engine that also names the model somewhere else lists every -// flag that has to move together: MTPLX serves whatever --model-id says, so a -// launch that rewrites only --model keeps answering to the derived id no client -// asks for. The action takes {"model": ""}, writes it into every declared -// flag of the saved launch settings and restarts a running engine on it. +// ActionLaunchModel names the launch flags that select the engine's model, such as +// "--model", and takes {"model": ""}: it writes that value into the saved launch +// settings and restarts a running engine on it. +// +// Flags are the flags PAIR writes, and the first is the one the engine loads its weights +// from: it alone answers "which model is selected", because an engine launched without it +// has nothing to load. +// +// ClearFlags names a flag the engine still takes that PAIR has stopped writing. It is not +// simply left alone: a value sitting there is a name for whichever pack was selected when +// it was last written, so it is removed at every change of model — the load that replaces +// it and the eject that gives it back alike. A flag may not be in both lists, which would +// ask PAIR to write a model into a flag and empty the same flag in one transaction. +// +// Resolve names a lookup run on the value before it is written, for an engine whose launch +// does not take the name its caller uses. "pack-path" replaces the pack the caller named +// with the directory that pack's own listing keeps it in, which needs a loaded_models +// result.residency declaration to read those rows from. A value the lookup cannot place — +// one the listing does not hold, or a listing PAIR could not read — is written as it was +// given, because a launch argument a user wrote is theirs to keep and a failed lookup is +// no licence to write a path. type ActionLaunchModel struct { - Flags []string `json:"flags"` + Flags []string `json:"flags"` + ClearFlags []string `json:"clear_flags,omitempty"` + Resolve string `json:"resolve,omitempty"` +} + +// clearedFlags is every flag a site that takes the model away has to leave empty: the +// ones the action writes, since the model is being taken out of them, and the ones it no +// longer writes, since a leftover there is a model name still being handed to the engine. +// Only a site that writes nothing takes this list — one that writes the model first would +// undo its own write, because the write collapses each flag it manages to a single +// occurrence. The sites that ask which model is selected read Flags alone: a flag this +// engine no longer writes is the leftover of a selection, not one. +func (a *ActionLaunchModel) clearedFlags() []string { + if len(a.ClearFlags) == 0 { + return a.Flags + } + flags := make([]string, 0, len(a.Flags)+len(a.ClearFlags)) + flags = append(flags, a.Flags...) + return append(flags, a.ClearFlags...) } // ActionHTTP is a templated call against the engine's loopback base URL. @@ -1018,6 +1051,18 @@ func (m *Manifest) Validate() error { return fmt.Errorf("action %q: launch_model requires platform %q to declare runtime.ready", name, key) } } + // A lookup is only as good as the rows it reads, and a manifest that says + // "resolve" without declaring where the engine's pack rows come from has + // asked for a lookup with nothing to look in. loaded_models result.residency + // is the declared place those rows are read from — the same listing the + // residency join reads, so a launch and an eject cannot end up disagreeing + // about which directories this engine's cache holds. + if a.LaunchModel.Resolve == launchModelResolvePackPath { + loaded, ok := m.Actions["loaded_models"] + if !ok || loaded.Result == nil || loaded.Result.Residency == nil { + return fmt.Errorf("action %q: launch_model.resolve %q requires a loaded_models result.residency to read the pack rows from", name, launchModelResolvePackPath) + } + } } if a.RestartAfter { for key, p := range m.Platforms { @@ -1391,6 +1436,25 @@ func (a *Action) validate(name string) error { } seen[flag] = true } + // A flag PAIR clears is one it hands to the engine with no model in it, so it is + // spelled the same way and has to stay out of the list it writes: a flag in both + // would be set and emptied by one transaction, in an order no manifest states. + cleared := make(map[string]bool, len(a.LaunchModel.ClearFlags)) + for _, flag := range a.LaunchModel.ClearFlags { + if !strings.HasPrefix(flag, "-") || strings.ContainsAny(flag, " \t=") { + return fmt.Errorf("action %q: launch_model.clear_flags entry %q must be a flag such as \"--model-id\"", name, flag) + } + if seen[flag] { + return fmt.Errorf("action %q: launch_model.clear_flags lists %q, which launch_model.flags writes; a flag cannot be both", name, flag) + } + if cleared[flag] { + return fmt.Errorf("action %q: launch_model.clear_flags lists %q twice", name, flag) + } + cleared[flag] = true + } + if a.LaunchModel.Resolve != "" && a.LaunchModel.Resolve != launchModelResolvePackPath { + return fmt.Errorf("action %q: launch_model.resolve %q invalid (want %q)", name, a.LaunchModel.Resolve, launchModelResolvePackPath) + } } if hasHFCache && strings.TrimSpace(a.HFCache.Dir) == "" { return fmt.Errorf("action %q: hf_cache.dir is required", name) diff --git a/services/nvpair-engine-manager/residency.go b/services/nvpair-engine-manager/residency.go index d49ba81c0..39769e527 100644 --- a/services/nvpair-engine-manager/residency.go +++ b/services/nvpair-engine-manager/residency.go @@ -182,6 +182,27 @@ func packRowForKey(rows []packRow, path string) (packRow, bool) { return packRow{}, false } +// packRowForRepoID finds the row for the pack named exactly this way — the key its own +// listing carries, which is the spelling PAIR's model list, a request, and a delete all +// use, and the only one a caller can be holding when the question is "where does that pack +// sit?". +// +// Like packRowForKey the comparison is exact, for the same reason and with the same +// consequence: the three other spellings one pack has (its directory, the name its running +// server answers as, and any case or separator variant of the key) find nothing here. That +// is the whole safety of the lookup. A caller that took the nearest row instead would hand +// the engine a directory holding a different pack, which is worse than launching nothing, +// and on the two Macs measured the nearest row is a real pack under the other machine's +// root. +func packRowForRepoID(rows []packRow, repoID string) (packRow, bool) { + for _, row := range rows { + if row.repoID == repoID { + return row, true + } + } + return packRow{}, false +} + // residentPackFrom answers which pack a running engine has mapped, as the inventory row // the engine itself gives for it, for a caller that has already read the inventory the join // joins against. The answer is reused only when it came from the action the join names; diff --git a/services/nvpair-engine-manager/residency_test.go b/services/nvpair-engine-manager/residency_test.go index 96d79872b..43e987ffe 100644 --- a/services/nvpair-engine-manager/residency_test.go +++ b/services/nvpair-engine-manager/residency_test.go @@ -401,6 +401,86 @@ func TestPackInventoryFrom_KeepsTwoRootsApartAndNeverGuessesASymlink(t *testing. assert.False(t, found, "a trailing separator is not trimmed either") } +// TestPackRowForRepoID_GivesTheDirectoryTheListingKeepsTheNamedPackIn is the lookup a +// launch goes through: the model list and a request name a pack, and what the engine has +// to be given is the directory the listing keeps it in. It runs against the two machines' +// listings because that is where the answer differs — the same pack name on a second +// machine sits under a second root — and against a directory on this machine because a +// lookup that only worked for the two paths it was written from would not be a lookup. +func TestPackRowForRepoID_GivesTheDirectoryTheListingKeepsTheNamedPackIn(t *testing.T) { + localPack := filepath.Join(t.TempDir(), "Youssofal--Qwen3.8-Flash-Next-MTPLX-Optimized-Speed") + localListing := `{"models":[{"repo_id":` + quoteJSON(mtplxPackRepoID) + `,"path":` + quoteJSON(localPack) + `}]}` + + for _, tc := range []struct { + name string + listing string + repoID string + want string + }{ + { + name: "the machine these listings came from", listing: sagittariusModelsBody, + repoID: mtplxPackRepoID, want: mtplxServedPath, + }, + { + name: "a second machine, under its own root", listing: bellatrixModelsBody, + repoID: "Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed", + want: "/Users/steven/.mtplx/models/Youssofal--Qwen3.5-4B-MTPLX-Optimized-Speed", + }, + { + name: "a cache root this machine made for itself", listing: localListing, + repoID: mtplxPackRepoID, want: localPack, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: tc.listing}) + + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) + + require.True(t, ok, "the listing arrived whole, so the cache is known") + row, found := packRowForRepoID(rows, tc.repoID) + require.True(t, found, "the listing names this pack, so its directory is answerable") + assert.Equal(t, tc.want, row.path, "the launch gets the directory this listing gives for this pack") + }) + } +} + +// TestPackRowForRepoID_FindsNothingForAnyOtherSpellingOfAPack is the lookup's other half, +// and the one that keeps a failed lookup from becoming a wrong path: a name the listing +// does not key a row by finds nothing, so the caller leaves the model it was given alone +// rather than launching a pack nobody asked for. +func TestPackRowForRepoID_FindsNothingForAnyOtherSpellingOfAPack(t *testing.T) { + ex := residencyAsking(t, residencyManifest(t), map[string]string{residencyInventoryPath: sagittariusModelsBody}) + + rows, ok := ex.packInventoryFrom(t.Context(), "mtplx", inventoryAnswer{}) + + require.True(t, ok, "the listing arrived whole, so the cache is known") + + // The same pack has three other spellings and only one of them is a row key: the + // directory it sits in, and the name its running server answers requests as, are the + // other two. + _, found := packRowForRepoID(rows, mtplxServedPath) + assert.False(t, found, "the directory a pack sits in is not the name the listing keys it by") + _, found = packRowForRepoID(rows, mtplxServedModel) + assert.False(t, found, "the name the server answers as is not the name the listing keys it by") + _, found = packRowForRepoID(rows, strings.ToUpper(mtplxPackRepoID)) + assert.False(t, found, "the lookup is exact, so an upper-cased name finds nothing") + _, found = packRowForRepoID(rows, mtplxPackRepoID+"/") + assert.False(t, found, "a trailing separator is not trimmed") + + // The other machine's packs are not this machine's. A lookup that settled for the + // closest row — by prefix, by folder name, or by "the other root on this host" — + // answers a pack this cache does not hold with a directory that holds a different + // one, and the engine loads the wrong weights. + for _, other := range []string{ + "Youssofal/Qwen3.5-4B-MTPLX-Optimized-Speed", + "Youssofal/Qwen3.8-Flash-Next-MTPLX-Optimized-Speed-Experimental", + "Youssofal/Qwen3.8-Flash-Next", + } { + _, found := packRowForRepoID(rows, other) + assert.False(t, found, "a name no row is keyed by finds nothing (%s)", other) + } +} + func TestPackInventoryFrom_TreatsAnEmptyListingAsKnownAndABlockedOneAsUnknown(t *testing.T) { manifest := residencyManifest(t) @@ -965,6 +1045,61 @@ func TestManifest_TheBundledMTPLXManifestDeclaresThePackJoin(t *testing.T) { assert.Empty(t, residency.RowKeyField, "the row key is the listing's own field, not a second spelling") } +// A launch that takes a pack's directory instead of its name finds that directory in the +// engine's own listing, which is the same listing the residency declaration says how to +// read. A manifest that asks for the lookup without declaring that has asked to look in +// nothing, and the two could drift apart just as easily as the launch and the eject could. +func TestManifestValidate_RejectsAPackPathLaunchWithNoListingToRead(t *testing.T) { + packPathLaunch := func(t *testing.T) *Manifest { + t.Helper() + + manifest := residencyManifestWithRestart(t) + manifest.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{ + Flags: []string{"--model"}, + ClearFlags: []string{"--model-id"}, + Resolve: launchModelResolvePackPath, + }} + manifest.Actions["unload_model"] = Action{StopEngine: true} + require.NoError(t, manifest.Validate(), "this is the shape the shipped MTPLX manifest has") + return manifest + } + + withoutTheJoin := func(manifest *Manifest) { + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency = nil + manifest.Actions["loaded_models"] = loaded + } + + t.Run("with the listing removed from what loaded_models declares", func(t *testing.T) { + manifest := packPathLaunch(t) + withoutTheJoin(manifest) + + err := manifest.Validate() + + require.Error(t, err, "a lookup with nowhere to read its rows is not a lookup") + assert.Contains(t, err.Error(), "result.residency") + }) + + t.Run("with no loaded_models action to declare it on", func(t *testing.T) { + manifest := packPathLaunch(t) + delete(manifest.Actions, "loaded_models") + + err := manifest.Validate() + + require.Error(t, err, "the rows have to be declared somewhere the manifest can be checked against") + assert.Contains(t, err.Error(), "result.residency") + }) + + t.Run("a launch that asks for no lookup keeps the shape it always had", func(t *testing.T) { + manifest := residencyManifestWithRestart(t) + withoutTheJoin(manifest) + manifest.Actions["load_model"] = Action{LaunchModel: &ActionLaunchModel{Flags: []string{"--model"}}} + + require.NoError(t, manifest.Validate(), + "an engine that takes the name its caller sends, as vLLM does, needs no listing to read") + }) +} + func TestManifestValidate_RejectsAResidencyThatCouldNeverResolve(t *testing.T) { // Each case is a residency block that would leave PAIR looking for a pack // with the wrong recipe: no rows to look in, nothing to look the path up diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index e1a33d253..b4991c9b3 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -157,8 +157,9 @@ loading is provided by the PAIR proxy endpoint. request-triggered loading, subject to the custom alias restriction above. Their `list_models` disk inventory is also reported as `downloadedByEngine`, including while stopped or disabled; `loadedByEngine` names a resident model - the way that inventory names it — MTPLX by the `data[].id` that its - `--model-id` pins to the cache id, vLLM by the cached repository id, not a + the way that inventory names it — MTPLX by the residency join, which matches + the directory its `/health` reports against that same listing, vLLM by the + cached repository id, not a `--served-model-name` alias. `requestableByEngine` carries loader capability independently of ON/OFF intent for the broker's local route updates. A successful empty inventory retains an engine key with `[]`; a missing, diff --git a/services/nvpair-engine-manager/testdata/fakeengine/main.go b/services/nvpair-engine-manager/testdata/fakeengine/main.go index 8df58af38..c98306422 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -39,6 +39,9 @@ var ( modelsMu sync.Mutex models = map[string]bool{"llama3.2:1b": true} loaded = map[string]bool{"llama3.2:1b": true} + // launchModel is what --model named, which for an engine that takes a directory + // rather than a name is a directory, not a pack. Only /health reports it. + launchModel string ) func modelNames() []string { @@ -191,6 +194,7 @@ func main() { if ok { models = map[string]bool{served: true} loaded = map[string]bool{served: true} + launchModel = served } } // FAKE_SERVE_MODEL stands in for a server someone started on another model @@ -451,6 +455,14 @@ func main() { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) + // MTPLX answers /health with the directory it loaded its model from — for it the + // only spelling that says which cache the pack sits in — and PAIR joins that to the + // engine's own listing to work out which pack a running server holds. An engine + // launched by name has no directory to report, so it reports none. + mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "model_path": launchModel}) + }) // Ollama-shape model API (stateful). mux.HandleFunc("/api/tags", func(w http.ResponseWriter, r *http.Request) { ms := make([]map[string]string, 0) diff --git a/services/nvpair-tui/ui/engineswire.go b/services/nvpair-tui/ui/engineswire.go index 1749bdb8b..2b89f9a78 100644 --- a/services/nvpair-tui/ui/engineswire.go +++ b/services/nvpair-tui/ui/engineswire.go @@ -153,9 +153,10 @@ var modelWires = map[string]modelWire{ "pull": modelOnly("pull_model"), }, // MTPLX is vLLM-shaped: one model per process, so load restarts the server - // on the pack and eject stops it. Its CLI takes the cache id under "model" - // alone, which is also the id the server answers to (--model-id) and the id - // `mtplx models --json` reports. + // on the pack and eject stops it. A client names the pack by the cache id + // `mtplx models --json` reports; the engine-manager turns that into the + // directory the listing keeps the pack in before it reaches the launch, + // because that is what `mtplx serve` is given. engines.NameMTPLX: { "load": modelOnly("load_model"), "unload": modelOnly("unload_model"), From 503463b7cb3fb168596ad3f7b714de45df845ebd Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 08/10] fix(engine-manager): stop deleting a pack by quitting the whole engine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deleting a MTPLX pack takes the server down with it: MTPLX has no in-use guard, so a pack removed while a server holds it mapped leaves that server reading a file that is gone, and the delete therefore stops the engine and waits for its port to go quiet first (`stop_before`). What it did not do was ask whether there was anything to stop. It asked the running engine what it had mapped and read the answer as two things — "this pack" or "everything else" — and everything else took the engine down. That covers an idle MTPLX, which always answers `model_path` and answers it empty when it loaded no model; a server the user started themselves that never had a pack; and an engine serving a directory no cached pack sits in. Those cases removed the file with nothing stopped, only after quitting a working server to do it. The same two-valued read also answered a non-answer — no reply, a body larger than PAIR reads, a reply carrying no `model_path` at all — exactly as it answered a clear one, so a rename upstream silently turns every delete into a guess about whether a server has a pack open. Residency at the delete gate is three states now: this pack is what the engine has mapped, the engine says it is not, or PAIR cannot tell. Only the first two are facts about a running server, and only a server that cannot be asked is taken down on suspicion. A server that answers for something else stays up with its port answering, since the removal cannot be removing what that process holds: an engine PAIR did not start is one it adopts rather than quits, and that is the same rule the eject and the status path already apply to a third-party listener. "Cannot tell" still stops, which is the caution the eject takes from the other side — but it is now a state rather than the leftover of a comparison, because the empty answer and the missing answer are one value unless something keeps them apart, and only one of them can delete a pack a server is serving. The three states live at the delete gate only. residentJoin still reports a name or nothing, so the loaded badge, the eject guard and the launch argument read exactly what they read before; `Executor.readLoadedPath` is the read with its two empty cases kept in three, and `loadedPackPath` answers through it unchanged. Joining stays exact string equality, so a directory that only looks familiar once something folds its case or tidies its separators is "cannot tell", not "not this pack", and stops the engine. Tests are fixture-driven and run on any host: the delete seam drives the prebuilt fake engine on reserved loopback ports, and nothing reads a real pack cache, shells out to mtplx, or touches a live port. The fake already answered /health with what it was launched on, empty when it was launched with nothing, so the idle case needed no new fixture. The engine-running-but-idle test fails while a clear "nothing mapped" still reads as unknown, and the stops-for-every answer that cannot name another pack fails while either arm of "cannot tell" is read as permission to skip the stop — so a regression that flattens the states back to two is caught from both directions. Signed-off-by: Steven Beverly --- services/nvpair-engine-manager/actions.go | 101 ++- .../delete-mapped_test.go | 633 ++++++++++++++++++ .../delete-mapped_unix_test.go | 110 +++ .../manifests/mtplx.json | 5 +- services/nvpair-engine-manager/registry.go | 61 +- services/nvpair-engine-manager/residency.go | 205 +++++- .../testdata/fakeengine/main.go | 140 ++++ .../testdata/fakeengine/owngroup_unix.go | 22 + .../testdata/fakeengine/owngroup_windows.go | 18 + 9 files changed, 1265 insertions(+), 30 deletions(-) create mode 100644 services/nvpair-engine-manager/delete-mapped_test.go create mode 100644 services/nvpair-engine-manager/delete-mapped_unix_test.go create mode 100644 services/nvpair-engine-manager/testdata/fakeengine/owngroup_unix.go create mode 100644 services/nvpair-engine-manager/testdata/fakeengine/owngroup_windows.go diff --git a/services/nvpair-engine-manager/actions.go b/services/nvpair-engine-manager/actions.go index 57f33900a..7bc536e44 100644 --- a/services/nvpair-engine-manager/actions.go +++ b/services/nvpair-engine-manager/actions.go @@ -23,7 +23,9 @@ import ( ) // Action runs a manifest-declared action against the engine and, when the -// action declares restart_after, restarts the engine on success. +// action declares restart_after, restarts the engine on success. When the action +// declares stop_before, the engine is stopped and its port waited out first, unless it +// answers that it is not serving what the action removes: see stopBeforeAction. func (e *Executor) Action(ctx context.Context, engine, action string, params json.RawMessage) (json.RawMessage, error) { st, err := e.state(engine) if err != nil { @@ -41,6 +43,18 @@ func (e *Executor) Action(ctx context.Context, engine, action string, params jso if act.StopEngine { return e.ejectByStopping(ctx, engine, params) } + if act.StopBefore { + // One operation lock for the whole sequence, taken here rather than inside the + // steps so they cannot be interleaved with a Stop or a Start: the answer to + // "is this pack the one being served?" is only worth what it cost if nothing + // can start or stop the engine between reading it and removing the pack. The + // defer runs when Action returns, so it still covers the dispatch below. + st.lockOperation() + defer st.unlockOperation() + if err := e.stopBeforeAction(ctx, st, engine, action, act, params); err != nil { + return nil, err + } + } res, err := e.dispatchAction(ctx, st, engine, action, act, params) if err != nil { return nil, err @@ -55,6 +69,91 @@ func (e *Executor) Action(ctx context.Context, engine, action string, params jso return res, nil } +// stopBeforeAction does what a stop_before action promises before it removes +// anything: it asks what the running engine has mapped, and only when that answer is +// this pack — or when there is no answer to read — stops the engine and waits for its +// port to stop answering. It is the +// other half of the residency join Task 5 built for loaded_models, read here at the +// moment it is true rather than from an earlier sweep — the one question this sequence +// cannot afford to answer from memory is whether this engine is holding the pack. +// +// MTPLX is what it is for. Its server keeps a pack mapped for the life of the +// process, so `mtplx remove` deletes what a running server is serving, and the eject +// that releases the GPU memory is a stop. The action's own removal, whatever it +// declares, then runs — normally the engine's `remove` command; a guarded path is +// refused while the engine runs, so a manifest that removes by path must go through +// its CLI for a pack the engine could be holding. +// +// Residency is read here in three states, because two of them arrive as the same value +// unless something keeps them apart and they lead to different actions: "this server has +// nothing mapped" and "we could not get an answer". A server that answers for something +// else — nothing loaded, or a directory its own listing keys to a different pack — is left +// running with its port answering, because the removal cannot be removing what is running +// and PAIR was asked to delete a file, not to take anyone's model down. That covers the +// engine the user started themselves as well as an idle one PAIR brought up: an engine PAIR +// did not start is one it adopts rather than quits. A server that cannot be asked is treated +// as if this pack were mapped, which is the same caution the eject takes from the other side +// — the eject refuses to claim a pack is not resident when it cannot read, and here the safe +// reading of the same unknown is that the pack is in use and the engine has to come down +// first. The opposite direction would let a status blip delete a pack a server has mapped. +// +// Not running is an answer, not a failed read: the join reports nothing when the engine is +// down, so a stopped engine is checked first and its pack cannot be mapped. +// +// The stop is doStop, so the same engine that Stop reports as running under external +// management refuses here, in the same words, and the pack stays. +func (e *Executor) stopBeforeAction(ctx context.Context, st *engineState, engine, action string, act Action, params json.RawMessage) error { + var pack struct { + Model string `json:"model"` + } + if err := json.Unmarshal(params, &pack); err != nil { + return fmt.Errorf("action %q: params must be a JSON object with a model string: %w", action, err) + } + repoID := strings.TrimSpace(pack.Model) + + st.mu.Lock() + running, port := st.running, st.port + st.mu.Unlock() + if !running { + return nil + } + + // Three answers, two actions. See residencyState for why the middle one is not + // folded into either side. + state := e.residencyForDelete(ctx, engine, repoID) + switch state { + case residencyNotMapped: + // The engine answered clearly for something else, so the removal below cannot + // be removing what its process holds, and the port keeps answering through it. + slog.Debug("engine:residency the running server says this pack is not what it has mapped", + "engine", engine, "action", action, "port", port) + return nil + case residencyMappedHere, residencyUnknown: + // Either this pack is the one being served, or there was no answer to read, + // which is taken the same way: the pack stays unreachable rather than going + // missing under a server that still has it mapped. + } + + slog.Info("stopping engine before removing what it may have mapped", + "engine", engine, "action", action, "port", port, "residency", state) + if err := e.doStop(st, engine); err != nil { + return err + } + if !e.confirmPortsQuiet(ctx, st.plat.Runtime.Ready, singlePortSweep(port), stopBeforeQuietBound) { + return fmt.Errorf("action %q: engine %q was stopped but something still answers on port %d, so nothing was removed", action, engine, port) + } + return nil +} + +// stopBeforeQuietBound is how long a stop_before sequence waits, after stopping the +// engine, for the engine's port to stop answering before it will remove anything. It +// bounds the wait a manifest takes responsibility for when it declares stop_before, so +// a listener that outlives the engine delays a removal instead of allowing it. +// +// It is the same shape as stopGrace: the sequence's whole cost is a stop the user asked +// for plus this allowance, and it is a var so a test can prove it waits at all. +var stopBeforeQuietBound = 15 * time.Second + // restartAfterAction restarts a running engine after one of its actions // succeeded (see Action.RestartAfter). A stopped engine has no serving state to // reconcile, so it stays stopped. The restart failing is reported as the diff --git a/services/nvpair-engine-manager/delete-mapped_test.go b/services/nvpair-engine-manager/delete-mapped_test.go new file mode 100644 index 000000000..5daebb353 --- /dev/null +++ b/services/nvpair-engine-manager/delete-mapped_test.go @@ -0,0 +1,633 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +// A manifest-declared stop_before, pinned against a fake engine that really binds a +// port and really takes the order to stop. Each expectation below is read from the +// transcript that engine writes — which call reached its control CLI, and whether its +// port answered at that moment — because what this feature promises is a promise +// about an instant: the removal must not be the thing that happens while something is +// still serving the pack. "The engine was told to stop first" is not that promise, and +// neither is "the removal ran afterwards"; only what the port was doing in between is. + +import ( + "encoding/json" + "io/fs" + "net" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + // The pack the delete under test names. The spellings are the engine's own — a + // cache id and a directory — and none of them is a path on the machine running + // the test: the directory is only ever echoed back by the fake's listing and its + // health answer, which is all the join needs to join on. + deleteSeamRepoID = "fixture/Quiet-Pack" + deleteSeamPack = "/fixture/packs/quiet-pack" + + deleteSeamOtherRepoID = "fixture/Served-Pack" + deleteSeamOtherPack = "/fixture/packs/served-pack" +) + +// listedPack is one entry of the pack listing the engine's own CLI answers: which pack +// the cache holds, and the directory it sits in. The running server names only the +// directory it loaded, so joining these two is what says which pack is in use. +type listedPack struct { + RepoID string `json:"repo_id"` + Path string `json:"path"` +} + +var ( + deleteQuietPack = listedPack{RepoID: deleteSeamRepoID, Path: deleteSeamPack} + deleteServedPack = listedPack{RepoID: deleteSeamOtherRepoID, Path: deleteSeamOtherPack} +) + +// deleteSeam is one MTPLX-shaped engine a pack may be deleted from, plus the +// transcript a test reads: what ran against the engine's control CLI, and whether the +// engine's port was answering when it did. +type deleteSeam struct { + ex *Executor + manifest *Manifest + port int + transcript string +} + +type deleteSeamOptions struct { + // serves is the directory the engine launches on, which is the directory its + // health answer reports as the one it loaded. Left empty, the engine starts with + // nothing mapped and answers the residency read with an empty string, which is + // what an idle MTPLX answers: the field is always there and says "" when no model + // was loaded. That is an answer about the running server, not a missing read, and + // the two must not be staged the same way. + serves string + // cacheRows is the listing the engine's CLI answers for the packs its cache + // holds. + cacheRows []listedPack + // readPath overrides where the manifest reads the mapped pack's directory from. + // Set it to a path the engine answers nothing for, to ask a question that cannot + // be answered. + readPath string + // termDrain is how long the engine keeps running after its listener has gone: a + // port released in the order a real server releases one. + termDrain string + // holderPIDFile asks the engine to hand its port to a helper that outlives it, + // for a port that answers after the process PAIR started is gone. + holderPIDFile string +} + +// newDeleteSeam reserves the port the engine will serve on and sets up the transcript +// it writes. The delete under test is declared through the manifest's JSON shape, so +// see stoppingFirst. +func newDeleteSeam(t *testing.T, deleteAction Action, opts deleteSeamOptions) *deleteSeam { + t.Helper() + + port := portRun(t, 1)[0] + record := filepath.Join(t.TempDir(), "engine-transcript") + t.Setenv("FAKE_RECORD_FILE", record) + t.Setenv("FAKE_RECORD_PORT", strconv.Itoa(port)) + rows, err := json.Marshal(map[string][]listedPack{"models": opts.cacheRows}) + require.NoError(t, err, "the cache listing the engine answers with") + t.Setenv("FAKE_PACK_ROWS", string(rows)) + if opts.termDrain != "" { + t.Setenv("FAKE_TERM_DRAIN", opts.termDrain) + } + if opts.holderPIDFile != "" { + t.Setenv("FAKE_TERM_HOLDER_PID", opts.holderPIDFile) + } + + manifest := mtplxSeamManifest(t, deleteAction, opts, port) + + ex := newTestExecutor(t, manifest) + t.Cleanup(func() { _ = ex.Stop("mtplx") }) + return &deleteSeam{ex: ex, manifest: manifest, port: port, transcript: record} +} + +// mtplxSeamManifest is an MTPLX-shaped manifest whose lifecycle is the real fake +// engine: one pack per process, the packs it holds listed in one place and the +// directory its server has mapped in another, and the delete under test. +func mtplxSeamManifest(t *testing.T, deleteAction Action, opts deleteSeamOptions, port int) *Manifest { + t.Helper() + + manifest := testEngineManifest(fakeEngineBin) + manifest.Engine = "mtplx" + key := hostPlatformKey() + platform := manifest.Platforms[key] + platform.Runtime.Port = port + if opts.serves != "" { + platform.Runtime.Args = []string{"--model=" + opts.serves} + } + manifest.Platforms[key] = platform + + readPath := opts.readPath + if readPath == "" { + readPath = "/health" + } + manifest.Actions = map[string]Action{ + // MTPLX's two questions, in the two spellings it answers them: its CLI lists + // the packs the cache holds and names each directory, and the running server + // names a directory and no id. The join is what makes them one pack. + "list_models": { + Cmd: []string{"{cli}", "models", "--json"}, + Result: &ActionResult{Array: "models", Field: "repo_id"}, + }, + "loaded_models": { + HTTP: &ActionHTTP{Method: "GET", Path: "/v1/models"}, + Result: &ActionResult{Array: "data", Field: "id", Residency: &ActionResidency{ + Source: "list_models", + Read: &ActionHTTP{Method: "GET", Path: readPath}, + PathField: "model_path", + RowPathField: "path", + }}, + }, + "delete_model": deleteAction, + } + require.NoError(t, manifest.Validate(), "the shape every case below starts from") + return manifest +} + +func (s *deleteSeam) run(t *testing.T) { + t.Helper() + require.NoError(t, s.ex.Start(t.Context(), "mtplx"), "start the engine on its reserved port") +} + +func (s *deleteSeam) delete(t *testing.T, repoID string) (json.RawMessage, error) { + t.Helper() + return s.ex.Action(t.Context(), "mtplx", "delete_model", []byte(`{"model":"`+repoID+`"}`)) +} + +// lines reads the transcript in the order the engine wrote it. +func (s *deleteSeam) lines(t *testing.T) []string { + t.Helper() + + body, err := os.ReadFile(s.transcript) + if os.IsNotExist(err) { + return nil + } + require.NoError(t, err, "read the engine's transcript") + lines := []string{} + for _, line := range strings.Split(strings.TrimRight(string(body), "\n"), "\n") { + if line != "" { + lines = append(lines, line) + } + } + return lines +} + +// stoppingFirst declares "stop_before": true on an action the way a manifest does, in +// JSON rather than through a Go field. A fixture that could not compile until the +// field existed would fail for the wrong reason; declared this way, the tests below +// fail because nothing stopped the engine before it removed the pack. +func stoppingFirst(t *testing.T, action Action) Action { + t.Helper() + + body, err := json.Marshal(action) + require.NoError(t, err, "marshal the action as a manifest would write it") + var declared map[string]json.RawMessage + require.NoError(t, json.Unmarshal(body, &declared), "read back what the action declares") + declared["stop_before"] = json.RawMessage("true") + patched, err := json.Marshal(declared) + require.NoError(t, err, "write the manifest's declaration") + var stopping Action + require.NoError(t, json.Unmarshal(patched, &stopping), "a manifest that says stop_before has to be readable") + return stopping +} + +// cliDelete is MTPLX's own removal: its control CLI, the cache id as the argument, and +// the --yes that keeps it from waiting for a prompt nobody is going to answer. +func cliDelete() Action { + return Action{Cmd: []string{"{cli}", "remove", "{model}", "--yes", "--json"}} +} + +// shrinkQuietBound spends the shortest wait that still distinguishes waiting from +// not waiting, so these tests do not sit through the whole allowance while they check +// what happened inside it. +func shrinkQuietBound(t *testing.T, bound time.Duration) { + t.Helper() + + previous := stopBeforeQuietBound + stopBeforeQuietBound = bound + t.Cleanup(func() { stopBeforeQuietBound = previous }) +} + +func portIsAnswering(port int) bool { + conn, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(port), 500*time.Millisecond) + if err != nil { + return false + } + _ = conn.Close() + return true +} + +// TestStopBeforeAction_RemovesOnlyAfterTheStoppedEngineHasStoppedAnswering is the +// sequence MTPLX needs: the engine holding the pack is stopped, its port is waited out, +// and the removal is what runs afterwards. Without the wait the removal runs while the +// listener is still up, and the transcript's last line says so. +func TestStopBeforeAction_RemovesOnlyAfterTheStoppedEngineHasStoppedAnswering(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + // The engine stops answering immediately and exits a beat later, which is + // the order a real server releases a port. + termDrain: "300ms", + }) + shrinkQuietBound(t, 5*time.Second) + seam.run(t) + require.True(t, portIsAnswering(seam.port), "the engine under test has to be serving") + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model") + require.False(t, portIsAnswering(seam.port), "the engine was left serving the pack it just had removed") + assert.Equal(t, []string{ + "cmd models --json port=answered", + "stop port=answered", + "cmd remove " + deleteSeamRepoID + " --yes --json port=quiet", + }, seam.lines(t), "what was mapped is read while the engine can still answer, the engine is stopped, and the removal runs once nothing answers") +} + +// TestStopBeforeAction_RemovesWithNoStopWhenNothingIsRunning covers the half of the +// rule that keeps a delete of a stopped engine from becoming a stop: nothing is +// serving the pack, so there is no mapping to wait out and no listener to ask about. +func TestStopBeforeAction_RemovesWithNoStopWhenNothingIsRunning(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + }) + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model against a stopped engine") + lines := seam.lines(t) + require.Len(t, lines, 1, "a stopped engine gets no stop order and no residency read: %v", lines) + assert.Equal(t, "cmd remove "+deleteSeamRepoID+" --yes --json port=quiet", lines[0], "the removal is the only thing that ran") +} + +// TestStopBeforeAction_RemovesWithoutStoppingWhenAnotherPackIsMapped keeps stop_before +// from turning every delete into a restart: MTPLX serves one pack, so a pack other +// than the mapped one is not in use, and stopping the engine would be a outage the +// user did not ask for. +func TestStopBeforeAction_RemovesWithoutStoppingWhenAnotherPackIsMapped(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamOtherPack, + cacheRows: []listedPack{deleteQuietPack, deleteServedPack}, + termDrain: "300ms", + }) + seam.run(t) + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model") + assert.Equal(t, []string{ + "cmd models --json port=answered", + "cmd remove " + deleteSeamRepoID + " --yes --json port=answered", + }, seam.lines(t), "the pack is not the one being served, so nothing was stopped and the port answered throughout") + assert.True(t, portIsAnswering(seam.port), "an engine serving a different pack was taken down for a delete it had no part in") +} + +// TestStopBeforeAction_StopsTheEngineItCannotAskAboutAsIfThePackWereMapped pins the +// direction of the doubt, which is the opposite of the eject's: an eject refuses to +// claim a pack is not resident when the read failed, and a delete here treats the pack +// as mapped on the same failure. The two are the same caution about the same unknown — +// neither acts as if it knew — and only one of them can cost the user a running model +// or a pack a server has mapped. +func TestStopBeforeAction_StopsTheEngineItCannotAskAboutAsIfThePackWereMapped(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + termDrain: "300ms", + // The engine is up and answering, and the one question the join asks of it + // is not answered: no field, so no pack to compare against. + readPath: "/api/nothing-to-join-here", + }) + shrinkQuietBound(t, 5*time.Second) + seam.run(t) + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model") + lines := seam.lines(t) + assert.Contains(t, lines, "stop port=answered", "an engine whose mapped pack could not be read was deleted from without being stopped: %v", lines) + require.NotEmpty(t, lines) + last := lines[len(lines)-1] + assert.Equal(t, "cmd remove "+deleteSeamRepoID+" --yes --json port=quiet", last, + "the removal ran while something still answered on the engine's port: %v", lines) +} + +// TestStopBeforeAction_RemovesWithoutStoppingAnIdleEngineThatMapsNothing is the case +// the three states exist for: an engine is up, it answers the residency read clearly, +// and what it answers is that it has nothing mapped. That is not "we could not get an +// answer" — the server always sends the field and sends it empty when it loaded no +// model — so PAIR removes the file and leaves the engine up with its port still +// answering. Reading the empty answer as unknown instead would quit an idle engine, and +// a model-less server the user started themselves, to delete a pack neither one had +// open. +func TestStopBeforeAction_RemovesWithoutStoppingAnIdleEngineThatMapsNothing(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + // No --model, so the engine answers /health with {"ok":true,"model_path":""}. + cacheRows: []listedPack{deleteQuietPack}, + // The drain is here so a stop would leave a mark: it keeps the port answering + // for 300 ms after the order arrives. Without it the transcript could not tell + // "nothing was stopped" from "stopped and gone instantly". + termDrain: "300ms", + }) + seam.run(t) + require.True(t, portIsAnswering(seam.port), "the engine under test has to be up and answering") + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model") + assert.Equal(t, []string{ + // The removal is the only thing that ran, and it ran with the port answering: + // no stop order, and no wait for a quiet that was never coming. + "cmd remove " + deleteSeamRepoID + " --yes --json port=answered", + }, seam.lines(t), "an engine that had nothing mapped was taken down to delete a file it never touched") + assert.True(t, portIsAnswering(seam.port), "the engine was left down after a delete it had no part in") +} + +// TestStopBeforeAction_StopsForEveryAnswerThatCannotNameAnotherPack pins the third +// state beside the second: everything that is not a readable answer naming a provably +// different pack stops the engine first. These two tests are what prove the states are +// three — this one fails if the middle state swallows either arm of "cannot tell", and +// the idle test above fails if it swallows a clear "nothing mapped". +func TestStopBeforeAction_StopsForEveryAnswerThatCannotNameAnotherPack(t *testing.T) { + cases := []struct { + name string + serves string + cacheRows []listedPack + readPath string + }{ + { + name: "a JSON answer that names no loaded path", + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + // The fake answers any path it was not told about, /api/tags included, with a + // real listing: valid JSON carrying no model_path. That is what an engine + // with the field renamed or dropped answers, and it is the exact place where + // reading "no model loaded" instead of "no answer" destroys a pack a server + // has open — this engine really does have this pack's directory mapped. + readPath: "/api/tags", + }, + { + name: "a directory no cached pack sits in", + // The engine is serving served-pack's directory, spelled so that no row in + // the listing holds it. The listing does hold that directory spelled the way + // the listing writes it, so a join that folded case or cleaned the path would + // answer "a different pack is mapped" and remove this one with the engine + // still serving. PAIR joins on exact strings: it cannot pair what is served + // with either pack, and that is not evidence of an empty server. + serves: "/FIXTURE/PACKS/SERVED-PACK", + cacheRows: []listedPack{deleteQuietPack, deleteServedPack}, + }, + } + + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: test.serves, + cacheRows: test.cacheRows, + readPath: test.readPath, + termDrain: "300ms", + }) + shrinkQuietBound(t, 5*time.Second) + seam.run(t) + + _, err := seam.delete(t, deleteSeamRepoID) + + require.NoError(t, err, "delete_model") + lines := seam.lines(t) + assert.Contains(t, lines, "stop port=answered", + "the engine was deleted from without being stopped, although its answer named no provably different pack: %v", lines) + require.NotEmpty(t, lines) + assert.Equal(t, "cmd remove "+deleteSeamRepoID+" --yes --json port=quiet", lines[len(lines)-1], + "the removal ran while something still answered on the engine's port: %v", lines) + }) + } +} + +// TestStopBeforeAction_ReportsTheRefusalToStopAnEngineUnderExternalManagement keeps +// stop_before from inventing a second way to be refused: the engine that PAIR cannot +// take down says so in doStop's own words, and the pack stays. +func TestStopBeforeAction_ReportsTheRefusalToStopAnEngineUnderExternalManagement(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + }) + // Someone else's MTPLX is answering on the port, in a form PAIR adopted rather + // than started: running, with no process of its own to terminate. + listener, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(seam.port)) + require.NoError(t, err, "bind the port the adopted engine is answering on") + t.Cleanup(func() { _ = listener.Close() }) + go func() { + _ = http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + }() + st, err := seam.ex.state("mtplx") + require.NoError(t, err, "engine state") + st.mu.Lock() + st.running, st.adopted, st.proc, st.port = true, true, nil, seam.port + st.mu.Unlock() + + _, err = seam.delete(t, deleteSeamRepoID) + + require.Error(t, err, "the delete removed a pack out from under an engine it had not stopped") + assert.Contains(t, err.Error(), "running under external management", + "a delete that cannot stop the engine says so in the words Stop already uses") + assert.NotContains(t, strings.Join(seam.lines(t), "\n"), "remove", + "the removal ran after the stop was refused: %v", seam.lines(t)) +} + +// TestStopBeforeAction_HoldsOneEngineOperationAcrossTheReadStopAndRemoval pins the +// shape that makes the sequence mean anything: a Stop that arrives while a delete is +// working cannot interleave with it, because the residency read, the stop and the +// removal are one operation. Held from the test the way any operation holds it, the +// delete does not begin at all until the lock is free. +func TestStopBeforeAction_HoldsOneEngineOperationAcrossTheReadStopAndRemoval(t *testing.T) { + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + termDrain: "300ms", + }) + shrinkQuietBound(t, 5*time.Second) + seam.run(t) + st, err := seam.ex.state("mtplx") + require.NoError(t, err, "engine state") + + st.opMu.Lock() // another lifecycle operation is in flight on this engine + unlock := sync.OnceFunc(st.opMu.Unlock) + t.Cleanup(unlock) + finished := make(chan error, 1) + go func() { + _, err := seam.delete(t, deleteSeamRepoID) + finished <- err + }() + + select { + case err := <-finished: + unlock() + require.NoError(t, err, "read the failure") + require.FailNow(t, "delete_model ran while another operation held the engine") + case <-time.After(750 * time.Millisecond): + } + assert.Empty(t, seam.lines(t), "the delete read what was mapped and removed the pack outside the operation it was supposed to hold") + + unlock() + require.NoError(t, <-finished, "delete_model once the engine was free") + assert.Equal(t, []string{ + "cmd models --json port=answered", + "stop port=answered", + "cmd remove " + deleteSeamRepoID + " --yes --json port=quiet", + }, seam.lines(t), "all three ran in the one hold, in that order") +} + +// TestActionValidate_StopBeforeRequiresResidencyAndRefusesRestartAfter covers the two +// declarations that cannot be obeyed. Without a residency read there is no answer to +// "is this the pack being served", so a manifest asking to stop first is asking to +// stop whatever happens to be up. And restart_after cannot follow a stop the action +// itself carries out under the engine's operation lock: the restart would take the +// same lock again, and an engine lock is not reentrant. +func TestActionValidate_StopBeforeRequiresResidencyAndRefusesRestartAfter(t *testing.T) { + manifestWith := func(t *testing.T, deleteAction Action) *Manifest { + t.Helper() + return mtplxSeamManifest(t, deleteAction, deleteSeamOptions{}, 0) + } + + t.Run("with nothing declared to ask what is mapped", func(t *testing.T) { + manifest := manifestWith(t, stoppingFirst(t, cliDelete())) + loaded := manifest.Actions["loaded_models"] + loaded.Result.Residency = nil + manifest.Actions["loaded_models"] = loaded + + err := manifest.Validate() + + require.Error(t, err, "a stop_before with no residency read cannot know which pack is in use") + assert.Contains(t, err.Error(), "stop_before") + assert.Contains(t, err.Error(), "residency") + }) + + t.Run("with a restart declared after it", func(t *testing.T) { + manifest := manifestWith(t, stoppingFirst(t, cliDelete())) + deleting := manifest.Actions["delete_model"] + deleting.RestartAfter = true + manifest.Actions["delete_model"] = deleting + + err := manifest.Validate() + + require.Error(t, err, "an action that stops the engine itself cannot also ask for a restart") + assert.Contains(t, err.Error(), "stop_before") + assert.Contains(t, err.Error(), "restart_after") + }) + + t.Run("with the stop itself declared as the action", func(t *testing.T) { + manifest := manifestWith(t, stoppingFirst(t, cliDelete())) + delete(manifest.Actions, "delete_model") + manifest.Actions["unload_model"] = Action{StopEngine: true, StopBefore: true} + + err := manifest.Validate() + + require.Error(t, err, "an eject is the stop, so a stop_before in front of it would never run") + assert.Contains(t, err.Error(), "stop_before") + assert.Contains(t, err.Error(), "stop_engine") + }) + + t.Run("with the residency read declared and no restart", func(t *testing.T) { + manifest := manifestWith(t, stoppingFirst(t, cliDelete())) + + assert.NoError(t, manifest.Validate(), "the declaration MTPLX's manifest makes") + }) +} + +// TestManifestValidate_RefusesAResidencySourceThatDeletesOrStops closes the gap the +// join's own fence left open: the source was already barred from stopping, restarting +// or relaunching the engine it is asked about, and a source that deletes is just as +// unkind to the pack it is only meant to look up. A stop_before source is worse again, +// because reading the rows would take the engine down before the read finished, and the +// operation lock it holds is not reentrant. +func TestManifestValidate_RefusesAResidencySourceThatDeletesOrStops(t *testing.T) { + // Every source below declares rows to read, so the rule that refuses it is the + // fence and not the earlier "the source declares no result" check. + rows := &ActionResult{Array: "models", Field: "repo_id"} + cases := []struct { + name string + source Action + mustSay []string + reason string + }{ + { + name: "a source that removes a pack's directory", + source: Action{RemovePath: &ActionRemovePath{Root: "/fixture/cache", Path: "/fixture/cache/{model}"}, Result: rows}, + mustSay: []string{"result.residency.source", "remove_path"}, + reason: "a residency lookup that deletes the pack it looked up", + }, + { + name: "a source that stops the engine before reading", + source: Action{Cmd: []string{"{cli}", "models", "--json"}, StopBefore: true, Result: rows}, + mustSay: []string{"result.residency.source", "stop_before"}, + reason: "a residency lookup that takes the engine down on its way to a question, on a lock that is not reentrant", + }, + { + // The hub-cache route is already refused, by the older rule that reserves + // hf_cache.delete for delete_model. It is here because the fence is meant to + // be the reason a residency source never deletes, and a reader who checks + // that rule should see all three kinds. + name: "a source that deletes through the hub cache", + source: Action{HFCache: &ActionHFCache{Dir: "/fixture/cache", Delete: true, Tool: "hf"}, Result: rows}, + mustSay: []string{"hf_cache.delete"}, + reason: "a residency lookup that deletes the pack it looked up", + }, + } + + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + manifest := mtplxSeamManifest(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{}, 0) + manifest.Actions["list_models"] = test.source + + err := manifest.Validate() + + require.Error(t, err, "%s is not a lookup", test.reason) + for _, phrase := range test.mustSay { + assert.Contains(t, err.Error(), phrase, "the refusal is not about the declaration it is refusing") + } + }) + } + + t.Run("a source that only reads is still accepted", func(t *testing.T) { + manifest := mtplxSeamManifest(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{}, 0) + manifest.Actions["list_models"] = Action{HFCache: &ActionHFCache{Dir: "/fixture/cache"}, Result: rows} + + assert.NoError(t, manifest.Validate(), "a cache listing is what a residency source is for") + }) +} + +// TestBundledMTPLXManifest_DeclaresDeleteModelStoppingFirst is the change that reaches +// the user: the shipped manifest says the pack in use is stopped before it is removed, +// keeps the argument that made the removal run by itself, and no longer tells the user +// to eject first as if that were their job. +func TestBundledMTPLXManifest_DeclaresDeleteModelStoppingFirst(t *testing.T) { + raw, err := fs.ReadFile(bundledManifests, "manifests/mtplx.json") + require.NoError(t, err, "read the shipped manifest") + var manifest Manifest + require.NoError(t, json.Unmarshal(raw, &manifest), "the shipped manifest has to parse into the same shape a test builds") + require.NoError(t, manifest.Validate()) + + deleting := manifest.Actions["delete_model"] + assert.True(t, deleting.StopBefore, "MTPLX serves one pack per process, so deleting it can be deleting what is running") + assert.False(t, deleting.RestartAfter, "a stopped MTPLX has nothing to serve the deleted pack, and a restart would relaunch it") + assert.Contains(t, deleting.Cmd, "--yes", "the removal still runs without waiting for a prompt") + assert.Contains(t, deleting.Cmd, "{model}", "the argument is still the cache id, and not the directory it resolves to") + assert.Contains(t, manifest.Actions["loaded_models"].Result.Residency.Source, "list_models", + "stop_before asks that join which pack is mapped") + assert.Contains(t, deleting.Description, "stop", "the description still tells the user to eject it first, which is now what the action does") + assert.NotContains(t, deleting.Description, "Eject it first", "the advice a user follows has to match what the action now does") +} diff --git a/services/nvpair-engine-manager/delete-mapped_unix_test.go b/services/nvpair-engine-manager/delete-mapped_unix_test.go new file mode 100644 index 000000000..edd5a61ea --- /dev/null +++ b/services/nvpair-engine-manager/delete-mapped_unix_test.go @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows + +package main + +// The half of stop_before that has to refuse: a port still answering after the process +// PAIR started is gone. It is Unix-only because of how a stop works here rather than +// what is being tested — a stop asks the engine's process group to leave and then +// force-kills the group, so the only thing that can still be holding the port is a +// process in no such group, and on Windows the stop is a taskkill /T /F, which ends the +// tree however a child was created. Nothing portable can stand in for a listener PAIR +// has no handle on and no right to kill, so the fake's holder goes in its own group. + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// packOnDisk is a pack a filesystem removal can be pointed at: a directory in the +// test's own tree, named by the same cache id the delete passes. +func packOnDisk(t *testing.T) (root, repoID, dir string) { + t.Helper() + + root = t.TempDir() + repoID = "quiet-pack" + dir = filepath.Join(root, repoID) + require.NoError(t, os.MkdirAll(dir, 0o755), "create the pack to delete") + require.NoError(t, os.WriteFile(filepath.Join(dir, "weights.bin"), []byte("weights"), 0o644), "fill it") + return root, repoID, dir +} + +// stopLeakedHolder ends the helper that holds the port, whatever a test below does +// with it. It waits for the helper to have taken the port before it kills anything, +// because that is the moment the pid file appears. +func stopLeakedHolder(t *testing.T, pidFile string) { + t.Helper() + + t.Cleanup(func() { + for range 50 { + body, err := os.ReadFile(pidFile) + if err == nil { + if pid, err := strconv.Atoi(strings.TrimSpace(string(body))); err == nil { + if proc, err := os.FindProcess(pid); err == nil { + _ = proc.Kill() + } + } + return + } + time.Sleep(20 * time.Millisecond) + } + }) +} + +// TestStopBeforeAction_LeavesTheRemovalForAListenerThatOutlivesTheEngine is the case +// the wait exists for: the process is gone, and the port still answers. Both removal +// kinds a manifest can declare are refused, because neither is safe against a pack a +// server still has mapped, and an error that says nothing happened is the only honest +// report. +func TestStopBeforeAction_LeavesTheRemovalForAListenerThatOutlivesTheEngine(t *testing.T) { + t.Run("the engine's own removal command", func(t *testing.T) { + holderPIDFile := filepath.Join(t.TempDir(), "holder.pid") + stopLeakedHolder(t, holderPIDFile) // the holder is in its own group: nothing else will end it + seam := newDeleteSeam(t, stoppingFirst(t, cliDelete()), deleteSeamOptions{ + serves: deleteSeamPack, + cacheRows: []listedPack{deleteQuietPack}, + holderPIDFile: holderPIDFile, + }) + shrinkQuietBound(t, 500*time.Millisecond) + seam.run(t) + + _, err := seam.delete(t, deleteSeamRepoID) + + require.Error(t, err, "the pack was removed while the engine's port answered") + assert.Contains(t, err.Error(), "delete_model") + require.True(t, portIsAnswering(seam.port), "the test's own fixture failed: nothing was holding the port to refuse the removal over") + assert.NotContains(t, strings.Join(seam.lines(t), "\n"), "remove", + "the removal ran against a port that never went quiet: %v", seam.lines(t)) + }) + + t.Run("a guarded filesystem path", func(t *testing.T) { + root, repoID, dir := packOnDisk(t) + holderPIDFile := filepath.Join(t.TempDir(), "holder.pid") + stopLeakedHolder(t, holderPIDFile) // the holder is in its own group: nothing else will end it + seam := newDeleteSeam(t, stoppingFirst(t, Action{ + RemovePath: &ActionRemovePath{Root: root, Path: filepath.Join(root, "{model}")}, + }), deleteSeamOptions{ + serves: dir, + cacheRows: []listedPack{{RepoID: repoID, Path: dir}}, + holderPIDFile: holderPIDFile, + }) + shrinkQuietBound(t, 500*time.Millisecond) + seam.run(t) + + _, err := seam.delete(t, repoID) + + require.Error(t, err, "the pack's files were removed while the engine's port answered") + require.True(t, portIsAnswering(seam.port), "the test's own fixture failed: nothing was holding the port") + _, statErr := os.Stat(dir) + assert.NoError(t, statErr, "a running server had that pack mapped and its files are gone") + }) +} diff --git a/services/nvpair-engine-manager/manifests/mtplx.json b/services/nvpair-engine-manager/manifests/mtplx.json index 2afdd342d..ea07dbf3b 100644 --- a/services/nvpair-engine-manager/manifests/mtplx.json +++ b/services/nvpair-engine-manager/manifests/mtplx.json @@ -79,8 +79,9 @@ "cmd": ["{cli}", "pull", "{model}", "--json"] }, "delete_model": { - "description": "Delete a model pack from the local MTPLX cache (params: {\"model\": \"\"}). Eject it first: MTPLX has no in-use guard, so this deletes a pack the running server still has mapped, and it does not take the deleted pack out of the launch arguments of a stopped engine. Download it again to recover either way.", - "cmd": ["{cli}", "remove", "{model}", "--yes", "--json"] + "description": "Delete a model pack from the local MTPLX cache (params: {\"model\": \"\"}). MTPLX has no in-use guard, so when the running server has this pack mapped the action stops MTPLX and waits for its port to stop answering before deleting anything; a pack the server is not serving is removed without stopping it. The engine is left stopped rather than restarted, and a pack that was in the launch arguments of a stopped engine stays there, so choose another model before starting again. Download the pack again to recover.", + "cmd": ["{cli}", "remove", "{model}", "--yes", "--json"], + "stop_before": true } } } \ No newline at end of file diff --git a/services/nvpair-engine-manager/registry.go b/services/nvpair-engine-manager/registry.go index cd4240925..5b5e17ea3 100644 --- a/services/nvpair-engine-manager/registry.go +++ b/services/nvpair-engine-manager/registry.go @@ -479,6 +479,13 @@ type Action struct { // only a restart makes the deletion visible to clients. A stopped engine is // left stopped; a restart failure fails the action. RestartAfter bool `json:"restart_after,omitempty"` + // StopBefore, for a manifest whose engine keeps the pack it serves inside a + // running process, makes the action stop that engine first and wait for its + // port to stop answering, unless the engine answers clearly that it is not + // serving what the action removes. It means "this action removes something the + // running engine may have mapped": what is removed is still whatever else the + // action declares. See Executor.stopBeforeAction. + StopBefore bool `json:"stop_before,omitempty"` } // ActionResult is the list-extraction spec on an Action (see Action.Result). @@ -1088,10 +1095,15 @@ func (m *Manifest) Validate() error { // something that only looks. stop_engine, restart_after and launch_model // each take the engine down or re-tune it, and any of them on the source // would make answering a question about a pack stop, restart or re-launch - // the engine that holds it. Nothing bundled does that today; the rule is - // here so a manifest cannot add the path later. - if source.StopEngine || source.RestartAfter || source.LaunchModel != nil { - return fmt.Errorf("action %q: result.residency.source %q stops, restarts or relaunches the engine, and a residency lookup must only read", name, a.Result.Residency.Source) + // the engine that holds it. remove_path and stop_before are the same + // mistake in the other direction: one deletes the pack the lookup was + // only meant to find, and the other takes the engine down as its first + // step, on the operation lock the lookup is already holding and cannot + // take again. hf_cache.delete is refused by the older rule that reserves + // it for delete_model. Nothing bundled does any of these today; the rule + // is here so a manifest cannot add the path later. + if declared := residencySourceChange(source); declared != "" { + return fmt.Errorf("action %q: result.residency.source %q declares %s, and a residency lookup must only read", name, a.Result.Residency.Source, declared) } } } @@ -1118,9 +1130,44 @@ func (m *Manifest) Validate() error { if act, ok := m.Actions["loaded_models"]; ok && act.Result != nil && act.Result.InventoryField != "" && m.AdvertisedModels != advertisedModelsLoaded && m.AdvertisedModels != advertisedModelsAvailable { return fmt.Errorf("action %q: result.inventory_field requires advertised_models %q", "loaded_models", advertisedModelsLoaded) } + // stop_before is "this action removes what the running engine may have mapped", + // and the only way to know that is the residency join. A manifest that declares + // no join has no answer to ask for, so the stop would take down whatever engine + // happens to be up. result.residency is itself only valid on loaded_models. + for name, a := range m.Actions { + if !a.StopBefore { + continue + } + loaded := m.Actions["loaded_models"] + if loaded.Result == nil || loaded.Result.Residency == nil { + return fmt.Errorf("action %q: stop_before requires loaded_models to declare result.residency, so the pack the engine has mapped is known before it is stopped", name) + } + } return m.validatePlaceholders() } +// residencySourceChange names the first declaration on an action used as a +// result.residency.source that would change the engine or its packs, or "" when the +// action only looks. It is the residency fence in Manifest.Validate: see the comment +// there for what each declaration would do. +func residencySourceChange(source Action) string { + for _, declaration := range []struct { + set bool + name string + }{ + {source.StopEngine, "stop_engine"}, + {source.RestartAfter, "restart_after"}, + {source.StopBefore, "stop_before"}, + {source.LaunchModel != nil, "launch_model"}, + {source.RemovePath != nil, "remove_path"}, + } { + if declaration.set { + return declaration.name + } + } + return "" +} + // advertisedModels values for Manifest.AdvertisedModels. const ( advertisedModelsList = "list" @@ -1415,6 +1462,12 @@ func (a *Action) validate(name string) error { if a.StopEngine && name != "unload_model" { return fmt.Errorf("action %q: stop_engine belongs to unload_model", name) } + if a.StopBefore && a.RestartAfter { + return fmt.Errorf("action %q: stop_before and restart_after cannot both be declared: the action stops the engine itself, on the operation lock the restart would have to take again", name) + } + if a.StopBefore && a.StopEngine { + return fmt.Errorf("action %q: stop_before and stop_engine cannot both be declared: that action is the stop, so there would be no removal for a stop before it to protect", name) + } if hasHFPull { tool := a.HFPull.Tool if name != pullModelAction || tool == "" || tool != filepath.Base(tool) || strings.TrimSpace(a.HFPull.Dir) == "" { diff --git a/services/nvpair-engine-manager/residency.go b/services/nvpair-engine-manager/residency.go index 39769e527..c73074e09 100644 --- a/services/nvpair-engine-manager/residency.go +++ b/services/nvpair-engine-manager/residency.go @@ -333,33 +333,172 @@ func (e *Executor) residentJoin(ctx context.Context, engine string, inventory in return residencyAnswer{row: row, named: true, complete: true} } -// loadedPackPath asks a running engine which directory it loaded its model from, at -// the answer its manifest named (ActionResidency.Read) and in the field it named -// there (PathField). +// residencyState is one reading of what a running engine has mapped, in the three states +// a delete has to act on. // -// The read is the one every probe answer is read under — 3 s bound, the -// maxProbeJSONBytes cap, drain-and-close on every path — because this is a health -// check being asked one more question, and two bounds on the same request are two -// chances to disagree about whether an engine is answering. The cap is why a body -// bigger than PAIR reads answers unknown rather than half-parsed: readProbeBody -// returns no body at all for an answer it could not read whole, so there is nothing -// here to mistake for a partial answer. +// It is three states, not the two residentJoin reports, because the middle one is a fact +// rather than a gap. residentJoin's empty answer means both "the engine named a directory +// no cached pack sits in" and "PAIR never got an answer", which is enough for a caller +// showing a badge or refusing an eject: both of those do the cautious thing either way. A +// caller about to delete a file is not choosing between two safe options — one of these +// states means the engine gets quit to delete a file nobody had open, and the other means +// it does not — so the two have to stay apart here even though they stay together in the +// join. That is why this is its own reading rather than a third field on residencyAnswer: +// the eject reads residencyAnswer's `complete` to decide whether it may claim a pack is +// not resident, and a flag that means both "not resident" and "unknown" on the same struct +// is the exact shape that made the delete wrong. +type residencyState int + +const ( + // residencyMappedHere is the engine naming this pack's directory, so the delete + // would be removing what a live server has open. + residencyMappedHere residencyState = iota + // residencyNotMapped is the engine answering clearly for something else: either it + // has nothing mapped at all, or it named a directory that this machine's own + // listing keys to a different pack. Removing this pack cannot be removing what is + // running, so nothing is stopped for it. + residencyNotMapped + // residencyUnknown is no answer to act on, which is taken the same way as a mapped + // pack: the read failed, or arrived bigger than PAIR reads, or named no loaded + // path, or named a directory no row in the listing holds. The last two are the same + // unknown the eject reads from the other side, and a pack deleted from under a + // server still serving it cannot be put back. + residencyUnknown +) + +// String names the reading for the log, so the record says why an engine was stopped for +// a delete rather than only that it was. +func (s residencyState) String() string { + switch s { + case residencyMappedHere: + return "this pack is what it has mapped" + case residencyNotMapped: + return "it answered this pack is not mapped" + default: + return "cannot tell what it has mapped" + } +} + +// residencyForDelete answers, for the pack a delete names, whether the running engine has +// that pack mapped, for a caller that will act differently on each of the three answers. // -// No status code is consulted, deliberately: the field is the evidence, and an answer -// that names a loaded path is an engine talking about its model whatever it arrived -// with. An error answer that names none is unknown like every other non-answer. -func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, residency *ActionResidency) (string, bool) { +// It reads the same two answers residentJoin joins — where the running server loaded its +// model from, and which directories the engine's own listing names — but it stops reading +// as soon as the answer is decided, because what it costs is a subprocess. An engine that +// says it has nothing mapped is answered from the first read: no cache listing can turn "I +// loaded nothing" back into a pack being served, so running `mtplx models --json` to +// confirm it would buy nothing and delay the delete by however long that takes to time +// out. +// +// The join stays exact string equality, with no case folding, separator rewriting or +// symlink resolution, for the reason packRowForKey gives: on the machines measured, the +// spellings that differ really are different packs. A path that only looks like a known +// directory once something normalises it therefore answers residencyUnknown, and the +// delete stops the engine. Guessing here deletes a pack a server has mapped, which is the +// one thing this sequence exists to avoid. +func (e *Executor) residencyForDelete(ctx context.Context, engine, repoID string) residencyState { + st, err := e.state(engine) + if err != nil { + return residencyUnknown + } + residency := residencyDeclaration(st) + if residency == nil || residency.Read == nil { + // Nothing is declared to ask this engine by, so nothing is ruled out. A + // manifest that declares stop_before has to declare the read (Manifest.Validate + // refuses it without), which leaves this the unconfigured engine rather than a + // shortcut past the question. + return residencyUnknown + } + st.mu.Lock() + running, port := st.running, st.port + st.mu.Unlock() + if !running { + // A stopped engine cannot have anything mapped, and the delete gate answers + // that for itself before asking — see stopBeforeAction. Asked anyway, it gets + // the cautious state: there is nothing here to tell an engine that is down from + // one that is up and silent. + return residencyUnknown + } + + path, state := e.readLoadedPath(ctx, engine, port, residency) + if state == loadedPathNothing { + // The server answered clearly that it has nothing mapped. MTPLX always sends + // `model_path` and sends it empty when it loaded no model, so this is a + // readable answer about a running process and not a failed read; folding it + // into residencyUnknown is what quit an idle engine to delete a file. + return residencyNotMapped + } + if state != loadedPathNamed { + return residencyUnknown + } + rows, ok := e.packInventoryFrom(ctx, engine, inventoryAnswer{}) + if !ok { + return residencyUnknown + } + row, found := packRowForKey(rows, path) + if !found { + // Something is mapped that no row holds: a pack handed over as a pair bundle, + // a cache that moved, a pack already deleted from under a server still serving + // it — and possibly this pack under a spelling PAIR does not match. None of + // those is evidence that the pack being deleted is free. + return residencyUnknown + } + if row.repoID == repoID { + return residencyMappedHere + } + return residencyNotMapped +} + +// loadedPathState is what one read of "which directory does this engine have mapped" +// amounts to, before anyone joins it to a cache listing. +type loadedPathState int + +const ( + // loadedPathUnreadable is no answer: nothing arrived, more arrived than PAIR + // reads, it was not a JSON object, the field the manifest named was absent, or it + // held something other than a string. + loadedPathUnreadable loadedPathState = iota + // loadedPathNothing is the field arriving with an empty string in it, which is an + // engine saying it loaded no model. + loadedPathNothing + // loadedPathNamed is the field arriving with a directory in it, whether or not any + // cached pack sits there. + loadedPathNamed +) + +// readLoadedPath asks a running engine where it loaded its model from, at the answer its +// manifest named (ActionResidency.Read) and in the field it named there (PathField), and +// says which of the three kinds of answer came back. +// +// It is the read loadedPackPath reports as one value, kept in three: what the field says +// and whether there was a field to read are different facts, and the delete gate is the +// caller that cannot afford to mix them up. The shape of the read is unchanged from it — +// the same 3 s bound, the same maxProbeJSONBytes cap, drain-and-close on every path — +// because this is a health check being asked one more question, and two bounds on the same +// request are two chances to disagree about whether an engine is answering. The cap is why +// a body bigger than PAIR reads answers loadedPathUnreadable rather than a half-parsed +// pack identity: readProbeBody returns no body at all for an answer it could not read +// whole, so there is nothing here to mistake for a partial answer. +// +// No status code is consulted, deliberately: the field is the evidence, and an answer that +// names a loaded path is an engine talking about its model whatever it arrived with. An +// error answer that names none is unknown like every other non-answer. A field that is +// absent, or holds something other than a string, is unknown for the same reason and not +// for free: MTPLX's server always answers `model_path`, so the only way to see none is for +// the answer to have stopped being this engine's, and guessing from that is how a pack a +// server has open gets deleted. +func (e *Executor) readLoadedPath(ctx context.Context, engine string, port int, residency *ActionResidency) (string, loadedPathState) { path, err := resolvePlaceholders(residency.Read.Path, map[string]string{"port": strconv.Itoa(port)}) if err != nil { slog.Debug("engine:residency loaded-path read names an unresolvable path", "engine", engine, "path", residency.Read.Path) - return "", false + return "", loadedPathUnreadable } requestURL := fmt.Sprintf("http://127.0.0.1:%d%s", port, path) pctx, cancel := context.WithTimeout(ctx, probeReadTimeout) defer cancel() req, err := http.NewRequestWithContext(pctx, strings.ToUpper(residency.Read.Method), requestURL, nil) if err != nil { - return "", false + return "", loadedPathUnreadable } // The probe marker, so PAIR's own facade answers this itself instead of // forwarding a residency read through to whatever it fronts. @@ -367,28 +506,48 @@ func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, resp, err := e.client.Do(req) if err != nil { slog.Debug("engine:residency loaded-path read failed", "engine", engine, "path", path) - return "", false + return "", loadedPathUnreadable } body := readProbeBody(resp.Body) if body == "" { // Either nothing arrived or more arrived than PAIR reads; readProbeBody - // answers both with no body, and the join does not care which it was. + // answers both with no body, and neither of them is an engine saying it + // loaded nothing. slog.Debug("engine:residency loaded-path answer was empty or larger than PAIR reads", "engine", engine, "path", path) - return "", false + return "", loadedPathUnreadable } var obj map[string]json.RawMessage if err := json.Unmarshal([]byte(body), &obj); err != nil { slog.Debug("engine:residency loaded-path answer was not a JSON object", "engine", engine, "path", path, "bytes", len(body)) - return "", false + return "", loadedPathUnreadable } value, ok := resolveObjectPath(obj, residency.PathField) if !ok { slog.Debug("engine:residency loaded-path answer named no loaded path", "engine", engine, "path", path, "field", residency.PathField) - return "", false + return "", loadedPathUnreadable } var loaded string - if err := json.Unmarshal(value, &loaded); err != nil || loaded == "" { - slog.Debug("engine:residency loaded-path answer held no path PAIR can read", "engine", engine, "path", path, "field", residency.PathField) + if err := json.Unmarshal(value, &loaded); err != nil { + slog.Debug("engine:residency loaded-path answer held a path PAIR cannot read", "engine", engine, "path", path, "field", residency.PathField) + return "", loadedPathUnreadable + } + if loaded == "" { + return "", loadedPathNothing + } + return loaded, loadedPathNamed +} + +// loadedPackPath asks a running engine which directory it loaded its model from, and +// answers two-valued: a directory, or no answer. +// +// The two empty cases are deliberately folded here. residentJoin reads this for a row to +// name, and "the engine loaded nothing" and "the engine did not say" both leave it with no +// row and no evidence, which is what residencyAnswer.complete is for; only the delete gate +// needs the difference, and it reads readLoadedPath. Callers that want a name must not +// take the empty result as "it serves nothing". +func (e *Executor) loadedPackPath(ctx context.Context, engine string, port int, residency *ActionResidency) (string, bool) { + loaded, state := e.readLoadedPath(ctx, engine, port, residency) + if state != loadedPathNamed { return "", false } return loaded, true diff --git a/services/nvpair-engine-manager/testdata/fakeengine/main.go b/services/nvpair-engine-manager/testdata/fakeengine/main.go index c98306422..71e29adfb 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -26,6 +26,7 @@ import ( "strconv" "strings" "sync" + "syscall" "time" ) @@ -77,6 +78,121 @@ func bstr(m map[string]any, k string) string { return "" } +// recordInvocation appends one line to the file named by FAKE_RECORD_FILE, for a +// test that has to see which calls ran and in what order. Only the two CLI shapes a +// removal sequence uses are recorded — a pack listing and a removal — so the +// transcript holds that sequence rather than this process's every startup. When +// FAKE_RECORD_PORT names a port, each line says whether that port answered at the +// instant of the call, which is the question a delete that stops the engine first +// has to answer: was anything still serving the pack it was about to remove? +func recordInvocation() { + path := os.Getenv("FAKE_RECORD_FILE") + if path == "" || len(os.Args) < 2 { + return + } + switch os.Args[1] { + case "models", "remove": + default: + return + } + recordLine(path, "cmd "+strings.Join(os.Args[1:], " ")) +} + +func recordLine(path, line string) { + if port := os.Getenv("FAKE_RECORD_PORT"); port != "" { + line += " port=" + portAnswerState(port) + } + file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + fmt.Fprintln(os.Stderr, "fake-engine record "+path+": "+err.Error()) + return + } + defer file.Close() + fmt.Fprintln(file, line) +} + +// portAnswerState dials a port the way a caller would, so the record says what was +// true of that port at that moment rather than what the caller believed. +func portAnswerState(port string) string { + conn, err := net.DialTimeout("tcp", "127.0.0.1:"+port, 500*time.Millisecond) + if err != nil { + return "quiet" + } + _ = conn.Close() + return "answered" +} + +// holdUntilSignaled stands in for the two ways an engine's port outlives the order +// to stop it: this process closes its listener and takes a beat to exit, or a +// process it started keeps answering on that port after it is gone. A removal that +// means the pack to be gone when it returns has to wait out the first and refuse +// the second, so a test chooses which one this engine does. +func holdUntilSignaled(ln net.Listener, drain time.Duration, holderPIDFile string) { + go func() { + signals := make(chan os.Signal, 1) + signal.Notify(signals, syscall.SIGTERM, os.Interrupt) + defer signal.Stop(signals) + <-signals + if path := os.Getenv("FAKE_RECORD_FILE"); path != "" { + recordLine(path, "stop") // the order arrived; the listener is still up + } + port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port) + if holderPIDFile != "" { + holder := exec.Command(os.Args[0], "holdport", port, holderPIDFile) + detachFromProcessGroup(holder) + if holder.Start() != nil { + os.Exit(1) + } + _ = ln.Close() + os.Exit(0) + } + _ = ln.Close() // the port stops answering here ... + time.Sleep(drain) + os.Exit(0) // ... and this process goes a beat later + }() +} + +// mustDuration reads FAKE_TERM_DRAIN, where an empty value means no drain at all: +// the helper, not this process, is what keeps the port answering. +func mustDuration(raw string) time.Duration { + if raw == "" { + return 0 + } + d, err := time.ParseDuration(raw) + if err != nil { + log.Fatalf("invalid FAKE_TERM_DRAIN %q: %v", raw, err) + } + return d +} + +// holdPort answers on 127.0.0.1: and writes its PID to pidfile once it has the +// port, so a test can stop it. It retries the bind because the listener it stands in +// for closes at about the same moment, and it gives up on its own after a minute so a +// test that forgets to stop it cannot wedge that port for the rest of the run. +func holdPort(port, pidFile string) { + var ln net.Listener + var err error + for range 50 { + if ln, err = net.Listen("tcp", "127.0.0.1:"+port); err == nil { + break + } + time.Sleep(20 * time.Millisecond) + } + if err != nil { + os.Exit(1) + } + if err := os.WriteFile(pidFile, []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { + os.Exit(1) + } + go func() { + time.Sleep(time.Minute) + os.Exit(0) + }() + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) + _ = http.Serve(ln, mux) +} + // reportDownloadProgress renders one `lms get` progress redraw at the // percentage named in os.Args[2], in the CLI's own two-decimal shape. func reportDownloadProgress() { @@ -150,6 +266,7 @@ func downloadUntilInterrupted(interrupts int) { } func main() { + recordInvocation() if path := os.Getenv("PAIR_TEST_ENV_FILE"); path != "" { values := map[string]string{} for _, key := range []string{"OLLAMA_ORIGINS", "PAIR_TEST_LITERAL", "PAIR_TEST_EMPTY", "OLLAMA_HOST", "MODEL_ENDPOINT"} { @@ -274,6 +391,23 @@ func main() { case "holdoutput": // the helper downloadleavesahelper starts time.Sleep(time.Minute) os.Exit(2) + case "models": // stand in for `mtplx models --json`: which packs the cache holds + // and in which directory each sits. /health below says which directory a + // running server mapped, and the two have to be joined to know which pack + // that is — hence a listing of its own, as the engine answers it. + fmt.Println(os.Getenv("FAKE_PACK_ROWS")) + return + case "remove": // stand in for `mtplx remove --yes --json`: it does the + // removal and reports nothing. The line recordInvocation wrote on the way in + // — with whether the engine's port was answering then — is what a test reads. + return + case "holdport": // keep answering on a port the engine that opened it has given up + // args: holdport + if len(os.Args) < 4 { + os.Exit(2) + } + holdPort(os.Args[2], os.Args[3]) + return case "listfrom": // stand in for `mtplx models --json` answering: print the // listing held in the named file and exit. This is a cache listing run as // a command rather than a request, with no shell between the two. @@ -613,6 +747,12 @@ func main() { if err != nil { log.Fatalf("fake-engine listen %s: %v", addr, err) } + // FAKE_TERM_DRAIN is how long this process keeps running after its listener has + // gone; FAKE_TERM_HOLDER_PID hands the port to a helper that outlives the + // process. Each is a way a port can still answer after a stop looked done. + if drain, holderPID := os.Getenv("FAKE_TERM_DRAIN"), os.Getenv("FAKE_TERM_HOLDER_PID"); drain != "" || holderPID != "" { + holdUntilSignaled(ln, mustDuration(drain), holderPID) + } fmt.Fprintf(os.Stderr, "fake-engine listening on %s\n", ln.Addr()) if err := http.Serve(ln, mux); err != nil { log.Fatalf("fake-engine serve: %v", err) diff --git a/services/nvpair-engine-manager/testdata/fakeengine/owngroup_unix.go b/services/nvpair-engine-manager/testdata/fakeengine/owngroup_unix.go new file mode 100644 index 000000000..7d033c918 --- /dev/null +++ b/services/nvpair-engine-manager/testdata/fakeengine/owngroup_unix.go @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows + +package main + +// How the fake's port holder escapes the process tree PAIR terminates. The holder +// stands in for a listener that outlives the engine process, which is only a thing +// that can happen when the process holding the port is not one PAIR started: a stop +// asks the engine's whole group to exit and then force-kills what is left of it. + +import ( + "os/exec" + "syscall" +) + +// detachFromProcessGroup gives the helper its own process group, so neither the +// graceful signal nor the forced kill that follows it reaches it. +func detachFromProcessGroup(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} +} diff --git a/services/nvpair-engine-manager/testdata/fakeengine/owngroup_windows.go b/services/nvpair-engine-manager/testdata/fakeengine/owngroup_windows.go new file mode 100644 index 000000000..248b68d75 --- /dev/null +++ b/services/nvpair-engine-manager/testdata/fakeengine/owngroup_windows.go @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows + +package main + +// How the fake's port holder escapes the process tree PAIR terminates. The holder +// stands in for a listener that outlives the engine process, which is only a thing +// that can happen when the process holding the port is not one PAIR started: a stop +// asks the engine's whole group to exit and then force-kills what is left of it. + +import "os/exec" + +// detachFromProcessGroup has no Windows equivalent that would hold: a stop there is +// taskkill /T /F, which ends the whole tree however the child was created, so no +// helper this process starts can outlive it. The test that needs one is Unix-only. +func detachFromProcessGroup(*exec.Cmd) {} From e98d348c9b508198d2a431ac2dcf527c6951cc45 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 09/10] feat(desktop): name the quit on a delete that takes MTPLX down Deleting a MTPLX pack takes the server down with it, and the engine manager now asks why before it quits anything: a pack the running engine says it is not serving is removed with the server left up, and only a pack the server holds, or one that cannot be ruled out, stops MTPLX first. The desktop still answered that with what it offered before the service decided any of it, namely Delete disabled on the one pack the engine reported and a one-click delete on every row where nothing had been reported. So the delete that quits a working engine was a single click on a list that could not say so, and the row that did warn only warned by greying out. Delete is decided per row now, from the same three answers the engine manager uses: the engine says this pack is not resident, it says it is, or it was never asked. `EngineModels.residencyKnown` carries the third answer across the bridge, because `ModelItem.status` cannot hold it: a missing residency answer still stamps every row `idle`, which is a true statement about what was claimed and a false statement about what is. It is a required field with no default, since a `?? true` fails open on exactly the data the flag exists to describe, and the terminal interface already keeps those three answers apart as `no`, `yes` and `?`. Quitting is always safe and a one-click delete is not, so the two cautious answers share the "Quit MTPLX and delete" row and only the known-idle one acts at once. The confirmation says what happens to the engine rather than what happens to the pack, because on the unasked row the pack may well not be loaded and nothing knows that either way. Whether a delete asks first travels to the handler as the menu item's id, `delete` or `delete-confirm`, which keeps the decision in one function and the handler's dependencies stable. The 180s safety net is keyed on the new `stopsEngineBeforeDelete` capability instead of a fourth timeout, and stays above the 120s RPC budget that has to outlast the stop grace plus the wait for the port to go quiet. `tests/modular/model-delete-affordance.test.ts` holds the whole matrix at component level, `mtplx-served-model-list.test.ts` pins a missing residency key against an empty one, `pending-actions-delete.test.ts` runs the quit's timeout on a fake clock, and `delete-model-restart.test.ts` ties `stop_before` to its capability the way it already tied `restart_after`, including that no manifest may declare both. Each was checked against a broken build: a missing answer offering the plain delete, the bridge defaulting residency to known, an empty answer read as no answer, the timeout dropping MTPLX back to 60s, and a menu id that never asked each failed their own tests, and dropping `stopsEngineBeforeDelete` from the caps failed four files. Left open on purpose: the desktop hides the model list for a stopped engine, which MTPLX's offline cache read and the terminal interface do not, so both delete spellings appear only while MTPLX is up. Recorded in `desktop/docs/services-parity.md`, unchanged here. Signed-off-by: Steven Beverly --- desktop/docs/services-parity.md | 55 ++- .../electron/service-bridge/modular-state.ts | 74 ++-- desktop/src/shared/types/engines.ts | 11 + desktop/src/shared/utils/engines.ts | 8 +- .../components/ModelManager/ModelManager.tsx | 44 ++- .../ui/components/ModelManager/ModelRow.tsx | 19 +- .../NodeList/NodeEngineSettings.tsx | 1 + .../src/ui/constants/engine-capabilities.ts | 11 +- .../src/ui/stores/pending-actions.store.ts | 38 ++- desktop/src/ui/types/engine-info.ts | 7 + desktop/src/ui/types/engine-manifest.ts | 10 + desktop/src/ui/types/model-row.ts | 8 + desktop/src/ui/utils/model-delete.ts | 98 ++++++ .../modular/delete-model-restart.test.ts | 83 ++++- desktop/tests/modular/engine-identity.test.ts | 11 +- .../modular/engine-install-button.test.ts | 1 + .../engine-model-selection-action.test.ts | 11 +- .../modular/model-delete-affordance.test.ts | 323 ++++++++++++++++++ .../modular/model-manager-transitions.test.ts | 1 + .../modular/model-manager-visibility.test.ts | 1 + .../tests/modular/mtplx-card-actions.test.ts | 1 + .../modular/mtplx-served-model-list.test.ts | 76 ++++- .../modular/pending-actions-delete.test.ts | 29 +- 23 files changed, 826 insertions(+), 95 deletions(-) create mode 100644 desktop/src/ui/utils/model-delete.ts create mode 100644 desktop/tests/modular/model-delete-affordance.test.ts diff --git a/desktop/docs/services-parity.md b/desktop/docs/services-parity.md index 9481d6aea..38dbd3821 100644 --- a/desktop/docs/services-parity.md +++ b/desktop/docs/services-parity.md @@ -294,8 +294,18 @@ invisible while clearly running. Identifier matching is byte-exact, as on LM Studio, llama.cpp and vLLM, rather than Ollama's implied `:latest`. Pulls and deletes are CLI actions with no byte progress, so a pull shows only that it is pulling. `mtplx remove` has no in-use guard and does not clear a -deleted pack from a stopped engine's launch arguments, so the desktop app blocks -Delete on the pack being served (`deleteBlockedWhileLoaded`). +deleted pack from a stopped engine's launch arguments, so the engine manager quits +MTPLX and waits for its port to stop answering before removing a pack the running +server could be holding, and leaves it down (`stop_before`). The desktop says that +on the row: Delete reads "Quit MTPLX and delete" and asks first, on the pack being +served and on any pack whose residency could not be read, because a one-click delete +is only safe where the engine has shown it is not in use. It is not blocked the way +vLLM blocks its served model (`deleteBlockedWhileLoaded`), and "eject first" was +never a way round it: eject is the same stop. Both spellings appear only while MTPLX +is up, though: the desktop hides the whole model list for a stopped engine, while the +engine manager reads MTPLX's pack cache offline and the terminal interface keeps +Delete available with the engine down. That is an open divergence between the desktop +and the two clients of the same data, not a deliberate narrowing. MTPLX's catalogue is MTPLX's own published pack list rather than a Hugging Face browse, because the engine loads only packs rebuilt for its decode path and a general @@ -405,23 +415,34 @@ for any other engine and never issues `engine:restart` itself, so the bundled deletion in-process, so their manifests omit `restart_after` and their capability entries omit `restartsOnModelDelete`: no engine bounce and no restart confirmation. llama.cpp may stop the selected model while removing its cache -entry, but the router and its other models stay up. Those manifest and -capability facts have to stay in step across Go and TypeScript, which nothing in -either type system enforces — so +entry, but the router and its other models stay up. MTPLX changes itself a third +way: its `delete_model` declares `stop_before`, so the engine manager quits MTPLX +and waits for its port to stop answering before removing a pack the running server +could be holding — `mtplx remove` has no in-use guard — and leaves it down rather +than restarting it. Because that also interrupts inference, +`EngineCapabilities.mtplx.stopsEngineBeforeDelete` confirms it first, with wording +that says the engine is quitting rather than bouncing. It is asked per row, not per +engine: MTPLX removes a pack it reports not serving without stopping anything, so a +row only asks where non-residency is not established — which includes a residency +answer that could not be read. +Those manifest and capability facts have to stay in step across Go and TypeScript, +which nothing in either type system enforces — so `tests/modular/delete-model-restart.test.ts` reads the shipped manifests and -asserts the pair agrees, and `TestBundledManifestsRestartOnlyLMStudio` guards the -same thing from the Go side. - -Several model-action timeouts have to be ordered correctly. For a -restart-backed delete, the reply is withheld until the engine is ready again -(LM Studio's `ready.timeout_s` alone is 60s), so +asserts the pair agrees, for `restart_after` and `stop_before` alike and for the +two never appearing together, and +`TestBundledManifestsRestartOnlyLMStudio` guards the restart half from the Go side. + +Several model-action timeouts have to be ordered correctly. For a delete that +changes the engine, the reply is withheld until that is done — LM Studio's +`ready.timeout_s` alone is 60s, and MTPLX spends its stop grace plus the 15s it +waits for the port to go quiet — so `MODULAR_MODEL_ACTION_TIMEOUT_MS` anchors the delete-specific observers. Ollama Load uses a separate 10/31-minute response-header budget: | Budget | Value | Why | | ------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `MODULAR_MODEL_ACTION_TIMEOUT_MS` (`modular-runtime.ts`) | 120s | The RPC must outlast a full stop + readiness-probed start. | -| `RESTART_DELETE_TIMEOUT_MS` (`pending-actions.store.ts`) | 180s | The optimistic-spinner safety net must outlast the RPC, or it expires mid-flight and drops the spinner while the delete is still running. | +| `DELETE_ENGINE_CHANGE_TIMEOUT_MS` (`pending-actions.store.ts`) | 180s | The optimistic-spinner safety net for either engine-changing delete. It must outlast the RPC, or it expires mid-flight and drops the spinner while the delete is still running. | | `engineResponseHeaderTimeout` (`executor.go`) | 30s | Downloads and ordinary local HTTP actions retain a prompt response-header bound; probe contexts stay shorter. | | `pullProgressTimeout` (`executor.go`) | 30min | Streaming Ollama and llama.cpp pulls may run indefinitely while layer/file completed bytes advance; 30 minutes without advancing bytes cancels the stalled pull. | | `ollamaLoadResponseHeaderTimeout` (`executor.go`) | 10min | Only Ollama's local `run_model` action gets the cold-load allowance. | @@ -729,6 +750,16 @@ safety-net timeout (`pending-actions.store.ts`). Loaded state carries no `sizeVram`/`expiresAt` — the backend delivers the simpler `loadedByEngine` name-set, not structured details. +A missing `loadedByEngine` key is not an empty one, and the desktop keeps that +apart: `EngineModels.residencyKnown` says whether anything answered what the +engine holds, the same presence test `inventoryKnown` uses for the downloaded +list and the same three answers the terminal interface shows as `"no"`, `"yes"` +and `"?"`. A row whose residency is unknown still reads as idle, because +nothing claimed it was loaded, but it does not get the one-click Delete that a +known-idle row gets: on MTPLX an unreadable answer is treated as the pack being +in use, which is what the engine manager does with it. See +`modelDeleteMode` (`src/ui/utils/model-delete.ts`). + vLLM and MTPLX advertise only the model they are serving, so each `modelsByEngine` entry is that one name, for routing. The whole downloaded list arrives as `downloadedByEngine`, read even while the engine is stopped, and `modelsForEngine` diff --git a/desktop/src/electron/service-bridge/modular-state.ts b/desktop/src/electron/service-bridge/modular-state.ts index eeb0d2a10..3b724463d 100644 --- a/desktop/src/electron/service-bridge/modular-state.ts +++ b/desktop/src/electron/service-bridge/modular-state.ts @@ -470,9 +470,24 @@ function pendingEngineOpIdleTimeoutMs(status: EngineProcessStatus): number { * The set of models a node reports loaded in memory for an engine, read from * `ModularNode.loadedByEngine` (enriched from the backend's per-engine * `loadedByEngine`), whose keys use the engine-manager's spelling. + * + * `null` is a third answer, not an empty set: the node never said what it holds. + * `nvpair-engine-manager` keeps those apart on purpose — `ModelsResult.LoadedByEngine` + * in `services/nvpair-engine-manager/models.go` reads "an engine key with an empty + * list means 'running, nothing loaded' while a MISSING key means 'not running / not + * queryable / no loaded endpoint'" — and the TUI's LOADED column shows the two as + * `"no"` and `"?"`, pinned by `TestUnreportedLoadState_IsUnknown` in + * `services/nvpair-tui/ui/nodedetail_test.go`. The desktop keeps the split for the + * same reason: a delete that would take the engine down with it treats `null` as + * "possibly resident". See `modelDeleteMode` in `@/ui/utils/model-delete`. */ -function loadedNamesForEngine(node: ModularNode | undefined, engineType: EngineType): Set { - return new Set(node?.loadedByEngine[engineManagerName(engineType)] ?? []) +function residencyForEngine( + node: ModularNode | undefined, + engineType: EngineType +): Set | null { + const key = engineManagerName(engineType) + if (!node || !(key in node.loadedByEngine)) return null + return new Set(node.loadedByEngine[key]) } function sameStringList(left: string[], right: string[]): boolean { @@ -1186,15 +1201,16 @@ class ModularBridgeState { } else { const cached = this.localManagerModels.get(engineType) if (cached) { - const loaded = loadedNamesForEngine(selfNode, engineType) + const loaded = residencyForEngine(selfNode, engineType) models.push({ engineType, nodeId: selfId, models: cached.map(item => ({ ...item, - status: loaded.has(item.name) ? 'loaded' : 'idle' + status: loaded?.has(item.name) ? 'loaded' : 'idle' })), - inventoryKnown: true + inventoryKnown: true, + residencyKnown: loaded !== null }) } } @@ -1914,12 +1930,15 @@ class ModularBridgeState { * Called by the supervisor after a model read (or with an empty list when the * engine is stopped, since its own list is unreachable then). * - * `loadedNames` is the set that read reported resident in memory; `null` - * means it reported none, so residency carries over from what the node last - * reported. A supplied set is written to the node as well: - * {@link discoveryModelsForNode} and {@link getEngineInitialState} re-stamp - * residency from the node, so a cache-only update would list the model being - * served as idle. + * `loadedNames` is the residency answer that read got: an array, including an + * empty one, is an answer and says what the engine holds; `null` means the + * read got no answer, which is not the same claim. With no answer this falls + * back to what the node last reported, because that is the only residency + * evidence there is — but it does not *make* an answer, so a node that never + * reported one pushes the patch with `residencyKnown: false`. A supplied set + * is written to the node as well: {@link discoveryModelsForNode} and + * {@link getEngineInitialState} re-stamp residency from the node, so a + * cache-only update would list the model being served as idle. */ setLocalEngineModels( engineType: EngineType, @@ -1932,8 +1951,8 @@ class ModularBridgeState { // node's loaded set so a refresh (pull/lifecycle) preserves residency // instead of resetting every row to idle. That set is seeded by discovery // self-enrichment and kept fresh by {@link applyLocalModelSnapshot}. - const loaded = loadedNames ? new Set(loadedNames) : loadedNamesForEngine(node, engineType) - const items = modelNames.map(name => modelItem(name, loaded.has(name))) + const loaded = loadedNames ? new Set(loadedNames) : residencyForEngine(node, engineType) + const items = modelNames.map(name => modelItem(name, loaded !== null && loaded.has(name))) this.localManagerModels.set(engineType, items) if (!nodeId) return if (node && loadedNames) { @@ -1948,7 +1967,13 @@ class ModularBridgeState { emitBridgePush('engines:state-changed', { nodeId, engineType, - models: { engineType, nodeId, models: items, inventoryKnown: true } + models: { + engineType, + nodeId, + models: items, + inventoryKnown: true, + residencyKnown: loaded !== null + } }) } @@ -2083,12 +2108,13 @@ class ModularBridgeState { } private toEngineModels(node: ModularNode, engine: ProxyEngine): EngineModels { - const loaded = loadedNamesForEngine(node, engine) + const loaded = residencyForEngine(node, engine) + const managerName = engineManagerName(engine) return { engineType: engine, nodeId: node.id, models: this.modelsForEngine(node, engine).map(name => - modelItem(name, loaded.has(name)) + modelItem(name, loaded !== null && loaded.has(name)) ), // An engine whose list is read from disk is listed while stopped, so // an empty list reads as "nothing downloaded". That is true only when @@ -2096,7 +2122,11 @@ class ModularBridgeState { // whose list never arrived, is unknown. inventoryKnown: !EnginesListingModelsWhenStopped.includes(engine) || - engineManagerName(engine) in node.downloadedByEngine + managerName in node.downloadedByEngine, + // The same presence test, one key over: `loadedByEngine` is written + // from the same sweep and its missing key means the peer's residency + // was never read. See {@link residencyForEngine}. + residencyKnown: managerName in node.loadedByEngine } } @@ -2126,15 +2156,19 @@ class ModularBridgeState { // The cached list is the authoritative `list_models` set (names // only); stamp `'loaded'` from the self node's discovery/push // loaded set so the local card reflects in-memory residency too. - const loaded = loadedNamesForEngine(node, engine) + const loaded = residencyForEngine(node, engine) return { engineType: engine, nodeId, models: cached.map(item => ({ ...item, - status: loaded.has(item.name) ? 'loaded' : 'idle' + status: loaded?.has(item.name) ? 'loaded' : 'idle' })), - inventoryKnown: true + inventoryKnown: true, + // The cache says what is on disk, never what is in memory, so + // residency is known only when some source actually reported + // the engine's loaded set for this node. + residencyKnown: loaded !== null } } } diff --git a/desktop/src/shared/types/engines.ts b/desktop/src/shared/types/engines.ts index f25dbba3c..3b242e036 100644 --- a/desktop/src/shared/types/engines.ts +++ b/desktop/src/shared/types/engines.ts @@ -126,6 +126,17 @@ export interface EngineModels { * list must not be shown as "nothing downloaded". */ inventoryKnown: boolean + /** + * Whether the engine answered what it holds in memory, which is what lets a + * row say a model is *not* resident rather than merely unreported. False + * keeps that question open: every model is then treated as possibly resident + * wherever acting on that doubt is destructive. `ModelItem.status` answers + * only "known resident", so it cannot carry this — an unanswered read still + * stamps `idle` — and a per-engine flag is the twin of + * {@link inventoryKnown}. `modelDeleteMode` in `src/ui/utils/model-delete.ts` + * is what reads it. + */ + residencyKnown: boolean } export interface ModelItem { diff --git a/desktop/src/shared/utils/engines.ts b/desktop/src/shared/utils/engines.ts index f6599149d..107b99498 100644 --- a/desktop/src/shared/utils/engines.ts +++ b/desktop/src/shared/utils/engines.ts @@ -94,13 +94,17 @@ export function engineOwnerTool(owner: string | undefined): string | null { /** * Shallow placeholder when no model list has been pushed for this node/engine * yet. For an engine whose list is read from disk and shown while it is stopped, - * no list yet means unknown, not "nothing downloaded". + * no list yet means unknown, not "nothing downloaded". Nothing is known about + * residency either, which is why {@link EngineModels.residencyKnown} is false + * here rather than derived from the other flag: an engine that was never asked + * what it holds has not answered "nothing". */ export function emptyEngineModels(nodeId: string, engineType: EngineType): EngineModels { return { nodeId, engineType, models: [], - inventoryKnown: !EnginesListingModelsWhenStopped.includes(engineType) + inventoryKnown: !EnginesListingModelsWhenStopped.includes(engineType), + residencyKnown: false } } diff --git a/desktop/src/ui/components/ModelManager/ModelManager.tsx b/desktop/src/ui/components/ModelManager/ModelManager.tsx index dd649ab78..96abff96f 100644 --- a/desktop/src/ui/components/ModelManager/ModelManager.tsx +++ b/desktop/src/ui/components/ModelManager/ModelManager.tsx @@ -6,6 +6,7 @@ import { Banner, Button, Flex, Stack, Text } from '@nvidia/foundations-react-cor import type { BackendInfo } from '@/ui/types/engine-info' import { EngineCapabilities } from '@/ui/constants/engine-capabilities' import { formatModelDisplayName } from '@/ui/utils/format-model-display-name' +import { deleteConfirmCopy } from '@/ui/utils/model-delete' import { ModelExpiry } from '@/shared/types/engines' import { ConfirmModal } from '@/ui/components/ConfirmModal' @@ -119,14 +120,15 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId return results })() - // Only an engine that restarts to pick a deletion up (LM Studio today) - // confirms first, because the restart interrupts in-flight inference. - // Ollama and every other engine delete straight away — this stays false for - // them, which `tests/modular/delete-model-restart.test.ts` pins against the - // engine-manager manifests. The restart itself belongs to the engine - // manager, not to this click. - const confirmBeforeDelete = caps?.restartsOnModelDelete ?? false - + // Whether a delete asks before firing is decided per row by `modelDeleteMode` + // and travels to this handler as the menu item's id: `delete` acts now, + // `delete-confirm` asks first. Only an engine that has to change itself to + // remove a pack asks — LM Studio restarts for every delete, MTPLX quits + // wherever it cannot rule the model out — because that change interrupts + // in-flight inference. Ollama, llama.cpp and vLLM delete straight away, which + // `tests/modular/delete-model-restart.test.ts` pins against the engine-manager + // manifests. The engine change itself belongs to the engine manager, not to + // this click. const handleAction = useCallback( (modelName: string, action: string) => { if (!canManageModels) return @@ -138,15 +140,25 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId window.pairApi.engines.unloadModel(backendType, nodeId, modelName) break case 'delete': - if (confirmBeforeDelete) { - setModelPendingDelete(modelName) - break - } window.pairApi.engines.deleteModel(backendType, nodeId, modelName) break + case 'delete-confirm': + setModelPendingDelete(modelName) + break } }, - [backendType, confirmBeforeDelete, canManageModels, nodeId] + [backendType, canManageModels, nodeId] + ) + + // One dialog serves every row, so its wording comes from what the engine + // declares, not from the row: a delete that quits the engine and one that + // restarts it need different sentences, and no engine does both — + // `Manifest.Validate` (`services/nvpair-engine-manager/registry.go`) refuses a + // manifest declaring `stop_before` and `restart_after` together. The dialog + // only ever opens for a delete that changes the engine. + const deleteCopy = useMemo( + () => deleteConfirmCopy(caps, backend.displayName, displayName(modelPendingDelete ?? '')), + [caps, backend.displayName, displayName, modelPendingDelete] ) // `ConfirmModal` closes (`onOpenChange(false)`) before it calls `onConfirm`, @@ -267,6 +279,8 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId key={model.name} model={model} isRunning={canManageModels} + engineName={backend.displayName} + residencyKnown={backend.residencyKnown} capabilities={caps} progress={getProgress(nodeId, backend.type, 'pull', model.name)} pendingAction={usePendingActionsStore @@ -288,8 +302,8 @@ export function ModelManager({ backend, nodeId }: { backend: BackendInfo; nodeId if (!open) setModelPendingDelete(null) }} title="Delete model?" - message={`Deleting ${displayName(modelPendingDelete ?? '')} requires ${backend.displayName} to be restarted.`} - confirmLabel="Delete and restart" + message={deleteCopy.message} + confirmLabel={deleteCopy.confirmLabel} confirmColor="danger" onConfirm={handleConfirmDelete} /> diff --git a/desktop/src/ui/components/ModelManager/ModelRow.tsx b/desktop/src/ui/components/ModelManager/ModelRow.tsx index 136eb8b59..4a98b26a3 100644 --- a/desktop/src/ui/components/ModelManager/ModelRow.tsx +++ b/desktop/src/ui/components/ModelManager/ModelRow.tsx @@ -4,6 +4,7 @@ import { memo, useMemo } from 'react' import { Divider, Stack } from '@nvidia/foundations-react-core' import { useDropdownClickable } from '@/ui/hooks/useDropdownClickable' +import { deleteActionName, deleteMenuItemLabel, modelDeleteMode } from '@/ui/utils/model-delete' import { ModelRowHeader } from './ModelRowHeader' import { ModelRowSecondaryRow } from './ModelRowSecondaryRow' import type { ModelRowProps } from '@/ui/types/model-row' @@ -28,6 +29,8 @@ function pendingLabel(action: EngineCommandType): string | null { function ModelRowInner({ model, isRunning, + engineName, + residencyKnown, capabilities, progress, pendingAction, @@ -46,6 +49,10 @@ function ModelRowInner({ // A command is already in flight for this model -- lock the whole menu so // the user cannot fire a second conflicting op before it resolves. const busy = !isRunning || pendingAction !== undefined + // `capabilities` is a module-level constant per engine, so depending on the + // object rather than picking its fields keeps this honest: the delete mode + // reads three of them and they cannot change independently of its identity. + const deleteMode = modelDeleteMode(capabilities, residencyKnown, isLoaded) items.push({ id: 'load', children: 'Load', @@ -64,18 +71,18 @@ function ModelRowInner({ } if (capabilities.hasDeleteModel) { items.push({ - id: 'delete', - children: 'Delete', + id: deleteActionName(deleteMode), + children: deleteMenuItemLabel(deleteMode, engineName), danger: true, - disabled: busy || (isLoaded && !!capabilities.deleteBlockedWhileLoaded) + disabled: busy || deleteMode === 'blocked' }) } return items }, [ - capabilities.hasEject, - capabilities.hasDeleteModel, - capabilities.deleteBlockedWhileLoaded, + capabilities, + residencyKnown, isLoaded, + engineName, isRunning, model.downloaded, pendingAction diff --git a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx index a7d733233..a6e503289 100644 --- a/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx +++ b/desktop/src/ui/components/NodeList/NodeEngineSettings.tsx @@ -104,6 +104,7 @@ export default function NodeEngineSettings({ nodeId }: { nodeId: string }) { proxyPort: status.proxyPort, models: models.models, modelsKnown: models.inventoryKnown, + residencyKnown: models.residencyKnown, docsUrl: EngineDefaultLinks[type]?.docsUrl, installUrl: EngineDefaultLinks[type]?.installUrl, installedVersion: status.installedVersion, diff --git a/desktop/src/ui/constants/engine-capabilities.ts b/desktop/src/ui/constants/engine-capabilities.ts index b6e17b0d8..0e57ee6a4 100644 --- a/desktop/src/ui/constants/engine-capabilities.ts +++ b/desktop/src/ui/constants/engine-capabilities.ts @@ -118,10 +118,13 @@ export const EngineCapabilities: Record = { // and its list comes from `mtplx models --json`, which answers offline. hasModelSearchOnlyWhenRunning: false, hasDeleteModel: true, - // `mtplx remove` has no in-use guard, and a stopped engine keeps the - // deleted pack in its launch arguments, so Delete is refused on the pack - // being served: eject first. - deleteBlockedWhileLoaded: true, + // `mtplx remove` has no in-use guard, so the engine manager quits MTPLX and + // waits for its port to go quiet before removing a pack the running server + // could be holding, and leaves it down (`stop_before`). It is not blocked + // the way vLLM blocks, and "eject first" was never a way round it: eject is + // the same stop, and with the engine down the model list is hidden and every + // row's controls are disabled anyway. + stopsEngineBeforeDelete: true, // Load writes the pack's directory into MTPLX's launch arguments and // restarts the engine on them. loadRestartsEngine: true, diff --git a/desktop/src/ui/stores/pending-actions.store.ts b/desktop/src/ui/stores/pending-actions.store.ts index a094bcd5b..9493f1e06 100644 --- a/desktop/src/ui/stores/pending-actions.store.ts +++ b/desktop/src/ui/stores/pending-actions.store.ts @@ -47,16 +47,22 @@ const OLLAMA_LOAD_PENDING_TIMEOUT_MS = 32 * 60_000 */ const RESTART_LOAD_PENDING_TIMEOUT_MS = MODEL_SWITCH_TIMEOUT_MS /** - * Safety net for a delete on an engine whose backend restarts to pick the - * deletion up (`EngineCaps.restartsOnModelDelete` / the manifest's - * `restart_after`). That delete does not reply until the engine has stopped and - * passed its readiness probe again — for LM Studio, `ready.timeout_s` alone is - * 60s — so the default net would expire mid-flight and drop the spinner while - * the operation is still running. Keep this above - * `MODULAR_MODEL_ACTION_TIMEOUT_MS` (120s) so the real result, success or - * failure, always wins the race against the net. + * Safety net for a delete on an engine that has to change itself to remove a + * model, rather than just losing a file: one that restarts to pick the deletion + * up (`EngineCaps.restartsOnModelDelete` / the manifest's `restart_after`, LM + * Studio) and one that quits first and stays down + * (`EngineCaps.stopsEngineBeforeDelete` / `stop_before`, MTPLX). Neither replies + * until that is done — LM Studio bounces the server and passes its readiness + * probe again, `ready.timeout_s` alone being 60s, and MTPLX spends its stop + * grace plus the 15s it waits for the port to go quiet + * (`stopBeforeQuietBound`, `actions.go`) before it removes anything. The default + * net would expire mid-flight and drop the spinner while the operation is still + * running, and a row that re-enables Delete there hands back a destructive + * control to fire again. Keep this above + * `MODULAR_MODEL_ACTION_TIMEOUT_MS` (120s) so the real + * result, success or failure, always wins the race against the net. */ -const RESTART_DELETE_TIMEOUT_MS = 180_000 +const DELETE_ENGINE_CHANGE_TIMEOUT_MS = 180_000 /** How often the sweep drops expired entries. */ const SWEEP_INTERVAL_MS = 1_000 @@ -111,8 +117,10 @@ interface PendingAction { /** * How long the safety net waits for a command before re-enabling its control. - * Slow Ollama loads and restart-backed Loads or deletes outlast the default net; - * every other command keeps 60 seconds. + * Slow Ollama loads and engine-changing Loads or deletes outlast the default net; + * every other command keeps 60 seconds. A delete is graded by how the engine + * reacts to it, not by which engine it is: the two delete flags name the two + * ways an engine changes to lose a model, and no manifest declares both. */ function timeoutFor(command: EngineCommandType, engineType: EngineType): number { if (command === 'loadModel' && engineType === 'ollama') { @@ -121,8 +129,12 @@ function timeoutFor(command: EngineCommandType, engineType: EngineType): number if (command === 'loadModel' && EngineCapabilities[engineType]?.loadRestartsEngine) { return RESTART_LOAD_PENDING_TIMEOUT_MS } - if (command === 'deleteModel' && EngineCapabilities[engineType]?.restartsOnModelDelete) { - return RESTART_DELETE_TIMEOUT_MS + if ( + command === 'deleteModel' && + (EngineCapabilities[engineType]?.restartsOnModelDelete || + EngineCapabilities[engineType]?.stopsEngineBeforeDelete) + ) { + return DELETE_ENGINE_CHANGE_TIMEOUT_MS } return PENDING_TIMEOUT_MS } diff --git a/desktop/src/ui/types/engine-info.ts b/desktop/src/ui/types/engine-info.ts index f37c9cf64..8580a595b 100644 --- a/desktop/src/ui/types/engine-info.ts +++ b/desktop/src/ui/types/engine-info.ts @@ -102,6 +102,13 @@ export interface BackendInfo { * be, so an empty list is not shown as "nothing downloaded". */ modelsKnown: boolean + /** + * Whether the engine answered which of {@link models} it holds in memory, + * carried here from the node's model snapshot. False is not "holds none": + * with no answer, deleting a model has to assume the engine could be serving + * it, which is what decides that row's Delete affordance. + */ + residencyKnown: boolean /** System-level dependencies required before install/run (local node only) */ prerequisites?: BackendPrerequisite[] /** Progress info during install/uninstall (local node only, ephemeral) */ diff --git a/desktop/src/ui/types/engine-manifest.ts b/desktop/src/ui/types/engine-manifest.ts index f75c9f522..d2e980b5f 100644 --- a/desktop/src/ui/types/engine-manifest.ts +++ b/desktop/src/ui/types/engine-manifest.ts @@ -72,6 +72,16 @@ export interface EngineCaps { * model files go, so the backend refuses it and the UI does not offer it. */ deleteBlockedWhileLoaded?: boolean + /** + * When true, deleting a model the engine could be holding quits the engine + * first and leaves it down, so Delete names that on the item and asks before + * firing. Mirrors the manifest's `stop_before`, which is what makes the engine + * manager stop and wait out the port — including when the engine cannot be + * asked what it holds. Declared instead of inferred from + * `loadRestartsEngine` because loading and deleting take the engine down for + * opposite reasons, and only one of them brings it back. + */ + stopsEngineBeforeDelete?: boolean /** * If the engine has its own public model catalog (e.g. ollama.com), provide the * hub config here. Presence doubles as the truthy flag for the hub source selector. diff --git a/desktop/src/ui/types/model-row.ts b/desktop/src/ui/types/model-row.ts index 674913b22..f332b24d4 100644 --- a/desktop/src/ui/types/model-row.ts +++ b/desktop/src/ui/types/model-row.ts @@ -16,6 +16,14 @@ export type ModelRowDropdownControl = { export interface ModelRowProps { model: ModelItem isRunning: boolean + /** Display name of the engine owning this row, used to name it in Delete copy. */ + engineName: string + /** + * Whether the engine answered what it holds in memory. False is not "holds + * nothing": it keeps the question open, which is what decides whether this + * row can offer a one-click Delete. See `modelDeleteMode`. + */ + residencyKnown: boolean capabilities: EngineCaps progress?: EngineProgress /** diff --git a/desktop/src/ui/utils/model-delete.ts b/desktop/src/ui/utils/model-delete.ts new file mode 100644 index 000000000..9cc43d296 --- /dev/null +++ b/desktop/src/ui/utils/model-delete.ts @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { EngineCaps } from '@/ui/types/engine-manifest' + +/** + * What removing one model does to the engine, and therefore what its row offers. + * The engine manager decides this; the desktop only says it, so every arm here + * traces to a manifest declaration plus what the engine was able to answer. + * + * A manifest's `restart_after` bounces the engine back up after the removal + * (LM Studio, which builds its model index at startup). Its `stop_before` quits + * the engine and waits for its port to go quiet first (MTPLX), and it does that + * for **two** of the three answers to "is this model the one being served?": the + * engine says it is, and the engine cannot be asked — see `stopBeforeAction` in + * `services/nvpair-engine-manager/actions.go`, which treats an unreadable answer + * as the model being in use. `Manifest.Validate` refuses a manifest declaring + * both `stop_before` and `restart_after` (`registry.go`), so no engine both + * quits and restarts, and the two flags stay enough to pick one wording. + * + * That is the same three-way split the TUI's LOADED column keeps apart — + * `"no"`, `"yes"`, `"?"`, pinned by `TestUnreportedLoadState_IsUnknown` in + * `services/nvpair-tui/ui/nodedetail_test.go` — where an engine left out of + * `loadedByEngine` means "cannot tell", not "nothing resident". Two of the three + * answers are the same button here, because quitting the engine is always safe + * and a one-click Delete is only safe when non-residency is known. That is why + * `residencyKnown` is an input: reading a missing answer as "not loaded" is what + * this file exists to prevent. + */ +type ModelDeleteMode = 'blocked' | 'plain' | 'restarts-engine' | 'quits-engine' + +/** + * Choose the affordance for one model row. + * + * @param capabilities the engine's declared capabilities. + * @param residencyKnown whether the engine answered what it holds in memory. + * False covers both "no residency read exists" and "the read failed", and is + * deliberately not the same as {@link residentInEngine}: not knowing is not + * knowing-absent. + * @param residentInEngine the engine reported this model resident. + */ +export function modelDeleteMode( + capabilities: EngineCaps, + residencyKnown: boolean, + residentInEngine: boolean +): ModelDeleteMode { + // vLLM refuses a delete that would pull the model out from under its own + // server, so there is nothing to offer — not a warning, a closed door. + if (residentInEngine && capabilities.deleteBlockedWhileLoaded) return 'blocked' + // MTPLX's removal stops the engine whenever it cannot rule the model out, so + // the row warns for a resident pack and an unreadable one alike. + if (capabilities.stopsEngineBeforeDelete && (!residencyKnown || residentInEngine)) { + return 'quits-engine' + } + // LM Studio rebuilds its index only at startup, so any delete bounces it. + if (capabilities.restartsOnModelDelete) return 'restarts-engine' + return 'plain' +} + +/** The menu text. Names the engine only where deleting takes it down. */ +export function deleteMenuItemLabel(mode: ModelDeleteMode, engineName: string): string { + return mode === 'quits-engine' ? `Quit ${engineName} and delete` : 'Delete' +} + +/** + * Which handler the click goes to: act now, or ask first. Carried as the menu + * item's id because that is the row's only channel to the list, and it keeps + * the decision in one place — the row that shows the warning is the row that + * asks for it. + */ +export function deleteActionName(mode: ModelDeleteMode): 'delete' | 'delete-confirm' { + return mode === 'quits-engine' || mode === 'restarts-engine' ? 'delete-confirm' : 'delete' +} + +/** + * What the confirmation says, once the user has asked for a delete that takes + * the engine with it. It describes what the engine manager is about to do to the + * engine, which is the one thing that is certain at that moment, in words taken + * from `manifests/mtplx.json` and `manifests/lmstudio.json`. It deliberately does + * not say the model is loaded: the same dialog covers "the engine is serving it" + * and "the engine could not be asked", and only the second one is a guess. + */ +export function deleteConfirmCopy( + capabilities: EngineCaps, + engineName: string, + modelName: string +): { message: string; confirmLabel: string } { + if (capabilities.stopsEngineBeforeDelete) { + return { + message: `Deleting ${modelName} stops ${engineName} first and leaves it down: it serves one model per process, so PAIR will not remove a pack it cannot rule out being the one served.`, + confirmLabel: `Quit ${engineName} and delete` + } + } + return { + message: `Deleting ${modelName} requires ${engineName} to be restarted.`, + confirmLabel: 'Delete and restart' + } +} diff --git a/desktop/tests/modular/delete-model-restart.test.ts b/desktop/tests/modular/delete-model-restart.test.ts index 4e8614d96..de0618b61 100644 --- a/desktop/tests/modular/delete-model-restart.test.ts +++ b/desktop/tests/modular/delete-model-restart.test.ts @@ -8,18 +8,24 @@ import { EngineCapabilities } from '@/ui/constants/engine-capabilities' import type { EngineType } from '@/shared/types/engines' /** - * Deleting a model restarts the engine only where the engine cannot - * see the deletion any other way — LM Studio, which answers `/v1/models` from an - * index built at startup and exposes no rescan. Two independent decisions have - * to agree on that, and they live in different languages: + * Deleting a model changes the engine only where the engine cannot see the + * deletion any other way: LM Studio, which answers `/v1/models` from an index + * built at startup and exposes no rescan, and MTPLX, whose `mtplx remove` has no + * in-use guard. Three independent decisions have to agree on what that change + * is, and they live in different languages: * - * - `restart_after` in the engine-manager manifest decides whether the *backend* - * bounces the engine. - * - `EngineCaps.restartsOnModelDelete` decides whether the *UI* warns first. + * - `restart_after` in the engine-manager manifest bounces the engine back up. + * - `stop_before` in the manifest quits it and waits for its port to go quiet + * first, and leaves it down. + * - `EngineCaps.restartsOnModelDelete` / `stopsEngineBeforeDelete` decide whether + * the desktop warns first, and which wording it uses. * * Nothing in the type system ties them together, so a manifest gaining * `restart_after` without the matching capability would silently bounce an - * engine mid-inference with no confirmation. This test is that tie. + * engine mid-inference with no confirmation. This test is that tie. Reading the + * real manifests also holds the pair that `Manifest.Validate` (`registry.go`) + * refuses apart: no engine both quits and restarts, which is what lets one + * engine declare exactly one wording. */ const MANIFEST_DIR = path.resolve(process.cwd(), '../services/nvpair-engine-manager/manifests') @@ -34,6 +40,7 @@ const ENGINE_TYPE_BY_MANIFEST_ID: Record = { interface ManifestAction { restart_after?: boolean + stop_before?: boolean } interface Manifest { @@ -48,7 +55,7 @@ function readManifests(): Manifest[] { .map(name => JSON.parse(fs.readFileSync(path.join(MANIFEST_DIR, name), 'utf8')) as Manifest) } -describe('delete-model restart is scoped to LM Studio', () => { +describe('delete-model engine changes are declared, not inferred', () => { it('only LM Studio declares restart_after, and only on delete_model', () => { const declaring = readManifests().flatMap(m => Object.entries(m.actions ?? {}) @@ -58,12 +65,38 @@ describe('delete-model restart is scoped to LM Studio', () => { expect(declaring).toEqual(['lmstudio.delete_model']) }) - it('Ollama deletes without a restart and therefore without a confirmation', () => { + it('only MTPLX declares stop_before, and only on delete_model', () => { + const declaring = readManifests().flatMap(m => + Object.entries(m.actions ?? {}) + .filter(([, action]) => action.stop_before === true) + .map(([name]) => `${m.engine}.${name}`) + ) + expect(declaring).toEqual(['mtplx.delete_model']) + }) + + it('no action declares both stop_before and restart_after', () => { + // One wording per engine is only sound while no engine both quits and + // restarts: `deleteConfirmCopy` reads exactly these two flags to choose it, + // and `Manifest.Validate` in `services/nvpair-engine-manager/registry.go` + // rejects the pair. Pinned here because the desktop cannot see that check. + for (const manifest of readManifests()) { + for (const [name, action] of Object.entries(manifest.actions ?? {})) { + expect( + action.restart_after === true && action.stop_before === true, + `${manifest.engine}.${name} declares both stop_before and restart_after` + ).toBe(false) + } + } + }) + + it('Ollama deletes with neither flag and therefore without a confirmation', () => { const ollama = readManifests().find(m => m.engine === 'ollama') expect(ollama?.actions?.delete_model?.restart_after).toBeUndefined() - // `?? false` in ModelManager.tsx turns "absent" into "no confirmation", - // so absent is the assertion that matters, not `false`. + expect(ollama?.actions?.delete_model?.stop_before).toBeUndefined() + // `modelDeleteMode` only asks first when one of the two is set, so absent + // is the assertion that matters, not `false`. expect(EngineCapabilities.ollama.restartsOnModelDelete).toBeFalsy() + expect(EngineCapabilities.ollama.stopsEngineBeforeDelete).toBeFalsy() expect(EngineCapabilities.ollama.hasDeleteModel).toBe(true) }) @@ -71,7 +104,9 @@ describe('delete-model restart is scoped to LM Studio', () => { const llamacpp = readManifests().find(m => m.engine === 'llamacpp') expect(llamacpp?.actions?.delete_model).toBeDefined() expect(llamacpp?.actions?.delete_model?.restart_after).toBeUndefined() + expect(llamacpp?.actions?.delete_model?.stop_before).toBeUndefined() expect(EngineCapabilities['llama-cpp'].restartsOnModelDelete).toBeFalsy() + expect(EngineCapabilities['llama-cpp'].stopsEngineBeforeDelete).toBeFalsy() expect(EngineCapabilities['llama-cpp'].hasDeleteModel).toBe(true) }) @@ -87,9 +122,31 @@ describe('delete-model restart is scoped to LM Studio', () => { } }) - it('LM Studio still bounces — the whole point of the ticket', () => { + it('every engine that quits on delete also warns the user first', () => { + for (const manifest of readManifests()) { + const engineType = ENGINE_TYPE_BY_MANIFEST_ID[manifest.engine] + if (!engineType) continue + const quits = manifest.actions?.delete_model?.stop_before === true + expect( + EngineCapabilities[engineType].stopsEngineBeforeDelete ?? false, + `${manifest.engine}: manifest stop_before=${quits} but EngineCapabilities['${engineType}'].stopsEngineBeforeDelete disagrees` + ).toBe(quits) + } + }) + + it('keeps LM Studio bouncing and MTPLX quitting, and only MTPLX quitting', () => { const lmstudio = readManifests().find(m => m.engine === 'lmstudio') expect(lmstudio?.actions?.delete_model?.restart_after).toBe(true) expect(EngineCapabilities['lm-studio'].restartsOnModelDelete).toBe(true) + + const mtplx = readManifests().find(m => m.engine === 'mtplx') + expect(mtplx?.actions?.delete_model?.stop_before).toBe(true) + expect(mtplx?.actions?.delete_model?.restart_after).toBeUndefined() + expect(EngineCapabilities.mtplx.stopsEngineBeforeDelete).toBe(true) + // MTPLX does not close the door the way vLLM closes it, and + // `modelDeleteMode` tests the block first: a stale + // `deleteBlockedWhileLoaded` here would disable Delete on exactly the pack + // whose copy has to say the engine is quitting. + expect(EngineCapabilities.mtplx.deleteBlockedWhileLoaded).toBeUndefined() }) }) diff --git a/desktop/tests/modular/engine-identity.test.ts b/desktop/tests/modular/engine-identity.test.ts index 5179fb007..7d43f92b3 100644 --- a/desktop/tests/modular/engine-identity.test.ts +++ b/desktop/tests/modular/engine-identity.test.ts @@ -67,12 +67,19 @@ describe('engine identity', () => { // MTPLX serves one pack per process, the way vLLM serves one model: Eject // stops the engine and Load starts it again on the chosen pack. Its manifest // declares only darwin/arm64 and declares no installer, so PAIR drives an - // engine the user installed and never offers to install one. + // engine the user installed and never offers to install one. Where it + // differs from vLLM is the delete: vLLM refuses one on the model it serves, + // so there is nothing to offer (`deleteBlockedWhileLoaded`), while MTPLX's + // `stop_before` performs it after quitting the engine — so its row warns + // instead of disabling, which is `stopsEngineBeforeDelete`. The two are + // separate answers, not spellings of one: see + // `tests/modular/delete-model-restart.test.ts`, which ties both back to the + // manifests. expect(EngineCapabilities.mtplx).toMatchObject({ hasEject: true, hasModelSearchOnlyWhenRunning: false, hasDeleteModel: true, - deleteBlockedWhileLoaded: true, + stopsEngineBeforeDelete: true, loadRestartsEngine: true, hasInstall: [], hasEnginePort: true, diff --git a/desktop/tests/modular/engine-install-button.test.ts b/desktop/tests/modular/engine-install-button.test.ts index 3ab8128d8..b88facb0a 100644 --- a/desktop/tests/modular/engine-install-button.test.ts +++ b/desktop/tests/modular/engine-install-button.test.ts @@ -32,6 +32,7 @@ function buttonMarkup( proxyPort: null, models: [], modelsKnown: false, + residencyKnown: false, installUrl: VLLM_INSTALL_URL, ...facts } diff --git a/desktop/tests/modular/engine-model-selection-action.test.ts b/desktop/tests/modular/engine-model-selection-action.test.ts index b572bf719..38a99290c 100644 --- a/desktop/tests/modular/engine-model-selection-action.test.ts +++ b/desktop/tests/modular/engine-model-selection-action.test.ts @@ -256,7 +256,16 @@ function cachedModel(name: string, downloaded = true): ModelItem { function reportModels(models: ModelItem[], engineType: EngineType = 'vllm') { useEngineModelsStore.setState({ models: new Map([ - [`${nodeId}:${engineType}`, { engineType, nodeId, models, inventoryKnown: true }] + [ + `${nodeId}:${engineType}`, + { + engineType, + nodeId, + models, + inventoryKnown: true, + residencyKnown: true + } + ] ]) }) } diff --git a/desktop/tests/modular/model-delete-affordance.test.ts b/desktop/tests/modular/model-delete-affordance.test.ts new file mode 100644 index 000000000..157d2dbd0 --- /dev/null +++ b/desktop/tests/modular/model-delete-affordance.test.ts @@ -0,0 +1,323 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// @vitest-environment jsdom + +import { act, createElement, type ComponentProps, type ReactNode } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { BannerProps, ButtonProps, DropdownProps } from '@nvidia/foundations-react-core' +import { EngineDisplayNames } from '@/shared/constants/engines' +import type { EngineProcessStatus, EngineType, ModelItemStatus } from '@/shared/types/engines' +import type { BackendInfo } from '@/ui/types/engine-info' +import type { IEngineApi } from '@/ui/api/engine-api' +import type { ConfirmModal } from '@/ui/components/ConfirmModal' +import type { ModelHubModal } from '@/ui/components/ModelHub/ModelHubModal' +import { ModelManager } from '@/ui/components/ModelManager/ModelManager' +import { usePendingActionsStore } from '@/ui/stores/pending-actions.store' + +/** + * What a model row offers for Delete, and what the confirmation says when it has + * to ask. `modelDeleteMode` decides that from three inputs — the engine's declared + * capabilities, whether the engine answered what it holds in memory, and whether + * it answered *this* model — so these cases are the whole matrix, held together by + * `tests/modular/delete-model-restart.test.ts` for the manifest half. + * + * The library dropdown is replaced with plain buttons so the menu items are + * readable, and `ConfirmModal` with a passthrough that prints its own message and + * label: the wording is a product decision and is asserted exactly, not by + * `toContain`. + */ +vi.mock('@nvidia/foundations-react-core', () => { + const container = ({ children }: { children?: ReactNode }) => + createElement('div', null, children) + return { + Flex: container, + Stack: container, + Text: container, + Banner: ({ children, role }: BannerProps) => createElement('div', { role }, children), + Divider: () => createElement('hr'), + Button: ({ children, disabled, onClick }: ButtonProps) => + createElement('button', { disabled, onClick }, children), + Dropdown: ({ items, children, disabled, 'aria-label': label }: DropdownProps) => + createElement( + 'div', + null, + createElement('button', { disabled, 'aria-label': label }, children), + items.map((item, index) => { + if (typeof item === 'string' || !('onSelect' in item)) return null + return createElement( + 'button', + { + key: index, + disabled: disabled || item.disabled, + onClick: () => item.onSelect?.(new Event('select')) + }, + item.children + ) + }) + ) + } +}) + +vi.mock('@/ui/components/ConfirmModal', () => ({ + ConfirmModal: ({ + open, + message, + confirmLabel, + onOpenChange, + onConfirm + }: ComponentProps) => + open + ? createElement( + 'div', + { role: 'dialog', 'aria-label': 'Delete confirmation' }, + createElement('p', null, message), + createElement( + 'button', + { + onClick: () => { + onOpenChange(false) + onConfirm() + } + }, + confirmLabel + ) + ) + : null +})) + +vi.mock('@/ui/components/ModelHub/ModelHubModal', () => ({ + ModelHubModal: ({ engine }: ComponentProps) => + engine ? createElement('div', { role: 'dialog', 'aria-label': 'Model catalog' }) : null +})) + +const commands = { + loadModel: vi.fn(), + unloadModel: vi.fn(), + deleteModel: vi.fn(), + pullModel: vi.fn(), + setModelExpiry: vi.fn() +} + +const NODE_ID = 'test-node' +/** + * One pack name for every case. It has no `/`, so MTPLX renders it as written and + * the confirmation copy can be asserted exactly; LM Studio's formatter turns its + * dash into a space, which is what its own assertion spells out. + */ +const PACK = 'mtplx-lite' + +let host: HTMLDivElement +let root: Root + +beforeEach(() => { + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { + configurable: true, + value: true + }) + Object.defineProperty(window, 'pairApi', { configurable: true, value: { engines: commands } }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) +}) + +afterEach(async () => { + await act(() => root.unmount()) + host.remove() + vi.clearAllMocks() + usePendingActionsStore.setState({ pending: new Map() }) + Reflect.deleteProperty(window, 'pairApi') + Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT') +}) + +/** + * One row, one engine. `residencyKnown` is the third input and the one the rest of + * the suite never varies: false means no source answered what the engine holds, + * which is not the same answer as "holds nothing". + */ +async function renderRow(options: { + type: EngineType + residencyKnown: boolean + status: ModelItemStatus + processStatus?: EngineProcessStatus +}) { + const backend: BackendInfo = { + type: options.type, + displayName: EngineDisplayNames[options.type], + source: 'installed', + processStatus: options.processStatus ?? 'running', + port: 8101, + proxyPort: 8100, + modelsKnown: true, + residencyKnown: options.residencyKnown, + models: [ + { + name: PACK, + size: 1024, + downloaded: true, + status: options.status, + parameterSize: '1B', + quantization: '', + family: '', + digest: '', + sizeVram: null, + expiresAt: null, + expiry: '10m', + capabilities: [] + } + ] + } + await act(() => root.render(createElement(ModelManager, { backend, nodeId: NODE_ID }))) +} + +/** Menu items and dialogs both render as buttons; keep the two apart. */ +function rowButtons(): HTMLButtonElement[] { + return Array.from(host.querySelectorAll('button')).filter( + button => !button.closest('[role="dialog"]') + ) +} + +function rowButton(label: string): HTMLButtonElement { + const found = rowButtons().find(button => button.textContent === label) + if (!found) throw new Error(`Missing row button: ${label}`) + return found +} + +function dialog(): Element | null { + return host.querySelector('[aria-label="Delete confirmation"]') +} + +function dialogConfirm(): HTMLButtonElement { + const button = dialog()?.querySelector('button') + if (!button) throw new Error('Missing confirmation button') + return button +} + +async function clickRow(label: string) { + await act(() => rowButton(label).click()) +} + +const QUIT_LABEL = 'Quit MTPLX and delete' +const QUIT_MESSAGE = + `Deleting ${PACK} stops MTPLX first and leaves it down: it serves one model ` + + 'per process, so PAIR will not remove a pack it cannot rule out being the one served.' + +describe('MTPLX delete affordance', () => { + it('offers a one-click Delete for a pack the running engine says it is not serving', async () => { + await renderRow({ type: 'mtplx', residencyKnown: true, status: 'idle' }) + + expect(rowButton('Delete').disabled).toBe(false) + await clickRow('Delete') + + expect(commands.deleteModel).toHaveBeenCalledExactlyOnceWith('mtplx', NODE_ID, PACK) + expect(dialog()).toBeNull() + }) + + it('names the quit on the row whose pack the engine is serving', async () => { + await renderRow({ type: 'mtplx', residencyKnown: true, status: 'loaded' }) + + // Not disabled: unlike vLLM, MTPLX does remove a served pack, and the + // label says so in the same breath as the warning. + expect(rowButton(QUIT_LABEL).disabled).toBe(false) + + await clickRow(QUIT_LABEL) + expect(commands.deleteModel).not.toHaveBeenCalled() + + await act(() => dialogConfirm().click()) + expect(commands.deleteModel).toHaveBeenCalledExactlyOnceWith('mtplx', NODE_ID, PACK) + expect(dialog()).toBeNull() + }) + + it('refuses a one-click Delete on a row whose residency was never reported', async () => { + await renderRow({ type: 'mtplx', residencyKnown: false, status: 'idle' }) + + expect(() => rowButton('Delete')).toThrow('Missing row button: Delete') + await clickRow(QUIT_LABEL) + expect(commands.deleteModel).not.toHaveBeenCalled() + expect(dialog()).not.toBeNull() + }) + + it('gives the unreadable residency the same affordance as the readable one', async () => { + // The two states the service treats alike — `residencyMappedHere` and + // `residencyUnknown` both stop the engine — must not split in the UI. + await renderRow({ type: 'mtplx', residencyKnown: false, status: 'loaded' }) + expect(dialog()).toBeNull() + const cannotTell = rowButtons().map(button => button.textContent) + + await renderRow({ type: 'mtplx', residencyKnown: true, status: 'loaded' }) + expect(rowButtons().map(button => button.textContent)).toEqual(cannotTell) + }) + + it('says what the delete does to the engine without claiming the pack is loaded', async () => { + await renderRow({ type: 'mtplx', residencyKnown: false, status: 'idle' }) + await clickRow(QUIT_LABEL) + + expect(dialog()?.textContent).toContain(QUIT_MESSAGE) + expect(dialogConfirm().textContent).toBe(QUIT_LABEL) + // Nothing here asserts the pack is in memory, because on this row it may + // not be, and it does not offer an eject or a restart that does not exist. + expect(dialog()?.textContent).not.toMatch(/loaded|restart|eject/i) + }) +}) + +describe('engines that do not quit to delete', () => { + it('keeps vLLM Delete disabled on the model it serves, without quit wording', async () => { + await renderRow({ type: 'vllm', residencyKnown: true, status: 'loaded' }) + + expect(rowButton('Delete').disabled).toBe(true) + await clickRow('Delete') + expect(commands.deleteModel).not.toHaveBeenCalled() + expect(dialog()).toBeNull() + }) + + it('keeps LM Studio on the restart wording, which is its own kind of engine change', async () => { + await renderRow({ type: 'lm-studio', residencyKnown: false, status: 'idle' }) + + // Asks first, but its delete restarts rather than quits, so it keeps the + // plain label and the restart sentence. The name is what the list shows, + // which for LM Studio turns the pack's dash into a space. + await clickRow('Delete') + expect(dialog()?.textContent).toContain( + 'Deleting mtplx lite requires LM Studio to be restarted.' + ) + expect(dialogConfirm().textContent).toBe('Delete and restart') + + await act(() => dialogConfirm().click()) + expect(commands.deleteModel).toHaveBeenCalledExactlyOnceWith('lm-studio', NODE_ID, PACK) + }) + + it.each(['ollama', 'llama-cpp', 'vllm'])( + 'lets %s delete straight away even when residency cannot be read', + async type => { + await renderRow({ type, residencyKnown: false, status: 'idle' }) + + await clickRow('Delete') + expect(commands.deleteModel).toHaveBeenCalledExactlyOnceWith(type, NODE_ID, PACK) + expect(dialog()).toBeNull() + } + ) +}) + +describe('a delete in flight', () => { + it('locks the MTPLX row that is already deleting', async () => { + usePendingActionsStore.setState({ + pending: new Map([ + [ + `${NODE_ID}:mtplx:model:${PACK}`, + { + nodeId: NODE_ID, + engineType: 'mtplx', + action: 'deleteModel', + model: PACK, + expiresAt: Date.now() + 60_000 + } + ] + ]) + }) + await renderRow({ type: 'mtplx', residencyKnown: true, status: 'loaded' }) + + expect(rowButton(QUIT_LABEL).disabled).toBe(true) + await clickRow(QUIT_LABEL) + expect(commands.deleteModel).not.toHaveBeenCalled() + }) +}) diff --git a/desktop/tests/modular/model-manager-transitions.test.ts b/desktop/tests/modular/model-manager-transitions.test.ts index 037fa89b3..8130af540 100644 --- a/desktop/tests/modular/model-manager-transitions.test.ts +++ b/desktop/tests/modular/model-manager-transitions.test.ts @@ -140,6 +140,7 @@ function backend( port: 8001, proxyPort: 8000, modelsKnown: true, + residencyKnown: true, models: [ { name: 'org/cached-model', diff --git a/desktop/tests/modular/model-manager-visibility.test.ts b/desktop/tests/modular/model-manager-visibility.test.ts index 7e4d5e525..517019ec2 100644 --- a/desktop/tests/modular/model-manager-visibility.test.ts +++ b/desktop/tests/modular/model-manager-visibility.test.ts @@ -41,6 +41,7 @@ function engineInfo(type: EngineType, overrides: Partial = {}): Bac proxyPort: 8000, models: [], modelsKnown: true, + residencyKnown: true, ...overrides } } diff --git a/desktop/tests/modular/mtplx-card-actions.test.ts b/desktop/tests/modular/mtplx-card-actions.test.ts index 8739d2a67..b17aaec96 100644 --- a/desktop/tests/modular/mtplx-card-actions.test.ts +++ b/desktop/tests/modular/mtplx-card-actions.test.ts @@ -39,6 +39,7 @@ function cardFor( proxyPort: 8100, models: [], modelsKnown: EnginesListingModelsWhenStopped.includes(engineType), + residencyKnown: false, docsUrl: EngineDefaultLinks[engineType].docsUrl, installUrl: EngineDefaultLinks[engineType].installUrl, ...facts diff --git a/desktop/tests/modular/mtplx-served-model-list.test.ts b/desktop/tests/modular/mtplx-served-model-list.test.ts index 683d94060..f50947664 100644 --- a/desktop/tests/modular/mtplx-served-model-list.test.ts +++ b/desktop/tests/modular/mtplx-served-model-list.test.ts @@ -25,9 +25,11 @@ let nextNode = 0 * A Mac that already runs MTPLX before PAIR starts: the engine-manager reports * MTPLX online and the self node is known. `discoveryResident` is what the node's * discovery record says MTPLX has in memory before any model sweep is read; each - * case then decides what `engine:models` answers. + * case then decides what `engine:models` answers. Pass `null` for a node that + * never reported residency at all — no `loadedByEngine` key, which is a third + * answer rather than an empty one. */ -function startMTPLX(discoveryResident: string[]) { +function startMTPLX(discoveryResident: string[] | null) { const state = getModularBridgeState() const supervisor = getModularSupervisor() const nodeId = `mtplx-served-model-${++nextNode}` @@ -44,9 +46,11 @@ function startMTPLX(discoveryResident: string[]) { name: `${nodeId}-host`, ipAddress: '192.0.2.10', port: 14318, - models: discoveryResident, - modelsByEngine: { mtplx: discoveryResident }, - loadedByEngine: { mtplx: discoveryResident } + models: discoveryResident ?? [], + modelsByEngine: { mtplx: discoveryResident ?? [] }, + ...(discoveryResident === null + ? {} + : { loadedByEngine: { mtplx: discoveryResident } }) } ] } @@ -170,4 +174,66 @@ describe('MTPLX model list', () => { await vi.waitFor(() => expect(machine.call).toHaveBeenCalledOnce()) expect(machine.rows()?.models.map(model => model.name)).toEqual([cachedPack, servedModel]) }) + + it('reports residency as unknown, not as empty, when no source names what MTPLX serves', async () => { + // MTPLX is up and its cache was read, but nothing answered what it holds in + // memory: no `loadedByEngine` key in the discovery record and none in the + // `engine:models` reply. That is the third answer, and rendering it as + // "holds nothing" would tell the row a one-click Delete is safe. + // + // These pack names appear in no other case here. The bridge caches one + // model list per engine for the whole file, so names the earlier cases + // already used would let this assertion read that stale list and pass + // without ever reading the reply. + const packOnDisk = 'unreported/mtplx-lite' + const packServedFromPath = 'unreported/mtplx-flash-next-optimized-speed' + const machine = startMTPLX(null) + machine.call.mockResolvedValue({ + downloadedByEngine: { mtplx: [packOnDisk, packServedFromPath] } + }) + + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + + await vi.waitFor(() => + expect(machine.rows()?.models.map(model => model.name)).toEqual([ + packOnDisk, + packServedFromPath + ]) + ) + expect(machine.rows()?.inventoryKnown).toBe(true) + expect(machine.rows()?.residencyKnown).toBe(false) + expect( + machine.rows()?.models.map(model => ({ name: model.name, status: model.status })) + ).toEqual([ + { name: packOnDisk, status: 'idle' }, + { name: packServedFromPath, status: 'idle' } + ]) + }) + + it('reports residency as known when MTPLX answers that it serves nothing', async () => { + // Same reply plus one key. An empty `loadedByEngine` for a running MTPLX + // is an answer — the server was queried and holds no pack — so the rows may + // offer the plain Delete that the case above has to withhold. + const packOnDisk = 'reported/mtplx-lite' + const packServedFromPath = 'reported/mtplx-flash-next-optimized-speed' + const machine = startMTPLX(null) + machine.call.mockResolvedValue({ + downloadedByEngine: { mtplx: [packOnDisk, packServedFromPath] }, + loadedByEngine: { mtplx: [] } + }) + + machine.supervisor.refreshManagedEngineModels({ engine: 'mtplx', running: true }) + + // Wait on the list, not on the call: names and `residencyKnown` arrive in + // the same push, and the bridge still holds the previous case's list until + // this read lands. + await vi.waitFor(() => + expect(machine.rows()?.models.map(model => model.name)).toEqual([ + packOnDisk, + packServedFromPath + ]) + ) + expect(machine.rows()?.residencyKnown).toBe(true) + expect(machine.rows()?.models.map(model => model.status)).toEqual(['idle', 'idle']) + }) }) diff --git a/desktop/tests/modular/pending-actions-delete.test.ts b/desktop/tests/modular/pending-actions-delete.test.ts index 48e97c7f9..7f0e94906 100644 --- a/desktop/tests/modular/pending-actions-delete.test.ts +++ b/desktop/tests/modular/pending-actions-delete.test.ts @@ -173,6 +173,29 @@ describe('pending-actions store: model actions', () => { ).toBeUndefined() }) + it('keeps an MTPLX delete pending past the default net, since it awaits a quit', () => { + usePendingActionsStore.getState().begin({ + command: 'deleteModel', + engineType: 'mtplx', + nodeId: 'node-1', + model: 'mtplx/mtplx-lite' + }) + + // MTPLX quits and waits out its stop grace plus the 15s it gives the port + // to stop answering before removing anything, so the reply can arrive well + // after the 60s default and even after the main process's 120s RPC + // timeout. Graded by `stopsEngineBeforeDelete`, not by the engine's name. + vi.advanceTimersByTime(130_000) + expect( + usePendingActionsStore.getState().getModelPending('node-1', 'mtplx', 'mtplx/mtplx-lite') + ).toBe('deleteModel') + + vi.advanceTimersByTime(60_000) + expect( + usePendingActionsStore.getState().getModelPending('node-1', 'mtplx', 'mtplx/mtplx-lite') + ).toBeUndefined() + }) + it('leaves the default net in place for an Ollama delete, which never bounces', () => { usePendingActionsStore.getState().begin({ command: 'deleteModel', @@ -211,7 +234,8 @@ describe('pending-actions store: model actions', () => { nodeId: 'local-node', engineType: 'ollama', models: [loadedModel('llama3.2')], - inventoryKnown: true + inventoryKnown: true, + residencyKnown: true } }) errorsCb?.([ @@ -312,7 +336,8 @@ describe('a vLLM Load is one pending action for the row and the engine', () => { nodeId: 'local-node', engineType: 'vllm', models: [loadedModel('Qwen/Qwen3-8B')], - inventoryKnown: true + inventoryKnown: true, + residencyKnown: true } }) From ea38c64faefb9391d89da3b9c374c357a5b7110d Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Tue, 24 Nov 2026 14:22:06 -0700 Subject: [PATCH 10/10] fix(desktop): let a refused load or eject name the row it failed on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed model load or eject reported nothing at all. `sendProcess` was called without `observeResponse`, so the request went out through `JsonRpcSubprocess.send()`, which registers no pending entry — the engine-manager's error reply arrived with nowhere to go. `sendWithResponse` observes it and imposes no timeout, so a load that legitimately takes minutes is still not cut off at 10 s. The fallback report was also unattributable: `failAction` was passed no node, engine, or model, and `pending-actions.store` skips an error that carries no `nodeId` and no real `engineType`. With no superseding model push for these two commands — an engine that refuses keeps serving the model — that left the row spinning for the whole 60 s safety net under a message saying the load had already failed. `refuseRemote` had the attribution half of the same problem: with no context, `reportError` stamped this machine's id on a refusal to uninstall or update a peer, so the entry it might have released was the wrong one, and with no id at all it stamped `''` and released nothing. Adds `tests/modular/model-action-failure.test.ts`, which drives the real emit path — a fake broker child, the real supervisor, the real push bus — rather than handing the store a hand-built error. All four of its cases fail against the code as it was: the three model cases because nothing is reported, the remote case because the error is reported against this machine. Signed-off-by: Steven Beverly --- .../electron/service-bridge/empty-handlers.ts | 54 ++- .../tests/modular/engine-command-load.test.ts | 33 +- .../modular/model-action-failure.test.ts | 321 ++++++++++++++++++ 3 files changed, 392 insertions(+), 16 deletions(-) create mode 100644 desktop/tests/modular/model-action-failure.test.ts diff --git a/desktop/src/electron/service-bridge/empty-handlers.ts b/desktop/src/electron/service-bridge/empty-handlers.ts index 6ec2b2b68..ba3527724 100644 --- a/desktop/src/electron/service-bridge/empty-handlers.ts +++ b/desktop/src/electron/service-bridge/empty-handlers.ts @@ -225,13 +225,16 @@ function stopLocalEngine(engine: string, engineType: EngineType): void { } /** - * Dispatch a UI engine command to the local `nvpair-engine-manager`. Lifecycle and - * model operations are **fire-and-forget**: the engine-manager runs each in its - * own goroutine and reports progress (`engine:install-progress`), completion - * (`engine:state-changed`), and failures (`errors:report`) through push events. - * We must not await these RPCs — a download or model pull runs for minutes and - * would trip the request timeout, fabricating a failure while the operation is - * actually succeeding. + * Dispatch a UI engine command to the local `nvpair-engine-manager`. Nothing here + * awaits a reply on a short deadline: a download or model pull runs for minutes and + * a fabricated timeout would report a failure while the operation is succeeding. + * Those long operations announce themselves through push events + * (`engine:install-progress`, `engine:state-changed`) and are sent without + * observing the reply. A model load or eject is not one of them — the manager + * reports a refused or failed load/eject only in that request's own error reply, + * and leaves the model loaded when it fails, so no push clears the row either. + * Those two therefore observe their reply, which costs no timeout; see + * `ModularSupervisor.sendProcess`. */ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): void { const supervisor = getModularSupervisor() @@ -389,6 +392,12 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): true ) } else { + // LM Studio runs `lms load` and llama.cpp answers `POST + // /models/load`; a failed load comes back as this request's error + // reply and nothing else reports it — the model never enters + // memory, so no model list push arrives either. Observe the reply + // (without a timeout, see sendProcess) and name the row the + // failure belongs to. supervisor.sendProcess( 'broker', 'engine:action', @@ -397,7 +406,13 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): action: 'load_model', params: { model: payload.model } }, - failAction('load model') + failAction('load model', { + nodeId: payload.nodeId, + engineType: payload.engineType, + operation: 'load', + modelName: payload.model + }), + true ) } } @@ -408,6 +423,14 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): payload.engineType === 'ollama' ? { model: payload.model, keep_alive: 0 } : { model: payload.model } + // Eject changes the engine, not just the row: MTPLX and vLLM declare + // it a `stop_engine` action and the rest run a CLI or HTTP call. Each + // way it fails reports itself only in this request's error reply — a + // refused eject (the engine says it serves another model), a stop that + // cannot touch a server PAIR did not start, `lms unload` exiting + // non-zero — and the engine keeps serving the model afterwards, so no + // push clears the row either. Observe the reply, and pass the node, + // engine and model the pending-actions store needs to attribute it. supervisor.sendProcess( 'broker', 'engine:action', @@ -416,7 +439,12 @@ function routeEngineManagerCommand(payload: WsInvokeRequest<'engine:command'>): action: 'unload_model', params: unloadParams }, - failAction('unload model') + failAction('unload model', { + nodeId: payload.nodeId, + engineType: payload.engineType, + modelName: payload.model + }), + true ) } break @@ -455,7 +483,13 @@ function routeRemoteEngineCommand(payload: WsInvokeRequest<'engine:command'>): v const nodeId = payload.nodeId const refuseRemote = (detail: string): void => { - supervisor.reportError(detail, 'warning', `engine-cmd:remote:${payload.command}`) + // Name the peer the command was aimed at. The pending-actions store keys its + // optimistic entry by node and engine, and `reportError` would otherwise + // stamp this machine's id on a command that was never meant for this machine. + supervisor.reportError(detail, 'warning', `engine-cmd:remote:${payload.command}`, { + nodeId, + engineType: payload.engineType + }) } switch (payload.command) { diff --git a/desktop/tests/modular/engine-command-load.test.ts b/desktop/tests/modular/engine-command-load.test.ts index be020de45..f09553820 100644 --- a/desktop/tests/modular/engine-command-load.test.ts +++ b/desktop/tests/modular/engine-command-load.test.ts @@ -169,7 +169,10 @@ describe('local model load command', () => { }) }) - it('leaves the LM Studio load path unobserved', async () => { + // A failed `lms load` is reported nowhere else: the model never enters memory, + // so no model-list push arrives to release the row either. The reply has to be + // observed and the failure has to name the row. + it('observes and attributes an LM Studio load rejection to the pending model row', async () => { await handleServiceBridgeInvoke('engine:command', { command: 'loadModel', engineType: 'lm-studio', @@ -178,8 +181,9 @@ describe('local model load command', () => { }) expect(mocks.supervisor.sendProcess).toHaveBeenCalledOnce() - expect(mocks.supervisor.sendProcess.mock.calls[0]).toHaveLength(4) - expect(mocks.supervisor.sendProcess).toHaveBeenCalledWith( + const [name, method, params, onFailure, observeResponse] = + mocks.supervisor.sendProcess.mock.calls[0] + expect([name, method, params, observeResponse]).toEqual([ 'broker', 'engine:action', { @@ -187,7 +191,21 @@ describe('local model load command', () => { action: 'load_model', params: { model: 'publisher/demo' } }, - expect.any(Function) + true + ]) + + assert.isDefined(onFailure) + onFailure('load failed: no compatible runtime', true) + expect(mocks.supervisor.reportError).toHaveBeenCalledWith( + 'Failed to load model on lmstudio: load failed: no compatible runtime', + 'error', + 'engine-cmd:load model:lmstudio', + { + nodeId: 'local-node', + engineType: 'lm-studio', + operation: 'load', + modelName: 'publisher/demo' + } ) }) @@ -205,6 +223,7 @@ describe('local model load command', () => { model: 'ggml-org/gemma-3-1b-it-GGUF:Q4_K_M' }) + // Both manifest actions answer in their own reply, so both are observed. expect(mocks.supervisor.sendProcess).toHaveBeenNthCalledWith( 1, 'broker', @@ -214,7 +233,8 @@ describe('local model load command', () => { action: 'load_model', params: { model: 'ggml-org/gemma-3-1b-it-GGUF:Q4_K_M' } }, - expect.any(Function) + expect.any(Function), + true ) expect(mocks.supervisor.sendProcess).toHaveBeenNthCalledWith( 2, @@ -225,7 +245,8 @@ describe('local model load command', () => { action: 'unload_model', params: { model: 'ggml-org/gemma-3-1b-it-GGUF:Q4_K_M' } }, - expect.any(Function) + expect.any(Function), + true ) }) }) diff --git a/desktop/tests/modular/model-action-failure.test.ts b/desktop/tests/modular/model-action-failure.test.ts new file mode 100644 index 000000000..f4b21019e --- /dev/null +++ b/desktop/tests/modular/model-action-failure.test.ts @@ -0,0 +1,321 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * A refused model eject, a refused model load, and a refused remote command each + * have to release the control they were clicked from. + * + * `pending-actions.store` attributes a reported error to a row only when that + * error carries a `nodeId` *and* a real `engineType`; it skips anything else. A + * model load or eject has no other superseding push either: an engine that refuses + * still serves the model afterwards, so the model list never changes, and eject + * registers no lifecycle entry. An unattributed report therefore leaves the row + * disabled for the whole safety-net window, under a message that already says + * nothing happened. + * + * These tests drive the real emit path instead of handing the store the payload it + * is supposed to receive. A real `JsonRpcSubprocess` stands in for the broker, the + * real supervisor parses the error snapshot it answers with, and the real + * `emitBridgePush` puts that snapshot on the push bus the preload bridge carries to + * the renderer. That distinction matters: a hand-written + * `{ nodeId: 'node-1', engineType: 'lm-studio' }` fed straight to the store passes + * with production dropping both fields, which is how the eject path stayed stuck + * while its own unit test stayed green. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EngineCommandPayload } from '@/shared/types/engine-api' +import type { ServiceError } from '@/shared/types/errors' + +vi.mock('electron', () => ({ + // Both halves stay real code paths: `app` for the supervisor, `BrowserWindow` + // for the broadcaster. With no window open, `emitBridgePush` only ever reaches + // the in-process push bus, which is what the subscription below listens to. + app: { + isPackaged: false, + getAppPath: () => process.cwd() + }, + BrowserWindow: { getAllWindows: () => [] } +})) + +vi.mock('@/shared/utils/log', () => ({ + createStructuredLogger: () => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + verbose: vi.fn() + }) +})) + +vi.mock('@/electron/config/ui-config', () => ({ + isFirstRun: () => false +})) + +import { JsonRpcSubprocess } from '@/electron/service-bridge/json-rpc-subprocess' +import { getModularSupervisor } from '@/electron/service-bridge/modular-supervisor' +import { getModularBridgeState } from '@/electron/service-bridge/modular-state' +import { handleServiceBridgeInvoke } from '@/electron/service-bridge/empty-handlers' +import { subscribePush } from '@/electron/service-bridge/push-bus' +import { usePendingActionsStore } from '@/ui/stores/pending-actions.store' + +/** + * A broker that refuses every `engine:action`, the way a refused eject or load + * answers in the service, and replays each reported error as a one-error + * `errors:update` snapshot — the shape the broker relay plus `nvpair-errors` + * broadcast back after an `errors:report`. + * + * The 10 ms delay matters: the reply cannot be folded into the write that asked + * for it, so only an actually observed response can release the row. Exiting on + * `shutdown` keeps the teardown's `stop()` from waiting out its grace. + */ +const FAKE_BROKER = ` +const readline = require('readline').createInterface({ input: process.stdin }) +const write = message => process.stdout.write(JSON.stringify(message) + '\\n') +readline.on('line', line => { + const message = JSON.parse(line) + if (message.method === 'shutdown') process.exit(0) + if (message.method === 'engine:action' && message.id !== undefined) { + setTimeout(() => { + write({ + jsonrpc: '2.0', + id: message.id, + error: { code: -32000, message: 'refused by the engine' } + }) + }, 10) + } + if (message.method === 'errors:report' && message.params) { + write({ jsonrpc: '2.0', method: 'errors:update', params: [message.params] }) + } +}) +` + +/** The supervisor state this has to stage: the broker child and its readiness. */ +interface SupervisorHarness { + processes: Map + brokerReady: boolean + attachChildHandlers: (child: JsonRpcSubprocess) => void +} + +/** The bridge state this has to stage: which node this machine is, and what it has already reported. */ +interface BridgeStateHarness { + selfId: string | null + errors: ServiceError[] +} + +// Neither half of the path can be staged through the public surface. The broker +// child lives in the supervisor's process map and its notification handlers are +// attached privately; `reportError` only takes the `errors:report` relay while the +// broker reads ready; and the node id it defaults to comes from a `selfId` that +// `setSelfId` cannot unset once set. Same reach-in as +// `modular-supervisor-readiness.test.ts`. +const supervisor = getModularSupervisor() as unknown as SupervisorHarness +const bridgeState = getModularBridgeState() as unknown as BridgeStateHarness + +const LOCAL_NODE = 'local-node' +const PEER_NODE = 'peer-node' +const MTPLX_MODEL = 'mtplx/mtplx-lite' +const LMSTUDIO_MODEL = 'publisher/demo' + +/** Every `errors:update` payload handed on since the last reset, oldest first. */ +let pushedSnapshots: ServiceError[][] = [] +let unsubscribeCapture: (() => void) | null = null +let broker: JsonRpcSubprocess | null = null + +function errorReport(): string { + const seen = pushedSnapshots.flat() + return seen.length === 0 ? 'nothing was reported' : `reported ${JSON.stringify(seen)}` +} + +/** + * Wait for a control to stop spinning, and say on failure whether nothing was + * reported at all or the report simply carried no node and engine to attribute it + * to. Those are two different defects — a reply nobody observed, and an observed + * reply nobody could place — and a test going red should not make you guess which + * one came back. + * + * Real timers, deliberately. The round trip needs real async stdio, and at this + * scale the 60 s safety net cannot expire, so the only way a row can be released + * inside the wait is the error path under test. + */ +async function expectCleared(label: string, readPending: () => string | undefined): Promise { + await vi.waitFor( + () => { + expect(readPending(), `${label} still spinning; ${errorReport()}`).toBeUndefined() + }, + { timeout: 8_000, interval: 20 } + ) +} + +/** + * Seed the optimistic entry the way the renderer's `fireCommand` does — `begin` + * with the payload, then the same payload into `engine:command` — and wait for it + * to clear. Recording it first is part of the test: a row that was never spinning + * proves nothing about a fix meant to stop it spinning. + */ +async function fireUntilCleared( + label: string, + payload: EngineCommandPayload, + readPending: () => string | undefined +): Promise { + usePendingActionsStore.getState().begin(payload) + expect(readPending(), `${label}: the click recorded no pending entry`).toBeDefined() + + await handleServiceBridgeInvoke('engine:command', payload) + await expectCleared(label, readPending) +} + +/** + * The subscription shape `window.pairApi` has in the app, fed from the push bus + * rather than IPC. Everything behind it stays real: parsing the snapshot, deciding + * which keys it releases, and the safety net that was the only way out before. + */ +function makeFakeWindow() { + const noopUnsub = (): void => {} + return { + pairApi: { + engines: { + onStateChanged: () => noopUnsub, + onProgress: () => noopUnsub, + onSettingsChanged: () => noopUnsub + }, + errors: { + onUpdate: (cb: (errors: ServiceError[]) => void) => + subscribePush(event => { + if (event.channel !== 'errors:update') return + cb(event.payload) + }) + } + } + } +} + +beforeEach(() => { + pushedSnapshots = [] + + const child = new JsonRpcSubprocess('broker', process.execPath) + broker = child + supervisor.processes.set('broker', child) + supervisor.attachChildHandlers(child) + supervisor.brokerReady = true + child.start(['-e', FAKE_BROKER]) + + bridgeState.errors = [] + bridgeState.selfId = LOCAL_NODE + + // A second subscriber, used only to describe the failure. The store keeps its + // own subscription through `window.pairApi`, which `cleanup()` releases. + unsubscribeCapture = subscribePush(event => { + if (event.channel === 'errors:update') pushedSnapshots.push(event.payload) + }) + + vi.stubGlobal('window', makeFakeWindow()) + usePendingActionsStore.getState().initialize() +}) + +afterEach(async () => { + usePendingActionsStore.getState().cleanup() + unsubscribeCapture?.() + unsubscribeCapture = null + + const child = broker + broker = null + if (child) { + // Retire the child before stopping it: the exit handler only acts for the + // broker currently in the map, so a test that already finished cannot start + // a broker-crash notification. + supervisor.processes.delete('broker') + supervisor.brokerReady = false + await child.stop(2_000) + } + + vi.unstubAllGlobals() +}) + +describe('a refused model action releases the row it was clicked from', () => { + it('releases an eject whose engine refused to drop the model', async () => { + // MTPLX ejects by quitting the server, and refuses outright when the named + // model is not the one it is serving. Either way the model stays loaded, so + // no model-list push would have released the row. + await fireUntilCleared( + 'mtplx eject of mtplx/mtplx-lite', + { + command: 'unloadModel', + engineType: 'mtplx', + nodeId: LOCAL_NODE, + model: MTPLX_MODEL + }, + () => + usePendingActionsStore.getState().getModelPending(LOCAL_NODE, 'mtplx', MTPLX_MODEL) + ) + }) + + it('releases a load that the engine refused', async () => { + // A failed `lms load` is reported nowhere else: the model never enters + // memory, so there is no inventory change to release the row either. + await fireUntilCleared( + 'lm-studio load of publisher/demo', + { + command: 'loadModel', + engineType: 'lm-studio', + nodeId: LOCAL_NODE, + model: LMSTUDIO_MODEL + }, + () => + usePendingActionsStore + .getState() + .getModelPending(LOCAL_NODE, 'lm-studio', LMSTUDIO_MODEL) + ) + }) + + it('names the node the row is keyed on when this machine has no id of its own', async () => { + // While this machine has no cluster id, `handleEngineCommand` routes the + // command on the local path and `reportError` would fall back to an empty + // nodeId — which the store skips, since an error without a node belongs to + // no row. The nodeId has to come from the payload either way. + bridgeState.selfId = null + + await fireUntilCleared( + 'peer-node eject of mtplx/mtplx-lite', + { + command: 'unloadModel', + engineType: 'mtplx', + nodeId: PEER_NODE, + model: MTPLX_MODEL + }, + () => usePendingActionsStore.getState().getModelPending(PEER_NODE, 'mtplx', MTPLX_MODEL) + ) + }) +}) + +describe('a refused remote command releases the peer control it was aimed at', () => { + it('clears the peer uninstall and leaves the local one alone', async () => { + // Remote uninstall is not supported, and the refusal is the only thing that + // will ever answer this click. A seeded local entry rides along to show the + // report is attributed to the peer the command was aimed at, not to + // whichever node `reportError` would default to. + usePendingActionsStore + .getState() + .begin({ command: 'uninstall', engineType: 'mtplx', nodeId: LOCAL_NODE }) + usePendingActionsStore + .getState() + .begin({ command: 'uninstall', engineType: 'mtplx', nodeId: PEER_NODE }) + expect( + usePendingActionsStore.getState().getLifecyclePending(PEER_NODE, 'mtplx'), + 'the peer uninstall was never recorded' + ).toBe('uninstall') + + await handleServiceBridgeInvoke('engine:command', { + command: 'uninstall', + engineType: 'mtplx', + nodeId: PEER_NODE + }) + + await expectCleared('peer mtplx uninstall', () => + usePendingActionsStore.getState().getLifecyclePending(PEER_NODE, 'mtplx') + ) + expect( + usePendingActionsStore.getState().getLifecyclePending(LOCAL_NODE, 'mtplx'), + `a refusal aimed at ${PEER_NODE} released the local row instead; ${errorReport()}` + ).toBe('uninstall') + }) +})