Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: install the newest audio.cpp release and offer it in updates (#13589)

Etherl7b6b2a8e4871
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 8582bc0edb2..30bbc53265c 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -264,7 +264,6 @@
/studio/setup.sh @danielhanchen
/studio/setup.ps1 @danielhanchen
/studio/setup.bat @danielhanchen
-/studio/audio_cpp_prebuilt_pins.json @danielhanchen
/studio/install_audio_cpp_prebuilt.py @danielhanchen
/studio/install_manifest.py @danielhanchen
/studio/install_python_stack.py @danielhanchen
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.yml
index 549163e1318..84ea2adf9cb 100644
--- a/.github/workflows/studio-update-smoke.yml
+++ b/.github/workflows/studio-update-smoke.yml
@@ -28,8 +28,6 @@ on:
- 'studio/prebuilt_core.py'
# install_node_prebuilt.py reads the default version and archive digests from here.
- 'studio/node_prebuilt_pins.json'
- # install_audio_cpp_prebuilt.py checks every runtime archive against these digests.
- - 'studio/audio_cpp_prebuilt_pins.json'
- 'studio/setup.ps1'
- 'install.ps1'
- 'studio/backend/requirements/**'
@@ -102,8 +100,6 @@ on:
- 'studio/prebuilt_core.py'
# install_node_prebuilt.py reads the default version and archive digests from here.
- 'studio/node_prebuilt_pins.json'
- # install_audio_cpp_prebuilt.py checks every runtime archive against these digests.
- - 'studio/audio_cpp_prebuilt_pins.json'
- 'studio/setup.ps1'
- 'install.ps1'
- 'studio/backend/requirements/**'
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index a4ddeedd142..eaf3b1537a2 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -45,7 +45,6 @@ on:
- 'studio/backend/utils/**'
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- - 'studio/audio_cpp_prebuilt_pins.json'
- 'unsloth_cli/**'
# frontend-dist-restore keys its cache on exactly these three globs, and a miss
# makes the checked-out setup.ps1 run npm run build (setup.ps1:5060), so a
@@ -76,7 +75,6 @@ on:
- 'studio/backend/utils/**'
- 'studio/install_*.py'
- 'studio/node_prebuilt_pins.json'
- - 'studio/audio_cpp_prebuilt_pins.json'
- 'unsloth_cli/**'
- 'studio/frontend/*'
- 'studio/frontend/src/**'
diff --git a/studio/audio_cpp_prebuilt_pins.json b/studio/audio_cpp_prebuilt_pins.json
deleted file mode 100644
index a004c45d998..00000000000
--- a/studio/audio_cpp_prebuilt_pins.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "schema_version": 1,
- "comment": "Trust anchor for install_audio_cpp_prebuilt.py: sha256 of each audio.cpp runtime archive, copied from the GitHub release asset digests. Generated; do not edit by hand. To bump: change DEFAULT_TAG / UPSTREAM_FALLBACK_TAG, then run `python studio/install_audio_cpp_prebuilt.py --write-pins` (the same digests `gh release view <tag> -R <repo> --json assets` lists).",
- "releases": {
- "unslothai/audio.cpp": {
- "v0.9.0-unsloth.1": {
- "audio-v0.9.0-unsloth.1-bin-macos-arm64-metal.tar.gz": "8eb13c99d0b1d9fec07b0cea2ab0b2b54cd10c95286c6b628494c8f168fa1f34",
- "audio-v0.9.0-unsloth.1-bin-macos-x64-metal.tar.gz": "da2e7211b507ba456e7c1e3581e1f16f46c8caafd0214d3896854e9680ce9549",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-arm64-cpu.tar.gz": "1ce3a1c976216bbd451a3a16f0db0de6aed94602e652fa9208e03ac447319b9f",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-cpu-portable.tar.gz": "46cc9315efa010bb8a00f20a269bd0f98ddb02d6abaa32a4eef06d20c2457385",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-cpu.tar.gz": "10aecb17d4ea4e45a38c5b206909ad5ab8800ee6203e1cc307ff40f1cc99e680",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-cuda12.tar.gz": "1f7ca305d8ec35560f71e6e928d85826cbd9be8c8fe6f5f87ae87d07fab8682e",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-cuda13.tar.gz": "c4085661930256e66cecb21c3ee578407f17e5d2514e9abdf7f46f047da44cd1",
- "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-vulkan.tar.gz": "9b6e243196d42ac9890a3f0499eb4a0c9d0f6075cb36e0ad06cf327024476793",
- "audio-v0.9.0-unsloth.1-bin-windows-x64-cpu-portable.zip": "05193187d2aaa47806e5dce1f8417cd31ef1a94d544041e4d083f882315ae8c2",
- "audio-v0.9.0-unsloth.1-bin-windows-x64-cpu.zip": "3c3979d2b801b4ae562ee8e00d2d3a657c55f84b80fb5380ab7c779caf20713e",
- "audio-v0.9.0-unsloth.1-bin-windows-x64-cuda12.zip": "ad157f2bd50abbd4d71b9fd370e6e9e73148bae2e3709e5b787fc360c3b08ff6",
- "audio-v0.9.0-unsloth.1-bin-windows-x64-cuda13.zip": "09ee47dd7338dc16722512da2bdad51e1570238f5dca89d307f14aecd1171371",
- "audio-v0.9.0-unsloth.1-bin-windows-x64-vulkan.zip": "ad6eb033d1d5fef44ab8000ec0db2650116f732658a1bc8244b02b0832778264",
- "audio-v0.9.0-unsloth.1-cudart-windows-x64-cuda12.zip": "78ff03c3215e254c5c38c8689a9054287d39d9490626a7c475babd88b326f2a6",
- "audio-v0.9.0-unsloth.1-cudart-windows-x64-cuda13.zip": "3853900a3056a147737f09ffe5f440c3ca8047d4b1ae0554d1799b193db6bd7b"
- }
- },
- "0xShug0/audio.cpp": {
- "v0.9.0": {
- "audio-v0.9.0-bin-macos-arm64-metal.tar.gz": "7cea9219d5f06475011c5d225d71d988cecef633ff7d098ee8a4c7b08583b1b4",
- "audio-v0.9.0-bin-macos-x64-metal.tar.gz": "f6e50c776bfe3b23cb5e420f1dd31b11661ed3dc01207cf05cf780dfdadca1c9",
- "audio-v0.9.0-bin-ubuntu-x64-cpu-portable.tar.gz": "cf87b6baa46cf45fc8a2816b8f04f0f3f3fce32cca297231a4da56543f19fe87",
- "audio-v0.9.0-bin-ubuntu-x64-cpu.tar.gz": "d0f0db4ab13bd3de1c15b6d60256e615d2bac65892fdd4fccc9a2b678db47635",
- "audio-v0.9.0-bin-ubuntu-x64-cuda12.8-colab.tar.gz": "c9ed906f918246669c324f0d31f1b7dd80cbe003c35cf8a54932f333b57ca3f6",
- "audio-v0.9.0-bin-ubuntu-x64-vulkan-portable.tar.gz": "ce661a7b39add12e91f1c7cc590d55854a39ec0a2fd04c004b3fed29cb978398",
- "audio-v0.9.0-bin-ubuntu-x64-vulkan.tar.gz": "9f01f7bedb7aff67d553360ad62fa11db5b638ddbb85d49dd718127575f7d799",
- "audio-v0.9.0-bin-windows-x64-cpu-portable.zip": "3ee19466a1a2b5366364ca8447a4794391dd89671e655ffd01aa421ac1668bfa",
- "audio-v0.9.0-bin-windows-x64-cpu.zip": "6e65c6f112aee53e9f02cee134222915f3a88edf3c7bd0bc7db065683c07dfc5",
- "audio-v0.9.0-bin-windows-x64-cuda12.4.zip": "f935d399b1cabb96422d9b35278dcabbbe7c16638a0e100a9b983421511eeb91",
- "audio-v0.9.0-bin-windows-x64-cuda13.3.zip": "46eb928af284babb3526fc5198da12a4fe4e4445812d60e90a04e82cb5a87786",
- "audio-v0.9.0-bin-windows-x64-vulkan.zip": "f884538138e44528a0bf17bb75dbe7ff7350cb91a14cb72c3e9cc1d4a31d6f1f",
- "audio-v0.9.0-cudart-windows-x64-cuda12.4.zip": "155377e0b18d568002a6cb252a36dc2b96aaa93606c0e44ace945ec3123564fe",
- "audio-v0.9.0-cudart-windows-x64-cuda13.3.zip": "2c7b1054df88a3cb357c005d5284a5d9d6faf14a13885f6cf0e74d966d74c013"
- }
- }
- }
-}
diff --git a/studio/backend/core/inference/audio_cpp_models.py b/studio/backend/core/inference/audio_cpp_models.py
index 59924d3a77e..cae82fadc2c 100644
--- a/studio/backend/core/inference/audio_cpp_models.py
+++ b/studio/backend/core/inference/audio_cpp_models.py
@@ -1840,12 +1840,12 @@ def runtime_spec(family: str) -> Optional[dict]:
def runtime_knows_family(family: str) -> Optional[bool]:
- """Whether the installed runtime loads ``family``; None when Studio cannot tell.
+ """Whether the installed runtime loads ``family``; None when Unsloth Studio cannot tell.
A runtime that ships ``model_specs/`` answers from it. The prebuilt bundles do not ship that
- folder, so for the pinned prebuilt the families its source tree specs are listed in
- ``audio_cpp_spec_families``. Any other runtime (no install, a custom build, another tag) is
- unknown, and the spec's own tasks decide as before.
+ folder, so for the prebuilt releases in ``AUDIO_CPP_SPEC_FAMILIES_TAGS`` the families their
+ source tree specs are listed in ``audio_cpp_spec_families``. Any other runtime (no install, a
+ custom build, an unlisted tag) is unknown, and the spec's own tasks decide as before.
"""
if not family or not re.fullmatch(r"[a-z0-9_]+", family):
return None
@@ -1870,10 +1870,10 @@ def runtime_knows_family(family: str) -> Optional[bool]:
return None
from core.inference.audio_cpp_spec_families import (
AUDIO_CPP_SPEC_FAMILIES,
- AUDIO_CPP_SPEC_FAMILIES_TAG,
+ AUDIO_CPP_SPEC_FAMILIES_TAGS,
)
- if tag != AUDIO_CPP_SPEC_FAMILIES_TAG:
+ if tag not in AUDIO_CPP_SPEC_FAMILIES_TAGS:
return None
return family in AUDIO_CPP_SPEC_FAMILIES
diff --git a/studio/backend/core/inference/audio_cpp_spec_families.py b/studio/backend/core/inference/audio_cpp_spec_families.py
index abeac93f2f3..5e6d108b01b 100644
--- a/studio/backend/core/inference/audio_cpp_spec_families.py
+++ b/studio/backend/core/inference/audio_cpp_spec_families.py
@@ -1,18 +1,19 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""The model families the pinned audio.cpp runtime loads, for prebuilt bundles that ship no ``model_specs/``.
+"""The model families the prebuilt audio.cpp runtime loads, for bundles that ship no ``model_specs/``.
-A family Studio does not list is offered from the tasks its GGUF's spec declares, and that spec can
-be newer than the runtime. This set lets Studio refuse such a family up front instead of failing at
-load with "unsupported model family hint". It holds only for the tag it was generated from.
+A family Unsloth Studio does not list is offered from the tasks its GGUF's spec declares, and that
+spec can be newer than the runtime. This set lets Unsloth Studio refuse such a family up front instead
+of failing at load with "unsupported model family hint". It holds only for the tags it was checked against.
"""
from __future__ import annotations
-AUDIO_CPP_SPEC_FAMILIES_TAG = "v0.9.0-unsloth.1"
+# The unslothai/audio.cpp releases whose model_specs/*.json stems equal the set below. Add a release
+# here once its stems are checked equal; on any change, regenerate the set and keep only matching tags.
+AUDIO_CPP_SPEC_FAMILIES_TAGS = frozenset({"v0.9.0-unsloth.1", "v0.9.1-unsloth.1"})
-# Regenerate on a pin bump: the stems of model_specs/*.json in unslothai/audio.cpp at that tag.
AUDIO_CPP_SPEC_FAMILIES = frozenset(
(
"ace_step",
diff --git a/studio/backend/main.py b/studio/backend/main.py
index f7c3dda77b6..c18aea8f70c 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -2999,6 +2999,7 @@ def get_hardware_info(
**video_capability(),
}
if include_details:
+ from utils.audio_cpp_update import get_installed_audio_cpp_version
from utils.llama_cpp_update import get_installed_llama_version
# All backend-visible GPUs (respects CUDA_VISIBLE_DEVICES); get_gpu_summary reports only the primary. Sort by
@@ -3010,6 +3011,7 @@ def get_hardware_info(
for d in sorted(devices, key = lambda d: d.get("visible_ordinal", 0))
]
body["llama_cpp"] = get_installed_llama_version()
+ body["audio_cpp"] = get_installed_audio_cpp_version()
return body
diff --git a/studio/backend/tests/test_audio_cpp_freshness.py b/studio/backend/tests/test_audio_cpp_freshness.py
new file mode 100644
index 00000000000..fadbf901fa5
--- /dev/null
+++ b/studio/backend/tests/test_audio_cpp_freshness.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The audio.cpp release policy: the tolerant version parser, is_behind with its downgrade guard, and the release caches, including the cache-only read the Audio page status relies on."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import time
+from pathlib import Path
+
+import pytest
+
+from utils import audio_cpp_freshness as fr
+from utils.prebuilt import freshness_flow
+
+_REPO = "unslothai/audio.cpp"
+
+# The same table the installer's release_version_key is held to.
+_VERSIONS = [
+ ("v0.9.1-unsloth.1", (0, 9, 1, 1)),
+ ("v0.9.0-unsloth.1", (0, 9, 0, 1)),
+ ("v0.9.0", (0, 9, 0, 0)),
+ ("v0.8.2-audio8-perf-hotfix-unsloth.1", (0, 8, 2, 1)),
+ ("b123", None),
+ ("", None),
+ (None, None),
+ ("latest", None),
+ # Tags are lowercase-v and carry no spaces; both parsers refuse anything else alike.
+ ("V0.9.1-unsloth.1", None),
+ ("v0.9.1-unsloth.1 rc", None),
+]
+
+
[email protected](autouse = True)
+def _isolated(monkeypatch, tmp_path):
+ monkeypatch.setattr(fr, "_cache_dir", lambda: tmp_path / "audio_cpp_freshness")
+ fr.reset_caches()
+ yield
+ fr.reset_caches()
+
+
+def _no_network(monkeypatch):
+ calls: list = []
+
+ def boom(*args, **kwargs):
+ calls.append(args)
+ raise AssertionError("network fetch")
+
+ monkeypatch.setattr(freshness_flow, "_fetch_newest_published_release", boom)
+ return calls
+
+
+# --- version policy ---
+
+
[email protected]("tag, key", _VERSIONS)
+def test_parse_release_version(tag, key):
+ assert fr.parse_release_version(tag) == key
+
+
+def test_the_installer_parses_the_same_table():
+ installer_path = Path(__file__).resolve().parents[2] / "install_audio_cpp_prebuilt.py"
+ spec = importlib.util.spec_from_file_location("_audio_cpp_installer_parity", installer_path)
+ installer = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(installer)
+ for tag, key in _VERSIONS:
+ assert installer.release_version_key(tag) == key, tag
+ assert installer.release_version_key(tag) == fr.parse_release_version(tag), tag
+
+
+ "installed, latest, behind",
+ [
+ ("v0.9.0-unsloth.1", "v0.9.1-unsloth.1", True),
+ # Upstream's tag carries no serial, so the fork's build of the same version is newer.
+ ("v0.9.0", "v0.9.0-unsloth.1", True),
+ # A hotfix of an older line published last is never offered over the newer install.
+ ("v0.9.1-unsloth.1", "v0.8.2-audio8-perf-hotfix-unsloth.1", False),
+ ("v0.9.1-unsloth.1", "v0.9.1-unsloth.1", False),
+ ("v0.9.1-unsloth.1", "v0.9.0-unsloth.1", False),
+ # No order, no proof the install is older.
+ ("custom-build", "v0.9.1-unsloth.1", False),
+ ("v0.9.0-unsloth.1", "nightly", False),
+ (None, "v0.9.1-unsloth.1", False),
+ ("v0.9.0-unsloth.1", None, False),
+ ],
+)
+def test_is_behind(installed, latest, behind):
+ assert fr.is_behind(installed, latest) is behind
+
+
+# --- release caches ---
+
+
+def test_latest_is_memoized_and_written_to_disk(monkeypatch, tmp_path):
+ calls: list = []
+ monkeypatch.setattr(
+ fr, "_fetch_latest_release_tag", lambda repo: calls.append(repo) or "v0.9.1-unsloth.1"
+ )
+ assert fr.latest_published_release(_REPO) == "v0.9.1-unsloth.1"
+ assert fr.latest_published_release(_REPO) == "v0.9.1-unsloth.1"
+ assert calls == [_REPO]
+ cached = json.loads(
+ (tmp_path / "audio_cpp_freshness" / "unslothai__audio.cpp.json").read_text()
+ )
+ assert cached["latest_tag"] == "v0.9.1-unsloth.1"
+ assert fr.latest_published_release(_REPO, force_refresh = True) == "v0.9.1-unsloth.1"
+ assert calls == [_REPO, _REPO]
+
+
+def test_a_failed_lookup_is_not_retried_on_every_poll(monkeypatch):
+ calls: list = []
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo: calls.append(repo))
+ assert fr.latest_published_release(_REPO) is None
+ assert fr.latest_published_release(_REPO) is None
+ assert calls == [_REPO]
+ # An explicit check skips the failure memo.
+ assert fr.latest_published_release(_REPO, force_refresh = True) is None
+ assert calls == [_REPO, _REPO]
+
+
+def test_a_failed_asset_lookup_is_not_retried_on_every_poll(monkeypatch):
+ calls: list = []
+ monkeypatch.setattr(fr, "_fetch_latest_release_assets", lambda repo: calls.append(repo))
+ assert fr.latest_release_assets(_REPO) is None
+ assert fr.latest_release_assets(_REPO) is None
+ assert calls == [_REPO]
+ assert fr.latest_release_assets(_REPO, force_refresh = True) is None
+ assert calls == [_REPO, _REPO]
+ monkeypatch.setattr(fr, "_fetch_latest_release_assets", lambda repo: {"a.tar.gz": 7})
+ assert fr.latest_release_assets(_REPO, force_refresh = True) == {"a.tar.gz": 7}
+ assert _REPO not in fr._assets_failed_at
+
+
+def test_a_failed_lookup_keeps_the_last_good_value(monkeypatch, tmp_path):
+ freshness_flow.save_disk_cache(
+ _REPO, "v0.9.0-unsloth.1", tmp_path / "audio_cpp_freshness", log_message = "test"
+ )
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo: None)
+ assert fr.latest_published_release(_REPO, force_refresh = True) == "v0.9.0-unsloth.1"
+
+
+def test_the_lookup_goes_through_the_shared_fetch(monkeypatch):
+ seen: list = []
+
+ def newest(repo, timeout, *, log_message):
+ seen.append(repo)
+ return {"tag_name": "v0.9.1-unsloth.1", "assets": [{"name": "a.tar.gz", "size": 7}]}
+
+ monkeypatch.setattr(freshness_flow, "_fetch_newest_published_release", newest)
+ assert fr.latest_published_release(_REPO) == "v0.9.1-unsloth.1"
+ assert fr.latest_release_assets(_REPO) == {"a.tar.gz": 7}
+ assert seen == [_REPO, _REPO]
+
+
+def test_cached_latest_reads_memory_without_the_network(monkeypatch):
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo: "v0.9.1-unsloth.1")
+ fr.latest_published_release(_REPO)
+ calls = _no_network(monkeypatch)
+ assert fr.cached_latest_release(_REPO) == "v0.9.1-unsloth.1"
+ assert calls == []
+
+
+def test_cached_latest_reads_an_expired_disk_cache_without_the_network(monkeypatch, tmp_path):
+ calls = _no_network(monkeypatch)
+ path = freshness_flow.cache_path_for(_REPO, tmp_path / "audio_cpp_freshness")
+ path.parent.mkdir(parents = True)
+ stale = time.time() - 10 * freshness_flow.RELEASE_CACHE_TTL_SECONDS
+ path.write_text(json.dumps({"fetched_at": stale, "latest_tag": "v0.9.1-unsloth.1"}))
+ assert fr.cached_latest_release(_REPO) == "v0.9.1-unsloth.1"
+ assert calls == []
+
+
+def test_cached_latest_is_none_when_nothing_was_looked_up(monkeypatch):
+ calls = _no_network(monkeypatch)
+ assert fr.cached_latest_release(_REPO) is None
+ assert fr.cached_latest_release("") is None
+ assert calls == []
+
+
+def test_reset_caches_can_drop_the_disk_cache(monkeypatch, tmp_path):
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo: "v0.9.1-unsloth.1")
+ monkeypatch.setattr(fr, "_fetch_latest_release_assets", lambda repo: {"a.tar.gz": 1})
+ fr.latest_published_release(_REPO)
+ fr.latest_release_assets(_REPO)
+ fr.reset_caches()
+ # Memory only: the disk cache still answers.
+ assert fr._release_memo == {} and fr._assets_memo == {}
+ assert fr.cached_latest_release(_REPO) == "v0.9.1-unsloth.1"
+ fr.reset_caches(drop_disk = True)
+ assert not (tmp_path / "audio_cpp_freshness").exists()
+ assert fr.cached_latest_release(_REPO) is None
diff --git a/studio/backend/tests/test_audio_cpp_models.py b/studio/backend/tests/test_audio_cpp_models.py
index f27d5b0ffe3..1dfecd9d50b 100644
--- a/studio/backend/tests/test_audio_cpp_models.py
+++ b/studio/backend/tests/test_audio_cpp_models.py
@@ -376,19 +376,14 @@ def _fake_runtime(
return binary
-def test_the_spec_family_list_matches_the_pinned_runtime():
- import importlib.util
-
+def test_the_spec_family_list_covers_the_published_runtimes():
from core.inference.audio_cpp_spec_families import (
AUDIO_CPP_SPEC_FAMILIES,
- AUDIO_CPP_SPEC_FAMILIES_TAG,
+ AUDIO_CPP_SPEC_FAMILIES_TAGS,
)
- installer = Path(__file__).resolve().parents[2] / "install_audio_cpp_prebuilt.py"
- spec = importlib.util.spec_from_file_location("_audio_cpp_installer", installer)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- assert AUDIO_CPP_SPEC_FAMILIES_TAG == module.DEFAULT_TAG
+ # Both releases ship the same model_specs/ stems, so a v0.9.0 install keeps the up-front refusal.
+ assert {"v0.9.0-unsloth.1", "v0.9.1-unsloth.1"} <= AUDIO_CPP_SPEC_FAMILIES_TAGS
for family in ("crisperwhisper", "index_echo", "audio_flamingo", "kugelaudio", "smart_turn"):
assert family not in AUDIO_CPP_SPEC_FAMILIES
for family in ("samsone", "gigaam_asr", "maya1"):
@@ -396,32 +391,30 @@ def test_the_spec_family_list_matches_the_pinned_runtime():
assert set(acm.FAMILIES) - AUDIO_CPP_SPEC_FAMILIES == {"marblenet_vad", "silero_vad"}
-def test_runtime_knows_a_family_from_its_specs_or_the_pinned_list(monkeypatch, tmp_path):
+def test_runtime_knows_a_family_from_its_specs_or_the_listed_tags(monkeypatch, tmp_path):
from core.inference import audio_cpp_server
- from core.inference.audio_cpp_spec_families import AUDIO_CPP_SPEC_FAMILIES_TAG
monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: None)
assert acm.runtime_knows_family("samsone") is None
- _fake_runtime(monkeypatch, tmp_path / "pinned", tag = AUDIO_CPP_SPEC_FAMILIES_TAG)
- assert acm.runtime_knows_family("samsone") is True
- assert acm.runtime_knows_family("crisperwhisper") is False
+ for tag in ("v0.9.0-unsloth.1", "v0.9.1-unsloth.1"):
+ _fake_runtime(monkeypatch, tmp_path / tag, tag = tag)
+ assert acm.runtime_knows_family("samsone") is True
+ assert acm.runtime_knows_family("crisperwhisper") is False
_fake_runtime(monkeypatch, tmp_path / "newer", tag = "v9.9.9-unsloth.1")
assert acm.runtime_knows_family("crisperwhisper") is None
_fake_runtime(monkeypatch, tmp_path / "custom")
assert acm.runtime_knows_family("crisperwhisper") is None
_fake_runtime(
- monkeypatch, tmp_path / "specs", tag = AUDIO_CPP_SPEC_FAMILIES_TAG, specs = ("crisperwhisper",)
+ monkeypatch, tmp_path / "specs", tag = "v0.9.1-unsloth.1", specs = ("crisperwhisper",)
)
assert acm.runtime_knows_family("crisperwhisper") is True
assert acm.runtime_knows_family("samsone") is False
def test_a_spec_fallback_family_the_runtime_lacks_is_refused(hub, monkeypatch, tmp_path):
- from core.inference.audio_cpp_spec_families import AUDIO_CPP_SPEC_FAMILIES_TAG
-
# The hub fixture leaves the runtime out of reach; this test installs one.
monkeypatch.setattr(acm, "runtime_knows_family", _REAL_RUNTIME_KNOWS_FAMILY)
- _fake_runtime(monkeypatch, tmp_path, tag = AUDIO_CPP_SPEC_FAMILIES_TAG)
+ _fake_runtime(monkeypatch, tmp_path, tag = "v0.9.1-unsloth.1")
for family, folder, tasks in (
("gigaam_asr", "GigaAM-v3-GGUF", ["asr"]),
("crisperwhisper", "CrisperWhisper2.0-GGUF", ["asr"]),
diff --git a/studio/backend/tests/test_audio_cpp_runtime_status.py b/studio/backend/tests/test_audio_cpp_runtime_status.py
index 8fec928e4ec..81b60cf1842 100644
--- a/studio/backend/tests/test_audio_cpp_runtime_status.py
+++ b/studio/backend/tests/test_audio_cpp_runtime_status.py
@@ -5,12 +5,14 @@
import asyncio
import json
+import time
import pytest
from core.inference import audio_cpp_server
from routes import inference
-from utils import audio_cpp_update
+from utils import audio_cpp_freshness, audio_cpp_update
+from utils.prebuilt import freshness_flow
def _patch(
@@ -117,7 +119,8 @@ def test_malformed_record_fields_are_dropped(monkeypatch):
assert status["backend"] is None and status["release_tag"] is None
-_LADDER = [("unslothai/audio.cpp", "v0.9.0-unsloth.1"), ("0xShug0/audio.cpp", "v0.9.0")]
+_REPO = "unslothai/audio.cpp"
+_LATEST = "v0.9.1-unsloth.1"
# setup.sh / setup.ps1 leave the managed tree alone when any of these is set.
_SETUP_SKIPS = ("AUDIOCPP_SERVER_PATH", "UNSLOTH_AUDIO_CPP_PATH", "UNSLOTH_SKIP_AUDIO_CPP_INSTALL")
@@ -126,69 +129,149 @@ def _managed(
monkeypatch,
tmp_path,
record,
- ladder = _LADDER,
+ *,
+ pin = None,
+ cached = _LATEST,
):
- """a Studio-managed install of ``record`` and the releases setup would install."""
- for name in _SETUP_SKIPS:
+ """an Unsloth Studio-managed install of ``record``, the configured target, and the newest release already cached."""
+ for name in (*_SETUP_SKIPS, "UNSLOTH_DISABLE_UPDATE_CHECK"):
monkeypatch.delenv(name, raising = False)
tmp_path.mkdir(parents = True, exist_ok = True)
(tmp_path / ".unsloth-studio-owned").touch()
_patch(monkeypatch, binary = str(tmp_path / "audiocpp_server"), record = record, espeak = True)
monkeypatch.setattr(audio_cpp_server, "managed_audio_cpp_dir", lambda: tmp_path)
- monkeypatch.setattr(audio_cpp_update, "_release_ladder", lambda: ladder)
+ monkeypatch.setattr(audio_cpp_update, "_target", lambda: (_REPO, pin))
+ monkeypatch.setattr(audio_cpp_freshness, "_cache_dir", lambda: tmp_path / ".freshness")
+ audio_cpp_freshness.reset_caches()
+ if cached is not None:
+ audio_cpp_freshness._release_memo[_REPO] = (time.time(), cached)
+
+
[email protected](autouse = True)
+def _forget_the_release_cache():
+ yield
+ audio_cpp_freshness.reset_caches()
+
+
+def test_managed_install_of_the_newest_release_is_current(monkeypatch, tmp_path):
+ _managed(monkeypatch, tmp_path, {"published_repo": _REPO, "release_tag": _LATEST})
+ status = inference._audio_cpp_runtime_status()
+ assert status["expected_tag"] == _LATEST
+ assert status["outdated"] is False
-def test_managed_install_of_the_pinned_release_is_current(monkeypatch, tmp_path):
+def test_managed_install_newer_than_the_cached_latest_is_current(monkeypatch, tmp_path):
+ # A stale cache can only under-report: the older "latest" is never offered as a downgrade.
_managed(
monkeypatch,
tmp_path,
- {"published_repo": "unslothai/audio.cpp", "release_tag": "v0.9.0-unsloth.1"},
+ {"published_repo": _REPO, "release_tag": _LATEST},
+ cached = "v0.9.0-unsloth.1",
)
- status = inference._audio_cpp_runtime_status()
- assert status["expected_tag"] == "v0.9.0-unsloth.1"
- assert status["outdated"] is False
+ assert inference._audio_cpp_runtime_status()["outdated"] is False
-def test_managed_fallback_install_is_current(monkeypatch, tmp_path):
- # setup falls back to the upstream release when the fork cannot serve the host.
+def test_managed_upstream_install_is_outdated(monkeypatch, tmp_path):
+ # The removed 0xShug0 fallback rung could leave such a record; an update installs the fork's newest.
_managed(
monkeypatch, tmp_path, {"published_repo": "0xShug0/audio.cpp", "release_tag": "v0.9.0"}
)
- assert inference._audio_cpp_runtime_status()["outdated"] is False
+ status = inference._audio_cpp_runtime_status()
+ assert status["expected_tag"] == _LATEST
+ assert status["outdated"] is True
def test_managed_install_of_an_old_release_is_outdated(monkeypatch, tmp_path):
- # setup keeps the old tree when the release lookup fails after a pin bump.
_managed(
monkeypatch,
tmp_path,
- {"published_repo": "unslothai/audio.cpp", "release_tag": "v0.8.0-unsloth.1"},
+ {"published_repo": _REPO, "release_tag": "v0.9.0-unsloth.1"},
)
status = inference._audio_cpp_runtime_status()
- assert status["release_tag"] == "v0.8.0-unsloth.1"
- assert status["expected_tag"] == "v0.9.0-unsloth.1"
+ assert status["release_tag"] == "v0.9.0-unsloth.1"
+ assert status["expected_tag"] == _LATEST
assert status["outdated"] is True
-def test_same_tag_from_another_repo_is_outdated(monkeypatch, tmp_path):
+def test_nothing_cached_cannot_tell(monkeypatch, tmp_path):
_managed(
- monkeypatch, tmp_path, {"published_repo": "someone/audio.cpp", "release_tag": "v0.9.0"}
+ monkeypatch,
+ tmp_path,
+ {"published_repo": _REPO, "release_tag": "v0.8.0-unsloth.1"},
+ cached = None,
)
- assert inference._audio_cpp_runtime_status()["outdated"] is True
+ status = inference._audio_cpp_runtime_status()
+ assert status["expected_tag"] is None and status["outdated"] is False
-def test_latest_tracking_ladder_cannot_tell(monkeypatch, tmp_path):
- # UNSLOTH_AUDIO_CPP_TAG='' tracks the latest release, which no record can be checked against.
+def test_the_disk_cache_answers_whatever_its_age(monkeypatch, tmp_path):
_managed(
monkeypatch,
tmp_path,
- {"published_repo": "unslothai/audio.cpp", "release_tag": "v0.8.0"},
- ladder = [("unslothai/audio.cpp", None)],
+ {"published_repo": _REPO, "release_tag": "v0.9.0-unsloth.1"},
+ cached = None,
)
+ cache = freshness_flow.cache_path_for(_REPO, tmp_path / ".freshness")
+ cache.parent.mkdir(parents = True)
+ cache.write_text(json.dumps({"fetched_at": 1.0, "latest_tag": _LATEST}))
+ status = inference._audio_cpp_runtime_status()
+ assert status["expected_tag"] == _LATEST and status["outdated"] is True
+
+
[email protected]("cached", [_LATEST, None])
+def test_the_runtime_status_never_touches_the_network(monkeypatch, tmp_path, cached):
+ # /audio/stt/status calls this inside an async handler.
+ _managed(
+ monkeypatch,
+ tmp_path,
+ {"published_repo": _REPO, "release_tag": "v0.9.0-unsloth.1"},
+ cached = cached,
+ )
+ calls: list = []
+
+ def fetch(*args, **kwargs):
+ calls.append(args)
+ raise AssertionError("network fetch")
+
+ monkeypatch.setattr(freshness_flow, "_fetch_newest_published_release", fetch)
+ status = inference._audio_cpp_runtime_status()
+ assert status["outdated"] is (cached is not None)
+ assert calls == []
+
+
+def test_disabled_update_checks_are_not_outdated(monkeypatch, tmp_path):
+ _managed(monkeypatch, tmp_path, {"published_repo": _REPO, "release_tag": "v0.9.0-unsloth.1"})
+ monkeypatch.setenv("UNSLOTH_DISABLE_UPDATE_CHECK", "1")
status = inference._audio_cpp_runtime_status()
assert status["expected_tag"] is None and status["outdated"] is False
+def test_a_pinned_release_is_expected_without_a_lookup(monkeypatch, tmp_path):
+ # UNSLOTH_AUDIO_CPP_TAG names the release setup installs, newer or older.
+ _managed(
+ monkeypatch,
+ tmp_path,
+ {"published_repo": _REPO, "release_tag": _LATEST},
+ pin = "v0.9.0-unsloth.1",
+ cached = None,
+ )
+ status = inference._audio_cpp_runtime_status()
+ assert status["expected_tag"] == "v0.9.0-unsloth.1" and status["outdated"] is True
+ _managed(
+ monkeypatch,
+ tmp_path,
+ {"published_repo": _REPO, "release_tag": "v0.9.0-unsloth.1"},
+ pin = "v0.9.0-unsloth.1",
+ cached = None,
+ )
+ assert inference._audio_cpp_runtime_status()["outdated"] is False
+
+
+def test_same_tag_from_another_repo_is_outdated(monkeypatch, tmp_path):
+ _managed(monkeypatch, tmp_path, {"published_repo": "someone/audio.cpp", "release_tag": _LATEST})
+ assert inference._audio_cpp_runtime_status()["outdated"] is True
+
+
def test_managed_install_without_a_tag_is_not_flagged(monkeypatch, tmp_path):
_managed(monkeypatch, tmp_path, {})
status = inference._audio_cpp_runtime_status()
@@ -253,21 +336,11 @@ def test_release_lookup_error_is_not_outdated(monkeypatch, tmp_path):
def boom():
raise ImportError("installer missing")
- monkeypatch.setattr(audio_cpp_update, "_release_ladder", boom)
+ monkeypatch.setattr(audio_cpp_update, "_target", boom)
status = inference._audio_cpp_runtime_status()
assert status["available"] is True and status["outdated"] is False
-def test_release_ladder_comes_from_the_installer(monkeypatch):
- monkeypatch.delenv("UNSLOTH_AUDIO_CPP_REPO", raising = False)
- monkeypatch.delenv("UNSLOTH_AUDIO_CPP_TAG", raising = False)
- import install_audio_cpp_prebuilt as installer
-
- ladder = audio_cpp_update._release_ladder()
- assert ladder[0] == (installer.DEFAULT_REPO, installer.DEFAULT_TAG)
- assert (installer.UPSTREAM_FALLBACK_REPO, installer.UPSTREAM_FALLBACK_TAG) in ladder
-
-
def test_stt_status_payload_includes_runtime_block(monkeypatch):
_patch(
monkeypatch,
diff --git a/studio/backend/tests/test_audio_cpp_update.py b/studio/backend/tests/test_audio_cpp_update.py
index 3085b5107c0..4378feae916 100644
--- a/studio/backend/tests/test_audio_cpp_update.py
+++ b/studio/backend/tests/test_audio_cpp_update.py
@@ -8,17 +8,26 @@ from __future__ import annotations
import json
import threading
from contextlib import contextmanager
+from pathlib import Path
from types import SimpleNamespace
import pytest
from core.inference import audio_cpp_server, model_slots
from core.inference.audio_cpp_models import AUDIO_CPP_MUSIC_AUDIO_TYPE, AUDIO_CPP_TTS_AUDIO_TYPE
+from utils import audio_cpp_freshness
from utils import audio_cpp_update as aupd
from utils.prebuilt import update_flow
-# A Studio pinned one release past the installed one, so the tests do not depend on the real pin.
-_LADDER = [("unslothai/audio.cpp", "v0.9.1-unsloth.1"), ("0xShug0/audio.cpp", "v0.9.1")]
+_REPO = "unslothai/audio.cpp"
+_LATEST = "v0.9.1-unsloth.1"
+# The newest release's assets: the bundle the recorded one renames to, another host's, and a Windows CUDA pair.
+_ASSETS = {
+ f"audio-{_LATEST}-bin-ubuntu-x64-cpu-portable.tar.gz": 56_000_000,
+ f"audio-{_LATEST}-bin-ubuntu-x64-vulkan.tar.gz": 70_000_000,
+ f"audio-{_LATEST}-bin-windows-x64-cuda12.8.zip": 400_000_000,
+ f"audio-{_LATEST}-cudart-windows-x64-cuda12.8.zip": 300_000_000,
+}
_real_unload = aupd._unload_audio_cpp_models
_SETUP_SKIPS = ("AUDIOCPP_SERVER_PATH", "UNSLOTH_AUDIO_CPP_PATH", "UNSLOTH_SKIP_AUDIO_CPP_INSTALL")
@@ -27,6 +36,7 @@ def _write_record(tree, **fields):
record = {
"published_repo": "unslothai/audio.cpp",
"release_tag": "v0.9.0-unsloth.1",
+ "asset": "audio-v0.9.0-unsloth.1-bin-ubuntu-x64-cpu-portable.tar.gz",
"accelerator": "cpu",
"accelerator_request": "cpu",
**fields,
@@ -36,7 +46,7 @@ def _write_record(tree, **fields):
@pytest.fixture
def managed(monkeypatch, tmp_path):
- """A Studio-managed install of v0.9.0-unsloth.1 under a Studio that pins v0.9.1-unsloth.1."""
+ """An Unsloth Studio-managed install of v0.9.0-unsloth.1 whose repo's newest release is v0.9.1-unsloth.1."""
for name in (*_SETUP_SKIPS, "UNSLOTH_DISABLE_UPDATE_CHECK"):
monkeypatch.delenv(name, raising = False)
tree = tmp_path / "audio.cpp"
@@ -47,31 +57,158 @@ def managed(monkeypatch, tmp_path):
_write_record(tree)
script = tmp_path / "install_audio_cpp_prebuilt.py"
script.write_text("stub")
+ lookups: list = []
+ state = SimpleNamespace(latest = _LATEST, assets = dict(_ASSETS))
+
+ def latest(repo, *, force_refresh = False):
+ lookups.append(("latest", repo, force_refresh))
+ return state.latest
+
+ def assets(repo, *, force_refresh = False):
+ lookups.append(("assets", repo, force_refresh))
+ return state.assets
+
monkeypatch.setattr(audio_cpp_server, "managed_audio_cpp_dir", lambda: tree)
monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: str(binary))
- monkeypatch.setattr(aupd, "_release_ladder", lambda: list(_LADDER))
+ monkeypatch.setattr(aupd, "_target", lambda: (_REPO, None))
monkeypatch.setattr(aupd, "_installer_script", lambda: script)
- return SimpleNamespace(tree = tree, binary = binary, script = script)
+ monkeypatch.setattr(audio_cpp_freshness, "latest_published_release", latest)
+ monkeypatch.setattr(audio_cpp_freshness, "latest_release_assets", assets)
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "x86_64")
+ return SimpleNamespace(tree = tree, binary = binary, script = script, lookups = lookups, state = state)
# --- plan ---
-def test_an_old_managed_runtime_is_offered_the_pinned_release(managed):
+def test_an_old_managed_runtime_is_offered_the_newest_release(managed):
plan = aupd.chained_phase_plan()
assert plan["update_available"] is True and plan["skip_reason"] is None
assert plan["status"] == {
"installed_tag": "v0.9.0-unsloth.1",
- "latest_tag": "v0.9.1-unsloth.1",
- "update_size_bytes": None,
+ "latest_tag": _LATEST,
+ "update_size_bytes": 56_000_000,
}
assert plan["phase"] == {
"install_dir": managed.tree,
"script": managed.script,
"accelerator": "cpu",
"from_tag": "v0.9.0-unsloth.1",
- "to_tag": "v0.9.1-unsloth.1",
+ "to_tag": _LATEST,
+ "pin_release_tag": _LATEST,
+ "repo": _REPO,
}
+ assert ("latest", _REPO, False) in managed.lookups
+
+
+def test_the_size_falls_back_to_the_installers_pick(managed):
+ # An asset name that does not carry the installed tag still sizes the host's bundle.
+ _write_record(
+ managed.tree, asset = "renamed.tar.gz", accelerator = "vulkan", accelerator_request = "auto"
+ )
+ assert aupd.chained_phase_plan()["status"]["update_size_bytes"] == 70_000_000
+
+
+def test_assets_of_another_release_never_decide_the_offer(managed):
+ # After a restart the tag comes from the 24h disk cache while the asset list is fetched fresh, and a
+ # newer release may have been published in between: its assets say nothing about the offered tag.
+ managed.state.assets = {"audio-v0.9.2-unsloth.1-bin-windows-x64-cuda13.zip": 1}
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True and plan["skip_reason"] is None
+ assert plan["status"]["update_size_bytes"] is None
+ assert plan["phase"]["pin_release_tag"] == _LATEST
+ managed.state.assets = {
+ "audio-v0.9.2-unsloth.1-bin-ubuntu-x64-cpu-portable.tar.gz": 1,
+ **_ASSETS,
+ }
+ assert aupd.chained_phase_plan()["status"]["update_size_bytes"] == 56_000_000
+
+
+def test_a_tag_that_extends_the_offered_one_is_another_release(managed, monkeypatch):
+ # Upstream publishes v0.8.2 and later v0.8.2-audio8-perf-hotfix: the hotfix's assets start with
+ # "audio-v0.8.2-" too, yet say nothing about v0.8.2.
+ monkeypatch.setattr(aupd, "_target", lambda: ("0xShug0/audio.cpp", None))
+ _write_record(
+ managed.tree,
+ published_repo = "0xShug0/audio.cpp",
+ release_tag = "v0.8.1",
+ asset = "audio-v0.8.1-bin-ubuntu-x64-cpu-portable.tar.gz",
+ )
+ managed.state.latest = "v0.8.2"
+ managed.state.assets = {"audio-v0.8.2-audio8-perf-hotfix-bin-windows-x64-cpu.zip": 1}
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True and plan["status"]["update_size_bytes"] is None
+ managed.state.assets["audio-v0.8.2-bin-ubuntu-x64-cpu-portable.tar.gz"] = 5
+ assert aupd.chained_phase_plan()["status"]["update_size_bytes"] == 5
+
+
+def test_the_size_adds_the_cuda_runtime_zip(managed, monkeypatch):
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "AMD64")
+ _write_record(
+ managed.tree,
+ asset = "audio-v0.9.0-unsloth.1-bin-windows-x64-cuda12.8.zip",
+ cudart_asset = "audio-v0.9.0-unsloth.1-cudart-windows-x64-cuda12.8.zip",
+ accelerator = "cuda",
+ accelerator_request = "cuda",
+ )
+ assert aupd.chained_phase_plan()["status"]["update_size_bytes"] == 700_000_000
+ # A release without the runtime zip: the installer downloads the bundle alone.
+ del managed.state.assets[f"audio-{_LATEST}-cudart-windows-x64-cuda12.8.zip"]
+ plan = aupd.chained_phase_plan()
+ assert plan["status"]["update_size_bytes"] == 400_000_000 and plan["update_available"] is True
+
+
[email protected]("torch_has_runtime", [False, True])
+def test_the_cuda_runtime_zip_follows_the_current_torch(managed, monkeypatch, torch_has_runtime):
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "AMD64")
+ monkeypatch.setattr(
+ aupd._installer(), "torch_provides_cuda_runtime", lambda major: torch_has_runtime
+ )
+ # The record says nothing about the runtime zip: what the installer does now decides the size.
+ _write_record(
+ managed.tree,
+ asset = "audio-v0.9.0-unsloth.1-bin-windows-x64-cuda12.8.zip",
+ accelerator = "cuda",
+ accelerator_request = "cuda",
+ )
+ size = aupd.chained_phase_plan()["status"]["update_size_bytes"]
+ assert size == (400_000_000 if torch_has_runtime else 700_000_000)
+
+
+def test_another_repos_cuda_bundle_is_sized_like_the_installer_picks(managed, monkeypatch):
+ monkeypatch.setattr(aupd.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(aupd.platform, "machine", lambda: "AMD64")
+ seen = {}
+ installer = aupd._installer()
+ real = installer.resolve_release_asset
+ monkeypatch.setattr(installer, "nvidia_driver_cuda_version", lambda: (12, 8))
+ monkeypatch.setattr(installer, "torch_cuda_major", lambda: 12)
+
+ def resolve(names, **kwargs):
+ seen.update(kwargs)
+ return real(names, **kwargs)
+
+ monkeypatch.setattr(installer, "resolve_release_asset", resolve)
+ _write_record(
+ managed.tree,
+ published_repo = "0xShug0/audio.cpp",
+ release_tag = "v0.9.0",
+ asset = "audio-v0.9.0-bin-windows-x64-cuda12.4.zip",
+ accelerator = "cuda",
+ accelerator_request = "cuda",
+ )
+ aupd.chained_phase_plan()
+ assert seen["driver_cuda"] == (12, 8) and seen["prefer_cuda_major"] == 12
+
+
+def test_unknown_assets_size_nothing_but_still_offer(managed):
+ managed.state.assets = None
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True
+ assert plan["status"]["update_size_bytes"] is None
def test_an_automatic_install_keeps_detecting_the_host(managed):
@@ -84,6 +221,7 @@ def test_a_runtime_setup_skips_is_unmanaged(managed, monkeypatch, name):
monkeypatch.setenv(name, "1" if name == "UNSLOTH_SKIP_AUDIO_CPP_INSTALL" else "/elsewhere")
plan = aupd.chained_phase_plan()
assert plan["update_available"] is False and plan["skip_reason"] == "unmanaged"
+ assert managed.lookups == []
def test_a_tree_without_the_ownership_marker_is_unmanaged(managed):
@@ -105,34 +243,87 @@ def test_no_runtime_is_not_installed(managed, monkeypatch):
assert plan["skip_reason"] == "not_installed" and plan["status"] is None
[email protected]("repo, tag", _LADDER)
-def test_either_rung_is_up_to_date(managed, repo, tag):
- _write_record(managed.tree, published_repo = repo, release_tag = tag)
[email protected]("tag", [_LATEST, "v0.9.2-unsloth.1", "v1.0.0"])
+def test_the_newest_or_a_newer_release_is_up_to_date(managed, tag):
+ _write_record(managed.tree, release_tag = tag)
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is False and plan["skip_reason"] == "up_to_date"
+ assert plan["status"]["latest_tag"] == _LATEST
+
+
+def test_a_hotfix_published_last_is_not_offered_as_a_downgrade(managed):
+ _write_record(managed.tree, release_tag = _LATEST)
+ managed.state.latest = "v0.8.2-audio8-perf-hotfix-unsloth.1"
plan = aupd.chained_phase_plan()
assert plan["update_available"] is False and plan["skip_reason"] == "up_to_date"
-def test_a_latest_tracking_ladder_cannot_compare(managed, monkeypatch):
- monkeypatch.setattr(aupd, "_release_ladder", lambda: [("unslothai/audio.cpp", None)])
- assert aupd.chained_phase_plan()["skip_reason"] == "tracks_latest"
+def test_an_unknown_latest_offers_nothing(managed):
+ managed.state.latest = None
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is False and plan["skip_reason"] == "up_to_date"
+ assert plan["phase"] is None
+
+
+def test_a_record_without_a_tag_is_up_to_date(managed):
+ _write_record(managed.tree, release_tag = None)
+ assert aupd.chained_phase_plan()["skip_reason"] == "up_to_date"
+
+
+def test_an_upstream_install_is_offered_the_forks_newest(managed):
+ # The removed 0xShug0 fallback rung could leave such a record; the configured repo replaces it.
+ _write_record(
+ managed.tree,
+ published_repo = "0xShug0/audio.cpp",
+ release_tag = "v0.9.1",
+ asset = "audio-v0.9.1-bin-ubuntu-x64-cpu-portable.tar.gz",
+ )
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True
+ assert plan["phase"]["pin_release_tag"] == _LATEST
+ assert plan["phase"]["repo"] == _REPO
+ assert plan["status"]["update_size_bytes"] == 56_000_000
+
+
+def test_an_upstream_install_is_left_alone_while_latest_is_unknown(managed):
+ _write_record(managed.tree, published_repo = "0xShug0/audio.cpp", release_tag = "v0.9.0")
+ managed.state.latest = None
+ assert aupd.chained_phase_plan()["skip_reason"] == "up_to_date"
+
+
+def test_force_refresh_reaches_the_release_lookup(managed):
+ aupd.chained_phase_plan(force_refresh = True)
+ assert ("latest", _REPO, True) in managed.lookups
+ assert ("assets", _REPO, True) in managed.lookups
-def test_disabled_update_checks_skip_the_offer(managed, monkeypatch):
+def test_a_pinned_tag_is_compared_with_no_lookup(managed, monkeypatch):
+ monkeypatch.setattr(aupd, "_target", lambda: (_REPO, "v0.9.0-unsloth.1"))
+ plan = aupd.chained_phase_plan()
+ assert plan["skip_reason"] == "up_to_date"
+ assert plan["status"]["latest_tag"] == "v0.9.0-unsloth.1"
+ monkeypatch.setattr(aupd, "_target", lambda: (_REPO, "v0.8.0-unsloth.1"))
+ plan = aupd.chained_phase_plan()
+ assert plan["update_available"] is True
+ assert plan["phase"]["pin_release_tag"] == "v0.8.0-unsloth.1"
+ assert plan["status"]["update_size_bytes"] is None
+ assert managed.lookups == []
+
+
+def test_disabled_update_checks_skip_the_offer_without_a_lookup(managed, monkeypatch):
# Without this skip the union would show a card that start_update refuses.
monkeypatch.setenv("UNSLOTH_DISABLE_UPDATE_CHECK", "1")
assert aupd.chained_phase_plan()["skip_reason"] == "update_checks_disabled"
+ assert managed.lookups == []
+ monkeypatch.setattr(aupd, "_target", lambda: (_REPO, "v0.8.0-unsloth.1"))
+ assert aupd.chained_phase_plan()["skip_reason"] == "update_checks_disabled"
+ assert managed.lookups == []
-def test_a_host_no_pinned_bundle_covers_has_no_prebuilt(managed, monkeypatch):
- installer = aupd._installer()
- pins = {
- repo: {tag: {f"audio-{tag}-bin-windows-x64-cpu.zip": "0" * 64}} for repo, tag in _LADDER
- }
- monkeypatch.setattr(installer, "load_pins", lambda path = None: pins)
- monkeypatch.setattr(aupd.platform, "system", lambda: "Linux")
- monkeypatch.setattr(aupd.platform, "machine", lambda: "x86_64")
+def test_a_host_the_newest_release_does_not_cover_has_no_prebuilt(managed, monkeypatch):
+ managed.state.assets = {f"audio-{_LATEST}-bin-windows-x64-cpu.zip": 1}
assert aupd.chained_phase_plan()["skip_reason"] == "no_prebuilt"
- # The same pins cover a Windows host.
+ # The same release covers a Windows host.
monkeypatch.setattr(aupd.platform, "system", lambda: "Windows")
assert aupd.chained_phase_plan()["update_available"] is True
@@ -142,12 +333,7 @@ def test_an_explicit_accelerator_is_not_offered_the_cpu_bundle(
managed, monkeypatch, request_, offered
):
# The installer never downgrades an explicit request, so a CPU-only release cannot satisfy it.
- installer = aupd._installer()
- pins = {
- repo: {tag: {f"audio-{tag}-bin-ubuntu-arm64-cpu.tar.gz": "0" * 64}} for repo, tag in _LADDER
- }
- monkeypatch.setattr(installer, "load_pins", lambda path = None: pins)
- monkeypatch.setattr(aupd.platform, "system", lambda: "Linux")
+ managed.state.assets = {f"audio-{_LATEST}-bin-ubuntu-arm64-cpu.tar.gz": 1}
monkeypatch.setattr(aupd.platform, "machine", lambda: "aarch64")
_write_record(managed.tree, accelerator = "vulkan", accelerator_request = request_)
plan = aupd.chained_phase_plan()
@@ -164,16 +350,27 @@ def test_a_probe_that_raises_is_a_skip(managed, monkeypatch):
def boom():
raise OSError("unreadable")
- monkeypatch.setattr(aupd, "_release_ladder", boom)
- plan = aupd.chained_phase_plan()
+ monkeypatch.setattr(aupd, "_target", boom)
+ plan = aupd.chained_phase_plan(force_refresh = True)
assert plan["update_available"] is False and plan["skip_reason"] == "unavailable"
-def test_the_pinned_ladder_comes_from_the_installer(monkeypatch):
+ "env, target",
+ [
+ ({}, (_REPO, None)),
+ ({"UNSLOTH_AUDIO_CPP_TAG": ""}, (_REPO, None)),
+ ({"UNSLOTH_AUDIO_CPP_TAG": "Latest"}, (_REPO, None)),
+ ({"UNSLOTH_AUDIO_CPP_TAG": "v0.9.0-unsloth.1"}, (_REPO, "v0.9.0-unsloth.1")),
+ ({"UNSLOTH_AUDIO_CPP_REPO": "someone/audio.cpp"}, ("someone/audio.cpp", None)),
+ ],
+)
+def test_the_target_comes_from_the_installer_env(monkeypatch, env, target):
monkeypatch.delenv("UNSLOTH_AUDIO_CPP_REPO", raising = False)
monkeypatch.delenv("UNSLOTH_AUDIO_CPP_TAG", raising = False)
- installer = aupd._installer()
- assert aupd._release_ladder()[0] == (installer.DEFAULT_REPO, installer.DEFAULT_TAG)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ assert aupd._target() == target
# --- run ---
@@ -202,14 +399,18 @@ def run_env(managed, monkeypatch):
monkeypatch.setattr(stt_audiocpp_sidecar, "get_audio_cpp_stt_sidecar", lambda: _Sidecar(events))
monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: events.append("unload") or False)
- def _installer(new_tag = "v0.9.1-unsloth.1", error = None):
+ def _installer(
+ new_tag = "v0.9.1-unsloth.1",
+ error = None,
+ published_repo = _REPO,
+ ):
def _stream(cmd, env, *, set_progress, timeout_seconds):
events.append("install")
calls.update(cmd = cmd, env = env, flag = audio_cpp_server.UPDATE_IN_PROGRESS.is_set())
if error is not None:
raise error
set_progress(0.5)
- _write_record(managed.tree, release_tag = new_tag)
+ _write_record(managed.tree, release_tag = new_tag, published_repo = published_repo)
monkeypatch.setattr(update_flow, "stream_installer", _stream)
@@ -239,10 +440,69 @@ def test_the_installer_gets_the_managed_dir_and_recorded_accelerator(run_env, ma
str(managed.tree),
"--accelerator",
"cpu",
+ "--published-release-tag",
+ _LATEST,
+ "--keep-newer",
]
assert run_env.calls["env"]["UNSLOTH_PROGRESS_PERCENT_STEP"] == "5"
[email protected]("kept", [False, True])
+def test_the_release_cache_is_refreshed_after_the_install(run_env, managed, monkeypatch, kept):
+ events = run_env.events
+ monkeypatch.setattr(
+ audio_cpp_freshness,
+ "reset_caches",
+ lambda *, drop_disk = False: events.append(("reset", drop_disk)),
+ )
+ if kept:
+ run_env.installer(new_tag = "v0.9.0-unsloth.1")
+ managed.lookups.clear()
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert events[events.index("install") + 1] == ("reset", True)
+ assert managed.lookups == [("latest", _REPO, True)]
+
+
+def test_a_failed_release_refresh_does_not_fail_the_install(run_env, monkeypatch):
+ def offline(repo, *, force_refresh = False):
+ raise OSError("offline")
+
+ monkeypatch.setattr(audio_cpp_freshness, "latest_published_release", offline)
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert result["to_tag"] == _LATEST
+
+
+def test_the_install_drops_the_on_disk_release_cache(run_env, managed, monkeypatch, tmp_path):
+ cache = tmp_path / "audio_cpp_freshness"
+ monkeypatch.setattr(audio_cpp_freshness, "_cache_dir", lambda: cache)
+ cache.mkdir()
+ (cache / "unslothai__audio.cpp.json").write_text(
+ json.dumps({"fetched_at": 1.0, "latest_tag": "v0.9.0-unsloth.1"})
+ )
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert not cache.exists()
+ assert audio_cpp_freshness.cached_latest_release(_REPO) is None
+
+
+def test_a_newer_runtime_installed_since_the_plan_is_not_downgraded(run_env, managed):
+ _write_record(managed.tree, release_tag = "v0.9.2-unsloth.1")
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert "install" not in run_env.events
+ assert result["to_tag"] == "v0.9.2-unsloth.1"
+ assert result["message"] == "audio.cpp is already at v0.9.2-unsloth.1."
+
+
+def test_a_user_pin_still_installs_an_older_release(run_env, managed, monkeypatch):
+ monkeypatch.setattr(aupd, "_target", lambda: (_REPO, "v0.9.0-unsloth.1"))
+ _write_record(managed.tree, release_tag = "v0.9.2-unsloth.1")
+ run_env.installer(new_tag = "v0.9.0-unsloth.1")
+ phase = dict(run_env.phase, to_tag = "v0.9.0-unsloth.1", pin_release_tag = "v0.9.0-unsloth.1")
+ result = aupd.run_chained_phase(phase, lambda fraction: None)
+ assert "install" in run_env.events
+ assert result["to_tag"] == "v0.9.0-unsloth.1"
+ assert "--keep-newer" not in run_env.calls["cmd"]
+
+
def test_an_unloaded_model_asks_for_a_reload(run_env, monkeypatch):
monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: True)
result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
@@ -296,6 +556,29 @@ def test_a_kept_tree_is_not_reported_as_updated(run_env):
)
+def test_a_same_tag_from_another_repo_is_reported_as_updated(managed, run_env, monkeypatch):
+ # UNSLOTH_AUDIO_CPP_REPO switched to a repo whose newest release has the installed tag.
+ _write_record(
+ managed.tree,
+ published_repo = "0xShug0/audio.cpp",
+ release_tag = _LATEST,
+ asset = f"audio-{_LATEST}-bin-ubuntu-x64-cpu-portable.tar.gz",
+ )
+ monkeypatch.setattr(aupd, "_target", lambda: ("someone/audio.cpp", None))
+ phase = aupd.chained_phase_plan()["phase"]
+ run_env.installer(new_tag = _LATEST, published_repo = "someone/audio.cpp")
+ result = aupd.run_chained_phase(phase, lambda fraction: None)
+ assert result["message"] == f"Updated audio.cpp to {_LATEST}."
+
+
+def test_a_runtime_already_at_the_offered_release_is_not_reported_as_kept(managed, run_env):
+ # A setup run installed the offered release between the plan and the in-app install.
+ _write_record(managed.tree, release_tag = _LATEST)
+ run_env.installer(new_tag = _LATEST)
+ result = aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert result["message"] == f"Updated audio.cpp to {_LATEST}."
+
+
def test_a_kept_tree_still_asks_for_a_reload_after_an_unload(run_env, monkeypatch):
monkeypatch.setattr(aupd, "_unload_audio_cpp_models", lambda: True)
run_env.installer(new_tag = "v0.9.0-unsloth.1")
@@ -331,6 +614,19 @@ def test_a_rate_limit_gets_token_advice(run_env, monkeypatch):
aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+def test_an_unreachable_release_fails_the_update_and_says_the_install_was_kept(run_env):
+ tail = (
+ "installer exited 1: audio.cpp: unslothai/audio.cpp release lookup failed (network is unreachable)\n"
+ "error: no audio.cpp release lookup answered (unslothai/audio.cpp v0.9.1-unsloth.1: network is unreachable)\n"
+ )
+ run_env.installer(error = update_flow.InstallerExit(1, tail))
+ with pytest.raises(RuntimeError) as info:
+ aupd.run_chained_phase(run_env.phase, lambda fraction: None)
+ assert str(info.value) == (
+ "Could not reach the audio.cpp release on GitHub, so the existing install was kept. Try again later."
+ )
+
+
def test_no_sidecar_coordination_fails_closed(run_env, monkeypatch):
from core.inference import stt_audiocpp_sidecar
@@ -453,3 +749,33 @@ def test_a_kept_audio_cpp_slot_is_dropped(slots):
model_slots.slots[:] = [music, chat]
assert aupd._unload_audio_cpp_models() is True
assert slots.dropped == [music]
+
+
+# --- installed version (Settings > About) ---
+
+
+def test_the_installed_version_is_the_records_release_tag(managed):
+ assert aupd.get_installed_audio_cpp_version() == "v0.9.0-unsloth.1"
+
+
+def test_no_runtime_has_no_installed_version(managed, monkeypatch):
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", lambda: None)
+ assert aupd.get_installed_audio_cpp_version() is None
+
+
+def test_a_build_without_a_record_has_no_installed_version(managed):
+ (managed.tree / audio_cpp_server.INSTALL_RECORD).unlink()
+ assert aupd.get_installed_audio_cpp_version() is None
+
+
+def test_a_probe_that_raises_has_no_installed_version(managed, monkeypatch):
+ def unreadable():
+ raise OSError("unreadable")
+
+ monkeypatch.setattr(audio_cpp_server, "find_audio_cpp_server_binary", unreadable)
+ assert aupd.get_installed_audio_cpp_version() is None
+
+
+def test_the_hardware_details_report_the_installed_version():
+ main = (Path(aupd.__file__).resolve().parents[1] / "main.py").read_text(encoding = "utf-8")
+ assert 'body["audio_cpp"] = get_installed_audio_cpp_version()' in main
diff --git a/studio/backend/tests/test_combined_update.py b/studio/backend/tests/test_combined_update.py
index 5b2303b94b4..4e1b41eca4b 100644
--- a/studio/backend/tests/test_combined_update.py
+++ b/studio/backend/tests/test_combined_update.py
@@ -181,7 +181,7 @@ def _clean_state(monkeypatch, tmp_path):
monkeypatch.setattr(
aupd,
"chained_phase_plan",
- lambda: {
+ lambda **_kw: {
"status": None,
"update_available": False,
"skip_reason": "not_installed",
@@ -269,8 +269,8 @@ def _setup_audio(
"""An offered audio.cpp phase whose runs are recorded instead of installing."""
plans = []
- def _plan():
- plans.append("audio")
+ def _plan(**kw):
+ plans.append(("audio", kw))
return {
"status": dict(_AUDIO_STATUS),
"update_available": True,
@@ -1064,6 +1064,15 @@ def test_status_union_audio_only_surfaces_update(monkeypatch, tmp_path):
assert st["installed_tag"] == "b9518"
[email protected]("force_refresh", [True, False])
+def test_status_force_refresh_reaches_audio(monkeypatch, tmp_path, force_refresh):
+ _setup_llama(monkeypatch, tmp_path, installed = "b9518", latest = "b9518")
+ _setup_whisper(monkeypatch, tmp_path, installed = "v1.9.2-unsloth.1", latest = "v1.9.2-unsloth.1")
+ plans = _setup_audio(monkeypatch, [])
+ upd.get_update_status(force_refresh = force_refresh)
+ assert plans == [("audio", {"force_refresh": force_refresh})]
+
+
def test_status_llama_keeps_the_card_name_over_audio(monkeypatch, tmp_path):
_setup_llama(monkeypatch, tmp_path)
_setup_audio(monkeypatch, [])
@@ -1082,7 +1091,7 @@ def test_status_whisper_keeps_the_card_name_over_audio(monkeypatch, tmp_path):
def test_status_survives_audio_probe_failure(monkeypatch, tmp_path):
_setup_llama(monkeypatch, tmp_path)
- def _boom():
+ def _boom(**_kw):
raise RuntimeError("probe exploded")
monkeypatch.setattr(aupd, "chained_phase_plan", _boom)
diff --git a/studio/backend/utils/audio_cpp_freshness.py b/studio/backend/utils/audio_cpp_freshness.py
new file mode 100644
index 00000000000..7a5e187cb75
--- /dev/null
+++ b/studio/backend/utils/audio_cpp_freshness.py
@@ -0,0 +1,148 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""audio.cpp prebuilt freshness: the newest published release of the configured audio.cpp repo (unslothai/audio.cpp unless UNSLOTH_AUDIO_CPP_REPO says otherwise) and the version policy utils.audio_cpp_update compares the install record against. Fails open on any missing data so we never offer a misleading update. The mechanics (GitHub fetch, memo + disk cache, the shared rate-limit lockout) live in utils.prebuilt.freshness_flow; this module keeps the audio version policy and the per-module caches its tests patch. Unlike whisper it does not use freshness_flow.check_freshness, which reads the repo from the install marker: an install from another repo is checked against the configured one."""
+
+from __future__ import annotations
+
+import re
+import time
+from pathlib import Path
+from typing import Optional
+
+import structlog
+
+from utils.prebuilt import freshness_flow as _flow
+
+logger = structlog.get_logger(__name__)
+
+_release_memo: dict[str, tuple[float, Optional[str]]] = {}
+# The combined update status is polled, so an offline host pays the fetch deadline once a minute, not on every poll.
+_release_failed_at: dict[str, float] = {}
+# Newest-release asset sizes (name -> bytes), memoized like the tag (24h TTL).
+_assets_memo: dict[str, tuple[float, dict[str, int]]] = {}
+# An offline host with a disk-cached newer tag still asks for its assets: without this every poll pays the fetch deadline.
+_assets_failed_at: dict[str, float] = {}
+
+# A leading v?X.Y[.Z], any middle label (``-audio8-perf-hotfix``), then an optional ``-unsloth.N``.
+_VERSION = re.compile(r"v?(\d+)\.(\d+)(?:\.(\d+))?(?:-\S*)?")
+_UNSLOTH_SERIAL = re.compile(r"-unsloth\.(\d+)$")
+
+
+def _cache_dir() -> Path:
+ """Lazy import so tests can stub storage_roots."""
+ try:
+ from utils.paths.storage_roots import cache_root
+ return cache_root() / "audio_cpp_freshness"
+ except Exception:
+ return Path.home() / ".unsloth" / "studio" / "cache" / "audio_cpp_freshness"
+
+
+def _save_disk_cache(repo: str, latest_tag: Optional[str]) -> None:
+ _flow.save_disk_cache(
+ repo, latest_tag, _cache_dir(), log_message = "audio.cpp freshness cache write failed"
+ )
+
+
+def _fetch_latest_release_tag(repo: str, timeout: float = 5.0) -> Optional[str]:
+ """Newest published release tag for `repo`, by publish time (see freshness_flow for why this is not GitHub's /releases/latest pointer)."""
+ return _flow.fetch_latest_release_tag(
+ repo, timeout, log_message = "audio.cpp freshness fetch failed"
+ )
+
+
+def latest_published_release(repo: str, *, force_refresh: bool = False) -> Optional[str]:
+ """Newest release tag for `repo`, with 24h success and 60s failure caches. None when offline and never previously cached."""
+ return _flow.latest_published_release(
+ repo,
+ force_refresh = force_refresh,
+ memo = _release_memo,
+ failed_at = _release_failed_at,
+ cache_dir = lambda: _cache_dir(),
+ fetch = lambda r: _fetch_latest_release_tag(r),
+ save = lambda r, tag: _save_disk_cache(r, tag),
+ )
+
+
+def cached_latest_release(repo: str) -> Optional[str]:
+ """The newest release tag already known for `repo`, from memory or the disk cache whatever its age. Never touches the network: the Audio page status reads this inside an async handler. A stale value can only under-report, since an older "latest" is never behind (see is_behind)."""
+ if not repo:
+ return None
+ cached = _release_memo.get(repo)
+ if cached:
+ return cached[1]
+ disk = _flow.load_disk_cache(repo, _cache_dir())
+ return disk[1] if disk else None
+
+
+def _fetch_latest_release_assets(repo: str, timeout: float = 5.0) -> Optional[dict[str, int]]:
+ """Asset name -> size (bytes) for the newest published release of `repo`, selected exactly like _fetch_latest_release_tag. None on any failure."""
+ return _flow.fetch_latest_release_assets(
+ repo, timeout, log_message = "audio.cpp freshness asset fetch failed"
+ )
+
+
+def latest_release_assets(repo: str, *, force_refresh: bool = False) -> Optional[dict[str, int]]:
+ """Newest-release asset sizes for `repo`, memoized (24h TTL) with the same 60s failure cache as the tag. None when offline and never fetched. In-memory only, so a restart simply re-fetches."""
+ failed = _assets_failed_at.get(repo)
+ if (
+ not force_refresh
+ and failed is not None
+ and time.monotonic() - failed < _flow.RELEASE_FAILURE_CACHE_TTL_SECONDS
+ ):
+ cached = _assets_memo.get(repo)
+ return cached[1] if cached else None
+ fetched = []
+
+ def _fetch(r: str) -> Optional[dict[str, int]]:
+ assets = _fetch_latest_release_assets(r)
+ fetched.append(assets)
+ return assets
+
+ assets = _flow.latest_release_assets(
+ repo, force_refresh = force_refresh, memo = _assets_memo, fetch = _fetch
+ )
+ if fetched and fetched[-1] is None:
+ _assets_failed_at[repo] = time.monotonic()
+ elif fetched:
+ _assets_failed_at.pop(repo, None)
+ return assets
+
+
+def parse_release_version(tag: object) -> Optional[tuple]:
+ """Comparable key ``(major, minor, patch, unsloth_serial)`` for a tag like ``v0.9.1-unsloth.1``. Tolerant of a missing ``v``, patch or ``-unsloth.N`` (each then 0) and of a middle label such as ``-audio8-perf-hotfix``, which is ignored. None for anything else. Keep in step with release_version_key in install_audio_cpp_prebuilt.py, which runs before the backend can be imported; a parity test holds the two to one table."""
+ if not isinstance(tag, str):
+ return None
+ s = tag.strip()
+ m = _VERSION.fullmatch(s)
+ if not m:
+ return None
+ serial = _UNSLOTH_SERIAL.search(s)
+ return (
+ int(m.group(1)),
+ int(m.group(2)),
+ int(m.group(3) or 0),
+ int(serial.group(1)) if serial else 0,
+ )
+
+
+def is_behind(installed: Optional[str], latest: Optional[str]) -> bool:
+ """Whether `installed` is genuinely behind `latest`: identical tags are not behind; when both parse, behind only when the latest key is strictly greater (the downgrade guard: v0.8.2-audio8-perf-hotfix-unsloth.1 published after v0.9.1-unsloth.1 is never offered over it). Unlike whisper, a tag that does not parse is never behind: with no order there is no proof the install is older."""
+ if not installed or not latest:
+ return False
+ installed, latest = installed.strip(), latest.strip()
+ if installed == latest:
+ return False
+ installed_key, latest_key = parse_release_version(installed), parse_release_version(latest)
+ if installed_key is None or latest_key is None:
+ return False
+ return latest_key > installed_key
+
+
+def reset_caches(*, drop_disk: bool = False) -> None:
+ """Drop the in-memory freshness caches. The no-arg form is test-only. With ``drop_disk = True`` also delete the on-disk 24h release cache, used after an install: clearing memory alone leaves the old value on disk, so an offline refresh would replay it and the offer could point at the build just replaced."""
+ _flow.reset_caches(
+ (_release_memo, _release_failed_at, _assets_memo, _assets_failed_at),
+ drop_disk = drop_disk,
+ cache_dir = lambda: _cache_dir(),
+ )
diff --git a/studio/backend/utils/audio_cpp_update.py b/studio/backend/utils/audio_cpp_update.py
index 80416a641e1..2e4a565f934 100644
--- a/studio/backend/utils/audio_cpp_update.py
+++ b/studio/backend/utils/audio_cpp_update.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""In-app audio.cpp runtime update: the third phase of the combined llama.cpp update item (utils.llama_cpp_update chains run_chained_phase after the whisper phase). Unlike llama.cpp and whisper.cpp, audio.cpp is pinned in source: the target is the release install_audio_cpp_prebuilt.py would install for this Studio (its release ladder and sha256 pins), never GitHub's latest, so the status needs no network call. Only the Studio-managed tree is offered, the same predicate the Audio page notice reads. The mechanics (the streamed installer run, the chained job) live in utils.prebuilt.update_flow; this module keeps the audio.cpp policy."""
+"""In-app audio.cpp runtime update: the third phase of the combined llama.cpp update item (utils.llama_cpp_update chains run_chained_phase after the whisper phase). Like llama.cpp and whisper.cpp, the target tracks the newest unslothai/audio.cpp release (or the release UNSLOTH_AUDIO_CPP_TAG names, which needs no network call), looked up through utils.audio_cpp_freshness. Only the Unsloth Studio-managed tree is offered, the same predicate the Audio page notice reads. The mechanics (the streamed installer run, the chained job) live in utils.prebuilt.update_flow; this module keeps the audio.cpp policy."""
from __future__ import annotations
@@ -13,6 +13,7 @@ from typing import Optional
import structlog
+from utils import audio_cpp_freshness as _freshness
from utils.prebuilt import update_flow as _flow
from utils.update_status import update_checks_disabled
@@ -41,8 +42,10 @@ def _installer():
return install_audio_cpp_prebuilt
-def _release_ladder() -> list:
- return _installer()._release_ladder()
+def _target() -> tuple[str, Optional[str]]:
+ """``(repo, pin)`` the installer would install from: the configured repo, and the release UNSLOTH_AUDIO_CPP_TAG pins (None tracks the newest)."""
+ installer = _installer()
+ return installer._repo(), installer._pinned_tag()
def _installer_script() -> Optional[Path]:
@@ -71,44 +74,101 @@ def _tag(record: dict) -> Optional[str]:
return tag if isinstance(tag, str) and tag else None
+def get_installed_audio_cpp_version() -> Optional[str]:
+ """Display string for the active audio.cpp runtime: the release tag its install record names (e.g. 'v0.9.1-unsloth.1'), or None for no runtime or a custom build without a record. Reads only that record, no network and no exec, so it is safe on the About panel's path."""
+ from core.inference import audio_cpp_server
+ try:
+ binary = audio_cpp_server.find_audio_cpp_server_binary()
+ return _tag(audio_cpp_server.read_install_record(binary)) if binary else None
+ except Exception as exc: # noqa: BLE001 - the About panel omits the row rather than failing
+ logger.debug("audio.cpp version probe failed: %s", exc)
+ return None
+
+
def release_status(binary: str, record: dict) -> dict:
- """``expected_tag`` and ``outdated`` for an installed runtime: the release this Studio would install, and whether the record names neither rung of the ladder. Raises when the ladder cannot be read; callers treat that as current."""
+ """``expected_tag`` and ``outdated`` for an installed runtime: the release an update would install, and whether the record is behind it or from another repo. Reads only the cached newest release, never the network, since the async Audio page status calls this. Raises when the installer cannot be read; callers treat that as current."""
status = {"expected_tag": None, "outdated": False}
- if _tag(record) is None or not _is_managed(binary):
+ tag = _tag(record)
+ if tag is None or not _is_managed(binary):
return status
- ladder = _release_ladder()
- # a None tag tracks the latest release, so an installed release cannot be compared.
- if ladder and all(tag for _, tag in ladder):
- status["expected_tag"] = ladder[0][1]
- status["outdated"] = (record.get("published_repo"), _tag(record)) not in ladder
+ repo, pin = _target()
+ if pin:
+ status["expected_tag"] = pin
+ status["outdated"] = (record.get("published_repo"), tag) != (repo, pin)
+ return status
+ if update_checks_disabled():
+ return status
+ latest = _freshness.cached_latest_release(repo)
+ if latest is None:
+ return status
+ status["expected_tag"] = latest
+ status["outdated"] = record.get("published_repo") != repo or _freshness.is_behind(tag, latest)
return status
def _host_has_prebuilt(
- ladder: list,
+ names: Optional[list],
accelerator: Optional[str],
explicit: Optional[str] = None,
) -> bool:
- """Whether any pinned rung publishes a bundle for this host. Offline: the pins list every asset name. A rung without pins (a release the user picked) can only be answered by the online lookup, so it counts as available. An explicit request is never downgraded to CPU by the installer, so only it is checked."""
+ """Whether the newest release publishes a bundle for this host. Unknown names (offline, or a pinned tag) can only be answered by the installer, so they count as available. An explicit request is never downgraded to CPU by the installer, so only it is checked."""
+ if not names:
+ return True
installer = _installer()
- pins = installer.load_pins()
accels = (explicit,) if explicit else tuple(dict.fromkeys((accelerator or "cpu", "cpu")))
- for repo, tag in ladder:
- names = list((pins.get(repo) or {}).get(tag) or {})
- if not names:
- return True
- for accel in accels:
- if installer.resolve_release_asset(
- names,
- system = platform.system(),
- machine = platform.machine(),
- accelerator = accel,
- ):
- return True
- return False
-
-
-def _plan() -> dict:
+ return any(
+ installer.resolve_release_asset(
+ names,
+ system = platform.system(),
+ machine = platform.machine(),
+ accelerator = accel,
+ )
+ for accel in accels
+ )
+
+
+def _update_size_bytes(
+ assets: Optional[dict], record: dict, installed_tag: str, latest_tag: str
+) -> Optional[int]:
+ """Download size of the newest release's bundle for this install (plus its CUDA runtime zip when the install has one). The bundle is the recorded asset renamed to the new tag, else the installer's pick for the recorded accelerator. None on any miss."""
+ if not assets:
+ return None
+ installer = _installer()
+ names = list(assets)
+ bundle = None
+ asset = record.get("asset")
+ prefix = f"audio-{installed_tag}-"
+ if isinstance(asset, str) and asset.startswith(prefix):
+ renamed = f"audio-{latest_tag}-{asset[len(prefix) :]}"
+ if renamed in assets:
+ bundle = renamed
+ if bundle is None:
+ accelerator = record.get("accelerator")
+ accelerator = accelerator if isinstance(accelerator, str) else "cpu"
+ # The installer's own constraints, so another repo's CUDA line maps onto the bundle it will pick.
+ bundle = installer.resolve_release_asset(
+ names,
+ system = platform.system(),
+ machine = platform.machine(),
+ accelerator = accelerator,
+ driver_cuda = installer.nvidia_driver_cuda_version() if accelerator == "cuda" else None,
+ prefer_cuda_major = installer.torch_cuda_major(),
+ )
+ if bundle is None or bundle not in assets:
+ return None
+ size = assets[bundle]
+ cudart = installer.cudart_asset_for(names, bundle)
+ if cudart is not None:
+ # The installer's own call: the runtime zip is skipped only when torch ships that CUDA major now.
+ line = installer._CUDA_LINE.search(bundle)
+ if not (line and installer.torch_provides_cuda_runtime(int(line.group(1)))):
+ if cudart not in assets:
+ return None
+ size += assets[cudart]
+ return size
+
+
+def _plan(*, force_refresh: bool = False) -> dict:
from core.inference import audio_cpp_server
plan: dict = {"status": None, "update_available": False, "skip_reason": None, "phase": None}
@@ -122,29 +182,48 @@ def _plan() -> dict:
if not _is_managed(binary):
plan["skip_reason"] = "unmanaged"
return plan
- ladder = _release_ladder()
- if not ladder or not all(tag for _, tag in ladder):
- plan["skip_reason"] = "tracks_latest"
- return plan
- status["latest_tag"] = ladder[0][1]
- if (
- status["installed_tag"] is None
- or (
- record.get("published_repo"),
- status["installed_tag"],
- )
- in ladder
- ):
- plan["skip_reason"] = "up_to_date"
- return plan
- if update_checks_disabled():
- plan["skip_reason"] = "update_checks_disabled"
- return plan
+ repo, pin = _target()
+ installed = status["installed_tag"]
+ names = None
+ if pin:
+ # A pinned release is compared as is, with no lookup, and its assets stay unknown.
+ status["latest_tag"] = pin
+ if installed is None or (record.get("published_repo"), installed) == (repo, pin):
+ plan["skip_reason"] = "up_to_date"
+ return plan
+ if update_checks_disabled():
+ plan["skip_reason"] = "update_checks_disabled"
+ return plan
+ else:
+ # Checked before the lookup: disabled checks make no GitHub call.
+ if update_checks_disabled():
+ plan["skip_reason"] = "update_checks_disabled"
+ return plan
+ latest = _freshness.latest_published_release(repo, force_refresh = force_refresh)
+ status["latest_tag"] = latest
+ # An unknown latest, or one that is not newer (the downgrade guard), is nothing to offer. A record from another repo is replaced by this repo's newest.
+ if (
+ installed is None
+ or latest is None
+ or (
+ record.get("published_repo") == repo and not _freshness.is_behind(installed, latest)
+ )
+ ):
+ plan["skip_reason"] = "up_to_date"
+ return plan
+ assets = _freshness.latest_release_assets(repo, force_refresh = force_refresh)
+ # The tag can come from the 24h disk cache while the asset list is fetched fresh, so after a newer release the two can disagree: keep only the offered release's assets.
+ prefixes = (f"audio-{latest}-bin-", f"audio-{latest}-cudart-")
+ assets = {
+ name: size for name, size in (assets or {}).items() if name.startswith(prefixes)
+ } or None
+ names = list(assets) if assets else None
+ status["update_size_bytes"] = _update_size_bytes(assets, record, installed, latest)
installer = _installer()
request = record.get("accelerator_request")
resolved = record.get("accelerator")
explicit = request if request in installer.ACCELERATORS and request != "auto" else None
- if not _host_has_prebuilt(ladder, resolved if isinstance(resolved, str) else None, explicit):
+ if not _host_has_prebuilt(names, resolved if isinstance(resolved, str) else None, explicit):
plan["skip_reason"] = "no_prebuilt"
return plan
script = _installer_script()
@@ -157,16 +236,19 @@ def _plan() -> dict:
"script": script,
# What setup asked for, so an automatic install keeps detecting the host.
"accelerator": request if request in installer.ACCELERATORS else None,
- "from_tag": status["installed_tag"],
+ "from_tag": installed,
"to_tag": status["latest_tag"],
+ # Installs exactly the offered release, even if a newer one appears before the phase runs.
+ "pin_release_tag": status["latest_tag"],
+ "repo": repo,
}
return plan
-def chained_phase_plan() -> dict:
- """audio.cpp's side of the combined update item. Returns {status, update_available, skip_reason, phase} like whisper_cpp_update.chained_phase_plan. Never raises: a probe that fails is a skip, so audio.cpp can never break the llama status or apply."""
+def chained_phase_plan(*, force_refresh: bool = False) -> dict:
+ """audio.cpp's side of the combined update item. Returns {status, update_available, skip_reason, phase} like whisper_cpp_update.chained_phase_plan; force_refresh bypasses the 24h release cache. Never raises: a probe that fails is a skip, so audio.cpp can never break the llama status or apply."""
try:
- return _plan()
+ return _plan(force_refresh = force_refresh)
except Exception as exc: # noqa: BLE001 - fail open
logger.debug("audio.cpp update: plan failed", error = str(exc))
return {
@@ -207,17 +289,62 @@ def _failure_message(exc: _flow.InstallerExit, env: dict) -> str:
if _flow.is_github_rate_limit_text(text):
advice = _flow.github_rate_limit_advice(_flow.github_token_present(env))
return f"Could not update audio.cpp: GitHub is rate-limiting release downloads. {advice}"
+ # The installer's ReleaseLookupUnavailable: the offered release was unreachable and the tree was never touched.
+ if "no audio.cpp release lookup answered" in text:
+ return "Could not reach the audio.cpp release on GitHub, so the existing install was kept. Try again later."
# The installer's own verdict is its last "error:" line; the rest of the tail is download progress.
errors = [line.strip() for line in text.splitlines() if line.strip().startswith("error: ")]
return errors[-1][len("error: ") :] if errors else text
-def _install(phase: dict, set_progress, unloaded: bool) -> dict:
+def _refresh_release_cache(repo: Optional[str]) -> None:
+ """Forget the cached newest release after an install, the tree kept or replaced, so the next status reads it fresh. The disk cache goes too: offline, the old value would otherwise come back as the last good one."""
+ _freshness.reset_caches(drop_disk = True)
+ if not repo:
+ return
+ try:
+ _freshness.latest_published_release(repo, force_refresh = True)
+ except Exception as exc: # noqa: BLE001 - the install already finished
+ logger.debug("audio.cpp update: release refresh failed", error = str(exc))
+
+
+def _installed_identity() -> tuple[Optional[str], Optional[str]]:
+ """``(published_repo, release_tag)`` of the managed runtime's install record."""
from core.inference import audio_cpp_server
+ binary = audio_cpp_server.find_audio_cpp_server_binary()
+ record = audio_cpp_server.read_install_record(binary) if binary else {}
+ repo = record.get("published_repo")
+ return (repo if isinstance(repo, str) else None), _tag(record)
+
+
+def _install(phase: dict, set_progress, unloaded: bool) -> dict:
+ before = _installed_identity()
+ reload_hint = " Reload your model to use it." if unloaded else ""
+ # The offered tag is passed as a pin, which the installer never second-guesses. A setup run that installed a
+ # newer release since the plan was made must not be downgraded by it; a user's UNSLOTH_AUDIO_CPP_TAG still is.
+ to_tag = phase.get("to_tag")
+ if (
+ before[0] == phase.get("repo")
+ and before[1]
+ and to_tag
+ and _target()[1] is None
+ and _freshness.is_behind(to_tag, before[1])
+ ):
+ logger.info("audio.cpp update: already newer", installed = before[1], offered = to_tag)
+ return {
+ "to_tag": before[1],
+ "reload_required": unloaded,
+ "message": f"audio.cpp is already at {before[1]}.{reload_hint}",
+ }
cmd = [sys.executable, str(phase["script"]), "--install-dir", str(phase["install_dir"])]
if phase.get("accelerator"):
cmd.extend(["--accelerator", phase["accelerator"]])
+ if phase.get("pin_release_tag"):
+ cmd.extend(["--published-release-tag", phase["pin_release_tag"]])
+ if _target()[1] is None:
+ # The installer re-checks under its lock, which the guard above cannot hold.
+ cmd.append("--keep-newer")
logger.info("audio.cpp update: installing", cmd = " ".join(cmd))
env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")
try:
@@ -232,11 +359,15 @@ def _install(phase: dict, set_progress, unloaded: bool) -> dict:
raise _AudioPhaseError(_failure_message(exc, env), reload_required = unloaded) from exc
except Exception as exc:
raise _AudioPhaseError(str(exc), reload_required = unloaded) from exc
-
- binary = audio_cpp_server.find_audio_cpp_server_binary()
- new_tag = _tag(audio_cpp_server.read_install_record(binary)) if binary else None
- reload_hint = " Reload your model to use it." if unloaded else ""
- if new_tag == phase["from_tag"]:
+ _refresh_release_cache(phase.get("repo"))
+
+ new_repo, new_tag = _installed_identity()
+ # Repo and tag together: switching UNSLOTH_AUDIO_CPP_REPO can replace a runtime with another repo's same tag.
+ # A runtime that is already the offered release (a setup run got there first) is not a kept old tree.
+ if (new_repo, new_tag) == before and (new_repo, new_tag) != (
+ phase.get("repo"),
+ phase.get("to_tag"),
+ ):
# Exit 0 also means the release lookup could not answer and the intact tree was kept.
message = (
f"audio.cpp could not be updated right now, so the existing {new_tag} "
diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.py
index 29c2a478aac..2a99e717d3e 100644
--- a/studio/backend/utils/llama_cpp_update.py
+++ b/studio/backend/utils/llama_cpp_update.py
@@ -361,19 +361,19 @@ def _merge_whisper_status(status: dict, *, force_refresh: bool = False) -> dict:
return status
-def _audio_chain_status() -> Optional[dict]:
+def _audio_chain_status(*, force_refresh: bool = False) -> Optional[dict]:
"""audio.cpp's plan for the combined update item. None disables it: fail-open like the whisper probe."""
try:
from utils import audio_cpp_update
- return audio_cpp_update.chained_phase_plan()
+ return audio_cpp_update.chained_phase_plan(force_refresh = force_refresh)
except Exception as exc: # pragma: no cover - defensive
logger.debug("llama update: audio.cpp probe failed", error = str(exc))
return None
-def _merge_audio_status(status: dict) -> dict:
+def _merge_audio_status(status: dict, *, force_refresh: bool = False) -> dict:
"""Fold the audio.cpp sub-status in after whisper's: it joins the update_available union and names the component only when neither llama.cpp nor whisper.cpp is pending."""
- plan = _audio_chain_status()
+ plan = _audio_chain_status(force_refresh = force_refresh)
if plan is None:
status["audio"] = None
return status
@@ -397,7 +397,7 @@ def get_update_status(*, force_refresh: bool = False) -> dict:
"""Report whether an update is available plus the job state. This is the single main update item: llama.cpp drives it and the whisper and audio.cpp phases are folded in (_merge_whisper_status, _merge_audio_status). force_refresh bypasses the 24h release cache for an explicit "check now"."""
status = _llama_only_status(force_refresh = force_refresh)
status = _merge_whisper_status(status, force_refresh = force_refresh)
- return _merge_audio_status(status)
+ return _merge_audio_status(status, force_refresh = force_refresh)
def get_update_changelog(
diff --git a/studio/frontend/src/features/audio/audio-page-policy.ts b/studio/frontend/src/features/audio/audio-page-policy.ts
index 358c12fceae..0543d6d71d0 100644
--- a/studio/frontend/src/features/audio/audio-page-policy.ts
+++ b/studio/frontend/src/features/audio/audio-page-policy.ts
@@ -38,42 +38,6 @@ export function audioCppRuntimeProblem(
return null;
}
-/** setup keeps the old managed runtime when it cannot reach the release. */
-export function audioCppRuntimeUpdate(
- runtime: AudioCppRuntimeStatus | null | undefined,
-): { installed: string; expected: string } | null {
- if (!runtime?.available || !runtime.outdated) return null;
- if (!runtime.release_tag || !runtime.expected_tag) return null;
- return { installed: runtime.release_tag, expected: runtime.expected_tag };
-}
-
-export type AudioRuntimeNoticeMode =
- | "update"
- | "updating"
- | "checking"
- | "ask_owner"
- | "cli";
-
-/** What the outdated-runtime notice offers. The in-app update is owner-only, and the backend
- * offers it only for a runtime it can replace; otherwise the notice keeps the CLI route. */
-export function audioRuntimeNoticeMode({
- isOwner,
- offered,
- applying,
- checked,
-}: {
- isOwner: boolean;
- offered: boolean;
- applying: boolean;
- /** The update status has loaded; before that the offer is unknown, not absent. */
- checked: boolean;
-}): AudioRuntimeNoticeMode {
- if (!isOwner) return "ask_owner";
- if (applying) return "updating";
- if (!checked) return "checking";
- return offered ? "update" : "cli";
-}
-
/** GGUF music families whose prompt needs a description beside the lyrics: MiniMax Music 3
* takes it as the caption and YuE2 as the style. The others fall back to the lyrics. */
const DESCRIBED_MUSIC_FAMILIES = new Set(["minimax_music3", "yue2"]);
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index eecda3f6c14..b47eefcdeec 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -55,7 +55,6 @@ import {
settledDeleteMarkers,
} from "./audio-page-policy";
import { type AudioSourceSelection, clipReference } from "./audio-run-request";
-import { AudioRuntimeUpdateNotice } from "./components/audio-runtime-update-notice";
import { AudioActiveProvider } from "./components/audio-source-input";
import {
audioModelLabel,
@@ -338,7 +337,6 @@ export function AudioPage({
selectedSttRepoRef,
sttStatusRefreshGeneration,
audioCppRuntime,
- runtimeUpdate,
sttLoadGeneration,
sttGgufVariants,
sttEngines,
@@ -1854,14 +1852,6 @@ export function AudioPage({
<p className="text-xs leading-snug text-muted-foreground">
{capabilityLine}
</p>
- {runtimeUpdate ? (
- <AudioRuntimeUpdateNotice
- update={runtimeUpdate}
- onUpdated={() =>
- Promise.all([refreshStatus(), refreshSttStatus()])
- }
- />
- ) : null}
</div>
{mode === "speak" ? (
diff --git a/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx b/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx
deleted file mode 100644
index 4ce31d850aa..00000000000
--- a/studio/frontend/src/features/audio/components/audio-runtime-update-notice.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-
-import { Button } from "@/components/ui/button";
-import { useIsAccountOwner } from "@/features/auth";
-import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";
-import { toast } from "@/lib/toast";
-import { Alert02Icon } from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { type ReactElement, useEffect, useRef, useState } from "react";
-import { audioRuntimeNoticeMode } from "../audio-page-policy";
-
-/** The managed audio runtime is not the release this Studio pins. The owner updates it in place
- * through the shared update job, which also installs any pending llama.cpp or whisper.cpp update;
- * the app-wide update card follows that job and resyncs the loaded model. */
-export function AudioRuntimeUpdateNotice({
- update,
- onUpdated,
-}: {
- update: { installed: string; expected: string };
- onUpdated: () => Promise<unknown>;
-}): ReactElement {
- const isOwner = useIsAccountOwner();
- const { status, applying, apply } = useLlamaUpdateCheck({
- enabled: isOwner,
- });
- const offered = Boolean(status?.audio?.update_available);
- // Re-read the runtime after a followed job or a withdrawn offer (another tab updated), staying
- // on "updating" until then: a stale notice would send the owner to the CLI.
- const followedJob = useRef(false);
- const wasOffered = useRef(false);
- const [refreshing, setRefreshing] = useState(false);
- useEffect(() => {
- if (applying) {
- followedJob.current = true;
- return;
- }
- const offerWithdrawn = wasOffered.current && !offered;
- wasOffered.current = offered;
- if (followedJob.current || offerWithdrawn) {
- followedJob.current = false;
- setRefreshing(true);
- void onUpdated().finally(() => setRefreshing(false));
- }
- }, [applying, offered, onUpdated]);
- const mode = audioRuntimeNoticeMode({
- isOwner,
- offered,
- applying: applying || refreshing,
- checked: status !== null,
- });
-
- async function handleUpdate() {
- const result = await apply();
- if (result.ok) {
- // The job says what each phase did, including a release lookup that kept the old tree.
- toast.success(
- result.message?.trim() || `audio.cpp updated to ${update.expected}.`,
- );
- } else {
- // The shared job may have failed in its llama.cpp or whisper.cpp phase.
- toast.error(`Update failed: ${result.error ?? "unknown error"}`);
- }
- }
-
- return (
- <div
- role="status"
- className="mt-1 flex items-start gap-1.5 text-ui-12 leading-snug text-foreground"
- >
- <HugeiconsIcon
- icon={Alert02Icon}
- className="mt-0.5 size-3.5 shrink-0 text-muted-foreground"
- />
- <div className="grid justify-items-start gap-1.5">
- <span>
- Your audio runtime is{" "}
- <span className="whitespace-nowrap">{update.installed}</span>; Unsloth
- expects <span className="whitespace-nowrap">{update.expected}</span>.{" "}
- {mode === "ask_owner" ? (
- <>
- Some models may not work until it is updated. Ask the Unsloth
- owner to update it.
- </>
- ) : mode === "updating" || mode === "checking" ? null : (
- <>Some models may not work until you update. </>
- )}
- {mode === "cli" ? (
- <>
- Stop Unsloth, run{" "}
- <code className="font-mono">unsloth studio update</code>, then
- start it again.
- </>
- ) : null}
- </span>
- {mode === "update" || mode === "updating" ? (
- <Button
- size="xs"
- onClick={handleUpdate}
- disabled={mode === "updating"}
- >
- {mode === "updating" ? "Updating..." : "Update"}
- </Button>
- ) : null}
- </div>
- </div>
- );
-}
diff --git a/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
index f8948938199..91a5c256e94 100644
--- a/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
+++ b/studio/frontend/src/features/audio/hooks/use-stt-sidecar.ts
@@ -18,7 +18,6 @@ import { usePersistedChoice } from "@/hooks/use-persisted-choice";
import { toast } from "@/lib/toast";
import type { AudioCppRuntimeStatus } from "../audio-cpp-catalog";
import {
- audioCppRuntimeUpdate,
reconcileSttSelection,
resolveSttResidency,
type SttDownloadedArtifact,
@@ -55,9 +54,6 @@ export function useSttSidecar({
selectedSttRepoRef.current = selectedSttRepo;
const sttStatusRefreshGeneration = useRef(0);
const audioCppRuntime = useRef<AudioCppRuntimeStatus | null>(null);
- // state drives the page display; the ref only gates a pick.
- const [runtimeUpdate, setRuntimeUpdate] =
- useState<ReturnType<typeof audioCppRuntimeUpdate>>(null);
const sttLoadGeneration = useRef(0);
const sttGgufVariants = useRef(
new Map<string, string>(
@@ -110,13 +106,6 @@ export function useSttSidecar({
);
if (generation !== sttStatusRefreshGeneration.current) return;
audioCppRuntime.current = stt.audio_cpp_runtime ?? null;
- const nextUpdate = audioCppRuntimeUpdate(audioCppRuntime.current);
- setRuntimeUpdate((current) =>
- current?.installed === nextUpdate?.installed &&
- current?.expected === nextUpdate?.expected
- ? current
- : nextUpdate,
- );
const nextDownloadedArtifacts = sttDownloadedArtifacts(
stt,
sttRepoIdForSidecarKey,
@@ -358,7 +347,6 @@ export function useSttSidecar({
selectedSttRepoRef,
sttStatusRefreshGeneration,
audioCppRuntime,
- runtimeUpdate,
sttLoadGeneration,
sttGgufVariants,
sttEngines,
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 83d5bbe21da..c84001a3638 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -20,7 +20,10 @@ import {
isBackendDownForDesktopUpdate,
isSilencedDesktopUpdateFailure,
} from "@/lib/desktop-update-activity";
-import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
+import {
+ notifyModelLifecycle,
+ subscribeModelLifecycle,
+} from "@/lib/model-lifecycle-events";
import { resolveSpeculativeType } from "@/lib/speculative-modes";
import {
type TransferSample,
@@ -869,6 +872,10 @@ export async function resyncInferenceStatusAfterServerModelChange(): Promise<voi
useChatRuntimeStore.getState().clearCheckpoint();
}
await syncInferenceStatusToStore();
+ // The update also unloads audio.cpp models, and the Audio page holds its own status: a settled
+ // "chat" re-reads its speech slot and "stt" its dictation, else Generate stays enabled and 400s.
+ notifyModelLifecycle({ runtime: "chat", loading: false, model: null });
+ notifyModelLifecycle({ runtime: "stt", loading: false, model: null });
}
function pickOf(info: {
diff --git a/studio/frontend/src/features/settings/components/studio-version-section.tsx b/studio/frontend/src/features/settings/components/studio-version-section.tsx
index ba5d9bcc0b6..396955cfc3a 100644
--- a/studio/frontend/src/features/settings/components/studio-version-section.tsx
+++ b/studio/frontend/src/features/settings/components/studio-version-section.tsx
@@ -65,15 +65,18 @@ async function fetchStudioVersions(): Promise<StudioVersions> {
}
// Shared "Unsloth" version block, shown in both General and About. The About
-// tab passes llamaCppVersion to surface the installed llama.cpp build alongside
-// the version rows; General omits it, so the row only shows on About. Children
-// are appended below the version rows, for controls that act on them.
+// tab passes llamaCppVersion and audioCppVersion to surface the installed
+// llama.cpp and audio.cpp builds alongside the version rows; General omits them,
+// so those rows only show on About. Children are appended below the version
+// rows, for controls that act on them.
export function StudioVersionSection({
llamaCppVersion,
+ audioCppVersion,
desktopAppVersion,
children,
}: {
llamaCppVersion?: string | null;
+ audioCppVersion?: string | null;
desktopAppVersion?: string | null;
children?: ReactNode;
} = {}) {
@@ -120,6 +123,13 @@ export function StudioVersionSection({
</code>
</SettingsRow>
) : null}
+ {audioCppVersion ? (
+ <SettingsRow label={t("settings.about.audioCppVersion")}>
+ <code className="font-mono text-xs text-muted-foreground">
+ {audioCppVersion}
+ </code>
+ </SettingsRow>
+ ) : null}
{children}
</SettingsSection>
);
diff --git a/studio/frontend/src/features/settings/tabs/about-tab.tsx b/studio/frontend/src/features/settings/tabs/about-tab.tsx
index 2e60f701f22..6e32d647da6 100644
--- a/studio/frontend/src/features/settings/tabs/about-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/about-tab.tsx
@@ -156,10 +156,11 @@ export function AboutTab() {
</p>
</header>
- {/* llama.cpp row lives in the shared version section so it sits with the
- Unsloth/Package rows; the prop keeps it About-only (General passes none). */}
+ {/* llama.cpp and audio.cpp rows live in the shared version section so they sit with
+ the Unsloth/Package rows; the props keep them About-only (General passes none). */}
<StudioVersionSection
llamaCppVersion={hw.llamaCpp}
+ audioCppVersion={hw.audioCpp}
desktopAppVersion={desktopAppVersion}
/>
diff --git a/studio/frontend/src/hooks/use-hardware-info.ts b/studio/frontend/src/hooks/use-hardware-info.ts
index 71e5f47a419..63571b35c87 100644
--- a/studio/frontend/src/hooks/use-hardware-info.ts
+++ b/studio/frontend/src/hooks/use-hardware-info.ts
@@ -28,6 +28,7 @@ export interface HardwareInfo {
transformers: string | null;
unsloth: string | null;
llamaCpp: string | null;
+ audioCpp: string | null;
// Whether export can run here (true only on a supported accelerator), with a torch-aware
// reason. `null` until the authoritative response lands, so callers don't briefly enable
// export; `loaded` flips true once a real (non-error) response arrives.
@@ -57,6 +58,7 @@ const DEFAULT: HardwareInfo = {
transformers: null,
unsloth: null,
llamaCpp: null,
+ audioCpp: null,
exportSupported: null,
exportUnsupportedReason: null,
exportUnsupportedMessage: null,
@@ -118,6 +120,7 @@ async function fetchOnce(): Promise<HardwareInfo> {
transformers: data?.versions?.transformers ?? null,
unsloth: data?.versions?.unsloth ?? null,
llamaCpp: data?.llama_cpp ?? null,
+ audioCpp: data?.audio_cpp ?? null,
exportSupported: data?.export_supported ?? null,
exportUnsupportedReason: data?.export_unsupported_reason ?? null,
exportUnsupportedMessage: data?.export_unsupported_message ?? null,
diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.ts
index 1c69b1c592b..347d1a4575a 100644
--- a/studio/frontend/src/hooks/use-llama-update-check.ts
+++ b/studio/frontend/src/hooks/use-llama-update-check.ts
@@ -3,6 +3,7 @@
import { authFetch, getAuthToken } from "@/features/auth";
import { refreshHardwareInfo } from "@/hooks/use-hardware-info";
+import { notifyModelLifecycle } from "@/lib/model-lifecycle-events";
import {
signalRunningLlamaJob,
subscribeToLlamaJobStarted,
@@ -57,7 +58,7 @@ export interface LlamaUpdateStatus {
// and the card lists every one the notification settings allow.
llama: ComponentOffer;
whisper: ComponentOffer | null;
- // The release this Studio pins, when the managed audio.cpp runtime is another one.
+ // The newest audio.cpp release, when the managed runtime is behind it.
audio: ComponentOffer | null;
installed_tag: string | null;
latest_tag: string | null;
@@ -481,6 +482,22 @@ export function useLlamaUpdateCheck({
[],
);
+ // The update stops a loaded dictation sidecar and may swap the audio.cpp runtime without asking for a
+ // reload, so the Audio page re-reads STT and runtime status once per finished job, whichever path saw it.
+ const settledNotifiedForRef = useRef<string | null>(null);
+ const notifySettledOnce = useCallback(
+ (job: Pick<LlamaUpdateJob, "state" | "finished_at">) => {
+ if (
+ (job.state === "success" || job.state === "error") &&
+ job.finished_at !== settledNotifiedForRef.current
+ ) {
+ settledNotifiedForRef.current = job.finished_at;
+ notifyModelLifecycle({ runtime: "stt", loading: false, model: null });
+ }
+ },
+ [],
+ );
+
// Used by apply() and another-tab job tracking.
const startJobPoll = useCallback(
(onDone?: (result: LlamaApplyResult) => void) => {
@@ -493,6 +510,7 @@ export function useLlamaUpdateCheck({
const presentation = commitStatus(s);
if (presentation.running) return;
clearPollTimer();
+ notifySettledOnce(s.job);
if (s.job.state === "success") {
void refreshHardwareInfo();
// The update unloads the running model server-side, so the chat runtime still points at a
@@ -517,7 +535,13 @@ export function useLlamaUpdateCheck({
}, JOB_POLL_INTERVAL_MS);
pollTimer.current = timer;
},
- [clearPollTimer, readStatus, commitStatus, notifyReloadIfNeeded],
+ [
+ clearPollTimer,
+ readStatus,
+ commitStatus,
+ notifyReloadIfNeeded,
+ notifySettledOnce,
+ ],
);
const surfaceIfAvailable = useCallback(
@@ -532,8 +556,9 @@ export function useLlamaUpdateCheck({
// the running window entirely (mounted, or only checks hourly and misses both the running and
// just-finished moments) still needs to resync here, not just from the poll path above.
notifyReloadIfNeeded(next.job);
+ notifySettledOnce(next.job);
},
- [commitStatus, startJobPoll, notifyReloadIfNeeded],
+ [commitStatus, startJobPoll, notifyReloadIfNeeded, notifySettledOnce],
);
useEffect(() => {
surfaceRef.current = surfaceIfAvailable;
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index c3142c4a316..c9e6e3785d9 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -3121,6 +3121,7 @@ export const ar = {
desktopAppVersion: "إصدار تطبيق سطح المكتب",
desktopAppVersionUnavailable: "غير متاح",
llamaCppVersion: "إصدار llama.cpp",
+ audioCppVersion: "إصدار audio.cpp",
hardware: "الأجهزة",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 39152371fda..6b9bc660a4e 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -3168,6 +3168,7 @@ export const de = {
desktopAppVersion: "Version der Desktop-App",
desktopAppVersionUnavailable: "Nicht verfügbar",
llamaCppVersion: "llama.cpp-Version",
+ audioCppVersion: "audio.cpp-Version",
hardware: "Hardware",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index faa9faefd2e..7e315b65c6d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3169,6 +3169,7 @@ export const en = {
desktopAppVersion: "Desktop App Version",
desktopAppVersionUnavailable: "Unavailable",
llamaCppVersion: "llama.cpp Version",
+ audioCppVersion: "audio.cpp Version",
hardware: "Hardware",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 5f57601d508..65313d8ae9c 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -3162,6 +3162,7 @@ export const es = {
desktopAppVersion: "Versión de la app de escritorio",
desktopAppVersionUnavailable: "No disponible",
llamaCppVersion: "Versión de llama.cpp",
+ audioCppVersion: "Versión de audio.cpp",
hardware: "Hardware",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index a4126cb72f6..c1ece382546 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -3170,6 +3170,7 @@ export const fr = {
desktopAppVersion: "Version de l’application de bureau",
desktopAppVersionUnavailable: "Indisponible",
llamaCppVersion: "Version de llama.cpp",
+ audioCppVersion: "Version d'audio.cpp",
hardware: "Matériel",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 2ff6ef1f53b..7a3cca64ecc 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -3241,6 +3241,7 @@ export const he = {
desktopAppVersion: "גרסת אפליקציית Desktop",
desktopAppVersionUnavailable: "לא זמין",
llamaCppVersion: "גרסת llama.cpp",
+ audioCppVersion: "גרסת audio.cpp",
hardware: "חומרה",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 094b2c8a218..53906fac208 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -3130,6 +3130,7 @@ export const hi = {
desktopAppVersion: "डेस्कटॉप ऐप संस्करण",
desktopAppVersionUnavailable: "उपलब्ध नहीं",
llamaCppVersion: "llama.cpp संस्करण",
+ audioCppVersion: "audio.cpp संस्करण",
hardware: "हार्डवेयर",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 197fe591fcd..42442c59bff 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -3073,6 +3073,7 @@ export const it = {
desktopAppVersionUnavailable: "Non disponibile",
packageVersion: "Versione del pacchetto",
llamaCppVersion: "Versione di llama.cpp",
+ audioCppVersion: "Versione di audio.cpp",
hardware: "Hardware",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 5808971534f..3b117396f5a 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -3090,6 +3090,7 @@ export const ja = {
desktopAppVersion: "デスクトップアプリのバージョン",
desktopAppVersionUnavailable: "利用できません",
llamaCppVersion: "llama.cpp バージョン",
+ audioCppVersion: "audio.cpp バージョン",
hardware: "ハードウェア",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 0a8a6f6a513..fe16677cdd4 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -3109,6 +3109,7 @@ export const ko = {
desktopAppVersion: "데스크톱 앱 버전",
desktopAppVersionUnavailable: "확인할 수 없음",
llamaCppVersion: "llama.cpp 버전",
+ audioCppVersion: "audio.cpp 버전",
hardware: "하드웨어",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 7467744b747..417a67b39ea 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -3141,6 +3141,7 @@ export const ptBR = {
desktopAppVersion: "Versão do aplicativo de desktop",
desktopAppVersionUnavailable: "Indisponível",
llamaCppVersion: "Versão do llama.cpp",
+ audioCppVersion: "Versão do audio.cpp",
hardware: "Hardware",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 07e586f8e66..db40edc936b 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -3136,6 +3136,7 @@ export const ru = {
desktopAppVersion: "Версия настольного приложения",
desktopAppVersionUnavailable: "Недоступно",
llamaCppVersion: "Версия llama.cpp",
+ audioCppVersion: "Версия audio.cpp",
hardware: "Оборудование",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 0c7c8355088..aa91d42016a 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -3346,6 +3346,7 @@ export const sv = {
desktopAppVersion: "Skrivbordsappens version",
desktopAppVersionUnavailable: "Inte tillgänglig",
llamaCppVersion: "llama.cpp-version",
+ audioCppVersion: "audio.cpp-version",
hardware: "Maskinvara",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 94bdba5a293..247918e8b1c 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -3068,6 +3068,7 @@ export const zhCN = {
desktopAppVersion: "桌面应用版本",
desktopAppVersionUnavailable: "不可用",
llamaCppVersion: "llama.cpp 版本",
+ audioCppVersion: "audio.cpp 版本",
hardware: "硬件",
gpu: "GPU",
cuda: "CUDA",
diff --git a/studio/frontend/tests/about-audio-cpp-version.test.ts b/studio/frontend/tests/about-audio-cpp-version.test.ts
new file mode 100644
index 00000000000..205c4731b2a
--- /dev/null
+++ b/studio/frontend/tests/about-audio-cpp-version.test.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Settings > About lists the installed audio.cpp release beside the llama.cpp build.
+
+import assert from "node:assert/strict";
+import { readdirSync, readFileSync } from "node:fs";
+import test from "node:test";
+
+const SRC = new URL("../src/", import.meta.url);
+const read = (relative: string) => readFileSync(new URL(relative, SRC), "utf8");
+
+test("the hardware details carry the audio.cpp version to the About tab", () => {
+ assert.match(
+ read("hooks/use-hardware-info.ts"),
+ /audioCpp: data\?\.audio_cpp \?\? null,/,
+ );
+ assert.match(
+ read("features/settings/tabs/about-tab.tsx"),
+ /llamaCppVersion=\{hw\.llamaCpp\}\s*audioCppVersion=\{hw\.audioCpp\}/,
+ );
+});
+
+test("the audio.cpp row shows only when a version is known", () => {
+ assert.match(
+ read("features/settings/components/studio-version-section.tsx"),
+ /\{audioCppVersion \? \(\s*<SettingsRow label=\{t\("settings\.about\.audioCppVersion"\)\}>\s*<code className="font-mono text-xs text-muted-foreground">\s*\{audioCppVersion\}/,
+ );
+});
+
+test("every locale labels the audio.cpp row", () => {
+ const locales = readdirSync(new URL("i18n/locales/", SRC)).filter((name) =>
+ name.endsWith(".ts"),
+ );
+ assert.ok(locales.length > 1);
+ for (const name of locales) {
+ assert.match(
+ read(`i18n/locales/${name}`),
+ /audioCppVersion: "[^"\n]*audio\.cpp[^"\n]*",/,
+ name,
+ );
+ }
+});
diff --git a/studio/frontend/tests/audio-cpp-catalog.test.ts b/studio/frontend/tests/audio-cpp-catalog.test.ts
index 7834084111c..2f3fb3c6190 100644
--- a/studio/frontend/tests/audio-cpp-catalog.test.ts
+++ b/studio/frontend/tests/audio-cpp-catalog.test.ts
@@ -28,7 +28,6 @@ import {
import {
MINIMAX_MUSIC_MAX_SECONDS,
audioCppRuntimeProblem,
- audioCppRuntimeUpdate,
audioSamplingControlsApply,
isGgufTtsTarget,
isTtsAudioType,
@@ -880,44 +879,6 @@ test("recommended speech and music picks are refused when the runtime cannot run
);
});
-test("an outdated managed runtime names both releases; anything else shows no notice", () => {
- const current = {
- available: true,
- espeak: true,
- backend: "cuda",
- release_tag: "v0.9.0-unsloth.1",
- expected_tag: "v0.9.0-unsloth.1",
- outdated: false,
- };
- const outdated = { ...current, release_tag: "v0.8.0-unsloth.1", outdated: true };
- assert.deepEqual(audioCppRuntimeUpdate(outdated), {
- installed: "v0.8.0-unsloth.1",
- expected: "v0.9.0-unsloth.1",
- });
- assert.equal(audioCppRuntimeUpdate(current), null);
- assert.equal(audioCppRuntimeUpdate(null), null);
- assert.equal(audioCppRuntimeUpdate(undefined), null);
- // support servers older than these fields or unable to name either release.
- assert.equal(
- audioCppRuntimeUpdate({ available: true, espeak: true, backend: null, release_tag: "v0.8.0" }),
- null,
- );
- assert.equal(audioCppRuntimeUpdate({ ...outdated, expected_tag: null }), null);
- assert.equal(audioCppRuntimeUpdate({ ...outdated, release_tag: null }), null);
- assert.equal(audioCppRuntimeUpdate({ ...outdated, available: false }), null);
- const route = readText("../../backend/routes/inference.py");
- assert.match(route, /"expected_tag": None,\s*"outdated": False,/);
- const page = readAudioWorkspaceSource();
- assert.match(page, /const nextUpdate = audioCppRuntimeUpdate\(audioCppRuntime\.current\);/);
- assert.match(page, /\{runtimeUpdate \? \(\s*<AudioRuntimeUpdateNotice\s+update=\{runtimeUpdate\}/);
- // The CLI route stays for whoever the in-app update is not offered to.
- const notice = readText("../src/features/audio/components/audio-runtime-update-notice.tsx");
- assert.match(
- notice,
- /Stop Unsloth, run\{" "\}\s*<code className="font-mono">unsloth studio update<\/code>, then\s*start it again\./,
- );
-});
-
test("the capability line names GGUF audio and music, never the runtime's internal type", () => {
assert.equal(audioCapabilityLine("tts", "audiocpp_tts"), "Text-to-speech · GGUF");
assert.equal(audioCapabilityLine("music", "audiocpp_music"), "Music generation · GGUF");
diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.ts
index 4401f25f443..8775d6d359d 100644
--- a/studio/frontend/tests/audio-page-policy.test.ts
+++ b/studio/frontend/tests/audio-page-policy.test.ts
@@ -11,7 +11,6 @@ import {
MINIMAX_MUSIC_MAX_SECONDS,
audioEjectAvailable,
audioGenerationPresentation,
- audioRuntimeNoticeMode,
canTransitionAudioMode,
exactGgufLoadSelector,
expectedGgufDownloadBytes,
@@ -861,37 +860,6 @@ test("trained speech checkpoints are offered only on Speak and Music", () => {
);
});
-test("the outdated-runtime notice offers the in-app update only to the owner", () => {
- const mode = (isOwner: boolean, offered: boolean, applying = false, checked = true) =>
- audioRuntimeNoticeMode({ isOwner, offered, applying, checked });
- assert.equal(mode(true, true), "update");
- // A running job, started here or from the update card.
- assert.equal(mode(true, true, true), "updating");
- assert.equal(mode(true, false, true), "updating");
- // A skipped offer (checks disabled, no bundle, no installer) or an older backend.
- assert.equal(mode(true, false), "cli");
- // Before the status loads the offer is unknown: no CLI instruction yet.
- assert.equal(mode(true, false, false, false), "checking");
- assert.equal(mode(false, false, false, false), "ask_owner");
- // POST /api/llama/update is owner-only.
- assert.equal(mode(false, true), "ask_owner");
- assert.equal(mode(false, false, true), "ask_owner");
-});
-
-// The card, or another tab, can run the update without this notice's own click,
-// so the page refreshes from the followed job or from the offer disappearing,
-// and stays on "updating" until that refresh has re-read the runtime.
-test("the outdated-runtime notice refreshes the page however the update ran", () => {
- const notice = readSrc("features/audio/components/audio-runtime-update-notice.tsx");
- assert.match(notice, /const offerWithdrawn = wasOffered\.current && !offered;/);
- assert.match(
- notice,
- /if \(followedJob\.current \|\| offerWithdrawn\) \{\s*followedJob\.current = false;\s*setRefreshing\(true\);\s*void onUpdated\(\)\.finally\(\(\) => setRefreshing\(false\)\);/,
- );
- assert.match(notice, /applying: applying \|\| refreshing,/);
- assert.doesNotMatch(notice, /toast\.success\([^;]*;\s*onUpdated\(\)/);
-});
-
test("the audio picker marks the main slot's loaded model and quant, not the chat model", () => {
assert.deepEqual(
audioLoadedSelection({
diff --git a/studio/frontend/tests/llama-update-offer-key.test.ts b/studio/frontend/tests/llama-update-offer-key.test.ts
index a1f1f478791..398b658813a 100644
--- a/studio/frontend/tests/llama-update-offer-key.test.ts
+++ b/studio/frontend/tests/llama-update-offer-key.test.ts
@@ -16,6 +16,7 @@ const { offerKey } = loadWithStubs<typeof HookModule>(
getAuthToken: () => null,
},
"@/hooks/use-hardware-info": { refreshHardwareInfo: async () => {} },
+ "@/lib/model-lifecycle-events": { notifyModelLifecycle() {} },
"@/lib/llama-job-events": {
signalRunningLlamaJob() {},
subscribeToLlamaJobStarted: () => () => {},
diff --git a/studio/frontend/tests/llama-update-poll-race.test.ts b/studio/frontend/tests/llama-update-poll-race.test.ts
index 091a033882d..de2756b8a40 100644
--- a/studio/frontend/tests/llama-update-poll-race.test.ts
+++ b/studio/frontend/tests/llama-update-poll-race.test.ts
@@ -43,6 +43,7 @@ function harness() {
react,
"@/features/auth": { authFetch, getAuthToken: () => "token" },
"@/hooks/use-hardware-info": { refreshHardwareInfo: async () => {} },
+ "@/lib/model-lifecycle-events": { notifyModelLifecycle() {} },
"@/lib/llama-job-events": {
signalRunningLlamaJob() {},
subscribeToLlamaJobStarted: () => () => {},
diff --git a/studio/frontend/tests/update-resync-audio-page.test.ts b/studio/frontend/tests/update-resync-audio-page.test.ts
new file mode 100644
index 00000000000..72108369780
--- /dev/null
+++ b/studio/frontend/tests/update-resync-audio-page.test.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The combined update unloads audio.cpp models too, and the Audio page keeps its own status. With its
+// own update notice gone, the update card's resync is the only signal it gets: without it Generate
+// stays enabled against an unloaded slot and the next run 400s with "No model loaded".
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { readText } from "./helpers/kit.ts";
+
+test("the post-update resync tells the Audio page to re-read both slots", () => {
+ const runtime = readText(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ );
+ const start = runtime.indexOf(
+ "export async function resyncInferenceStatusAfterServerModelChange",
+ );
+ assert.ok(start >= 0);
+ const body = runtime.slice(start, runtime.indexOf("\n}\n", start));
+ assert.match(
+ body,
+ /notifyModelLifecycle\(\{ runtime: "chat", loading: false/,
+ );
+ assert.match(body, /notifyModelLifecycle\(\{ runtime: "stt", loading: false/);
+
+ const page = readText("../src/features/audio/audio-page.tsx");
+ assert.match(
+ page,
+ /subscribeModelLifecycle\(\(\{ runtime, loading \}\) => \{\s*if \(loading\) return;\s*if \(runtime === "chat"\) void refreshStatus\(\);\s*if \(runtime === "stt"\) void refreshSttStatus\(\);/,
+ );
+});
+
+test("the update card resyncs through that function", () => {
+ const banner = readText("../src/components/llama-update-banner.tsx");
+ assert.match(
+ banner,
+ /onReloadRequired: resyncInferenceStatusAfterServerModelChange/,
+ );
+});
+
+test("every path that sees a finished update job re-reads dictation once", () => {
+ const hook = readText("../src/hooks/use-llama-update-check.ts");
+ const once = hook.slice(hook.indexOf("const notifySettledOnce"));
+ assert.match(
+ once,
+ /job\.finished_at !== settledNotifiedForRef\.current[\s\S]*?notifyModelLifecycle\(\{ runtime: "stt", loading: false/,
+ );
+ const poll = hook.slice(
+ hook.indexOf("const startJobPoll"),
+ hook.indexOf("const surfaceIfAvailable"),
+ );
+ assert.match(poll, /clearPollTimer\(\);\s*notifySettledOnce\(s\.job\);/);
+ const surface = hook.slice(hook.indexOf("const surfaceIfAvailable"));
+ assert.match(
+ surface,
+ /notifyReloadIfNeeded\(next\.job\);\s*notifySettledOnce\(next\.job\);/,
+ );
+});
diff --git a/studio/install_audio_cpp_prebuilt.py b/studio/install_audio_cpp_prebuilt.py
index dac65fe5a32..46a2c83957f 100644
--- a/studio/install_audio_cpp_prebuilt.py
+++ b/studio/install_audio_cpp_prebuilt.py
@@ -15,17 +15,25 @@ The bundle is extracted into a staging directory beside the managed tree, starte
with ``--help`` so a bundle this host cannot load is refused, and swapped in only then,
so an interrupted or unusable install never replaces a working tree.
-Every bundle and CUDA runtime archive must match a sha256 pinned in
-``audio_cpp_prebuilt_pins.json`` unless the user picked the release
-(``UNSLOTH_AUDIO_CPP_REPO`` / ``UNSLOTH_AUDIO_CPP_TAG``). A re-run whose install record
-already names the pinned release makes no network call, and a lookup that cannot answer
+The newest unslothai/audio.cpp release is installed unless ``UNSLOTH_AUDIO_CPP_TAG`` (or
+``--published-release-tag``) names one. The release is resolved like whisper.cpp's, through
+prebuilt_core: the download host first, then the GitHub API. Every bundle and CUDA runtime
+archive must match the sha256 in the release's own ``audio-cpp-prebuilt-sha256.json``, which
+is bound to the release tag; an archive the index does not cover is refused. That checksum
+comes from the same release as the archive, so it proves integrity (a corrupt or swapped
+download), not authenticity. A user-picked repo or tag whose release publishes no index
+falls back to GitHub's asset digest.
+
+A re-run whose install record already names the newest release (one HEAD to github.com,
+no API call) or the pinned one (no network call) downloads nothing, an intact install newer
+than the release a lookup names is never replaced by it, and a lookup that cannot answer
keeps a complete install.
Usage:
python studio/install_audio_cpp_prebuilt.py # auto-detect host
python studio/install_audio_cpp_prebuilt.py --accelerator cpu
python studio/install_audio_cpp_prebuilt.py --print-asset # resolve only
- python studio/install_audio_cpp_prebuilt.py --write-pins # regenerate the digest pins
+ python studio/install_audio_cpp_prebuilt.py --published-release-tag v0.9.1-unsloth.1
"""
from __future__ import annotations
@@ -69,23 +77,19 @@ else:
_safe_extractall,
)
-# The Unsloth fork publishes the bundles Studio pins (CI: .github/workflows/unsloth-prebuilt.yml there,
-# like unslothai/whisper.cpp); UNSLOTH_AUDIO_CPP_REPO overrides it.
+# The Unsloth fork publishes the bundles Studio installs (CI: .github/workflows/unsloth-prebuilt.yml
+# there, like unslothai/whisper.cpp); UNSLOTH_AUDIO_CPP_REPO overrides it. Its tags carry the Unsloth
+# packaging (static eSpeak-ng, lean multi-arch Linux CUDA) and a manifest + sha256 index per release.
DEFAULT_REPO = "unslothai/audio.cpp"
-UPSTREAM_FALLBACK_REPO = "0xShug0/audio.cpp"
-# Pinned for reproducibility; UNSLOTH_AUDIO_CPP_TAG overrides ('' tracks latest). The fork's tags carry
-# the Unsloth packaging (static eSpeak-ng, lean multi-arch Linux CUDA); upstream never publishes them.
-DEFAULT_TAG = "v0.9.0-unsloth.1"
-# The upstream release the fork tag is built from, tried when the fork cannot serve this host.
-UPSTREAM_FALLBACK_TAG = "v0.9.0"
+
+# What prebuilt_core's release lookup and index parsers read through _OPS.
+COMPONENT = "audio.cpp"
+MANIFEST_ASSET_NAME = "audio-cpp-prebuilt-manifest.json"
+SHA256_ASSET_NAME = "audio-cpp-prebuilt-sha256.json"
INSTALL_RECORD = "UNSLOTH_AUDIO_CPP_PREBUILT_INFO.json"
OWNERSHIP_MARKER = ".unsloth-studio-owned"
SERVER_NAME = "audiocpp_server.exe" if sys.platform == "win32" else "audiocpp_server"
-# {repo: {tag: {asset: sha256}}} for the default fork tag and its upstream fallback. Regenerate with
-# `python studio/install_audio_cpp_prebuilt.py --write-pins` after bumping either tag; it reads the same
-# digests `gh release view <tag> -R <repo> --json assets` shows.
-PINS_PATH = Path(__file__).resolve().with_name("audio_cpp_prebuilt_pins.json")
ACCELERATORS = ("auto", "cpu", "cuda", "vulkan", "metal")
# The staged server's --help must exit 0 within this long before it replaces the live tree.
@@ -108,7 +112,8 @@ def log(message: str) -> None:
print(f"audio.cpp: {message}", file = sys.stderr, flush = True)
-# Late-binding seam for prebuilt_core: its downloader reads USER_AGENT and log from here.
+# Late-binding seam for prebuilt_core: its downloader and release lookup read USER_AGENT, log and the
+# asset names above from here, and see a test's monkeypatch of any core name set on this module.
_OPS = core.ModuleOps(globals())
_OS_TOKENS = {
@@ -132,49 +137,77 @@ def _repo() -> str:
def _pinned_tag() -> Optional[str]:
- val = os.environ.get("UNSLOTH_AUDIO_CPP_TAG", DEFAULT_TAG).strip()
- return val or None
+ """``UNSLOTH_AUDIO_CPP_TAG``, the exact release to install; ``None`` (track the newest) when it
+ is unset, empty or ``latest``."""
+ val = (os.environ.get("UNSLOTH_AUDIO_CPP_TAG") or "").strip()
+ return None if not val or val.lower() == "latest" else val
def _user_picked_release() -> bool:
- """The user chose the repo or tag, so a digest this repo never pinned is theirs to trust."""
+ """The user chose the repo or tag, so a release without a sha256 index is theirs to trust
+ on GitHub's digest."""
+ return (
+ bool((os.environ.get("UNSLOTH_AUDIO_CPP_REPO") or "").strip()) or _pinned_tag() is not None
+ )
+
+
+# "v0.9.1-unsloth.1", "v0.9.0", "v0.8.2-audio8-perf-hotfix-unsloth.1": a leading version, any label.
+_RELEASE_VERSION = re.compile(r"v?(\d+)\.(\d+)(?:\.(\d+))?(?:-\S*)?")
+_UNSLOTH_SERIAL = re.compile(r"-unsloth\.(\d+)$")
+
+
+def release_version_key(tag: Optional[str]) -> Optional[tuple[int, int, int, int]]:
+ """``(major, minor, patch, unsloth_serial)`` of a release tag, or ``None``. A label between the
+ version and ``-unsloth.N`` is ignored, so a hotfix of an older line still sorts below a newer
+ release. Kept in step with ``audio_cpp_freshness.parse_release_version`` (a test compares them)."""
+ if not isinstance(tag, str):
+ return None
+ tag = tag.strip()
+ match = _RELEASE_VERSION.fullmatch(tag)
+ if not match:
+ return None
+ serial = _UNSLOTH_SERIAL.search(tag)
return (
- bool((os.environ.get("UNSLOTH_AUDIO_CPP_REPO") or "").strip())
- or "UNSLOTH_AUDIO_CPP_TAG" in os.environ
+ int(match.group(1)),
+ int(match.group(2)),
+ int(match.group(3) or 0),
+ int(serial.group(1)) if serial else 0,
)
-# Every pinned Linux bundle (CPU and CUDA) is built on Ubuntu 22.04.
-_PINNED_LINUX_GLIBC_FLOOR = (2, 35)
+def _record_is_current(record_tag: Optional[str], latest_tag: Optional[str]) -> bool:
+ """Whether an installed tag needs nothing from ``latest_tag``: the same release, or one that
+ parses strictly newer (``/releases/latest`` and the API's newest can name an older release)."""
+ if not record_tag or not latest_tag:
+ return False
+ if record_tag == latest_tag:
+ return True
+ installed, latest = release_version_key(record_tag), release_version_key(latest_tag)
+ return installed is not None and latest is not None and installed > latest
-def _glibc_below_pinned_floor() -> Optional[str]:
- """The host glibc when it is older than the pinned Linux bundles need, else ``None``. Without
- this the start check fails after a full download (~1 GB for CUDA) on every setup run."""
- if not sys.platform.startswith("linux") or _user_picked_release():
+_GLIBC_MIN_OS = re.compile(r"glibc-(\d+)\.(\d+)")
+
+
+def _glibc_below(min_os: Optional[str]) -> Optional[str]:
+ """The host glibc when it is older than a Linux bundle's manifest ``min_os`` (``glibc-2.35``),
+ else ``None``. Checked before the download: without it the start check fails after a full
+ download (~1 GB for CUDA) on every setup run. No manifest (a user-picked release) skips it."""
+ if not sys.platform.startswith("linux") or not isinstance(min_os, str):
+ return None
+ floor = _GLIBC_MIN_OS.fullmatch(min_os.strip())
+ if not floor:
return None
name, version = platform.libc_ver()
try:
parsed = tuple(int(x) for x in version.split(".")[:2])
except ValueError:
return None
- if name != "glibc" or len(parsed) != 2 or parsed >= _PINNED_LINUX_GLIBC_FLOOR:
+ if name != "glibc" or len(parsed) != 2 or parsed >= (int(floor.group(1)), int(floor.group(2))):
return None
return version
-def _release_ladder() -> list[tuple[str, Optional[str]]]:
- """``(repo, tag)`` lookups in order: the pinned tag on the primary repo, then, when the user
- pinned neither repo nor tag, the upstream release the fork tag was cut from. ``None`` (latest)
- only when the user set ``UNSLOTH_AUDIO_CPP_TAG=''``; a pinned install never drifts to an
- untested latest. A user-chosen tag never reaches a repo the user did not choose."""
- primary = _repo()
- ladder = [(primary, _pinned_tag())]
- if not _user_picked_release() and primary != UPSTREAM_FALLBACK_REPO:
- ladder.append((UPSTREAM_FALLBACK_REPO, UPSTREAM_FALLBACK_TAG))
- return ladder
-
-
def _accelerator_from_env() -> str:
"""``UNSLOTH_AUDIO_CPP_ACCELERATOR`` (auto|cpu|cuda|vulkan|metal), for hosts whose GPU is not visible
at install time (a Docker build). Set, it is an explicit request and never downgraded."""
@@ -191,41 +224,16 @@ def _accelerator_from_env() -> str:
return raw
-def load_pins(path: Optional[Path] = None) -> dict:
- try:
- with open(path or PINS_PATH, "r", encoding = "utf-8") as f:
- data = json.load(f)
- except (OSError, ValueError):
- return {}
- releases = data.get("releases") if isinstance(data, dict) else None
- return releases if isinstance(releases, dict) else {}
-
-
-def pinned_sha256(repo: str, tag: Optional[str], asset: str) -> Optional[str]:
- if not tag:
- return None
- digest = ((load_pins().get(repo) or {}).get(tag) or {}).get(asset)
- return core.normalize_sha256_digest(digest)
-
-
-def _expected_sha256(repo: str, tag: Optional[str], asset: dict) -> Optional[str]:
- """The sha256 an asset must hash to: the in-repo pin, which GitHub's own digest must agree with.
- Unpinned assets are refused unless the user picked the release, where GitHub's digest (if any)
- is the best available."""
- name = asset["name"]
- published = core.normalize_sha256_digest(asset.get("digest"))
- pinned = pinned_sha256(repo, tag, name)
- if pinned:
- if published and published != pinned:
- raise RuntimeError(
- f"{name}: GitHub reports sha256 {published} but {PINS_PATH.name} pins {pinned}; refusing it"
- )
- return pinned
- if _user_picked_release():
- return published
- raise RuntimeError(
- f"{name} from {repo} {tag or 'latest'} has no sha256 pinned in {PINS_PATH.name}; refusing an unpinned "
- "download (set UNSLOTH_AUDIO_CPP_REPO or UNSLOTH_AUDIO_CPP_TAG to install a release you chose)"
+def _expected_sha256(release: dict, asset: dict) -> Optional[str]:
+ """The sha256 an asset must hash to: its entry in the release's sha256 index, which any digest
+ the manifest embeds must agree with. An asset the index does not cover raises
+ ``ReleaseIntegrityError``. Only a user-picked release without an index (``checksums`` None)
+ falls back to GitHub's digest, if it reports one."""
+ checksums = release.get("checksums")
+ if checksums is None:
+ return core.normalize_sha256_digest(asset.get("digest"))
+ return core.expected_sha256_for(
+ _OPS, checksums, asset["name"], manifest_sha256 = asset.get("manifest_sha256")
)
@@ -448,54 +456,162 @@ def _fetch_release(
return None # pragma: no cover - the loop returns or raises
-def resolve(accelerator: str, token: Optional[str]) -> tuple[str, Optional[dict], Optional[str]]:
- """``(repo, release, asset)`` for this host along ``_release_ladder()``. Raises
- ``ReleaseLookupUnavailable`` when no lookup answered, so a caller can keep what is installed."""
- primary = _repo()
- driver = nvidia_driver_cuda_version() if accelerator == "cuda" else None
- prefer = torch_cuda_major()
- answered = False
- failures = []
- for repo, want in _release_ladder():
+# Per process, so the CPU-fallback re-resolve and a full install after the re-run check ask once.
+_LATEST_TAG_MEMO: dict[str, Optional[str]] = {}
+_RELEASE_INDEX_MEMO: dict[tuple[str, Optional[str]], Optional[dict]] = {}
+
+
+def _latest_tag_via_download_host(repo: str) -> Optional[str]:
+ """The tag ``github.com/<repo>/releases/latest`` redirects to: one HEAD, no api.github.com call.
+ ``None`` on any failure, so the caller asks the full lookup instead."""
+ if repo not in _LATEST_TAG_MEMO:
try:
- release = _fetch_release(repo, want, token)
- except GitHubRateLimited:
+ _LATEST_TAG_MEMO[repo] = _OPS._download_host_latest_release_tag(repo)
+ except Exception as exc: # noqa: BLE001 - offline, DNS, 5xx: no shortcut
+ print(
+ f"audio.cpp: {repo} latest release lookup failed ({exc})",
+ file = sys.stderr,
+ flush = True,
+ )
+ _LATEST_TAG_MEMO[repo] = None
+ return _LATEST_TAG_MEMO[repo]
+
+
+def _release_index(
+ repo: str,
+ tag: Optional[str],
+ *,
+ token: Optional[str] = None,
+ allow_unindexed: bool = False,
+) -> Optional[dict]:
+ """``{"tag_name", "assets", "checksums"}`` for ``repo`` at ``tag`` (newest when ``None``), through
+ prebuilt_core's release lookup: the manifest's assets with their tag-pinned download URLs, and the
+ release's sha256 index. A lookup that cannot answer raises (``PrebuiltFallback``, ``URLError``,
+ ``OSError``, ``RuntimeError``).
+
+ ``allow_unindexed`` (a user-picked repo or tag) lets a release that publishes no sha256 index
+ through on one GitHub API fetch, with ``checksums`` None so GitHub's digest is the expected sha256.
+ ``None`` when that release does not exist."""
+ key = (repo, tag)
+ if key in _RELEASE_INDEX_MEMO:
+ return _RELEASE_INDEX_MEMO[key]
+ try:
+ bundle, checksums = _OPS.fetch_release_for_install(repo, published_release_tag = tag)
+ except core.ReleaseIntegrityError:
+ raise
+ except core.PrebuiltFallback:
+ if not allow_unindexed:
raise
- except Exception as exc: # noqa: BLE001 - network: try the next rung
- print(f"audio.cpp: {repo} release lookup failed ({exc})", file = sys.stderr, flush = True)
- failures.append(f"{repo}: {exc}")
- continue
- answered = True
- if not release:
- continue
- names = [a["name"] for a in release.get("assets") or []]
- chosen = resolve_release_asset(
- names,
- system = platform.system(),
- machine = platform.machine(),
- accelerator = accelerator,
- driver_cuda = driver,
- prefer_cuda_major = prefer,
+ release = _fetch_release(repo, tag, token)
+ if release is not None:
+ names = {a.get("name") for a in release.get("assets") or [] if isinstance(a, dict)}
+ if SHA256_ASSET_NAME in names:
+ # An index exists, so the lookup failed for another reason: never skip the index.
+ raise
+ print(
+ f"audio.cpp: {repo} {release.get('tag_name')} publishes no {SHA256_ASSET_NAME}; "
+ "using GitHub's asset digests",
+ file = sys.stderr,
+ flush = True,
+ )
+ release = {
+ "tag_name": release.get("tag_name"),
+ "assets": [
+ {
+ "name": a["name"],
+ "browser_download_url": a.get("browser_download_url"),
+ "digest": a.get("digest"),
+ "manifest_sha256": None,
+ "min_os": None,
+ }
+ for a in release.get("assets") or []
+ if isinstance(a, dict) and isinstance(a.get("name"), str)
+ ],
+ "checksums": None,
+ }
+ else:
+ release = {
+ "tag_name": bundle.release_tag,
+ "assets": [
+ {
+ "name": a["asset"],
+ "browser_download_url": _OPS.asset_download_url(bundle, a["asset"]),
+ "manifest_sha256": a.get("sha256"),
+ "min_os": a.get("min_os"),
+ }
+ for a in bundle.manifest.get("artifacts") or []
+ ],
+ "checksums": checksums,
+ }
+ _RELEASE_INDEX_MEMO[key] = release
+ return release
+
+
+def _rate_limit_text(exc: BaseException) -> bool:
+ # prebuilt_core.fetch_json turns an API 403 / 429 into a RuntimeError with this text.
+ return bool(re.search(r"GitHub API returned (403|429)\b", str(exc)))
+
+
+def resolve(
+ accelerator: str,
+ token: Optional[str],
+ tag: Optional[str] = None,
+) -> tuple[str, Optional[dict], Optional[str]]:
+ """``(repo, release, asset)`` for this host from ``_repo()``: ``tag`` (``--published-release-tag``),
+ else ``UNSLOTH_AUDIO_CPP_TAG``, else the newest release. Raises ``ReleaseLookupUnavailable`` (or
+ ``GitHubRateLimited``) when the lookup could not answer, so a caller can keep what is installed;
+ ``ReleaseIntegrityError`` (the release answered and cannot be trusted) is never one of those."""
+ repo = _repo()
+ explicit = (tag or "").strip() or None
+ pin = explicit or _pinned_tag()
+ want = pin or _latest_tag_via_download_host(repo)
+ driver = nvidia_driver_cuda_version() if accelerator == "cuda" else None
+ prefer = torch_cuda_major()
+ try:
+ release = _release_index(
+ repo,
+ want,
+ token = token,
+ # Trust follows the user's own repo/tag pick, so the in-app update can install the tag it
+ # offered from that repo too; the default fork release always publishes its index.
+ allow_unindexed = _user_picked_release(),
)
- if chosen:
- if repo != primary:
- print(f"audio.cpp: falling back to {repo}", file = sys.stderr, flush = True)
- return repo, release, chosen
- if not answered:
+ except core.ReleaseIntegrityError:
+ raise
+ except GitHubRateLimited:
+ raise
+ except (core.PrebuiltFallback, urllib.error.URLError, OSError, RuntimeError) as exc:
+ if _is_rate_limited(exc) or _rate_limit_text(exc):
+ raise GitHubRateLimited(_rate_limit_message()) from exc
+ print(f"audio.cpp: {repo} release lookup failed ({exc})", file = sys.stderr, flush = True)
raise ReleaseLookupUnavailable(
- "no audio.cpp release lookup answered (" + "; ".join(failures) + ")"
- )
- return primary, None, None
+ f"no audio.cpp release lookup answered ({repo} {want or 'latest'}: {exc})"
+ ) from exc
+ if not release:
+ return repo, None, None
+ names = [a["name"] for a in release.get("assets") or []]
+ chosen = resolve_release_asset(
+ names,
+ system = platform.system(),
+ machine = platform.machine(),
+ accelerator = accelerator,
+ driver_cuda = driver,
+ prefer_cuda_major = prefer,
+ )
+ return repo, release, chosen
def resolve_for_request(
- requested: str, detected: Optional[str], token: Optional[str]
+ requested: str,
+ detected: Optional[str],
+ token: Optional[str],
+ tag: Optional[str] = None,
) -> tuple[str, str, Optional[dict], Optional[str]]:
"""``(accelerator, repo, release, asset)``. An auto-detected GPU the published bundles do not
cover (an older driver, Linux arm64) falls back to the CPU build, which still runs every model;
an explicit request is never downgraded."""
accel = detected if requested == "auto" and detected else requested
- repo, release, chosen = resolve(accel, token)
+ repo, release, chosen = resolve(accel, token, tag)
if requested == "auto" and accel == "cuda" and chosen:
major = _cuda_major(chosen)
if not _linux_cuda_runtime_available(major):
@@ -506,49 +622,14 @@ def resolve_for_request(
flush = True,
)
accel = "cpu"
- repo, release, chosen = resolve(accel, token)
+ repo, release, chosen = resolve(accel, token, tag)
if (release is None or not chosen) and requested == "auto" and accel != "cpu":
print(f"audio.cpp: no {accel} bundle for this host; installing the CPU build", flush = True)
accel = "cpu"
- repo, release, chosen = resolve(accel, token)
+ repo, release, chosen = resolve(accel, token, tag)
return accel, repo, release, chosen
-def write_pins(path: Optional[Path] = None, token: Optional[str] = None) -> Path:
- """Regenerate the digest pins from GitHub for the default fork tag and its upstream fallback.
- Only runtime archives are pinned: host bundles (``-bin-``) and Windows CUDA runtimes (``-cudart-``)."""
- releases: dict = {}
- for repo, tag in ((DEFAULT_REPO, DEFAULT_TAG), (UPSTREAM_FALLBACK_REPO, UPSTREAM_FALLBACK_TAG)):
- release = _fetch_release(repo, tag, token)
- if not release:
- raise RuntimeError(f"{repo} has no release {tag}")
- digests = {}
- for asset in release.get("assets") or []:
- name = asset.get("name") or ""
- if "-bin-" not in name and "-cudart-" not in name:
- continue
- digest = core.normalize_sha256_digest(asset.get("digest"))
- if not digest:
- raise RuntimeError(f"{repo} {tag} publishes no sha256 digest for {name}")
- digests[name] = digest
- if not digests:
- raise RuntimeError(f"{repo} {tag} has no audio.cpp runtime assets")
- releases.setdefault(repo, {})[tag] = dict(sorted(digests.items()))
- payload = {
- "schema_version": 1,
- "comment": (
- "Trust anchor for install_audio_cpp_prebuilt.py: sha256 of each audio.cpp runtime archive, "
- "copied from the GitHub release asset digests. Generated; do not edit by hand. To bump: change "
- "DEFAULT_TAG / UPSTREAM_FALLBACK_TAG, then run `python studio/install_audio_cpp_prebuilt.py "
- "--write-pins` (the same digests `gh release view <tag> -R <repo> --json assets` lists)."
- ),
- "releases": releases,
- }
- target = path or PINS_PATH
- target.write_text(json.dumps(payload, indent = 2) + "\n", encoding = "utf-8", newline = "\n")
- return target
-
-
def _download(url: str, dest: Path) -> None:
"""Retried, progress-reporting download (prebuilt_core's), written atomically to ``dest``."""
core.download_file(_OPS, url, dest)
@@ -690,28 +771,13 @@ def _intact_install(target: Path, record: dict) -> Optional[Path]:
return server if _cuda_runtime_satisfied(record) else None
-def _pinned_install_matches(
- target: Path, record: dict, requested: str, detected: Optional[str]
-) -> Optional[Path]:
- """Answer "already matches" with no network call: the record names a (repo, tag) this run would
- look up, its archive digest is the pinned one, it was installed for the same accelerator request
- (and, for auto, the same detected host), and the server on disk is the one it installed."""
- ladder = _release_ladder()
- if not record or any(tag is None for _, tag in ladder):
- return None
- repo, tag = record.get("published_repo"), record.get("release_tag")
- # Only the first rung: a fallback install (the fork lookup failed that run) must ask again.
- if (repo, tag) != ladder[0]:
- return None
- pin = pinned_sha256(repo, tag, str(record.get("asset") or ""))
- if pin is None and not _user_picked_release():
- return None
- if pin is not None and pin != record.get("asset_sha256"):
- return None
+def _record_fits_request(record: dict, requested: str, detected: Optional[str]) -> bool:
+ """The record was installed for the same accelerator request (and, for auto, the same detected
+ host), and is not a CPU fallback that torch's CUDA runtime, here now, would replace."""
if record.get("accelerator_request") != requested:
- return None
+ return False
if requested == "auto" and record.get("detected_accelerator") != detected:
- return None
+ return False
if (
requested == "auto"
and detected == "cuda"
@@ -719,6 +785,29 @@ def _pinned_install_matches(
and _linux_cuda_runtime_available(torch_cuda_major())
):
# Installed as the CPU fallback; torch's CUDA runtime is here now, so look up the GPU build.
+ return False
+ return True
+
+
+def _current_install_matches(
+ target: Path,
+ record: dict,
+ requested: str,
+ detected: Optional[str],
+ latest_tag: Optional[str],
+ *,
+ pinned: bool = False,
+) -> Optional[Path]:
+ """Answer "already matches" before any release lookup: the record names this repo and
+ ``latest_tag`` (the pin, or the newest release ``/releases/latest`` names), or, unpinned, a
+ release newer than it; it fits this accelerator request; and the server on disk is the one it
+ installed. ``latest_tag`` None (that HEAD failed) never matches."""
+ if not record or not latest_tag or record.get("published_repo") != _repo():
+ return None
+ tag = record.get("release_tag")
+ if not (tag == latest_tag if pinned else _record_is_current(tag, latest_tag)):
+ return None
+ if not _record_fits_request(record, requested, detected):
return None
return _intact_install(target, record)
@@ -897,9 +986,13 @@ def install(
accelerator: str = "auto",
token: Optional[str] = None,
force: bool = False,
+ release_tag: Optional[str] = None,
+ keep_newer: bool = False,
) -> Path:
"""Install (or keep) the bundle for ``accelerator``; ``"auto"`` detects the host here, so the
- CPU fallback for an uncovered GPU applies. Serialised on prebuilt_core's install lock."""
+ CPU fallback for an uncovered GPU applies. ``release_tag`` installs exactly that release (the
+ in-app update passes the one it offered); with ``keep_newer`` an intact install of a newer
+ release of this repo is kept instead. Serialised on prebuilt_core's install lock."""
if accelerator not in ACCELERATORS:
raise RuntimeError(
f"unknown accelerator {accelerator!r}; expected one of {', '.join(ACCELERATORS)}"
@@ -916,11 +1009,21 @@ def install(
)
with core.install_lock(core.install_lock_path(target)):
try:
- return _install_locked(target, accelerator, token, force)
+ return _install_locked(
+ target, accelerator, token, force, release_tag = release_tag, keep_newer = keep_newer
+ )
except NoVulkanDevice as exc:
# Forced so the record keeps detected "vulkan": later runs keep this CPU build without a lookup.
print(f"audio.cpp: {exc}; installing the CPU build", flush = True)
- return _install_locked(target, accelerator, token, True, vulkan_unusable = True)
+ return _install_locked(
+ target,
+ accelerator,
+ token,
+ True,
+ vulkan_unusable = True,
+ release_tag = release_tag,
+ keep_newer = keep_newer,
+ )
def _install_locked(
@@ -929,30 +1032,49 @@ def _install_locked(
token: Optional[str],
force: bool,
vulkan_unusable: bool = False,
+ release_tag: Optional[str] = None,
+ keep_newer: bool = False,
) -> Path:
_sweep_retired_trees(target)
detected = detect_accelerator() if requested == "auto" else None
existing = read_install_record(target)
- if not force:
- server = _pinned_install_matches(target, existing, requested, detected)
+ release_tag = (release_tag or "").strip() or None
+ pin = release_tag or _pinned_tag()
+ if (
+ keep_newer
+ and release_tag
+ and not force
+ and existing.get("published_repo") == _repo()
+ and existing.get("release_tag") != release_tag
+ and _record_is_current(existing.get("release_tag"), release_tag)
+ and _record_fits_request(existing, requested, detected)
+ ):
+ # Checked under the install lock: a setup run that got here first with a newer release wins over a
+ # stale offer the in-app update pinned.
+ server = _intact_install(target, existing)
if server is not None:
print(f"audio.cpp: already matches {existing.get('asset')}", flush = True)
return server
- old_glibc = _glibc_below_pinned_floor()
- if old_glibc:
- raise RuntimeError(
- f"audio.cpp prebuilt bundles need glibc {'.'.join(map(str, _PINNED_LINUX_GLIBC_FLOOR))}+; "
- f"this host has {old_glibc}. Set UNSLOTH_AUDIO_CPP_PATH to a local build instead."
+ if not force:
+ # Pinned: no network. Newest: one HEAD, reused as the tag a full install then looks up.
+ latest = pin or _latest_tag_via_download_host(_repo())
+ server = _current_install_matches(
+ target, existing, requested, detected, latest, pinned = pin is not None
)
+ if server is not None:
+ print(f"audio.cpp: already matches {existing.get('asset')}", flush = True)
+ return server
token = token or os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
try:
accel, repo, release, chosen = resolve_for_request(
- requested, "cpu" if vulkan_unusable else detected, token
+ requested, "cpu" if vulkan_unusable else detected, token, release_tag
)
except (ReleaseLookupUnavailable, GitHubRateLimited) as exc:
# The lookup could not answer, which says nothing about the tree on disk. Keep a complete one
- # unless this run asked for something it is not (--force, another explicit accelerator).
- kept = None if force else _intact_install(target, existing)
+ # unless this run asked for something it is not (--force, another explicit accelerator, or a
+ # pinned release: --published-release-tag or UNSLOTH_AUDIO_CPP_TAG, which an installed tree that
+ # matched it already answered above without a lookup).
+ kept = None if force or pin else _intact_install(target, existing)
if kept is None or (requested != "auto" and existing.get("accelerator") != requested):
raise
# "keeping the existing complete install" is the substring setup.sh and setup.ps1 grep for.
@@ -971,7 +1093,7 @@ def _install_locked(
assets = {a["name"]: a for a in release.get("assets") or []}
asset = assets[chosen]
tag = release.get("tag_name")
- expected = _expected_sha256(repo, tag, asset)
+ expected = _expected_sha256(release, asset)
if (
not force
and expected
@@ -981,14 +1103,32 @@ def _install_locked(
):
print(f"audio.cpp: already matches {chosen}", flush = True)
return _intact_install(target, existing)
+ if (
+ not force
+ and pin is None
+ and existing.get("published_repo") == repo
+ and existing.get("release_tag") != tag
+ and _record_is_current(existing.get("release_tag"), tag)
+ and _record_fits_request(existing, requested, detected)
+ and _intact_install(target, existing) is not None
+ ):
+ # The lookup named an older release than the one installed: never downgrade to it.
+ print(f"audio.cpp: already matches {existing.get('asset')}", flush = True)
+ return _intact_install(target, existing)
cudart = cudart_asset_for(list(assets), chosen)
cuda_match = _CUDA_LINE.search(chosen)
cuda_major = int(cuda_match.group(1)) if cuda_match else None
torch_runtime = bool(cudart and cuda_major and torch_provides_cuda_runtime(cuda_major))
cudart_expected = (
- _expected_sha256(repo, tag, assets[cudart]) if cudart and not torch_runtime else None
+ _expected_sha256(release, assets[cudart]) if cudart and not torch_runtime else None
)
+ old_glibc = _glibc_below(asset.get("min_os"))
+ if old_glibc:
+ raise RuntimeError(
+ f"audio.cpp prebuilt bundles need {asset['min_os'].strip().replace('-', ' ', 1)}+; "
+ f"this host has {old_glibc}. Set UNSLOTH_AUDIO_CPP_PATH to a local build instead."
+ )
if target.exists() and _server_in_use(_locate_server(target)):
# Checked again before the swap; here it saves the download.
@@ -1088,25 +1228,32 @@ def main(argv: Optional[list[str]] = None) -> int:
p.add_argument("--force", action = "store_true", help = "reinstall even when the bundle matches")
p.add_argument("--print-asset", action = "store_true", help = "resolve and print the asset only")
p.add_argument(
- "--write-pins",
+ "--published-release-tag",
+ default = None,
+ help = "install exactly this release of the repo (default: UNSLOTH_AUDIO_CPP_TAG, else the newest)",
+ )
+ p.add_argument(
+ "--keep-newer",
action = "store_true",
- help = f"regenerate {PINS_PATH.name} from the pinned GitHub releases",
+ help = "with --published-release-tag: keep an intact install of a newer release of the repo",
)
args = p.parse_args(argv)
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
+ release_tag = (args.published_release_tag or "").strip() or None
try:
- if args.write_pins:
- print(f"audio.cpp: wrote {write_pins(token = token)}")
- return EXIT_OK
if args.print_asset:
detected = detect_accelerator() if args.accelerator == "auto" else None
- _, repo, release, chosen = resolve_for_request(args.accelerator, detected, token)
+ _, repo, release, chosen = resolve_for_request(
+ args.accelerator, detected, token, release_tag
+ )
print(f"{repo} {release.get('tag_name') if release else '-'} {chosen or '(none)'}")
return EXIT_OK if chosen else EXIT_FAILED
install(
install_dir = Path(args.install_dir).expanduser() if args.install_dir else None,
accelerator = args.accelerator,
force = args.force,
+ release_tag = release_tag,
+ keep_newer = args.keep_newer,
)
except GitHubRateLimited as exc:
print(f"error: {exc}", file = sys.stderr)
diff --git a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
index c0263d3e7a6..e8531f72b93 100644
--- a/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
+++ b/tests/studio/install/test_install_audio_cpp_prebuilt_logic.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Logic tests for studio/install_audio_cpp_prebuilt.py -- the self-contained audiocpp_server installer.
-# No network/GPU: asset lists are the real upstream v0.8.2 release names, archives are built in a tmp dir.
+# No network/GPU: asset lists are the real upstream v0.8.2 release names, archives are built in a tmp dir,
+# and release lookups are served from trimmed copies of the published v0.9.1-unsloth.1 manifest and index.
import importlib.util
import json
@@ -129,14 +130,18 @@ def test_driver_cuda_version_reads_both_spellings(monkeypatch, smi, expected):
# Install flow. Archives are real zips in tmp_path; the download copies them, the staged-server check
-# is stubbed (its own tests below), and pins are a per-test dict.
+# is stubbed (its own tests below), and every release carries its own sha256 index, as the fork's do.
FORK = M.DEFAULT_REPO
-FORK_TAG = M.DEFAULT_TAG
+FORK_TAG = "v0.9.1-unsloth.1"
+OLDER_TAG = "v0.9.0-unsloth.1"
+HOTFIX_TAG = "v0.8.2-audio8-perf-hotfix-unsloth.1"
CPU_ZIP = f"audio-{FORK_TAG}-bin-windows-x64-cpu-portable.zip"
+OLDER_ZIP = f"audio-{OLDER_TAG}-bin-windows-x64-cpu-portable.zip"
# The real functions, before any test replaces them.
RESOLVE = M.resolve
SMOKE = M.smoke_test_staged_server
+LATEST_TAG = M._latest_tag_via_download_host
@pytest.fixture(autouse = True)
@@ -150,13 +155,39 @@ def _isolated_env(monkeypatch):
):
monkeypatch.delenv(var, raising = False)
monkeypatch.setattr(M.core, "sleep_backoff", lambda *a, **k: None)
+ monkeypatch.setattr(M, "_LATEST_TAG_MEMO", {})
+ monkeypatch.setattr(M, "_RELEASE_INDEX_MEMO", {})
+ # /releases/latest names FORK_TAG unless a test says otherwise.
+ heads = []
+ monkeypatch.setattr(
+ M, "_latest_tag_via_download_host", lambda repo: heads.append(repo) or FORK_TAG
+ )
+ # Nothing reaches the network: a seam a test forgot to replace fails the test here.
+ hits = []
+
+ class _NoNetwork:
+ def open(
+ self,
+ request,
+ timeout = None,
+ ):
+ hits.append(getattr(request, "full_url", request))
+ raise OSError("network disabled in tests")
+
+ def _no_urlopen(request, timeout = None):
+ hits.append(getattr(request, "full_url", request))
+ raise OSError("network disabled in tests")
+
+ monkeypatch.setattr(M.core, "_URL_OPENER", _NoNetwork())
+ monkeypatch.setattr(M.urllib.request, "urlopen", _no_urlopen)
+ yield heads
+ assert hits == [], f"unexpected network access: {hits}"
@pytest.fixture
-def pins(monkeypatch):
- table = {}
- monkeypatch.setattr(M, "pinned_sha256", lambda repo, tag, asset: table.get((repo, tag, asset)))
- return table
+def heads(_isolated_env):
+ """Repos the stubbed ``/releases/latest`` HEAD was asked for."""
+ return _isolated_env
def _sha(path):
@@ -169,7 +200,10 @@ def _release(
server_path = "bin/audiocpp_server.exe",
tag = FORK_TAG,
extra = (),
+ min_os = None,
):
+ """What ``_release_index`` returns for a release whose one bundle is a real zip in tmp_path,
+ with the index and manifest digests both naming that zip."""
archive = tmp_path / "src" / bundle_name
archive.parent.mkdir(parents = True, exist_ok = True)
with zipfile.ZipFile(archive, "w") as zf:
@@ -180,25 +214,36 @@ def _release(
zf.writestr("bin/README.txt", b"hi")
for name, data in extra:
zf.writestr(name, data)
+ digest = _sha(archive)
return {
"tag_name": tag,
"assets": [
{
"name": bundle_name,
"browser_download_url": str(archive),
- "digest": "sha256:" + _sha(archive),
+ "manifest_sha256": digest,
+ "min_os": min_os,
}
],
+ "checksums": {bundle_name: digest},
}
-def _pin_release(
- pins,
- release,
- repo = FORK,
-):
- for asset in release["assets"]:
- pins[(repo, release["tag_name"], asset["name"])] = asset["digest"].partition(":")[2]
+def _names_release(tag, names):
+ """A release index with these asset names and no archives behind them (lookup-only tests)."""
+ return {
+ "tag_name": tag,
+ "assets": [
+ {
+ "name": n,
+ "browser_download_url": f"https://github.com/{FORK}/releases/download/{tag}/{n}",
+ "manifest_sha256": None,
+ "min_os": None,
+ }
+ for n in names
+ ],
+ "checksums": {n: "0" * 64 for n in names},
+ }
def _fake_download(url, dest):
@@ -216,15 +261,12 @@ def _install(
monkeypatch,
tmp_path,
release,
- pins = None,
repo = FORK,
accelerator = "cpu",
**kw,
):
bundle = release["assets"][0]["name"]
- if pins is not None:
- _pin_release(pins, release, repo)
- monkeypatch.setattr(M, "resolve", lambda accel, token: (repo, release, bundle))
+ monkeypatch.setattr(M, "resolve", lambda accel, token, tag = None: (repo, release, bundle))
_stub_install_io(monkeypatch)
return M.install(install_dir = tmp_path / "audio.cpp", accelerator = accelerator, **kw)
@@ -233,15 +275,64 @@ def _tree_digest(root):
return {p.relative_to(root).as_posix(): _sha(p) for p in sorted(root.rglob("*")) if p.is_file()}
-def test_install_swaps_in_a_complete_tree_and_records_it(monkeypatch, tmp_path, pins):
+def _windows_host(monkeypatch):
+ # The real resolver picks by host; the fixture archives are Windows zips.
+ monkeypatch.setattr(M.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(M.platform, "machine", lambda: "AMD64")
+
+
+def _real_head(monkeypatch, answer):
+ """The real memoized ``_latest_tag_via_download_host`` over a counted prebuilt_core HEAD seam."""
+ calls = []
+
+ def head(repo):
+ calls.append(repo)
+ if isinstance(answer, BaseException):
+ raise answer
+ return answer
+
+ monkeypatch.setattr(M, "_latest_tag_via_download_host", LATEST_TAG)
+ monkeypatch.setattr(M, "_download_host_latest_release_tag", head, raising = False)
+ return calls
+
+
+def _serve_index(monkeypatch, releases):
+ """Replace ``_release_index`` with a ``{(repo, tag): release}`` table; returns what was asked."""
+ asked = []
+
+ def index(
+ repo,
+ tag,
+ *,
+ token = None,
+ allow_unindexed = False,
+ ):
+ asked.append((repo, tag, allow_unindexed))
+ return releases.get((repo, tag))
+
+ monkeypatch.setattr(M, "_release_index", index)
+ return asked
+
+
+def _lookup_fails(monkeypatch, exc):
+ """prebuilt_core's release lookup (reached through _OPS) raises ``exc``."""
+
+ def fetch(repo, *, published_release_tag):
+ raise exc
+
+ monkeypatch.setattr(M, "fetch_release_for_install", fetch, raising = False)
+
+
+def test_install_swaps_in_a_complete_tree_and_records_it(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
- server = _install(monkeypatch, tmp_path, release, pins)
+ server = _install(monkeypatch, tmp_path, release)
root = tmp_path / "audio.cpp"
assert server.is_file() and server.parent == root / "bin"
record = json.loads((root / M.INSTALL_RECORD).read_text())
assert record["backend"] == "cpu"
assert record["server_relpath"] == f"bin/{M.SERVER_NAME}"
assert record["published_repo"] == FORK and record["release_tag"] == FORK_TAG
+ assert record["asset_sha256"] == release["checksums"][CPU_ZIP]
assert record["server_sha256"] == _sha(server)
assert record["server_version"].startswith("audio.cpp test")
assert (
@@ -255,28 +346,54 @@ def test_install_swaps_in_a_complete_tree_and_records_it(monkeypatch, tmp_path,
assert M.core.install_lock_path(root) == tmp_path / ".audio.cpp.install.lock"
-# G2: a no-op re-run does no network work
+# G2: a no-op re-run does no download, one HEAD when tracking the newest, nothing when pinned
-def test_rerun_on_the_pinned_install_makes_no_release_lookup(monkeypatch, tmp_path, pins, capsys):
+def test_rerun_on_the_newest_install_asks_one_head_and_nothing_else(monkeypatch, tmp_path, capsys):
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins, accelerator = "auto")
+ _install(monkeypatch, tmp_path, release, accelerator = "auto")
before = _tree_digest(tmp_path / "audio.cpp")
+ calls = _real_head(monkeypatch, FORK_TAG)
+ monkeypatch.setattr(
+ M, "resolve", lambda *a, **k: pytest.fail("resolve must not run on a matching install")
+ )
monkeypatch.setattr(
- M, "resolve", lambda *a: pytest.fail("resolve must not run on a matching install")
+ M, "_release_index", lambda *a, **k: pytest.fail("no release lookup expected")
)
monkeypatch.setattr(M, "_download", lambda *a: pytest.fail("no download expected"))
capsys.readouterr()
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
assert f"audio.cpp: already matches {CPU_ZIP}" in capsys.readouterr().out
+ assert calls == [FORK]
assert _tree_digest(tmp_path / "audio.cpp") == before
[email protected]("how", ["env", "flag"])
+def test_rerun_on_a_pinned_install_makes_no_network_call(monkeypatch, tmp_path, capsys, how):
+ argv = ["--install-dir", str(tmp_path / "audio.cpp")]
+ if how == "env":
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", FORK_TAG)
+ else:
+ argv += ["--published-release-tag", FORK_TAG]
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP), accelerator = "auto")
+ monkeypatch.setattr(
+ M, "_latest_tag_via_download_host", lambda repo: pytest.fail("a pin asks no HEAD")
+ )
+ monkeypatch.setattr(M, "resolve", lambda *a, **k: pytest.fail("no lookup expected"))
+ monkeypatch.setattr(M, "_download", lambda *a: pytest.fail("no download expected"))
+ capsys.readouterr()
+ assert M.main(argv) == M.EXIT_OK
+ assert f"audio.cpp: already matches {CPU_ZIP}" in capsys.readouterr().out
+
+
@pytest.mark.parametrize(
"mutate",
[
- pytest.param(lambda root, rec: rec.update(release_tag = "v0.8.1-unsloth.1"), id = "older-tag"),
- pytest.param(lambda root, rec: rec.update(asset_sha256 = "0" * 64), id = "unpinned-digest"),
+ pytest.param(lambda root, rec: rec.update(release_tag = OLDER_TAG), id = "older-tag"),
+ pytest.param(
+ lambda root, rec: rec.update(published_repo = "0xShug0/audio.cpp"), id = "other-repo"
+ ),
+ pytest.param(lambda root, rec: rec.update(release_tag = "b123"), id = "unparseable-tag"),
pytest.param(lambda root, rec: rec.update(detected_accelerator = "cuda"), id = "host-changed"),
pytest.param(
lambda root, rec: (root / rec["server_relpath"]).write_bytes(b"tampered"),
@@ -284,75 +401,198 @@ def test_rerun_on_the_pinned_install_makes_no_release_lookup(monkeypatch, tmp_pa
),
],
)
-def test_a_record_that_no_longer_fits_still_looks_up(monkeypatch, tmp_path, pins, mutate):
+def test_a_record_that_no_longer_fits_still_looks_up(monkeypatch, tmp_path, mutate):
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins, accelerator = "auto")
+ _install(monkeypatch, tmp_path, release, accelerator = "auto")
root = tmp_path / "audio.cpp"
record = json.loads((root / M.INSTALL_RECORD).read_text())
mutate(root, record)
(root / M.INSTALL_RECORD).write_text(json.dumps(record))
asked = []
monkeypatch.setattr(
- M, "resolve", lambda accel, token: asked.append(accel) or (FORK, release, CPU_ZIP)
+ M,
+ "resolve",
+ lambda accel, token, tag = None: asked.append(accel) or (FORK, release, CPU_ZIP),
)
M.install(install_dir = root, accelerator = "auto")
assert asked == ["cpu"]
-def test_an_explicit_request_does_not_match_an_auto_install(monkeypatch, tmp_path, pins):
+def test_an_explicit_request_does_not_match_an_auto_install(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins, accelerator = "auto")
+ _install(monkeypatch, tmp_path, release, accelerator = "auto")
asked = []
monkeypatch.setattr(
- M, "resolve", lambda accel, token: asked.append(accel) or (FORK, None, None)
+ M, "resolve", lambda accel, token, tag = None: asked.append(accel) or (FORK, None, None)
)
with pytest.raises(RuntimeError, match = "No prebuilt"):
M.install(install_dir = tmp_path / "audio.cpp", accelerator = "vulkan")
assert asked == ["vulkan"]
-def test_tracking_latest_always_looks_up(monkeypatch, tmp_path, pins):
- release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins)
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", "")
+def test_a_newer_latest_release_is_looked_up_once_and_installed(monkeypatch, tmp_path):
+ _install(monkeypatch, tmp_path, _release(tmp_path / "old", OLDER_ZIP, tag = OLDER_TAG))
+ monkeypatch.setattr(M, "resolve", RESOLVE)
+ _windows_host(monkeypatch)
+ new = _release(tmp_path, CPU_ZIP)
+ asked = _serve_index(monkeypatch, {(FORK, FORK_TAG): new})
+ calls = _real_head(monkeypatch, FORK_TAG)
+ server = M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cpu")
+ # One HEAD: the re-run check asked it, and the lookup reused its answer as the tag.
+ assert calls == [FORK]
+ assert asked == [(FORK, FORK_TAG, False)]
+ record = M.read_install_record(server.parent.parent)
+ assert (record["published_repo"], record["release_tag"], record["asset"]) == (
+ FORK,
+ FORK_TAG,
+ CPU_ZIP,
+ )
+
+
+# A6: an intact install is never replaced by an older release a lookup names
+
+
+def test_an_older_latest_never_replaces_a_newer_install(monkeypatch, tmp_path, capsys):
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP), accelerator = "auto")
root = tmp_path / "audio.cpp"
- assert M._pinned_install_matches(root, M.read_install_record(root), "cpu", None) is None
+ before = _tree_digest(root)
+ calls = _real_head(monkeypatch, HOTFIX_TAG)
+ monkeypatch.setattr(M, "resolve", lambda *a, **k: pytest.fail("no lookup expected"))
+ monkeypatch.setattr(M, "_download", lambda *a: pytest.fail("no download expected"))
+ capsys.readouterr()
+ assert M.main(["--install-dir", str(root)]) == M.EXIT_OK
+ assert f"audio.cpp: already matches {CPU_ZIP}" in capsys.readouterr().out
+ assert calls == [FORK]
+ assert _tree_digest(root) == before
-# G2/AC3: a lookup that cannot answer keeps a complete install
+def test_a_lookup_naming_an_older_release_does_not_downgrade(monkeypatch, tmp_path, capsys):
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP), accelerator = "auto")
+ root = tmp_path / "audio.cpp"
+ before = _tree_digest(root)
+ # No HEAD answer, so the full lookup runs, and the API's newest is an older release.
+ _real_head(monkeypatch, M.urllib.error.URLError("offline"))
+ older = _release(tmp_path / "older", OLDER_ZIP, tag = OLDER_TAG)
+ monkeypatch.setattr(M, "resolve", lambda accel, token, tag = None: (FORK, older, OLDER_ZIP))
+ monkeypatch.setattr(M, "_download", lambda *a: pytest.fail("no download expected"))
+ capsys.readouterr()
+ assert M.main(["--install-dir", str(root)]) == M.EXIT_OK
+ assert f"audio.cpp: already matches {CPU_ZIP}" in capsys.readouterr().out
+ assert _tree_digest(root) == before
-def _offline(monkeypatch):
- def fetch(
- repo,
- tag,
- token,
- timeout = 30.0,
- ):
- raise OSError("network is unreachable")
+def test_a_pinned_older_release_is_installed(monkeypatch, tmp_path):
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP))
+ root = tmp_path / "audio.cpp"
+ older = _release(tmp_path / "older", OLDER_ZIP, tag = OLDER_TAG)
+ asked = []
+ monkeypatch.setattr(
+ M,
+ "resolve",
+ lambda accel, token, tag = None: asked.append(tag) or (FORK, older, OLDER_ZIP),
+ )
+ assert (
+ M.main(
+ [
+ "--install-dir",
+ str(root),
+ "--accelerator",
+ "cpu",
+ "--published-release-tag",
+ OLDER_TAG,
+ ]
+ )
+ == M.EXIT_OK
+ )
+ assert asked == [OLDER_TAG]
+ assert M.read_install_record(root)["release_tag"] == OLDER_TAG
- monkeypatch.setattr(M, "_fetch_release", fetch)
+
+def test_keep_newer_keeps_a_newer_install_over_the_pinned_offer(monkeypatch, tmp_path, capsys):
+ # The in-app update pins the release it offered; a setup run that installed a newer one under the lock first wins.
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP))
+ root = tmp_path / "audio.cpp"
+ before = _tree_digest(root)
+ monkeypatch.setattr(M, "resolve", lambda *a, **k: pytest.fail("no lookup expected"))
+ monkeypatch.setattr(M, "_download", lambda *a: pytest.fail("no download expected"))
+ capsys.readouterr()
+ argv = [
+ "--install-dir",
+ str(root),
+ "--accelerator",
+ "cpu",
+ "--published-release-tag",
+ OLDER_TAG,
+ ]
+ assert M.main([*argv, "--keep-newer"]) == M.EXIT_OK
+ assert f"audio.cpp: already matches {CPU_ZIP}" in capsys.readouterr().out
+ assert _tree_digest(root) == before
+
+
+ "tag, key",
+ [
+ ("v0.9.1-unsloth.1", (0, 9, 1, 1)),
+ ("v0.9.0-unsloth.1", (0, 9, 0, 1)),
+ ("v0.9.0", (0, 9, 0, 0)),
+ ("v0.8.2-audio8-perf-hotfix-unsloth.1", (0, 8, 2, 1)),
+ ("0.10", (0, 10, 0, 0)),
+ ("b123", None),
+ ("", None),
+ (None, None),
+ ("latest", None),
+ ],
+)
+def test_release_version_key(tag, key):
+ assert M.release_version_key(tag) == key
+
+
+ "installed, latest, current",
+ [
+ (FORK_TAG, FORK_TAG, True),
+ (FORK_TAG, OLDER_TAG, True),
+ (FORK_TAG, HOTFIX_TAG, True),
+ (OLDER_TAG, FORK_TAG, False),
+ # Upstream's v0.9.0 is older than the fork's packaging of it.
+ ("v0.9.0", OLDER_TAG, False),
+ # Unparseable never counts as newer.
+ ("b123", FORK_TAG, False),
+ (FORK_TAG, "b123", False),
+ (FORK_TAG, None, False),
+ (None, FORK_TAG, False),
+ ],
+)
+def test_record_is_current_never_takes_an_older_latest(installed, latest, current):
+ assert M._record_is_current(installed, latest) is current
+
+
+# G2/AC3: a lookup that cannot answer keeps a complete install; an integrity failure never does
+
+
+def _offline(monkeypatch):
+ monkeypatch.setattr(M, "_latest_tag_via_download_host", lambda repo: None)
+ _lookup_fails(monkeypatch, M.urllib.error.URLError("network is unreachable"))
def _installed_then_stale(
monkeypatch,
tmp_path,
- pins,
accelerator = "auto",
):
- """A complete install whose record no longer names the pinned tag, so the run must look up."""
+ """A complete install whose record names an older release, so the run must look up."""
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins, accelerator = accelerator)
+ _install(monkeypatch, tmp_path, release, accelerator = accelerator)
root = tmp_path / "audio.cpp"
record = json.loads((root / M.INSTALL_RECORD).read_text())
- record["release_tag"] = "v0.8.1-unsloth.1"
+ record["release_tag"] = OLDER_TAG
(root / M.INSTALL_RECORD).write_text(json.dumps(record))
monkeypatch.setattr(M, "resolve", RESOLVE)
return root
-def test_offline_rerun_keeps_a_complete_install(monkeypatch, tmp_path, pins, capsys):
- root = _installed_then_stale(monkeypatch, tmp_path, pins)
+def test_offline_rerun_keeps_a_complete_install(monkeypatch, tmp_path, capsys):
+ root = _installed_then_stale(monkeypatch, tmp_path)
before = _tree_digest(root)
_offline(monkeypatch)
capsys.readouterr()
@@ -362,20 +602,91 @@ def test_offline_rerun_keeps_a_complete_install(monkeypatch, tmp_path, pins, cap
assert _tree_digest(root) == before
-def test_rate_limited_rerun_keeps_a_complete_install(monkeypatch, tmp_path, pins, capsys):
- root = _installed_then_stale(monkeypatch, tmp_path, pins)
+ "exc",
+ [
+ pytest.param(
+ M.core.PrebuiltFallback(
+ "release unslothai/audio.cpp@x has no audio-cpp-prebuilt-manifest.json"
+ ),
+ id = "prebuilt-fallback",
+ ),
+ pytest.param(
+ M.urllib.error.URLError("temporary failure in name resolution"), id = "urlerror"
+ ),
+ pytest.param(OSError("connection reset"), id = "oserror"),
+ pytest.param(
+ RuntimeError(
+ "GitHub API returned 403 for https://api.github.com/repos/unslothai/audio.cpp/releases?per_page=30"
+ ),
+ id = "rate-limit",
+ ),
+ pytest.param(M.GitHubRateLimited("rate limited"), id = "rate-limited"),
+ ],
+)
+def test_a_lookup_that_cannot_answer_keeps_a_complete_install(monkeypatch, tmp_path, capsys, exc):
+ root = _installed_then_stale(monkeypatch, tmp_path)
+ before = _tree_digest(root)
+ _lookup_fails(monkeypatch, exc)
+ capsys.readouterr()
+ assert M.main(["--install-dir", str(root)]) == M.EXIT_OK
+ assert M.KEPT_EXISTING_LINE in capsys.readouterr().out.splitlines()
+ assert _tree_digest(root) == before
- def fetch(
- repo,
- tag,
- token,
- timeout = 30.0,
- ):
- raise M.GitHubRateLimited("rate limited")
- monkeypatch.setattr(M, "_fetch_release", fetch)
- assert M.main(["--install-dir", str(root)]) == M.EXIT_OK
- assert M.KEPT_EXISTING_LINE in capsys.readouterr().out
[email protected]("how", ["flag", "env"])
+ "exc",
+ [
+ pytest.param(M.urllib.error.URLError("network is unreachable"), id = "offline"),
+ pytest.param(M.GitHubRateLimited("rate limited"), id = "rate-limited"),
+ ],
+)
+def test_a_pinned_release_never_keeps_the_old_tree_when_the_lookup_cannot_answer(
+ monkeypatch, tmp_path, capsys, exc, how
+):
+ # A pin names the release to install; exit 0 would report a release that was never installed.
+ root = _installed_then_stale(monkeypatch, tmp_path)
+ before = _tree_digest(root)
+ _lookup_fails(monkeypatch, exc)
+ capsys.readouterr()
+ argv = ["--install-dir", str(root)]
+ if how == "flag":
+ argv += ["--published-release-tag", FORK_TAG]
+ else:
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", FORK_TAG)
+ assert M.main(argv) == M.EXIT_FAILED
+ assert M.KEPT_EXISTING_LINE not in capsys.readouterr().out
+ assert _tree_digest(root) == before
+
+
+def test_a_rate_limit_from_the_core_lookup_is_reported_as_one(monkeypatch):
+ _lookup_fails(
+ monkeypatch,
+ RuntimeError(
+ "GitHub API returned 429 for https://api.github.com/repos/unslothai/audio.cpp/releases"
+ ),
+ )
+ with pytest.raises(M.GitHubRateLimited, match = "set GH_TOKEN or GITHUB_TOKEN"):
+ M.resolve("cpu", None)
+ _lookup_fails(monkeypatch, M.core.PrebuiltFallback("no manifest"))
+ monkeypatch.setattr(M, "_RELEASE_INDEX_MEMO", {})
+ with pytest.raises(M.ReleaseLookupUnavailable):
+ M.resolve("cpu", None)
+
+
+def test_an_integrity_failure_is_never_kept(monkeypatch, tmp_path, capsys):
+ root = _installed_then_stale(monkeypatch, tmp_path)
+ before = _tree_digest(root)
+ _lookup_fails(
+ monkeypatch, M.core.ReleaseIntegrityError("manifest sha256 disagrees with the index")
+ )
+ capsys.readouterr()
+ assert M.main(["--install-dir", str(root)]) == M.EXIT_FAILED
+ captured = capsys.readouterr()
+ assert M.KEPT_EXISTING_LINE not in captured.out
+ assert "disagrees with the index" in captured.err
+ assert _tree_digest(root) == before
def test_offline_without_an_install_fails(monkeypatch, tmp_path, capsys):
@@ -385,18 +696,16 @@ def test_offline_without_an_install_fails(monkeypatch, tmp_path, capsys):
assert "no audio.cpp release lookup answered" in capsys.readouterr().err
-def test_offline_keeps_nothing_for_a_tampered_server(monkeypatch, tmp_path, pins, capsys):
- root = _installed_then_stale(monkeypatch, tmp_path, pins)
+def test_offline_keeps_nothing_for_a_tampered_server(monkeypatch, tmp_path, capsys):
+ root = _installed_then_stale(monkeypatch, tmp_path)
(root / "bin" / M.SERVER_NAME).write_bytes(b"truncated")
_offline(monkeypatch)
assert M.main(["--install-dir", str(root)]) == M.EXIT_FAILED
assert M.KEPT_EXISTING_LINE not in capsys.readouterr().out
-def test_offline_does_not_keep_an_install_for_another_explicit_accelerator(
- monkeypatch, tmp_path, pins
-):
- root = _installed_then_stale(monkeypatch, tmp_path, pins)
+def test_offline_does_not_keep_an_install_for_another_explicit_accelerator(monkeypatch, tmp_path):
+ root = _installed_then_stale(monkeypatch, tmp_path)
_offline(monkeypatch)
assert M.main(["--install-dir", str(root), "--accelerator", "vulkan"]) == M.EXIT_FAILED
assert M.main(["--install-dir", str(root), "--force"]) == M.EXIT_FAILED
@@ -408,7 +717,11 @@ def test_offline_does_not_keep_an_install_for_another_explicit_accelerator(
def _resolve_recording(release, covers = ("cpu",)):
asked = []
- def resolve(accel, token):
+ def resolve(
+ accel,
+ token,
+ tag = None,
+ ):
asked.append(accel)
if accel in covers:
return FORK, release, release["assets"][0]["name"]
@@ -417,11 +730,8 @@ def _resolve_recording(release, covers = ("cpu",)):
return asked, resolve
-def test_main_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(
- monkeypatch, tmp_path, pins
-):
+def test_main_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
- _pin_release(pins, release)
asked, resolve = _resolve_recording(release)
_stub_install_io(monkeypatch)
monkeypatch.setattr(M, "resolve", resolve)
@@ -437,10 +747,9 @@ def test_main_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(
def test_auto_cuda_without_a_cuda_runtime_installs_the_cpu_build_and_reruns_offline(
- monkeypatch, tmp_path, pins
+ monkeypatch, tmp_path
):
release = _release(tmp_path, CPU_ZIP)
- _pin_release(pins, release)
asked, resolve = _resolve_recording(release, covers = ("cpu", "cuda"))
_stub_install_io(monkeypatch)
seen = []
@@ -457,13 +766,17 @@ def test_auto_cuda_without_a_cuda_runtime_installs_the_cpu_build_and_reruns_offl
"auto",
"cuda",
)
- monkeypatch.setattr(M, "resolve", lambda *a: pytest.fail("a matching rerun must not look up"))
+ monkeypatch.setattr(
+ M, "resolve", lambda *a, **k: pytest.fail("a matching rerun must not look up")
+ )
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
# torch's CUDA runtime arrived: the CPU fallback is no longer a match, so the GPU build is looked up.
monkeypatch.setattr(M, "_linux_cuda_runtime_available", lambda major: True)
looked = []
monkeypatch.setattr(
- M, "resolve", lambda accel, token: looked.append(accel) or (FORK, release, CPU_ZIP)
+ M,
+ "resolve",
+ lambda accel, token, tag = None: looked.append(accel) or (FORK, release, CPU_ZIP),
)
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
assert looked == ["cuda"]
@@ -475,7 +788,7 @@ def test_explicit_cuda_is_not_downgraded_for_a_missing_cuda_runtime(monkeypatch)
monkeypatch.setattr(
M,
"resolve",
- lambda accel, token: asked.append(accel)
+ lambda accel, token, tag = None: asked.append(accel)
or (FORK, {"assets": []}, "a-bin-ubuntu-x64-cuda13.tar.gz"),
)
M.resolve_for_request("cuda", None, None)
@@ -525,7 +838,7 @@ def test_cuda_lines_with_and_without_a_minor(names, driver, prefer, want):
assert M.cudart_asset_for(win, win[0]) == win[1]
-def test_main_explicit_gpu_request_is_never_downgraded(monkeypatch, tmp_path, pins):
+def test_main_explicit_gpu_request_is_never_downgraded(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
asked, resolve = _resolve_recording(release)
_stub_install_io(monkeypatch)
@@ -550,18 +863,32 @@ def test_print_asset_resolves_like_install(monkeypatch, tmp_path, capsys):
monkeypatch.setattr(M, "_linux_cuda_runtime_available", lambda major: True)
assert M.main(["--print-asset"]) == M.EXIT_OK
assert asked == ["cuda", "cpu"]
- assert capsys.readouterr().out.strip().endswith(CPU_ZIP)
+ assert capsys.readouterr().out.strip().splitlines()[-1] == f"{FORK} {FORK_TAG} {CPU_ZIP}"
+
+
+def test_print_asset_takes_the_pin_flag(monkeypatch, capsys):
+ # The flag overrides the env pin and asks no HEAD.
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", HOTFIX_TAG)
+ monkeypatch.setattr(
+ M, "_latest_tag_via_download_host", lambda repo: pytest.fail("a pin asks no HEAD")
+ )
+ _windows_host(monkeypatch)
+ asked = _serve_index(monkeypatch, {(FORK, OLDER_TAG): _names_release(OLDER_TAG, [OLDER_ZIP])})
+ argv = ["--print-asset", "--accelerator", "cpu", "--published-release-tag", OLDER_TAG]
+ assert M.main(argv) == M.EXIT_OK
+ assert capsys.readouterr().out.strip() == f"{FORK} {OLDER_TAG} {OLDER_ZIP}"
+ # The env pin is the user's pick, so an index-less release could fall back to GitHub's digest.
+ assert asked == [(FORK, OLDER_TAG, True)]
# G12: UNSLOTH_AUDIO_CPP_ACCELERATOR
-def test_accelerator_env_is_an_explicit_request(monkeypatch, tmp_path, pins):
+def test_accelerator_env_is_an_explicit_request(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
asked, resolve = _resolve_recording(release, covers = ("cpu", "cuda"))
_stub_install_io(monkeypatch)
monkeypatch.setattr(M, "resolve", resolve)
- _pin_release(pins, release)
monkeypatch.setattr(
M, "detect_accelerator", lambda: pytest.fail("an explicit accelerator must not detect")
)
@@ -580,191 +907,522 @@ def test_an_unknown_accelerator_env_falls_back_to_auto(monkeypatch, capsys):
assert "ignoring UNSLOTH_AUDIO_CPP_ACCELERATOR" in capsys.readouterr().err
-# G11: release ladder and digest pins
+# G11: which release, from which repo
-def test_default_ladder_is_the_pinned_fork_tag_then_its_upstream_release(monkeypatch):
- tried = []
- monkeypatch.setattr(
- M, "_fetch_release", lambda repo, tag, token: tried.append((repo, tag)) or None
- )
- monkeypatch.setattr(M, "nvidia_driver_cuda_version", lambda: None)
- assert M.resolve("cpu", None) == (FORK, None, None)
- # No "latest" rungs: a pinned install never drifts to an untested release.
- assert tried == [
- (M.DEFAULT_REPO, M.DEFAULT_TAG),
- (M.UPSTREAM_FALLBACK_REPO, M.UPSTREAM_FALLBACK_TAG),
- ]
+def test_the_default_repo_is_the_fork_with_no_fallback_repo():
+ assert M.DEFAULT_REPO == "unslothai/audio.cpp" and M._repo() == M.DEFAULT_REPO
+ # No upstream rung and no in-repo digest table: the fork's own release index is the trust anchor.
+ assert not [name for name in vars(M) if "UPSTREAM" in name or "PINS" in name.upper()]
+
+
[email protected]("value", [None, "", "latest", " LATEST "])
+def test_an_unset_empty_or_latest_tag_tracks_the_newest_release(monkeypatch, heads, value):
+ if value is not None:
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", value)
+ assert M._pinned_tag() is None and M._user_picked_release() is False
+ _windows_host(monkeypatch)
+ asked = _serve_index(monkeypatch, {(FORK, FORK_TAG): _names_release(FORK_TAG, [CPU_ZIP])})
+ assert M.resolve("cpu", None)[1:] == (_names_release(FORK_TAG, [CPU_ZIP]), CPU_ZIP)
+ assert asked == [(FORK, FORK_TAG, False)] and heads == [FORK]
-def test_latest_is_tried_only_when_the_user_asks_for_it(monkeypatch):
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", "")
- assert M._release_ladder() == [(M.DEFAULT_REPO, None)]
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_REPO", "someone/audio.cpp")
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", "v1")
- assert M._release_ladder() == [("someone/audio.cpp", "v1")]
+def test_an_exact_tag_pins_the_release(monkeypatch, heads):
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", f" {OLDER_TAG} ")
+ assert M._pinned_tag() == OLDER_TAG and M._user_picked_release() is True
+ _windows_host(monkeypatch)
+ asked = _serve_index(
+ monkeypatch,
+ {
+ (FORK, OLDER_TAG): _names_release(OLDER_TAG, [OLDER_ZIP]),
+ (FORK, FORK_TAG): _names_release(FORK_TAG, [CPU_ZIP]),
+ },
+ )
+ assert M.resolve("cpu", None) == (FORK, _names_release(OLDER_TAG, [OLDER_ZIP]), OLDER_ZIP)
+ # --published-release-tag beats the env pin; trust still follows the user's pick from the env.
+ assert M.resolve("cpu", None, FORK_TAG)[2] == CPU_ZIP
+ assert asked == [(FORK, OLDER_TAG, True), (FORK, FORK_TAG, True)]
+ assert heads == []
-def test_a_user_chosen_tag_never_reaches_the_upstream_repo(monkeypatch):
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", "v9")
- assert M._release_ladder() == [(M.DEFAULT_REPO, "v9")]
+def test_a_repo_override_tracks_that_repos_newest_release(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_REPO", " someone/audio.cpp ")
+ monkeypatch.setattr(M, "_latest_tag_via_download_host", lambda repo: "v2")
+ asked = _serve_index(monkeypatch, {})
+ assert M.resolve("cpu", None) == ("someone/audio.cpp", None, None)
+ assert asked == [("someone/audio.cpp", "v2", True)]
@pytest.mark.parametrize(
- "libc, refused",
+ "min_os, libc, refused",
[
- (("glibc", "2.31"), True),
- (("glibc", "2.34"), True),
- (("glibc", "2.35"), False),
- (("glibc", "2.39"), False),
- (("", ""), False),
- (("glibc", "weird"), False),
+ ("glibc-2.35", ("glibc", "2.31"), True),
+ ("glibc-2.35", ("glibc", "2.34"), True),
+ ("glibc-2.35", ("glibc", "2.35"), False),
+ ("glibc-2.35", ("glibc", "2.39"), False),
+ ("glibc-2.35", ("", ""), False),
+ ("glibc-2.35", ("glibc", "weird"), False),
+ # The floor is the manifest's, not a constant.
+ ("glibc-2.39", ("glibc", "2.35"), True),
+ # No manifest (a user-picked release without one): no check.
+ (None, ("glibc", "2.31"), False),
],
)
-def test_old_glibc_is_refused_before_any_download(monkeypatch, tmp_path, libc, refused):
+def test_old_glibc_is_refused_before_the_bundle_download(
+ monkeypatch, tmp_path, min_os, libc, refused
+):
monkeypatch.setattr(M.sys, "platform", "linux")
monkeypatch.setattr(M.platform, "libc_ver", lambda: libc)
- lookups = []
+ release = _release(tmp_path, CPU_ZIP, min_os = min_os)
+ _stub_install_io(monkeypatch)
+ downloads = []
monkeypatch.setattr(
- M, "resolve_for_request", lambda *a: lookups.append(a) or ("cpu", FORK, None, None)
+ M, "_download", lambda url, dest: downloads.append(url) or _fake_download(url, dest)
)
- with pytest.raises(RuntimeError) as exc:
- M._install_locked(tmp_path / "audio.cpp", "cpu", None, False)
- assert ("need glibc 2.35+" in str(exc.value)) is refused
- assert (lookups == []) is refused
+ monkeypatch.setattr(M, "resolve_for_request", lambda *a: ("cpu", FORK, release, CPU_ZIP))
+ target = tmp_path / "audio.cpp"
+ if refused:
+ floor = min_os.split("-")[1]
+ with pytest.raises(RuntimeError, match = rf"need glibc {floor}\+; this host has {libc[1]}"):
+ M._install_locked(target, "cpu", None, False)
+ assert downloads == [] and not target.exists()
+ else:
+ assert M._install_locked(target, "cpu", None, False).is_file()
+ assert len(downloads) == 1
-def test_old_glibc_is_not_refused_for_a_user_chosen_release(monkeypatch):
- monkeypatch.setattr(M.sys, "platform", "linux")
- monkeypatch.setattr(M.platform, "libc_ver", lambda: ("glibc", "2.31"))
- assert M._glibc_below_pinned_floor() == "2.31"
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_REPO", "someone/audio.cpp")
- assert M._glibc_below_pinned_floor() is None
+# A3: every archive is checked against the release's own sha256 index
-def test_an_unpinned_asset_is_refused_by_default(monkeypatch, tmp_path, pins):
- release = _release(tmp_path, CPU_ZIP)
- with pytest.raises(RuntimeError, match = "no sha256 pinned"):
- _install(monkeypatch, tmp_path, release)
- assert not (tmp_path / "audio.cpp").exists()
+def _install_via_main(monkeypatch, tmp_path, release, *argv):
+ bundle = release["assets"][0]["name"]
+ monkeypatch.setattr(M, "resolve", lambda accel, token, tag = None: (FORK, release, bundle))
+ _stub_install_io(monkeypatch)
+ downloads = []
+ monkeypatch.setattr(
+ M,
+ "_download",
+ lambda url, dest: downloads.append(Path(url).name) or _fake_download(url, dest),
+ )
+ code = M.main(["--install-dir", str(tmp_path / "audio.cpp"), "--accelerator", "cpu", *argv])
+ return code, downloads
-def test_an_unpinned_asset_is_allowed_for_a_release_the_user_picked(monkeypatch, tmp_path, pins):
- monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", FORK_TAG)
+def test_an_asset_the_index_does_not_cover_is_refused(monkeypatch, tmp_path, capsys):
release = _release(tmp_path, CPU_ZIP)
- assert _install(monkeypatch, tmp_path, release).is_file()
+ release["checksums"] = {f"audio-{FORK_TAG}-bin-windows-x64-cpu.zip": "1" * 64}
+ code, downloads = _install_via_main(monkeypatch, tmp_path, release)
+ assert code == M.EXIT_FAILED and downloads == []
+ assert f"{CPU_ZIP} is not covered by {M.SHA256_ASSET_NAME}" in capsys.readouterr().err
+ assert not (tmp_path / "audio.cpp").exists()
-def test_a_github_digest_that_disagrees_with_the_pin_is_refused(monkeypatch, tmp_path, pins):
+def test_a_manifest_digest_that_disagrees_with_the_index_is_refused(monkeypatch, tmp_path, capsys):
release = _release(tmp_path, CPU_ZIP)
- _pin_release(pins, release)
- release["assets"][0]["digest"] = "sha256:" + "1" * 64
- with pytest.raises(RuntimeError, match = "pins"):
- _install(monkeypatch, tmp_path, release)
+ release["assets"][0]["manifest_sha256"] = "1" * 64
+ code, downloads = _install_via_main(monkeypatch, tmp_path, release)
+ assert code == M.EXIT_FAILED and downloads == []
+ assert "disagrees with" in capsys.readouterr().err
+ assert not (tmp_path / "audio.cpp").exists()
-def test_a_download_that_does_not_hash_to_the_pin_is_refused(monkeypatch, tmp_path, pins):
+def test_a_download_that_does_not_hash_to_the_index_is_refused(monkeypatch, tmp_path, capsys):
release = _release(tmp_path, CPU_ZIP)
- pins[(FORK, FORK_TAG, CPU_ZIP)] = "0" * 64
- release["assets"][0]["digest"] = None
- with pytest.raises(RuntimeError, match = "sha256 mismatch"):
- _install(monkeypatch, tmp_path, release)
+ release["checksums"][CPU_ZIP] = release["assets"][0]["manifest_sha256"] = "0" * 64
+ code, downloads = _install_via_main(monkeypatch, tmp_path, release)
+ assert code == M.EXIT_FAILED and downloads == [CPU_ZIP]
+ assert f"sha256 mismatch for {CPU_ZIP}" in capsys.readouterr().err
assert not (tmp_path / "audio.cpp").exists()
-OLD_TAG = "v0.8.2-audio8-perf-hotfix-unsloth.1"
-
-
-def _installed_at_an_older_release(monkeypatch, tmp_path, pins):
- """What the in-app update replaces: a Studio-managed tree of a release this Studio no longer pins."""
- old = _release(tmp_path, f"audio-{OLD_TAG}-bin-windows-x64-cpu-portable.zip", tag = OLD_TAG)
- _install(monkeypatch, tmp_path, old, pins)
+def _installed_at_an_older_release(monkeypatch, tmp_path):
+ """What an update replaces: a Studio-managed tree of an older release."""
+ old = _release(tmp_path, f"audio-{HOTFIX_TAG}-bin-windows-x64-cpu-portable.zip", tag = HOTFIX_TAG)
+ _install(monkeypatch, tmp_path, old)
return tmp_path / "audio.cpp"
-def test_an_older_release_is_replaced_by_the_pinned_one(monkeypatch, tmp_path, pins):
- root = _installed_at_an_older_release(monkeypatch, tmp_path, pins)
- server = _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP), pins)
+def test_an_older_release_is_replaced_by_the_newest(monkeypatch, tmp_path):
+ root = _installed_at_an_older_release(monkeypatch, tmp_path)
+ server = _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP))
record = json.loads((root / M.INSTALL_RECORD).read_text())
assert (record["release_tag"], record["asset"]) == (FORK_TAG, CPU_ZIP)
assert server.read_bytes() == b"binary " + CPU_ZIP.encode()
-def test_an_update_that_fails_its_pin_leaves_the_older_tree(monkeypatch, tmp_path, pins):
- root = _installed_at_an_older_release(monkeypatch, tmp_path, pins)
+def test_an_update_that_fails_the_index_leaves_the_older_tree(monkeypatch, tmp_path, capsys):
+ root = _installed_at_an_older_release(monkeypatch, tmp_path)
before = _tree_digest(root)
release = _release(tmp_path, CPU_ZIP)
- release["assets"][0]["digest"] = None
- pins[(FORK, FORK_TAG, CPU_ZIP)] = "0" * 64
- with pytest.raises(RuntimeError, match = "sha256 mismatch"):
- _install(monkeypatch, tmp_path, release)
+ release["checksums"][CPU_ZIP] = release["assets"][0]["manifest_sha256"] = "0" * 64
+ capsys.readouterr()
+ code, _ = _install_via_main(monkeypatch, tmp_path, release)
+ assert code == M.EXIT_FAILED
+ out, err = capsys.readouterr()
+ assert "sha256 mismatch" in err
+ assert not any(line.startswith("audio.cpp: installed") for line in out.splitlines())
assert _tree_digest(root) == before
-def test_the_pins_file_covers_both_default_releases():
- table = M.load_pins()
- for repo, tag in (
- (M.DEFAULT_REPO, M.DEFAULT_TAG),
- (M.UPSTREAM_FALLBACK_REPO, M.UPSTREAM_FALLBACK_TAG),
+WIN_CUDA_ZIP = f"audio-{FORK_TAG}-bin-windows-x64-cuda12.zip"
+CUDART_ZIP = f"audio-{FORK_TAG}-cudart-windows-x64-cuda12.zip"
+
+
+def _cuda_release(monkeypatch, tmp_path):
+ """A Windows CUDA bundle plus its cudart archive, on a Python whose torch ships no CUDA runtime."""
+ release = _release(tmp_path, WIN_CUDA_ZIP)
+ runtime = tmp_path / "src" / CUDART_ZIP
+ with zipfile.ZipFile(runtime, "w") as zf:
+ zf.writestr("cudart64_12.dll", b"runtime")
+ digest = _sha(runtime)
+ release["assets"].append(
+ {
+ "name": CUDART_ZIP,
+ "browser_download_url": str(runtime),
+ "manifest_sha256": digest,
+ "min_os": None,
+ }
+ )
+ release["checksums"][CUDART_ZIP] = digest
+ _stub_install_io(monkeypatch)
+ downloads = []
+ monkeypatch.setattr(
+ M,
+ "_download",
+ lambda url, dest: downloads.append(Path(url).name) or _fake_download(url, dest),
+ )
+ monkeypatch.setattr(M, "torch_provides_cuda_runtime", lambda major: False)
+ monkeypatch.setattr(M, "_cuda_runtime_dirs", lambda backend: [])
+ monkeypatch.setattr(M, "resolve", lambda accel, token, tag = None: (FORK, release, WIN_CUDA_ZIP))
+ return release, downloads
+
+
+def test_the_cuda_runtime_archive_is_verified_against_the_index(monkeypatch, tmp_path, capsys):
+ release, downloads = _cuda_release(monkeypatch, tmp_path)
+ server = M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cuda")
+ assert downloads == [WIN_CUDA_ZIP, CUDART_ZIP]
+ assert (server.parent / "cudart64_12.dll").read_bytes() == b"runtime"
+ record = M.read_install_record(tmp_path / "audio.cpp")
+ assert (record["asset"], record["cudart_asset"], record["backend"]) == (
+ WIN_CUDA_ZIP,
+ CUDART_ZIP,
+ "cuda",
+ )
+ err = capsys.readouterr().err
+ assert f"verifying {CUDART_ZIP} against {M.SHA256_ASSET_NAME}" in err
+
+
+def test_a_cuda_runtime_archive_the_index_does_not_cover_is_refused(monkeypatch, tmp_path):
+ release, downloads = _cuda_release(monkeypatch, tmp_path)
+ del release["checksums"][CUDART_ZIP]
+ with pytest.raises(M.core.ReleaseIntegrityError, match = "not covered"):
+ M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cuda")
+ # Refused before either archive is fetched.
+ assert downloads == [] and not (tmp_path / "audio.cpp").exists()
+
+
+def test_a_cuda_runtime_download_that_does_not_hash_to_the_index_is_refused(monkeypatch, tmp_path):
+ release, downloads = _cuda_release(monkeypatch, tmp_path)
+ release["checksums"][CUDART_ZIP] = release["assets"][1]["manifest_sha256"] = "0" * 64
+ with pytest.raises(RuntimeError, match = f"sha256 mismatch for {CUDART_ZIP}"):
+ M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cuda")
+ assert downloads == [WIN_CUDA_ZIP, CUDART_ZIP] and not (tmp_path / "audio.cpp").exists()
+
+
+# User-picked releases without an index: GitHub's digest, and only for the user's own pick
+
+
+UPSTREAM = "0xShug0/audio.cpp"
+UPSTREAM_ZIP = "audio-v0.9.1-bin-windows-x64-cpu-portable.zip"
+
+
+def _unindexed_upstream(
+ monkeypatch,
+ tmp_path,
+ *,
+ publishes_index = False,
+):
+ """The fork-style lookup fails (no manifest, no index); the API release lists GitHub digests."""
+ _lookup_fails(
+ monkeypatch,
+ M.core.PrebuiltFallback(f"release {UPSTREAM}@v0.9.1 has no {M.MANIFEST_ASSET_NAME}"),
+ )
+ archive = _release(tmp_path, UPSTREAM_ZIP, tag = "v0.9.1")["assets"][0]["browser_download_url"]
+ assets = [
+ {
+ "name": UPSTREAM_ZIP,
+ "browser_download_url": archive,
+ "digest": "sha256:" + _sha(Path(archive)),
+ },
+ {"name": "framework.tar.gz", "browser_download_url": "x", "digest": None},
+ ]
+ if publishes_index:
+ assets.append({"name": M.SHA256_ASSET_NAME, "browser_download_url": "x", "digest": None})
+ fetched = []
+
+ def fetch(
+ repo,
+ tag,
+ token,
+ timeout = 30.0,
):
- names = list(table[repo][tag])
- # Stale after a tag bump until `--write-pins` regenerates it.
- assert names and all(f"audio-{tag}-" in n for n in names), (repo, tag)
- assert all(M.core.normalize_sha256_digest(table[repo][tag][n]) for n in names)
- for system, machine, accel in (
- ("Windows", "AMD64", "cpu"),
- ("Windows", "AMD64", "cuda"),
- ("Linux", "x86_64", "cpu"),
- ("Linux", "x86_64", "cuda"),
- ("Darwin", "arm64", "metal"),
- ):
- chosen = M.resolve_release_asset(
- names, system = system, machine = machine, accelerator = accel
- )
- assert chosen, (repo, tag, system, accel)
- if system == "Windows" and accel == "cuda":
- assert M.cudart_asset_for(names, chosen) in names
+ fetched.append((repo, tag))
+ return {"tag_name": "v0.9.1", "assets": assets}
+ monkeypatch.setattr(M, "_fetch_release", fetch)
+ monkeypatch.setattr(M, "_latest_tag_via_download_host", lambda repo: "v0.9.1")
+ _windows_host(monkeypatch)
+ return fetched
-def test_write_pins_regenerates_from_the_release_digests(monkeypatch, tmp_path):
- releases = {
- (M.DEFAULT_REPO, M.DEFAULT_TAG): [
- {
- "name": f"audio-{M.DEFAULT_TAG}-bin-windows-x64-cpu.zip",
- "digest": "sha256:" + "b" * 64,
- },
- {
- "name": f"audio-{M.DEFAULT_TAG}-cudart-windows-x64-cuda12.4.zip",
- "digest": "sha256:" + "c" * 64,
- },
- {
- "name": f"audio-{M.DEFAULT_TAG}-bin-macos-arm64-metal.tar.gz",
- "digest": "sha256:" + "a" * 64,
- },
- {"name": "framework.tar.gz", "digest": None},
- ],
- (M.UPSTREAM_FALLBACK_REPO, M.UPSTREAM_FALLBACK_TAG): [
- {
- "name": f"audio-{M.UPSTREAM_FALLBACK_TAG}-bin-windows-x64-cpu.zip",
- "digest": "sha256:" + "d" * 64,
- },
- ],
- }
- monkeypatch.setattr(
- M,
- "_fetch_release",
- lambda repo, tag, token: {"tag_name": tag, "assets": releases[(repo, tag)]},
+
+def test_a_user_picked_release_without_an_index_installs_on_githubs_digest(
+ monkeypatch, tmp_path, capsys
+):
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_REPO", UPSTREAM)
+ fetched = _unindexed_upstream(monkeypatch, tmp_path)
+ _stub_install_io(monkeypatch)
+ server = M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cpu")
+ record = M.read_install_record(server.parent.parent)
+ assert (record["published_repo"], record["release_tag"], record["asset"]) == (
+ UPSTREAM,
+ "v0.9.1",
+ UPSTREAM_ZIP,
)
- out = M.write_pins(tmp_path / "pins.json")
- first = out.read_bytes()
- assert M.write_pins(tmp_path / "pins.json").read_bytes() == first
- table = M.load_pins(out)
- fork = table[M.DEFAULT_REPO][M.DEFAULT_TAG]
- assert list(fork) == sorted(fork) and "framework.tar.gz" not in fork
- assert fork[f"audio-{M.DEFAULT_TAG}-cudart-windows-x64-cuda12.4.zip"] == "c" * 64
- releases[(M.DEFAULT_REPO, M.DEFAULT_TAG)][0]["digest"] = None
- with pytest.raises(RuntimeError, match = "no sha256 digest"):
- M.write_pins(tmp_path / "pins.json")
+ assert record["asset_sha256"] == _sha(tmp_path / "src" / UPSTREAM_ZIP)
+ assert fetched == [(UPSTREAM, "v0.9.1")]
+ assert f"publishes no {M.SHA256_ASSET_NAME}" in capsys.readouterr().err
+
+
+def test_an_unindexed_release_trusts_githubs_digest_or_none():
+ release = {"checksums": None}
+ assert M._expected_sha256(release, {"name": "a.zip", "digest": None}) is None
+ assert (
+ M._expected_sha256(release, {"name": "a.zip", "digest": "sha256:" + "A" * 64}) == "a" * 64
+ )
+
+
+def test_the_index_is_never_skipped_by_default(monkeypatch, tmp_path):
+ fetched = _unindexed_upstream(monkeypatch, tmp_path)
+ with pytest.raises(M.ReleaseLookupUnavailable, match = "has no"):
+ M.resolve("cpu", None)
+ assert fetched == []
+
+
+def test_the_pin_flag_never_skips_the_index_of_the_default_repo(monkeypatch, tmp_path):
+ fetched = _unindexed_upstream(monkeypatch, tmp_path)
+ with pytest.raises(M.ReleaseLookupUnavailable, match = "has no"):
+ M.resolve("cpu", None, "v0.9.1")
+ assert fetched == []
+
+
+def test_the_in_app_pin_installs_from_a_user_picked_repo_without_an_index(monkeypatch, tmp_path):
+ # The in-app update passes the tag it offered; setup accepted this repo on GitHub's digest, so the
+ # update must too, or the offer could never be applied.
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_REPO", UPSTREAM)
+ fetched = _unindexed_upstream(monkeypatch, tmp_path)
+ repo, release, chosen = M.resolve("cpu", None, "v0.9.1")
+ assert (repo, chosen, release["checksums"]) == (UPSTREAM, UPSTREAM_ZIP, None)
+ assert fetched == [(UPSTREAM, "v0.9.1")]
+
+
+def test_a_user_picked_release_that_publishes_an_index_never_skips_it(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_AUDIO_CPP_TAG", "v0.9.1")
+ fetched = _unindexed_upstream(monkeypatch, tmp_path, publishes_index = True)
+ with pytest.raises(M.ReleaseLookupUnavailable):
+ M.resolve("cpu", None)
+ assert fetched == [(FORK, "v0.9.1")]
+
+
+# _release_index through prebuilt_core's real lookup and parsers, fed the published v0.9.1-unsloth.1
+# manifest and sha256 index (trimmed to three of their artifacts; digests as published).
+
+_V091 = "v0.9.1-unsloth.1"
+_V091_COMMIT = "cf124a67cc55d8f65a9a15eec69edbff0fb212c8"
+_V091_LINUX_CPU = f"audio-{_V091}-bin-ubuntu-x64-cpu-portable.tar.gz"
+_V091_WIN_CUDA = f"audio-{_V091}-bin-windows-x64-cuda12.zip"
+_V091_CUDART = f"audio-{_V091}-cudart-windows-x64-cuda12.zip"
+_V091_SHA = {
+ _V091_LINUX_CPU: "a1e61f1ed2d987b15950cb63e61872b2edd4fbf5e463602e64aa404296d901bb",
+ _V091_WIN_CUDA: "e865b05fac29956110b1140457fccd9319583be3025aa6a30f1f653aa0003a75",
+ _V091_CUDART: "78ff03c3215e254c5c38c8689a9054287d39d9490626a7c475babd88b326f2a6",
+ f"audio.cpp-source-{_V091}.tar.gz": "d5df360aa4e2017bb733479b09b205c434561cc2f05fbd67e87e67733cc3f7a8",
+ "audio-cpp-prebuilt-manifest.json": "fa6cc5965111cf4d025d2d7508877c3cbba9fe8c706f66323dd387f06d620625",
+}
+_V091_MANIFEST = {
+ "schema_version": 1,
+ "component": "audio.cpp",
+ "source_repo": "unslothai/audio.cpp",
+ "source_commit": _V091_COMMIT,
+ "upstream_repo": "0xShug0/audio.cpp",
+ "upstream_tag": "v0.9.1",
+ "packaging_tag": _V091,
+ "studio_protocol": {"version": 1, "probe_argv": ["--help", "--version"]},
+ "artifacts": [
+ {
+ "asset": _V091_LINUX_CPU,
+ "kind": "bundle",
+ "os": "ubuntu",
+ "arch": "x64",
+ "accel": "cpu-portable",
+ "backend": "cpu",
+ "min_os": "glibc-2.35",
+ "espeak": True,
+ "sha256": _V091_SHA[_V091_LINUX_CPU],
+ },
+ {
+ "asset": _V091_WIN_CUDA,
+ "kind": "bundle",
+ "os": "windows",
+ "arch": "x64",
+ "accel": "cuda12",
+ "backend": "cuda",
+ "runtime_line": "cuda12",
+ "cuda_runtime_bundled": False,
+ "min_os": "windows-10",
+ "espeak": True,
+ "sha256": _V091_SHA[_V091_WIN_CUDA],
+ },
+ {
+ "asset": _V091_CUDART,
+ "kind": "cuda-runtime",
+ "os": "windows",
+ "arch": "x64",
+ "accel": "cuda12",
+ "backend": "cuda",
+ "runtime_line": "cuda12",
+ "sha256": _V091_SHA[_V091_CUDART],
+ },
+ ],
+}
+_V091_INDEX = {
+ "schema_version": 1,
+ "component": "audio.cpp",
+ "source_repo": "unslothai/audio.cpp",
+ "source_commit": _V091_COMMIT,
+ "upstream_tag": "v0.9.1",
+ "release_tag": _V091,
+ "artifacts": {
+ name: {
+ "kind": "bundle",
+ "repo": "unslothai/audio.cpp",
+ "sha256": digest,
+ "source_commit": _V091_COMMIT,
+ "upstream_tag": "v0.9.1",
+ }
+ for name, digest in _V091_SHA.items()
+ },
+}
+
+
+def _cdn(name, tag = _V091):
+ return f"https://github.com/{FORK}/releases/download/{tag}/{name}"
+
+
+def _download_host(
+ monkeypatch,
+ *,
+ index = None,
+ manifest = None,
+ latest = _V091,
+):
+ """Serve the fork release from the download host; every api.github.com fetch fails (offline)."""
+ import copy
+
+ files = {
+ _cdn(M.SHA256_ASSET_NAME): copy.deepcopy(index or _V091_INDEX),
+ _cdn(M.MANIFEST_ASSET_NAME): copy.deepcopy(manifest or _V091_MANIFEST),
+ }
+ requests = []
+
+ def head(repo):
+ requests.append(("HEAD", f"https://github.com/{repo}/releases/latest"))
+ return latest
+
+ def get_json(url):
+ requests.append(("GET", url))
+ if url not in files:
+ raise M.urllib.error.HTTPError(url, 404, "Not Found", {}, None)
+ return files[url]
+
+ def fetch_json(url):
+ requests.append(("API", url))
+ raise M.urllib.error.URLError("api.github.com unreachable in this test")
+
+ monkeypatch.setattr(M, "_latest_tag_via_download_host", LATEST_TAG)
+ monkeypatch.setattr(M, "_download_host_latest_release_tag", head, raising = False)
+ monkeypatch.setattr(M, "_download_host_json", get_json, raising = False)
+ monkeypatch.setattr(M, "fetch_json", fetch_json, raising = False)
+ return requests
+
+
+def test_the_newest_fork_release_resolves_through_its_own_sha256_index(monkeypatch, capsys):
+ requests = _download_host(monkeypatch)
+ release = M._release_index(FORK, M._latest_tag_via_download_host(FORK))
+ assert release["tag_name"] == _V091
+ assert [a["name"] for a in release["assets"]] == [_V091_LINUX_CPU, _V091_WIN_CUDA, _V091_CUDART]
+ assets = {a["name"]: a for a in release["assets"]}
+ assert assets[_V091_LINUX_CPU]["browser_download_url"] == _cdn(_V091_LINUX_CPU)
+ assert assets[_V091_LINUX_CPU]["min_os"] == "glibc-2.35"
+ for name in (_V091_LINUX_CPU, _V091_WIN_CUDA, _V091_CUDART):
+ assert M._expected_sha256(release, assets[name]) == _V091_SHA[name]
+ # The index first, then the manifest, from the download host: no API call.
+ assert requests == [
+ ("HEAD", f"https://github.com/{FORK}/releases/latest"),
+ ("GET", _cdn(M.SHA256_ASSET_NAME)),
+ ("GET", _cdn(M.MANIFEST_ASSET_NAME)),
+ ]
+ assert f"resolved {FORK}@{_V091} via the download host" in capsys.readouterr().err
+ # Memoized per (repo, tag): the CPU-fallback re-resolve fetches nothing again.
+ assert M._release_index(FORK, _V091) is release
+ assert len(requests) == 3
+
+
+def test_the_default_install_lookup_asks_only_the_fork(monkeypatch, capsys):
+ requests = _download_host(monkeypatch)
+ monkeypatch.setattr(M.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(M.platform, "machine", lambda: "x86_64")
+ assert M.main(["--print-asset", "--accelerator", "cpu"]) == M.EXIT_OK
+ assert capsys.readouterr().out.strip() == f"{FORK} {_V091} {_V091_LINUX_CPU}"
+ assert [kind for kind, _ in requests] == ["HEAD", "GET", "GET"]
+ assert all(f"github.com/{FORK}/" in url for _, url in requests)
+ assert not any("0xShug0" in url for _, url in requests)
+
+
+def test_an_index_bound_to_another_release_is_rejected(monkeypatch):
+ import copy
+
+ index = copy.deepcopy(_V091_INDEX)
+ index["release_tag"] = OLDER_TAG
+ requests = _download_host(monkeypatch, index = index)
+ with pytest.raises(M.ReleaseLookupUnavailable):
+ M.resolve("cpu", None)
+ # The download host refused it; the API fallback (offline here) was asked for the same tag.
+ assert requests[-1] == ("API", f"https://api.github.com/repos/{FORK}/releases/tags/{_V091}")
+ assert ("GET", _cdn(M.MANIFEST_ASSET_NAME)) not in requests
+
+
+def test_a_manifest_digest_the_index_contradicts_is_refused_through_the_core(monkeypatch):
+ import copy
+
+ manifest = copy.deepcopy(_V091_MANIFEST)
+ manifest["artifacts"][2]["sha256"] = "1" * 64
+ _download_host(monkeypatch, manifest = manifest)
+ release = M._release_index(FORK, _V091)
+ cudart = {a["name"]: a for a in release["assets"]}[_V091_CUDART]
+ with pytest.raises(M.core.ReleaseIntegrityError, match = "possibly tampered"):
+ M._expected_sha256(release, cudart)
+
+
+def test_latest_tag_lookup_is_memoized_and_never_raises(monkeypatch):
+ calls = _real_head(monkeypatch, M.urllib.error.URLError("offline"))
+ assert M._latest_tag_via_download_host(FORK) is None
+ assert M._latest_tag_via_download_host(FORK) is None
+ assert calls == [FORK]
+ calls = _real_head(monkeypatch, FORK_TAG)
+ monkeypatch.setattr(M, "_LATEST_TAG_MEMO", {})
+ assert M._latest_tag_via_download_host(FORK) == FORK_TAG
+ assert M._latest_tag_via_download_host(FORK) == FORK_TAG
+ assert calls == [FORK]
# G3(b): the staged server must start before it replaces anything
@@ -780,15 +1438,14 @@ class _Ran:
self.returncode, self.stdout, self.stderr = returncode, stdout, stderr
-def test_a_staged_server_that_cannot_start_keeps_the_old_tree(monkeypatch, tmp_path, pins, capsys):
+def test_a_staged_server_that_cannot_start_keeps_the_old_tree(monkeypatch, tmp_path, capsys):
good = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, good, pins)
+ _install(monkeypatch, tmp_path, good)
root = tmp_path / "audio.cpp"
before = _tree_digest(root)
newer = _release(tmp_path, f"audio-{FORK_TAG}-bin-windows-x64-cpu.zip")
- _pin_release(pins, newer)
monkeypatch.setattr(
- M, "resolve", lambda accel, token: (FORK, newer, newer["assets"][0]["name"])
+ M, "resolve", lambda accel, token, tag = None: (FORK, newer, newer["assets"][0]["name"])
)
monkeypatch.setattr(M, "smoke_test_staged_server", SMOKE)
loader_error = (
@@ -834,7 +1491,7 @@ def test_staged_server_check_puts_the_bundle_dir_first_and_records_the_version(
def test_a_cuda_bundle_is_checked_with_the_wheel_cuda_runtime_on_the_loader_path(
- monkeypatch, tmp_path, pins
+ monkeypatch, tmp_path
):
# The Linux CUDA server links libcublas/libcudart/libcufft/libnccl dynamically: without torch's
# nvidia-* wheel dirs the check would refuse every CUDA install.
@@ -956,30 +1613,29 @@ def test_release_lookups_are_retried(monkeypatch):
# Carried over from the first installer
-def test_refuses_to_replace_a_directory_it_does_not_own(monkeypatch, tmp_path, pins):
+def test_refuses_to_replace_a_directory_it_does_not_own(monkeypatch, tmp_path):
foreign = tmp_path / "audio.cpp"
foreign.mkdir()
(foreign / "mine.txt").write_text("user data")
release = _release(tmp_path, CPU_ZIP)
with pytest.raises(RuntimeError, match = "not an Unsloth-managed directory"):
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
assert (foreign / "mine.txt").read_text() == "user data"
-def test_bundle_without_a_server_leaves_the_old_tree(monkeypatch, tmp_path, pins):
+def test_bundle_without_a_server_leaves_the_old_tree(monkeypatch, tmp_path):
good = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, good, pins)
+ _install(monkeypatch, tmp_path, good)
bad = _release(
tmp_path, f"audio-{FORK_TAG}-bin-windows-x64-cpu.zip", server_path = "bin/other.exe"
)
with pytest.raises(RuntimeError, match = "contains no"):
- _install(monkeypatch, tmp_path, bad, pins, force = True)
+ _install(monkeypatch, tmp_path, bad, force = True)
assert (tmp_path / "audio.cpp" / "bin" / M.SERVER_NAME).is_file()
-def test_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(monkeypatch, tmp_path, pins):
+def test_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
- _pin_release(pins, release)
asked, resolve = _resolve_recording(release)
_stub_install_io(monkeypatch)
monkeypatch.setattr(M, "resolve", resolve)
@@ -990,7 +1646,7 @@ def test_auto_detected_gpu_without_a_bundle_installs_the_cpu_build(monkeypatch,
def test_an_explicit_gpu_request_is_never_downgraded(monkeypatch, tmp_path):
- monkeypatch.setattr(M, "resolve", lambda accel, token: (FORK, None, None))
+ monkeypatch.setattr(M, "resolve", lambda accel, token, tag = None: (FORK, None, None))
with pytest.raises(RuntimeError, match = "No prebuilt"):
M.install(install_dir = tmp_path / "audio.cpp", accelerator = "cuda")
@@ -1000,9 +1656,9 @@ def test_intel_mac_bundle_runs_on_the_cpu_backend():
assert M._backend_of(f"audio-{TAG}-bin-macos-arm64-metal.tar.gz") == "metal"
-def test_record_notes_a_static_espeak_build(monkeypatch, tmp_path, pins):
+def test_record_notes_a_static_espeak_build(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP, extra = [("bin/espeak-ng-data.bin", b"data")])
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
assert json.loads((tmp_path / "audio.cpp" / M.INSTALL_RECORD).read_text())["espeak"] is True
target = tmp_path / "audio.cpp"
record = json.loads((target / M.INSTALL_RECORD).read_text())
@@ -1012,29 +1668,29 @@ def test_record_notes_a_static_espeak_build(monkeypatch, tmp_path, pins):
assert M._intact_install(target, record) is None
-def test_a_dir_holding_only_the_old_child_home_is_adopted(monkeypatch, tmp_path, pins):
+def test_a_dir_holding_only_the_old_child_home_is_adopted(monkeypatch, tmp_path):
leftover = tmp_path / "audio.cpp" / ".child_home" / "AppData"
leftover.mkdir(parents = True)
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
assert (tmp_path / "audio.cpp" / M.OWNERSHIP_MARKER).is_file()
assert not (tmp_path / "audio.cpp" / ".child_home").exists()
-def test_retired_trees_are_swept_on_the_next_run(monkeypatch, tmp_path, pins):
+def test_retired_trees_are_swept_on_the_next_run(monkeypatch, tmp_path):
stale = tmp_path / "audio.cpp.old-1234"
stale.mkdir()
(stale / M.OWNERSHIP_MARKER).touch()
foreign = tmp_path / "audio.cpp.old-user"
foreign.mkdir()
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
assert not stale.exists() and foreign.exists()
-def test_a_running_server_reports_busy_before_downloading(monkeypatch, tmp_path, pins):
+def test_a_running_server_reports_busy_before_downloading(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
monkeypatch.setattr(M, "_server_in_use", lambda server: True)
downloaded = []
monkeypatch.setattr(M, "_download", lambda *a, **k: downloaded.append(a))
@@ -1075,34 +1731,45 @@ def test_tar_extraction_without_filters_still_refuses_traversal(monkeypatch, tmp
assert not (tmp_path / "escape.txt").exists()
-def test_an_upstream_fallback_install_asks_for_the_fork_again(monkeypatch, tmp_path, pins):
- # The fork lookup failed on the run that installed upstream; the next run must not call that a match.
- up_zip = f"audio-{M.UPSTREAM_FALLBACK_TAG}-bin-windows-x64-cpu-portable.zip"
- release = _release(tmp_path, up_zip, tag = M.UPSTREAM_FALLBACK_TAG)
- _install(monkeypatch, tmp_path, release, pins, repo = M.UPSTREAM_FALLBACK_REPO)
+def test_an_upstream_record_is_replaced_by_the_forks_newest(monkeypatch, tmp_path):
+ # A 0xShug0 install (the old fallback rung, or a UNSLOTH_AUDIO_CPP_REPO pick) is not this repo's release.
+ up_zip = "audio-v0.9.0-bin-windows-x64-cpu-portable.zip"
+ _install(
+ monkeypatch,
+ tmp_path,
+ _release(tmp_path / "up", up_zip, tag = "v0.9.0"),
+ repo = "0xShug0/audio.cpp",
+ )
root = tmp_path / "audio.cpp"
record = M.read_install_record(root)
- assert record["published_repo"] == M.UPSTREAM_FALLBACK_REPO
- assert M._pinned_install_matches(root, record, "cpu", None) is None
+ assert record["published_repo"] == "0xShug0/audio.cpp"
+ assert M._current_install_matches(root, record, "cpu", None, "v0.9.0") is None
+ assert M._current_install_matches(root, record, "cpu", None, "v0.9.0", pinned = True) is None
+ _install(monkeypatch, tmp_path, _release(tmp_path, CPU_ZIP))
+ record = M.read_install_record(root)
+ assert (record["published_repo"], record["release_tag"], record["asset"]) == (
+ FORK,
+ FORK_TAG,
+ CPU_ZIP,
+ )
-def test_the_accelerator_flag_takes_what_setup_forwards(monkeypatch, tmp_path, pins):
+def test_the_accelerator_flag_takes_what_setup_forwards(monkeypatch, tmp_path):
release = _release(tmp_path, CPU_ZIP)
asked, resolve = _resolve_recording(release, covers = ("cpu", "cuda"))
_stub_install_io(monkeypatch)
monkeypatch.setattr(M, "resolve", resolve)
- _pin_release(pins, release)
root = str(tmp_path / "audio.cpp")
assert M.main(["--install-dir", root, "--accelerator", " CUDA "]) == M.EXIT_OK
assert asked == ["cuda"]
-def test_a_killed_install_leaves_no_staging_dir_behind(monkeypatch, tmp_path, pins):
+def test_a_killed_install_leaves_no_staging_dir_behind(monkeypatch, tmp_path):
stranded = tmp_path / ".audio.cpp-staging-killed"
stranded.mkdir()
(stranded / "partial.zip").write_bytes(b"x" * 16)
release = _release(tmp_path, CPU_ZIP)
- _install(monkeypatch, tmp_path, release, pins)
+ _install(monkeypatch, tmp_path, release)
assert not stranded.exists()
@@ -1296,14 +1963,16 @@ def test_the_vulkan_check_needs_a_listed_vulkan_gpu(monkeypatch, tmp_path, liste
VK_ZIP = f"audio-{FORK_TAG}-bin-windows-x64-vulkan.zip"
-def _vulkan_host(monkeypatch, tmp_path, pins, *, device):
+def _vulkan_host(monkeypatch, tmp_path, *, device):
cpu = _release(tmp_path / "cpu", CPU_ZIP)
vk = _release(tmp_path / "vk", VK_ZIP)
- _pin_release(pins, cpu)
- _pin_release(pins, vk)
asked = []
- def resolve(accel, token):
+ def resolve(
+ accel,
+ token,
+ tag = None,
+ ):
asked.append(accel)
rel = vk if accel == "vulkan" else cpu
return FORK, rel, rel["assets"][0]["name"]
@@ -1334,30 +2003,32 @@ def _record(tmp_path):
return rec["asset"], rec["backend"], rec["accelerator_request"], rec["detected_accelerator"]
-def test_auto_on_an_amd_gpu_installs_the_vulkan_bundle(monkeypatch, tmp_path, pins):
- asked, checked = _vulkan_host(monkeypatch, tmp_path, pins, device = True)
+def test_auto_on_an_amd_gpu_installs_the_vulkan_bundle(monkeypatch, tmp_path):
+ asked, checked = _vulkan_host(monkeypatch, tmp_path, device = True)
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
assert asked == ["vulkan"] and checked == [("vulkan", True)]
assert _record(tmp_path) == (VK_ZIP, "vulkan", "auto", "vulkan")
def test_auto_vulkan_without_a_vulkan_gpu_installs_the_cpu_build_once(
- monkeypatch, tmp_path, pins, capsys
+ monkeypatch, tmp_path, capsys
):
- asked, checked = _vulkan_host(monkeypatch, tmp_path, pins, device = False)
+ asked, checked = _vulkan_host(monkeypatch, tmp_path, device = False)
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
assert asked == ["vulkan", "cpu"]
assert checked == [("vulkan", True), ("cpu", False)]
assert "finds no Vulkan GPU on this host; installing the CPU build" in capsys.readouterr().out
assert _record(tmp_path) == (CPU_ZIP, "cpu", "auto", "vulkan")
# The record names the detected Vulkan host, so the next setup run is a no-op.
- monkeypatch.setattr(M, "resolve", lambda *a: pytest.fail("a matching rerun must not look up"))
+ monkeypatch.setattr(
+ M, "resolve", lambda *a, **k: pytest.fail("a matching rerun must not look up")
+ )
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
-def test_an_existing_cpu_install_on_an_amd_gpu_moves_to_vulkan(monkeypatch, tmp_path, pins):
+def test_an_existing_cpu_install_on_an_amd_gpu_moves_to_vulkan(monkeypatch, tmp_path):
# What every AMD host has before #13042: auto, detected "cpu", the CPU bundle.
- asked, _ = _vulkan_host(monkeypatch, tmp_path, pins, device = True)
+ asked, _ = _vulkan_host(monkeypatch, tmp_path, device = True)
monkeypatch.setattr(M, "detect_accelerator", lambda: "cpu")
assert M.main(["--install-dir", str(tmp_path / "audio.cpp")]) == M.EXIT_OK
assert _record(tmp_path) == (CPU_ZIP, "cpu", "auto", "cpu")
@@ -1366,9 +2037,9 @@ def test_an_existing_cpu_install_on_an_amd_gpu_moves_to_vulkan(monkeypatch, tmp_
assert _record(tmp_path) == (VK_ZIP, "vulkan", "auto", "vulkan")
-def test_explicit_vulkan_is_not_checked_for_a_device(monkeypatch, tmp_path, pins):
+def test_explicit_vulkan_is_not_checked_for_a_device(monkeypatch, tmp_path):
# A Docker build sees no GPU; an explicit request installs what it names.
- asked, checked = _vulkan_host(monkeypatch, tmp_path, pins, device = False)
+ asked, checked = _vulkan_host(monkeypatch, tmp_path, device = False)
assert (
M.main(["--install-dir", str(tmp_path / "audio.cpp"), "--accelerator", "vulkan"])
== M.EXIT_OK