From 0d4fd7c995a5b28ea9a1b465b87d03a8ba7d4d14 Mon Sep 17 00:00:00 2001 From: Biogenic Ooze Date: Wed, 11 Nov 2026 16:46:16 +0300 Subject: [PATCH 1/4] Support Foundry Local 2.4 with isolated accelerator runtimes --- docs/contracts.md | 33 ++ ...repare-foundry-macos-webgpu-through-ort.md | 14 + ...dry-local-with-build-scoped-preparation.md | 14 + ...te-managed-foundry-cuda-dlls-on-windows.md | 19 + ...prepare-foundry-cuda-on-linux-and-arm64.md | 35 ++ ...re-foundry-windows-x64-cuda-from-nvidia.md | 35 ++ docs/decisions/INDEX.md | 10 + docs/testing-critical-flows.md | 2 + src/contracts/foundry-local.ts | 3 + src/core/create.ts | 23 +- src/engine-builds/engines.ts | 53 ++- src/engine-builds/foundry-local.ts | 11 +- src/engine-builds/manifest.test.ts | 58 ++- src/engine-builds/manifest.ts | 22 +- src/engine-builds/select.test.ts | 52 ++- src/engine-builds/select.ts | 28 +- src/engine-builds/service.test.ts | 92 ++++- src/engine-builds/service.ts | 9 +- .../foundry-local/accelerators.test.ts | 89 ++++- src/runtime/foundry-local/accelerators.ts | 103 ++++-- src/runtime/foundry-local/check.test.ts | 55 ++- src/runtime/foundry-local/check.ts | 36 +- .../foundry-local/cuda/host-env.test.ts | 22 ++ src/runtime/foundry-local/cuda/host-env.ts | 20 + src/runtime/foundry-local/cuda/index.ts | 5 + src/runtime/foundry-local/cuda/linux-pins.ts | 206 +++++++++++ src/runtime/foundry-local/cuda/pins.ts | 128 +++++++ src/runtime/foundry-local/cuda/store.test.ts | 86 +++++ src/runtime/foundry-local/cuda/store.ts | 133 +++++++ src/runtime/foundry-local/host/ffi-bun.ts | 250 ++++++++++++- .../foundry-local/host/library.test.ts | 17 +- src/runtime/foundry-local/host/library.ts | 27 +- .../foundry-local/host/openvino.test.ts | 84 +++++ src/runtime/foundry-local/host/openvino.ts | 38 ++ src/runtime/foundry-local/host/run.test.ts | 71 ++++ src/runtime/foundry-local/host/run.ts | 19 +- .../foundry-local/host/webgpu/index.ts | 2 + .../foundry-local/host/webgpu/policy.test.ts | 88 +++++ .../foundry-local/host/webgpu/policy.ts | 39 ++ .../foundry-local/host/webgpu/store.test.ts | 87 +++++ .../foundry-local/host/webgpu/store.ts | 89 +++++ .../foundry-local/host/windows-dlls.test.ts | 50 +++ .../foundry-local/host/windows-dlls.ts | 32 ++ src/runtime/foundry-local/runtime.test.ts | 46 +++ src/runtime/foundry-local/runtime.ts | 49 ++- .../control/routes/foundry-local.test.ts | 33 ++ test/e2e/engine-builds.test.ts | 127 ++++++- test/e2e/foundry-host.test.ts | 347 +++++++++++++++++- test/helpers/fake-foundry-host.mjs | 4 +- 49 files changed, 2795 insertions(+), 100 deletions(-) create mode 100644 docs/decisions/2026-11-10-prepare-foundry-macos-webgpu-through-ort.md create mode 100644 docs/decisions/2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md create mode 100644 docs/decisions/2026-11-11-isolate-managed-foundry-cuda-dlls-on-windows.md create mode 100644 docs/decisions/2026-11-11-prepare-foundry-cuda-on-linux-and-arm64.md create mode 100644 docs/decisions/2026-11-11-prepare-foundry-windows-x64-cuda-from-nvidia.md create mode 100644 src/runtime/foundry-local/cuda/host-env.test.ts create mode 100644 src/runtime/foundry-local/cuda/host-env.ts create mode 100644 src/runtime/foundry-local/cuda/index.ts create mode 100644 src/runtime/foundry-local/cuda/linux-pins.ts create mode 100644 src/runtime/foundry-local/cuda/pins.ts create mode 100644 src/runtime/foundry-local/cuda/store.test.ts create mode 100644 src/runtime/foundry-local/cuda/store.ts create mode 100644 src/runtime/foundry-local/host/openvino.test.ts create mode 100644 src/runtime/foundry-local/host/openvino.ts create mode 100644 src/runtime/foundry-local/host/webgpu/index.ts create mode 100644 src/runtime/foundry-local/host/webgpu/policy.test.ts create mode 100644 src/runtime/foundry-local/host/webgpu/policy.ts create mode 100644 src/runtime/foundry-local/host/webgpu/store.test.ts create mode 100644 src/runtime/foundry-local/host/webgpu/store.ts create mode 100644 src/runtime/foundry-local/host/windows-dlls.test.ts create mode 100644 src/runtime/foundry-local/host/windows-dlls.ts diff --git a/docs/contracts.md b/docs/contracts.md index 263766ba..ef72ace2 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -170,6 +170,39 @@ New with Foundry Local (ADRs 2026-10-15-foundry-local-*): `/foundry-local/ builds, the variants the app installs, the library's own data (accelerators, shared by every build) with the core's `runtime/accelerators.json`, each host's catalog cache (`tmp/`, deleted when the host exits), the library's logs — and `/foundry-local/foundry-local-manifest.cache.json`. +Foundry Local 2.4 (change `upgrade-foundry-local-2-4`): new preparation records are +`foundry-local/runtime///accelerators.json`; the unversioned record remains exclusive +to 2.1.0 and stays readable after rollback. Preparation, model checks and loads capture a build's identity. +The schema 1 manifest optionally declares `distribution: "atomic-conf"`, restricted to +`https://github.com/AtomicBot-ai/atomic-chat-conf/releases/download/foundry-local-/`; +without it the Microsoft URL stays unchanged. C API 2 and 3 are supported. Linux ARM64 needs glibc +2.34 for runtime 2.4.0 (2.28 for 2.1.0); Linux x64 remains at 2.28. Installation validates the loaded +library's normalized runtime version and maximum supported table against the selected release before activation. +Windows x64 2.4.0 bundles Intel OpenVINO 1.8.1 and its dependencies under the build's +`lib/openvino/`. The child host explicitly registers it on the shared ORT environment when +OpenVINO is requested, instead of using the incompatible system WinML EP. Discovery still uses +WinML; the current process reports registered only after the bundled registration succeeds. +Missing Intel files fail OpenVINO preparation with a reinstall instruction; CPU and CUDA do not +load this bundle. Runtime 2.1.0 and other platforms retain their original provider registration. +macOS ARM64 2.4.0 prepares the original Microsoft WebGPU EP 0.2.1 ZIP using the core downloader, +then registers the verified library through ORT API 31 instead of the failing native bootstrap. +Its library cache is `foundry-local/runtime/v2.4.0/macos-arm64/webgpu-ep/0.2.1/`. +Both the archive and native library have pinned sizes and SHA-256 hashes; cache activation is atomic. +Only explicit accelerator preparation may download it. Every model host validates and registers +the cached library locally; an absent or modified library asks for preparation again. Other runtime +versions retain their provider path. The existing accelerator events and control API are unchanged. +Foundry Local 2.4.0 stages pinned NVIDIA CUDA and cuDNN redistributables on +explicit CUDA preparation for Windows and Linux x64 and ARM64. Each complete +runtime set and its notices are cached in +`foundry-local/runtime/v2.4.0//cuda//`. The revision is +computed from that target's pins. CUDA preparation and model hosts receive the +private cache through the child loader search path. The core checks Linux ARM64 +CUDA variants against a minimum runtime of 2.4.0 and requires the CUDA provider +reported by the active build. The existing API is unchanged. +`POST /atomic/v1/models/foundry-local/check` accepts optional `min_runtime_version: "X.Y.Z"`. +An installed runtime below the minimum returns `engine-update-required` with both versions in +`reason`; an absent engine remains `engine-not-installed`. Comparison is numeric and local; omitted +minimum and `0.0.0` retain the old verdicts. Invalid direct minima return `INVALID_ARGUMENT` (400). New with LiteRT-LM (ADRs 2026-10-21-litert-lm-*): `/litert-lm/{backends,accelerators,models,cache,runtime,tmp,logs}` — builds, prepared OpenVINO (`accelerators/openvino//`), the variants the clients install (`models//` + `model.yml`), the library's `cache_dir` (CPU XNNPACK caches, about 1 GB per model, named diff --git a/docs/decisions/2026-11-10-prepare-foundry-macos-webgpu-through-ort.md b/docs/decisions/2026-11-10-prepare-foundry-macos-webgpu-through-ort.md new file mode 100644 index 00000000..d5613927 --- /dev/null +++ b/docs/decisions/2026-11-10-prepare-foundry-macos-webgpu-through-ort.md @@ -0,0 +1,14 @@ +--- +date: 2026-11-10 +title: "Prepare Foundry macOS WebGPU through ORT" +--- + +# 2026-11-10 — Prepare Foundry macOS WebGPU through ORT + +- **Context:** Foundry 2.4.0 installs on macOS ARM64, but its native `Manager_DownloadAndRegisterEps` fails with `unknown error` after extracting WebGPU 0.2.1. A typed C++ client reproduces the failure without Bun FFI. The unchanged provider registers through standard ORT API 31 and generates through Foundry 2.4.0/GenAI 0.19.0. This resolves the Mac acceptance limitation recorded in the Foundry upgrade ADR. +- **Decision:** Only for macOS ARM64/runtime 2.4.0, explicitly prepare and register the same Microsoft CDN provider. Reuse the core downloader and regular-file archive extractor, pin both ZIP and dylib sizes/SHA-256, and atomically cache the original library under `foundry-local/runtime/v2.4.0/macos-arm64/webgpu-ep/0.2.1/`. Register it on ORT's shared environment and hold that reference until after the manager and its sessions are released. Report registered only after the real call succeeds. Await asynchronous preparation before emitting readiness or loading a model. Permit downloads only in `foundry-host prepare`; `serve` validates and reuses the cache, with an instruction to prepare again if it is missing or modified. +- **Alternatives:** Retrying native preparation repeats the same failure. Ignoring it and marking the accelerator prepared does not register a usable provider. Mutating Microsoft's private `active` pointer couples our preparation to its bundle lifecycle; 2.1.0 can remove unreferenced generations from that shared directory. The separate build cache avoids that coupling. Changing ORT/GenAI, signatures or published runtime archives is unnecessary. +- **Consequences:** First preparation downloads 3,447,797 bytes; the installed library is 10,432,384 bytes. A changed CDN artifact fails integrity checks instead of silently replacing native code. Each model host verifies the cached dylib and registers it again without fetching. CPU, 2.1.0, other platforms and future runtime versions retain their existing paths. The internal manager method may now return a promise; its synchronous implementations remain supported. Disk failures retain `[disk_*]` tags. Signed desktop application qualification remains a separate consumer check. +- **Evidence:** Ordinary compiled core: prepare → load Qwen3.5 0.8B WebGPU → streamed public `/v1/chat/completions` answer → unload, with all 13 original model-file hashes unchanged. Targeted compiled app-core also prepares and generates from a fresh host; a separate case refuses an unprepared model without creating/downloading an EP cache. Unit tests cover deferred registration, failures, scope, cache reuse, both hash boundaries, tampering, repair and disk errors. +- **Owner:** team. +- **Links:** [Foundry upgrade ADR](2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md); [disk contract](../contracts.md); `atomic-chat-spec/openspec/changes/upgrade-foundry-local-2-4/rulings/core.md`. diff --git a/docs/decisions/2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md b/docs/decisions/2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md new file mode 100644 index 00000000..b26433cf --- /dev/null +++ b/docs/decisions/2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md @@ -0,0 +1,14 @@ +--- +date: 2026-11-10 +title: "Upgrade Foundry Local with build-scoped preparation" +--- + +# 2026-11-10 — Upgrade Foundry Local with build-scoped preparation + +- **Context:** Foundry Local 2.4.0 ships as five archives repackaged by conf from Microsoft NuGet packages, with an additional pinned Intel OpenVINO 1.8.1 package for Windows x64. It requires C API 3 and, on Linux ARM64, glibc 2.34. Existing 2.1.0 installations, locally installed models and accelerator preparation must remain usable until an explicit update and after manual rollback. +- **Decision:** Accept the optional schema 1 `distribution: atomic-conf` only in the fixed conf release namespace; absence retains the Microsoft URL. Apply one host/core/API compatibility predicate to manifest candidates and offline active builds, retaining `minCoreVersion` in new install records. Negotiate API 3 before API 2 and require staging's actual library version and supported table to match the selected release before activation. Keep the legacy accelerator record exclusively for 2.1.0; new releases use `runtime///accelerators.json`. Capture the build for every preparation, model check and load. Add the optional model runtime minimum to the existing check route, comparing runtime versions numerically without a network request. +- **Consequences:** Linux ARM64 with glibc 2.28–2.33 stays on 2.1.0 even if 2.4.0 files are present. A failed staging probe leaves the previous session running. Successful activation may interrupt its response, as before; rollback remains unload plus removal of the new build. Old cores can still read the untouched 2.1.0 preparation record. Foundry's legacy parsed cache omits `schema_version`; only the cache reader restores that discriminator, while network parsing stays strict. Windows DLL search changes run only in the child host, retaining the build's dependencies and inherited PATH while adding CUDA/cuDNN bins through `AddDllDirectory` and `SetDefaultDllDirectories`. Preload Foundry with `LoadLibraryExW(DLL_LOAD_DIR | DEFAULT_DIRS)` before binding its symbols: otherwise a system ORT (1.17.1 on the acceptance host) can replace the bundled ORT and fail initialization with error 1114. A failed CUDA preparation does not block CPU or other accelerators. Real native probes are separate evidence from generation and hardware acceptance; consumer releases remain gated on their own qualification. +- **Windows NPU qualification:** The owner approved adding Intel.ML.OnnxRuntime.EP.OpenVINO 1.8.1 after the system WinML OpenVINO 1.8.95 EP failed on ORT 1.31.0 and 1.31.1 (`OrtEpApi_ReleaseEpContextConfig_SinceV28` unavailable). The same NPU model still generates with 2.1.0/ORT 1.30.0. Downgrading ORT alone is incompatible with GenAI 0.19.0, which needs ORT API 31. Preserve the three Microsoft packages and all signed native bytes; place Intel's Windows natives in `lib/openvino/` with its original license metadata and notices. Use a distinct `foundry-local-win-x64-openvino-1-8-1.zip` asset and retain the original published ZIP. Register the pinned plugin through standard ORT API 31 on its shared process environment. Acquire an environment reference lazily when OpenVINO is requested and release it after the Foundry manager. Do not accept WinML's registration as the bundled EP's readiness or fall back to the incompatible system plugin. Other EPs and 2.1.0 keep their paths. Missing Intel files do not block CPU probes or CUDA preparation. The new archive is 93,972,839 bytes, SHA-256 `23ce1fea75d64254e99042c3e99e1fc2bb0dd5befff07d4a013857920c67b2a1`; the NuGet catalog SHA-512 is pinned in conf. Production core and app-core both generated with the unchanged NPU-only model on Windows. A local download fixture exercised the production installer/hash/staging pipeline before remote publication was explicitly approved. The owner then authorized publication: the corrected archive is now public and its downloaded bytes match the recorded SHA-256. Conf's local candidate selects this asset for Windows x64 only. An audit preserved all five original asset IDs, digests, sizes and modification timestamps; the production manifest remains unchanged pending consumer releases. +- **Additional Mac acceptance:** Public 2.4.0 installation passes on macOS 26.6.2 ARM64, but ordinary core WebGPU preparation fails with `Manager_DownloadAndRegisterEps: unknown error`. The unchanged vendor C API reproduces the same failure in a typed C++ client with shared hosting disabled, without Bun FFI or a progress callback. The CDN download succeeds, and direct registration of its unchanged WebGPU 0.2.1 library in ORT 1.31 succeeds. A diagnostic host using that registration generates a real Qwen3.5 0.8B answer through Foundry 2.4.0/GenAI 0.19.0 (4096 context, 15 completion tokens, stop, exit 0). Early environment creation alone does not fix native preparation. The precise internal exception remains unknown; the ordinary Mac flow is not qualified. No production registration workaround or signing/security change was made. All 13 original model files and the isolated model copy remain unchanged after generation, apart from the explicitly reduced context in the copy before testing. +- **Owner:** team. +- **Links:** `atomic-chat-spec/openspec/changes/upgrade-foundry-local-2-4/{design,tasks}.md`; [control and disk contracts](../contracts.md); [Windows DLL search flags](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories); [per-library dependency precedence](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw); [Microsoft regression report](https://github.com/microsoft/foundry-local/issues/1261); [standard EP registration](https://learn.microsoft.com/en-us/windows/ai/new-windows-ml/bring-your-own-eps). diff --git a/docs/decisions/2026-11-11-isolate-managed-foundry-cuda-dlls-on-windows.md b/docs/decisions/2026-11-11-isolate-managed-foundry-cuda-dlls-on-windows.md new file mode 100644 index 00000000..ead18b7b --- /dev/null +++ b/docs/decisions/2026-11-11-isolate-managed-foundry-cuda-dlls-on-windows.md @@ -0,0 +1,19 @@ +--- +date: 2026-11-11 +title: "Isolate managed Foundry CUDA DLLs on Windows" +--- + +# 2026-11-11 — Isolate managed Foundry CUDA DLLs on Windows + +Windows does not specify the order among directories registered with +`AddDllDirectory`. Adding the managed cache and installed Toolkit directories +allowed DLLs with the same basename to compete inside the Foundry host. + +Core passes the managed cache path explicitly to the Windows preparation and +CUDA model hosts. With that path set, both Windows architectures limit the DLL +search to the Foundry build, the managed CUDA directory and System32. This +keeps the system NVIDIA driver accessible. The legacy discovery path still +serves hosts without a managed CUDA cache. All loader settings are local to the +child process. + +- [Microsoft DLL search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order) diff --git a/docs/decisions/2026-11-11-prepare-foundry-cuda-on-linux-and-arm64.md b/docs/decisions/2026-11-11-prepare-foundry-cuda-on-linux-and-arm64.md new file mode 100644 index 00000000..1a6d1f4f --- /dev/null +++ b/docs/decisions/2026-11-11-prepare-foundry-cuda-on-linux-and-arm64.md @@ -0,0 +1,35 @@ +--- +date: 2026-11-11 +title: "Prepare Foundry CUDA on Linux and ARM64" +--- + +# 2026-11-11 — Prepare Foundry CUDA on Linux and ARM64 + +Foundry Local 2.4.0 exposes Microsoft CUDA providers for Windows and Linux on +x64 and ARM64. The x64 providers require CUDA 12. The ARM64 providers require +CUDA 13. Both use cuDNN 9. Native model hosts need the matching libraries before +registering the provider. + +The existing CUDA prepare and cache lifecycle now selects a pinned archive set +by the active Foundry build and its platform. Windows ARM64 uses NVIDIA CUDA +13.4 Update 2 and the matching cuDNN 9.25 ZIPs. Linux x64 uses the NVIDIA CUDA +12 and cuDNN 9.20 wheels previously qualified on Ubuntu. Linux ARM64 uses the +CUDA 13.4 and cuDNN 9.25 ARM64 wheels. Wheels are ZIP archives with the runtime +SONAME files already materialized, so core can use its existing streaming ZIP +reader and leave each ELF library under its required loader name. Each archive +has a pinned URL, size, SHA-256, an exact member allowlist and a license notice. + +Only the explicit Prepare CUDA flow downloads the archives. The Windows child +uses its private cache through `PATH`, with x64 also using `AddDllDirectory`. +The Linux child gets its cache at the front of `LD_LIBRARY_PATH` before spawn. +The NVIDIA driver remains a system dependency. Windows x64 keeps the existing +cache revision, and macOS continues to use WebGPU. + +Linux ARM64 CUDA model checks and loads require Foundry 2.4.0 or newer and use +its actual provider discovery and preparation record. Managed preparation is +pinned to the 2.4.0 release on all four targets. + +- [Foundry Local 2.4.0 release notes](https://github.com/microsoft/Foundry-Local/releases/tag/v2.4.0) +- [NVIDIA CUDA 13.4 Update 2 redistribution manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.4.2.json) +- [NVIDIA cuDNN 9.25 redistribution manifest](https://developer.download.nvidia.com/compute/cudnn/redist/redistrib_9.25.1.json) +- [NVIDIA cuDNN 9.25 package metadata](https://pypi.org/project/nvidia-cudnn-cu13/9.25.1.1/) diff --git a/docs/decisions/2026-11-11-prepare-foundry-windows-x64-cuda-from-nvidia.md b/docs/decisions/2026-11-11-prepare-foundry-windows-x64-cuda-from-nvidia.md new file mode 100644 index 00000000..3bf76c7e --- /dev/null +++ b/docs/decisions/2026-11-11-prepare-foundry-windows-x64-cuda-from-nvidia.md @@ -0,0 +1,35 @@ +--- +date: 2026-11-11 +title: "Prepare Foundry Windows x64 CUDA from NVIDIA" +--- + +# 2026-11-11 — Prepare Foundry Windows x64 CUDA from NVIDIA + +The Foundry Local 2.4.0 Microsoft CUDA provider expects the CUDA 12 and cuDNN 9 +runtime libraries to be available on Windows x64. Windows can discover the +provider with just an NVIDIA driver and then fail registration with error 126. + +On explicit CUDA preparation for that build and platform, core downloads the +NVIDIA redistribution archives for CUDA Runtime 12.8.90, cuBLAS 12.8.4.1 and +cuDNN 9.20.0.48 for CUDA 12. Core pins the archive URLs, sizes and SHA-256 hashes +from NVIDIA's release manifests. It verifies the archives before streaming the +allowlisted runtime DLLs and NVIDIA notices into a private staging directory, +then publishes the complete set by rename. The download is about 1.2 GB and the +resulting cache is about 1.7 GB. The CUDA provider continues to come from +Microsoft, and the NVIDIA GPU driver comes from the machine. + +The prepare host and later CUDA model hosts receive the cache directory through +child `PATH`. The Windows host passes it to `AddDllDirectory`. Model hosts +reuse the installed files locally. Core checks that the CUDA provider is offered +before starting an NVIDIA download. When multiple providers are requested, core +prepares the other providers before it downloads the CUDA runtime and reports +CUDA failures through the existing preparation result. + +The same staging lifecycle can support additional platform and architecture +pins once their exact native dependencies and an actual CUDA inference have +been verified. Linux needs its `LD_LIBRARY_PATH` configured before host launch. +Microsoft specifies CUDA 13 with cuDNN 9 on ARM64. + +- [Foundry Local 2.4.0 release notes](https://github.com/microsoft/Foundry-Local/releases/tag/v2.4.0) +- [CUDA 12.8 Update 1 redistribution manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_12.8.1.json) +- [cuDNN 9.20 redistribution manifest](https://developer.download.nvidia.com/compute/cudnn/redist/redistrib_9.20.0.json) diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index db338b80..1358e69f 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -11,6 +11,16 @@ add a new one that says which record it supersedes. ## Records +- [2026-11-11 — Isolate managed Foundry CUDA DLLs on Windows](2026-11-11-isolate-managed-foundry-cuda-dlls-on-windows.md) + +- [2026-11-11 — Prepare Foundry CUDA on Linux and ARM64](2026-11-11-prepare-foundry-cuda-on-linux-and-arm64.md) + +- [2026-11-11 — Prepare Foundry Windows x64 CUDA from NVIDIA](2026-11-11-prepare-foundry-windows-x64-cuda-from-nvidia.md) + +- [2026-11-10 — Prepare Foundry macOS WebGPU through ORT](2026-11-10-prepare-foundry-macos-webgpu-through-ort.md) + +- [2026-11-10 — Upgrade Foundry Local with build-scoped preparation](2026-11-10-upgrade-foundry-local-with-build-scoped-preparation.md) + - [2026-11-10 — Offer the upstream Linux x64 CUDA and Windows arm64 Vulkan builds](2026-11-10-offer-upstream-linux-x64-cuda-and-windows-arm64-vulkan.md) - [2026-11-07 — Expose typed FastFlowLM launch settings through the core](2026-11-07-expose-flm-launch-settings.md) diff --git a/docs/testing-critical-flows.md b/docs/testing-critical-flows.md index 59f2d17a..252d215a 100644 --- a/docs/testing-critical-flows.md +++ b/docs/testing-critical-flows.md @@ -12,6 +12,8 @@ Line coverage alone never raises a grade. A PR may not lower a grade. | Flow | Grade | Evidence | Phase target | | --- | --- | --- | --- | +| Foundry Local 2.1.0 → 2.4.0 and manual rollback | Partial | `src/engine-builds/{manifest,select,service}.test.ts`: both distributions, host/core/API filters, legacy disk cache, staging version/ABI rejection; `src/runtime/foundry-local/{accelerators,runtime,check}.test.ts`: build-scoped preparation, late result, minimum model runtime; `test/e2e/engine-builds.test.ts`: compiled core with a fake CPU host, failed staging keeps the old streamed answer, successful update stops the old host, rollback reopens unchanged model files; `test/e2e/foundry-host.test.ts`: both real native releases probed from both binaries on macOS ARM64 and Windows x64. Windows RTX 5090 Laptop: real CPU migration, rejected staging keeps the old answer, new CPU answer, CUDA failure without its DLLs leaves CPU working, CUDA generation with process-scoped CUDA 12/cuDNN 9 DLLs, and firewall-blocked offline CPU rollback with all 9 model-file hashes and the legacy preparation record unchanged. Baseline 2.1.0 NPU generation passes with the existing WinML EP. Stock 2.4.0 NPU loading fails in ORT 1.31.0 and 1.31.1 with `OrtEpApi_ReleaseEpContextConfig_SinceV28` unavailable (Microsoft foundry-local issue 1261). The corrected Windows archive bundles Intel.ML.OnnxRuntime.EP.OpenVINO 1.8.1 on the unchanged ORT 1.31.0. A local download fixture passes the production install/hash/staging pipeline; ordinary core.exe then prepares, loads the same NPU-only model, streams a reply through /v1 and unloads. Targeted Windows native e2e also passes app-core preparation/generation and a missing-Intel failure with a working native probe (2 passed, 11 skipped). The corrected archive is now public, its downloaded SHA-256 is verified, and conf's local candidate selects it for Windows x64; all five original assets are unchanged. Mac ARM64 now prepares the pinned, unmodified WebGPU 0.2.1 bundle through the core downloader and registers it through ORT API 31. The ordinary core passed cold prepare, Qwen3.5 0.8B load, a streamed public /v1 answer (683 ms), unload and all 13 original-file hash checks. Two targeted Mac e2e cases pass: app-core prepare/generation in a fresh host, and refusal without downloading when preparation is absent. Unit tests cover asynchronous readiness, offline cache reuse, archive/native integrity, tampering, repair and disk tags. Ubuntu 26.04.1 x64/glibc 2.43: the compiled core installs public 2.4.0 (C API 3), streams a Qwen 2.5 0.5B CPU answer, and unloads. Native CUDA preparation on the CUDA 13 host reports missing libcublasLt.so.12. With the official CUDA 12 and cuDNN 9 libraries on the test process search path, ordinary core prepares CUDA, streams a Qwen 3.5 0.8B answer, and unloads. NVIDIA reports 2,052 MiB allocated to the model host on RTX 4070 Laptop. Both owners exit cleanly. Managed Windows x64 CUDA now passes a cold app-core preparation on MSI RTX 5090 Laptop without system CUDA or cuDNN. The attached test client waits through the official pinned NVIDIA downloads and Microsoft registration (217 s). The private cache contains 11 DLLs and three notices and is reused on a second prepare. A fresh model host loads six NVIDIA modules from that cache and streams a complete Qwen 3.5 0.8B CUDA reply through `/v1`. The model unloads and the test owner exits cleanly. Consumer release/qualification remains pending | Strong after consumer qualification | +| Foundry Local 2.4.0 managed CUDA delivery | Partial | Focused `cuda/store.test.ts`, `check.test.ts`, `runtime.test.ts`, and `host/run.test.ts` exercise the platform matrix, verified ZIP extraction, cache reuse, the Linux ARM64 minimum, the child loader environment and CUDA 13 diagnostics. The MSI RTX 5090 Laptop and Ubuntu RTX 4070 Laptop both pass cold preparation with no matching system CUDA and cuDNN, cache reuse and streamed Qwen 3.5 0.8B generation. Ubuntu takes 526 s, caches 15 shared libraries and six notices, and loads eight cached NVIDIA modules in the model host with 2,000 MiB allocated on the GPU. Windows and Linux ARM64 app-core binaries cross-build. The two NVIDIA ARM64 CUDA Runtime archives pass real download, SHA-256 verification and AArch64 file inspection. A separate MSI run exposes competing CUDA 12 and cuDNN 9 DLLs through CUDA_PATH, CUDNN_PATH and PATH. Preparation and generation pass with all six loaded NVIDIA runtime DLLs from the managed cache. Native ARM64 provider registration and GPU inference remain pending | Strong after native ARM64 acceptance | | Windows upstream ROCm runtime delivery | Partial (automation), real hardware acceptance | `src/backend/install/windows-rocm-runtime.test.ts`: 8 targeted cases, including filesystem installation, integrity failure and preserving the previous pack; actual AMD wheel RECORD checks; compiled atc on Windows 11 / Radeon 860M: automatic runtime delivery through a temporary request proxy, then proxy removed, Qwen3 0.6B loaded with 29/29 GPU layers and generated an answer. See ADR `2026-11-07-deliver-windows-rocm-runtime.md`. Other Radeon architectures and desktop UI have not been exercised on hardware. | extend hardware coverage as available | | CLI: version, usage, dispatch, exit codes | Strong | `src/cli/main.test.ts` (dispatch to every phase-1 command, a full daemon → serve → shutdown cycle in one process), `src/cli/commands.test.ts`, `test/e2e/{binary,owner}.test.ts` on the compiled binary | maintained | | Rust contract parity: argv, error cascade, runtime-device, `--list-devices` | Strong (contract) | `test/contract/{args,errors,runtime-device,devices}.test.ts` replay every fixture in `test/fixtures/app/` with the comparator the emitter names; checksum shared with the app | maintained; the three shim sets replay since stage 4a (`test/contract/shims.test.ts`), `proxy-http` and `state-file` since stage 4b (`test/contract/{proxy-http,state-file}.test.ts`, also under Bun) | diff --git a/src/contracts/foundry-local.ts b/src/contracts/foundry-local.ts index b209ec98..e16d4e9b 100644 --- a/src/contracts/foundry-local.ts +++ b/src/contracts/foundry-local.ts @@ -63,6 +63,8 @@ export interface FoundryLocalAcceleratorsEvent { /** `POST /models/foundry-local/check`: the variant's accelerator and device, as conf and `model.yml` spell them. */ export interface FoundryLocalCheckRequest { + /** Minimum runtime required by this model revision, X.Y.Z; absent: no version constraint. */ + min_runtime_version?: string execution_provider: string device: string } @@ -73,6 +75,7 @@ export const FOUNDRY_LOCAL_CHECK_VERDICTS = [ 'accelerator-unavailable', 'platform-unsupported', 'engine-not-installed', + 'engine-update-required', ] as const export type FoundryLocalCheckVerdict = (typeof FOUNDRY_LOCAL_CHECK_VERDICTS)[number] diff --git a/src/core/create.ts b/src/core/create.ts index 7ae1b08c..e5734639 100644 --- a/src/core/create.ts +++ b/src/core/create.ts @@ -37,6 +37,7 @@ import { ExternalSessions } from '../runtime/index.js' import type { LocalRuntime } from '../runtime/index.js' import { FoundationModelsRuntime } from '../runtime/foundation-models/index.js' import { MlxRuntime } from '../runtime/mlx/index.js' +import { CudaRuntimeStore } from '../runtime/foundry-local/cuda/index.js' import { FoundryLocalAcceleratorService, FoundryLocalRuntime, @@ -436,6 +437,11 @@ export async function createAtomicCore( const geniexHostCmd = geniexHostCommand(env) const foundryLocalPaths = layout.provider('foundry-local') const foundryHost = foundryHostCommand(env) + const foundryCuda = new CudaRuntimeStore({ + runtimeDir: foundryLocalPaths.runtimeDir as string, + platform, + fetch: options.fetch ?? fetch, + }) // The provider itself (task 6.6): one foundry-host per model, where the platform rule holds. The // active build and the prepared accelerators are read per load, from services wired below. const foundryLocalRuntime: FoundryLocalRuntime | undefined = @@ -449,14 +455,15 @@ export async function createAtomicCore( arch: foundryLocalArch, hostCommand: foundryHost, resolveBuild: (): Promise => engineBuilds.activeDir('foundry-local'), - preparedAccelerators: async () => - foundryLocalAccelerators ? foundryLocalAccelerators.prepared() : [], + preparedAccelerators: async (build) => + foundryLocalAccelerators ? foundryLocalAccelerators.prepared(build) : [], trustedHosts: managedTrustedHosts, readSettings: async () => settings.get('foundry-local'), journal, emit: (name, payload) => emitter.emit(name, payload), claimGpu: gpuResidency.hook('foundry-local'), baseEnv: env, + cuda: foundryCuda, log: runtimeLog, ...(options.backendOutput ? { backendOutput: options.backendOutput } : {}), }) @@ -898,7 +905,7 @@ export async function createAtomicCore( }, hostProbes: { 'foundry-local': async (libDir) => { - await runFoundryHostProbe( + const probe = await runFoundryHostProbe( foundryHost, { libDir, @@ -907,6 +914,7 @@ export async function createAtomicCore( }, { env } ) + return { libraryVersion: probe.version ?? null, cApiVersion: probe.c_api_version, devices: [] } }, 'litert-lm': liteRtHostProber(liteRtHost, env), 'geniex': geniexHostProber(geniexHostCmd, env), @@ -984,6 +992,7 @@ export async function createAtomicCore( logsDir: foundryLocalPaths.logsDir as string, emit: (name, payload) => emitter.emit(name, payload), env, + cuda: foundryCuda, }) // The managed container environment and the one Docker executor of this core (task 2.6). The @@ -1240,13 +1249,17 @@ export async function createAtomicCore( // Task 6.5: the platform, the active build, the last probe, the NPU — no network. 'foundry-local': async (body: unknown) => { const request = parseFoundryLocalCheckRequest(body) - const installed = (await engineBuilds.activeDir('foundry-local')) !== undefined + const active = await engineBuilds.activeBuild('foundry-local') + const installed = active !== undefined return foundryLocalVerdict( { platform, arch: foundryLocalArch, installed, - accelerators: installed ? (await foundryLocalAccelerators.list()).accelerators : [], + ...(active ? { runtimeVersion: active.tag.replace(/^v/, '') } : {}), + accelerators: active + ? (await foundryLocalAccelerators.list({ build: active.dir })).accelerators + : [], npu: (await foundryLocalNpu()).present, }, request diff --git a/src/engine-builds/engines.ts b/src/engine-builds/engines.ts index 9764caf4..c5d89dd3 100644 --- a/src/engine-builds/engines.ts +++ b/src/engine-builds/engines.ts @@ -23,7 +23,6 @@ import { listLiteRtLmBuilds, prepareLiteRtLmTree, writeLiteRtLmInstallRecord } f import { listGeniexBuilds, prepareGeniexTree, writeGeniexInstallRecord } from './geniex.js' import { audiocppAssetUrl, - FOUNDRY_LOCAL_C_API_VERSIONS, foundryLocalAssetUrl, mlxAssetUrl, sdcppAssetUrl, @@ -48,6 +47,7 @@ import { backendKindOf, companionFor, foundryLocalHostChoice, + foundryLocalBuildCompatible, geniexHostChoice, liteRtLmHostChoice, mlxHostChoice, @@ -61,6 +61,8 @@ import type { GeniexHostPlatform } from '../runtime/geniex/chip.js' /** One build on disk as the service sees it. */ export interface Build extends EngineBuildRef { + /** Foundry: retained locally so downgrading core cannot activate an incompatible build offline. */ + min_core_version?: string /** For a bundled MLX build, `resources-dir`; otherwise the build's own directory. */ immutable_sha256?: string dir: string @@ -82,6 +84,8 @@ export interface Build extends EngineBuildRef { * nothing to keep answer `void`. */ export interface EngineProbeFacts { + /** Foundry Local: the maximum supported table actually provided by the loaded library. */ + cApiVersion?: number libraryVersion: string | null devices: string[] } @@ -127,6 +131,7 @@ export interface HostChoice { export type ArchiveRef = Omit & { sha256?: string; size?: number } export interface BuildRecordInfo { + minCoreVersion?: string flmIdentity?: FastFlowLmIdentity tag: string backendId: string @@ -142,6 +147,7 @@ export interface BuildRecordInfo { } export interface BuildRelease { + min_core_version?: string tag: string published_at: string | null c_api_version?: number @@ -150,6 +156,8 @@ export interface BuildRelease { } export interface EngineDescriptor { + /** Filter once so catalog, update and installation use the same host-compatible candidates. */ + compatibleManifest?(manifest: M, ctx: EngineContext): M /** The release an install takes from the manifest, and the order key it carries. */ release(manifest: M): BuildRelease | null hostChoice(ctx: EngineContext, manifest: M | null): Promise @@ -173,7 +181,7 @@ export interface EngineDescriptor { record(staging: string, info: BuildRecordInfo): Promise builds(ctx: EngineContext): Promise /** The build the next load uses. */ - active(builds: Build[]): Build | undefined + active(builds: Build[], ctx?: EngineContext): Build | undefined /** * Present when a build that fails its probe sends the install down the host's ladder (sd.cpp, * design D7 of `move-sdcpp-mlx-install-to-core`): remember the failed rung for this tag. @@ -345,9 +353,29 @@ function bundledMlxBuild(bundled: BundledMlx, resourcesDir: string): Build { } const foundryLocal: EngineDescriptor = { + compatibleManifest: (manifest, ctx) => ({ + ...manifest, + releases: manifest.releases.filter((release) => + release.assets.some((asset) => + foundryLocalBuildCompatible(ctx.hostPlatform as FoundryLocalHostPlatform, { + tag: release.tag, + backend_id: asset.platform, + c_api_version: release.c_api_version, + min_core_version: release.min_core_version, + }) + ) + ), + }), release: (manifest) => { - const newest = manifest.releases[0] as FoundryLocalManifest['releases'][number] - return { tag: newest.tag, published_at: newest.published_at, c_api_version: newest.c_api_version } + const newest = manifest.releases[0] + return newest + ? { + tag: newest.tag, + published_at: newest.published_at, + c_api_version: newest.c_api_version, + min_core_version: newest.min_core_version, + } + : null }, hostChoice: async (ctx, manifest) => foundryLocalHostChoice(ctx.hostPlatform as FoundryLocalHostPlatform, manifest?.releases[0] ?? null), @@ -359,13 +387,21 @@ const foundryLocal: EngineDescriptor = { : [] }, prepare: (staging, ctx) => prepareFoundryLocalTree(staging, ctx.platform), - async probe(staging, ctx) { + async probe(staging, ctx, _backendId, release) { if (!ctx.hostProbe) throw new AtomicCoreError( 'ENGINE_INSTALL_FAILED', 'This core has no Foundry Local host to check the build with.' ) - await ctx.hostProbe(staging) + const facts = await ctx.hostProbe(staging) + const version = facts?.libraryVersion?.trim().match(/^v?(\d+\.\d+\.\d+)(?:$|[+\s-])/u)?.[1] + if (!release || version !== release.tag.replace(/^v/, '') || facts?.cApiVersion !== release.c_api_version) + throw new AtomicCoreError( + 'ENGINE_INSTALL_FAILED', + 'The Foundry Local library version or C API does not match the selected release.', + `Expected ${release?.tag} / C API ${release?.c_api_version}; loaded ${facts?.libraryVersion ?? 'unknown'} / C API ${facts?.cApiVersion ?? 'unknown'}.` + ) + return facts }, record: (staging, { abi: _abi, probe: _probe, ...info }) => writeFoundryLocalInstallRecord(staging, info), async builds(ctx) { @@ -377,14 +413,15 @@ const foundryLocal: EngineDescriptor = { installed_at_ms: record.installedAtMs, published_at: record.publishedAt, c_api_version: record.cApiVersion, + ...(record.minCoreVersion ? { min_core_version: record.minCoreVersion } : {}), })) }, /** The newest by `published_at` among the builds whose C API this core's host binds (design D2). */ - active: (builds) => + active: (builds, ctx) => newest( 'foundry-local', builds.filter( - (build) => build.c_api_version != null && FOUNDRY_LOCAL_C_API_VERSIONS.includes(build.c_api_version) + (build) => ctx && foundryLocalBuildCompatible(ctx.hostPlatform as FoundryLocalHostPlatform, build) ) ), } diff --git a/src/engine-builds/foundry-local.ts b/src/engine-builds/foundry-local.ts index c2cbbb34..bdf2e71a 100644 --- a/src/engine-builds/foundry-local.ts +++ b/src/engine-builds/foundry-local.ts @@ -48,6 +48,8 @@ export async function prepareFoundryLocalTree(staging: string, platform: NodeJS. } export interface FoundryLocalInstallRecord { + /** Absent in the legacy 2.1.0 record. */ + minCoreVersion?: string tag: string backendId: string sha256: string | null @@ -70,6 +72,7 @@ export async function writeFoundryLocalInstallRecord( installedAtMs: record.installedAtMs, publishedAt: record.publishedAt, cApiVersion: record.cApiVersion, + ...(record.minCoreVersion ? { minCoreVersion: record.minCoreVersion } : {}), } await writeFile(join(dir, INSTALL_RECORD), JSON.stringify(file, null, 2)) } @@ -82,7 +85,10 @@ async function readFoundryLocalInstallRecord(dir: string): Promise + const { tag, backendId, sha256, installedAtMs, publishedAt, cApiVersion, minCoreVersion } = raw as Record< + string, + unknown + > if ( typeof tag !== 'string' || typeof backendId !== 'string' || @@ -91,6 +97,9 @@ async function readFoundryLocalInstallRecord(dir: string): Promise = {}) => ({ const FL_HOST = { coreVersion: '0.18.0', cApiVersions: [2] } describe('parseFoundryLocalManifest', () => { + it('preserves the atomic-conf distribution and resolves only its fixed release URL', () => { + const parsed = parseFoundryLocalManifest( + FOUNDRY([ + FL_RELEASE('v2.4.0', '2026-11-09T00:00:00Z', { c_api_version: 3, distribution: 'atomic-conf' }), + FL_RELEASE('v2.1.0', '2026-09-30T00:00:00Z'), + ]), + { coreVersion: '0.22.1', cApiVersions: [2, 3] } + ) + const release = parsed.releases[0]! + expect(release).toHaveProperty('distribution', 'atomic-conf') + expect(foundryLocalAssetUrl(parsed, release, release.assets[3]!)).toBe( + 'https://github.com/AtomicBot-ai/atomic-chat-conf/releases/download/foundry-local-v2.4.0/foundry-local-linux-x64.tgz' + ) + const old = parsed.releases[1]! + expect(foundryLocalAssetUrl(parsed, old, old.assets[3]!)).toBe( + 'https://github.com/microsoft/foundry-local/releases/download/v2.1.0/foundry-local-linux-x64.tgz' + ) + }) + + it('skips unknown distributions instead of downloading from upstream by mistake', () => { + const parsed = parseFoundryLocalManifest( + FOUNDRY([ + FL_RELEASE('v2.4.0', '2026-11-09T00:00:00Z', { distribution: 'other' }), + FL_RELEASE('v2.1.0', '2026-09-30T00:00:00Z'), + ]), + FL_HOST + ) + expect(parsed.releases.map((release) => release.tag)).toEqual(['v2.1.0']) + }) + it('reads the manifest conf publishes, .tgz archives included, newest release first', () => { const parsed = parseFoundryLocalManifest( FOUNDRY([FL_RELEASE('v2.1.0', '2026-09-30T00:43:42Z'), FL_RELEASE('v2.0.0', '2026-08-01T00:00:00Z')]), @@ -695,7 +725,7 @@ afterEach(() => data.cleanup()) const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }) function source( - kind: 'sd-cpp' | 'fastflowlm' | 'mlx' | 'litert-lm' | 'geniex' | 'audio-cpp', + kind: 'foundry-local' | 'sd-cpp' | 'fastflowlm' | 'mlx' | 'litert-lm' | 'geniex' | 'audio-cpp', respond: (url: string) => Response | Promise, opts: { env?: Record; clock?: { now: number } } = {} ) { @@ -718,6 +748,32 @@ function source( } describe('EngineManifestSource', () => { + it('reloads a Foundry file override from disk without a network after restart', async () => { + const doc = FOUNDRY([ + FL_RELEASE('v2.4.0', '2026-11-09T00:00:00Z', { c_api_version: 3, distribution: 'atomic-conf' }), + FL_RELEASE('v2.1.0', '2026-09-30T00:00:00Z'), + ]) + const file = join(data.root, 'foundry-local-manifest.json') + await writeFile(file, JSON.stringify(doc)) + const local = source>( + 'foundry-local', + () => { + throw new Error('network forbidden') + }, + { + env: { ATOMIC_FOUNDRY_LOCAL_MANIFEST_URL: pathToFileURL(file).href }, + } + ) + expect((await local.src.read()).manifest?.releases.map((r) => r.tag)).toEqual(['v2.4.0', 'v2.1.0']) + expect(local.urls).toEqual([]) + const offline = source>('foundry-local', () => { + throw new Error('offline') + }) + const cached = await offline.src.read() + expect(cached.source).toBe('cache') + expect(cached.manifest?.releases[0]).toHaveProperty('distribution', 'atomic-conf') + }) + it('reads conf main, caches the accepted document on disk and serves memory until the TTL ends', async () => { const { src, urls, clock } = source('sd-cpp', () => json(SDCPP)) const first = await src.read() diff --git a/src/engine-builds/manifest.ts b/src/engine-builds/manifest.ts index ae9a8ff1..845bc0bc 100644 --- a/src/engine-builds/manifest.ts +++ b/src/engine-builds/manifest.ts @@ -37,7 +37,7 @@ import { CORE_VERSION } from '../version.js' * The `FOUNDRY_LOCAL_API_VERSION`s this core's `foundry-host` binds (design D1). A release built * against another one is not offered. */ -export const FOUNDRY_LOCAL_C_API_VERSIONS: readonly number[] = [2] +export const FOUNDRY_LOCAL_C_API_VERSIONS: readonly number[] = [2, 3] /** * The `abi` numbers this core's `litert-host` binds (change `add-litert-lm-runtime`, design D2). The @@ -144,6 +144,8 @@ export interface FoundryLocalAsset { } export interface FoundryLocalRelease { + /** Absent: Microsoft releases; atomic-conf: the fixed conf release namespace. */ + distribution?: 'atomic-conf' /** The `microsoft/foundry-local` release tag, `v..`. */ tag: string /** The order builds of this engine have. */ @@ -394,6 +396,7 @@ function parseFoundryLocalAsset(raw: unknown): FoundryLocalAsset | null { function parseFoundryLocalRelease(raw: unknown): FoundryLocalRelease | null { if (!isRecord(raw)) return null const { tag, published_at, min_core_version, c_api_version, notes_url } = raw + if (raw['distribution'] !== undefined && raw['distribution'] !== 'atomic-conf') return null if (typeof tag !== 'string' || !FOUNDRY_LOCAL_TAG_RE.test(tag)) return null if (!isDateTime(published_at)) return null if (typeof min_core_version !== 'string' || !SEMVER_RE.test(min_core_version)) return null @@ -412,6 +415,7 @@ function parseFoundryLocalRelease(raw: unknown): FoundryLocalRelease | null { published_at, min_core_version, c_api_version, + ...(raw['distribution'] === 'atomic-conf' ? { distribution: 'atomic-conf' as const } : {}), ...(typeof notes_url === 'string' && /^https:\/\/\S+$/.test(notes_url) ? { notes_url } : {}), assets, } @@ -643,11 +647,15 @@ export function foundryLocalAssetUrl( release: FoundryLocalRelease, asset: FoundryLocalAsset ): string { - return `https://github.com/${manifest.upstream_repo}/releases/download/${release.tag}/${asset.name}` + return release.distribution === 'atomic-conf' + ? `https://github.com/AtomicBot-ai/atomic-chat-conf/releases/download/foundry-local-${release.tag}/${asset.name}` + : `https://github.com/${manifest.upstream_repo}/releases/download/${release.tag}/${asset.name}` } /** Which manifest: everything that differs between the engines. */ export interface ManifestKind { + /** A legacy disk document may omit fields the network parser deliberately drops. */ + parseCached?: (data: unknown) => T label: string url: string urlEnv: string @@ -698,6 +706,11 @@ export function manifestKinds(layout: DataLayout): { coreVersion: CORE_VERSION, cApiVersions: FOUNDRY_LOCAL_C_API_VERSIONS, }), + parseCached: (data) => + parseFoundryLocalManifest(isRecord(data) ? { schema_version: 1, ...data } : data, { + coreVersion: CORE_VERSION, + cApiVersions: FOUNDRY_LOCAL_C_API_VERSIONS, + }), cacheFile: join(layout.provider('foundry-local').root, 'foundry-local-manifest.cache.json'), }, 'litert-lm': { @@ -866,7 +879,10 @@ export class EngineManifestSource { try { const raw = JSON.parse(await (this.deps.readFile ?? defaultReadFile)(this.cachePath)) as unknown if (!isRecord(raw) || typeof raw['fetched_at'] !== 'number') return null - return { fetchedAt: raw['fetched_at'], manifest: this.kind.parse(raw['manifest']) } + return { + fetchedAt: raw['fetched_at'], + manifest: (this.kind.parseCached ?? this.kind.parse)(raw['manifest']), + } } catch { return null } diff --git a/src/engine-builds/select.test.ts b/src/engine-builds/select.test.ts index 0884195a..1a1ad6db 100644 --- a/src/engine-builds/select.test.ts +++ b/src/engine-builds/select.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest' import { foundryLocalHostChoice, + foundryLocalBuildCompatible, foundryLocalHostPlatform, liteRtLmHostChoice, liteRtLmHostPlatform, @@ -620,8 +621,14 @@ describe('foundryLocalHostPlatform', () => { }) it('takes Linux x64 and arm64 with glibc 2.28 or newer, and nothing without glibc', () => { - expect(host({ arch: 'x64', glibcVersion: '2.28' })).toEqual({ platform: 'linux-x64' }) - expect(host({ arch: 'arm64', glibcVersion: '2.43' })).toEqual({ platform: 'linux-arm64' }) + expect(host({ arch: 'x64', glibcVersion: '2.28' })).toEqual({ + platform: 'linux-x64', + glibcVersion: '2.28', + }) + expect(host({ arch: 'arm64', glibcVersion: '2.43' })).toEqual({ + platform: 'linux-arm64', + glibcVersion: '2.43', + }) expect(host({ glibcVersion: '2.27' })).toEqual({ platform: null, reason: expect.stringMatching(/glibc 2\.28/), @@ -756,3 +763,44 @@ describe('geniexHostChoice (change add-geniex-runtime, task 4.4)', () => { }) }) }) + +describe('foundryLocalBuildCompatible', () => { + it('rejects a local build requiring a newer core without a manifest or network', () => { + expect( + foundryLocalBuildCompatible( + { platform: 'win-x64' }, + { + tag: 'v2.4.0', + backend_id: 'win-x64', + c_api_version: 3, + min_core_version: '99.0.0', + } + ) + ).toBe(false) + }) + + it.each([ + ['linux-arm64', '2.31', 'v2.1.0', 2, true], + ['linux-arm64', '2.31', 'v2.4.0', 3, false], + ['linux-arm64', '2.34', 'v2.4.0', 3, true], + ['linux-arm64', undefined, 'v2.4.0', 3, false], + ['linux-x64', '2.28', 'v2.4.0', 3, true], + ['linux-x64', '2.28', 'v2.4.0', 99, false], + ] as const)('%s glibc %s / %s API %s compatible: %s', (platform, glibcVersion, tag, api, expected) => { + expect( + foundryLocalBuildCompatible( + { platform, ...(glibcVersion ? { glibcVersion } : {}) }, + { + tag, + backend_id: platform, + c_api_version: api, + } + ) + ).toBe(expected) + }) + it('rejects a different platform and an unsupported host even for an installed library', () => { + const build = { tag: 'v2.1.0', backend_id: 'win-x64', c_api_version: 2 } + expect(foundryLocalBuildCompatible({ platform: 'macos-arm64' }, build)).toBe(false) + expect(foundryLocalBuildCompatible({ platform: null, reason: 'unsupported' }, build)).toBe(false) + }) +}) diff --git a/src/engine-builds/select.ts b/src/engine-builds/select.ts index 04c8408a..a427ff98 100644 --- a/src/engine-builds/select.ts +++ b/src/engine-builds/select.ts @@ -36,6 +36,8 @@ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' import type { AudioBackend, DiffusionBackend } from '../contracts/index.js' +import { CORE_VERSION } from '../version.js' +import { FOUNDRY_LOCAL_C_API_VERSIONS } from './manifest.js' import { getSupportedFeatures } from '../backend/index.js' import type { HardwareFacts } from '../hardware/index.js' import type { FoundryLocalPlatform, LiteRtLmPlatform } from './manifest.js' @@ -350,7 +352,8 @@ export interface FoundryLocalHostFacts { glibcVersion: string | undefined } -export type FoundryLocalHostPlatform = { platform: FoundryLocalPlatform } | { platform: null; reason: string } +export type FoundryLocalHostPlatform = + { platform: FoundryLocalPlatform; glibcVersion?: string } | { platform: null; reason: string } const leadingNumbers = (version: string): number[] => version.split('.').map((part) => Number.parseInt(part, 10)) @@ -374,11 +377,32 @@ export function foundryLocalHostPlatform(host: FoundryLocalHostFacts): FoundryLo platform: null, reason: `Foundry Local needs glibc ${needMajor}.${needMinor} or newer${host.glibcVersion ? `; this system has ${host.glibcVersion}` : '; this system has none'}.`, } - return { platform: `linux-${arch}` } + return { platform: `linux-${arch}`, glibcVersion: host.glibcVersion } } return { platform: null, reason: `Foundry Local does not run on ${host.platform} ${host.arch}.` } } +/** Release-specific host and ABI policy, shared by remote candidates and offline installs. */ +export function foundryLocalBuildCompatible( + host: FoundryLocalHostPlatform, + build: { tag: string; backend_id: string; c_api_version?: number | null; min_core_version?: string } +): boolean { + if (host.platform === null || build.backend_id !== host.platform) return false + if ( + build.min_core_version && + compareVersions(versionKey(build.min_core_version), versionKey(CORE_VERSION)) > 0 + ) + return false + if (build.c_api_version == null || !FOUNDRY_LOCAL_C_API_VERSIONS.includes(build.c_api_version)) return false + if ( + host.platform !== 'linux-arm64' || + compareVersions(versionKey(build.tag.replace(/^v/, '')), [2, 4, 0]) < 0 + ) + return true + if (!host.glibcVersion) return false + return compareVersions(versionKey(host.glibcVersion), [2, 34]) >= 0 +} + /** The host's archive in the newest installable release, as a one-rung ladder. */ export function foundryLocalHostChoice( host: FoundryLocalHostPlatform, diff --git a/src/engine-builds/service.test.ts b/src/engine-builds/service.test.ts index f36f6909..71abb552 100644 --- a/src/engine-builds/service.test.ts +++ b/src/engine-builds/service.test.ts @@ -168,7 +168,7 @@ function harness( resourcesDir?: string platform?: NodeJS.Platform foundryLocalHost?: FoundryLocalHostPlatform - foundryProbe?: (dir: string) => Promise + foundryProbe?: (dir: string) => Promise liteRtLmHost?: LiteRtLmHostPlatform liteRtLmProbe?: (dir: string) => Promise geniexHost?: GeniexHostPlatform @@ -262,10 +262,18 @@ function harness( 'geniex': opts.geniexHost ?? { platform: 'win-arm64', chip: 'x-elite' }, }, hostProbes: { + ...(opts.foundryProbe + ? { + 'foundry-local': async (dir: string) => { + const facts = await opts.foundryProbe!(dir) + const tag = dir.split(/[\\/]/).at(-2)!.replace(/^v/, '') + return facts ?? { libraryVersion: tag, cApiVersion: tag === '2.4.0' ? 3 : 2, devices: [] } + }, + } + : {}), ...(opts.geniexProbe ? { geniex: opts.geniexProbe } : {}), }, probe: { - ...(opts.foundryProbe ? { 'foundry-local': opts.foundryProbe } : {}), ...(opts.liteRtLmProbe ? { 'litert-lm': opts.liteRtLmProbe } : {}), }, hardware: async () => opts.facts ?? LINUX_VULKAN, @@ -1102,6 +1110,86 @@ describe.skipIf(!POSIX)('EngineBuildsService.remove (task 3.4)', () => { }) describe.skipIf(!POSIX)('Foundry Local builds (task 4.5)', () => { + it.each([ + { libraryVersion: '2.1.0', cApiVersion: 3, devices: [] }, + { libraryVersion: '2.4.0', cApiVersion: 2, devices: [] }, + { libraryVersion: null, cApiVersion: 3, devices: [] }, + ])( + 'rejects a Foundry staging identity mismatch %j before activating or stopping the old build', + async (facts) => { + const h = harness({ foundryProbe: async () => facts }) + h.setFoundry( + foundryManifest([ + { + tag: 'v2.4.0', + published_at: '2026-11-09T00:00:00Z', + c_api_version: 3, + assets: serve('v2.4.0', { + 'linux-x64': { + name: 'foundry-local-linux-x64.tgz', + body: await foundryArchive('mismatch', FOUNDRY_LINUX), + }, + }), + }, + ]) + ) + await expect(h.service.install('foundry-local', { task_id: 'mismatch' })).rejects.toMatchObject({ + code: 'ENGINE_INSTALL_FAILED', + }) + expect(h.hosts['foundry-local'].calls).toEqual([]) + expect(await ls(join(FOUNDRY_ROOT(), 'v2.4.0'))).toEqual([]) + } + ) + + it.each([ + ['linux-arm64', '2.31', 'v2.1.0'], + ['linux-arm64', '2.34', 'v2.4.0'], + ['linux-x64', '2.28', 'v2.4.0'], + ] as const)( + 'uses the same compatible Foundry release for %s glibc %s online and offline', + async (platform, glibcVersion, expected) => { + const h = harness({ foundryLocalHost: { platform, glibcVersion }, foundryProbe: async () => {} }) + const releases = [] + for (const [tag, date, api] of [ + ['v2.1.0', '2026-09-30T00:00:00Z', 2], + ['v2.4.0', '2026-11-09T00:00:00Z', 3], + ] as const) { + releases.push({ + tag, + published_at: date, + c_api_version: api, + assets: serve(tag, { + [platform]: { + name: `foundry-local-${platform}.tgz`, + body: await foundryArchive(tag, FOUNDRY_LINUX), + }, + }), + }) + } + h.setFoundry(foundryManifest([releases[0]!])) + await h.service.install('foundry-local', { task_id: 'old-compatible' }) + h.setFoundry(foundryManifest(releases)) + expect((await h.service.catalog('foundry-local')).manifest?.tag).toBe(expected) + const result = await h.service.install('foundry-local', { task_id: 'compatible' }) + expect(result.build.tag).toBe(expected) + const record = JSON.parse( + await readFile(join(FOUNDRY_ROOT(), expected, platform, 'install.json'), 'utf8') + ) + expect(record.minCoreVersion).toBe('0.1.0') + expect(await h.service.checkUpdates('foundry-local')).toMatchObject({ update_needed: false }) + const offline = harness({ foundryLocalHost: { platform, glibcVersion } }) + expect(await offline.service.activeDir('foundry-local')).toBe(join(FOUNDRY_ROOT(), expected, platform)) + if (platform === 'linux-arm64') { + const oldHost = harness({ foundryLocalHost: { platform, glibcVersion: '2.31' } }) + expect(await oldHost.service.activeDir('foundry-local')).toBe( + join(FOUNDRY_ROOT(), 'v2.1.0', platform) + ) + } + const unsupported = harness({ foundryLocalHost: { platform: null, reason: 'unsupported' } }) + expect(await unsupported.service.activeDir('foundry-local')).toBeUndefined() + } + ) + it('installs the host archive: debug symbols gone, the Linux soname added, probed in staging, then activated', async () => { const probed: string[] = [] const h = harness({ diff --git a/src/engine-builds/service.ts b/src/engine-builds/service.ts index f1c5c7ba..b006c991 100644 --- a/src/engine-builds/service.ts +++ b/src/engine-builds/service.ts @@ -412,6 +412,7 @@ export class EngineBuildsService { cApiVersion: cApiVersion ?? null, abi: abi ?? null, probe: facts, + ...(release.min_core_version ? { minCoreVersion: release.min_core_version } : {}), ...(release.flmIdentity ? { flmIdentity: release.flmIdentity } : {}), }), }) @@ -537,7 +538,7 @@ export class EngineBuildsService { } private activeOf(engine: EngineBuildId, builds: Build[]): Build | undefined { - return this.engine(engine).active(builds) + return this.engine(engine).active(builds, this.context(engine)) } /** The table row of `engine`; one cast, since TypeScript cannot correlate a key with its row. */ @@ -589,7 +590,7 @@ export class EngineBuildsService { // --- manifests and the host ------------------------------------------------------------------ - private readManifest( + private async readManifest( engine: EngineBuildId, request: EngineBuildCatalogRequest ): Promise> { @@ -597,7 +598,9 @@ export class EngineBuildsService { ...(request.force ? { force: true } : {}), ...(request.proxy ? { proxy: request.proxy } : {}), } - return this.deps.manifests[engine].read(options) + const read = await this.deps.manifests[engine].read(options) + const filter = this.engine(engine).compatibleManifest + return read.manifest && filter ? { ...read, manifest: filter(read.manifest, this.context(engine)) } : read } private hostChoice(engine: EngineBuildId, manifest: AnyManifest | null): Promise { diff --git a/src/runtime/foundry-local/accelerators.test.ts b/src/runtime/foundry-local/accelerators.test.ts index 3d9e1727..386f7688 100644 --- a/src/runtime/foundry-local/accelerators.test.ts +++ b/src/runtime/foundry-local/accelerators.test.ts @@ -19,7 +19,16 @@ beforeEach(async () => { afterEach(() => data.cleanup()) function service( - opts: { eps?: string; fail?: string; mode?: string; build?: () => Promise } = {} + opts: { + eps?: string + fail?: string + mode?: string + build?: () => Promise + cuda?: { + supports(build: string): boolean + prepare(build: string, progress: (fraction: number) => void): Promise + } + } = {} ) { const events: FoundryLocalAcceleratorsEvent[] = [] const argvFile = join(data.root, 'argv.jsonl') @@ -38,6 +47,7 @@ function service( FAKE_FOUNDRY_MODE: opts.mode ?? 'ready', }, now: () => 1_000, + ...(opts.cuda ? { cuda: opts.cuda } : {}), }) const probes = async () => existsSync(argvFile) @@ -51,6 +61,49 @@ function service( } describe.skipIf(!POSIX)('FoundryLocalAcceleratorService (task 6.4)', () => { + it('keeps legacy preparation and errors on 2.1.0, isolates 2.4.0, and restores them on rollback', async () => { + let tag = 'v2.1.0' + const { accelerators, paths } = service({ + fail: 'CUDAExecutionProvider', + build: async () => join(data.layout.provider('foundry-local').backendsDir, tag, 'linux-x64'), + }) + await accelerators.prepare({}) + const legacy = await readFile(join(paths.runtimeDir!, 'accelerators.json'), 'utf8') + tag = 'v2.4.0' + expect(await accelerators.prepared()).toEqual([]) + const newer = await accelerators.list() + expect(newer.accelerators.every((ep) => !ep.prepared && ep.reason === undefined)).toBe(true) + await accelerators.prepare({ accelerators: ['CUDAExecutionProvider'] }) + expect(await readFile(join(paths.runtimeDir!, 'accelerators.json'), 'utf8')).toBe(legacy) + tag = 'v2.1.0' + expect(await accelerators.prepared()).toEqual(['WebGpuExecutionProvider']) + expect( + (await accelerators.list()).accelerators.find((ep) => ep.name === 'CUDAExecutionProvider')?.reason + ).toContain('libcublasLt') + }) + + it('writes a late preparation result to the original build even after active changes', async () => { + let tag = 'v2.1.0' + let announce: () => void = () => {} + const started = new Promise((resolve) => { + announce = resolve + }) + const { accelerators } = service({ + build: async () => { + const original = tag + announce() + return join(data.layout.provider('foundry-local').backendsDir, original, 'linux-x64') + }, + }) + const preparing = accelerators.prepare({ accelerators: ['WebGpuExecutionProvider'] }) + await started + tag = 'v2.4.0' + await preparing + expect(await accelerators.prepared()).toEqual([]) + tag = 'v2.1.0' + expect(await accelerators.prepared()).toEqual(['WebGpuExecutionProvider']) + }) + it('probes the active build on the first request and answers from that probe until the build changes', async () => { let build = 'v2.1.0' const { accelerators, probes, paths } = service({ @@ -146,6 +199,40 @@ describe.skipIf(!POSIX)('FoundryLocalAcceleratorService (task 6.4)', () => { expect((await probes()).at(-1)).toEqual(expect.arrayContaining(['--prepared', 'WebGpuExecutionProvider'])) }) + it('fetches NVIDIA libraries only for an offered CUDA prepare', async () => { + const cuda = { supports: () => true, prepare: vi.fn(async () => 'C:\\atomic-cuda') } + const { accelerators } = service({ cuda }) + await accelerators.list() + await accelerators.prepare({ accelerators: ['WebGpuExecutionProvider'] }) + expect(cuda.prepare).not.toHaveBeenCalled() + const absent = service({ cuda, eps: 'WebGpuExecutionProvider' }) + await absent.accelerators.prepare({ accelerators: ['CUDAExecutionProvider'] }) + expect(cuda.prepare).not.toHaveBeenCalled() + expect((await accelerators.prepare({ accelerators: ['CUDAExecutionProvider'] })).accelerators).toEqual([ + { name: 'CUDAExecutionProvider', prepared: true }, + ]) + expect(cuda.prepare).toHaveBeenCalledOnce() + }) + + it('records NVIDIA download failure and still prepares other accelerators', async () => { + const cuda = { + supports: () => true, + prepare: vi.fn(async () => { + throw new Error('bad digest') + }), + } + const { accelerators, events } = service({ cuda }) + const result = await accelerators.prepare({}) + expect(result.accelerators).toEqual([ + { name: 'WebGpuExecutionProvider', prepared: true }, + { name: 'CUDAExecutionProvider', prepared: false, reason: expect.stringContaining('bad digest') }, + ]) + expect(await accelerators.prepared()).toEqual(['WebGpuExecutionProvider']) + expect(events).toContainEqual( + expect.objectContaining({ accelerator: 'CUDAExecutionProvider', stage: 'failed' }) + ) + }) + it('runs one prepare at a time, and needs an installed build', async () => { const { accelerators } = service() const first = accelerators.prepare({ accelerators: ['WebGpuExecutionProvider'] }) diff --git a/src/runtime/foundry-local/accelerators.ts b/src/runtime/foundry-local/accelerators.ts index a0dc19c0..27eb14f9 100644 --- a/src/runtime/foundry-local/accelerators.ts +++ b/src/runtime/foundry-local/accelerators.ts @@ -1,6 +1,7 @@ /** * Foundry Local's accelerators (openspec change `add-foundry-local`, task 6.4, design D3). The - * library finds and downloads them itself; core only decides when: a `probe` of the active build + * library discovers and downloads its provider bundles; core stages external CUDA dependencies and + * decides when to run a `probe` of the active build * when a client first asks or the active build changed, and a `prepare` when a client orders it — one * at a time, each step published as `foundry-local:accelerators`. * @@ -20,7 +21,9 @@ import type { FoundryLocalPrepareResult, } from '../../contracts/index.js' import { runFoundryHostPrepare, runFoundryHostProbe } from './host-process.js' -import type { FoundryHostCommand } from './host-process.js' +import type { FoundryHostCommand, FoundryHostPrepareSummary } from './host-process.js' +import { FOUNDRY_CUDA_EXECUTION_PROVIDER, withCudaRuntime } from './cuda/index.js' +import type { CudaRuntimeStore } from './cuda/index.js' export const ACCELERATORS_FILE = 'accelerators.json' @@ -41,6 +44,7 @@ export interface FoundryLocalAcceleratorDeps { emit: (name: 'foundry-local:accelerators', payload: CoreEvents['foundry-local:accelerators']) => void env?: NodeJS.ProcessEnv now?: () => number + cuda?: Pick } const EMPTY: AcceleratorsRecord = { prepared: [], failures: {}, updated_at: 0 } @@ -55,13 +59,14 @@ export class FoundryLocalAcceleratorService { } /** The names core recorded as prepared: what a load checks before it starts a host. */ - async prepared(): Promise { - return [...(await this.read()).prepared] + async prepared(build?: string): Promise { + const selected = build ?? (await this.deps.resolveBuild()) + return selected ? [...(await this.read(selected)).prepared] : [] } /** The last probe of the active build, with core's record of what is prepared; `force` probes again. */ - async list(options: { force?: boolean } = {}): Promise { - const build = await this.deps.resolveBuild() + async list(options: { force?: boolean; build?: string } = {}): Promise { + const build = options.build ?? (await this.deps.resolveBuild()) if (!build) return { installed: false, @@ -72,7 +77,7 @@ export class FoundryLocalAcceleratorService { accelerators: [], error: null, } - const record = await this.read() + const record = await this.read(build) if (!options.force && this.cache?.build === build) return this.withRecord(this.cache.answer, record) const name = `${basename(dirname(build))}/${basename(build)}` let answer: FoundryLocalAccelerators @@ -133,14 +138,8 @@ export class FoundryLocalAcceleratorService { 'BINARY_NOT_FOUND', 'Foundry Local is not installed; install it before preparing accelerators.' ) - const summary = await runFoundryHostPrepare( - this.deps.hostCommand, - { libDir: build, appDataDir: this.deps.runtimeDir, logsDir: this.deps.logsDir }, - request.accelerators ?? [], - (step) => this.deps.emit('foundry-local:accelerators', step), - this.deps.env ? { env: this.deps.env } : {} - ) - const record = await this.read() + const summary = await this.prepareHost(build, request.accelerators ?? []) + const record = await this.read(build) const prepared = new Set(record.prepared) const failures = { ...record.failures } for (const outcome of summary.accelerators) { @@ -152,7 +151,7 @@ export class FoundryLocalAcceleratorService { failures[outcome.name] = outcome.reason ?? 'Foundry Local did not register it.' } } - await this.write({ prepared: [...prepared], failures, updated_at: this.now() }) + await this.write(build, { prepared: [...prepared], failures, updated_at: this.now() }) // The library state changed: the next request probes again (spec: after install, update, prepare). this.cache = null return { accelerators: summary.accelerators } @@ -161,6 +160,58 @@ export class FoundryLocalAcceleratorService { } } + private async prepareHost(build: string, requested: string[]): Promise { + const target = { libDir: build, appDataDir: this.deps.runtimeDir, logsDir: this.deps.logsDir } + const env = this.deps.env ?? process.env + const emit = (step: CoreEvents['foundry-local:accelerators']) => + this.deps.emit('foundry-local:accelerators', step) + const run = (names: readonly string[]) => + runFoundryHostPrepare(this.deps.hostCommand, target, names, emit, { env }) + const cuda = this.deps.cuda + const accelerator = FOUNDRY_CUDA_EXECUTION_PROVIDER + if (!cuda?.supports(build) || (requested.length && !requested.includes(accelerator))) + return run(requested) + const offered = (await this.list({ build })).accelerators.map(({ name }) => name) + if (!offered.includes(accelerator)) return run(requested) + + const names = requested.length ? requested : offered + const otherNames = names.filter((name) => name !== accelerator) + // Let the other accelerators finish before a potentially long CUDA download. + const others = otherNames.length ? (await run(otherNames)).accelerators : [] + emit({ accelerator, stage: 'started', fraction: 0 }) + let outcomes: FoundryHostPrepareSummary['accelerators'] + try { + const dir = await cuda.prepare(build, (fraction) => + emit({ accelerator, stage: 'downloading', fraction: fraction / 2 }) + ) + const result = await runFoundryHostPrepare( + this.deps.hostCommand, + target, + [accelerator], + (step) => { + if (step.stage === 'started') return + emit( + step.stage === 'downloading' && step.fraction !== null + ? { ...step, fraction: 0.5 + step.fraction / 2 } + : step + ) + }, + { env: dir ? withCudaRuntime(env, build, dir) : env } + ) + outcomes = result.accelerators + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + emit({ accelerator, stage: 'failed', fraction: null, reason }) + outcomes = [{ name: accelerator, prepared: false, reason }] + } + let otherIndex = 0 + return { + accelerators: names.flatMap((name) => + name === accelerator ? outcomes : others.slice(otherIndex, ++otherIndex) + ), + } + } + private withRecord(answer: FoundryLocalAccelerators, record: AcceleratorsRecord): FoundryLocalAccelerators { return { ...answer, @@ -172,11 +223,17 @@ export class FoundryLocalAcceleratorService { } } - private async read(): Promise { + /** 2.1.0 keeps its legacy record readable by an older core after rollback. */ + private recordPath(build: string): string { + const tag = basename(dirname(build)) + return tag === 'v2.1.0' + ? join(this.deps.runtimeDir, ACCELERATORS_FILE) + : join(this.deps.runtimeDir, tag, basename(build), ACCELERATORS_FILE) + } + + private async read(build: string): Promise { try { - const raw = JSON.parse( - await readFile(join(this.deps.runtimeDir, ACCELERATORS_FILE), 'utf8') - ) as Partial + const raw = JSON.parse(await readFile(this.recordPath(build), 'utf8')) as Partial return { prepared: Array.isArray(raw.prepared) ? raw.prepared.filter((name): name is string => typeof name === 'string') @@ -193,9 +250,9 @@ export class FoundryLocalAcceleratorService { } /** Write-then-rename: a crash mid-write leaves the previous record, never half of one. */ - private async write(record: AcceleratorsRecord): Promise { - await mkdir(this.deps.runtimeDir, { recursive: true }) - const path = join(this.deps.runtimeDir, ACCELERATORS_FILE) + private async write(build: string, record: AcceleratorsRecord): Promise { + const path = this.recordPath(build) + await mkdir(dirname(path), { recursive: true }) const temporary = `${path}.tmp-${process.pid}` await writeFile(temporary, JSON.stringify(record, null, 2)) await rename(temporary, path) diff --git a/src/runtime/foundry-local/check.test.ts b/src/runtime/foundry-local/check.test.ts index fac6111a..c006bd53 100644 --- a/src/runtime/foundry-local/check.test.ts +++ b/src/runtime/foundry-local/check.test.ts @@ -55,7 +55,25 @@ describe('foundryLocalVerdict (task 6.5)', () => { 'gpu', 'platform-unsupported', ], - ['CUDA on Linux arm64', { platform: 'linux', arch: 'arm64' }, 'cuda', 'gpu', 'platform-unsupported'], + [ + 'CUDA on Linux ARM64 needs Foundry 2.4.0', + { platform: 'linux', arch: 'arm64', runtimeVersion: '2.1.0' }, + 'cuda', + 'gpu', + 'engine-update-required', + ], + [ + 'CUDA on Linux ARM64 can use the prepared Foundry 2.4.0 provider', + { + platform: 'linux', + arch: 'arm64', + runtimeVersion: '2.4.0', + accelerators: [ep('CUDAExecutionProvider', true)], + }, + 'cuda', + 'gpu', + 'ok', + ], [ 'an accelerator this core does not know (TensorRT-RTX)', {}, @@ -105,3 +123,38 @@ describe('parseFoundryLocalCheckRequest', () => { ) }) }) + +describe('Foundry minimum runtime version', () => { + const cpu = { execution_provider: 'cpu', device: 'cpu', min_runtime_version: '2.4.0' } + it.each([ + ['2.1.0', 'engine-update-required'], + ['2.4.0', 'ok'], + ['2.10.0', 'ok'], + ['2.3.99', 'engine-update-required'], + ] as const)('compares runtime %s numerically: %s', (runtimeVersion, verdict) => { + const result = foundryLocalVerdict({ ...WINDOWS_WITH_NPU, runtimeVersion }, cpu) + expect(result.verdict).toBe(verdict) + if (verdict === 'engine-update-required') { + expect(result.reason).toContain(runtimeVersion) + expect(result.reason).toContain('2.4.0') + } + }) + it('keeps missing-engine precedence and treats zero as no extra minimum', () => { + expect(foundryLocalVerdict({ ...WINDOWS_WITH_NPU, installed: false }, cpu).verdict).toBe( + 'engine-not-installed' + ) + expect( + foundryLocalVerdict( + { ...WINDOWS_WITH_NPU, runtimeVersion: '2.1.0' }, + { ...cpu, min_runtime_version: '0.0.0' } + ).verdict + ).toBe('ok') + }) + it('parses an optional valid minimum and rejects invalid direct requests', () => { + expect(parseFoundryLocalCheckRequest(cpu)).toEqual(cpu) + for (const value of [null, 2.4, '', '2.4', 'v2.4.0', '2.4.0-beta', ' 2.4.0 ']) + expect(() => parseFoundryLocalCheckRequest({ ...cpu, min_runtime_version: value })).toThrow( + expect.objectContaining({ code: 'INVALID_ARGUMENT' }) + ) + }) +}) diff --git a/src/runtime/foundry-local/check.ts b/src/runtime/foundry-local/check.ts index e61f1e97..d75ac582 100644 --- a/src/runtime/foundry-local/check.ts +++ b/src/runtime/foundry-local/check.ts @@ -11,14 +11,17 @@ import type { FoundryLocalCheckResult, FoundryLocalExecutionProvider, } from '../../contracts/index.js' +import { compareVersions } from '../../backend/index.js' import { executionProvider } from './host/execution-providers.js' -import { variantRunsOn } from './runtime.js' +import { minimumFoundryVariantRuntime, variantRunsOn } from './runtime.js' export interface FoundryLocalCheckFacts { platform: NodeJS.Platform arch: string /** A Foundry Local build is installed and active. */ installed: boolean + /** The active runtime version, not the core npm version. */ + runtimeVersion?: string /** The last probe's accelerators, with core's record of what is prepared. */ accelerators: readonly FoundryLocalAccelerator[] /** An NPU on this machine (`probeNpu`); `null` when unknown — the probe's list decides then. */ @@ -51,6 +54,22 @@ export function foundryLocalVerdict( reason: 'Foundry Local is not installed on this computer.', accelerator, } + const platformMinimum = minimumFoundryVariantRuntime(facts.platform, facts.arch, short) + const requestedMinimum = request.min_runtime_version + const minimum = + requestedMinimum && (!platformMinimum || compareVersions(requestedMinimum, platformMinimum) > 0) + ? requestedMinimum + : platformMinimum + if ( + minimum && + minimum !== '0.0.0' && + (!facts.runtimeVersion || compareVersions(facts.runtimeVersion, minimum) < 0) + ) + return { + verdict: 'engine-update-required', + reason: `Foundry Local ${facts.runtimeVersion ?? 'unknown'} is active; this model requires ${minimum} or newer.`, + accelerator, + } if (accelerator === null) return { verdict: 'ok', reason: null, accelerator: null } if (request.device === 'npu' && facts.npu === false) return { verdict: 'accelerator-unavailable', reason: 'This computer has no NPU.', accelerator } @@ -70,7 +89,7 @@ export function foundryLocalVerdict( return { verdict: 'ok', reason: null, accelerator } } -/** The request body, strictly: the accelerator and the device as text, nothing else. */ +/** The request body, strictly: the accelerator, device and optional runtime minimum. */ export function parseFoundryLocalCheckRequest(body: unknown): FoundryLocalCheckRequest { const invalid = (why: string): never => { throw new AtomicCoreError('INVALID_ARGUMENT', why) @@ -78,11 +97,20 @@ export function parseFoundryLocalCheckRequest(body: unknown): FoundryLocalCheckR if (typeof body !== 'object' || body === null || Array.isArray(body)) return invalid('The request body must be a JSON object.') const record = body as Record - const extra = Object.keys(record).filter((key) => key !== 'execution_provider' && key !== 'device') + const extra = Object.keys(record).filter( + (key) => key !== 'execution_provider' && key !== 'device' && key !== 'min_runtime_version' + ) if (extra.length > 0) invalid(`The request has fields this core does not know: ${extra.sort().join(', ')}.`) const { execution_provider: executionProvider, device } = record if (typeof executionProvider !== 'string' || executionProvider === '') invalid('execution_provider is required.') if (typeof device !== 'string' || device === '') invalid('device is required.') - return { execution_provider: executionProvider as string, device: device as string } + const minimum = record['min_runtime_version'] + if (minimum !== undefined && (typeof minimum !== 'string' || !/^\d+\.\d+\.\d+$/.test(minimum))) + invalid('min_runtime_version must be a version in X.Y.Z format.') + return { + execution_provider: executionProvider as string, + device: device as string, + ...(typeof minimum === 'string' ? { min_runtime_version: minimum } : {}), + } } diff --git a/src/runtime/foundry-local/cuda/host-env.test.ts b/src/runtime/foundry-local/cuda/host-env.test.ts new file mode 100644 index 00000000..5cb4055e --- /dev/null +++ b/src/runtime/foundry-local/cuda/host-env.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { withCudaRuntime } from './host-env.js' + +describe('withCudaRuntime', () => { + it('prepends the verified directory to the Windows host PATH without adding a second casing', () => { + const original = { Path: 'C:\\Windows\\System32', Other: 'keep' } + expect(withCudaRuntime(original, '/build/v2.4.0/win-x64', 'C:\\cache\\cuda')).toEqual({ + Path: 'C:\\cache\\cuda;C:\\Windows\\System32', + ATOMIC_FOUNDRY_CUDA_CACHE_DIR: 'C:\\cache\\cuda', + Other: 'keep', + }) + expect(original.Path).toBe('C:\\Windows\\System32') + }) + + it('sets the Linux loader path on the host environment before spawn', () => { + expect( + withCudaRuntime({ LD_LIBRARY_PATH: '/usr/local/lib' }, '/build/v2.4.0/linux-x64', '/cache/cuda') + ).toEqual({ + LD_LIBRARY_PATH: '/cache/cuda:/usr/local/lib', + }) + }) +}) diff --git a/src/runtime/foundry-local/cuda/host-env.ts b/src/runtime/foundry-local/cuda/host-env.ts new file mode 100644 index 00000000..79ce2a78 --- /dev/null +++ b/src/runtime/foundry-local/cuda/host-env.ts @@ -0,0 +1,20 @@ +import { basename } from 'node:path' + +export const FOUNDRY_CUDA_CACHE_DIR = 'ATOMIC_FOUNDRY_CUDA_CACHE_DIR' + +export function withCudaRuntime( + env: Env, + build: string, + directory: string +): Env { + const windows = basename(build).startsWith('win-') + const key = windows + ? (Object.keys(env).find((key) => key.toUpperCase() === 'PATH') ?? 'Path') + : 'LD_LIBRARY_PATH' + const current = env[key] + return { + ...env, + ...(windows ? { [FOUNDRY_CUDA_CACHE_DIR]: directory } : {}), + [key]: current ? `${directory}${windows ? ';' : ':'}${current}` : directory, + } +} diff --git a/src/runtime/foundry-local/cuda/index.ts b/src/runtime/foundry-local/cuda/index.ts new file mode 100644 index 00000000..9829f268 --- /dev/null +++ b/src/runtime/foundry-local/cuda/index.ts @@ -0,0 +1,5 @@ +export { CudaRuntimeStore } from './store.js' + +export const FOUNDRY_CUDA_EXECUTION_PROVIDER = 'CUDAExecutionProvider' + +export { FOUNDRY_CUDA_CACHE_DIR, withCudaRuntime } from './host-env.js' diff --git a/src/runtime/foundry-local/cuda/linux-pins.ts b/src/runtime/foundry-local/cuda/linux-pins.ts new file mode 100644 index 00000000..bfa8cd40 --- /dev/null +++ b/src/runtime/foundry-local/cuda/linux-pins.ts @@ -0,0 +1,206 @@ +import type { CudaArchive } from './pins.js' + +// NVIDIA publishes the ELF runtimes as ZIP-format wheels with real SONAME files. Core +// extracts those files directly, so installing them needs neither Python nor an xz tool. +function wheel( + component: string, + url: string, + size: number, + sha256: string, + bin: string, + libraries: Record, + license: string, + noticeSize: number +): CudaArchive { + return { + url, + size, + sha256, + files: [ + ...Object.entries(libraries).map(([name, size]) => ({ entry: `${bin}/${name}`, name, size })), + { entry: license, name: `${component}.LICENSE`, size: noticeSize }, + ], + } +} + +export const LINUX_X64_CUDA: readonly CudaArchive[] = [ + wheel( + 'cuda-runtime', + 'https://files.pythonhosted.org/packages/bc/46/a92db19b8309581092a3add7e6fceb4c301a3fd233969856a8cbf042cd3c/nvidia_cuda_runtime_cu12-12.9.79-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl', + 3493179, + '25bba2dfb01d48a9b59ca474a1ac43c6ebf7011f1b0b8cc44f54eb6ac48a96c3', + 'nvidia/cuda_runtime/lib', + { + 'libcudart.so.12': 741088, + }, + 'nvidia_cuda_runtime_cu12-12.9.79.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cublas', + 'https://files.pythonhosted.org/packages/77/3c/aa88abe01f3be3d1f8f787d1d33dc83e76fec05945f9a28fbb41cfb99cd5/nvidia_cublas_cu12-12.9.1.4-py3-none-manylinux_2_27_x86_64.whl', + 581242350, + '453611eb21a7c1f2c2156ed9f3a45b691deda0440ec550860290dc901af5b4c2', + 'nvidia/cublas/lib', + { + 'libcublas.so.12': 105140976, + 'libcublasLt.so.12': 749205904, + }, + 'nvidia_cublas_cu12-12.9.1.4.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cufft', + 'https://files.pythonhosted.org/packages/95/f4/61e6996dd20481ee834f57a8e9dca28b1869366a135e0d42e2aa8493bdd4/nvidia_cufft_cu12-11.4.1.4-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl', + 200877592, + 'c67884f2a7d276b4b80eb56a79322a95df592ae5e765cf1243693365ccab4e28', + 'nvidia/cufft/lib', + { + 'libcufft.so.11': 291507928, + }, + 'nvidia_cufft_cu12-11.4.1.4.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'curand', + 'https://files.pythonhosted.org/packages/31/44/193a0e171750ca9f8320626e8a1f2381e4077a65e69e2fb9708bd479e34a/nvidia_curand_cu12-10.3.10.19-py3-none-manylinux_2_27_x86_64.whl', + 68295626, + '49b274db4780d421bd2ccd362e1415c13887c53c214f0d4b761752b8f9f6aa1e', + 'nvidia/curand/lib', + { + 'libcurand.so.10': 166965432, + }, + 'nvidia_curand_cu12-10.3.10.19.dist-info/License.txt', + 59262 + ), + wheel( + 'cuda-nvrtc', + 'https://files.pythonhosted.org/packages/b8/85/e4af82cc9202023862090bfca4ea827d533329e925c758f0cde964cb54b7/nvidia_cuda_nvrtc_cu12-12.9.86-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl', + 89568129, + '210cf05005a447e29214e9ce50851e83fc5f4358df8b453155d5e1918094dcb4', + 'nvidia/cuda_nvrtc/lib', + { + 'libnvrtc-builtins.so.12.9': 7202760, + 'libnvrtc.so.12': 106244480, + }, + 'nvidia_cuda_nvrtc_cu12-12.9.86.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cudnn', + 'https://files.pythonhosted.org/packages/3b/52/94aecda69df65ba1079a8b7dbe84632af5614dc0ed2c733185f6431874e3/nvidia_cudnn_cu12-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl', + 657910570, + '7d7479e1321c7a039b33827f0247791ee1be091759032c1f66a287c4a643396a', + 'nvidia/cudnn/lib', + { + 'libcudnn.so.9': 129240, + 'libcudnn_adv.so.9': 272749720, + 'libcudnn_cnn.so.9': 4203784, + 'libcudnn_engines_precompiled.so.9': 515924288, + 'libcudnn_engines_runtime_compiled.so.9': 31483576, + 'libcudnn_graph.so.9': 4460064, + 'libcudnn_heuristic.so.9': 60822016, + 'libcudnn_ops.so.9': 106964632, + }, + 'nvidia_cudnn_cu12-9.20.0.48.dist-info/licenses/License.txt', + 18174 + ), +] + +export const LINUX_ARM64_CUDA: readonly CudaArchive[] = [ + wheel( + 'cuda-runtime', + 'https://files.pythonhosted.org/packages/51/3b/2c6e9d88efa7b3585572760bca5e7da83fa9e06098a9386c7b29c81c46b2/nvidia_cuda_runtime-13.4.92-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl', + 2509438, + 'bef071788589550ab02846fcbc732a2b88c2b16f2cd8a0f45d98e68e8c5fb0c8', + 'nvidia/cu13/lib', + { + 'libcudart.so.13': 793872, + }, + 'nvidia_cuda_runtime-13.4.92.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cublas', + 'https://files.pythonhosted.org/packages/c9/9e/0c73b14c14cd32e8b3a028133371f4bf1d9d14b811c515c5fd1201a3c38d/nvidia_cublas-13.8.0.4-py3-none-manylinux_2_27_aarch64.whl', + 552729449, + 'e22b25be18f8b7d267dbbe2a8ec78e2c69c05762536d299dd0afa2c847115740', + 'nvidia/cu13/lib', + { + 'libcublas.so.13': 71959256, + 'libcublasLt.so.13': 648206104, + }, + 'nvidia_cublas-13.8.0.4.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cufft', + 'https://files.pythonhosted.org/packages/41/f1/bb8cc4e1ffee345a51fe4cf656352bc705274431dcbd6c23ed9f00585ec7/nvidia_cufft-12.4.0.43-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl', + 161750525, + '3938644a5b594e06d396e02d6e52bdd84589b3c1f3a8a127a2704211c2abc441', + 'nvidia/cu13/lib', + { + 'libcufft.so.12': 231611600, + }, + 'nvidia_cufft-12.4.0.43.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'curand', + 'https://files.pythonhosted.org/packages/e8/9d/42faff77e90e5498eecb9b099894d5deea744b3d6b35e700dafd0381e07a/nvidia_curand-10.4.4.72-py3-none-manylinux_2_27_aarch64.whl', + 63771251, + '53bef256d4362eb3d70c9c048a8d31bcf003f9dcade17720c73d3a494a7dcaa3', + 'nvidia/cu13/lib', + { + 'libcurand.so.10': 136236248, + }, + 'nvidia_curand-10.4.4.72.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cuda-nvrtc', + 'https://files.pythonhosted.org/packages/4f/73/cf76dc0083d68bd1e29309bc51fc95ada28d4b64d341e945eb3f8ec8edec/nvidia_cuda_nvrtc-13.4.92-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl', + 50927348, + '24b9f5eccc6a5a19779038cf468aecb7cecfa8716269beaef5640bd989d21c28', + 'nvidia/cu13/lib', + { + 'libnvrtc-builtins.so.13.4': 7108392, + 'libnvrtc.so.13': 115809136, + }, + 'nvidia_cuda_nvrtc-13.4.92.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'nvjitlink', + 'https://files.pythonhosted.org/packages/1f/a8/1cbd4014898af8b419e69b0d7dbc63da2121ee92d92b47d59f4fe9075349/nvidia_nvjitlink-13.4.92-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl', + 40420120, + '25f74fad0d654271c921ac4dca614bd6258bc21791242fc7b2289dad7ae9c099', + 'nvidia/cu13/lib', + { + 'libnvJitLink.so.13': 93911560, + }, + 'nvidia_nvjitlink-13.4.92.dist-info/licenses/License.txt', + 59262 + ), + wheel( + 'cudnn', + 'https://files.pythonhosted.org/packages/fb/de/5038a69d0f35f75b28d00d7de9ea219969096b11812bbb3097604059b9a6/nvidia_cudnn_cu13-9.25.1.1-py3-none-manylinux_2_27_aarch64.whl', + 601067473, + '6ed974d46b1b5fd123c0d9ff031c857142aa94257c6df41c40f6b5fd11a01d50', + 'nvidia/cudnn/lib', + { + 'libcudnn.so.9': 6329600, + 'libcudnn_adv.so.9': 140627624, + 'libcudnn_cnn.so.9': 2501816, + 'libcudnn_engines_precompiled.so.9': 316686752, + 'libcudnn_engines_runtime_compiled.so.9': 39867664, + 'libcudnn_engines_tensor_ir.so.9': 211822608, + 'libcudnn_ext.so.9': 2039600, + 'libcudnn_graph.so.9': 128140800, + 'libcudnn_heuristic.so.9': 65015144, + 'libcudnn_ops.so.9': 54537056, + }, + 'nvidia_cudnn_cu13-9.25.1.1.dist-info/licenses/License.txt', + 18174 + ), +] diff --git a/src/runtime/foundry-local/cuda/pins.ts b/src/runtime/foundry-local/cuda/pins.ts new file mode 100644 index 00000000..971151d3 --- /dev/null +++ b/src/runtime/foundry-local/cuda/pins.ts @@ -0,0 +1,128 @@ +import { LINUX_ARM64_CUDA, LINUX_X64_CUDA } from './linux-pins.js' + +export interface CudaArchive { + url: string + size: number + sha256: string + files: readonly { entry: string; name: string; size: number }[] +} + +function windowsArchive( + component: string, + version: string, + size: number, + sha256: string, + bin: string, + dlls: Record, + noticeSize: number, + arch = 'x86_64' +): CudaArchive { + const stem = `${component}-windows-${arch}-${version}-archive` + const product = component === 'cudnn' ? 'cudnn' : 'cuda' + return { + url: `https://developer.download.nvidia.com/compute/${product}/redist/${component}/windows-${arch}/${stem}.zip`, + size, + sha256, + files: [ + ...Object.entries(dlls).map(([name, size]) => ({ entry: `${stem}/${bin}/${name}`, name, size })), + { entry: `${stem}/LICENSE`, name: `${component}.LICENSE`, size: noticeSize }, + ], + } +} + +// NVIDIA redistrib_12.8.1.json and cuDNN redistrib_9.20.0.json (CUDA 12 variant). +export const WINDOWS_X64_CUDA: readonly CudaArchive[] = [ + windowsArchive( + 'cuda_cudart', + '12.8.90', + 3037735, + '4a39058fd8519444a81cfc7ae055d136f48d1a31ffa41ae255b35b2edd61e13b', + 'bin', + { 'cudart64_12.dll': 573952 }, + 63021 + ), + windowsArchive( + 'libcublas', + '12.8.4.1', + 563660944, + '57a470112cec7e112c95253dde8b3c7184d795dbd92b0bde77a4cb7f8c94c8aa', + 'bin', + { 'cublas64_12.dll': 113716224, 'cublasLt64_12.dll': 674667520 }, + 63021 + ), + windowsArchive( + 'cudnn', + '9.20.0.48_cuda12', + 634960681, + '003a5d022899268f7deef0c3530f1587a3195a93905a16fd0e3c9da0c46b88ab', + 'bin/x64', + { + 'cudnn64_9.dll': 264304, + 'cudnn_adv64_9.dll': 269016688, + 'cudnn_cnn64_9.dll': 2984560, + 'cudnn_engines_precompiled64_9.dll': 480614000, + 'cudnn_engines_runtime_compiled64_9.dll': 27769456, + 'cudnn_graph64_9.dll': 2535536, + 'cudnn_heuristic64_9.dll': 58882672, + 'cudnn_ops64_9.dll': 105600624, + }, + 29574 + ), +] + +// NVIDIA CUDA 13.4 Update 2 and the corresponding cuDNN 9.25 redistribution ZIPs. +const WINDOWS_ARM64_CUDA: readonly CudaArchive[] = [ + windowsArchive( + 'cuda_cudart', + '13.4.92', + 2772086, + 'd3cec2717ba3c2c714c5869a5374365d087c698d87c0ddd3bd41715447112891', + 'bin/arm64', + { + 'cudart64_13.dll': 606832, + }, + 69791, + 'arm64' + ), + windowsArchive( + 'libcublas', + '13.8.0.4', + 153929951, + 'ec79698528f64361a370d1b0254a927e369b57525831fadcb2cdb7732d8ab621', + 'bin/arm64', + { + 'cublas64_13.dll': 24142448, + 'cublasLt64_13.dll': 194595440, + }, + 69791, + 'arm64' + ), + windowsArchive( + 'cudnn', + '9.25.1.1_cuda13.4', + 433715143, + 'be292b95ad6511aa01ada7094d16eee78acd69369d996586366d82ffe53b16c7', + 'bin/arm64', + { + 'cudnn64_9.dll': 271472, + 'cudnn_adv64_9.dll': 23012976, + 'cudnn_cnn64_9.dll': 627824, + 'cudnn_engines_precompiled64_9.dll': 61971568, + 'cudnn_engines_runtime_compiled64_9.dll': 32155760, + 'cudnn_engines_tensor_ir64_9.dll': 150128, + 'cudnn_ext64_9.dll': 137840, + 'cudnn_graph64_9.dll': 107633776, + 'cudnn_heuristic64_9.dll': 58245232, + 'cudnn_ops64_9.dll': 13165168, + }, + 29574, + 'arm64' + ), +] + +export const CUDA_ARCHIVES: Readonly> = { + 'win-x64': WINDOWS_X64_CUDA, + 'win-arm64': WINDOWS_ARM64_CUDA, + 'linux-x64': LINUX_X64_CUDA, + 'linux-arm64': LINUX_ARM64_CUDA, +} diff --git a/src/runtime/foundry-local/cuda/store.test.ts b/src/runtime/foundry-local/cuda/store.test.ts new file mode 100644 index 00000000..86ccf314 --- /dev/null +++ b/src/runtime/foundry-local/cuda/store.test.ts @@ -0,0 +1,86 @@ +import { createHash } from 'node:crypto' +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makeZip } from '../../../../test/helpers/make-zip.js' +import { CudaRuntimeStore } from './store.js' + +let root: string +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'atomic-cuda-')) +}) +afterEach(() => rm(root, { recursive: true, force: true })) + +function fixture(files = ['cudart64_12.dll'], badHash = false) { + const url = 'https://developer.download.nvidia.com/cuda-test.zip' + const archive = makeZip([ + { name: 'runtime/bin/cudart64_12.dll', data: Buffer.from('DLL') }, + { name: 'runtime/lib/unneeded.lib', data: Buffer.from('SDK') }, + { name: 'runtime/LICENSE', data: Buffer.from('Notice') }, + ]) + const fetcher = vi.fn( + async (_url, init) => + new Response(init?.method === 'HEAD' ? null : archive, { + headers: { 'content-length': String(archive.length) }, + }) + ) + const build = join(root, 'backends', 'v2.4.0', 'win-x64') + const store = new CudaRuntimeStore({ + runtimeDir: join(root, 'runtime'), + platform: 'win32', + fetch: fetcher, + archives: [ + { + url, + size: archive.length, + sha256: badHash ? '0'.repeat(64) : createHash('sha256').update(archive).digest('hex'), + files: [ + ...files.map((name) => ({ entry: `runtime/bin/${name}`, name, size: 3 })), + { entry: 'runtime/LICENSE', name: 'cuda-test.LICENSE', size: 6 }, + ], + }, + ], + }) + return { store, build, fetcher } +} + +describe('CudaRuntimeStore', () => { + it.each([ + ['win32', 'v2.4.0', 'win-x64', true], + ['win32', 'v2.4.0', 'win-arm64', true], + ['linux', 'v2.4.0', 'linux-x64', true], + ['linux', 'v2.4.0', 'linux-arm64', true], + ['linux', 'v2.1.0', 'linux-arm64', false], + ['linux', 'v2.4.0', 'win-x64', false], + ['darwin', 'v2.4.0', 'macos-arm64', false], + ] as const)('scopes CUDA preparation to %s %s/%s', (platform, tag, target, expected) => { + const store = new CudaRuntimeStore({ runtimeDir: root, platform, fetch }) + expect(store.supports(join(root, 'backends', tag, target))).toBe(expected) + }) + + it('only installs the pinned runtime DLLs and notice, and reuses them offline', async () => { + const { store, build, fetcher } = fixture() + expect(await store.cached(build)).toBeUndefined() + expect(fetcher).not.toHaveBeenCalled() + const dir = await store.prepare(build, () => {}) + expect(await readFile(join(dir!, 'cudart64_12.dll'), 'utf8')).toBe('DLL') + expect(await readdir(dir!)).toEqual(['cuda-test.LICENSE', 'cudart64_12.dll']) + fetcher.mockClear() + expect(await store.cached(build)).toBe(dir) + expect(await store.prepare(build, () => {})).toBe(dir) + expect(fetcher).not.toHaveBeenCalled() + }) + + it('rejects a mismatching archive hash before publishing DLLs', async () => { + const { store, build } = fixture(undefined, true) + await expect(store.prepare(build, () => {})).rejects.toThrow(/hash verification failed/i) + expect(await store.cached(build)).toBeUndefined() + }) + + it('never publishes an incomplete DLL set', async () => { + const { store, build } = fixture(['cudart64_12.dll', 'missing.dll']) + await expect(store.prepare(build, () => {})).rejects.toThrow('missing.dll') + expect(await store.cached(build)).toBeUndefined() + }) +}) diff --git a/src/runtime/foundry-local/cuda/store.ts b/src/runtime/foundry-local/cuda/store.ts new file mode 100644 index 00000000..e8ff682d --- /dev/null +++ b/src/runtime/foundry-local/cuda/store.ts @@ -0,0 +1,133 @@ +import { createHash } from 'node:crypto' +import { createWriteStream } from 'node:fs' +import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises' +import { basename, dirname, join } from 'node:path' +import { pipeline } from 'node:stream/promises' +import yauzl from 'yauzl' +import { Downloader } from '../../../downloads/index.js' +import { CUDA_ARCHIVES } from './pins.js' +import type { CudaArchive } from './pins.js' + +const fileMatches = async (path: string, size: number): Promise => { + const info = await lstat(path).catch(() => undefined) + return info?.isFile() === true && info.size === size +} + +function extractPinnedZip(path: string, archive: CudaArchive, output: string): Promise { + const remaining = new Map(archive.files.map((file) => [file.entry, file])) + return new Promise((resolve, reject) => { + yauzl.open(path, { lazyEntries: true, strictFileNames: true }, (error, zip) => { + if (error || !zip) return reject(error ?? new Error('Failed to open NVIDIA archive.')) + const fail = (error: Error) => { + zip.close() + reject(error) + } + zip.on('error', fail) + zip.on('end', () => { + if (remaining.size) + reject(new Error(`NVIDIA archive is missing ${[...remaining.keys()].join(', ')}.`)) + else resolve() + }) + zip.on('entry', (entry) => { + const file = remaining.get(entry.fileName) + if (!file) return zip.readEntry() + const kind = (entry.externalFileAttributes >>> 16) & 0o170000 + if (entry.uncompressedSize !== file.size || (kind !== 0 && kind !== 0o100000)) + return fail(new Error(`Invalid NVIDIA archive member: ${entry.fileName}.`)) + zip.openReadStream(entry, (error, stream) => { + if (error || !stream) return fail(error ?? new Error(`Failed to read ${entry.fileName}.`)) + pipeline(stream, createWriteStream(join(output, file.name), { flags: 'wx' })).then(() => { + remaining.delete(file.entry) + zip.readEntry() + }, fail) + }) + }) + zip.readEntry() + }) + }) +} + +export class CudaRuntimeStore { + constructor( + private readonly options: { + runtimeDir: string + platform: NodeJS.Platform + fetch: typeof fetch + archives?: readonly CudaArchive[] + } + ) {} + + private archives(build: string): readonly CudaArchive[] | undefined { + const target = basename(build) + const os = this.options.platform === 'win32' ? 'win' : this.options.platform + if (basename(dirname(build)) !== 'v2.4.0' || !target.startsWith(`${os}-`)) return undefined + const pins = CUDA_ARCHIVES[target] + return pins && (this.options.archives ?? pins) + } + + supports(build: string): boolean { + return this.archives(build) !== undefined + } + + private directory(build: string, archives: readonly CudaArchive[]): string { + const revision = createHash('sha256').update(JSON.stringify(archives)).digest('hex').slice(0, 16) + return join(this.options.runtimeDir, basename(dirname(build)), basename(build), 'cuda', revision) + } + + /** Offline lookup. The complete directory is only published after archive verification and extraction. */ + async cached(build: string): Promise { + const archives = this.archives(build) + if (!archives) return undefined + const dir = this.directory(build, archives) + const info = await lstat(dir).catch(() => undefined) + if (!info?.isDirectory()) return undefined + const files = archives.flatMap((archive) => archive.files) + return (await Promise.all(files.map((file) => fileMatches(join(dir, file.name), file.size)))).every( + Boolean + ) + ? dir + : undefined + } + + async prepare(build: string, onProgress: (fraction: number) => void): Promise { + const archives = this.archives(build) + if (!archives) return undefined + const cached = await this.cached(build) + if (cached) return cached + const dir = this.directory(build, archives) + await mkdir(dirname(dir), { recursive: true }) + const staging = await mkdtemp(join(dirname(dir), '.incoming-')) + try { + const output = join(staging, 'runtime') + await mkdir(output) + const downloader = new Downloader({ + dataFolder: staging, + platform: this.options.platform, + fetch: this.options.fetch, + emit: (event, payload) => { + if (event === 'download:progress' && 'percent' in payload) onProgress(payload.percent / 100) + }, + }) + await downloader.download( + 'foundry-cuda-runtime', + archives.map((archive, index) => ({ + url: archive.url, + save_path: `${index}.zip`, + size: archive.size, + sha256: archive.sha256, + })), + { resume: true } + ) + for (const [index, archive] of archives.entries()) { + const path = join(staging, `${index}.zip`) + await extractPinnedZip(path, archive, output) + await rm(path) + } + await rm(dir, { recursive: true, force: true }) + await rename(output, dir) + return dir + } finally { + await rm(staging, { recursive: true, force: true }) + } + } +} diff --git a/src/runtime/foundry-local/host/ffi-bun.ts b/src/runtime/foundry-local/host/ffi-bun.ts index e63ce829..1a0ae7f2 100644 --- a/src/runtime/foundry-local/host/ffi-bun.ts +++ b/src/runtime/foundry-local/host/ffi-bun.ts @@ -4,7 +4,7 @@ * imported dynamically by the `foundry-host` mode alone, so the npm package still loads under Node. * * The library exports three symbols; everything else is a table of function pointers (`flApi` and its - * sub-APIs), read here by index. Indices follow `foundry_local_c.h` of C API version 2: tables only + * sub-APIs), read here by index. Indices follow `foundry_local_c.h` of C API versions 2 and 3: tables only * ever grow at the end, so a library that grants version 2 keeps these positions. * * Proven by the spike (rulings S1, S2): progress callbacks must not be `threadsafe` — the native caller @@ -14,9 +14,12 @@ import { CFunction, CString, dlopen, FFIType, JSCallback, ptr, read } from 'bun:ffi' import type { NativeArgument, Pointer } from 'bun:ffi' -import { existsSync } from 'node:fs' +import { existsSync, readdirSync } from 'node:fs' import { join } from 'node:path' -import { FoundryLibraryError } from './library.js' +import { foundryWindowsCudaCache, foundryWindowsDllDirectories } from './windows-dlls.js' +import { FoundryLibraryError, selectFoundryApi } from './library.js' +import { requiresBundledOpenVino, withBundledOpenVino } from './openvino.js' +import { ensureMacWebGpu, requiresMacWebGpu, withMacWebGpu } from './webgpu/index.js' import type { DiscoverableEp, FoundryLibrary, @@ -27,9 +30,6 @@ import type { ModelMetadata, } from './library.js' -/** The `FOUNDRY_LOCAL_API_VERSION` these bindings are written against. */ -export const BOUND_C_API_VERSION = 2 - const POINTER = 8 const CATALOG_LOCAL = 1 /** `flEpInfo`: u32 version, padding, `const char* name` at 8, `bool is_registered` at 16. */ @@ -87,6 +87,40 @@ const cstr = (value: string): Buffer => Buffer.from(`${value}\0`, 'utf8') const outPointer = (): BigUint64Array => new BigUint64Array(1) const deref = (out: BigUint64Array): Pointer => Number(out[0]) +function windowsSystemCudaDirectories(): string[] { + const children = (dir: string): string[] => { + try { + return readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + } catch { + return [] + } + } + const discovered: string[] = [] + const programFiles = process.env['ProgramFiles'] ?? 'C:\\Program Files' + const cudaRoot = join(programFiles, 'NVIDIA GPU Computing Toolkit', 'CUDA') + const cudnnRoot = join(programFiles, 'NVIDIA', 'CUDNN') + for (const version of children(cudaRoot).filter((version) => /^v12(?:\.|$)/.test(version))) + discovered.push(join(cudaRoot, version, 'bin'), join(cudaRoot, version, 'bin', 'x64')) + const cudnnRoots = [ + ...children(cudnnRoot) + .filter((version) => /^v9(?:\.|$)/.test(version)) + .map((version) => join(cudnnRoot, version)), + ...(process.env['CUDNN_PATH'] ? [process.env['CUDNN_PATH']] : []), + ] + for (const root of cudnnRoots) { + const bin = join(root, 'bin') + discovered.push( + bin, + ...children(bin) + .filter((version) => /^12(?:\.|$)/.test(version)) + .map((version) => join(bin, version)) + ) + } + return discovered +} + export const loadBunFoundryLibrary: LoadFoundryLibrary = async (libDir) => { const file = LIBRARY_FILE[process.platform] if (!file) throw new FoundryLibraryError('load', 0, `Foundry Local has no library for ${process.platform}`) @@ -94,26 +128,197 @@ export const loadBunFoundryLibrary: LoadFoundryLibrary = async (libDir) => { if (!existsSync(path)) throw new FoundryLibraryError('load', 0, `${path} not found: no ${file} in this build`) if (process.platform === 'win32') { - // The loader does not search the DLL's own folder for onnxruntime.dll and its siblings (error 126). - const kernel32 = dlopen('kernel32.dll', { SetDllDirectoryW: { args: [T.ptr], returns: T.i32 } }) - kernel32.symbols.SetDllDirectoryW(ptr(Buffer.from(`${libDir}\0`, 'utf16le'))) + // All loader changes stay in this child. Keep the build's dependencies and PATH providers, + // and expose CUDA/cuDNN directories to LoadLibraryEx(LOAD_LIBRARY_SEARCH_USER_DIRS). + const kernel32 = dlopen('kernel32.dll', { + SetDllDirectoryW: { args: [T.ptr], returns: T.i32 }, + SetDefaultDllDirectories: { args: [T.u32], returns: T.i32 }, + AddDllDirectory: { args: [T.ptr], returns: T.ptr }, + LoadLibraryExW: { args: [T.ptr, T.ptr, T.u32], returns: T.ptr }, + GetLastError: { args: [], returns: T.u32 }, + }) + const wide = (value: string) => ptr(Buffer.from(`${value}\0`, 'utf16le')) + if (!kernel32.symbols.SetDllDirectoryW(wide(libDir))) + throw new FoundryLibraryError('load', 0, 'Windows could not configure the Foundry DLL directory') + const cudaCache = foundryWindowsCudaCache(process.env) + // A managed CUDA host searches only the Foundry build, its CUDA cache and System32. + // AddDllDirectory does not promise an order when several directories supply the same DLL. + const searchFlags = cudaCache ? 0x0c00 : 0x1000 + if (process.arch === 'x64' || cudaCache) { + const discovered = cudaCache ? [] : windowsSystemCudaDirectories() + if (!kernel32.symbols.SetDefaultDllDirectories(searchFlags)) + throw new FoundryLibraryError('load', 0, 'Windows could not configure the Foundry DLL search path') + for (const dir of foundryWindowsDllDirectories(libDir, process.env, discovered)) { + if (dir === cudaCache) { + if (!kernel32.symbols.AddDllDirectory(wide(dir))) + throw new FoundryLibraryError( + 'load', + 0, + `Windows could not open the Foundry CUDA cache at ${dir}.` + ) + } else if (existsSync(dir)) { + kernel32.symbols.AddDllDirectory(wide(dir)) + } + } + } + // DLL_LOAD_DIR precedes the process search path for dependencies. In particular, Windows' + // own onnxruntime.dll must not replace the newer ORT shipped beside foundry_local.dll. + // Keep this handle for the child's lifetime; dlopen below binds the already loaded module. + if (!kernel32.symbols.LoadLibraryExW(wide(path), null, 0x100 | searchFlags)) + throw new FoundryLibraryError( + 'load', + 0, + `Windows could not load ${path} and its dependencies (error ${String(kernel32.symbols.GetLastError())})` + ) } const library = dlopen(path, { FoundryLocalGetApi: { args: [T.u32], returns: T.ptr }, FoundryLocalGetVersionString: { args: [], returns: T.cstring }, }) const version = String(library.symbols.FoundryLocalGetVersionString()) - const api = library.symbols.FoundryLocalGetApi(BOUND_C_API_VERSION) as Pointer | null - if (!api) - throw new FoundryLibraryError( - 'FoundryLocalGetApi', - 0, - `Foundry Local ${version} does not provide C API version ${BOUND_C_API_VERSION}` - ) - return bindLibrary(api, version) + const { api, cApiVersion } = selectFoundryApi( + version, + (requested) => library.symbols.FoundryLocalGetApi(requested) as Pointer | null + ) + return bindLibrary(api, version, cApiVersion, libDir) +} + +/** + * The pinned Intel EP is registered on ORT's shared process environment, which Foundry also uses. + * Acquire our own environment reference lazily: CPU/CUDA and installation probes need no Intel DLLs. + * Release it only after the manager and its sessions. DLL handles remain pinned for this child. + * OrtApi slots follow the original Microsoft.ML.OnnxRuntime 1.31.0 onnxruntime_c_api.h. + */ +function bundledOpenVino(libDir: string): { register(): void; release(): void } { + let releaseEnv: (() => void) | undefined + return { + register() { + if (releaseEnv) return + const dir = join(libDir, 'openvino') + const path = join(dir, 'onnxruntime_providers_openvino_plugin.dll') + if (!existsSync(path)) + throw new FoundryLibraryError( + 'OpenVINO', + 0, + 'This Foundry 2.4.0 build is missing the bundled Intel OpenVINO 1.8.1 EP. Reinstall the NPU-compatible Windows x64 build.' + ) + const kernel = dlopen('kernel32.dll', { + AddDllDirectory: { args: [T.ptr], returns: T.ptr }, + LoadLibraryExW: { args: [T.ptr, T.ptr, T.u32], returns: T.ptr }, + GetLastError: { args: [], returns: T.u32 }, + }) + const wide = (value: string) => Buffer.from(`${value}\0`, 'utf16le') + if ( + !kernel.symbols.AddDllDirectory(ptr(wide(dir))) || + !kernel.symbols.LoadLibraryExW(ptr(wide(path)), null, 0x1100) + ) + throw new FoundryLibraryError( + 'OpenVINO', + 0, + `Windows could not load the bundled Intel OpenVINO EP (error ${String(kernel.symbols.GetLastError())}). Reinstall this Foundry build and check the Intel NPU driver.` + ) + const ort = dlopen(join(libDir, 'onnxruntime.dll'), { + OrtGetApiBase: { args: [], returns: T.ptr }, + }) + const base = ort.symbols.OrtGetApiBase() as Pointer + const api = CFunction({ ptr: read.ptr(base), args: [T.u32], returns: T.ptr })(31) as Pointer | null + if (!api) throw new FoundryLibraryError('OpenVINO', 0, 'The bundled Intel EP requires ORT API 31') + const fn = (index: number, args: number[], returns: number) => + CFunction({ ptr: read.ptr(api, index * POINTER), args, returns }) + const statusCode = fn(1, [T.ptr], T.i32) + const statusMessage = fn(2, [T.ptr], T.cstring) + const statusRelease = fn(93, [T.ptr], T.void) + const check = (status: unknown) => { + if (!status) return + const code = Number(statusCode(status as Pointer)) + const message = String(statusMessage(status as Pointer)) + statusRelease(status as Pointer) + throw new FoundryLibraryError('OpenVINO', code, message) + } + const envOut = outPointer() + check(fn(3, [T.i32, T.ptr, T.ptr], T.ptr)(3, ptr(cstr('atomic-foundry-openvino')), ptr(envOut))) + const env = deref(envOut) + const release = () => fn(92, [T.ptr], T.void)(env) + try { + check( + fn(301, [T.ptr, T.ptr, T.ptr], T.ptr)( + env, + ptr(cstr('atomic-foundry-openvino-1.8.1')), + ptr(wide(path)) + ) + ) + releaseEnv = release + } catch (error) { + release() + throw error + } + }, + release() { + releaseEnv?.() + releaseEnv = undefined + }, + } +} + +/** Register the pinned Mac EP in the same ORT environment used by Foundry/GenAI. */ +function macWebGpu(libDir: string, config: FoundryManagerConfig) { + let releaseEnv: (() => void) | undefined + return { + async register(onProgress?: (percent: number) => void) { + if (releaseEnv) return + const file = await ensureMacWebGpu({ + runtimeDir: config.appDataDir, + allowDownload: config.allowEpDownloads === true, + fetch, + ...(onProgress ? { onProgress } : {}), + }) + const ort = dlopen(join(libDir, 'libonnxruntime.1.dylib'), { + OrtGetApiBase: { args: [], returns: T.ptr }, + }) + const base = ort.symbols.OrtGetApiBase() as Pointer + const api = CFunction({ ptr: read.ptr(base), args: [T.u32], returns: T.ptr })(31) as Pointer | null + if (!api) throw new FoundryLibraryError('WebGPU', 0, 'The pinned Mac WebGPU EP requires ORT API 31') + const fn = (index: number, args: number[], returns: number) => + CFunction({ ptr: read.ptr(api, index * POINTER), args, returns }) + const code = fn(1, [T.ptr], T.i32) + const message = fn(2, [T.ptr], T.cstring) + const releaseStatus = fn(93, [T.ptr], T.void) + const check = (status: unknown) => { + if (!status) return + const error = new FoundryLibraryError( + 'WebGPU', + Number(code(status as Pointer)), + String(message(status as Pointer)) + ) + releaseStatus(status as Pointer) + throw error + } + const envOut = outPointer() + check(fn(3, [T.i32, T.ptr, T.ptr], T.ptr)(3, ptr(cstr('atomic-foundry-webgpu')), ptr(envOut))) + const env = deref(envOut) + const release = () => fn(92, [T.ptr], T.void)(env) + try { + check( + fn(301, [T.ptr, T.ptr, T.ptr], T.ptr)( + env, + ptr(cstr('atomic-foundry-webgpu-0.2.1')), + ptr(cstr(file)) + ) + ) + releaseEnv = release + } catch (error) { + release() + throw error + } + }, + release() { + releaseEnv?.() + releaseEnv = undefined + }, + } } -function bindLibrary(api: Pointer, version: string): FoundryLibrary { +function bindLibrary(api: Pointer, version: string, cApiVersion: number, libDir: string): FoundryLibrary { const fn = (table: Pointer, index: number, args: number[], returns: number) => CFunction({ ptr: read.ptr(table, index * POINTER), args, returns }) @@ -191,7 +396,12 @@ function bindLibrary(api: Pointer, version: string): FoundryLibrary { } finally { f.configRelease(cfg) } - return bindManager(manager) + const bound = bindManager(manager) + if (requiresMacWebGpu(process.platform, process.arch, version)) + return withMacWebGpu(bound, macWebGpu(libDir, config)) + return requiresBundledOpenVino(process.platform, process.arch, version) + ? withBundledOpenVino(bound, bundledOpenVino(libDir)) + : bound } function bindManager(manager: Pointer): FoundryManager { @@ -294,5 +504,5 @@ function bindLibrary(api: Pointer, version: string): FoundryLibrary { } } - return { version, cApiVersion: BOUND_C_API_VERSION, createManager } + return { version, cApiVersion, createManager } } diff --git a/src/runtime/foundry-local/host/library.test.ts b/src/runtime/foundry-local/host/library.test.ts index c8039506..7adc5459 100644 --- a/src/runtime/foundry-local/host/library.test.ts +++ b/src/runtime/foundry-local/host/library.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { FoundryLibraryError } from './library.js' +import { FoundryLibraryError, selectFoundryApi } from './library.js' describe('FoundryLibraryError', () => { it('names the C API call and keeps the library code', () => { @@ -8,3 +8,18 @@ describe('FoundryLibraryError', () => { expect(error).toMatchObject({ name: 'FoundryLibraryError', operation: 'Model_Load', libraryCode: 3 }) }) }) + +describe('selectFoundryApi', () => { + it.each([3, 2])('reports the maximum supported C API %s, trying 3 before 2', (maximum) => { + const calls: number[] = [] + const selected = selectFoundryApi('2.4.0', (version) => { + calls.push(version) + return version <= maximum ? 123 : null + }) + expect(selected).toEqual({ api: 123, cApiVersion: maximum }) + expect(calls).toEqual(maximum === 3 ? [3] : [3, 2]) + }) + it('rejects a library with neither supported table, naming its version', () => { + expect(() => selectFoundryApi('9.0.0', () => null)).toThrow(/9.0.0.*3.*2/) + }) +}) diff --git a/src/runtime/foundry-local/host/library.ts b/src/runtime/foundry-local/host/library.ts index 56e1a9e9..f7290673 100644 --- a/src/runtime/foundry-local/host/library.ts +++ b/src/runtime/foundry-local/host/library.ts @@ -1,7 +1,8 @@ /** * The part of Foundry Local's C API (`foundry_local_c.h`, `FOUNDRY_LOCAL_API_VERSION` 2) the host * uses, as an interface. `ffi-bun.ts` implements it over `bun:ffi`; the protocol tests (tasks 5.2, - * 5.3) run the host against a fake one. Every call is synchronous and may block, like the C API. + * 5.3) run the host against a fake one. Native calls are synchronous and may block; host-managed + * accelerator preparation can await a verified download. */ /** A non-null `flStatus*`: the library's error code and message. */ @@ -25,6 +26,8 @@ export interface FoundryManagerConfig { webServiceEndpoints: string[] /** `SetAdditionalOptions`, e.g. `DisableNonessentialTelemetry`. */ additionalOptions: Record + /** Only explicit accelerator preparation may fetch a host-managed EP. */ + allowEpDownloads?: boolean } export interface DiscoverableEp { @@ -52,8 +55,12 @@ export interface FoundryManager { * CDN accelerators (spike findings 2, 15). Windows ML ones may call it from a thread of their own * on a first install, where the plain callback cannot run: pass it only for CDN accelerators. A * per-EP failure is not an error — read `discoverableEps()` afterwards. + * Await the return value: host-managed providers prepare asynchronously. */ - downloadAndRegisterEps(names: string[], onProgress?: (ep: string, percent: number) => void): void + downloadAndRegisterEps( + names: string[], + onProgress?: (ep: string, percent: number) => void + ): void | Promise /** `RegisterModel` in the local catalog; files are not copied. */ registerLocalModel(path: string, id: string, metadata: ModelMetadata): FoundryModel /** Start the built-in server; the bound URLs. */ @@ -72,3 +79,19 @@ export interface FoundryLibrary { /** Opens the library of one build (`/lib`); throws when it does not load or speaks another C API. */ export type LoadFoundryLibrary = (libDir: string) => Promise + +/** Highest supported table provided by the loaded library; API 3 keeps the API 2 slots. */ +export function selectFoundryApi( + version: string, + getApi: (version: number) => number | null +): { api: number; cApiVersion: number } { + for (const cApiVersion of [3, 2]) { + const api = getApi(cApiVersion) + if (api) return { api, cApiVersion } + } + throw new FoundryLibraryError( + 'FoundryLocalGetApi', + 0, + `Foundry Local ${version} provides neither supported C API 3 nor 2` + ) +} diff --git a/src/runtime/foundry-local/host/openvino.test.ts b/src/runtime/foundry-local/host/openvino.test.ts new file mode 100644 index 00000000..f3a8e39a --- /dev/null +++ b/src/runtime/foundry-local/host/openvino.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest' +import type { FoundryManager } from './library.js' +import { requiresBundledOpenVino, withBundledOpenVino } from './openvino.js' + +describe('requiresBundledOpenVino', () => { + it.each([ + ['win32', 'x64', '2.4.0', true], + ['win32', 'x64', '2.1.0', false], + ['win32', 'arm64', '2.4.0', false], + ['linux', 'x64', '2.4.0', false], + ['darwin', 'arm64', '2.4.0', false], + ['win32', 'x64', '2.5.0', false], + ])('%s/%s/%s requires the qualified Intel bundle: %s', (platform, arch, version, expected) => { + expect(requiresBundledOpenVino(platform, arch, version)).toBe(expected) + }) +}) + +function setup() { + const native = { + discoverableEps: vi.fn(() => [ + { name: 'OpenVINOExecutionProvider', registered: true }, + { name: 'CUDAExecutionProvider', registered: false }, + ]), + downloadAndRegisterEps: vi.fn(), + registerLocalModel: vi.fn(), + webServiceStart: vi.fn(), + shutdown: vi.fn(), + release: vi.fn(), + } satisfies FoundryManager + const bundled = { register: vi.fn(), release: vi.fn() } + return { native, bundled, manager: withBundledOpenVino(native, bundled) } +} + +describe('withBundledOpenVino', () => { + it('does not accept the system registration as preparation for the bundled EP', () => { + const { manager, bundled } = setup() + expect(manager.discoverableEps()[0]).toEqual({ name: 'OpenVINOExecutionProvider', registered: false }) + expect(bundled.register).not.toHaveBeenCalled() + }) + + it('registers the bundled EP once, avoiding the incompatible WinML EP', () => { + const { manager, native, bundled } = setup() + manager.downloadAndRegisterEps(['OpenVINOExecutionProvider']) + manager.downloadAndRegisterEps(['OpenVINOExecutionProvider']) + expect(bundled.register).toHaveBeenCalledTimes(1) + expect(native.downloadAndRegisterEps).not.toHaveBeenCalled() + expect(manager.discoverableEps()[0]?.registered).toBe(true) + }) + + it('leaves a failed bundled registration unprepared, without a system fallback', () => { + const { manager, native, bundled } = setup() + bundled.register.mockImplementation(() => { + throw new Error('Intel EP dependency missing') + }) + expect(() => manager.downloadAndRegisterEps(['OpenVINOExecutionProvider'])).toThrow( + 'Intel EP dependency missing' + ) + expect(manager.discoverableEps()[0]?.registered).toBe(false) + expect(native.downloadAndRegisterEps).not.toHaveBeenCalled() + }) + + it('preserves other EPs and their progress callback, including an all-EP request', () => { + const { manager, native, bundled } = setup() + const progress = vi.fn() + manager.downloadAndRegisterEps(['CUDAExecutionProvider'], progress) + expect(bundled.register).not.toHaveBeenCalled() + expect(native.downloadAndRegisterEps).toHaveBeenLastCalledWith(['CUDAExecutionProvider'], progress) + manager.downloadAndRegisterEps([], progress) + expect(bundled.register).toHaveBeenCalledTimes(1) + expect(native.downloadAndRegisterEps).toHaveBeenLastCalledWith(['CUDAExecutionProvider'], progress) + }) + + it('releases the ORT environment after the native manager, even if release throws', () => { + const { manager, native, bundled } = setup() + native.release.mockImplementation(() => { + throw new Error('native release failed') + }) + expect(() => manager.release()).toThrow('native release failed') + expect(bundled.release).toHaveBeenCalledTimes(1) + expect(native.release.mock.invocationCallOrder[0]).toBeLessThan( + bundled.release.mock.invocationCallOrder[0]! + ) + }) +}) diff --git a/src/runtime/foundry-local/host/openvino.ts b/src/runtime/foundry-local/host/openvino.ts new file mode 100644 index 00000000..55f8ac97 --- /dev/null +++ b/src/runtime/foundry-local/host/openvino.ts @@ -0,0 +1,38 @@ +import type { FoundryManager } from './library.js' + +const OPENVINO = 'OpenVINOExecutionProvider' + +/** Only the runtime/EP combination qualified by the 2.4.0 Windows x64 archive. */ +export function requiresBundledOpenVino(platform: string, arch: string, version: string): boolean { + return platform === 'win32' && arch === 'x64' && version === '2.4.0' +} + +/** Keep WinML's device discovery, but never register its incompatible OpenVINO EP on ORT 1.31. */ +export function withBundledOpenVino( + manager: FoundryManager, + bundled: { register(): void; release(): void } +): FoundryManager { + let registered = false + return { + ...manager, + discoverableEps: () => + manager.discoverableEps().map((ep) => (ep.name === OPENVINO ? { ...ep, registered } : ep)), + downloadAndRegisterEps(names, onProgress) { + const wanted = names.length ? names : manager.discoverableEps().map((ep) => ep.name) + if (wanted.includes(OPENVINO) && !registered) { + bundled.register() + registered = true + } + const other = wanted.filter((name) => name !== OPENVINO) + if (other.length) return manager.downloadAndRegisterEps(other, onProgress) + }, + release() { + try { + manager.release() + } finally { + bundled.release() + registered = false + } + }, + } +} diff --git a/src/runtime/foundry-local/host/run.test.ts b/src/runtime/foundry-local/host/run.test.ts index f76a6f01..c251762b 100644 --- a/src/runtime/foundry-local/host/run.test.ts +++ b/src/runtime/foundry-local/host/run.test.ts @@ -111,6 +111,30 @@ describe('libraryDir', () => { }) describe('runFoundryHost prepare', () => { + it('awaits asynchronous EP registration and enables downloads only for preparation', async () => { + let registered = false + const fake = fakeLibrary({ + discoverableEps: () => [{ name: 'WebGpuExecutionProvider', registered }], + downloadAndRegisterEps: async () => { + await Promise.resolve() + registered = true + }, + }) + const out = io() + expect( + await runFoundryHost(['prepare', ...COMMON, 'WebGpuExecutionProvider'], { + ...out, + loadLibrary: async () => fake.library, + readLogTail: async () => '', + }) + ).toBe(0) + expect(fake.configs[0]?.allowEpDownloads).toBe(true) + expect(JSON.parse(out.out.at(-1)!)).toEqual({ + done: true, + accelerators: [{ name: 'WebGpuExecutionProvider', prepared: true }], + }) + }) + /** A library whose CUDA download fails half way, as on a host without CUDA 12 (rulings S1, finding 11). */ function partlyFailing() { const registered = new Set() @@ -276,6 +300,17 @@ describe('runFoundryHost prepare', () => { }) describe('failureReason', () => { + it('explains a missing Windows CUDA dependency while preserving the native loader detail', () => { + const log = "[2026-11-10] [warning] EP: failed to load 'C:\\cuda-ep\\onnxruntime-genai-cuda.dll' (126)" + const reason = failureReason(log, 'CUDAExecutionProvider') + expect(failureReason(log, 'CUDAExecutionProvider', 13)).toContain('CUDA 13') + expect(reason).toContain('CUDA 12') + expect(reason).toContain('cuDNN 9') + expect(reason).toContain('126') + expect(reason).toContain('PATH') + expect(failureReason(log, 'OpenVINOExecutionProvider')).toBeNull() + }) + it('finds the cause the library logged, by the accelerator or its family, past the generic summary', () => { const linux = [ "[2026-10-15 16:32:51.303] [warning] EP: failed to load '/x/cuda-ep/bin/libonnxruntime-genai-cuda.so' (libcublasLt.so.12: cannot open shared object file: No such file or directory)", @@ -331,6 +366,42 @@ describe('logTailReader', () => { }) describe('runFoundryHost serve', () => { + it('awaits asynchronous EP registration before loading and forbids EP downloads on serve', async () => { + let registered = false + let loaded = false + const fake = fakeLibrary({ + discoverableEps: () => [{ name: 'WebGpuExecutionProvider', registered }], + downloadAndRegisterEps: async () => { + await Promise.resolve() + registered = true + }, + registerLocalModel: () => ({ + load: () => { + expect(registered).toBe(true) + loaded = true + }, + unload: () => {}, + executionProvider: () => 'WebGPUExecutionProvider', + }), + webServiceStart: () => ['http://127.0.0.1:41987'], + }) + const out = io() + expect( + await runFoundryHost(SERVE, { + ...out, + loadLibrary: async () => fake.library, + watchStop: () => ({ stopped: Promise.resolve(), dispose: () => {} }), + removeDir: async () => {}, + }) + ).toBe(0) + expect(loaded).toBe(true) + expect(fake.configs[0]?.allowEpDownloads).toBe(false) + expect(JSON.parse(out.out[0]!)).toMatchObject({ + ready: true, + execution_provider: 'WebGPUExecutionProvider', + }) + }) + const SERVE = [ 'serve', ...COMMON, diff --git a/src/runtime/foundry-local/host/run.ts b/src/runtime/foundry-local/host/run.ts index 58283fb4..2c5a8cce 100644 --- a/src/runtime/foundry-local/host/run.ts +++ b/src/runtime/foundry-local/host/run.ts @@ -9,7 +9,7 @@ import { existsSync } from 'node:fs' import { open, readdir, rm, stat } from 'node:fs/promises' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { FoundryHostUsageError, parseFoundryHostArgs } from './args.js' import type { FoundryHostArgs } from './args.js' import { describeDiscoverable, executionProvider } from './execution-providers.js' @@ -103,7 +103,7 @@ export function logTailReader(): (logsDir: string) => Promise { * The library's own words for why `name` was not registered: the last warning or error that names the * accelerator or its family (`cuda` for `CUDAExecutionProvider`), not the generic summary line. */ -export function failureReason(log: string, name: string): string | null { +export function failureReason(log: string, name: string, cudaMajor: 12 | 13 = 12): string | null { const family = name.replace(/ExecutionProvider$/, '').toLowerCase() const lines = log .split(/\r?\n/) @@ -114,7 +114,10 @@ export function failureReason(log: string, name: string): string | null { if (!last) return null const blocked = /failed to load '([^']+)' \(4551\)/.exec(last) if (blocked) return appControlBlocked(blocked[1] ?? '', family) - return last.replace(/^\[[^\]]*\]\s*\[[^\]]*\]\s*/, '').trim() + const detail = last.replace(/^\[[^\]]*\]\s*\[[^\]]*\]\s*/, '').trim() + if (family === 'cuda' && /\.dll['"]?\s*\(126\)/i.test(last)) + return `CUDA could not load a required DLL. Install CUDA ${cudaMajor} and cuDNN 9 for CUDA ${cudaMajor}, make their bin directories available through CUDA_PATH, CUDNN_PATH or PATH, then retry preparation. ${detail}` + return detail } /** @@ -189,6 +192,7 @@ function openManager( webServiceEndpoints: extra.endpoints, // Design D8: the optional telemetry off; `ProcessInfo` still goes, and is disclosed. additionalOptions: { DisableNonessentialTelemetry: 'true' }, + allowEpDownloads: args.mode === 'prepare', }) } @@ -251,6 +255,7 @@ async function prepare( await readLog(args.logs) const manager = openManager(library, args, { cache: join(args.appData, 'cache'), endpoints: [] }) const summary: PrepareSummary[] = [] + const cudaMajor = basename(args.lib) === 'win-arm64' ? 13 : 12 try { const offered = manager.discoverableEps().map((ep) => ep.name) const wanted = args.accelerators.length > 0 ? args.accelerators : offered @@ -264,7 +269,7 @@ async function prepare( try { // The callback goes only where the library calls it on this thread: Windows ML reported a first // install from a thread of its own, and Bun's plain callback called there failed the prepare. - manager.downloadAndRegisterEps( + await manager.downloadAndRegisterEps( [name], CDN_ACCELERATORS.has(name) ? (_label, percent) => @@ -282,7 +287,9 @@ async function prepare( summary.push({ name, prepared: true }) } else { const reason = - thrown ?? failureReason(await readLog(args.logs), name) ?? `Foundry Local did not register ${name}.` + thrown ?? + failureReason(await readLog(args.logs), name, cudaMajor) ?? + `Foundry Local did not register ${name}.` deps.stdout(json({ accelerator: name, stage: 'failed', fraction: null, reason })) summary.push({ name, prepared: false, reason }) } @@ -313,7 +320,7 @@ async function serve( }) try { if (ep.register) { - manager.downloadAndRegisterEps([ep.register]) + await manager.downloadAndRegisterEps([ep.register]) if (!manager.discoverableEps().some((found) => found.name === ep.register && found.registered)) { deps.stderr(`${ep.register} is not prepared on this computer; prepare it before loading this model.`) return 5 diff --git a/src/runtime/foundry-local/host/webgpu/index.ts b/src/runtime/foundry-local/host/webgpu/index.ts new file mode 100644 index 00000000..0e942091 --- /dev/null +++ b/src/runtime/foundry-local/host/webgpu/index.ts @@ -0,0 +1,2 @@ +export { requiresMacWebGpu, withMacWebGpu } from './policy.js' +export { ensureMacWebGpu } from './store.js' diff --git a/src/runtime/foundry-local/host/webgpu/policy.test.ts b/src/runtime/foundry-local/host/webgpu/policy.test.ts new file mode 100644 index 00000000..4d04083e --- /dev/null +++ b/src/runtime/foundry-local/host/webgpu/policy.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it, vi } from 'vitest' +import type { FoundryManager } from '../library.js' +import { requiresMacWebGpu, withMacWebGpu } from './policy.js' + +function setup() { + const native = { + discoverableEps: () => [ + { name: 'WebGpuExecutionProvider', registered: true }, + { name: 'CUDAExecutionProvider', registered: false }, + ], + downloadAndRegisterEps: vi.fn(), + registerLocalModel: vi.fn(), + webServiceStart: vi.fn(), + shutdown: vi.fn(), + release: vi.fn(), + } satisfies FoundryManager + const ep = { register: vi.fn(async (_progress?: (percent: number) => void) => {}), release: vi.fn() } + return { native, ep, manager: withMacWebGpu(native, ep) } +} + +describe('requiresMacWebGpu', () => { + it.each([ + ['darwin', 'arm64', '2.4.0', true], + ['darwin', 'arm64', '2.1.0', false], + ['darwin', 'arm64', '2.5.0', false], + ['darwin', 'x64', '2.4.0', false], + ['win32', 'x64', '2.4.0', false], + ['linux', 'arm64', '2.4.0', false], + ])('limits the registration override to %s/%s/%s: %s', (platform, arch, version, expected) => { + expect(requiresMacWebGpu(platform, arch, version)).toBe(expected) + }) +}) + +describe('withMacWebGpu', () => { + it('awaits actual registration before declaring prepared and forwards progress', async () => { + const { native, ep, manager } = setup() + let finish!: () => void + ep.register.mockImplementation( + (progress) => + new Promise((resolve) => { + progress?.(50) + finish = resolve + }) + ) + expect(manager.discoverableEps()[0]?.registered).toBe(false) + const progress = vi.fn() + const pending = manager.downloadAndRegisterEps(['WebGpuExecutionProvider'], progress) + expect(progress).toHaveBeenCalledWith('WebGpuExecutionProvider', 50) + expect(manager.discoverableEps()[0]?.registered).toBe(false) + finish() + await pending + expect(manager.discoverableEps()[0]?.registered).toBe(true) + await manager.downloadAndRegisterEps(['WebGpuExecutionProvider']) + expect(ep.register).toHaveBeenCalledTimes(1) + expect(native.downloadAndRegisterEps).not.toHaveBeenCalled() + }) + + it('does not mark a failed registration prepared or fall back to broken native preparation', async () => { + const { native, ep, manager } = setup() + ep.register.mockRejectedValue(new Error('Cached WebGPU EP failed integrity')) + await expect(manager.downloadAndRegisterEps(['WebGpuExecutionProvider'])).rejects.toThrow( + 'failed integrity' + ) + expect(manager.discoverableEps()[0]?.registered).toBe(false) + expect(native.downloadAndRegisterEps).not.toHaveBeenCalled() + }) + + it('leaves unrelated accelerators alone and supports an all-EP request', async () => { + const { native, ep, manager } = setup() + const progress = vi.fn() + await manager.downloadAndRegisterEps(['CUDAExecutionProvider'], progress) + expect(ep.register).not.toHaveBeenCalled() + expect(native.downloadAndRegisterEps).toHaveBeenLastCalledWith(['CUDAExecutionProvider'], progress) + await manager.downloadAndRegisterEps([], progress) + expect(ep.register).toHaveBeenCalledTimes(1) + expect(native.downloadAndRegisterEps).toHaveBeenLastCalledWith(['CUDAExecutionProvider'], progress) + }) + + it('releases its environment after native sessions even if native release fails', () => { + const { native, ep, manager } = setup() + native.release.mockImplementation(() => { + throw new Error('release failed') + }) + expect(() => manager.release()).toThrow('release failed') + expect(ep.release).toHaveBeenCalledTimes(1) + expect(native.release.mock.invocationCallOrder[0]).toBeLessThan(ep.release.mock.invocationCallOrder[0]!) + }) +}) diff --git a/src/runtime/foundry-local/host/webgpu/policy.ts b/src/runtime/foundry-local/host/webgpu/policy.ts new file mode 100644 index 00000000..9556243a --- /dev/null +++ b/src/runtime/foundry-local/host/webgpu/policy.ts @@ -0,0 +1,39 @@ +import type { FoundryManager } from '../library.js' + +const WEBGPU = 'WebGpuExecutionProvider' + +/** The native Mac EP bootstrap fails on this qualified runtime despite a compatible provider. */ +export function requiresMacWebGpu(platform: string, arch: string, version: string): boolean { + return platform === 'darwin' && arch === 'arm64' && version === '2.4.0' +} + +export function withMacWebGpu( + manager: FoundryManager, + ep: { register(onProgress?: (percent: number) => void): Promise; release(): void } +): FoundryManager { + let registered = false + return { + ...manager, + discoverableEps: () => + manager + .discoverableEps() + .map((offered) => (offered.name === WEBGPU ? { ...offered, registered } : offered)), + async downloadAndRegisterEps(names, onProgress) { + const wanted = names.length ? names : manager.discoverableEps().map((offered) => offered.name) + if (wanted.includes(WEBGPU) && !registered) { + await ep.register(onProgress ? (percent) => onProgress(WEBGPU, percent) : undefined) + registered = true + } + const other = wanted.filter((name) => name !== WEBGPU) + if (other.length) await manager.downloadAndRegisterEps(other, onProgress) + }, + release() { + try { + manager.release() + } finally { + ep.release() + registered = false + } + }, + } +} diff --git a/src/runtime/foundry-local/host/webgpu/store.test.ts b/src/runtime/foundry-local/host/webgpu/store.test.ts new file mode 100644 index 00000000..177a6a87 --- /dev/null +++ b/src/runtime/foundry-local/host/webgpu/store.test.ts @@ -0,0 +1,87 @@ +import { createHash } from 'node:crypto' +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makeZip } from '../../../../../test/helpers/make-zip.js' +import { ensureMacWebGpu, MAC_WEBGPU } from './store.js' + +const digest = (data: Uint8Array) => createHash('sha256').update(data).digest('hex') +let dir: string +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'atomic-mac-webgpu-')) +}) +afterEach(() => rm(dir, { recursive: true, force: true })) +function setup(library = Buffer.from('qualified test EP')) { + const archive = makeZip([{ name: MAC_WEBGPU.fileName, data: library }]) + const pin = { + ...MAC_WEBGPU, + archiveSize: archive.length, + archiveSha256: digest(archive), + librarySize: library.length, + librarySha256: digest(library), + } + const fetcher = vi.fn( + async (_url, init) => + new Response(init?.method === 'HEAD' ? null : archive, { + headers: { 'content-length': String(archive.length) }, + }) + ) + const options = { runtimeDir: dir, allowDownload: true, fetch: fetcher, pin } + return { library, archive, fetcher, options } +} + +describe('ensureMacWebGpu', () => { + it('preserves the disk failure tag when the provider cache cannot be created', async () => { + const { options } = setup() + await writeFile(join(dir, 'v2.4.0'), 'not a directory') + await expect(ensureMacWebGpu(options)).rejects.toThrow(/\[disk_io\]/) + }) + + it('installs verified native bytes and reuses the cache offline in a later host', async () => { + const { library, fetcher, options } = setup() + const progress = vi.fn() + const file = await ensureMacWebGpu({ ...options, onProgress: progress }) + expect(await readFile(file)).toEqual(library) + expect(file).toContain(join('v2.4.0', 'macos-arm64', 'webgpu-ep', '0.2.1')) + expect(progress).toHaveBeenCalled() + const offline = vi.fn(async () => { + throw new Error('offline') + }) + expect(await ensureMacWebGpu({ ...options, allowDownload: false, fetch: offline })).toBe(file) + expect(offline).not.toHaveBeenCalled() + expect(fetcher).toHaveBeenCalled() + }) + + it('never downloads during model loading when preparation is missing', async () => { + const { fetcher, options } = setup() + await expect(ensureMacWebGpu({ ...options, allowDownload: false })).rejects.toThrow(/prepare.*WebGPU/i) + expect(fetcher).not.toHaveBeenCalled() + }) + + it('does not activate an archive with a mismatching digest', async () => { + const { options } = setup() + options.pin.archiveSha256 = '0'.repeat(64) + await expect(ensureMacWebGpu(options)).rejects.toThrow(/Hash verification failed/) + expect(await readdir(join(dir, 'v2.4.0', 'macos-arm64', 'webgpu-ep', '0.2.1'))).toEqual([]) + }) + + it('verifies the extracted library independently of the archive hash', async () => { + const { options } = setup() + options.pin.librarySha256 = '0'.repeat(64) + await expect(ensureMacWebGpu(options)).rejects.toThrow(/Hash verification failed/) + expect(await readdir(join(dir, 'v2.4.0', 'macos-arm64', 'webgpu-ep', '0.2.1'))).toEqual([]) + }) + + it('rejects a tampered cache on load and repairs it only on explicit preparation', async () => { + const { library, fetcher, options } = setup() + const file = await ensureMacWebGpu(options) + await writeFile(file, Buffer.alloc(library.length)) + fetcher.mockClear() + await expect(ensureMacWebGpu({ ...options, allowDownload: false })).rejects.toThrow(/prepare.*WebGPU/i) + expect(fetcher).not.toHaveBeenCalled() + await ensureMacWebGpu(options) + expect(await readFile(file)).toEqual(library) + expect(fetcher).toHaveBeenCalled() + }) +}) diff --git a/src/runtime/foundry-local/host/webgpu/store.ts b/src/runtime/foundry-local/host/webgpu/store.ts new file mode 100644 index 00000000..53f5eab7 --- /dev/null +++ b/src/runtime/foundry-local/host/webgpu/store.ts @@ -0,0 +1,89 @@ +import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { + diskErrToString, + Downloader, + extractArchive, + verifyDownloadedFile, +} from '../../../../downloads/index.js' + +interface MacWebGpuPin { + version: string + fileName: string + url: string + archiveSize: number + archiveSha256: string + librarySize: number + librarySha256: string +} + +/** The unmodified Microsoft CDN bundle requested by Foundry 2.4.0 itself. */ +export const MAC_WEBGPU: Readonly = Object.freeze({ + version: '0.2.1', + fileName: 'libonnxruntime_providers_webgpu.dylib', + url: 'https://foundrypackages-ffhrdhbxb7gpdreh.b02.azurefd.net/webgpu_ep_0.2.1_macos-arm64.zip', + archiveSize: 3447797, + archiveSha256: '5f0f8378172f53efa281328f33d1ebc793e44197ffb4cc605d02c593b891c0ea', + librarySize: 10432384, + librarySha256: '8fac874a60f32f0127c74cb7def915807fcc8a6c30b77629e45f8cee60272eae', +}) + +function diskFailure(error: unknown): never { + throw new Error(diskErrToString(error)) +} + +/** Validate on every host start; a model load must never repair or fetch a missing provider. */ +export async function ensureMacWebGpu(options: { + runtimeDir: string + allowDownload: boolean + fetch: typeof fetch + onProgress?: (percent: number) => void + /** Test seam: small fixture archives, with the same two integrity boundaries. */ + pin?: Readonly +}): Promise { + const pin = options.pin ?? MAC_WEBGPU + const dir = join(options.runtimeDir, 'v2.4.0', 'macos-arm64', 'webgpu-ep', pin.version) + const library = join(dir, pin.fileName) + const verifyLibrary = async (file: string) => { + if (!(await lstat(file)).isFile()) throw new Error('WebGPU EP must be a regular file') + await verifyDownloadedFile({ size: pin.librarySize, sha256: pin.librarySha256 }, file) + } + try { + await verifyLibrary(library) + return library + } catch (error) { + const code = (error as NodeJS.ErrnoException | undefined)?.code + if (code && code !== 'ENOENT') diskFailure(error) + if (!options.allowDownload) + throw new Error('Prepare the WebGPU accelerator again: its verified library is missing or has changed.') + } + await mkdir(dir, { recursive: true }).catch(diskFailure) + const staging = await mkdtemp(join(dir, '.incoming-')).catch(diskFailure) + try { + const archive = join(staging, 'webgpu.zip') + const downloader = new Downloader({ + dataFolder: staging, + platform: 'darwin', + fetch: options.fetch, + emit: (name, payload) => { + if (name === 'download:progress' && 'percent' in payload) options.onProgress?.(payload.percent) + }, + }) + await downloader.download('foundry-mac-webgpu', [ + { + url: pin.url, + save_path: archive, + sha256: pin.archiveSha256, + size: pin.archiveSize, + }, + ]) + const extracted = join(staging, 'extracted') + await extractArchive(archive, extracted, true) + const incoming = join(extracted, pin.fileName) + await verifyLibrary(incoming) + await rename(incoming, library).catch(diskFailure) + return library + } finally { + await rm(staging, { recursive: true, force: true }).catch(diskFailure) + } +} diff --git a/src/runtime/foundry-local/host/windows-dlls.test.ts b/src/runtime/foundry-local/host/windows-dlls.test.ts new file mode 100644 index 00000000..5160edd1 --- /dev/null +++ b/src/runtime/foundry-local/host/windows-dlls.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { foundryWindowsDllDirectories } from './windows-dlls.js' + +describe('foundryWindowsDllDirectories', () => { + it('isolates managed CUDA from inherited CUDA, cuDNN, PATH and discovered Toolkit directories', () => { + expect( + foundryWindowsDllDirectories( + 'C:\\foundry\\lib', + { + ATOMIC_FOUNDRY_CUDA_CACHE_DIR: 'D:\\atomic\\cache', + CUDA_PATH: 'C:\\CUDA\\v12.9', + CUDNN_PATH: 'C:\\cuDNN', + Path: 'D:\\atomic\\cache;C:\\CUDA\\v12.9\\bin;C:\\cuDNN\\bin', + }, + ['C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v12.9\\bin'] + ) + ).toEqual(['C:\\foundry\\lib', 'D:\\atomic\\cache']) + }) + + it('keeps Foundry dependencies and the existing PATH while adding CUDA and cuDNN bins', () => { + expect( + foundryWindowsDllDirectories( + 'C:\\foundry\\lib', + { + CUDA_PATH: 'C:\\CUDA\\v12.9', + CUDA_PATH_V12_8: 'D:\\CUDA\\v12.8', + CUDNN_PATH: 'C:\\cuDNN', + Path: 'C:\\Windows\\System32;C:\\other-provider;relative;;', + }, + ['C:\\cuDNN\\bin\\12.9'] + ) + ).toEqual([ + 'C:\\foundry\\lib', + 'C:\\CUDA\\v12.9\\bin', + 'C:\\CUDA\\v12.9\\bin\\x64', + 'D:\\CUDA\\v12.8\\bin', + 'D:\\CUDA\\v12.8\\bin\\x64', + 'C:\\cuDNN\\bin', + 'C:\\cuDNN\\bin\\x64', + 'C:\\cuDNN\\bin\\12.9', + 'C:\\Windows\\System32', + 'C:\\other-provider', + ]) + }) + it('deduplicates Windows paths without adding relative paths or empty PATH entries', () => { + expect( + foundryWindowsDllDirectories('C:\\fl\\lib', { PATH: 'c:\\FL\\LIB;"C:\\cuda\\bin";.;' }, []) + ).toEqual(['C:\\fl\\lib', 'C:\\cuda\\bin']) + }) +}) diff --git a/src/runtime/foundry-local/host/windows-dlls.ts b/src/runtime/foundry-local/host/windows-dlls.ts new file mode 100644 index 00000000..65868d23 --- /dev/null +++ b/src/runtime/foundry-local/host/windows-dlls.ts @@ -0,0 +1,32 @@ +/** Windows dependency search policy; applied only inside the isolated Foundry host. */ +import { win32 } from 'node:path' +import { FOUNDRY_CUDA_CACHE_DIR } from '../cuda/index.js' + +export function foundryWindowsCudaCache(env: NodeJS.ProcessEnv): string | undefined { + const path = env[FOUNDRY_CUDA_CACHE_DIR] + return path && win32.isAbsolute(path) ? win32.normalize(path) : undefined +} + +export function foundryWindowsDllDirectories( + libDir: string, + env: Readonly>, + discovered: readonly string[] +): string[] { + const cache = foundryWindowsCudaCache(env) + if (cache) return [win32.normalize(libDir), cache] + const entries = Object.entries(env) + const roots = entries + .filter(([key]) => /^(CUDA_PATH(?:_V12_\d+)?|CUDNN_PATH)$/i.test(key)) + .flatMap(([, value]) => (value ? [win32.join(value, 'bin'), win32.join(value, 'bin', 'x64')] : [])) + const path = entries.find(([key]) => key.toUpperCase() === 'PATH')?.[1] ?? '' + const seen = new Set() + return [libDir, ...roots, ...discovered, ...path.split(';')].flatMap((value) => { + const trimmed = value.trim().replace(/^"(.*)"$/, '$1') + if (!win32.isAbsolute(trimmed)) return [] + const normalized = win32.normalize(trimmed) + const key = normalized.toLowerCase().replace(/\\+$/, '') + if (seen.has(key)) return [] + seen.add(key) + return [normalized] + }) +} diff --git a/src/runtime/foundry-local/runtime.test.ts b/src/runtime/foundry-local/runtime.test.ts index c5d302ff..6ba72bae 100644 --- a/src/runtime/foundry-local/runtime.test.ts +++ b/src/runtime/foundry-local/runtime.test.ts @@ -7,6 +7,7 @@ import { makeTmpDataFolder } from '../../../test/helpers/tmp-data-folder.js' import type { TmpDataFolder } from '../../../test/helpers/tmp-data-folder.js' import type { CoreEvents } from '../../contracts/index.js' import { ModelRegistry, serializeModelYml } from '../../models/index.js' +import { spawnAndAwaitReady } from '../shared/index.js' import type { GpuClaimHook } from '../shared/index.js' import { FoundryLocalRuntime } from './runtime.js' import type { FoundryLocalRuntimeOptions } from './runtime.js' @@ -91,6 +92,51 @@ const chat = ( }) describe.skipIf(!POSIX)('FoundryLocalRuntime (task 6.3)', () => { + it('checks preparation against the exact build selected for load', async () => { + await variant('gpu-build-scope', { execution_provider: 'webgpu', device: 'gpu' }) + let checked: string | undefined + const { rt } = runtime({ + preparedAccelerators: async (build) => { + checked = build + return [] + }, + }) + await expect(rt.load('gpu-build-scope')).rejects.toMatchObject({ + code: 'FOUNDRY_LOCAL_ACCELERATOR_NOT_PREPARED', + }) + expect(checked).toBe(BUILD) + expect(await starts()).toEqual([]) + }) + + it('uses the Linux ARM64 CUDA cache only after the active runtime reaches 2.4.0', async () => { + await variant('arm-cuda-gpu', { execution_provider: 'cuda', device: 'gpu' }) + let build = '/build/v2.1.0/linux-arm64' + const cached = vi.fn(async () => '/private/cuda') + const spawn: typeof spawnAndAwaitReady = (spec, options) => { + expect(spec.env?.['LD_LIBRARY_PATH']).toBe('/private/cuda:/driver/lib') + return spawnAndAwaitReady(spec, options) + } + const { rt } = runtime({ + platform: 'linux', + arch: 'arm64', + resolveBuild: async () => build, + preparedAccelerators: async () => ['CUDAExecutionProvider'], + cuda: { cached }, + baseEnv: { ...process.env, LD_LIBRARY_PATH: '/driver/lib' }, + spawn, + }) + await expect(rt.load('arm-cuda-gpu')).rejects.toMatchObject({ code: 'ENGINE_UPDATE_REQUIRED' }) + expect(cached).not.toHaveBeenCalled() + build = '/build/v2.4.0/linux-arm64' + const session = await rt.load('arm-cuda-gpu') + try { + expect(session.model_id).toBe('arm-cuda-gpu') + expect(cached).toHaveBeenCalledExactlyOnceWith(build) + } finally { + await rt.unload('arm-cuda-gpu') + } + }) + it('starts the host for a variant, registered explicitly, behind a gateway that names the model as core does', async () => { await variant('qwen3-0.6b-generic-gpu', { execution_provider: 'webgpu', diff --git a/src/runtime/foundry-local/runtime.ts b/src/runtime/foundry-local/runtime.ts index 70ba3b7c..09d725cd 100644 --- a/src/runtime/foundry-local/runtime.ts +++ b/src/runtime/foundry-local/runtime.ts @@ -13,7 +13,8 @@ */ import { randomUUID } from 'node:crypto' -import { join } from 'node:path' +import { basename, dirname, join } from 'node:path' +import { compareVersions } from '../../backend/index.js' import { AtomicCoreError } from '../../contracts/index.js' import type { ModelYmlFoundryLocal, SessionInfo, UnloadResult } from '../../contracts/index.js' import type { DataLayout } from '../../config/index.js' @@ -43,6 +44,8 @@ import type { BackendOutputSink } from '../shared/index.js' import { executionProvider } from './host/execution-providers.js' import { LOCAL_CATALOG_BASE_PATH } from './host/run.js' import type { FoundryHostCommand } from './host-process.js' +import { withCudaRuntime } from './cuda/index.js' +import type { CudaRuntimeStore } from './cuda/index.js' import { readFoundryLocalBlock } from './model-yml.js' /** The settings' `timeout` default, in seconds: registering, building the ORT session, compiling (OpenVINO). */ @@ -67,10 +70,19 @@ export function variantRunsOn( if (ep === 'cpu') return true if (platform === 'win32') return true if (platform === 'darwin') return ep === 'webgpu' - if (platform === 'linux') return arch === 'x64' && ep === 'cuda' + if (platform === 'linux') return (arch === 'x64' || arch === 'arm64') && ep === 'cuda' return false } +/** Linux ARM64 first supports the CUDA variant in Foundry Local 2.4. */ +export function minimumFoundryVariantRuntime( + platform: NodeJS.Platform, + arch: string, + ep: ModelYmlFoundryLocal['execution_provider'] +): string | undefined { + return platform === 'linux' && arch === 'arm64' && ep === 'cuda' ? '2.4.0' : undefined +} + /** The registration id the host serves the model under: `:`, one segment. */ export function registrationId(modelId: string): string { return `${modelId.replace(/[^A-Za-z0-9._-]+/g, '-')}:1` @@ -93,7 +105,7 @@ export interface FoundryLocalRuntimeOptions { /** The active build's directory (engine-builds), or nothing installed. */ resolveBuild: () => Promise /** The accelerators core recorded as prepared (`accelerators.json`, task 6.4). */ - preparedAccelerators: () => Promise + preparedAccelerators: (build: string) => Promise /** The same live trusted-hosts list `:1337` and the managed gateways use. */ trustedHosts: string[] /** The `foundry-local` provider settings, re-read per load. */ @@ -101,6 +113,7 @@ export interface FoundryLocalRuntimeOptions { journal?: ProcessJournal | undefined emit?: EmitFn baseEnv?: NodeJS.ProcessEnv + cuda?: Pick backendOutput?: BackendOutputSink log?: (level: 'debug' | 'info' | 'warn' | 'error', message: string) => void /** GPU residency (spec `gpu-residency`): CUDA and WebGPU variants hold every card. */ @@ -234,17 +247,28 @@ export class FoundryLocalRuntime implements LocalRuntime { 'FOUNDRY_LOCAL_VARIANT_UNSUPPORTED', `This ${block.execution_provider.toUpperCase()} variant does not run on ${this.options.platform} ${this.options.arch}.` ) - if (ep.register && !(await this.options.preparedAccelerators()).includes(ep.register)) - throw new AtomicCoreError( - 'FOUNDRY_LOCAL_ACCELERATOR_NOT_PREPARED', - `${ep.register} is not prepared; prepare it on the Foundry Local page before loading this model.` - ) const build = await this.options.resolveBuild() if (!build) throw new AtomicCoreError( 'BINARY_NOT_FOUND', 'Foundry Local is not installed; install it before loading a model.' ) + const minimum = minimumFoundryVariantRuntime( + this.options.platform, + this.options.arch, + block.execution_provider + ) + const version = basename(dirname(build)).replace(/^v/, '') + if (minimum && compareVersions(version, minimum) < 0) + throw new AtomicCoreError( + 'ENGINE_UPDATE_REQUIRED', + `Foundry Local ${version} is active; CUDA on Linux ARM64 requires ${minimum} or newer.` + ) + if (ep.register && !(await this.options.preparedAccelerators(build)).includes(ep.register)) + throw new AtomicCoreError( + 'FOUNDRY_LOCAL_ACCELERATOR_NOT_PREPARED', + `${ep.register} is not prepared; prepare it on the Foundry Local page before loading this model.` + ) const { modelPath } = registry.resolvePaths(yml) const settings = await this.options.readSettings() const timeoutSecs = @@ -332,8 +356,15 @@ export class FoundryLocalRuntime implements LocalRuntime { 'info', `starting the Foundry Local host for ${modelId} (${block.execution_provider}) from ${build}` ) + const cudaDir = block.execution_provider === 'cuda' ? await this.options.cuda?.cached(build) : undefined const started = await (this.options.spawn ?? spawnAndAwaitReady)( - { exe, args, env, stdin: 'pipe', platform: this.options.platform }, + { + exe, + args, + env: cudaDir ? withCudaRuntime(env, build, cudaDir) : env, + stdin: 'pipe', + platform: this.options.platform, + }, { timeoutMs: timeoutSecs * 1000, signal: this.table.signal, diff --git a/src/server/control/routes/foundry-local.test.ts b/src/server/control/routes/foundry-local.test.ts index 92715814..94e06539 100644 --- a/src/server/control/routes/foundry-local.test.ts +++ b/src/server/control/routes/foundry-local.test.ts @@ -1,3 +1,4 @@ +import { foundryLocalVerdict, parseFoundryLocalCheckRequest } from '../../../runtime/foundry-local/index.js' import { afterEach, describe, expect, it } from 'vitest' import { AtomicCoreError } from '../../../contracts/index.js' import type { FoundryLocalAccelerators, FoundryLocalPrepareRequest } from '../../../contracts/index.js' @@ -94,6 +95,38 @@ describe('foundry-local routes (task 6.4)', () => { }) describe('POST /models/foundry-local/check (task 6.5)', () => { + it('accepts a minimum version, returns update-required, and rejects an invalid minimum over HTTP', async () => { + h = await start({ + nativeModelChecks: { + 'foundry-local': async (body) => + foundryLocalVerdict( + { + platform: 'linux', + arch: 'x64', + installed: true, + runtimeVersion: '2.1.0', + accelerators: [], + npu: false, + }, + parseFoundryLocalCheckRequest(body) + ), + }, + }) + const post = (body: unknown) => + h!.get('/atomic/v1/models/foundry-local/check', { method: 'POST', body: JSON.stringify(body) }) + const cpu = { execution_provider: 'cpu', device: 'cpu' } + expect(await (await post(cpu)).json()).toMatchObject({ verdict: 'ok' }) + const result = await post({ ...cpu, min_runtime_version: '2.4.0' }) + expect(result.status).toBe(200) + expect(await result.json()).toMatchObject({ + verdict: 'engine-update-required', + reason: expect.stringMatching(/2.1.0.*2.4.0/), + }) + const bad = await post({ ...cpu, min_runtime_version: '2.4' }) + expect(bad.status).toBe(400) + expect(await bad.json()).toMatchObject({ error: { code: 'INVALID_ARGUMENT' } }) + }) + it('answers from the native check table, after the managed one has no entry for the provider', async () => { const seen: unknown[] = [] h = await start({ diff --git a/test/e2e/engine-builds.test.ts b/test/e2e/engine-builds.test.ts index a1292d2c..0aa519b8 100644 --- a/test/e2e/engine-builds.test.ts +++ b/test/e2e/engine-builds.test.ts @@ -20,7 +20,7 @@ import qwen from '../fixtures/fastflowlm/qwen3-candidate.json' with { type: 'jso import { flmRelease } from '../helpers/fastflowlm-manifest.js' import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' -import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' +import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { c as tarCreate } from 'tar' @@ -323,6 +323,129 @@ const FOUNDRY_PLATFORMS = ['win-x64', 'win-arm64', 'macos-arm64', 'linux-x64', ' const FOUNDRY_HOST = process.platform === 'win32' ? null : foundryLocalTestPlatform() describe.skipIf(!existsSync(BIN) || FOUNDRY_HOST === null)('Foundry Local builds through the core', () => { + it('migrates a loaded CPU variant only after staging passes and rolls back without rewriting model files', async () => { + const folder = ctx.dataFolder + const platform = FOUNDRY_HOST! + const archive = await foundryArchive(folder) + const manifest = join(folder, 'foundry-local-manifest.json') + const release = (tag: string, api: number, distribution?: string) => ({ + tag, + published_at: tag === 'v2.1.0' ? '2026-09-30T00:00:00Z' : '2026-11-09T00:00:00Z', + min_core_version: '0.1.0', + c_api_version: api, + ...(distribution ? { distribution } : {}), + assets: [ + { platform, name: `foundry-local-${platform}.tgz`, size: archive.size, sha256: archive.sha256 }, + ], + }) + const old = release('v2.1.0', 2) + const newer = release('v2.4.0', 3, 'atomic-conf') + const writeManifest = (releases: unknown[]) => + writeFile( + manifest, + JSON.stringify({ schema_version: 1, upstream_repo: 'microsoft/foundry-local', releases }) + ) + await writeManifest([old]) + mirror.serve( + `/microsoft/foundry-local/releases/download/v2.1.0/foundry-local-${platform}.tgz`, + archive.body + ) + mirror.serve( + `/AtomicBot-ai/atomic-chat-conf/releases/download/foundry-local-v2.4.0/foundry-local-${platform}.tgz`, + archive.body + ) + const fake = fileURLToPath(new URL('../helpers/fake-foundry-host.mjs', import.meta.url)) + const host = join(folder, 'fake-foundry-host') + const failFlag = join(folder, 'probe.fail') + const argvFile = join(folder, 'host.jsonl') + await writeFile( + host, + [ + '#!/bin/sh', + `if [ "$1" = probe ] && [ -f ${JSON.stringify(failFlag)} ]; then echo "missing native dependency" >&2; exit 3; fi`, + `export FAKE_FOUNDRY_ARGV=${JSON.stringify(argvFile)}`, + `exec ${JSON.stringify(process.execPath)} ${JSON.stringify(fake)} "$@"`, + ].join('\n'), + { mode: 0o755 } + ) + const { ready } = await core.startDaemon(folder, ctx.daemons, [], { + ATOMIC_FOUNDRY_LOCAL_MANIFEST_URL: pathToFileURL(manifest).href, + ATOMIC_FOUNDRY_HOST_TEST_COMMAND: host, + }) + const install = () => + post(ready, '/engine-builds/foundry-local/install', { task_id: 'migration', proxy: mirror.proxy }) + await json(await install()) + const model = join(folder, 'foundry-local', 'models', 'old-cpu') + await mkdir(model, { recursive: true }) + const files = { + 'genai_config.json': '{}', + 'weights.onnx': 'original model bytes', + 'model.yml': + 'model_path: foundry-local/models/old-cpu\nname: old-cpu\nsize_bytes: 20\nfoundry_local:\n model_id: old-cpu\n variant_id: old-cpu\n execution_provider: cpu\n device: cpu\n', + } + for (const [name, content] of Object.entries(files)) await writeFile(join(model, name), content) + const runtime = join(folder, 'foundry-local', 'runtime') + await mkdir(runtime, { recursive: true }) + const legacy = JSON.stringify({ prepared: ['CUDAExecutionProvider'], failures: {}, updated_at: 1 }) + await writeFile(join(runtime, 'accelerators.json'), legacy) + const load = () => post(ready, '/models/foundry-local/old-cpu/load') + const first = await json<{ session: { pid: number } }>(await load()) + const publicServer = await json<{ port: number }>(await post(ready, '/server/start', { port: 0 })) + const answer = async () => { + const response = await fetch(`http://127.0.0.1:${publicServer.port}/v1/chat/completions`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + model: 'old-cpu', + stream: true, + messages: [{ role: 'user', content: 'hello' }], + }), + }) + expect(response.status, await response.clone().text()).toBe(200) + expect(await response.text()).toContain('data: [DONE]') + } + await answer() + await writeManifest([newer, old]) + await json(await post(ready, '/engine-builds/foundry-local/catalog', { force: true })) + await writeFile(failFlag, '') + expect(await (await install()).json()).toMatchObject({ error: { code: 'ENGINE_INSTALL_FAILED' } }) + expect(process.kill(first.session.pid, 0)).toBe(true) + await answer() + await rm(failFlag) + await json(await install()) + expect(() => process.kill(first.session.pid, 0)).toThrow() + expect((await json(await post(ready, '/engine-builds/foundry-local/catalog'))).active?.tag).toBe( + 'v2.4.0' + ) + await json(await load()) + await answer() + await json(await post(ready, '/models/foundry-local/old-cpu/unload')) + expect( + await json( + await control(ctx, ready, `/engine-builds/foundry-local/v2.4.0/${platform}`, { method: 'DELETE' }) + ) + ).toEqual({ removed: true }) + await rm(manifest) + expect( + (await json(await post(ready, '/engine-builds/foundry-local/catalog', { force: true }))).active + ?.tag + ).toBe('v2.1.0') + await json(await load()) + await answer() + const starts = (await readFile(argvFile, 'utf8')) + .trim() + .split('\n') + .map((line) => (JSON.parse(line) as { argv: string[] }).argv) + .filter((argv) => argv[0] === 'serve') + expect(starts.map((argv) => argv[argv.indexOf('--lib') + 1])).toEqual( + ['v2.1.0', 'v2.4.0', 'v2.1.0'].map((tag) => join(folder, 'foundry-local', 'backends', tag, platform)) + ) + for (const [name, content] of Object.entries(files)) + expect(await readFile(join(model, name), 'utf8')).toBe(content) + expect(await readFile(join(runtime, 'accelerators.json'), 'utf8')).toBe(legacy) + expect(mirror.seen.some((path) => /azure/i.test(path))).toBe(false) + }, 120_000) + it('installs the host archive from a file:// manifest, checked by the host, and leaves nothing when the host refuses it', async () => { const folder = ctx.dataFolder const archive = await foundryArchive(folder) @@ -363,7 +486,7 @@ describe.skipIf(!existsSync(BIN) || FOUNDRY_HOST === null)('Foundry Local builds '#!/bin/sh', `echo "$@" >> ${JSON.stringify(argvFile)}`, `if [ -f ${JSON.stringify(failFlag)} ]; then echo "libatomic.so.1: cannot open shared object file" >&2; exit 3; fi`, - `echo '{"c_api_version":2,"accelerators":[]}'`, + `echo '{"version":"2.1.0","c_api_version":2,"accelerators":[]}'`, ].join('\n'), { mode: 0o755 } ) diff --git a/test/e2e/foundry-host.test.ts b/test/e2e/foundry-host.test.ts index 192bd129..2c04b3c8 100644 --- a/test/e2e/foundry-host.test.ts +++ b/test/e2e/foundry-host.test.ts @@ -7,7 +7,7 @@ */ import { spawn, spawnSync } from 'node:child_process' import { existsSync } from 'node:fs' -import { mkdtemp, readdir, rm } from 'node:fs/promises' +import { copyFile, mkdir, mkdtemp, readdir, readFile, rm } from 'node:fs/promises' import { createServer } from 'node:net' import { createInterface } from 'node:readline' import { tmpdir } from 'node:os' @@ -16,6 +16,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { APP_BIN, BIN } from '../helpers/compiled-core.js' const LIB = process.env['FOUNDRY_LOCAL_TEST_LIB'] +const EXPECTED_VERSION = process.env['FOUNDRY_LOCAL_TEST_VERSION'] ?? '2.1.0' +const EXPECTED_API = EXPECTED_VERSION === '2.1.0' ? 2 : 3 /** A CPU variant folder (e.g. qwen2.5-0.5b-instruct-generic-cpu, downloaded as the app's installer would). */ const MODEL = process.env['FOUNDRY_LOCAL_TEST_MODEL'] let dir: string @@ -38,9 +40,11 @@ describe.skipIf(!LIB || !existsSync(BIN))('foundry-host against a real Foundry L expect(run.status, run.stderr).toBe(0) const answer = JSON.parse(run.stdout.trim().split('\n').at(-1) as string) as { c_api_version: number + version: string accelerators: Array<{ name: string; device: string; prepared: boolean }> } - expect(answer.c_api_version).toBe(2) + expect(answer.c_api_version).toBe(EXPECTED_API) + expect(answer.version).toMatch(new RegExp(`^v?${EXPECTED_VERSION.replaceAll('.', '\\.')}(?:$|[+\\s-])`)) expect(Array.isArray(answer.accelerators)).toBe(true) for (const accelerator of answer.accelerators) expect(accelerator).toEqual({ @@ -51,6 +55,37 @@ describe.skipIf(!LIB || !existsSync(BIN))('foundry-host against a real Foundry L }) }) + it.each([ + ['atomic-chat-core', BIN], + ['atomic-chat-app-core', APP_BIN], + ])('%s rejects a real library whose bundled native dependencies are missing', async (_name, bin) => { + const library = + process.platform === 'darwin' + ? 'libfoundry_local.dylib' + : process.platform === 'win32' + ? 'foundry_local.dll' + : 'libfoundry_local.so' + const isolated = join(dir, 'incomplete') + await mkdir(join(isolated, 'lib'), { recursive: true }) + await copyFile(join(LIB!, 'lib', library), join(isolated, 'lib', library)) + const run = spawnSync( + bin, + [ + 'foundry-host', + 'probe', + '--lib', + isolated, + '--app-data', + join(dir, 'runtime'), + '--logs', + join(dir, 'logs'), + ], + { encoding: 'utf8', timeout: 60_000 } + ) + expect(run.status, run.stderr).toBe(3) + expect(run.stderr).toMatch(/onnxruntime|not found|could not|cannot|126/i) + }) + it('keeps the library to the data folders core gives it', async () => { spawnSync( BIN, @@ -230,3 +265,311 @@ describe.skipIf(!LIB || !MODEL || !existsSync(BIN))('foundry-host serve with a r 60_000 ) }) + +const NPU_MODEL = process.env['FOUNDRY_LOCAL_TEST_NPU_MODEL'] + +describe.skipIf( + process.platform !== 'win32' || !LIB || !NPU_MODEL || !existsSync(BIN) || !existsSync(APP_BIN) +)('foundry-host with the bundled Intel OpenVINO EP', () => { + it('reports a missing Intel bundle without breaking the native CPU probe', async () => { + const incomplete = join(dir, 'without-intel') + await mkdir(join(incomplete, 'lib'), { recursive: true }) + for (const entry of await readdir(join(LIB!, 'lib'), { withFileTypes: true })) + if (entry.isFile()) await copyFile(join(LIB!, 'lib', entry.name), join(incomplete, 'lib', entry.name)) + const common = ['--lib', incomplete, '--app-data', join(dir, 'runtime'), '--logs', join(dir, 'logs')] + const prepared = spawnSync(BIN, ['foundry-host', 'prepare', ...common, 'OpenVINOExecutionProvider'], { + encoding: 'utf8', + timeout: 60_000, + }) + expect(prepared.status, prepared.stderr).toBe(0) + expect(JSON.parse(prepared.stdout.trim().split('\n').at(-1)!)).toMatchObject({ + done: true, + accelerators: [ + { + name: 'OpenVINOExecutionProvider', + prepared: false, + reason: expect.stringContaining('missing the bundled Intel OpenVINO 1.8.1'), + }, + ], + }) + const probe = spawnSync(BIN, ['foundry-host', 'probe', ...common], { encoding: 'utf8', timeout: 60_000 }) + expect(probe.status, probe.stderr).toBe(0) + expect(JSON.parse(probe.stdout.trim().split('\n').at(-1)!)).toMatchObject({ + version: '2.4.0', + c_api_version: 3, + }) + }, 120_000) + + it.each([ + ['atomic-chat-core', BIN], + ['atomic-chat-app-core', APP_BIN], + ])( + '%s prepares the pinned EP and generates on an explicitly NPU-only model', + async (_name, bin) => { + const config = JSON.parse(await readFile(join(NPU_MODEL!, 'genai_config.json'), 'utf8')) as { + model: { + context_length: number + decoder: { session_options: { provider_options: Array<{ OpenVINO?: { device_type: string } }> } } + } + } + expect(config.model.decoder.session_options.provider_options).toContainEqual( + expect.objectContaining({ OpenVINO: expect.objectContaining({ device_type: 'NPU' }) }) + ) + const appData = join(dir, 'runtime') + const logs = join(dir, 'logs') + const prepared = spawnSync( + bin, + [ + 'foundry-host', + 'prepare', + '--lib', + LIB!, + '--app-data', + appData, + '--logs', + logs, + 'OpenVINOExecutionProvider', + ], + { encoding: 'utf8', timeout: 60_000 } + ) + expect(prepared.status, prepared.stderr).toBe(0) + expect(JSON.parse(prepared.stdout.trim().split('\n').at(-1)!)).toMatchObject({ + done: true, + accelerators: [{ name: 'OpenVINOExecutionProvider', prepared: true }], + }) + const port = await freePort() + const cache = join(dir, 'npu-catalog') + const host = spawn( + bin, + [ + 'foundry-host', + 'serve', + '--lib', + LIB!, + '--app-data', + appData, + '--logs', + logs, + '--model', + NPU_MODEL!, + '--ep', + 'openvino', + '--port', + String(port), + '--cache', + cache, + '--id', + 'atomic-e2e-npu:1', + '--context-length', + String(config.model.context_length), + ], + { stdio: ['pipe', 'pipe', 'pipe'] } + ) + let stderr = '' + host.stderr.on('data', (chunk) => { + stderr += String(chunk) + }) + const exited = new Promise((resolve) => host.once('exit', resolve)) + try { + const ready = await new Promise>((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`NPU readiness timed out: ${stderr}`)), 120_000) + createInterface({ input: host.stdout }).on('line', (line) => { + if (line.includes('"ready":true')) { + clearTimeout(timer) + resolve(JSON.parse(line) as Record) + } + }) + host.once('exit', (code) => { + clearTimeout(timer) + reject(new Error(`NPU host exited ${String(code)}: ${stderr}`)) + }) + host.once('error', (error) => { + clearTimeout(timer) + reject(error) + }) + }) + expect(ready).toMatchObject({ ready: true, execution_provider: 'OpenVINOExecutionProvider' }) + const response = await fetch(`http://127.0.0.1:${port}/catalogs/local/v1/chat/completions`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + model: 'atomic-e2e-npu:1', + max_tokens: 12, + messages: [{ role: 'user', content: 'Say hello.' }], + }), + signal: AbortSignal.timeout(60_000), + }) + const answer = await response.text() + expect(response.status, answer).toBe(200) + expect( + ( + JSON.parse(answer) as { choices: Array<{ message: { content: string } }> } + ).choices[0]?.message.content.trim() + ).toBeTruthy() + } finally { + host.stdin.end() + const killTimer = setTimeout(() => host.kill(), 10_000) + try { + expect(await exited, stderr).toBe(0) + } finally { + clearTimeout(killTimer) + } + } + expect(existsSync(cache)).toBe(false) + }, + 240_000 + ) +}) + +const WEBGPU_MODEL = process.env['FOUNDRY_LOCAL_TEST_WEBGPU_MODEL'] + +describe.skipIf( + process.platform !== 'darwin' || + EXPECTED_VERSION !== '2.4.0' || + !LIB || + !WEBGPU_MODEL || + !existsSync(BIN) || + !existsSync(APP_BIN) +)('foundry-host Mac WebGPU preparation', () => { + it('refuses an unprepared WebGPU model without downloading on serve', async () => { + const runtime = join(dir, 'runtime') + const run = spawnSync( + BIN, + [ + 'foundry-host', + 'serve', + '--lib', + LIB!, + '--app-data', + runtime, + '--logs', + join(dir, 'logs'), + '--model', + WEBGPU_MODEL!, + '--ep', + 'webgpu', + '--port', + String(await freePort()), + '--cache', + join(dir, 'catalog'), + '--id', + 'atomic-e2e-webgpu:1', + '--context-length', + '4096', + ], + { encoding: 'utf8', timeout: 30_000 } + ) + expect(run.status, run.stderr).toBe(4) + expect(run.stderr).toMatch(/Prepare the WebGPU accelerator again/) + expect(existsSync(join(runtime, 'v2.4.0', 'macos-arm64', 'webgpu-ep'))).toBe(false) + }, 45_000) + + it('app-core prepares WebGPU, then a fresh host generates using its verified cache', async () => { + const runtime = join(dir, 'runtime'), + logs = join(dir, 'logs'), + cache = join(dir, 'catalog') + const prepare = spawnSync( + APP_BIN, + [ + 'foundry-host', + 'prepare', + '--lib', + LIB!, + '--app-data', + runtime, + '--logs', + logs, + 'WebGpuExecutionProvider', + ], + { encoding: 'utf8', timeout: 90_000 } + ) + expect(prepare.status, prepare.stderr).toBe(0) + expect(JSON.parse(prepare.stdout.trim().split('\n').at(-1)!)).toMatchObject({ + done: true, + accelerators: [{ name: 'WebGpuExecutionProvider', prepared: true }], + }) + const port = await freePort() + const host = spawn( + APP_BIN, + [ + 'foundry-host', + 'serve', + '--lib', + LIB!, + '--app-data', + runtime, + '--logs', + logs, + '--model', + WEBGPU_MODEL!, + '--ep', + 'webgpu', + '--port', + String(port), + '--cache', + cache, + '--id', + 'atomic-e2e-webgpu:1', + '--context-length', + '4096', + '--tools', + '--reasoning-start', + '', + '--reasoning-end', + '', + ], + { stdio: ['pipe', 'pipe', 'pipe'] } + ) + let stderr = '' + host.stderr.on('data', (chunk) => { + stderr += String(chunk) + }) + const exited = new Promise((resolve) => host.once('close', resolve)) + try { + const ready = await new Promise>((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`WebGPU readiness timeout: ${stderr}`)), 120_000) + createInterface({ input: host.stdout }).on('line', (line) => { + if (line.includes('"ready":true')) { + clearTimeout(timer) + resolve(JSON.parse(line) as Record) + } + }) + host.once('exit', (code) => { + clearTimeout(timer) + reject(new Error(`WebGPU host exited ${String(code)}: ${stderr}`)) + }) + host.once('error', (error) => { + clearTimeout(timer) + reject(error) + }) + }) + expect(ready).toMatchObject({ ready: true, execution_provider: 'WebGPUExecutionProvider' }) + const response = await fetch(`http://127.0.0.1:${port}/catalogs/local/v1/chat/completions`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + model: 'atomic-e2e-webgpu:1', + max_tokens: 128, + messages: [{ role: 'user', content: 'Say hello in one short sentence.' }], + }), + signal: AbortSignal.timeout(90_000), + }) + const text = await response.text() + expect(response.status, text).toBe(200) + expect( + ( + JSON.parse(text) as { choices: Array<{ message: { content: string } }> } + ).choices[0]?.message.content.trim() + ).toBeTruthy() + } finally { + host.stdin.end() + const kill = setTimeout(() => host.kill(), 10_000) + try { + expect(await exited, stderr).toBe(0) + } finally { + clearTimeout(kill) + } + } + expect(existsSync(cache)).toBe(false) + }, 240_000) +}) diff --git a/test/helpers/fake-foundry-host.mjs b/test/helpers/fake-foundry-host.mjs index 19336442..bc157e63 100644 --- a/test/helpers/fake-foundry-host.mjs +++ b/test/helpers/fake-foundry-host.mjs @@ -41,8 +41,8 @@ if (argv[0] === 'probe' || argv[0] === 'prepare') { if (argv[0] === 'probe') { console.log( JSON.stringify({ - c_api_version: 2, - version: '2.1.0', + c_api_version: arg('--lib')?.includes('v2.4.0') ? 3 : 2, + version: arg('--lib')?.includes('v2.4.0') ? '2.4.0' : '2.1.0', accelerators: offered.map((name) => ({ name, execution_provider: short(name), From a4add7166f1c6b6f19d23348e879cb2e6ec72ff6 Mon Sep 17 00:00:00 2001 From: Biogenic Ooze Date: Wed, 11 Nov 2026 16:46:47 +0300 Subject: [PATCH 2/4] release: v0.22.4 --- package.json | 2 +- src/version.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 6aae7838..a91657c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@atomic-chat/core", - "version": "0.22.3", + "version": "0.22.4", "repository": { "type": "git", "url": "git+https://github.com/AtomicBot-ai/atomic-chat-core.git" diff --git a/src/version.ts b/src/version.ts index a4d7eb39..65ed98d6 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ /** Kept in sync with package.json by `src/version.test.ts`. Bump both together. */ -export const CORE_VERSION = '0.22.3' +export const CORE_VERSION = '0.22.4' From 64482bfb70f74aecc25cdfaaf1e340347901d172 Mon Sep 17 00:00:00 2001 From: Biogenic Ooze Date: Wed, 11 Nov 2026 17:03:39 +0300 Subject: [PATCH 3/4] Fix Foundry upgrade e2e fixtures and preparation expectations --- test/e2e/engine-builds.test.ts | 21 ++++++++++++++++++--- test/helpers/fake-foundry-host.mjs | 8 ++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/test/e2e/engine-builds.test.ts b/test/e2e/engine-builds.test.ts index 0aa519b8..bb3014ef 100644 --- a/test/e2e/engine-builds.test.ts +++ b/test/e2e/engine-builds.test.ts @@ -891,14 +891,29 @@ describe.skipIf(!existsSync(BIN) || FOUNDRY_HOST === null)( }) const afterSecondCheck = await probes() expect(afterSecondCheck).toBe(busyFree + 1) - expect(await accelerators()).toMatchObject({ + const upgraded = await accelerators() + expect(upgraded).toMatchObject({ build: `v2.2.0/${platform}`, accelerators: [ - expect.objectContaining({ name: 'WebGpuExecutionProvider', prepared: true }), - expect.anything(), + { name: 'WebGpuExecutionProvider', prepared: false }, + { name: 'CUDAExecutionProvider', prepared: false }, ], }) + expect(upgraded.accelerators[1]).not.toHaveProperty('reason') expect(await probes()).toBe(afterSecondCheck + 1) + + await json( + await post(ready, '/runtimes/foundry-local/accelerators/prepare', { + accelerators: ['WebGpuExecutionProvider'], + }) + ) + expect(await accelerators()).toMatchObject({ + build: `v2.2.0/${platform}`, + accelerators: [ + { name: 'WebGpuExecutionProvider', prepared: true }, + { name: 'CUDAExecutionProvider', prepared: false }, + ], + }) }, 120_000) } ) diff --git a/test/helpers/fake-foundry-host.mjs b/test/helpers/fake-foundry-host.mjs index bc157e63..75b63442 100644 --- a/test/helpers/fake-foundry-host.mjs +++ b/test/helpers/fake-foundry-host.mjs @@ -10,6 +10,7 @@ */ import { appendFileSync, mkdirSync, rmSync } from 'node:fs' import { createServer } from 'node:http' +import { basename, dirname } from 'node:path' const argv = process.argv.slice(2) const arg = (key) => { @@ -39,10 +40,13 @@ if (argv[0] === 'probe' || argv[0] === 'prepare') { } const prepared = argv.flatMap((a, i) => (argv[i - 1] === '--prepared' ? [a] : [])) if (argv[0] === 'probe') { + // Install probes run in an .incoming directory beside the final platform path. + const release = basename(dirname(arg('--lib') ?? '')) + const version = /^v(\d+\.\d+\.\d+)$/.exec(release)?.[1] ?? '2.1.0' console.log( JSON.stringify({ - c_api_version: arg('--lib')?.includes('v2.4.0') ? 3 : 2, - version: arg('--lib')?.includes('v2.4.0') ? '2.4.0' : '2.1.0', + c_api_version: version === '2.4.0' ? 3 : 2, + version, accelerators: offered.map((name) => ({ name, execution_provider: short(name), From 1368794869e50ea8ae57a2c78b2bce7304dfbf32 Mon Sep 17 00:00:00 2001 From: Biogenic Ooze Date: Wed, 11 Nov 2026 17:03:42 +0300 Subject: [PATCH 4/4] release: v0.22.5 --- package.json | 2 +- src/version.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index a91657c6..7134db8c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@atomic-chat/core", - "version": "0.22.4", + "version": "0.22.5", "repository": { "type": "git", "url": "git+https://github.com/AtomicBot-ai/atomic-chat-core.git" diff --git a/src/version.ts b/src/version.ts index 65ed98d6..0ffda789 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ /** Kept in sync with package.json by `src/version.test.ts`. Bump both together. */ -export const CORE_VERSION = '0.22.4' +export const CORE_VERSION = '0.22.5'