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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
import errno
import importlib.util
import io
import dataclasses
import json
import os
import shutil
import stat
import subprocess
import sys
import types
import tarfile
import urllib.error
import zipfile
from pathlib import Path
import pytest
from unsloth_pwsh_runner import run_pwsh
PACKAGE_ROOT = Path(__file__).resolve().parents[3]
MODULE_PATH = PACKAGE_ROOT / "studio" / "install_llama_prebuilt.py"
SPEC = importlib.util.spec_from_file_location("studio_install_llama_prebuilt", MODULE_PATH)
assert SPEC is not None and SPEC.loader is not None
INSTALL_LLAMA_PREBUILT = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = INSTALL_LLAMA_PREBUILT
SPEC.loader.exec_module(INSTALL_LLAMA_PREBUILT)
PrebuiltFallback = INSTALL_LLAMA_PREBUILT.PrebuiltFallback
BusyInstallConflict = INSTALL_LLAMA_PREBUILT.BusyInstallConflict
binary_env = INSTALL_LLAMA_PREBUILT.binary_env
is_secret_env_name = INSTALL_LLAMA_PREBUILT.is_secret_env_name
scrub_env = INSTALL_LLAMA_PREBUILT.scrub_env
isolated_runtime_home = INSTALL_LLAMA_PREBUILT.isolated_runtime_home
HostInfo = INSTALL_LLAMA_PREBUILT.HostInfo
AssetChoice = INSTALL_LLAMA_PREBUILT.AssetChoice
ApprovedArtifactHash = INSTALL_LLAMA_PREBUILT.ApprovedArtifactHash
ApprovedReleaseChecksums = INSTALL_LLAMA_PREBUILT.ApprovedReleaseChecksums
hydrate_source_tree = INSTALL_LLAMA_PREBUILT.hydrate_source_tree
remove_agent_instruction_files = INSTALL_LLAMA_PREBUILT.remove_agent_instruction_files
validate_prebuilt_choice = INSTALL_LLAMA_PREBUILT.validate_prebuilt_choice
activate_install_tree = INSTALL_LLAMA_PREBUILT.activate_install_tree
activate_staged_dir = INSTALL_LLAMA_PREBUILT.activate_staged_dir
create_install_staging_dir = INSTALL_LLAMA_PREBUILT.create_install_staging_dir
replace_with_busy_retry = INSTALL_LLAMA_PREBUILT.replace_with_busy_retry
blocked_replace_hint = INSTALL_LLAMA_PREBUILT.blocked_replace_hint
remove_tree_logged = INSTALL_LLAMA_PREBUILT.remove_tree_logged
prune_stale_install_side_paths = INSTALL_LLAMA_PREBUILT.prune_stale_install_side_paths
sha256_file = INSTALL_LLAMA_PREBUILT.sha256_file
source_archive_logical_name = INSTALL_LLAMA_PREBUILT.source_archive_logical_name
install_prebuilt = INSTALL_LLAMA_PREBUILT.install_prebuilt
write_prebuilt_metadata = INSTALL_LLAMA_PREBUILT.write_prebuilt_metadata
existing_install_matches_plan = INSTALL_LLAMA_PREBUILT.existing_install_matches_plan
existing_install_matches_choice = INSTALL_LLAMA_PREBUILT.existing_install_matches_choice
ensure_diffusion_visual_server = INSTALL_LLAMA_PREBUILT.ensure_diffusion_visual_server
runtime_payload_health_groups = INSTALL_LLAMA_PREBUILT.runtime_payload_health_groups
def write_metadata(
install_dir,
choice,
approved_checksums,
*,
requested_tag = "latest",
llama_tag = "b9001",
release_tag = "release-1",
prebuilt_fallback_used = False,
):
write_prebuilt_metadata(
install_dir,
requested_tag = requested_tag,
llama_tag = llama_tag,
release_tag = release_tag,
choice = choice,
approved_checksums = approved_checksums,
prebuilt_fallback_used = prebuilt_fallback_used,
)
def release_plan(
attempts,
approved_checksums,
*,
requested_tag = "latest",
llama_tag = "b9001",
release_tag = "release-1",
):
return INSTALL_LLAMA_PREBUILT.InstallReleasePlan(
requested_tag = requested_tag,
llama_tag = llama_tag,
release_tag = release_tag,
attempts = attempts,
approved_checksums = approved_checksums,
)
def asset_choice(**overrides) -> AssetChoice:
"""The b9001 linux-cpu upstream asset; `overrides` swaps any field. A `name`
override re-derives `url` as https://example.com/<name>, so pass `url` explicitly
only when it must differ."""
name = overrides.pop("name", "llama-b9001-bin-ubuntu-x64.tar.gz")
defaults = dict(
repo = "unslothai/llama.cpp",
tag = "release-1",
name = name,
url = f"https://example.com/{name}",
source_label = "upstream",
install_kind = "linux-cpu",
expected_sha256 = "a" * 64,
)
defaults.update(overrides)
return AssetChoice(**defaults)
UPSTREAM = ("ggml-org/llama.cpp", "upstream-prebuilt")
PREBUILT = ("unslothai/llama.cpp", "prebuilt")
_SOURCE = ("ggml-org/llama.cpp", "upstream-source")
def _artifact_hash(asset_name: str, sha256: str, origin: tuple[str, str]) -> ApprovedArtifactHash:
repo, kind = origin
return ApprovedArtifactHash(asset_name = asset_name, sha256 = sha256, repo = repo, kind = kind)
def release_checksums(
*assets: tuple[str, str, tuple[str, str]],
release_tag: str = "release-1",
upstream_tag: str = "b9001",
source_commit: str | None = "deadbeef",
source_sha256: str = "b" * 64,
) -> ApprovedReleaseChecksums:
"""Approved checksums for one unslothai/llama.cpp release: the upstream source
archive plus one entry per (asset_name, sha256, origin). source_commit = None
means "no source archive approved" and drops that entry."""
artifacts = {}
if source_commit is not None:
logical = source_archive_logical_name(upstream_tag)
artifacts[logical] = _artifact_hash(logical, source_sha256, _SOURCE)
for asset_name, sha256, origin in assets:
artifacts[asset_name] = _artifact_hash(asset_name, sha256, origin)
return ApprovedReleaseChecksums(
repo = "unslothai/llama.cpp",
release_tag = release_tag,
upstream_tag = upstream_tag,
source_commit = source_commit,
artifacts = artifacts,
)
def _host(platform: dict, **overrides) -> HostInfo:
base = dict(
nvidia_smi = None,
driver_cuda_version = None,
compute_caps = [],
visible_cuda_devices = None,
has_physical_nvidia = False,
has_usable_nvidia = False,
)
return HostInfo(**{**platform, **base, **overrides})
def linux_host(**overrides) -> HostInfo:
platform = dict(
system = "Linux",
machine = "x86_64",
is_windows = False,
is_linux = True,
is_macos = False,
is_x86_64 = True,
is_arm64 = False,
)
return _host(platform, **overrides)
def windows_host(**overrides) -> HostInfo:
platform = dict(
system = "Windows",
machine = "AMD64",
is_windows = True,
is_linux = False,
is_macos = False,
is_x86_64 = True,
is_arm64 = False,
)
return _host(platform, **overrides)
def macos_host(**overrides) -> HostInfo:
platform = dict(
system = "Darwin",
machine = "arm64",
is_windows = False,
is_linux = False,
is_macos = True,
is_x86_64 = False,
is_arm64 = True,
)
return _host(platform, **overrides)
def approved_release_checksums_for_asset(asset_name: str, sha256: str) -> ApprovedReleaseChecksums:
return ApprovedReleaseChecksums(
repo = "unslothai/llama.cpp",
release_tag = "b9334",
upstream_tag = "b9334",
artifacts = {
asset_name: ApprovedArtifactHash(
asset_name = asset_name,
sha256 = sha256,
repo = "unslothai/llama.cpp",
kind = "diffusion-visual-server",
)
},
)
def approved_checksums_for(
upstream_tag: str, *, source_archive: Path, bundle_archive: Path, bundle_name: str
) -> ApprovedReleaseChecksums:
return ApprovedReleaseChecksums(
repo = "local",
release_tag = upstream_tag,
upstream_tag = upstream_tag,
source_commit = None,
artifacts = {
source_archive_logical_name(upstream_tag): ApprovedArtifactHash(
asset_name = source_archive_logical_name(upstream_tag),
sha256 = sha256_file(source_archive),
repo = "ggml-org/llama.cpp",
kind = "upstream-source",
),
bundle_name: ApprovedArtifactHash(
asset_name = bundle_name,
sha256 = sha256_file(bundle_archive),
repo = "local",
kind = "local-test-bundle",
),
},
)
def test_remove_agent_instruction_files_does_not_follow_links(tmp_path: Path):
managed = tmp_path / "managed"
nested = managed / "nested"
external = tmp_path / "external"
nested.mkdir(parents = True)
external.mkdir()
(managed / "AGENTS.md").write_text("managed root", encoding = "utf-8")
(nested / "AGENTS.md").write_text("managed nested", encoding = "utf-8")
(managed / "CLAUDE.md").write_text("managed Claude root", encoding = "utf-8")
(nested / "CLAUDE.md").write_text("managed Claude nested", encoding = "utf-8")
(external / "AGENTS.md").write_text("user owned", encoding = "utf-8")
(external / "CLAUDE.md").write_text("user-owned Claude", encoding = "utf-8")
try:
(managed / "external-link").symlink_to(external, target_is_directory = True)
linked_root = tmp_path / "linked-root"
linked_root.symlink_to(external, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
assert remove_agent_instruction_files(managed) == 4
assert not list(managed.rglob("AGENTS.md"))
assert not list(managed.rglob("CLAUDE.md"))
assert (external / "AGENTS.md").read_text(encoding = "utf-8") == "user owned"
assert (external / "CLAUDE.md").read_text(encoding = "utf-8") == "user-owned Claude"
assert remove_agent_instruction_files(linked_root) == 0
assert (external / "AGENTS.md").exists()
assert (external / "CLAUDE.md").exists()
@pytest.mark.skipif(os.name != "nt", reason = "Windows junction behavior")
def test_remove_agent_instruction_files_does_not_follow_windows_junctions(tmp_path: Path):
managed = tmp_path / "managed"
external = tmp_path / "external"
managed.mkdir()
external.mkdir()
(external / "AGENTS.md").write_text("user owned", encoding = "utf-8")
(external / "CLAUDE.md").write_text("user-owned Claude", encoding = "utf-8")
nested_junction = managed / "external-junction"
root_junction = tmp_path / "linked-root"
for junction in (nested_junction, root_junction):
result = subprocess.run(
["cmd", "/d", "/c", "mklink", "/J", str(junction), str(external)],
capture_output = True,
text = True,
check = False,
)
if result.returncode != 0:
pytest.skip(f"directory junctions unavailable: {result.stderr or result.stdout}")
assert remove_agent_instruction_files(managed) == 0
assert remove_agent_instruction_files(root_junction) == 0
assert (external / "AGENTS.md").read_text(encoding = "utf-8") == "user owned"
assert (external / "CLAUDE.md").read_text(encoding = "utf-8") == "user-owned Claude"
def test_remove_agent_instruction_files_prunes_linklike_directories(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
managed = tmp_path / "managed"
simulated_junction = managed / "simulated-junction"
simulated_junction.mkdir(parents = True)
agents = simulated_junction / "AGENTS.md"
claude = simulated_junction / "CLAUDE.md"
agents.write_text("external instructions", encoding = "utf-8")
claude.write_text("external Claude instructions", encoding = "utf-8")
real_is_link_or_junction = INSTALL_LLAMA_PREBUILT._is_link_or_junction
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_is_link_or_junction",
lambda path: path == simulated_junction or real_is_link_or_junction(path),
)
assert remove_agent_instruction_files(managed) == 0
assert agents.exists()
assert claude.exists()
def test_remove_agent_instruction_files_continues_after_unlink_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
managed = tmp_path / "managed"
managed.mkdir()
blocked = managed / "AGENTS.md"
removable = managed / "CLAUDE.md"
blocked.write_text("blocked", encoding = "utf-8")
removable.write_text("remove me", encoding = "utf-8")
real_unlink = Path.unlink
def selective_unlink(path: Path, *args, **kwargs):
if path == blocked:
raise PermissionError(errno.EACCES, "Access is denied", str(path))
return real_unlink(path, *args, **kwargs)
monkeypatch.setattr(Path, "unlink", selective_unlink)
assert remove_agent_instruction_files(managed) == 1
assert blocked.exists()
assert not removable.exists()
captured = capsys.readouterr()
assert "could not remove contributor-only instruction" in captured.out + captured.err
def test_main_resolves_linked_install_path_and_preserves_cleanup_root(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
target = tmp_path / "target"
linked_root = tmp_path / "linked-root"
target.mkdir()
try:
linked_root.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
received = {}
monkeypatch.setattr(
sys,
"argv",
["install_llama_prebuilt.py", "--install-dir", str(linked_root)],
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"install_prebuilt",
lambda **kwargs: received.update(kwargs),
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_LOG_TO_STDOUT", False)
assert INSTALL_LLAMA_PREBUILT.main() == 0
assert received["install_dir"] == target.resolve()
assert received["instruction_cleanup_root"] == linked_root.absolute()
assert received["instruction_cleanup_root"].is_symlink()
def test_install_prebuilt_uses_explicit_instruction_cleanup_root(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "target"
linked_root = tmp_path / "linked-root"
install_dir.mkdir()
(install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text("{}", encoding = "utf-8")
try:
linked_root.symlink_to(install_dir, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
cleanup_roots = []
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"remove_agent_instruction_files",
lambda root: cleanup_roots.append(root) or 0,
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("stop after cleanup")),
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
with pytest.raises(SystemExit) as caught:
install_prebuilt(
install_dir.resolve(),
"latest",
"unslothai/llama.cpp",
"",
instruction_cleanup_root = linked_root.absolute(),
)
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
assert "stop after cleanup" in str(caught.value.__cause__)
assert cleanup_roots == [linked_root.absolute()]
def test_hydrate_source_tree_extracts_upstream_archive_contents(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
upstream_tag = "b9999"
archive_path = tmp_path / "llama.cpp-source.tar.gz"
with tarfile.open(archive_path, "w:gz") as archive:
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/CMakeLists.txt",
b"cmake_minimum_required(VERSION 3.14)\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/convert_hf_to_gguf.py",
b"#!/usr/bin/env python3\nimport gguf\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/gguf-py/gguf/__init__.py",
b"__all__ = []\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/AGENTS.md",
b"upstream contributor instructions\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/examples/AGENTS.md",
b"nested contributor instructions\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/CLAUDE.md",
b"Claude contributor instructions\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/examples/CLAUDE.md",
b"nested Claude contributor instructions\n",
)
source_urls = set(INSTALL_LLAMA_PREBUILT.upstream_source_archive_urls(upstream_tag))
def fake_download_file(url: str, destination: Path) -> None:
assert url in source_urls
destination.write_bytes(archive_path.read_bytes())
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
install_dir = tmp_path / "install"
work_dir = tmp_path / "work"
work_dir.mkdir()
hydrate_source_tree(
upstream_tag, install_dir, work_dir, expected_sha256 = sha256_file(archive_path)
)
assert (install_dir / "CMakeLists.txt").exists()
assert (install_dir / "convert_hf_to_gguf.py").exists()
assert (install_dir / "gguf-py" / "gguf" / "__init__.py").exists()
assert not (install_dir / f"llama.cpp-{upstream_tag}").exists()
assert not list(install_dir.rglob("AGENTS.md"))
assert not list(install_dir.rglob("CLAUDE.md"))
def test_release_asset_download_url():
fn = INSTALL_LLAMA_PREBUILT.release_asset_download_url
assert fn(
"unslothai/llama.cpp", "b9000-mix-abc1234", "llama.cpp-source-commit-deadbeef.tar.gz"
) == (
"https://github.com/unslothai/llama.cpp/releases/download/"
"b9000-mix-abc1234/llama.cpp-source-commit-deadbeef.tar.gz"
)
assert fn(None, "b9000", "x.tar.gz") is None
assert fn("unslothai/llama.cpp", None, "x.tar.gz") is None
assert fn("unslothai/llama.cpp", "b9000", None) is None
def _mk_source_tarball(path: Path, tag: str) -> None:
with tarfile.open(path, "w:gz") as archive:
add_bytes_to_tar(
archive, f"llama.cpp-{tag}/CMakeLists.txt", b"cmake_minimum_required(VERSION 3.14)\n"
)
add_bytes_to_tar(
archive,
f"llama.cpp-{tag}/convert_hf_to_gguf.py",
b"#!/usr/bin/env python3\nimport gguf\n",
)
add_bytes_to_tar(archive, f"llama.cpp-{tag}/gguf-py/gguf/__init__.py", b"__all__ = []\n")
def test_hydrate_source_tree_prefers_release_asset_for_mix(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
commit = "a" * 40
archive_path = tmp_path / "merged-source.tar.gz"
_mk_source_tarball(archive_path, f"b9000-mix-{commit[:7]}")
asset_url = INSTALL_LLAMA_PREBUILT.release_asset_download_url(
"unslothai/llama.cpp", "b9000-mix-abc1234", f"llama.cpp-source-commit-{commit}.tar.gz"
)
codeload_urls = set(
INSTALL_LLAMA_PREBUILT.commit_source_archive_urls("unslothai/llama.cpp", commit)
)
seen = []
def fake_download_file(url: str, destination: Path) -> None:
seen.append(url)
if url in codeload_urls:
raise AssertionError("codeload was hit even though the release asset was available")
assert url == asset_url
destination.write_bytes(archive_path.read_bytes())
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
install_dir = tmp_path / "install"
work_dir = tmp_path / "work"
work_dir.mkdir()
hydrate_source_tree(
commit,
install_dir,
work_dir,
source_repo = "unslothai/llama.cpp",
expected_sha256 = sha256_file(archive_path),
exact_source = True,
asset_url = asset_url,
)
assert seen == [asset_url]
assert (install_dir / "CMakeLists.txt").exists()
assert (install_dir / "convert_hf_to_gguf.py").exists()
def test_hydrate_source_tree_falls_back_to_codeload_when_asset_missing(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
commit = "b" * 40
archive_path = tmp_path / "vanilla-source.tar.gz"
_mk_source_tarball(archive_path, f"commit-{commit[:7]}")
asset_url = INSTALL_LLAMA_PREBUILT.release_asset_download_url(
"unslothai/llama.cpp", "b9000", f"llama.cpp-source-commit-{commit}.tar.gz"
)
codeload_urls = INSTALL_LLAMA_PREBUILT.commit_source_archive_urls("unslothai/llama.cpp", commit)
def fake_download_file(url: str, destination: Path) -> None:
if url == asset_url:
raise RuntimeError("404 Not Found")
assert url in codeload_urls
destination.write_bytes(archive_path.read_bytes())
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
install_dir = tmp_path / "install"
work_dir = tmp_path / "work"
work_dir.mkdir()
hydrate_source_tree(
commit,
install_dir,
work_dir,
source_repo = "unslothai/llama.cpp",
expected_sha256 = sha256_file(archive_path),
exact_source = True,
asset_url = asset_url,
)
assert (install_dir / "CMakeLists.txt").exists()
def test_validate_prebuilt_choice_creates_repo_shaped_linux_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
upstream_tag = "b9998"
bundle_name = "app-b9998-linux-x64-cuda13-newer.tar.gz"
source_archive = tmp_path / "source.tar.gz"
bundle_archive = tmp_path / "bundle.tar.gz"
with tarfile.open(source_archive, "w:gz") as archive:
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/CMakeLists.txt",
b"cmake_minimum_required(VERSION 3.14)\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/convert_hf_to_gguf.py",
b"#!/usr/bin/env python3\nimport gguf\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/gguf-py/gguf/__init__.py",
b"__all__ = []\n",
)
with tarfile.open(bundle_archive, "w:gz") as archive:
add_bytes_to_tar(archive, "llama-server", b"#!/bin/sh\nexit 0\n", mode = 0o755)
add_bytes_to_tar(archive, "llama-quantize", b"#!/bin/sh\nexit 0\n", mode = 0o755)
add_bytes_to_tar(archive, "libllama.so.0.0.1", b"libllama")
add_symlink_to_tar(archive, "libllama.so.0", "libllama.so.0.0.1")
add_symlink_to_tar(archive, "libllama.so", "libllama.so.0")
add_bytes_to_tar(archive, "libggml.so.0.9.8", b"libggml")
add_symlink_to_tar(archive, "libggml.so.0", "libggml.so.0.9.8")
add_symlink_to_tar(archive, "libggml.so", "libggml.so.0")
add_bytes_to_tar(archive, "libggml-base.so.0.9.8", b"libggml-base")
add_symlink_to_tar(archive, "libggml-base.so.0", "libggml-base.so.0.9.8")
add_symlink_to_tar(archive, "libggml-base.so", "libggml-base.so.0")
add_bytes_to_tar(archive, "libggml-cpu-x64.so.0.9.8", b"libggml-cpu")
add_symlink_to_tar(archive, "libggml-cpu-x64.so.0", "libggml-cpu-x64.so.0.9.8")
add_symlink_to_tar(archive, "libggml-cpu-x64.so", "libggml-cpu-x64.so.0")
add_bytes_to_tar(archive, "libmtmd.so.0.0.1", b"libmtmd")
add_symlink_to_tar(archive, "libmtmd.so.0", "libmtmd.so.0.0.1")
add_symlink_to_tar(archive, "libmtmd.so", "libmtmd.so.0")
add_bytes_to_tar(archive, "BUILD_INFO.txt", b"bundle metadata\n")
add_bytes_to_tar(archive, "THIRD_PARTY_LICENSES.txt", b"licenses\n")
source_urls = set(INSTALL_LLAMA_PREBUILT.upstream_source_archive_urls(upstream_tag))
def fake_download_file(url: str, destination: Path) -> None:
if url in source_urls:
destination.write_bytes(source_archive.read_bytes())
return
if url == "file://bundle":
destination.write_bytes(bundle_archive.read_bytes())
return
raise AssertionError(f"unexpected download url: {url}")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_bytes",
lambda url, **_: b"#!/usr/bin/env python3\nimport gguf\n",
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"preflight_linux_installed_binaries",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "validate_quantize", lambda *args, **kwargs: None)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "validate_server", lambda *args, **kwargs: None)
host = linux_host()
choice = asset_choice(
name = bundle_name,
url = "file://bundle",
repo = "local",
tag = upstream_tag,
source_label = "local",
is_ready_bundle = True,
install_kind = "linux-cuda",
bundle_profile = "cuda13-newer",
runtime_line = "cuda13",
expected_sha256 = sha256_file(bundle_archive),
)
install_dir = tmp_path / "install"
work_dir = tmp_path / "work"
work_dir.mkdir()
probe_path = tmp_path / "stories260K.gguf"
quantized_path = tmp_path / "stories260K-q4.gguf"
validate_prebuilt_choice(
choice,
host,
install_dir,
work_dir,
probe_path,
requested_tag = upstream_tag,
llama_tag = upstream_tag,
release_tag = upstream_tag,
approved_checksums = approved_checksums_for(
upstream_tag,
source_archive = source_archive,
bundle_archive = bundle_archive,
bundle_name = bundle_name,
),
prebuilt_fallback_used = False,
quantized_path = quantized_path,
)
assert (install_dir / "gguf-py" / "gguf" / "__init__.py").exists()
assert (install_dir / "convert_hf_to_gguf.py").exists()
assert (install_dir / "build" / "bin" / "llama-server").exists()
assert (install_dir / "build" / "bin" / "llama-quantize").exists()
assert (install_dir / "build" / "bin" / "libllama.so").exists()
assert (install_dir / "llama-server").exists()
assert (install_dir / "llama-quantize").exists()
assert (install_dir / "UNSLOTH_PREBUILT_INFO.json").exists()
assert (install_dir / "BUILD_INFO.txt").exists()
def test_validate_prebuilt_choice_creates_repo_shaped_windows_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
upstream_tag = "b9997"
bundle_name = "app-b9997-windows-x64-cpu.zip"
source_archive = tmp_path / "source.tar.gz"
bundle_archive = tmp_path / "bundle.zip"
with tarfile.open(source_archive, "w:gz") as archive:
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/CMakeLists.txt",
b"cmake_minimum_required(VERSION 3.14)\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/convert_hf_to_gguf.py",
b"#!/usr/bin/env python3\nimport gguf\n",
)
add_bytes_to_tar(
archive,
f"llama.cpp-{upstream_tag}/gguf-py/gguf/__init__.py",
b"__all__ = []\n",
)
with zipfile.ZipFile(bundle_archive, "w") as archive:
archive.writestr("llama-server.exe", b"MZ")
archive.writestr("llama-quantize.exe", b"MZ")
archive.writestr("llama.dll", b"DLL")
archive.writestr("BUILD_INFO.txt", b"bundle metadata\n")
source_urls = set(INSTALL_LLAMA_PREBUILT.upstream_source_archive_urls(upstream_tag))
def fake_download_file(url: str, destination: Path) -> None:
if url in source_urls:
destination.write_bytes(source_archive.read_bytes())
return
if url == "file://bundle.zip":
destination.write_bytes(bundle_archive.read_bytes())
return
raise AssertionError(f"unexpected download url: {url}")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_bytes",
lambda url, **_: b"#!/usr/bin/env python3\nimport gguf\n",
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"preflight_linux_installed_binaries",
lambda *args, **kwargs: None,
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "validate_quantize", lambda *args, **kwargs: None)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "validate_server", lambda *args, **kwargs: None)
host = windows_host()
choice = asset_choice(
name = bundle_name,
url = "file://bundle.zip",
repo = "local",
tag = upstream_tag,
source_label = "local",
is_ready_bundle = True,
install_kind = "windows-cpu",
expected_sha256 = sha256_file(bundle_archive),
)
install_dir = tmp_path / "install"
work_dir = tmp_path / "work"
work_dir.mkdir()
probe_path = tmp_path / "stories260K.gguf"
quantized_path = tmp_path / "stories260K-q4.gguf"
validate_prebuilt_choice(
choice,
host,
install_dir,
work_dir,
probe_path,
requested_tag = upstream_tag,
llama_tag = upstream_tag,
release_tag = upstream_tag,
approved_checksums = approved_checksums_for(
upstream_tag,
source_archive = source_archive,
bundle_archive = bundle_archive,
bundle_name = bundle_name,
),
prebuilt_fallback_used = False,
quantized_path = quantized_path,
)
assert (install_dir / "gguf-py" / "gguf" / "__init__.py").exists()
assert (install_dir / "convert_hf_to_gguf.py").exists()
assert (install_dir / "build" / "bin" / "Release" / "llama-server.exe").exists()
assert (install_dir / "build" / "bin" / "Release" / "llama-quantize.exe").exists()
assert (install_dir / "build" / "bin" / "Release" / "llama.dll").exists()
assert not (install_dir / "llama-server.exe").exists()
assert (install_dir / "UNSLOTH_PREBUILT_INFO.json").exists()
assert (install_dir / "BUILD_INFO.txt").exists()
def test_activate_install_tree_restores_existing_install_after_activation_failure(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
host = linux_host()
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
with pytest.raises(
PrebuiltFallback,
match = "activation failed; restored previous install",
):
activate_install_tree(staging_dir, install_dir, host)
assert (install_dir / "old.txt").read_text() == "old install\n"
assert not (install_dir / "new.txt").exists()
assert not staging_dir.exists()
assert not (tmp_path / ".staging").exists()
captured = capsys.readouterr()
output = captured.out + captured.err
assert "moving existing install to rollback path" in output
assert "restored previous install from rollback path" in output
def test_activate_install_tree_preserves_symlink_to_resolved_target(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "target"
linked_root = tmp_path / "linked-root"
staging_dir = tmp_path / "staging"
install_dir.mkdir()
staging_dir.mkdir()
(install_dir / "old.txt").write_text("old", encoding = "utf-8")
(staging_dir / "new.txt").write_text("new", encoding = "utf-8")
try:
linked_root.symlink_to(install_dir, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)
activate_install_tree(staging_dir, linked_root.resolve(), linux_host())
assert linked_root.is_symlink()
assert (linked_root / "new.txt").read_text(encoding = "utf-8") == "new"
assert not (linked_root / "old.txt").exists()
def test_activate_install_tree_keeps_rollback_when_restore_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
host = linux_host()
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
src_path = Path(src)
dst_path = Path(dst)
if "rollback-" in src_path.name and dst_path == install_dir:
raise OSError("restore failed")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"copytree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
OSError(errno.ENOSPC, "No space left on device")
),
)
with pytest.raises(PrebuiltFallback, match = "previous install kept at") as excinfo:
activate_install_tree(staging_dir, install_dir, host)
assert "cleaned install state for fresh source build" in str(excinfo.value)
assert not install_dir.exists()
assert not staging_dir.exists()
rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
assert (rollbacks[0] / "old.txt").read_text() == "old install\n"
captured = capsys.readouterr()
output = captured.out + captured.err
assert "rollback after failed activation also failed: restore failed" in output
assert "previous install kept at rollback path" in output
assert "cleaning staging, install, and failed paths before source build fallback" in output
assert "removing failed install path" in output
assert "removing rollback path" not in output
def _fail_activation_then_restore_rename(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, copy_error: Exception
) -> tuple[Path, Path]:
"""Activation fails for a reason that is *not* disk-related, the restore rename
then fails, and the copy back that follows raises ``copy_error``."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError(errno.EACCES, "Access is denied")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"copytree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(copy_error),
)
return install_dir, staging_dir
@pytest.mark.parametrize(
"make_copy_error",
[
# Per-file copytree failures arrive as Error(list of strings); only the text carries errno.
lambda: OSError(errno.ENOSPC, "No space left on device"),
lambda: shutil.Error(
[("src", "dst", "[Errno 28] No space left on device: 'llama-server'")]
),
],
ids = ["oserror", "shutil_error"],
)
def test_activate_install_tree_reports_a_recovery_disk_full_as_out_of_space(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, make_copy_error
):
"""The copy back is the first step that needs free space, so a full disk shows up only there;
dropping it would start a source build needing far more room than the failed copy."""
install_dir, staging_dir = _fail_activation_then_restore_rename(
tmp_path, monkeypatch, make_copy_error()
)
with pytest.raises(PrebuiltFallback) as excinfo:
activate_install_tree(staging_dir, install_dir, linux_host())
assert INSTALL_LLAMA_PREBUILT._environment_fatal_reason(excinfo.value) == (
"no space left on device"
)
rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
assert (rollbacks[0] / "old.txt").read_text() == "old install\n"
def test_activate_install_tree_keeps_the_activation_error_as_the_cause_when_not_out_of_space(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Only a disk-full recovery failure replaces the cause: an ordinary one still
reports the activation error, so the caller keeps its source build fallback."""
install_dir, staging_dir = _fail_activation_then_restore_rename(
tmp_path, monkeypatch, OSError(errno.EACCES, "Permission denied")
)
with pytest.raises(PrebuiltFallback) as excinfo:
activate_install_tree(staging_dir, install_dir, linux_host())
assert isinstance(excinfo.value.__cause__, RuntimeError)
assert str(excinfo.value.__cause__) == "activation confirm failed"
assert INSTALL_LLAMA_PREBUILT._environment_fatal_reason(excinfo.value) is None
def test_activate_install_tree_copies_previous_install_back_when_restore_rename_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError(errno.EACCES, "Access is denied")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
with pytest.raises(PrebuiltFallback, match = "activation failed; restored previous install"):
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "old.txt").read_text() == "old install\n"
assert not (install_dir / "new.txt").exists()
assert not staging_dir.exists()
assert sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*")) == []
output = "".join(capsys.readouterr())
assert "copying the previous install back" in output
def test_activate_install_tree_does_not_follow_a_symlink_out_of_the_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
outside = tmp_path / "outside"
outside.mkdir()
(outside / "precious.txt").write_text("precious\n")
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
try:
(install_dir / "link-out").symlink_to(outside, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError(errno.EACCES, "Access is denied")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
with pytest.raises(PrebuiltFallback):
activate_install_tree(staging_dir, install_dir, linux_host())
# Every removal and the copy fallback must treat the link as a link; one
# dereference would wipe a directory outside the install.
assert (outside / "precious.txt").read_text() == "precious\n"
assert (install_dir / "link-out").is_symlink()
assert (install_dir / "old.txt").read_text() == "old install\n"
def test_replace_with_busy_retry_waits_out_a_transient_windows_lock(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "src"
source.mkdir()
(source / "payload.txt").write_text("payload\n")
destination = tmp_path / "dst"
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
attempts = {"count": 0}
def sharing_violation(src, dst):
attempts["count"] += 1
if attempts["count"] < 3:
exc = OSError(errno.EACCES, "The process cannot access the file")
exc.winerror = 32
raise exc
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "name", "nt")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", sharing_violation)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.time, "sleep", lambda _seconds: None)
replace_with_busy_retry(source, destination)
assert attempts["count"] == 3
assert (destination / "payload.txt").read_text() == "payload\n"
def test_blocked_replace_hint_names_the_cause_per_winerror():
assert "scanner" in blocked_replace_hint(32)
denied = blocked_replace_hint(5)
assert "access is denied" in denied and "ACL" in denied
not_empty = blocked_replace_hint(145)
assert "not empty" in not_empty and "scanner" not in not_empty
def _run_denied_replace(tmp_path, monkeypatch, failures):
source = tmp_path / "src"
source.mkdir()
(source / "payload.txt").write_text("payload\n")
destination = tmp_path / "dst"
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
attempts = {"count": 0}
def access_denied(src, dst):
attempts["count"] += 1
if attempts["count"] <= failures:
exc = OSError(errno.EACCES, "Access is denied")
exc.winerror = 5
raise exc
return original_replace(src, dst)
logged: list[str] = []
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "name", "nt")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", access_denied)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.time, "sleep", lambda _seconds: None)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "log", logged.append)
return source, destination, logged
def test_replace_with_busy_retry_prints_acl_repair_once_when_denial_persists(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
with pytest.raises(OSError):
replace_with_busy_retry(source, destination, attempts = 3)
retry_lines = [line for line in logged if "blocked (5)" in line]
assert len(retry_lines) == 2 and "scanner" not in retry_lines[0].split("--")[0]
assert all("takeown" not in line for line in retry_lines)
assert logged.count(f'takeown /F "{source}" /R /D Y') == 1
assert logged.count(f'icacls "{source}" /reset /T') == 1
assert not any(str(destination) in line for line in logged if "takeown" in line)
assert any("Controlled folder access" in line for line in logged)
def test_replace_with_busy_retry_offers_no_recursive_repair_for_a_linked_tree(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
target = tmp_path / "external"
target.mkdir()
link = tmp_path / "linked"
try:
link.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
_source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_is_link_or_junction", lambda p: p == link)
with pytest.raises(OSError):
replace_with_busy_retry(link, destination, attempts = 2)
assert not any("takeown" in line or "icacls" in line for line in logged)
assert any("contains a link" in line for line in logged)
def test_replace_with_busy_retry_offers_no_recursive_repair_over_a_nested_link(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
outside = tmp_path / "outside"
outside.mkdir()
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
try:
(source / "link-out").symlink_to(outside, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_is_link_or_junction", lambda p: p.is_symlink())
with pytest.raises(OSError):
replace_with_busy_retry(source, destination, attempts = 2)
assert not any("takeown" in line or "icacls" in line for line in logged)
def test_replace_with_busy_retry_offers_only_a_root_repair_for_an_unlistable_tree(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
def denied_walk(
top,
onerror = None,
**_kwargs,
):
onerror(PermissionError(errno.EACCES, "Access is denied", str(top)))
return iter(())
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_is_link_or_junction", lambda p: False)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "walk", denied_walk)
with pytest.raises(OSError):
replace_with_busy_retry(source, destination, attempts = 2)
assert f'takeown /F "{source}"' in logged
assert f'icacls "{source}" /reset /L' in logged
assert not any(
"/R" in line or "/T" in line for line in logged if "takeown" in line or "icacls" in line
)
def test_replace_with_busy_retry_offers_a_root_repair_when_the_root_cannot_be_read(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
real_lstat = type(source).lstat
def denied_lstat(self):
if self == source:
raise PermissionError(errno.EACCES, "Access is denied")
return real_lstat(self)
monkeypatch.setattr(type(source), "lstat", denied_lstat)
with pytest.raises(OSError):
replace_with_busy_retry(source, destination, attempts = 2)
assert f'takeown /F "{source}"' in logged
assert not any("contains a link" in line for line in logged)
def test_replace_with_busy_retry_can_withhold_the_acl_repair(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 99)
with pytest.raises(OSError):
replace_with_busy_retry(source, destination, attempts = 2, acl_repair = False)
assert not any("takeown" in line or "icacls" in line for line in logged)
def test_replace_with_busy_retry_skips_acl_repair_when_denial_clears(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source, destination, logged = _run_denied_replace(tmp_path, monkeypatch, failures = 1)
replace_with_busy_retry(source, destination)
assert (destination / "payload.txt").read_text() == "payload\n"
assert any("blocked (5)" in line for line in logged)
assert not any("takeown" in line for line in logged)
def test_replace_with_busy_retry_does_not_retry_a_posix_permission_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
attempts = {"count": 0}
def denied(src, dst):
attempts["count"] += 1
raise OSError(errno.EACCES, "Permission denied")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "name", "posix")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", denied)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.time,
"sleep",
lambda _seconds: pytest.fail("POSIX permission errors must not be waited out"),
)
with pytest.raises(OSError):
replace_with_busy_retry(tmp_path / "src", tmp_path / "dst")
assert attempts["count"] == 1
def test_remove_tree_logged_clears_read_only_files(tmp_path: Path):
tree = tmp_path / "tree"
(tree / "nested").mkdir(parents = True)
locked = tree / "nested" / "locked.bin"
locked.write_bytes(b"locked")
os.chmod(locked, stat.S_IRUSR)
remove_tree_logged(tree, "read only tree")
assert not tree.exists()
def test_remove_tree_logged_refuses_a_symlinked_root_without_touching_the_target(tmp_path: Path):
target = tmp_path / "outside"
target.mkdir()
(target / "precious.txt").write_text("precious\n")
original_mode = stat.S_IMODE(os.stat(target).st_mode)
link = tmp_path / "link"
try:
link.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
with pytest.raises(OSError):
remove_tree_logged(link, "symlinked tree")
assert link.is_symlink()
assert (target / "precious.txt").read_text() == "precious\n"
assert stat.S_IMODE(os.stat(target).st_mode) == original_mode
def test_activate_install_tree_leaves_a_symlinked_install_target_intact(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
target = tmp_path / "real-install-elsewhere"
target.mkdir()
(target / "old.txt").write_text("old install\n")
original_mode = stat.S_IMODE(os.stat(target).st_mode)
install_dir = tmp_path / "llama.cpp"
try:
install_dir.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "new.txt").read_text() == "new install\n"
assert (target / "old.txt").read_text() == "old install\n"
assert stat.S_IMODE(os.stat(target).st_mode) == original_mode
def test_successful_activation_reclaims_side_paths_from_earlier_failed_updates(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)
stranded = staging_root / "llama.cpp.rollback-20200101000000-1"
stranded.mkdir()
(stranded / "old.txt").write_text("stranded\n")
stale_failed = staging_root / "llama.cpp.failed-20200101000000-1"
stale_failed.mkdir()
(stale_failed / "junk.txt").write_text("junk\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "new.txt").read_text() == "new install\n"
assert not stranded.exists()
assert not stale_failed.exists()
assert not (tmp_path / ".staging").exists()
def test_failed_activation_does_not_reclaim_side_paths(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)
stranded = staging_root / "llama.cpp.rollback-20200101000000-1"
stranded.mkdir()
(stranded / "old.txt").write_text("stranded\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
with pytest.raises(PrebuiltFallback):
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "old.txt").read_text() == "old install\n"
assert (stranded / "old.txt").read_text() == "stranded\n"
def _fail_restore_and_copy(monkeypatch: pytest.MonkeyPatch, install_dir: Path) -> None:
"""Force both ways of putting the previous install back to fail."""
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError("restore failed")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"copytree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
OSError(errno.ENOSPC, "No space left on device")
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
def test_repeated_retention_keeps_exactly_one_previous_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
staging_root = tmp_path / ".staging"
for attempt in range(3):
install_dir.mkdir(parents = True, exist_ok = True)
(install_dir / "old.txt").write_text(f"install {attempt}\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
_fail_restore_and_copy(monkeypatch, install_dir)
with pytest.raises(PrebuiltFallback, match = "previous install kept at"):
activate_install_tree(staging_dir, install_dir, linux_host())
monkeypatch.undo()
rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
assert (rollbacks[0] / "old.txt").read_text() == "install 2\n"
assert sorted(staging_root.glob("llama.cpp.failed-*")) == []
def _write_usable_install(root: Path, marker: bytes) -> None:
"""A tree confirm_install_tree accepts, tagged with recognisable bytes."""
(root / "build" / "bin").mkdir(parents = True, exist_ok = True)
for name in ("llama-server", "llama-quantize"):
(root / name).write_bytes(marker)
(root / "build" / "bin" / name).write_bytes(marker)
(root / "convert_hf_to_gguf.py").write_bytes(marker)
(root / "gguf-py").mkdir(exist_ok = True)
(root / "UNSLOTH_PREBUILT_INFO.json").write_text("{}\n", encoding = "utf-8")
def test_retention_keeps_a_known_good_install_over_an_unvalidated_one(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Two failed updates must not replace the last known-good install with a stub."""
good = b"GOOD-LLAMA-CPP\n"
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
_write_usable_install(install_dir, good)
staging_root = tmp_path / ".staging"
host = linux_host()
real_confirm = INSTALL_LLAMA_PREBUILT.confirm_install_tree
real_replace = INSTALL_LLAMA_PREBUILT.os.replace
real_rmtree = INSTALL_LLAMA_PREBUILT.shutil.rmtree
def confirm_bad_prebuilt(path, host_info, *args, **kwargs):
if Path(path) == install_dir:
raise RuntimeError("activation confirm failed")
return real_confirm(Path(path), host_info, *args, **kwargs)
def deny_failed_move(src, dst):
if "failed-" in Path(dst).name:
raise OSError(errno.EACCES, "Access is denied")
return real_replace(src, dst)
def deny_install_dir_rmtree(path, *args, **kwargs):
if Path(path) == install_dir:
raise OSError(errno.EACCES, "Access is denied")
return real_rmtree(path, *args, **kwargs)
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", confirm_bad_prebuilt)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", deny_failed_move)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.shutil, "rmtree", deny_install_dir_rmtree)
with pytest.raises(PrebuiltFallback, match = "previous install kept at"):
activate_install_tree(staging_dir, install_dir, host)
monkeypatch.undo()
rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
real_confirm(rollbacks[0], host)
with pytest.raises(RuntimeError):
real_confirm(install_dir, host)
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", confirm_bad_prebuilt)
def deny_restore(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError("restore failed")
return real_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", deny_restore)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"copytree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
OSError(errno.ENOSPC, "No space left on device")
),
)
with pytest.raises(PrebuiltFallback, match = "previous install kept at"):
activate_install_tree(staging_dir, install_dir, host)
monkeypatch.undo()
survivors = [path for path in staging_root.rglob("llama-server") if path.read_bytes() == good]
assert survivors, "the last known-good llama.cpp was deleted as superseded"
rollbacks = sorted(staging_root.glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
real_confirm(rollbacks[0], host)
assert (rollbacks[0] / "llama-server").read_bytes() == good
def test_retention_does_not_copy_a_linked_previous_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
target = tmp_path / "user-checkout"
target.mkdir()
(target / "old.txt").write_text("user build\n")
install_dir = tmp_path / "llama.cpp"
try:
install_dir.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "rollback-" in Path(src).name and Path(dst) == install_dir:
raise OSError("restore failed")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
copied: list[tuple] = []
original_copytree = INSTALL_LLAMA_PREBUILT.shutil.copytree
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"copytree",
lambda *args, **kwargs: (copied.append(args), original_copytree(*args, **kwargs))[1],
)
with pytest.raises(PrebuiltFallback, match = "previous install kept at"):
activate_install_tree(staging_dir, install_dir, linux_host())
# copytree follows its source root even with symlinks=True.
assert copied == []
assert (target / "old.txt").read_text() == "user build\n"
assert not (target / "new.txt").exists()
assert "previous install is a link; not copying it back" in "".join(capsys.readouterr())
def test_prune_stale_install_side_paths_ignores_another_installs_side_paths(tmp_path: Path):
bracketed = tmp_path / "llama[1].cpp"
bracketed.mkdir()
sibling = tmp_path / "llama1.cpp"
sibling.mkdir()
staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(bracketed)
victim = staging_root / "llama1.cpp.rollback-20240101000000-1"
victim.mkdir()
assert prune_stale_install_side_paths(bracketed) == 0
assert victim.exists()
def test_prune_stale_install_side_paths_ignores_a_sibling_named_like_a_side_path(tmp_path: Path):
# glob.escape only neutralises * ? [, so rollback-* could reach a sibling's rollback-special.
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
sibling = tmp_path / "llama.cpp.rollback-special"
sibling.mkdir()
staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)
assert staging_root == INSTALL_LLAMA_PREBUILT.install_staging_root(sibling)
own_stale = staging_root / "llama.cpp.rollback-20240101000000-1"
own_stale.mkdir()
own_stale_with_counter = staging_root / "llama.cpp.failed-20240101000000-1-2"
own_stale_with_counter.mkdir()
sibling_sole_copy = staging_root / "llama.cpp.rollback-special.rollback-20240102000000-2"
sibling_sole_copy.mkdir()
(sibling_sole_copy / "llama-server").write_text("the sibling's only llama.cpp\n")
sibling_failed = staging_root / "llama.cpp.rollback-special.failed-20240102000000-2"
sibling_failed.mkdir()
sibling_live_staging = staging_root / "llama.cpp.rollback-special.staging-abcd1234"
sibling_live_staging.mkdir()
assert prune_stale_install_side_paths(install_dir) == 2
assert not own_stale.exists()
assert not own_stale_with_counter.exists()
assert sibling_sole_copy.exists()
assert (sibling_sole_copy / "llama-server").read_text() == "the sibling's only llama.cpp\n"
assert sibling_failed.exists()
assert sibling_live_staging.exists()
assert prune_stale_install_side_paths(sibling) == 2
assert not sibling_sole_copy.exists()
assert not sibling_failed.exists()
assert sibling_live_staging.exists()
def test_replace_with_busy_retry_rejects_a_zero_attempt_budget(tmp_path: Path):
with pytest.raises(ValueError):
replace_with_busy_retry(tmp_path / "src", tmp_path / "dst", attempts = 0)
def test_readonly_rmtree_handler_only_retries_the_removal_calls(tmp_path: Path):
handler = INSTALL_LLAMA_PREBUILT._clear_readonly_and_retry
victim = tmp_path / "victim"
victim.mkdir()
error = PermissionError(errno.EACCES, "Permission denied")
for rejected in (os.open, os.scandir, os.lstat):
with pytest.raises(PermissionError):
handler(rejected, str(victim), error)
with pytest.raises(PermissionError):
handler(os.open, str(victim), (type(error), error, None))
assert victim.exists()
def test_readonly_rmtree_handler_never_chmods_through_a_link(tmp_path: Path):
target = tmp_path / "outside"
target.mkdir()
original_mode = stat.S_IMODE(os.stat(target).st_mode)
link = tmp_path / "link"
try:
link.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
error = OSError("Cannot call rmtree on a symbolic link")
with pytest.raises(OSError):
INSTALL_LLAMA_PREBUILT._clear_readonly_and_retry(os.rmdir, str(link), error)
assert link.is_symlink()
assert stat.S_IMODE(os.stat(target).st_mode) == original_mode
def test_remove_tree_logged_leaves_posix_directory_modes_alone(tmp_path: Path):
if os.name == "nt":
pytest.skip("the read-only handler is Windows only by design")
tree = tmp_path / "tree"
unreadable = tree / "unreadable"
unreadable.mkdir(parents = True)
(unreadable / "file.bin").write_bytes(b"x")
os.chmod(unreadable, 0o500)
if os.access(unreadable, os.W_OK): # pragma: no cover - root ignores the mode
pytest.skip("cannot make the directory undeletable for this user")
try:
with pytest.raises(OSError):
remove_tree_logged(tree, "unreadable tree")
# S_IWRITE assigns rather than clears a bit; on POSIX unlink permission is on the parent.
assert stat.S_IMODE(os.stat(unreadable).st_mode) == 0o500
finally:
if unreadable.exists():
os.chmod(unreadable, 0o700)
def test_prune_stale_install_side_paths_keeps_the_paths_it_is_told_to_keep(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
staging_root = INSTALL_LLAMA_PREBUILT.install_staging_root(install_dir)
keeper = staging_root / "llama.cpp.rollback-20250101000000-2"
keeper.mkdir()
doomed = staging_root / "llama.cpp.rollback-20200101000000-1"
doomed.mkdir()
assert prune_stale_install_side_paths(install_dir, keep = (keeper, None)) == 1
assert keeper.exists()
assert not doomed.exists()
def test_activate_install_tree_keeps_existing_install_when_aside_move_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
# EIO, not EXDEV: a cross-device rename is now completed by copy.
def failing_replace(src, dst):
if Path(src) == install_dir:
raise OSError(errno.EIO, "Input/output error")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", failing_replace)
with pytest.raises(
PrebuiltFallback,
match = "could not be moved aside; previous install left in place",
):
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "old.txt").read_text() == "old install\n"
assert not staging_dir.exists()
assert not (tmp_path / ".staging").exists()
captured = capsys.readouterr()
output = captured.out + captured.err
assert "existing install could not be moved aside; leaving it in place" in output
def test_activate_install_tree_copies_the_existing_install_aside_across_devices(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "confirm_install_tree", lambda *_args: None)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def cross_device_replace(src, dst):
if Path(src) == install_dir:
raise OSError(errno.EXDEV, "Invalid cross-device link")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", cross_device_replace)
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "new.txt").read_text() == "new install\n"
assert not staging_dir.exists()
captured = capsys.readouterr()
output = captured.out + captured.err
assert "copy+publish" in output
def test_move_install_dir_aside_leaves_no_partial_tree_when_the_copy_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
src = tmp_path / "llama.cpp"
src.mkdir()
(src / "old.txt").write_text("old install\n")
dst = tmp_path / "llama.cpp.rollback-20250101000000-1"
def cross_device_replace(from_path, to_path):
raise OSError(errno.EXDEV, "Invalid cross-device link")
def failing_copytree(*_args, **_kwargs):
raise OSError(errno.ENOSPC, "No space left on device")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", cross_device_replace)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.shutil, "copytree", failing_copytree)
with pytest.raises(OSError, match = "No space left on device"):
INSTALL_LLAMA_PREBUILT.move_install_dir_aside(src, dst)
assert not dst.exists()
assert not dst.with_name(dst.name + ".copying").exists()
assert (src / "old.txt").read_text() == "old install\n"
def test_move_install_dir_aside_refuses_to_copy_a_linked_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
target = tmp_path / "real-install-elsewhere"
target.mkdir()
(target / "old.txt").write_text("old install\n")
src = tmp_path / "llama.cpp"
try:
src.symlink_to(target, target_is_directory = True)
except OSError as exc:
pytest.skip(f"directory symlinks unavailable: {exc}")
dst = tmp_path / "llama.cpp.rollback-20250101000000-1"
def cross_device_replace(from_path, to_path):
raise OSError(errno.EXDEV, "Invalid cross-device link")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", cross_device_replace)
with pytest.raises(OSError, match = "cross-device"):
INSTALL_LLAMA_PREBUILT.move_install_dir_aside(src, dst)
assert not dst.exists()
assert src.is_symlink()
assert (target / "old.txt").read_text() == "old install\n"
def test_activate_install_tree_keeps_existing_install_when_aside_move_hits_busy_lock(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def busy_replace(src, dst):
if Path(src) == install_dir:
raise OSError(errno.EBUSY, "Device or resource busy")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", busy_replace)
with pytest.raises(
BusyInstallConflict,
match = "appears to still be in use; previous install left in place",
):
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "old.txt").read_text() == "old install\n"
assert not staging_dir.exists()
assert not (tmp_path / ".staging").exists()
def test_activate_install_tree_restores_previous_install_when_failed_move_fails(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "failed-" in Path(dst).name:
raise OSError(errno.EACCES, "Access is denied")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
with pytest.raises(
PrebuiltFallback,
match = "activation failed; restored previous install",
):
activate_install_tree(staging_dir, install_dir, linux_host())
assert (install_dir / "old.txt").read_text() == "old install\n"
assert not (install_dir / "new.txt").exists()
assert not staging_dir.exists()
assert not (tmp_path / ".staging").exists()
captured = capsys.readouterr()
output = captured.out + captured.err
assert "failed active install could not be moved aside" in output
assert "removing failed active install path" in output
assert "restored previous install from rollback path" in output
def test_activate_install_tree_keeps_rollback_when_failed_install_cannot_be_removed(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
(install_dir / "old.txt").write_text("old install\n")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
original_replace = INSTALL_LLAMA_PREBUILT.os.replace
def flaky_replace(src, dst):
if "failed-" in Path(dst).name:
raise OSError(errno.EACCES, "Access is denied")
return original_replace(src, dst)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", flaky_replace)
original_rmtree = INSTALL_LLAMA_PREBUILT.shutil.rmtree
def flaky_rmtree(path, *args, **kwargs):
if Path(path) == install_dir:
raise OSError(errno.EACCES, "Access is denied")
return original_rmtree(path, *args, **kwargs)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.shutil, "rmtree", flaky_rmtree)
with pytest.raises(PrebuiltFallback, match = "previous install kept at"):
activate_install_tree(staging_dir, install_dir, linux_host())
rollbacks = sorted((tmp_path / ".staging").glob("llama.cpp.rollback-*"))
assert len(rollbacks) == 1
assert (rollbacks[0] / "old.txt").read_text() == "old install\n"
captured = capsys.readouterr()
output = captured.out + captured.err
assert "recovering from the failed activation also failed" in output
assert "rollback after failed activation also failed" not in output
assert "previous install kept at rollback path" in output
assert "removing rollback path" not in output
def test_activate_install_tree_cleans_install_when_no_previous_install_exists(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
install_dir = tmp_path / "llama.cpp"
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "new.txt").write_text("new install\n")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"confirm_install_tree",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("activation confirm failed")),
)
with pytest.raises(
PrebuiltFallback,
match = "activation and rollback failed; cleaned install state for fresh source build",
):
activate_install_tree(staging_dir, install_dir, linux_host())
assert not install_dir.exists()
assert not staging_dir.exists()
assert not (tmp_path / ".staging").exists()
captured = capsys.readouterr()
output = captured.out + captured.err
assert "leaving it in place" not in output
assert "previous install kept at" not in output
def test_activate_staged_dir_copies_when_replace_hits_busy_lock(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
):
staging_dir = tmp_path / "llama.cpp.staging-test"
(staging_dir / "bin").mkdir(parents = True)
(staging_dir / "bin" / "ggml-base.dll").write_bytes(b"fake dll")
dst = tmp_path / "llama.cpp"
def denied_replace(src, dst_arg):
raise PermissionError(errno.EACCES, "Access is denied", str(src))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", denied_replace)
activate_staged_dir(staging_dir, dst)
assert (dst / "bin" / "ggml-base.dll").read_bytes() == b"fake dll"
assert not staging_dir.exists()
captured = capsys.readouterr()
assert "falling back to file-by-file copy" in captured.out + captured.err
@pytest.mark.skipif(os.name == "nt", reason = "soname links are a Unix bundle layout")
@pytest.mark.parametrize("dst_exists", [False, True])
def test_activate_staged_dir_copy_keeps_soname_links(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dst_exists: bool
):
"""The EXDEV copy must not turn a bundle's soname chain into duplicate libraries.
A Linux llama.cpp release ships libllama.so -> libllama.so.0 -> libllama.so.0.3.0
(10 such links in b10715), and copytree's default symlinks = False dereferences
every one of them into a full copy of the shared library.
"""
staging_dir = tmp_path / "llama.cpp.staging-test"
staging_dir.mkdir()
real = staging_dir / "libllama.so.0.3.0"
real.write_bytes(b"\0" * 4096)
(staging_dir / "libllama.so.0").symlink_to("libllama.so.0.3.0")
(staging_dir / "libllama.so").symlink_to("libllama.so.0")
dst = tmp_path / "llama.cpp"
if dst_exists:
# os.replace also refuses an EMPTY existing dst cross-device, and the copy
# still has to complete there
dst.mkdir()
def cross_device_replace(src, dst_arg):
raise OSError(errno.EXDEV, "Invalid cross-device link", str(src))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", cross_device_replace)
activate_staged_dir(staging_dir, dst)
assert (dst / "libllama.so.0.3.0").read_bytes() == b"\0" * 4096
for link, target in (("libllama.so.0", "libllama.so.0.3.0"), ("libllama.so", "libllama.so.0")):
assert (
dst / link
).is_symlink(), f"{link} was dereferenced into a copy of the library it aliases"
assert os.readlink(dst / link) == target
on_disk = sum(p.lstat().st_size for p in dst.iterdir())
assert on_disk < 2 * len(
b"\0" * 4096
), f"the activated tree duplicated libraries ({on_disk} bytes)"
assert not staging_dir.exists()
def test_activate_staged_dir_reraises_non_busy_errors(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
staging_dir = tmp_path / "llama.cpp.staging-test"
staging_dir.mkdir()
(staging_dir / "new.txt").write_text("new install\n")
dst = tmp_path / "llama.cpp"
def out_of_space_replace(src, dst_arg):
raise OSError(errno.ENOSPC, "No space left on device", str(src))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "replace", out_of_space_replace)
with pytest.raises(OSError, match = "No space left on device"):
activate_staged_dir(staging_dir, dst)
assert not dst.exists()
assert (staging_dir / "new.txt").read_text() == "new install\n"
def test_binary_env_linux_includes_binary_parent_in_ld_library_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
bin_dir = install_dir / "build" / "bin"
bin_dir.mkdir(parents = True)
binary_path = bin_dir / "llama-server"
binary_path.write_bytes(b"fake")
host = linux_host()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_runtime_dirs", lambda _bp: [])
env = binary_env(binary_path, install_dir, host)
ld_dirs = env["LD_LIBRARY_PATH"].split(os.pathsep)
assert (
str(bin_dir) in ld_dirs
), f"binary_path.parent ({bin_dir}) must be in LD_LIBRARY_PATH, got: {ld_dirs}"
assert str(install_dir) in ld_dirs
def test_binary_env_windows_skips_inaccessible_inherited_path_entry(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
denied = r"C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps"
install_dir = tmp_path / "llama.cpp"
bin_dir = install_dir / "bin"
runtime_dir = tmp_path / "runtime"
inherited_dir = tmp_path / "usable-path"
for directory in (bin_dir, runtime_dir, inherited_dir):
directory.mkdir(parents = True)
inaccessible = {denied}
class FakePath:
def __init__(self, raw):
self.raw = str(raw)
def expanduser(self):
return self
def is_dir(self):
if self.raw in inaccessible:
raise PermissionError(13, "Access is denied", self.raw, 5)
return Path(self.raw).is_dir()
def resolve(self):
return Path(self.raw).resolve()
host = windows_host()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "pathsep", ";")
monkeypatch.setenv(
"PATH",
";".join((denied, str(inherited_dir), str(runtime_dir), str(inherited_dir))),
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "Path", FakePath)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"windows_runtime_dirs_for_runtime_line",
lambda _runtime_line: [str(runtime_dir)],
)
env = binary_env(bin_dir / "llama-server.exe", install_dir, host, runtime_line = "cuda")
assert env["PATH"].split(";") == [
str(bin_dir.resolve()),
str(runtime_dir.resolve()),
str(inherited_dir.resolve()),
]
assert denied not in env["PATH"]
inaccessible.add(str(runtime_dir))
with pytest.raises(PermissionError, match = "Access is denied"):
binary_env(bin_dir / "llama-server.exe", install_dir, host, runtime_line = "cuda")
def test_scrub_env_drops_secrets_and_keeps_runtime_vars():
raw = {
"HF_TOKEN": "hf_x",
"HUGGING_FACE_HUB_TOKEN": "hf_y",
"GH_TOKEN": "gh_x",
"GITHUB_TOKEN": "gh_y",
"WANDB_API_KEY": "wandb_x",
"AWS_SECRET_ACCESS_KEY": "aws_x",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "oidc_x",
"ACTIONS_ID_TOKEN_REQUEST_URL": "https://oidc",
"SOME_VENDOR_API_KEY": "vendor_x",
"DB_PASSWORD": "pw",
"MY_PRIVATE_KEY": "pk",
"KUBECONFIG": "/home/runner/.kube/config",
"SSH_AUTH_SOCK": "/tmp/ssh-agent.sock",
"SSH_PASSPHRASE": "ssh_pass",
"PATH": "/usr/bin",
"LD_LIBRARY_PATH": "/opt/lib",
"DYLD_LIBRARY_PATH": "/opt/dyld",
"HOME": "/home/runner",
"TMPDIR": "/tmp",
"CUDA_VISIBLE_DEVICES": "0",
"HSA_OVERRIDE_GFX_VERSION": "11.0.0",
}
cleaned = scrub_env(raw)
for secret in (
"HF_TOKEN",
"HUGGING_FACE_HUB_TOKEN",
"GH_TOKEN",
"GITHUB_TOKEN",
"WANDB_API_KEY",
"AWS_SECRET_ACCESS_KEY",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
"ACTIONS_ID_TOKEN_REQUEST_URL",
"SOME_VENDOR_API_KEY",
"DB_PASSWORD",
"MY_PRIVATE_KEY",
"KUBECONFIG",
"SSH_AUTH_SOCK",
"SSH_PASSPHRASE",
):
assert secret not in cleaned, f"{secret} must be stripped from binary env"
for keep in (
"PATH",
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"HOME",
"TMPDIR",
"CUDA_VISIBLE_DEVICES",
"HSA_OVERRIDE_GFX_VERSION",
):
assert cleaned[keep] == raw[keep], f"{keep} must be preserved for the binary"
# no bare "KEY" marker: benign KEY-containing names survive
assert is_secret_env_name("API_KEY") is True
assert is_secret_env_name("SSH_KEYFILE_PATH") is False
assert is_secret_env_name("PATH") is False
def test_scrub_env_drops_proxy_index_and_embedded_url_credentials():
raw = {
"HTTPS_PROXY": "https://user:secret@proxy:8080",
"https_proxy": "https://user:secret@proxy:8080",
"ALL_PROXY": "socks5://user:secret@proxy:1080",
"PIP_INDEX_URL": "https://u:[email protected]/simple",
"UV_INDEX_URL": "https://u:[email protected]/simple",
"MY_DB_DSN": "postgres://admin:secret@db:5432/app",
"PATH": "/usr/bin",
"CUDA_VISIBLE_DEVICES": "0",
"NO_PROXY": "localhost,127.0.0.1",
"SOME_ENDPOINT": "https://example.com:8080/v1",
}
cleaned = scrub_env(raw)
for secret in (
"HTTPS_PROXY",
"https_proxy",
"ALL_PROXY",
"PIP_INDEX_URL",
"UV_INDEX_URL",
"MY_DB_DSN",
):
assert secret not in cleaned, f"{secret} must be stripped from binary env"
for keep in ("PATH", "CUDA_VISIBLE_DEVICES", "NO_PROXY", "SOME_ENDPOINT"):
assert cleaned[keep] == raw[keep], f"{keep} must be preserved for the binary"
assert is_secret_env_name("HTTPS_PROXY") is True
assert is_secret_env_name("https_proxy") is True
assert is_secret_env_name("NO_PROXY") is False
def test_binary_env_strips_secrets_from_downloaded_binary_environment(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
bin_dir = install_dir / "build" / "bin"
bin_dir.mkdir(parents = True)
binary_path = bin_dir / "llama-server"
binary_path.write_bytes(b"fake")
host = linux_host()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_runtime_dirs", lambda _bp: [])
monkeypatch.setenv("HF_TOKEN", "hf_secret_from_ci")
monkeypatch.setenv("GITHUB_TOKEN", "gh_secret_from_ci")
monkeypatch.setenv("GH_TOKEN", "gh_secret_from_ci")
monkeypatch.setenv("WANDB_API_KEY", "wandb_secret_from_ci")
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")
env = binary_env(binary_path, install_dir, host)
assert "HF_TOKEN" not in env
assert "GITHUB_TOKEN" not in env
assert "GH_TOKEN" not in env
assert "WANDB_API_KEY" not in env
assert str(bin_dir) in env["LD_LIBRARY_PATH"].split(os.pathsep)
assert env["CUDA_VISIBLE_DEVICES"] == "1"
def test_binary_env_redirects_home_away_from_real_credential_stores(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
bin_dir = install_dir / "build" / "bin"
bin_dir.mkdir(parents = True)
binary_path = bin_dir / "llama-server"
binary_path.write_bytes(b"fake")
host = linux_host()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_runtime_dirs", lambda _bp: [])
real_home = str(tmp_path / "real_home")
monkeypatch.setenv("HOME", real_home)
monkeypatch.setenv("HF_HOME", real_home + "/.cache/huggingface")
env = binary_env(binary_path, install_dir, host)
assert env["HOME"] != real_home
assert env["HF_HOME"] == env["HOME"]
assert env["HOME"] == isolated_runtime_home()
assert os.path.isdir(env["HOME"])
assert os.listdir(env["HOME"]) == []
# Windows reconstructs the profile from HOMEDRIVE + HOMEPATH.
assert env["HOMEDRIVE"] + env["HOMEPATH"] == env["HOME"]
def test_scrub_env_drops_token_only_url_userinfo():
raw = {
"GENERIC_REPO": "https://[email protected]/org/repo",
"GENERIC_OK": "https://example.com:8080/v1",
}
cleaned = scrub_env(raw)
assert "GENERIC_REPO" not in cleaned
assert cleaned["GENERIC_OK"] == raw["GENERIC_OK"]
def test_binary_env_drops_explicit_credential_file_pointers(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
host = linux_host()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_runtime_dirs", lambda _bp: [])
dropped = (
"NETRC",
"PIP_CONFIG_FILE",
"DOCKER_CONFIG",
"GIT_CONFIG_GLOBAL",
"GITHUB_ENV",
"GITHUB_PATH",
"GITHUB_OUTPUT",
"GITHUB_STEP_SUMMARY",
"BASH_ENV",
)
for var in dropped:
monkeypatch.setenv(var, "/home/realuser/secret")
env = binary_env(tmp_path / "llama-server", tmp_path, host)
for var in dropped:
assert var not in env
def test_linux_runtime_dirs_probes_with_secret_free_env(monkeypatch: pytest.MonkeyPatch):
captured: dict[str, object] = {}
def fake_missing(binary_path, *, env = None):
captured["env"] = env
return []
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_missing_libraries", fake_missing)
monkeypatch.setenv("HF_TOKEN", "hf_secret")
monkeypatch.setenv("GITHUB_TOKEN", "gh_secret")
INSTALL_LLAMA_PREBUILT.linux_runtime_dirs(Path("/fake/llama-server"))
probe_env = captured["env"]
assert probe_env is not None
assert "HF_TOKEN" not in probe_env
assert "GITHUB_TOKEN" not in probe_env
def test_install_prebuilt_falls_back_to_older_release_plan(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
host = linux_host()
first_choice = asset_choice(
name = "app-b9002-linux-x64.tar.gz",
tag = "old-release",
source_label = "published",
)
second_choice = asset_choice(
name = "app-b9001-linux-x64.tar.gz",
tag = "older-release",
source_label = "published",
)
first_plan = release_plan(
[first_choice],
release_checksums(release_tag = "release-2", upstream_tag = "b9002", source_commit = None),
llama_tag = "b9002",
release_tag = "release-2",
)
second_plan = release_plan([second_choice], release_checksums(source_commit = None))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[first_plan, second_plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda probe_path, cache_path: probe_path.write_bytes(b"probe"),
)
call_log: list[tuple[str, bool]] = []
def fake_validate(
attempts,
host,
install_dir,
work_dir,
probe_path,
*,
requested_tag,
llama_tag,
release_tag,
approved_checksums,
initial_fallback_used = False,
existing_install_dir = None,
force_cpu = False,
llama_backend = None,
backend_request = None,
rocm_gfx = None,
walk_back = None,
):
call_log.append((llama_tag, initial_fallback_used))
if llama_tag == "b9002":
raise PrebuiltFallback("validation failed for latest release")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "marker.txt").write_text("ready\n")
return attempts[0], staging_dir, initial_fallback_used
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_attempts",
fake_validate,
)
activated = {}
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"activate_install_tree",
lambda staging_dir, install_dir, host: activated.update(
{"staging_dir": staging_dir, "install_dir": install_dir}
),
)
ensured_tags: list[str] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"ensure_converter_scripts",
lambda install_dir, llama_tag, **kwargs: ensured_tags.append(llama_tag),
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert call_log == [("b9002", False), ("b9001", True)]
assert activated["install_dir"] == install_dir
assert ensured_tags == ["b9001"]
def _write_entrypoints(install_dir: Path) -> None:
"""Reuse checks runnability, not existence, so the entrypoints must be executable."""
runtime_dir = install_dir / "build" / "bin"
runtime_dir.mkdir(parents = True, exist_ok = True)
for directory in (install_dir, runtime_dir):
for name in ("llama-server", "llama-quantize"):
binary = directory / name
binary.write_text("#!/bin/sh\n", encoding = "utf-8")
binary.chmod(0o755)
def write_linux_install_shape(install_dir: Path) -> None:
runtime_dir = install_dir / "build" / "bin"
_write_entrypoints(install_dir)
# After the upstream impl split, llama-server and llama-quantize load these via DT_NEEDED.
(runtime_dir / "libllama-server-impl.so").write_bytes(b"DLL")
(runtime_dir / "libllama-quantize-impl.so").write_bytes(b"DLL")
(runtime_dir / "libllama-common.so.0").write_bytes(b"DLL")
(runtime_dir / "libllama.so.0").write_bytes(b"DLL")
(runtime_dir / "libggml.so.0").write_bytes(b"DLL")
(runtime_dir / "libggml-base.so.0").write_bytes(b"DLL")
(runtime_dir / "libggml-cpu-x64.so.0").write_bytes(b"DLL")
(runtime_dir / "libmtmd.so.0").write_bytes(b"DLL")
(install_dir / "convert_hf_to_gguf.py").write_text("#!/usr/bin/env python3\n", encoding = "utf-8")
(install_dir / "gguf-py" / "gguf").mkdir(parents = True, exist_ok = True)
def write_windows_install_shape(
install_dir: Path,
*,
include_llama_dll: bool = True,
include_cuda_dll: bool = False,
include_cudart_dlls: bool = False,
include_shared_runtime: bool = True,
) -> None:
runtime_dir = install_dir / "build" / "bin" / "Release"
runtime_dir.mkdir(parents = True, exist_ok = True)
(runtime_dir / "llama-server.exe").write_bytes(b"MZ")
(runtime_dir / "llama-quantize.exe").write_bytes(b"MZ")
if include_shared_runtime:
# What a BUILD_SHARED_LIBS bundle carries alongside llama.dll.
for name in (
"llama-common.dll",
"llama-server-impl.dll",
"llama-quantize-impl.dll",
"ggml.dll",
"ggml-base.dll",
"ggml-cpu-x64.dll",
"mtmd.dll",
):
(runtime_dir / name).write_bytes(b"DLL")
if include_llama_dll:
(runtime_dir / "llama.dll").write_bytes(b"DLL")
if include_cuda_dll:
(runtime_dir / "ggml-cuda.dll").write_bytes(b"DLL")
if include_cudart_dlls:
# cudart bundle DLLs that ship in cudart-llama-bin-win-cuda-*-x64.zip
(runtime_dir / "cudart64_12.dll").write_bytes(b"DLL")
(runtime_dir / "cublas64_12.dll").write_bytes(b"DLL")
(runtime_dir / "cublasLt64_12.dll").write_bytes(b"DLL")
(install_dir / "convert_hf_to_gguf.py").write_text("#!/usr/bin/env python3\n", encoding = "utf-8")
(install_dir / "gguf-py" / "gguf").mkdir(parents = True, exist_ok = True)
def write_macos_install_shape(
install_dir: Path,
*,
include_libllama: bool = True,
include_libggml: bool = True,
include_libmtmd: bool = True,
) -> None:
runtime_dir = install_dir / "build" / "bin"
_write_entrypoints(install_dir)
for name in ("libllama-common.0.dylib", "libggml-base.0.dylib", "libggml-cpu.0.dylib"):
(runtime_dir / name).write_bytes(b"DLL")
(runtime_dir / "libllama-server-impl.dylib").write_bytes(b"DLL")
(runtime_dir / "libllama-quantize-impl.dylib").write_bytes(b"DLL")
if include_libllama:
(runtime_dir / "libllama.0.dylib").write_bytes(b"DLL")
if include_libggml:
(runtime_dir / "libggml.0.dylib").write_bytes(b"DLL")
if include_libmtmd:
(runtime_dir / "libmtmd.0.dylib").write_bytes(b"DLL")
(install_dir / "convert_hf_to_gguf.py").write_text("#!/usr/bin/env python3\n", encoding = "utf-8")
(install_dir / "gguf-py" / "gguf").mkdir(parents = True, exist_ok = True)
def test_existing_install_matches_plan_with_fingerprint_linux(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
choice = asset_choice()
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
def test_existing_install_matches_plan_false_without_fingerprint(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
(install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text(
json.dumps({"tag": "b9001", "asset": "llama-b9001-bin-ubuntu-x64.tar.gz"}) + "\n",
encoding = "utf-8",
)
host = linux_host()
choice = asset_choice(url = "https://example.com/x.tar.gz")
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
plan = release_plan([choice], checksums)
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_existing_install_matches_plan_false_with_malformed_metadata(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
(install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text("{not-json\n", encoding = "utf-8")
host = linux_host()
choice = asset_choice(url = "https://example.com/x.tar.gz")
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
plan = release_plan([choice], checksums)
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_existing_install_matches_plan_windows_cpu_requires_llama_dll(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(install_dir, include_llama_dll = True)
host = windows_host()
choice = asset_choice(
name = "llama-b9001-bin-win-cpu-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cpu",
)
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
(install_dir / "build" / "bin" / "Release" / "llama.dll").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_existing_install_matches_plan_windows_rejects_an_empty_executable(tmp_path: Path):
"""Windows has no executable-image preflight and an older marker carries no runtime
record, so a zero-byte llama-server.exe passed every other check and was reused."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(install_dir, include_llama_dll = True)
host = windows_host()
choice = asset_choice(
name = "llama-b9001-bin-win-cpu-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cpu",
)
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
server = install_dir / "build" / "bin" / "Release" / "llama-server.exe"
saved = server.read_bytes()
server.write_bytes(b"")
assert existing_install_matches_plan(install_dir, host, plan) is False
server.write_bytes(saved)
assert existing_install_matches_plan(install_dir, host, plan) is True
def test_existing_install_matches_plan_windows_cuda_requires_cuda_dll(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(install_dir, include_llama_dll = True, include_cuda_dll = True)
host = windows_host(driver_cuda_version = (12, 4), has_usable_nvidia = True)
choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
)
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
(install_dir / "build" / "bin" / "Release" / "ggml-cuda.dll").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_existing_install_matches_plan_windows_cuda_paired_requires_cudart(tmp_path: Path):
"""A paired cudart bundle (#5106) marks the install stale unless cudart64_* and cublas64_* are on disk."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(
install_dir,
include_llama_dll = True,
include_cuda_dll = True,
include_cudart_dlls = True,
)
host = windows_host(driver_cuda_version = (12, 4), has_usable_nvidia = True)
choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
runtime_name = "cudart-llama-bin-win-cuda-12.4-x64.zip",
runtime_url = "https://example.com/cudart.zip",
runtime_sha256 = "c" * 64,
)
checksums = release_checksums(
(choice.name, choice.expected_sha256, PREBUILT),
(choice.runtime_name, choice.runtime_sha256, PREBUILT),
)
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
(install_dir / "build" / "bin" / "Release" / "cublas64_12.dll").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
write_windows_install_shape(
install_dir,
include_llama_dll = True,
include_cuda_dll = True,
include_cudart_dlls = True,
)
(install_dir / "build" / "bin" / "Release" / "cudart64_12.dll").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
write_windows_install_shape(
install_dir,
include_llama_dll = True,
include_cuda_dll = True,
include_cudart_dlls = True,
)
(install_dir / "build" / "bin" / "Release" / "cublasLt64_12.dll").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_existing_install_matches_plan_windows_cuda_unpaired_skips_cudart_check(tmp_path: Path):
"""With no paired runtime archive, a legacy install lacking cudart must still pass (else reinstall loops)."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(
install_dir,
include_llama_dll = True,
include_cuda_dll = True,
include_cudart_dlls = False,
)
host = windows_host(driver_cuda_version = (12, 4), has_usable_nvidia = True)
choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
)
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
def test_arch_fields_do_not_change_the_install_fingerprint(tmp_path: Path):
"""gfx_target and mapped_targets stay out of the fingerprint, or every ROCm install goes stale."""
choice_kwargs = dict(
repo = "unslothai/llama.cpp",
tag = "release-1",
name = "app-b9001-linux-x64-rocm-gfx110X.tar.gz",
url = "https://example.com/x.tar.gz",
source_label = "published",
install_kind = "linux-rocm",
runtime_line = "rocm7",
expected_sha256 = "a" * 64,
)
old_choice = AssetChoice(**choice_kwargs)
new_choice = AssetChoice(
**choice_kwargs,
gfx_target = "gfx110X",
mapped_targets = ["gfx1100", "gfx1101", "gfx1102", "gfx1103"],
)
checksums = release_checksums()
fingerprint_kwargs = dict(
llama_tag = "b9001", release_tag = "release-1", approved_checksums = checksums
)
old_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
choice = old_choice, **fingerprint_kwargs
)
new_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
choice = new_choice, **fingerprint_kwargs
)
assert old_fingerprint and old_fingerprint == new_fingerprint, (
"recording gfx_target/mapped_targets changed the install fingerprint; "
"every existing install would refresh on upgrade"
)
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_metadata(install_dir, new_choice, checksums)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())
assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]
assert marker["gfx_target"] == "gfx110X"
assert marker["install_fingerprint"] == old_fingerprint
def test_non_rocm_bundles_record_no_mapped_targets(tmp_path: Path):
"""Only published_rocm_choice_for_host sets the arch fields (issue 7624), so CPU, CUDA, Vulkan
and macOS bundles record an empty list and the runtime gate fails open."""
checksums = release_checksums()
for kind, asset in (
("linux-cpu", "app-b9001-linux-x64-cpu.tar.gz"),
("linux-cuda12", "app-b9001-linux-x64-cuda12-portable.tar.gz"),
("linux-vulkan", "app-b9001-linux-x64-vulkan.tar.gz"),
("windows-cpu", "app-b9001-windows-x64-cpu.zip"),
("macos-arm64", "llama-b9001-bin-macos-arm64.tar.gz"),
):
install_dir = tmp_path / kind
install_dir.mkdir()
write_metadata(
install_dir,
asset_choice(
name = asset,
url = "https://example.com/x",
source_label = "published",
install_kind = kind,
),
checksums,
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())
assert marker["mapped_targets"] == [], kind
assert marker["gfx_target"] is None, kind
def _rocm_choice(**overrides):
"""A published ROCm bundle choice, as published_rocm_choice_for_host returns."""
fields = dict(
repo = "unslothai/llama.cpp",
tag = "b10360",
name = "app-b10360-linux-x64-rocm-gfx110X.tar.gz",
url = "https://example.invalid/app.tar.gz",
source_label = "published",
install_kind = "app",
bundle_profile = "rocm",
runtime_line = "rocm",
coverage_class = "gfx110X",
gfx_target = "gfx110X",
mapped_targets = ["gfx1100", "gfx1101", "gfx1102", "gfx1103"],
)
fields.update(overrides)
return AssetChoice(**fields)
def _sync_arch_coverage(install_dir, choice):
"""sync_marker_selection with only the built-arch coverage in play."""
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir,
choice = choice,
backend_request = None,
persist_llama_backend = "auto",
)
def test_reused_install_backfills_the_arch_coverage(tmp_path: Path):
"""An install made before mapped_targets existed must gain it on reuse:
write_prebuilt_metadata only runs on a real install and the field sits outside the
fingerprint, so without the backfill the gate fails open indefinitely (#7624)."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps({"release_tag": "b10360", "llama_backend": "auto"}) + "\n",
encoding = "utf-8",
)
_sync_arch_coverage(install_dir, _rocm_choice())
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]
assert marker["gfx_target"] == "gfx110X"
assert marker["release_tag"] == "b10360"
assert marker["llama_backend"] == "auto"
def test_a_reused_bundle_records_whether_it_is_this_runs_fallback(tmp_path: Path):
"""A reused fallback must be recorded as one, or the no-network check keeps it forever."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps({"release_tag": "b10360", "prebuilt_fallback_used": False}) + "\n",
encoding = "utf-8",
)
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir, choice = _rocm_choice(), backend_request = None, prebuilt_fallback_used = True
)
assert json.loads(marker_path.read_text(encoding = "utf-8"))["prebuilt_fallback_used"] is True
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir, choice = _rocm_choice(), backend_request = None
)
assert json.loads(marker_path.read_text(encoding = "utf-8"))["prebuilt_fallback_used"] is True
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir, choice = _rocm_choice(), backend_request = None, prebuilt_fallback_used = False
)
assert json.loads(marker_path.read_text(encoding = "utf-8"))["prebuilt_fallback_used"] is False
source = open(INSTALL_LLAMA_PREBUILT.__file__, encoding = "utf-8").read()
assert 'marker.get("prebuilt_fallback_used") is True' in source
assert "_record_reused_selection(plan, satisfied.choice, satisfied.used_fallback)" in source
def test_reused_install_refreshes_corrected_arch_coverage(tmp_path: Path):
"""A manifest that corrects mapped_targets for an unchanged asset must reach the
marker. Stale coverage is worse than none: too narrow forces a supported GPU to
CPU, too wide leaves an unsupported one visible to crash."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps(
{
"release_tag": "b10360",
"gfx_target": "gfx110X",
"mapped_targets": ["gfx1100"],
}
)
+ "\n",
encoding = "utf-8",
)
_sync_arch_coverage(install_dir, _rocm_choice())
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["mapped_targets"] == ["gfx1100", "gfx1101", "gfx1102", "gfx1103"]
@pytest.mark.parametrize("targets", [None, [], ["", " "]])
def test_a_bundle_that_declares_no_arch_leaves_the_marker_alone(tmp_path: Path, targets):
"""CUDA, Vulkan, CPU and source builds declare no targets. Absent means "this
bundle has none", not "clear what is there": reuse requires a fingerprint match,
so the asset is the one the marker already describes."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
original = {
"release_tag": "b10360",
"gfx_target": "gfx110X",
"mapped_targets": ["gfx1100", "gfx1101"],
}
marker_path.write_text(json.dumps(original) + "\n", encoding = "utf-8")
_sync_arch_coverage(install_dir, _rocm_choice(gfx_target = None, mapped_targets = targets))
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["gfx_target"] == original["gfx_target"]
assert marker["mapped_targets"] == original["mapped_targets"]
def test_arch_coverage_sync_survives_a_missing_or_broken_marker(tmp_path: Path):
"""It runs after the install is already valid, so it must never raise:
an unexpected exit here no longer falls back to a source build."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
_sync_arch_coverage(install_dir, _rocm_choice())
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
assert not marker_path.exists()
for payload in ("{not json", "[1, 2]"):
marker_path.write_text(payload, encoding = "utf-8")
_sync_arch_coverage(install_dir, _rocm_choice())
assert marker_path.read_text(encoding = "utf-8") == payload
def test_every_reuse_path_syncs_the_arch_coverage():
"""The reuse paths skip write_prebuilt_metadata, so the coverage has to ride the
one writer they all share. Source-level because reaching them needs a full install
run: pinned on _record_reused_selection, which every reuse path calls."""
source = MODULE_PATH.read_text(encoding = "utf-8")
assert source.count("_record_reused_selection(") == 4
patch = source[
source.index("def _marker_selection_patch") : source.index("def sync_marker_selection")
]
assert 'patch["mapped_targets"] = targets' in patch
@pytest.mark.parametrize("visual_server", [True, False], ids = ["present", "missing"])
def test_a_published_bundle_owes_its_visual_server(tmp_path, monkeypatch, visual_server):
"""A published bundle must carry its source label, or an incomplete Vulkan tree reads as valid."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(
tmp_path, backend = "vulkan", source = "published", visual_server = visual_server
)
if visual_server:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
else:
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_an_upstream_bundle_does_not_owe_a_visual_server(tmp_path, monkeypatch):
"""Only "published" carries it; requiring it of an upstream tree would source build."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(
tmp_path, backend = "vulkan", source = "upstream", visual_server = False
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert (install_dir / "llama-server").exists()
def test_a_reused_install_backfills_the_paired_runtime_asset(tmp_path: Path):
"""Reuse backfills runtime_asset on older installs, or its cudart trio is never required."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps({"release_tag": "release-1", "llama_backend": "auto", "force_cpu": False}),
encoding = "utf-8",
)
choice = asset_choice(
name = "app-b9002-windows-cuda-x64.zip",
url = "https://example/x",
tag = "b9002",
source_label = "published",
install_kind = "windows-cuda",
runtime_name = "cudart-llama-bin-win-cuda-13.0-x64.zip",
)
INSTALL_LLAMA_PREBUILT.sync_marker_selection(install_dir, choice = choice, backend_request = "auto")
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["runtime_asset"] == "cudart-llama-bin-win-cuda-13.0-x64.zip"
def test_a_pair_less_reuse_does_not_invent_a_runtime_asset(tmp_path: Path):
"""Set, never cleared: a bundle with no pair is one the marker already describes."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps({"release_tag": "release-1", "llama_backend": "auto", "force_cpu": False}),
encoding = "utf-8",
)
choice = asset_choice(
name = "app-b9002-windows-cpu-x64.zip",
url = "https://example/x",
tag = "b9002",
source_label = "published",
install_kind = "windows-cpu",
)
INSTALL_LLAMA_PREBUILT.sync_marker_selection(install_dir, choice = choice, backend_request = "auto")
assert "runtime_asset" not in json.loads(marker_path.read_text(encoding = "utf-8"))
def test_marker_rewrite_preserves_arch_fields(tmp_path: Path):
"""A sync that touches other fields must not drop the arch ones (#7624).
sync_marker_selection reads the marker, patches it and writes the whole dict back; a
rebuild-from-known-keys version would strip mapped_targets and silently kill the gate."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps(
{
"release_tag": "release-1",
"llama_backend": "auto",
"force_cpu": False,
"gfx_target": "gfx110X",
"mapped_targets": ["gfx1100", "gfx1101"],
}
),
encoding = "utf-8",
)
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir,
choice = _rocm_choice(gfx_target = None, mapped_targets = None),
backend_request = "cpu",
persist_force_cpu = True,
persist_llama_backend = "auto",
ggml_tree = "tree-abc",
rocm_gfx = "gfx1101",
)
marker = json.loads(marker_path.read_text())
assert marker["gfx_target"] == "gfx110X"
assert marker["mapped_targets"] == ["gfx1100", "gfx1101"]
assert marker["force_cpu"] is True
assert marker["rocm_gfx"] == "gfx1101"
assert marker["ggml_tree"] == "tree-abc"
def _cuda_choice(**overrides):
fields = dict(
repo = "unslothai/llama.cpp",
tag = "b10360",
name = "app-b10360-linux-x64-cuda13-older.tar.gz",
url = "https://example.invalid/app.tar.gz",
source_label = "published",
install_kind = "linux-cuda",
bundle_profile = "app",
runtime_line = "cuda13",
coverage_class = "older",
supported_sms = ["75", "80", "86", "89"],
expected_sha256 = "a" * 64,
)
fields.update(overrides)
return AssetChoice(**fields)
def test_write_prebuilt_metadata_records_supported_sms(tmp_path: Path):
"""The runtime SM gate reads supported_sms from the marker; without it a
bundle installed on one GPU fails open when run on another."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
choice = _cuda_choice()
write_metadata(
install_dir,
choice,
approved_release_checksums_for_asset(choice.name, "a" * 64),
llama_tag = "b10360",
release_tag = "b10360",
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())
assert marker["supported_sms"] == ["75", "80", "86", "89"]
def test_reused_install_backfills_supported_sms(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker_path.write_text(
json.dumps({"release_tag": "b10360", "llama_backend": "auto"}) + "\n",
encoding = "utf-8",
)
_sync_arch_coverage(install_dir, _cuda_choice())
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["supported_sms"] == ["75", "80", "86", "89"]
assert marker["release_tag"] == "b10360"
@pytest.mark.parametrize("sms", [None, [], ["", " "]])
def test_a_bundle_that_declares_no_sms_leaves_the_marker_alone(tmp_path: Path, sms):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
original = {"release_tag": "b10360", "supported_sms": ["86", "89", "90"]}
marker_path.write_text(json.dumps(original) + "\n", encoding = "utf-8")
_sync_arch_coverage(install_dir, _cuda_choice(supported_sms = sms))
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
assert marker["supported_sms"] == original["supported_sms"]
def test_existing_install_fingerprint_changes_when_cudart_pair_added(tmp_path: Path):
"""A pre-#5322 CUDA install must go stale once the choice gains a runtime archive (#5106 fingerprint half)."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(
install_dir,
include_llama_dll = True,
include_cuda_dll = True,
include_cudart_dlls = False,
)
host = windows_host(driver_cuda_version = (12, 4), has_usable_nvidia = True)
legacy_choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
)
paired_choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "https://example.com/x.zip",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
runtime_name = "cudart-llama-bin-win-cuda-12.4-x64.zip",
runtime_url = "https://example.com/cudart.zip",
runtime_sha256 = "c" * 64,
)
checksums = release_checksums(
(legacy_choice.name, legacy_choice.expected_sha256, PREBUILT),
(paired_choice.runtime_name, paired_choice.runtime_sha256, PREBUILT),
)
write_metadata(install_dir, legacy_choice, checksums)
legacy_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
llama_tag = "b9001",
release_tag = "release-1",
choice = legacy_choice,
approved_checksums = checksums,
)
paired_fingerprint = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
llama_tag = "b9001",
release_tag = "release-1",
choice = paired_choice,
approved_checksums = checksums,
)
assert legacy_fingerprint != paired_fingerprint, (
"expected_install_fingerprint must hash runtime_name/runtime_sha256 "
"so pre-#5322 installs are not falsely considered up-to-date"
)
paired_plan = release_plan([paired_choice], checksums)
assert existing_install_matches_plan(install_dir, host, paired_plan) is False
def test_existing_install_matches_plan_macos_requires_dylibs(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_macos_install_shape(install_dir)
host = macos_host()
choice = asset_choice(
name = "llama-b9001-bin-macos-arm64.tar.gz",
url = "https://example.com/x.tar.gz",
source_label = "published",
install_kind = "macos-arm64",
)
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
assert existing_install_matches_plan(install_dir, host, plan) is True
(install_dir / "build" / "bin" / "libggml.0.dylib").unlink()
assert existing_install_matches_plan(install_dir, host, plan) is False
def test_install_prebuilt_skips_download_when_existing_install_matches(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
choice = asset_choice()
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
(install_dir / "AGENTS.md").write_text("old root instructions", encoding = "utf-8")
nested_agents = install_dir / "examples" / "AGENTS.md"
nested_agents.parent.mkdir()
nested_agents.write_text("old nested instructions", encoding = "utf-8")
(install_dir / "CLAUDE.md").write_text("old Claude instructions", encoding = "utf-8")
(nested_agents.parent / "CLAUDE.md").write_text(
"old nested Claude instructions", encoding = "utf-8"
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("matching install should skip before validation model download")
),
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert not list(install_dir.rglob("AGENTS.md"))
assert not list(install_dir.rglob("CLAUDE.md"))
def test_setup_scripts_prune_agent_files_without_shipping_a_repo_copy():
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
# A background frontend build installs the OXC runtime and prunes both trees itself.
assert (
'if [ -z "$_FRONTEND_BG_PID" ]; then\n'
" _install_oxc_runtime\n"
' _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"\n'
' _remove_agent_instruction_files "$_OXC_DIR/node_modules"\n'
"fi\n"
) in setup_sh
assert (
" _build_frontend\n"
" _install_oxc_runtime\n"
' rm -f "$_FRONTEND_BUILD_MARK"\n'
' _remove_agent_instruction_files "$SCRIPT_DIR/frontend/node_modules"\n'
' _remove_agent_instruction_files "$_OXC_DIR/node_modules"'
) in setup_sh
assert '_remove_agent_instruction_files "$SCRIPT_DIR/frontend" "$_OXC_DIR"' not in setup_sh
assert '_remove_agent_instruction_files "$LLAMA_CPP_DIR"' in setup_sh
assert "-name 'CLAUDE.md'" in setup_sh
assert 'if [ ! -L "$LLAMA_CPP_DIR" ] && {' in setup_sh
assert '${_LOCAL_LLAMA_CPP_LINKED:-false}" != true' not in setup_sh
assert "$LLAMA_CPP_DIR/$_STUDIO_OWNED_MARKER" in setup_sh
assert '_studio_owned_adoptable "$LLAMA_CPP_DIR"' in setup_sh
assert (
"Remove-AgentInstructionFiles -Roots @(\n"
' (Join-Path $FrontendDir "node_modules"),\n'
' (Join-Path $OxcValidatorDir "node_modules")\n'
")"
) in setup_ps1
assert "Remove-AgentInstructionFiles -Roots @($FrontendDir, $OxcValidatorDir)" not in setup_ps1
assert '"CLAUDE.md"' in setup_ps1
assert '-Include "AGENTS.md", "CLAUDE.md"' not in setup_ps1
assert '$child.Name -in @("AGENTS.md", "CLAUDE.md")' in setup_ps1
assert "$llamaCppIsLink" in setup_ps1
assert "if (-not $LocalLlamaCppLinked)" not in setup_ps1
assert "Join-Path $LlamaCppDir $StudioOwnedMarker" in setup_ps1
assert "Test-StudioOwnedAdoptable $LlamaCppDir" in setup_ps1
assert (
"Copy-Item -Recurse -LiteralPath $ResolvedLocal -Destination $LlamaCppDir\n"
" Remove-AgentInstructionFiles -Roots @($LlamaCppDir)"
) in setup_ps1
assert not (PACKAGE_ROOT / "studio" / "frontend" / "src" / "i18n" / "AGENTS.md").exists()
assert (PACKAGE_ROOT / "studio" / "frontend" / "src" / "i18n" / "README.md").is_file()
def test_setup_sh_cleanup_unlinks_instruction_symlink_only(tmp_path: Path):
if shutil.which("bash") is None:
pytest.skip("bash is not available")
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
start = setup_sh.index("_remove_agent_instruction_files() {")
end = setup_sh.index("\n}\n", start) + 2
function = setup_sh[start:end]
managed = tmp_path / "managed"
external = tmp_path / "external.md"
managed.mkdir()
external.write_text("external", encoding = "utf-8")
instruction = managed / "AGENTS.md"
try:
instruction.symlink_to(external)
except OSError as exc:
pytest.skip(f"symlinks unavailable: {exc}")
subprocess.run(
["bash", "-c", function + '\n_remove_agent_instruction_files "$1"', "bash", str(managed)],
check = True,
)
assert not os.path.lexists(instruction)
assert external.read_text(encoding = "utf-8") == "external"
def test_install_prebuilt_does_not_skip_unhealthy_existing_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
(install_dir / "llama-quantize").unlink()
host = linux_host()
choice = asset_choice()
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
plan = release_plan([choice], checksums)
write_metadata(install_dir, choice, checksums)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_attempts",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("unhealthy install must continue into normal install flow")
),
)
with pytest.raises(
AssertionError, match = "unhealthy install must continue into normal install flow"
):
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
def test_install_prebuilt_skips_when_older_release_fallback_matches_existing_install(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
latest_choice = asset_choice(
name = "llama-b9002-bin-ubuntu-x64.tar.gz",
tag = "release-2",
expected_sha256 = "c" * 64,
)
fallback_choice = asset_choice()
latest_checksums = release_checksums(
(latest_choice.name, latest_choice.expected_sha256, UPSTREAM),
release_tag = "release-2",
upstream_tag = "b9002",
source_commit = "beadfeed",
source_sha256 = "d" * 64,
)
fallback_checksums = release_checksums(
(fallback_choice.name, fallback_choice.expected_sha256, UPSTREAM)
)
latest_plan = release_plan(
[latest_choice],
latest_checksums,
llama_tag = "b9002",
release_tag = "release-2",
)
fallback_plan = release_plan([fallback_choice], fallback_checksums)
write_metadata(install_dir, fallback_choice, fallback_checksums, prebuilt_fallback_used = True)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[latest_plan, fallback_plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda probe_path, cache_path: probe_path.write_bytes(b"probe"),
)
call_log: list[str] = []
def fake_validate(
attempts,
host,
install_dir,
work_dir,
probe_path,
*,
requested_tag,
llama_tag,
release_tag,
approved_checksums,
initial_fallback_used = False,
existing_install_dir = None,
force_cpu = False,
llama_backend = None,
backend_request = None,
rocm_gfx = None,
walk_back = None,
):
call_log.append(llama_tag)
raise PrebuiltFallback("validation failed for latest release")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_attempts",
fake_validate,
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"activate_install_tree",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("matching fallback install should not reactivate")
),
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert call_log == ["b9002"]
@pytest.mark.skipif(os.name == "nt", reason = "the root wrapper is written on POSIX only")
@pytest.mark.parametrize("name", ["llama-server", "llama-quantize"])
def test_a_damaged_root_entrypoint_stops_the_release_being_reused(tmp_path: Path, name: str):
"""Keep decisions read _damaged_entrypoint so a rotten root wrapper forces repair; the launch
check must not mark stale a tree the resolver can still run via build/bin."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
choice = asset_choice(name = "llama-b9001-bin-ubuntu-x64-good.tar.gz")
checksums = release_checksums((choice.name, choice.expected_sha256, PREBUILT))
write_metadata(install_dir, choice, checksums)
kwargs = dict(
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
assert existing_install_matches_choice(install_dir, host, **kwargs) is True
assert INSTALL_LLAMA_PREBUILT.installed_runtime_health(install_dir, host = host) == (True, "")
(install_dir / name).chmod(0o644)
assert INSTALL_LLAMA_PREBUILT.installed_runtime_health(install_dir, host = host) == (True, "")
assert (
existing_install_matches_choice(install_dir, host, **kwargs) is False
), "a reinstall is what replaces a rotten root wrapper"
# is_file() and the exec bit survive truncation, so discovery picks it and exec hits ENOEXEC.
(install_dir / name).write_text("", encoding = "utf-8")
(install_dir / name).chmod(0o755)
assert INSTALL_LLAMA_PREBUILT.installed_runtime_health(install_dir, host = host) == (
False,
"llama_runtime_binaries_missing",
)
assert (
existing_install_matches_choice(install_dir, host, **kwargs) is False
), "a tree the probe rejects and this keeps is a repair that changes nothing"
def test_install_prebuilt_skips_same_release_fallback_attempt_when_installed(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
first_choice = asset_choice(
name = "llama-b9001-bin-ubuntu-x64-bad.tar.gz",
source_label = "published",
expected_sha256 = "c" * 64,
)
fallback_choice = asset_choice(name = "llama-b9001-bin-ubuntu-x64-good.tar.gz")
checksums = release_checksums(
(first_choice.name, first_choice.expected_sha256, PREBUILT),
(fallback_choice.name, fallback_choice.expected_sha256, UPSTREAM),
)
plan = release_plan([first_choice, fallback_choice], checksums)
write_metadata(install_dir, fallback_choice, checksums, prebuilt_fallback_used = True)
assert (
existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = fallback_choice,
approved_checksums = checksums,
)
is True
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda probe_path, cache_path: probe_path.write_bytes(b"probe"),
)
attempted_names: list[str] = []
def fake_validate_choice(
choice,
host,
staging_dir,
work_dir,
probe_path,
*,
requested_tag,
llama_tag,
release_tag,
approved_checksums,
prebuilt_fallback_used,
quantized_path,
force_cpu = False,
llama_backend = None,
backend_request = None,
rocm_gfx = None,
walk_back = None,
):
attempted_names.append(choice.name)
if choice.name == first_choice.name:
raise PrebuiltFallback("newest candidate failed")
raise AssertionError("installed fallback candidate should have been skipped")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_choice",
fake_validate_choice,
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"activate_install_tree",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("installed fallback candidate should not be activated")
),
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert attempted_names == [first_choice.name]
def test_install_prebuilt_same_tag_upstream_failure_uses_older_unsloth_release_plan(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
install_dir = tmp_path / "llama.cpp"
host = linux_host()
same_tag_upstream_choice = asset_choice(
name = "llama-b9002-bin-ubuntu-x64.tar.gz",
repo = "ggml-org/llama.cpp",
tag = "b9002",
)
older_release_choice = asset_choice(expected_sha256 = "b" * 64)
latest_plan = release_plan(
[same_tag_upstream_choice],
release_checksums(release_tag = "release-2", upstream_tag = "b9002", source_commit = None),
llama_tag = "b9002",
release_tag = "release-2",
)
older_plan = release_plan([older_release_choice], release_checksums(source_commit = None))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: (
"latest",
[latest_plan, older_plan],
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda probe_path, cache_path: probe_path.write_bytes(b"probe"),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"latest_upstream_release_tag",
lambda: (_ for _ in ()).throw(
AssertionError("install fallback should not walk upstream releases")
),
)
attempted = []
def fake_validate(
attempts,
host,
install_dir,
work_dir,
probe_path,
*,
requested_tag,
llama_tag,
release_tag,
approved_checksums,
initial_fallback_used = False,
existing_install_dir = None,
force_cpu = False,
llama_backend = None,
backend_request = None,
rocm_gfx = None,
walk_back = None,
):
attempted.append((llama_tag, release_tag, attempts[0].source_label))
if llama_tag == "b9002":
raise PrebuiltFallback("same-tag upstream asset failed validation")
staging_dir = create_install_staging_dir(install_dir)
(staging_dir / "marker.txt").write_text("ready\n")
return attempts[0], staging_dir, initial_fallback_used
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "validate_prebuilt_attempts", fake_validate)
activated = {}
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"activate_install_tree",
lambda staging_dir, install_dir, host: activated.update(
{"staging_dir": staging_dir, "install_dir": install_dir}
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"ensure_converter_scripts",
lambda install_dir, llama_tag, **kwargs: None,
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert attempted == [("b9002", "release-2", "upstream"), ("b9001", "release-1", "upstream")]
assert activated["install_dir"] == install_dir
def io_bytes(data: bytes):
return io.BytesIO(data)
def add_bytes_to_tar(
archive: tarfile.TarFile,
name: str,
data: bytes,
*,
mode: int = 0o644,
) -> None:
info = tarfile.TarInfo(name)
info.size = len(data)
info.mode = mode
archive.addfile(info, io_bytes(data))
def add_symlink_to_tar(archive: tarfile.TarFile, name: str, target: str) -> None:
info = tarfile.TarInfo(name)
info.type = tarfile.SYMTYPE
info.linkname = target
archive.addfile(info)
def test_existing_install_matches_choice_fails_when_install_tree_incomplete(tmp_path: Path):
"""confirm_install_tree guard rejects installs missing critical files."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
host = linux_host()
choice = asset_choice()
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
write_metadata(install_dir, choice, checksums)
assert (
existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
is True
)
(install_dir / "convert_hf_to_gguf.py").unlink()
assert (
existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
is False
)
def test_existing_install_matches_choice_fails_when_install_tree_incomplete_macos(tmp_path: Path):
"""confirm_install_tree guard rejects macOS arm64 installs missing critical files."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_macos_install_shape(install_dir)
host = macos_host()
choice = asset_choice(name = "llama-b9001-bin-macos-arm64.tar.gz", install_kind = "macos-arm64")
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
write_metadata(install_dir, choice, checksums)
assert (
existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
is True
)
(install_dir / "build" / "bin" / "libmtmd.0.dylib").unlink()
assert (
existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
is False
)
def test_existing_macos_install_that_cannot_load_is_not_reused(tmp_path: Path, monkeypatch):
"""A macOS install that dyld refuses must not be reused just because its fingerprint matches."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_macos_install_shape(install_dir)
host = macos_host(macos_version = (15, 5))
choice = asset_choice(name = "llama-b9001-bin-macos-arm64.tar.gz", install_kind = "macos-arm64")
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
write_metadata(install_dir, choice, checksums)
def matches() -> bool:
return existing_install_matches_choice(
install_dir,
host,
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "macos_dyld_load_issues", lambda *a, **k: [])
assert matches() is True
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"macos_dyld_load_issues",
lambda *a, **k: ["llama-server: Library not loaded: /usr/lib/librdma.dylib"],
)
assert matches() is False
def test_paired_runtime_dll_patterns_excludes_executables() -> None:
"""The paired runtime archive must contribute only CUDA DLLs (no *.exe/*.dll) so it can't overwrite binaries."""
paired_runtime_dll_patterns = INSTALL_LLAMA_PREBUILT.paired_runtime_dll_patterns
paired_choice = asset_choice(
name = "llama-b9001-bin-win-cuda-12.4-x64.zip",
url = "u",
repo = "x",
tag = "t",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
runtime_name = "cudart-llama-bin-win-cuda-12.4-x64.zip",
runtime_url = "https://example.com/cudart.zip",
runtime_sha256 = "c" * 64,
)
patterns = paired_runtime_dll_patterns(paired_choice)
assert "cudart64_*.dll" in patterns
assert "cublas64_*.dll" in patterns
assert "cublasLt64_*.dll" in patterns
assert "*.exe" not in patterns
assert "*.dll" not in patterns
for kind in (
"linux-cpu",
"linux-cuda",
"linux-rocm",
"macos-arm64",
"macos-x64",
"windows-cpu",
"windows-hip",
):
non_windows = asset_choice(
name = "x",
url = "u",
repo = "x",
tag = "t",
source_label = "published",
install_kind = kind,
)
assert paired_runtime_dll_patterns(non_windows) == []
def test_runtime_overlay_cannot_overwrite_main_archive_payload(tmp_path: Path) -> None:
"""A malformed runtime archive with llama-server.exe must NOT replace the main archive's binary."""
install_from_archives = INSTALL_LLAMA_PREBUILT.install_from_archives
work = tmp_path / "work"
install = tmp_path / "install"
archives = tmp_path / "archives"
work.mkdir()
install.mkdir()
archives.mkdir()
main_zip = archives / "llama-b9001-bin-win-cuda-12.4-x64.zip"
runtime_zip = archives / "cudart-llama-bin-win-cuda-12.4-x64.zip"
with zipfile.ZipFile(main_zip, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("llama-server.exe", b"MAIN-SERVER")
zf.writestr("llama-quantize.exe", b"MAIN-Q")
zf.writestr("llama.dll", b"DLL-llama")
zf.writestr("ggml-cuda.dll", b"DLL-ggml")
import hashlib
main_sha = hashlib.sha256(main_zip.read_bytes()).hexdigest()
with zipfile.ZipFile(runtime_zip, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("cudart64_12.dll", b"DLL-cudart")
zf.writestr("cublas64_12.dll", b"DLL-cublas")
zf.writestr("cublasLt64_12.dll", b"DLL-cublasLt")
zf.writestr("llama-server.exe", b"RUNTIME-OVERWRITE")
runtime_sha = hashlib.sha256(runtime_zip.read_bytes()).hexdigest()
choice = asset_choice(
name = main_zip.name,
url = f"https://example.com/{main_zip.name}",
source_label = "published",
install_kind = "windows-cuda",
runtime_line = "cuda12",
expected_sha256 = main_sha,
runtime_name = runtime_zip.name,
runtime_url = f"https://example.com/{runtime_zip.name}",
runtime_sha256 = runtime_sha,
)
host = windows_host(driver_cuda_version = (12, 4), has_usable_nvidia = True)
import shutil as _shutil
orig_download = INSTALL_LLAMA_PREBUILT.download_file_verified
def fake_download(
url,
target_path,
*,
expected_sha256 = None,
label = None,
**kw,
):
src = main_zip if "cudart" not in url else runtime_zip
_shutil.copy2(src, target_path)
if expected_sha256:
actual = hashlib.sha256(Path(target_path).read_bytes()).hexdigest()
if actual != expected_sha256:
raise INSTALL_LLAMA_PREBUILT.PrebuiltFallback(f"sha256 mismatch on {label}")
INSTALL_LLAMA_PREBUILT.download_file_verified = fake_download
try:
install_from_archives(choice, host, install, work)
finally:
INSTALL_LLAMA_PREBUILT.download_file_verified = orig_download
release_dir = install / "build" / "bin" / "Release"
server = release_dir / "llama-server.exe"
assert server.exists()
assert server.read_bytes() == b"MAIN-SERVER", (
"runtime archive overwrote main llama-server.exe; " f"got {server.read_bytes()!r}"
)
for name in ("cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll"):
assert (release_dir / name).exists(), f"missing {name}"
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX mode bits")
@pytest.mark.parametrize("ships_bench", [True, False])
def test_linux_overlay_keeps_llama_bench_executable_when_bundled(
tmp_path: Path, ships_bench: bool
) -> None:
# Bundle members are not executable; llama-bench is launched directly.
import hashlib
import shutil as _shutil
work = tmp_path / "work"
install = tmp_path / "install"
work.mkdir()
install.mkdir()
bundle = tmp_path / "app-b11160-linux-x64-cuda13-newer.tar.gz"
names = ["llama-server", "llama-quantize", "libllama.so"] + (
["llama-bench", "libllama-bench-impl.so"] if ships_bench else []
)
with tarfile.open(bundle, "w:gz") as archive:
for name in names:
payload = f"{name}\n".encode()
member = tarfile.TarInfo(name)
member.size = len(payload)
member.mode = 0o644
archive.addfile(member, io.BytesIO(payload))
choice = asset_choice(
name = bundle.name,
url = f"https://example.com/{bundle.name}",
tag = "b11160",
source_label = "published",
install_kind = "linux-cuda",
runtime_line = "cuda13",
expected_sha256 = hashlib.sha256(bundle.read_bytes()).hexdigest(),
)
host = linux_host(driver_cuda_version = (13, 0), has_physical_nvidia = True, has_usable_nvidia = True)
def fake_download(
url,
target_path,
*,
expected_sha256 = None,
label = None,
**kw,
):
_shutil.copy2(bundle, target_path)
orig_download = INSTALL_LLAMA_PREBUILT.download_file_verified
INSTALL_LLAMA_PREBUILT.download_file_verified = fake_download
try:
INSTALL_LLAMA_PREBUILT.install_from_archives(choice, host, install, work)
finally:
INSTALL_LLAMA_PREBUILT.download_file_verified = orig_download
bench = install / "build" / "bin" / "llama-bench"
if ships_bench:
assert bench.is_file() and os.access(bench, os.X_OK)
else:
assert not bench.exists()
def test_linux_runtime_overlay_copies_llama_tool_impl_libraries(tmp_path: Path) -> None:
install_from_archives = INSTALL_LLAMA_PREBUILT.install_from_archives
work = tmp_path / "work"
install = tmp_path / "install"
archives = tmp_path / "archives"
work.mkdir()
install.mkdir()
archives.mkdir()
bundle = archives / "app-b9334-linux-x64-cuda13-newer.tar.gz"
with tarfile.open(bundle, "w:gz") as archive:
for name in (
"llama-cli",
"llama-server",
"llama-quantize",
"libllama-cli-impl.so",
"libllama-server-impl.so",
"libllama-quantize-impl.so",
"libllama-common.so",
"libllama.so",
"libggml.so",
"libggml-base.so",
"libmtmd.so",
"libggml-cpu-x64.so",
"libggml-cuda.so",
):
payload = f"{name}\n".encode()
member = tarfile.TarInfo(name)
member.size = len(payload)
archive.addfile(member, io.BytesIO(payload))
import hashlib
import shutil as _shutil
bundle_sha = hashlib.sha256(bundle.read_bytes()).hexdigest()
choice = asset_choice(
name = bundle.name,
url = f"https://example.com/{bundle.name}",
tag = "b9334",
source_label = "published",
install_kind = "linux-cuda",
runtime_line = "cuda13",
expected_sha256 = bundle_sha,
)
host = linux_host(driver_cuda_version = (13, 0), has_physical_nvidia = True, has_usable_nvidia = True)
orig_download = INSTALL_LLAMA_PREBUILT.download_file_verified
def fake_download(
url,
target_path,
*,
expected_sha256 = None,
label = None,
**kw,
):
_shutil.copy2(bundle, target_path)
if expected_sha256:
actual = hashlib.sha256(Path(target_path).read_bytes()).hexdigest()
if actual != expected_sha256:
raise INSTALL_LLAMA_PREBUILT.PrebuiltFallback(f"sha256 mismatch on {label}")
INSTALL_LLAMA_PREBUILT.download_file_verified = fake_download
try:
install_from_archives(choice, host, install, work)
finally:
INSTALL_LLAMA_PREBUILT.download_file_verified = orig_download
runtime_dir = install / "build" / "bin"
for name in (
"libllama-cli-impl.so",
"libllama-server-impl.so",
"libllama-quantize-impl.so",
):
assert (runtime_dir / name).exists(), f"missing {name}"
assert not (runtime_dir / "llama-cli").exists()
@pytest.mark.skipif(os.name == "nt", reason = "Windows st_mode carries no POSIX mode bits")
@pytest.mark.parametrize("bundles_fit_params", [True, False])
def test_macos_install_makes_llama_fit_params_executable(
tmp_path: Path, bundles_fit_params: bool
) -> None:
"""#12901: the guarded extractor drops archive modes, so the optional Metal
probe must be chmod'ed like llama-server, and bundles without it still install."""
install_from_archives = INSTALL_LLAMA_PREBUILT.install_from_archives
work = tmp_path / "work"
install = tmp_path / "install"
archives = tmp_path / "archives"
work.mkdir()
install.mkdir()
archives.mkdir()
names = ["llama-server", "llama-quantize", "libllama.dylib", "libggml.dylib"]
if bundles_fit_params:
names.append("llama-fit-params")
bundle = archives / "llama-b9001-bin-macos-arm64.tar.gz"
with tarfile.open(bundle, "w:gz") as archive:
for name in names:
add_bytes_to_tar(archive, name, f"{name}\n".encode(), mode = 0o755)
import hashlib
choice = asset_choice(
name = bundle.name,
source_label = "published",
install_kind = "macos-arm64",
expected_sha256 = hashlib.sha256(bundle.read_bytes()).hexdigest(),
)
orig_download = INSTALL_LLAMA_PREBUILT.download_file_verified
def fake_download(url, target_path, **kw):
shutil.copy2(bundle, target_path)
INSTALL_LLAMA_PREBUILT.download_file_verified = fake_download
try:
install_from_archives(choice, macos_host(), install, work)
finally:
INSTALL_LLAMA_PREBUILT.download_file_verified = orig_download
fit_params = install / "build" / "bin" / "llama-fit-params"
if bundles_fit_params:
assert stat.S_IMODE(fit_params.stat().st_mode) == 0o755
else:
assert not fit_params.exists()
@pytest.mark.skipif(os.name == "nt", reason = "Windows st_mode carries no POSIX mode bits")
@pytest.mark.parametrize("skip_path", ["no_network_check", "plan_match"])
def test_a_reused_install_repairs_a_non_executable_llama_fit_params(
tmp_path: Path, monkeypatch, skip_path: str
) -> None:
"""#12901: installs made before the fix keep a 0644 probe, and an update on the same
release returns before any extraction, so the skip paths must restore the bit."""
M = INSTALL_LLAMA_PREBUILT
install_dir = tmp_path / "llama.cpp"
helper = install_dir / "build" / "bin" / "llama-fit-params"
helper.parent.mkdir(parents = True)
helper.write_bytes(b"probe\n")
helper.chmod(0o644)
host = macos_host()
choice = asset_choice(name = "llama-b9001-bin-macos-arm64.tar.gz", install_kind = "macos-arm64")
release_plan = M.InstallReleasePlan(
requested_tag = "latest",
llama_tag = "b9001",
release_tag = "release-1",
attempts = [choice],
approved_checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM)),
)
route = types.SimpleNamespace(
host = host, backend = "auto", published_repo = "unslothai/llama.cpp", published_release_tag = ""
)
monkeypatch.setattr(M, "route_backend_request", lambda **_k: route)
monkeypatch.setattr(
M,
"existing_install_current_without_plan",
lambda *_a, **_k: skip_path == "no_network_check",
)
monkeypatch.setattr(
M,
"select_backend_install",
lambda **_k: M.BackendSelection(
backend = "auto",
host = host,
published_repo = "unslothai/llama.cpp",
published_release_tag = "",
requested_tag = "latest",
release_plans = [release_plan],
persist_llama_backend = None,
persist_rocm_gfx = None,
),
)
monkeypatch.setattr(M, "existing_install_matches_plan", lambda *_a, **_k: True)
monkeypatch.setattr(M, "diffusion_visual_server_backfill_needed", lambda *_a, **_k: False)
monkeypatch.setattr(M, "sync_marker_selection", lambda *_a, **_k: None)
M.install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert stat.S_IMODE(helper.stat().st_mode) == 0o755
def test_python_runtime_dirs_covers_cu13_and_library_bin(monkeypatch, tmp_path: Path) -> None:
"""Installer DLL discovery must scan the same path set as the backend (cu12/cu13/conda layouts + torch/lib)."""
import site as _site
python_runtime_dirs = INSTALL_LLAMA_PREBUILT.python_runtime_dirs
site_dir = tmp_path / "Lib" / "site-packages"
cu12_bin = site_dir / "nvidia" / "cuda_runtime" / "bin"
cu12_bin.mkdir(parents = True)
cu13_arch = site_dir / "nvidia" / "cu13" / "bin" / "x86_64"
cu13_arch.mkdir(parents = True)
library_bin = site_dir / "nvidia" / "cublas" / "Library" / "bin"
library_bin.mkdir(parents = True)
torch_lib = site_dir / "torch" / "lib"
torch_lib.mkdir(parents = True)
monkeypatch.setattr(sys, "path", [str(site_dir)])
monkeypatch.setattr(_site, "getsitepackages", lambda: [str(site_dir)])
monkeypatch.setattr(_site, "getusersitepackages", lambda: "")
dirs = python_runtime_dirs()
assert str(cu12_bin) in dirs
assert str(cu13_arch) in dirs
assert str(library_bin) in dirs
assert str(torch_lib) in dirs
def _nvidia_linux_host():
return linux_host(compute_caps = ["10.0"], has_physical_nvidia = True, has_usable_nvidia = True)
def _run_validate_prebuilt_choice(
monkeypatch,
tmp_path,
*,
expected_sha256,
probe = None,
):
"""Run validate_prebuilt_choice with heavy steps stubbed; return the quantize/server smoke-test call counts."""
calls = {"quantize": 0, "server": 0}
server_path = tmp_path / "install" / "build" / "bin" / "llama-server"
quantize_path = tmp_path / "install" / "build" / "bin" / "llama-quantize"
src = INSTALL_LLAMA_PREBUILT
monkeypatch.setattr(
src, "preferred_source_archive", lambda *a, **k: ("repo", "ref", None, False)
)
monkeypatch.setattr(src, "hydrate_source_tree", lambda *a, **k: None)
monkeypatch.setattr(src, "install_from_archives", lambda *a, **k: (server_path, quantize_path))
monkeypatch.setattr(src, "preflight_linux_installed_binaries", lambda *a, **k: None)
monkeypatch.setattr(src, "preflight_macos_installed_binaries", lambda *a, **k: None)
monkeypatch.setattr(src, "ensure_repo_shape", lambda *a, **k: None)
monkeypatch.setattr(src, "write_prebuilt_metadata", lambda *a, **k: None)
monkeypatch.setattr(
src,
"validate_quantize",
lambda *a, **k: calls.__setitem__("quantize", calls["quantize"] + 1),
)
monkeypatch.setattr(
src, "validate_server", lambda *a, **k: calls.__setitem__("server", calls["server"] + 1)
)
bundle_name = "app-b9998-linux-x64-cuda13-newer.tar.gz"
source_archive = tmp_path / "source.tar.gz"
bundle_archive = tmp_path / "bundle.tar.gz"
source_archive.write_bytes(b"source")
bundle_archive.write_bytes(b"bundle")
choice = asset_choice(
name = bundle_name,
url = "file://bundle",
repo = "local",
tag = "b9998",
source_label = "local",
is_ready_bundle = True,
install_kind = "linux-cuda",
bundle_profile = "cuda13-newer",
runtime_line = "cuda13",
expected_sha256 = expected_sha256,
)
src.validate_prebuilt_choice(
choice,
_nvidia_linux_host(),
tmp_path / "install",
tmp_path / "work",
probe if probe is not None else tmp_path / "stories260K.gguf",
requested_tag = "b9998",
llama_tag = "b9998",
release_tag = "b9998",
approved_checksums = approved_checksums_for(
"b9998",
source_archive = source_archive,
bundle_archive = bundle_archive,
bundle_name = bundle_name,
),
prebuilt_fallback_used = False,
quantized_path = tmp_path / "stories260K-q4.gguf",
)
return calls
def _run_vulkan_device_gate(
monkeypatch,
tmp_path,
*,
required,
listed,
install_kind = "linux-vulkan",
):
"""validate_prebuilt_choice on a stubbed install; `listed` is what the bundle's --list-devices finds."""
src = INSTALL_LLAMA_PREBUILT
server_path = tmp_path / "install" / "build" / "bin" / "llama-server"
listings = []
def fake_listing(*_a, **_k):
listings.append(True)
return listed
monkeypatch.setattr(
src, "preferred_source_archive", lambda *a, **k: ("repo", "ref", None, False)
)
monkeypatch.setattr(src, "hydrate_source_tree", lambda *a, **k: None)
monkeypatch.setattr(src, "install_from_archives", lambda *a, **k: (server_path, server_path))
monkeypatch.setattr(src, "runtime_payload_is_healthy", lambda *a, **k: True)
monkeypatch.setattr(src, "preflight_linux_installed_binaries", lambda *a, **k: None)
monkeypatch.setattr(src, "preflight_macos_installed_binaries", lambda *a, **k: None)
monkeypatch.setattr(src, "ensure_repo_shape", lambda *a, **k: None)
monkeypatch.setattr(src, "write_prebuilt_metadata", lambda *a, **k: None)
monkeypatch.setattr(src, "bundle_lists_vulkan_device", fake_listing)
monkeypatch.setattr(src, "_RUN_STAGED_PREBUILT_VALIDATION", False)
bundle_name = f"app-b9998-{install_kind}.tar.gz"
source_archive = tmp_path / "source.tar.gz"
bundle_archive = tmp_path / "bundle.tar.gz"
source_archive.write_bytes(b"source")
bundle_archive.write_bytes(b"bundle")
choice = asset_choice(
name = bundle_name,
url = "file://bundle",
repo = "local",
tag = "b9998",
source_label = "local",
is_ready_bundle = True,
install_kind = install_kind,
expected_sha256 = "ab" * 32,
)
src.validate_prebuilt_choice(
choice,
linux_host(has_intel_gpu = True, vulkan_routed = True, vulkan_device_required = required),
tmp_path / "install",
tmp_path / "work",
tmp_path / "stories260K.gguf",
requested_tag = "b9998",
llama_tag = "b9998",
release_tag = "b9998",
approved_checksums = approved_checksums_for(
"b9998",
source_archive = source_archive,
bundle_archive = bundle_archive,
bundle_name = bundle_name,
),
prebuilt_fallback_used = False,
quantized_path = tmp_path / "stories260K-q4.gguf",
)
return listings
def test_probe_routed_vulkan_bundle_that_lists_no_gpu_falls_back(tmp_path, monkeypatch):
with pytest.raises(PrebuiltFallback, match = "lists no Vulkan GPU"):
_run_vulkan_device_gate(monkeypatch, tmp_path, required = True, listed = False)
def test_probe_routed_vulkan_bundle_that_lists_a_gpu_is_kept(tmp_path, monkeypatch):
assert _run_vulkan_device_gate(monkeypatch, tmp_path, required = True, listed = True) == [True]
@pytest.mark.parametrize(
"required, install_kind",
[(False, "linux-vulkan"), (True, "linux-arm64")],
ids = ["intel-or-forced-route", "cpu-bundle"],
)
def test_vulkan_device_gate_only_checks_probe_routed_vulkan_bundles(
tmp_path, monkeypatch, required, install_kind
):
assert (
_run_vulkan_device_gate(
monkeypatch, tmp_path, required = required, listed = False, install_kind = install_kind
)
== []
)
@pytest.mark.skipif(sys.platform == "win32", reason = "fake server is a POSIX shell script")
@pytest.mark.parametrize(
"output, code, expected",
[
("Available devices:\n Vulkan0: Adreno X1-85 (16000 MiB, 15000 MiB free)\n", 0, True),
("Available devices:\n (none)\n", 0, False),
("Available devices:\n RPC0: host:50052 (0 MiB, 0 MiB free)\n", 0, False),
("Available devices:\n Vulkan0: Adreno\n", 1, False),
],
ids = ["vulkan-device", "none", "other-device", "nonzero-exit"],
)
def test_bundle_lists_vulkan_device_reads_list_devices(tmp_path, output, code, expected):
server = tmp_path / "llama-server"
server.write_text(f"#!/bin/sh\nprintf '{output}'\nexit {code}\n", encoding = "utf-8")
server.chmod(0o755)
assert (
INSTALL_LLAMA_PREBUILT.bundle_lists_vulkan_device(server, tmp_path, linux_host())
is expected
)
def test_bundle_lists_vulkan_device_missing_binary_is_no_gpu(tmp_path):
missing = tmp_path / "llama-server"
assert (
INSTALL_LLAMA_PREBUILT.bundle_lists_vulkan_device(missing, tmp_path, linux_host()) is False
)
def test_validate_prebuilt_choice_approved_validation_skipped_when_flag_off(tmp_path, monkeypatch):
calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = "ab" * 32)
assert calls == {"quantize": 0, "server": 0}
def test_validate_prebuilt_choice_hashless_build_always_validated(tmp_path, monkeypatch):
calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = None)
assert calls == {"quantize": 1, "server": 1}
def test_validate_prebuilt_choice_approved_validation_runs_when_flag_enabled(tmp_path, monkeypatch):
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_RUN_STAGED_PREBUILT_VALIDATION", True)
calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = "ab" * 32)
assert calls == {"quantize": 1, "server": 1}
def test_validate_prebuilt_choice_never_fetches_probe_for_approved_bundle(tmp_path, monkeypatch):
def refuse() -> Path:
raise AssertionError("probe model must not be fetched when the smoke test is skipped")
calls = _run_validate_prebuilt_choice(
monkeypatch, tmp_path, expected_sha256 = "ab" * 32, probe = refuse
)
assert calls == {"quantize": 0, "server": 0}
def test_validate_prebuilt_choice_fetches_probe_once_when_validating(tmp_path, monkeypatch):
fetches = []
probe_path = tmp_path / "stories260K.gguf"
def fetch() -> Path:
fetches.append(1)
return probe_path
calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = None, probe = fetch)
assert calls == {"quantize": 1, "server": 1}
assert len(fetches) == 1
def test_lazy_validation_model_downloads_once_on_first_use(tmp_path, monkeypatch):
downloads = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda path, cache_path = None: downloads.append((path, cache_path)),
)
probe_path = tmp_path / "stories260K.gguf"
ensure = INSTALL_LLAMA_PREBUILT.lazy_validation_model(probe_path, tmp_path / "cache.gguf")
assert downloads == []
assert ensure() == probe_path
assert ensure() == probe_path
assert len(downloads) == 1
def test_probe_rate_limit_no_longer_forces_a_source_build(tmp_path, monkeypatch):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
host = linux_host()
choice = asset_choice()
checksums = ApprovedReleaseChecksums(
repo = "unslothai/llama.cpp",
release_tag = "release-1",
upstream_tag = "b9001",
source_commit = "deadbeef",
artifacts = {
choice.name: ApprovedArtifactHash(
asset_name = choice.name,
sha256 = choice.expected_sha256,
repo = "ggml-org/llama.cpp",
kind = "upstream-prebuilt",
),
},
)
plan = release_plan([choice], checksums)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: ("latest", [plan]),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda *args, **kwargs: (_ for _ in ()).throw(
urllib.error.HTTPError(
INSTALL_LLAMA_PREBUILT.TEST_MODEL_URL, 429, "Too Many Requests", None, None
)
),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_attempts",
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("reached the install flow")),
)
with pytest.raises(AssertionError, match = "reached the install flow"):
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
def test_probe_failure_does_not_demote_to_a_lower_priority_candidate(tmp_path, monkeypatch):
# validate_prebuilt_attempts catches per candidate, so resolve the probe before the loop.
fetches = []
def refuse() -> Path:
fetches.append(1)
raise INSTALL_LLAMA_PREBUILT.PrebuiltFallback(
"validation model unavailable: HTTP Error 429: Too Many Requests"
)
attempted: list[str] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_choice",
lambda attempt, *args, **kwargs: attempted.append(attempt.name),
)
def hashless(name: str, install_kind: str) -> AssetChoice:
return AssetChoice(
repo = "unslothai/llama.cpp",
tag = "release-1",
name = name,
url = f"https://example.com/{name}",
source_label = "direct-upstream",
install_kind = install_kind,
expected_sha256 = None,
)
with pytest.raises(INSTALL_LLAMA_PREBUILT.PrebuiltFallback, match = "429"):
INSTALL_LLAMA_PREBUILT.validate_prebuilt_attempts(
[
hashless("llama-b9001-bin-win-cuda-x64.zip", "windows-cuda"),
hashless("llama-b9001-bin-win-cpu-x64.zip", "windows-cpu"),
],
_nvidia_linux_host(),
tmp_path / "install",
tmp_path / "work",
refuse,
requested_tag = "b9001",
llama_tag = "b9001",
release_tag = "release-1",
approved_checksums = release_checksums(source_commit = None),
)
assert attempted == []
assert len(fetches) == 1
def test_probe_failure_does_not_demote_to_an_older_release(tmp_path, monkeypatch):
# install_prebuilt's per-release handler swallows PrebuiltFallback, so fetch the probe first.
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
def hashless_plan(release_tag: str, llama_tag: str):
choice = AssetChoice(
repo = "unslothai/llama.cpp",
tag = release_tag,
name = f"llama-{llama_tag}-bin-ubuntu-x64.tar.gz",
url = f"https://example.com/{llama_tag}.tar.gz",
source_label = "direct-upstream",
install_kind = "linux-cpu",
expected_sha256 = None,
)
return release_plan(
[choice],
release_checksums(release_tag = release_tag, upstream_tag = llama_tag, source_commit = None),
llama_tag = llama_tag,
release_tag = release_tag,
)
plans = [hashless_plan("release-2", "b9002"), hashless_plan("release-1", "b9001")]
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: _nvidia_linux_host())
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"resolve_simple_install_release_plans",
lambda llama_tag, host, published_repo, published_release_tag: ("latest", plans),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda *args, **kwargs: (_ for _ in ()).throw(
INSTALL_LLAMA_PREBUILT.PrebuiltFallback(
"validation model unavailable: HTTP Error 429: Too Many Requests"
)
),
)
validated: list[str] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_prebuilt_attempts",
lambda attempts, *args, **kwargs: validated.append(list(attempts)[0].name),
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
assert validated == []
def test_staged_validation_enabled_default_off(monkeypatch):
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_RUN_STAGED_PREBUILT_VALIDATION", False)
monkeypatch.delenv("UNSLOTH_LLAMA_STAGED_VALIDATION", raising = False)
assert INSTALL_LLAMA_PREBUILT.staged_validation_enabled() is False
@pytest.mark.parametrize("value", ["1", "true", "YES", "on"])
def test_staged_validation_enabled_env_opt_in(monkeypatch, value):
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_RUN_STAGED_PREBUILT_VALIDATION", False)
monkeypatch.setenv("UNSLOTH_LLAMA_STAGED_VALIDATION", value)
assert INSTALL_LLAMA_PREBUILT.staged_validation_enabled() is True
def test_validate_prebuilt_choice_approved_validation_runs_when_env_enabled(tmp_path, monkeypatch):
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_RUN_STAGED_PREBUILT_VALIDATION", False)
monkeypatch.setenv("UNSLOTH_LLAMA_STAGED_VALIDATION", "1")
calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = "ab" * 32)
assert calls == {"quantize": 1, "server": 1}
def test_validate_existing_install_runs_server_smoke(tmp_path, monkeypatch):
install_dir = tmp_path / "llama.cpp"
bin_dir = install_dir / "build" / "bin"
bin_dir.mkdir(parents = True)
(bin_dir / "llama-server").write_text("#!/bin/sh\n", encoding = "utf-8")
(bin_dir / "llama-quantize").write_text("#!/bin/sh\n", encoding = "utf-8")
calls: dict[str, int] = {"quantize": 0, "server": 0, "download": 0}
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"download_validation_model",
lambda path, cache = None: calls.__setitem__("download", calls["download"] + 1),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_quantize",
lambda *a, **k: calls.__setitem__("quantize", calls["quantize"] + 1),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"validate_server",
lambda *a, **k: calls.__setitem__("server", calls["server"] + 1),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"detect_host",
lambda: linux_host(),
)
INSTALL_LLAMA_PREBUILT.validate_existing_install(install_dir, install_kind = "linux-cuda")
assert calls == {"quantize": 1, "server": 1, "download": 1}
def test_validate_existing_install_missing_server_raises(tmp_path, monkeypatch):
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: linux_host())
with pytest.raises(INSTALL_LLAMA_PREBUILT.PrebuiltFallback, match = "llama-server not found"):
INSTALL_LLAMA_PREBUILT.validate_existing_install(tmp_path / "missing")
def test_diffusion_visual_server_uses_approved_checksum_download(monkeypatch, tmp_path: Path):
asset_name = "llama-diffusion-gemma-visual-server-linux-x64"
expected_sha = "a" * 64
asset_url = "https://github.com/unslothai/llama.cpp/releases/download/b9334/" + asset_name
calls: list[tuple[str, Path, str | None, str | None]] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_release_assets",
lambda repo, tag: (_ for _ in ()).throw(AssertionError("listed the release over the API")),
)
def fake_download_file(url, destination):
raise AssertionError("diffusion visual server must not use unverified download_file")
def fake_download_file_verified(url, destination, *, expected_sha256, label):
calls.append((url, Path(destination), expected_sha256, label))
Path(destination).write_bytes(b"verified visual server")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "download_file_verified", fake_download_file_verified
)
ensure_diffusion_visual_server(
tmp_path / "install",
linux_host(),
"b9334",
approved_release_checksums_for_asset(asset_name, expected_sha),
)
target = tmp_path / "install" / "build" / "bin" / "llama-diffusion-gemma-visual-server"
assert calls == [
(
asset_url,
target,
expected_sha,
f"diffusion visual server {asset_name}",
)
]
assert target.read_bytes() == b"verified visual server"
assert target.stat().st_mode & 0o777 == 0o755
def test_diffusion_visual_server_skips_when_the_manifest_names_no_visual_server(
monkeypatch, tmp_path: Path
):
verified_calls: list[str] = []
raw_calls: list[str] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_release_assets",
lambda repo, tag: (_ for _ in ()).throw(AssertionError("listed the release over the API")),
)
def fake_download_file(url, destination):
raw_calls.append(url)
def fake_download_file_verified(url, destination, *, expected_sha256, label):
verified_calls.append(url)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_file", fake_download_file)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "download_file_verified", fake_download_file_verified
)
ensure_diffusion_visual_server(
tmp_path / "install",
linux_host(),
"b9334",
ApprovedReleaseChecksums(
repo = "unslothai/llama.cpp",
release_tag = "b9334",
upstream_tag = "b9334",
artifacts = {},
),
)
target = tmp_path / "install" / "build" / "bin" / "llama-diffusion-gemma-visual-server"
assert not target.exists()
assert raw_calls == []
assert verified_calls == []
def test_dedupe_existing_dirs_skips_inaccessible_path_entry(monkeypatch):
denied = r"C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps"
class FakePath:
def __init__(self, raw):
self.raw = str(raw)
def expanduser(self):
return self
def is_dir(self):
if self.raw == denied:
raise PermissionError(13, "Access is denied", denied, 5)
return True
def resolve(self):
return Path(self.raw).resolve()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "Path", FakePath)
with pytest.raises(PermissionError, match = "Access is denied"):
INSTALL_LLAMA_PREBUILT.dedupe_existing_dirs([denied])
assert INSTALL_LLAMA_PREBUILT.dedupe_existing_dirs(
[denied, PACKAGE_ROOT], skip_unusable = True
) == [str(PACKAGE_ROOT.resolve())]
def test_windows_runtime_dirs_marks_path_candidates_as_optional(monkeypatch, tmp_path):
denied = r"C:\WINDOWS\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps"
observed = {}
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "pathsep", ";")
def fake_dedupe(paths, *, skip_unusable = False):
observed["paths"] = [str(path) for path in paths]
observed["skip_unusable"] = skip_unusable
return []
monkeypatch.setenv("PATH", denied)
monkeypatch.setenv("ProgramFiles", str(tmp_path))
for name in ("CUDA_RUNTIME_DLL_DIR", "CUDA_PATH", "CUDA_HOME", "CUDA_ROOT"):
monkeypatch.delenv(name, raising = False)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "python_runtime_dirs", lambda: [])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "dedupe_existing_dirs", fake_dedupe)
assert INSTALL_LLAMA_PREBUILT.windows_runtime_dirs() == []
assert observed == {"paths": [denied], "skip_unusable": True}
_SETUP_SH_ROUTING_START = 'if [ "$_PREBUILT_STATUS" -eq 0 ]; then'
_SETUP_PS1_ROUTING_START = "if ($prebuiltExit -eq 0) {"
_SETUP_SH_HARNESS = """
set -u
C_OK=""; C_WARN=""; C_ERR=""
_NEED_LLAMA_SOURCE_BUILD=false
_LLAMA_CPP_NO_SPACE=false
_LLAMA_CPP_DEGRADED=false
_explicit_llama_backend=""
_STUDIO_HOME_IS_CUSTOM=false
_RUNTIME_ROOT_IS_CUSTOM=false
_STUDIO_OWNED_MARKER=".unsloth-owned"
step() { echo "step: $2"; }
substep() { echo "substep: $1"; }
verbose_substep() { :; }
print_llama_error_log() { :; }
print_installed_llama_prebuilt_release() { :; }
_has_local_llama_server() { return 1; }
setup_fail() { echo "setup_fail: $1"; exit "$1"; }
"""
_SETUP_SH_HARNESS_TAIL = """
echo "source_build=$_NEED_LLAMA_SOURCE_BUILD"
echo "no_space=$_LLAMA_CPP_NO_SPACE"
"""
def _extract_block(text: str, start_marker: str, end_marker: str) -> str:
start = text.index(start_marker)
end = text.index(end_marker, start)
return text[start : end + len(end_marker)]
def _setup_sh_routing_block() -> str:
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
# The routing chain ends at the first dedented " fi" after it.
start = setup_sh.index(_SETUP_SH_ROUTING_START)
end = setup_sh.index("\n fi\n", start)
return setup_sh[start : end + len("\n fi\n")]
def _run_setup_sh_routing(
status: int,
tmp_path: Path,
*,
install_exists: bool,
explicit_backend: str = "",
) -> dict[str, str]:
"""Drive the real setup.sh exit-code chain with a stubbed helper result."""
llama_dir = tmp_path / "llama.cpp"
if install_exists:
llama_dir.mkdir(parents = True, exist_ok = True)
log_path = tmp_path / "prebuilt.log"
log_path.write_text("boom\n", encoding = "utf-8")
script = "\n".join(
[
_SETUP_SH_HARNESS,
f'LLAMA_CPP_DIR="{llama_dir}"',
f'_PREBUILT_LOG="{log_path}"',
f"_PREBUILT_STATUS={status}",
f'_explicit_llama_source_backend="{explicit_backend}"',
_setup_sh_routing_block(),
_SETUP_SH_HARNESS_TAIL,
]
)
completed = subprocess.run(["bash", "-c", script], capture_output = True, text = True, timeout = 60)
return {
"returncode": completed.returncode,
"stdout": completed.stdout,
"stderr": completed.stderr,
}
@pytest.mark.skipif(
os.name == "nt",
reason = "setup.sh is the POSIX installer; Windows runs setup.ps1, and driving a "
"POSIX script through Git Bash with Windows paths proves nothing about either",
)
@pytest.mark.parametrize(
"status, explicit_backend, expect_source_build, expect_exit",
[
(0, "", False, 0),
(1, "", False, 1), # helper error -> fail, never compile
(2, "", True, 0), # automatic selection may fall back to a source build
# Exit 2 means no concrete request; an unserved request arrives as exit 5.
(2, "cuda", True, 0),
(3, "", False, 3), # busy: a source build cannot replace locked binaries
(4, "", False, 0), # out of disk: compiling needs more, not less
(4, "rocm", False, 1), # an old install cannot satisfy an unchecked request
(5, "", False, 1), # a concrete selection failed; never substitute another
(5, "cuda", False, 1),
(137, "", False, 1), # SIGKILL/OOM and anything else -> fail, never compile
],
)
def test_setup_sh_starts_source_build_only_for_expected_prebuilt_exit(
tmp_path, status, explicit_backend, expect_source_build, expect_exit
):
"""Behavioural cover for the exit-code routing: runs the real block under bash.
The previous version compared ``str.index`` offsets, a tautology --
``index(needle, start)`` never returns less than ``start`` -- so it asserted only
that three literals appeared in order. The PowerShell side is covered textually by
test_setup_scripts_unexpected_exit_branch_never_sets_source_build, which is platform
independent.
"""
if shutil.which("bash") is None: # pragma: no cover - CI always has bash
pytest.skip("bash is required to exercise the setup.sh routing block")
result = _run_setup_sh_routing(
status, tmp_path, install_exists = True, explicit_backend = explicit_backend
)
assert result["returncode"] == expect_exit, result
if expect_source_build:
assert "source_build=true" in result["stdout"], result
else:
assert "source_build=true" not in result["stdout"], result
_SETUP_PS1_HARNESS = """
$ErrorActionPreference = "Stop"
$NeedLlamaSourceBuild = $false
$script:LlamaCppDegraded = $false
$StudioHomeIsCustom = $false
$prebuiltOutput = "boom"
function step { param($a, $b, $c) Write-Output "step: $b" }
function substep { param($a, $b) Write-Output "substep: $a" }
function Write-LlamaFailureLog { param($Output) }
function Mark-StudioOwned { param($Path) }
function Get-InstalledLlamaPrebuiltRelease { param($InstallDir) return $null }
function Test-PathQuiet { param($p) return $false }
# Nothing to keep, as in the bash mirror where the guard is absent: exit 2 falls back to a compile.
function Get-GpuPrebuiltToKeepOverSourceBuild { param($InstallDir) return "" }
function Get-LlamaUpdateFailReason { param($Output) return "network" }
function Exit-SetupFailure {
param($Message, $Code = 1)
Write-Output "setup_fail: $Code"
exit $Code
}
"""
_SETUP_PS1_HARNESS_TAIL = """
Write-Output "source_build=$($NeedLlamaSourceBuild.ToString().ToLower())"
"""
requires_pwsh = pytest.mark.skipif(
shutil.which("pwsh") is None, reason = "pwsh is required to execute the setup.ps1 routing block"
)
def _setup_ps1_routing_block() -> str:
setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
return _extract_block(setup_ps1, _SETUP_PS1_ROUTING_START, 'retry setup."\n }')
def _run_setup_ps1_routing(
status: int,
tmp_path: Path,
*,
install_exists: bool,
explicit_backend: str = "",
) -> dict[str, str]:
"""Drive the real setup.ps1 exit-code chain, the mirror of _run_setup_sh_routing."""
llama_dir = tmp_path / "llama.cpp"
if install_exists:
llama_dir.mkdir(parents = True, exist_ok = True)
else:
tmp_path.mkdir(parents = True, exist_ok = True)
script = "\n".join(
[
_SETUP_PS1_HARNESS,
f'$LlamaCppDir = "{llama_dir}"',
f"$prebuiltExit = {status}",
f'$explicitLlamaSourceBackend = "{explicit_backend}"',
_setup_ps1_routing_block(),
_SETUP_PS1_HARNESS_TAIL,
]
)
script_path = tmp_path / "routing.ps1"
script_path.write_text(script, encoding = "utf-8")
# run_pwsh, not subprocess.run: a pwsh killed at startup returns rc -6 with empty stdout.
completed = run_pwsh(
[
shutil.which("pwsh") or "pwsh",
"-NoProfile",
"-NonInteractive",
"-File",
str(script_path),
],
capture_output = True,
text = True,
timeout = 120,
)
return {
"returncode": completed.returncode,
"stdout": completed.stdout,
"stderr": completed.stderr,
}
@requires_pwsh
@pytest.mark.parametrize("install_exists", [True, False], ids = ["installed", "fresh"])
@pytest.mark.parametrize("explicit_backend", ["", "cuda", "rocm", "vulkan", "cpu"])
@pytest.mark.parametrize("status", [0, 1, 2, 3, 4, 5, 137])
def test_setup_ps1_routing_matches_setup_sh(status, explicit_backend, install_exists, tmp_path):
"""Windows must route an installer exit exactly as Linux does.
The assertions above compare SOURCE TEXT, which cannot catch a branch that reads the
same and behaves differently (a PowerShell `$false` string, an `exit` that does not
propagate, a guard whose variable was never set). Running both and comparing the
decision makes "the mirrored setup.ps1 does the same" a measurement, not a claim.
The decision is two values: the exit code, and whether a source build was queued.
Exit 5 must fail closed everywhere, while exit 2 stays the one automatic path
allowed to fall back to a compile.
"""
if shutil.which("bash") is None: # pragma: no cover - CI always has bash
pytest.skip("bash is required to compare against the setup.sh routing block")
sh_dir, ps_dir = tmp_path / "sh", tmp_path / "ps"
sh_dir.mkdir()
ps_dir.mkdir()
sh = _run_setup_sh_routing(
status,
sh_dir,
install_exists = install_exists,
explicit_backend = explicit_backend,
)
ps = _run_setup_ps1_routing(
status,
ps_dir,
install_exists = install_exists,
explicit_backend = explicit_backend,
)
assert ps["returncode"] == sh["returncode"], {"bash": sh, "pwsh": ps}
assert ("source_build=true" in ps["stdout"]) == ("source_build=true" in sh["stdout"]), {
"bash": sh,
"pwsh": ps,
}
if status == 5:
assert ps["returncode"] == 1
assert "source_build=true" not in ps["stdout"]
if status == 2:
assert "source_build=true" in ps["stdout"]
def test_setup_scripts_unexpected_exit_branch_never_sets_source_build():
"""The new catch-all must fail loudly, not queue a compile, on both platforms."""
setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")
sh_block = _setup_sh_routing_block()
sh_else = sh_block[sh_block.rindex("\n else\n") :]
assert "_NEED_LLAMA_SOURCE_BUILD=true" not in sh_else
assert "setup_fail 1" in sh_else
assert "prebuilt helper failed unexpectedly (exit code $_PREBUILT_STATUS)" in sh_else
assert sh_block.count("_NEED_LLAMA_SOURCE_BUILD=true") == 1
assert 'elif [ "$_PREBUILT_STATUS" -eq 5 ]; then' in sh_block
assert 'elif [ "$_PREBUILT_STATUS" -eq 2 ]; then' in sh_block
ps_block = _extract_block(setup_ps1, _SETUP_PS1_ROUTING_START, 'retry setup."\n }')
ps_else = ps_block[ps_block.rindex("} else {") :]
assert "$NeedLlamaSourceBuild = $true" not in ps_else
assert "Exit-SetupFailure" in ps_else
assert "prebuilt helper failed unexpectedly (exit code $prebuiltExit)" in ps_else
assert ps_block.count("$NeedLlamaSourceBuild = $true") == 1
assert "} elseif ($prebuiltExit -eq 5) {" in ps_block
assert "} elseif ($prebuiltExit -eq 2) {" in ps_block
for needle in ('elif [ "$_PREBUILT_STATUS" -eq 3 ]', 'elif [ "$_PREBUILT_STATUS" -eq 4 ]'):
assert needle in setup_sh
for needle in ("elseif ($prebuiltExit -eq 3)", "elseif ($prebuiltExit -eq 4)"):
assert needle in setup_ps1
@pytest.mark.parametrize(
"error",
[
# fetch_json raises a bare RuntimeError on rate limiting.
RuntimeError(
"GitHub API returned 403 for "
"https://api.github.com/repos/unslothai/llama.cpp/releases?per_page=100&page=1"
"; set GH_TOKEN or GITHUB_TOKEN to avoid GitHub API rate limits"
),
RuntimeError("unexpected releases payload for unslothai/llama.cpp"),
urllib.error.URLError("connection reset"),
TimeoutError("timed out"),
],
ids = ["rate-limit", "bad-payload", "urlerror", "timeout"],
)
def test_release_listing_failure_exits_fallback_not_error(tmp_path, monkeypatch, error):
"""A network failure listing releases must exit EXIT_FALLBACK: source builds use git, not the API."""
def boom(*args, **kwargs):
raise error
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_multiline_fallback_reason_logs_one_prefixed_line_each(tmp_path, monkeypatch, capsys):
"""Each reason line keeps the component prefix so the updater can tell it from the system report."""
def boom(*args, **kwargs):
raise INSTALL_LLAMA_PREBUILT.PrebuiltFallback(
"linux extracted binary preflight failed:\n"
"llama-server: missing=libcuda.so.1 ld_library_path=none\n"
"llama-quantize: missing=libgomp.so.1 ld_library_path=none"
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_LOG_TO_STDOUT", True)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
with pytest.raises(SystemExit):
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
reason = [
line
for line in capsys.readouterr().out.splitlines()
if "preflight failed" in line or "missing=" in line
]
assert len(reason) == 3
assert all(line.startswith("[llama-prebuilt] ") for line in reason)
@pytest.mark.parametrize("status", [403, 429])
def test_github_api_rate_limit_status_carries_the_token_hint(monkeypatch, status):
"""GitHub answers an exceeded rate limit with 403 or 429, and the raw
"HTTP Error 429: Too Many Requests" says nothing a user can act on."""
url = "https://api.github.com/repos/unslothai/llama.cpp/releases/tags/b10679-mix-67dfc8b"
def raise_status(_url, **_kw):
raise urllib.error.HTTPError(_url, status, "rate limited", {}, io.BytesIO(b""))
monkeypatch.delenv("GH_TOKEN", raising = False)
monkeypatch.delenv("GITHUB_TOKEN", raising = False)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_bytes", raise_status)
with pytest.raises(RuntimeError) as caught:
INSTALL_LLAMA_PREBUILT.fetch_json(url)
assert f"GitHub API returned {status}" in str(caught.value)
assert "GH_TOKEN" in str(caught.value)
def test_non_github_rate_limit_status_is_not_rewritten(monkeypatch):
"""huggingface.co has its own 429; it must not collect GitHub token advice."""
url = "https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf"
def raise_429(_url, **_kw):
raise urllib.error.HTTPError(_url, 429, "Too Many Requests", {}, io.BytesIO(b""))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "download_bytes", raise_429)
with pytest.raises(urllib.error.HTTPError):
INSTALL_LLAMA_PREBUILT.fetch_json(url)
_SHARED_PAYLOAD = {
"linux": [
"libllama-common.so",
"libllama.so",
"libggml.so",
"libggml-base.so",
"libggml-cpu.so",
"libmtmd.so",
"libllama-server-impl.so",
"libllama-quantize-impl.so",
],
"windows": ["llama.dll"],
}
_BACKEND_PAYLOAD = {
("windows", "cuda"): ["ggml-cuda.dll"],
("linux", "vulkan"): ["libggml-vulkan.so"],
}
_PUBLISHED_PAYLOAD = {"linux": ["llama-diffusion-gemma-visual-server"]}
def _complete_existing_llama_install(
tmp_path,
*,
executable = True,
backend = None,
payload = True,
windows = False,
backend_request = None,
runtime_asset = None,
paired_runtime = True,
runnable = True,
runnable_root = None,
runtime_line = None,
source = None,
visual_server = True,
):
install_dir = tmp_path / "llama.cpp"
runtime_dir = (
install_dir / "build" / "bin" / "Release" if windows else install_dir / "build" / "bin"
)
runtime_dir.mkdir(parents = True)
ext = ".exe" if windows else ""
marker = {"release_tag": "old-release", "tag": "old-upstream"}
if backend is not None:
marker["backend"] = backend
if backend_request is not None:
marker["backend_request"] = backend_request
if runtime_asset is not None:
marker["runtime_asset"] = runtime_asset
if runtime_line is not None:
marker["runtime_line"] = runtime_line
if source is not None:
marker["source"] = source
for path in (
install_dir / f"llama-server{ext}",
install_dir / f"llama-quantize{ext}",
runtime_dir / f"llama-server{ext}",
runtime_dir / f"llama-quantize{ext}",
install_dir / "convert_hf_to_gguf.py",
install_dir / "gguf-py",
install_dir / "UNSLOTH_PREBUILT_INFO.json",
):
if path.name == "gguf-py":
path.mkdir()
elif path.name == "UNSLOTH_PREBUILT_INFO.json":
path.write_text(json.dumps(marker) + "\n", encoding = "utf-8")
elif path.name.startswith("llama-"):
ok = (
runnable
if path.parent != install_dir
else (runnable if runnable_root is None else runnable_root)
)
# These get exec'd; a zero-byte file that kept its mode bits is ENOEXEC.
path.write_text("#!/bin/sh\nexit 0\n" if ok else "", encoding = "utf-8")
os.chmod(path, 0o755 if executable else 0o644)
else:
path.write_text("x", encoding = "utf-8")
os.chmod(path, 0o755 if executable else 0o644)
platform = "windows" if windows else "linux"
if payload:
for name in _SHARED_PAYLOAD[platform]:
(runtime_dir / name).write_text("x", encoding = "utf-8")
for name in _BACKEND_PAYLOAD.get((platform, backend), ()):
(runtime_dir / name).write_text("x", encoding = "utf-8")
if source == "published" and visual_server:
for name in _PUBLISHED_PAYLOAD[platform]:
(runtime_dir / name).write_text("x", encoding = "utf-8")
if runtime_asset is not None and paired_runtime:
for name in ("cudart64_13.dll", "cublas64_13.dll", "cublasLt64_13.dll"):
(runtime_dir / name).write_text("x", encoding = "utf-8")
return install_dir
def test_release_listing_failure_keeps_a_complete_existing_install(tmp_path, monkeypatch):
"""An unpinned transient update failure must keep a complete local runtime."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
install_dir = _complete_existing_llama_install(tmp_path)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert (install_dir / "llama-server").exists()
@pytest.mark.skipif(os.name == "nt", reason = "Windows st_mode carries no POSIX mode bits")
def test_an_offline_keep_repairs_a_non_executable_llama_fit_params(tmp_path, monkeypatch):
"""#12901: an update that cannot reach the release keeps the tree, so it must repair the probe too."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
install_dir = _complete_existing_llama_install(tmp_path)
helper = install_dir / "build" / "bin" / "llama-fit-params"
helper.write_bytes(b"probe\n")
helper.chmod(0o644)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert stat.S_IMODE(helper.stat().st_mode) == 0o755
def test_release_listing_failure_does_not_keep_a_non_executable_install(tmp_path, monkeypatch):
"""Do not keep a tree that fails setup.sh's executable reuse gate."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
install_dir = _complete_existing_llama_install(tmp_path, executable = False)
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
assert (install_dir / "llama-server").exists()
def _windows_host() -> HostInfo:
return windows_host()
@pytest.mark.parametrize(
("windows", "host", "backend"),
[
(False, linux_host, "cpu"),
(True, _windows_host, "cuda"),
],
ids = ["linux", "windows"],
)
def test_release_listing_failure_does_not_keep_a_gutted_runtime(
tmp_path, monkeypatch, windows, host, backend
):
"""Do not keep a tree that has lost its runtime payload."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
kept = _complete_existing_llama_install(tmp_path / "kept", backend = backend, windows = windows)
install_prebuilt(kept, "latest", "unslothai/llama.cpp", "")
gutted = _complete_existing_llama_install(
tmp_path / "gutted", backend = backend, payload = False, windows = windows
)
with pytest.raises(SystemExit) as caught:
install_prebuilt(gutted, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def _listing_failure(monkeypatch, host):
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
@pytest.mark.parametrize(
("runtime_asset", "paired_runtime", "kept"),
[
("cudart-llama-bin-win-cuda-13.0-x64.zip", True, True),
("cudart-llama-bin-win-cuda-13.0-x64.zip", False, False),
(None, False, True),
],
ids = ["paired-intact", "paired-gutted", "pair-less"],
)
def test_a_paired_cuda_install_needs_its_cudart_trio(
tmp_path, monkeypatch, runtime_asset, paired_runtime, kept
):
"""Require the cudart trio only from installs that recorded the paired archive."""
_listing_failure(monkeypatch, _windows_host)
install_dir = _complete_existing_llama_install(
tmp_path,
backend = "cuda",
windows = True,
runtime_asset = runtime_asset,
paired_runtime = paired_runtime,
)
if kept:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
else:
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
@pytest.mark.parametrize(
("windows", "host"),
[(True, _windows_host), (False, linux_host)],
ids = ["windows", "linux"],
)
@pytest.mark.parametrize("payload", [True, False], ids = ["intact", "gutted"])
def test_a_marker_that_names_no_backend_still_owes_the_shared_payload(
tmp_path, monkeypatch, windows, host, payload
):
"""Unknown markers still require the platform's shared payload."""
_listing_failure(monkeypatch, host)
install_dir = _complete_existing_llama_install(tmp_path, windows = windows, payload = payload)
if payload:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
else:
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_a_stored_backend_choice_the_install_already_satisfies_is_kept(tmp_path, monkeypatch):
"""Keep a working install that already satisfies its recorded backend."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert (install_dir / "llama-server").exists()
def test_a_backend_named_on_this_run_still_refuses_to_answer_with_the_old_install(
tmp_path, monkeypatch
):
"""backend_mandatory is a live instruction, not a stored preference."""
_listing_failure(monkeypatch, linux_host)
monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "cpu")
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE
def test_a_stored_backend_the_install_does_not_run_is_not_answered_with_it(tmp_path, monkeypatch):
"""A recorded request the tree does not satisfy is still exit 5, never a source build."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(
tmp_path, backend = "cpu", backend_request = "vulkan"
)
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE
@pytest.mark.parametrize(
("windows", "host"),
[(True, _windows_host), (False, linux_host)],
ids = ["windows", "linux"],
)
def test_release_listing_failure_does_not_keep_a_corrupt_binary(
tmp_path, monkeypatch, windows, host
):
"""A truncated llama-server keeps its mode bits, so os.access says yes and ldd on a
non-ELF finds nothing. On Windows neither preflight runs at all. execve sees it."""
_listing_failure(monkeypatch, host)
install_dir = _complete_existing_llama_install(
tmp_path, windows = windows, backend = "cuda" if windows else "cpu", runnable = False
)
ext = ".exe" if windows else ""
runtime = install_dir / "build" / "bin" / ("Release" if windows else "")
assert os.access(runtime / f"llama-server{ext}", os.X_OK), "the mode bits must survive"
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_a_rotten_root_entrypoint_is_not_saved_by_a_healthy_build_bin(tmp_path, monkeypatch):
"""_find_llama_server_binary searches <install>/llama-server before build/bin, so the
root copy is what runs; without a symlink it is a separate file that can rot alone."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", runnable_root = False)
assert os.access(install_dir / "build" / "bin" / "llama-server", os.X_OK)
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_a_windows_loader_status_is_not_a_successful_probe(tmp_path, monkeypatch):
"""A missing DLL exits 0xC0000135, which Python reports POSITIVE, so "not negative"
reads it as healthy. The payload groups cannot cover it: windows-cpu is only llama.dll."""
_listing_failure(monkeypatch, _windows_host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"run_capture",
lambda *a, **k: subprocess.CompletedProcess(a[0] if a else [], 0xC0000135, "", ""),
)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cuda", windows = True)
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
@pytest.mark.parametrize(
"kwargs",
[{"llama_backend": "auto"}, {"force_cpu": True}],
ids = ["backend-auto", "cpu-fallback"],
)
def test_a_selection_named_on_this_run_is_not_answered_with_the_old_install(
tmp_path, monkeypatch, kwargs
):
""" "auto" asks to re-detect; answering it with the old tree leaves the backend and its
marker untouched while reporting success."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu", backend_request = "cpu")
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "", **kwargs)
assert caught.value.code in (
INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK,
INSTALL_LLAMA_PREBUILT.EXIT_BACKEND_UNAVAILABLE,
)
@pytest.mark.parametrize(
"kwargs",
[{"override_has_rocm": True}, {"override_rocm_gfx": "gfx1151"}],
ids = ["has-rocm", "rocm-gfx"],
)
def test_forwarded_gpu_detection_is_not_a_selection_change(tmp_path, monkeypatch, kwargs):
"""setup.sh builds --rocm-gfx/--has-rocm into _PREBUILT_CMD from its own probe and
setup.ps1 does the same, so counting them would lose the keep path on every AMD host."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu")
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "", **kwargs)
assert (install_dir / "llama-server").exists()
def test_the_probe_gets_the_runtime_line_the_marker_recorded(tmp_path, monkeypatch):
"""binary_env puts the CUDA toolkit on PATH from runtime_line and
validate_prebuilt_choice passes it, so probing without it kills a pair-less install."""
_listing_failure(monkeypatch, linux_host)
seen: list = []
real_binary_env = INSTALL_LLAMA_PREBUILT.binary_env
def _record(*args, **kwargs):
seen.append(kwargs.get("runtime_line"))
return real_binary_env(*args, **kwargs)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "binary_env", _record)
install_dir = _complete_existing_llama_install(
tmp_path, backend = "cpu", runtime_line = "cuda-12.4"
)
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert (
"cuda-12.4" in seen
), f"the kept-install probe built its env without the marker's runtime_line: {seen}"
def test_a_non_default_published_repo_is_not_answered_with_the_old_install(tmp_path, monkeypatch):
"""A different release repo is a live choice the old tree cannot satisfy."""
_listing_failure(monkeypatch, linux_host)
install_dir = _complete_existing_llama_install(tmp_path, backend = "cpu")
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "someone-else/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_release_listing_failure_does_not_keep_an_unloadable_install(tmp_path, monkeypatch):
"""Executable is not runnable: a binary whose link graph is broken source builds."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "linux_missing_libraries", lambda *a, **k: ["libcuda.so.1"]
)
install_dir = _complete_existing_llama_install(tmp_path)
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
assert (install_dir / "llama-server").exists()
@pytest.mark.parametrize(
("llama_tag", "published_release_tag"),
[
("b9002", ""),
("latest", "release-2"),
("b9002", "release-2"),
],
ids = ["upstream-tag", "published-release", "both-pins"],
)
def test_release_listing_failure_does_not_ignore_an_explicit_version(
tmp_path, monkeypatch, llama_tag, published_release_tag
):
"""A usable older install cannot satisfy an explicit version request."""
def boom(*args, **kwargs):
raise urllib.error.URLError("connection reset")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")
install_dir = _complete_existing_llama_install(tmp_path)
with pytest.raises(SystemExit) as caught:
install_prebuilt(
install_dir,
llama_tag,
"unslothai/llama.cpp",
published_release_tag,
)
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
assert (install_dir / "llama-server").exists()
@pytest.mark.parametrize(
"error",
[
TypeError("bug"),
AttributeError("bug"),
NameError("bug"),
OSError(errno.EMFILE, "Too many open files"),
OSError(errno.ENOMEM, "Cannot allocate memory"),
PermissionError(errno.EACCES, "Permission denied"),
],
ids = ["typeerror", "attributeerror", "nameerror", "emfile", "enomem", "eacces"],
)
def test_release_listing_code_defect_stays_exit_error(tmp_path, monkeypatch, error):
"""A code defect in the listing stays EXIT_ERROR; only transport-style errors become a fallback."""
def boom(*args, **kwargs):
raise error
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
with pytest.raises(type(error)):
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
def test_release_listing_enospc_still_exits_no_space(tmp_path, monkeypatch):
"""A full disk must exit EXIT_NO_SPACE, never fall back to a source build."""
def boom(*args, **kwargs):
raise OSError(errno.ENOSPC, "No space left on device")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_fork_manifest_release_plans", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
with pytest.raises(OSError) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.errno == errno.ENOSPC
assert INSTALL_LLAMA_PREBUILT._environment_fatal_reason(caught.value)
def test_fallback_survives_a_failing_system_report(tmp_path, monkeypatch):
"""Diagnostics collected on the way out must not flip EXIT_FALLBACK to EXIT_ERROR."""
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_fork_manifest_release_plans",
lambda *a, **k: (_ for _ in ()).throw(PrebuiltFallback("no compatible prebuilt asset")),
)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", linux_host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"collect_system_report",
lambda *a, **k: (_ for _ in ()).throw(RuntimeError("nvidia-smi hung")),
)
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
with pytest.raises(SystemExit) as caught:
install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")
assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK
def test_marker_sync_strands_no_temp_file_when_the_first_write_fails(tmp_path, monkeypatch):
"""ENOSPC during a marker write must not strand a .tmp- file beside the marker."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
original = json.dumps({"force_cpu": False}) + "\n"
marker.write_text(original, encoding = "utf-8")
real_write = INSTALL_LLAMA_PREBUILT.tempfile.NamedTemporaryFile
class _FullDisk:
def __init__(self, handle):
self._handle = handle
def __getattr__(self, name):
return getattr(self._handle, name)
def write(self, *args, **kwargs):
raise OSError(errno.ENOSPC, "No space left on device")
class _Ctx:
def __enter__(self):
self._cm = real_write(prefix = marker.name + ".tmp-", dir = install_dir, delete = False)
return _FullDisk(self._cm.__enter__())
def __exit__(self, *exc):
return self._cm.__exit__(*exc)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.tempfile, "NamedTemporaryFile", lambda **kw: _Ctx())
_sync_force_cpu(install_dir)
assert marker.read_text(encoding = "utf-8") == original
assert [q.name for q in install_dir.iterdir() if ".tmp-" in q.name] == []
TREE_A = "8f3c6e197debb027f500df9f76e710e137f9fe68"
def _checksums(tree, repo = "unslothai/llama.cpp"):
return INSTALL_LLAMA_PREBUILT.ApprovedReleaseChecksums(
repo = repo,
release_tag = "b10173-mix-2c8b9c1",
upstream_tag = "b10173",
ggml_tree = tree,
)
def test_recorded_ggml_tree_only_for_binaries_from_that_release():
"""Only the fork's own bundles carry the fork's ggml tree; an upstream archive must not record it."""
def choice(repo):
return asset_choice(
name = "bundle.tar.gz",
url = "https://x/bundle",
repo = repo,
tag = "b10173",
source_label = "fork" if repo == "unslothai/llama.cpp" else "upstream",
is_ready_bundle = True,
bundle_profile = "cpu",
runtime_line = "cpu",
expected_sha256 = "0" * 64,
)
fork = choice("unslothai/llama.cpp")
upstream = choice("ggml-org/llama.cpp")
assert INSTALL_LLAMA_PREBUILT.recorded_ggml_tree(_checksums(TREE_A), fork) == TREE_A
assert INSTALL_LLAMA_PREBUILT.recorded_ggml_tree(_checksums(TREE_A), upstream) is None
assert INSTALL_LLAMA_PREBUILT.recorded_ggml_tree(_checksums(None), fork) is None
def test_reused_install_backfills_the_ggml_tree(tmp_path):
"""Reuse must backfill ggml_tree, or slim whisper pairing falls back to the -mix- suffix forever."""
install_dir = tmp_path / "llama.cpp"
(install_dir / "build" / "bin").mkdir(parents = True)
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker.write_text(json.dumps({"release_tag": "b10173-mix-2c8b9c1"}) + "\n", encoding = "utf-8")
_sync_ggml_tree(install_dir, TREE_A)
payload = json.loads(marker.read_text(encoding = "utf-8"))
assert payload["ggml_tree"] == TREE_A
assert payload["release_tag"] == "b10173-mix-2c8b9c1"
assert INSTALL_LLAMA_PREBUILT.installed_llama_ggml_tree(install_dir) == TREE_A
@pytest.mark.parametrize("declared", [None, ""])
def test_reused_install_keeps_the_ggml_tree_when_the_release_declares_none(tmp_path, declared):
"""A release with no ggml_tree (upstream ggml-org tags) must not erase one."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker.write_text(
json.dumps({"release_tag": "b10173-mix-2c8b9c1", "ggml_tree": TREE_A}) + "\n",
encoding = "utf-8",
)
_sync_ggml_tree(install_dir, declared)
assert json.loads(marker.read_text(encoding = "utf-8"))["ggml_tree"] == TREE_A
@pytest.mark.skipif(os.name == "nt", reason = "Windows st_mode carries no POSIX mode bits")
@pytest.mark.parametrize("mode", [0o444, 0o644, 0o664])
def test_marker_sync_preserves_the_marker_mode(tmp_path, mode):
"""A shared install's marker must stay readable by everyone who could read it.
os.replace keeps the SOURCE file's mode and NamedTemporaryFile is 0600, so a naive
atomic refresh would leave UNSLOTH_PREBUILT_INFO.json readable only by whoever ran
setup, and other users could no longer recognise or update the shared install.
"""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker.write_text(json.dumps({"force_cpu": False}) + "\n", encoding = "utf-8")
os.chmod(marker, mode)
_sync_force_cpu(install_dir)
assert stat.S_IMODE(marker.stat().st_mode) == mode
assert json.loads(marker.read_text(encoding = "utf-8"))["force_cpu"] is True
assert [p.name for p in install_dir.iterdir() if ".tmp-" in p.name] == []
def test_marker_sync_leaves_a_valid_marker_intact_when_the_write_fails(tmp_path, monkeypatch):
"""A failed marker refresh must leave the valid marker intact, never a truncated partial file."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
original = json.dumps({"force_cpu": False, "release_tag": "b9002"}, indent = 2) + "\n"
marker.write_text(original, encoding = "utf-8")
def out_of_space(*args, **kwargs):
raise OSError(errno.ENOSPC, "No space left on device")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "atomic_replace_from_tempfile", out_of_space)
_sync_force_cpu(install_dir)
assert marker.read_text(encoding = "utf-8") == original
assert [q.name for q in install_dir.iterdir() if ".tmp-" in q.name] == []
def test_python_runtime_dirs_skips_an_inaccessible_glob_result(monkeypatch, tmp_path):
"""A denied entry under a readable site-packages root is skipped rather than aborting discovery."""
root = tmp_path / "site-packages"
good = root / "torch" / "lib"
good.mkdir(parents = True)
denied = root / "nvidia" / "cublas" / "lib"
denied.mkdir(parents = True)
real_is_dir = Path.is_dir
def guarded_is_dir(self):
if str(self) == str(denied):
raise PermissionError(13, "Access is denied", str(self), 5)
return real_is_dir(self)
monkeypatch.setattr(Path, "is_dir", guarded_is_dir)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.sys, "path", [str(root)])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.site, "getsitepackages", lambda: [])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.site, "getusersitepackages", lambda: "")
assert INSTALL_LLAMA_PREBUILT.python_runtime_dirs() == [str(good.resolve())]
def test_python_runtime_dirs_skips_inaccessible_sys_path_entry(monkeypatch, tmp_path):
"""A denied sys.path entry must not escape windows_runtime_dirs()."""
usable = tmp_path / "site-packages"
(usable / "torch" / "lib").mkdir(parents = True)
denied = Path(r"\\\\denied-share\\site-packages")
real_is_dir = Path.is_dir
def guarded_is_dir(self):
if str(self) == str(denied):
raise PermissionError(13, "Access is denied", str(self), 5)
return real_is_dir(self)
monkeypatch.setattr(Path, "is_dir", guarded_is_dir)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.sys, "path", [str(denied), str(usable)])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.site, "getsitepackages", lambda: [])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.site, "getusersitepackages", lambda: "")
assert INSTALL_LLAMA_PREBUILT.python_runtime_dirs() == [
str((usable / "torch" / "lib").resolve())
]
def test_windows_runtime_dirs_skips_inaccessible_program_files(monkeypatch):
"""%ProgramFiles% is user-controllable, so its stat must not be fatal either."""
denied = r"C:\Denied Program Files"
real_is_dir = Path.is_dir
def guarded_is_dir(self):
if str(self).startswith(denied):
raise PermissionError(13, "Access is denied", str(self), 5)
return real_is_dir(self)
monkeypatch.setattr(Path, "is_dir", guarded_is_dir)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.os, "pathsep", ";")
monkeypatch.setenv("ProgramFiles", denied)
monkeypatch.delenv("CUDA_RUNTIME_DLL_DIR", raising = False)
monkeypatch.delenv("CUDA_PATH", raising = False)
monkeypatch.delenv("CUDA_HOME", raising = False)
monkeypatch.delenv("CUDA_ROOT", raising = False)
monkeypatch.setenv("PATH", "")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "python_runtime_dirs", lambda: [])
assert INSTALL_LLAMA_PREBUILT.windows_runtime_dirs() == []
def test_binary_env_linux_skips_inaccessible_inherited_ld_library_path(monkeypatch, tmp_path):
"""Same class of bug as the Windows PATH fix, on the LD_LIBRARY_PATH side."""
binary_dir = tmp_path / "llama.cpp"
binary_dir.mkdir()
binary_path = binary_dir / "llama-server"
binary_path.write_bytes(b"")
usable = tmp_path / "usable-lib"
usable.mkdir()
denied = tmp_path / "denied-lib"
denied.mkdir()
real_is_dir = Path.is_dir
def guarded_is_dir(self):
if str(self) == str(denied):
raise PermissionError(13, "Permission denied", str(self))
return real_is_dir(self)
monkeypatch.setattr(Path, "is_dir", guarded_is_dir)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "linux_runtime_dirs", lambda *a, **k: [])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_wsl_system_rocm_lib_dirs", lambda: [])
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_native_linux_system_rocm_lib_dirs", lambda *a: [])
monkeypatch.setenv("LD_LIBRARY_PATH", os.pathsep.join([str(denied), str(usable)]))
env = binary_env(binary_path, binary_dir, linux_host())
assert env["LD_LIBRARY_PATH"].split(os.pathsep) == [
str(binary_dir.resolve()),
str(usable.resolve()),
]
def _reused_choice(install_kind = "linux-cpu"):
"""The bundle a reuse path re-records the run's selection against."""
return asset_choice(
name = "bundle.tar.gz",
url = "file://bundle",
tag = "b10173",
source_label = "published",
install_kind = install_kind,
)
def _sync_force_cpu(install_dir, value = True):
"""sync_marker_selection with only the deliberate-CPU choice in play."""
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir,
choice = _reused_choice(),
backend_request = "cpu" if value else "auto",
persist_force_cpu = value,
)
def _sync_ggml_tree(install_dir, tree):
"""sync_marker_selection with only the paired ggml tree in play."""
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir,
choice = _reused_choice(),
backend_request = "auto",
ggml_tree = tree,
)
@pytest.mark.parametrize(
"kwargs, install_kind, field, expected",
[
({"persist_force_cpu": True, "backend_request": "cpu"}, "linux-cpu", "force_cpu", True),
(
{"persist_llama_backend": "vulkan", "backend_request": "vulkan"},
"linux-vulkan",
"llama_backend",
"vulkan",
),
({"backend_request": "vulkan"}, "linux-vulkan", "backend_request", "vulkan"),
],
)
def test_marker_sync_survives_a_read_only_marker(tmp_path, kwargs, install_kind, field, expected):
"""A read-only marker must not fail setup: the rewrite needs the same guard as the read."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker.write_text(
json.dumps({"force_cpu": False, "llama_backend": None}) + "\n", encoding = "utf-8"
)
os.chmod(marker, 0o444)
if os.access(marker, os.W_OK): # pragma: no cover - root ignores the mode
pytest.skip("cannot make the marker read-only for this user")
logged: list[str] = []
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "log", logged.append)
try:
INSTALL_LLAMA_PREBUILT.sync_marker_selection(
install_dir, choice = _reused_choice(install_kind), **kwargs
)
finally:
monkeypatch.undo()
if marker.exists():
os.chmod(marker, 0o644)
# Windows refuses os.replace onto a read-only file, so either it persisted or we warned.
persisted = json.loads(marker.read_text(encoding = "utf-8")).get(field) == expected
assert persisted or any("WARNING" in line and field in line for line in logged), logged
def test_marker_sync_never_fails_setup_when_the_write_cannot_land(tmp_path, monkeypatch):
"""If even the atomic swap is refused, warn and continue -- never abort setup."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker.write_text(json.dumps({"force_cpu": False}) + "\n", encoding = "utf-8")
def refuse(*args, **kwargs):
raise PermissionError(13, "Access is denied", str(marker), 5)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "atomic_replace_from_tempfile", refuse)
logged: list[str] = []
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "log", logged.append)
_sync_force_cpu(install_dir)
assert any("WARNING" in line and "force_cpu" in line for line in logged), logged
# Stubs mirror these signatures; fail here, once, when a keyword is added.
_VALIDATOR_KEYWORD_ONLY = {
"validate_prebuilt_attempts": (
"requested_tag",
"llama_tag",
"release_tag",
"approved_checksums",
"initial_fallback_used",
"existing_install_dir",
"force_cpu",
"llama_backend",
"backend_request",
"rocm_gfx",
"walk_back",
),
"validate_prebuilt_choice": (
"requested_tag",
"llama_tag",
"release_tag",
"approved_checksums",
"prebuilt_fallback_used",
"quantized_path",
"force_cpu",
"llama_backend",
"backend_request",
"rocm_gfx",
"walk_back",
),
}
@pytest.mark.parametrize("name", sorted(_VALIDATOR_KEYWORD_ONLY))
def test_the_validator_stubs_still_model_the_real_signature(name):
"""A stub that has fallen behind its real function is not a stub."""
import inspect
real = getattr(INSTALL_LLAMA_PREBUILT, name)
actual = tuple(
parameter_name
for parameter_name, parameter in inspect.signature(real).parameters.items()
if parameter.kind is inspect.Parameter.KEYWORD_ONLY
)
assert actual == _VALIDATOR_KEYWORD_ONLY[name], (
f"{name} keyword-only parameters are now {actual}; update the "
f"fake_validate stubs in this file, then this list"
)
def test_supported_sms_stays_out_of_the_install_fingerprint():
"""The CUDA analog of the mapped_targets fingerprint guard. Backfilling
supported_sms onto existing markers only works while it is not hashed: in
the payload, every install predating the field reinstalls on upgrade."""
base = dict(
repo = "unslothai/llama.cpp",
tag = "b9001",
name = "app-b9001-linux-x64-cuda13-older.tar.gz",
url = "https://example.invalid/app.tar.gz",
source_label = "published",
install_kind = "linux-cuda",
bundle_profile = "app",
runtime_line = "cuda13",
coverage_class = "older",
expected_sha256 = "a" * 64,
)
checksums = release_checksums()
kwargs = dict(llama_tag = "b9001", release_tag = "release-1", approved_checksums = checksums)
without = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
choice = AssetChoice(**base), **kwargs
)
with_sms = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(
choice = AssetChoice(**base, supported_sms = ["75", "80", "86", "89"]), **kwargs
)
assert without and without == with_sms, (
"recording supported_sms changed the install fingerprint; every existing "
"install would refresh on upgrade"
)
@pytest.mark.parametrize(
"install_kind, runtime_line",
[("linux-vulkan", "vulkan"), ("linux-cpu", "cpu"), ("linux-rocm", "rocm")],
)
def test_a_non_cuda_bundle_declares_no_supported_sms(tmp_path: Path, install_kind, runtime_line):
"""The runtime gate has no is_vulkan_backend guard and stays inert only because a non-CUDA
bundle records an empty supported_sms list, which reads as unknown coverage."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
choice = _cuda_choice(install_kind = install_kind, runtime_line = runtime_line, supported_sms = None)
write_metadata(
install_dir,
choice,
approved_release_checksums_for_asset(choice.name, "a" * 64),
llama_tag = "b10360",
release_tag = "b10360",
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())
assert marker["supported_sms"] == []
# Localized nvidia-smi output; the GBK lead bytes also defeat cp1252 decoding.
_LOCALIZED_NVIDIA_SMI = (
"import sys\n"
"a = sys.argv[1:]\n"
"if a == ['-L']:\n"
" sys.stdout.buffer.write(b'GPU 0: NVIDIA GeForce RTX 3090 (UUID: GPU-a)\\n')\n"
"elif a and a[0].startswith('--query-gpu'):\n"
" sys.stdout.buffer.write(b'0, GPU-a, 8.6\\n')\n"
"else:\n"
" sys.stdout.buffer.write(b'| NVIDIA-SMI 591.86 CUDA Version: 13.1 |\\n')\n"
" sys.stdout.buffer.write('\\u4e02\\u4fdd\\u7559\\u6240\\u6709\\u6743\\u5229\\u3002\\n'.encode('gbk'))\n"
)
def test_run_capture_keeps_ascii_lines_when_a_child_writes_another_code_page():
result = INSTALL_LLAMA_PREBUILT.run_capture(
[sys.executable, "-c", _LOCALIZED_NVIDIA_SMI], timeout = 30
)
assert "CUDA Version: 13.1" in result.stdout
assert "\ufffd" in result.stdout
def test_detect_host_reads_the_driver_cuda_version_from_a_localized_nvidia_smi(
monkeypatch, tmp_path
):
fake = tmp_path / "nvidia-smi.py"
fake.write_text(_LOCALIZED_NVIDIA_SMI, encoding = "utf-8")
real_run = subprocess.run
def run_fake_nvidia_smi(command, *args, **kwargs):
if command and command[0] == "nvidia-smi":
command = [sys.executable, str(fake), *command[1:]]
kwargs.setdefault("encoding", "utf-8") # what the launcher's -X utf8 does
return real_run(command, *args, **kwargs)
monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT.subprocess, "run", run_fake_nvidia_smi)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT.shutil,
"which",
lambda name, *a, **k: "nvidia-smi" if name == "nvidia-smi" else None,
)
host = INSTALL_LLAMA_PREBUILT.detect_host()
assert host.compute_caps == ["86"]
assert host.driver_cuda_version == (13, 1)
def _flat(groups: list[list[str]]) -> set[str]:
return {pattern for group in groups for pattern in group}
@pytest.mark.parametrize(
"install_kind",
[
"windows-cpu",
"windows-arm64",
"windows-cuda",
"windows-hip",
"windows-rocm",
"windows-vulkan",
],
)
def test_windows_prebuilt_health_requires_the_shared_runtime(install_kind: str):
"""Requiring only llama.dll let a tree missing llama-common.dll validate and
then fail at exec."""
patterns = _flat(runtime_payload_health_groups(install_kind, source_label = "published"))
for required in (
"llama.dll",
"llama-common.dll",
"llama-server.exe",
"llama-server-impl.dll",
"llama-quantize-impl.dll",
"ggml.dll",
"ggml-base.dll",
"ggml-cpu*.dll",
"mtmd.dll",
):
assert required in patterns, f"{install_kind} does not require {required}"
def test_windows_source_build_does_not_require_the_shared_runtime():
"""setup.ps1 builds with -DBUILD_SHARED_LIBS=OFF, so requiring these would
fail a healthy tree."""
patterns = _flat(runtime_payload_health_groups("windows-cpu", source_label = None))
assert "llama.dll" in patterns
for absent in (
"llama-common.dll",
"llama-server-impl.dll",
"llama-quantize-impl.dll",
"mtmd.dll",
):
assert absent not in patterns
def test_windows_upstream_bundles_require_the_shared_runtime_too():
"""Upstream ggml-org Windows zips are also built with shared libs on."""
patterns = _flat(runtime_payload_health_groups("windows-cpu", source_label = "upstream"))
assert "llama-common.dll" in patterns
# Real win-cpu-x64 zip payloads either side of the impl split (llama.cpp#23462).
_PRE_SPLIT_WINDOWS_PAYLOAD = (
"llama.dll",
"llama-common.dll",
"llama-server.exe",
"ggml.dll",
"ggml-base.dll",
"ggml-cpu-haswell.dll",
"mtmd.dll",
)
_POST_SPLIT_WINDOWS_PAYLOAD = _PRE_SPLIT_WINDOWS_PAYLOAD + (
"llama-server-impl.dll",
"llama-quantize-impl.dll",
)
@pytest.mark.parametrize(
("tag", "payload", "healthy"),
[
("b9279", _PRE_SPLIT_WINDOWS_PAYLOAD, True),
("b9283", _POST_SPLIT_WINDOWS_PAYLOAD, True),
("b9283", _PRE_SPLIT_WINDOWS_PAYLOAD, False),
],
ids = ["pre-split-monolithic", "post-split-complete", "post-split-truncated"],
)
def test_pre_split_upstream_windows_pin_is_not_forced_to_a_source_build(
tmp_path: Path, tag: str, payload: tuple[str, ...], healthy: bool
):
"""A pinned upstream tag older than b9283 ships no llama-server-impl.dll; requiring
it made validate_prebuilt_choice reject a valid downloaded prebuilt and fall back to
a costly Windows source build."""
install_dir = tmp_path / "llama.cpp"
runtime_dir = install_dir / "build" / "bin" / "Release"
runtime_dir.mkdir(parents = True)
for name in payload:
(runtime_dir / name).write_bytes(b"DLL")
choice = AssetChoice(
repo = "ggml-org/llama.cpp",
tag = tag,
name = f"llama-{tag}-bin-win-cpu-x64.zip",
url = f"https://github.com/ggml-org/llama.cpp/releases/download/{tag}/x.zip",
source_label = "upstream",
install_kind = "windows-cpu",
)
assert (
INSTALL_LLAMA_PREBUILT.runtime_payload_is_healthy(install_dir, _windows_host(), choice)
is healthy
)
def test_existing_install_matches_plan_windows_rejects_missing_llama_common(tmp_path: Path):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_windows_install_shape(install_dir, include_llama_dll = True)
runtime_dir = install_dir / "build" / "bin" / "Release"
(runtime_dir / "llama-common.dll").unlink()
groups = runtime_payload_health_groups("windows-cpu", source_label = "published")
host = HostInfo(
system = "Windows",
machine = "AMD64",
is_windows = True,
is_linux = False,
is_macos = False,
is_x86_64 = True,
is_arm64 = False,
nvidia_smi = None,
driver_cuda_version = None,
compute_caps = [],
visible_cuda_devices = None,
has_physical_nvidia = False,
has_usable_nvidia = False,
)
assert INSTALL_LLAMA_PREBUILT._runtime_payload_has(install_dir, host, groups) is False
(runtime_dir / "llama-common.dll").write_bytes(b"DLL")
assert INSTALL_LLAMA_PREBUILT._runtime_payload_has(install_dir, host, groups) is True
def test_a_fresh_windows_install_is_payload_checked_not_just_vulkan():
"""A source guard: reaching that call needs a real download, but the check
has to run where the bundle is unpacked, not only on the reuse path."""
source = MODULE_PATH.read_text(encoding = "utf-8")
gate = source[source.index("overlaying prebuilt bundle") :]
gate = gate[: gate.index("preflight_linux_installed_binaries")]
assert "runtime_payload_is_healthy" in gate, "fresh installs are not payload checked at all"
assert (
'choice.install_kind.startswith("windows-")' in gate
), "fresh Windows installs are not payload checked"
assert "VULKAN_INSTALL_KINDS" in gate, "the Vulkan check must not be dropped"
existing_install_current_without_plan = INSTALL_LLAMA_PREBUILT.existing_install_current_without_plan
runtime_file_records = INSTALL_LLAMA_PREBUILT.runtime_file_records
host_profile = INSTALL_LLAMA_PREBUILT.host_profile
sync_marker_selection = INSTALL_LLAMA_PREBUILT.sync_marker_selection
_CUDA_HOST_FIELDS = dict(
nvidia_smi = "nvidia-smi",
has_physical_nvidia = True,
has_usable_nvidia = True,
driver_cuda_version = (12, 8),
compute_caps = ["8.9"],
)
def _detects(monkeypatch, host: HostInfo) -> None:
"""What the hardware probes say on THIS run, whatever the install recorded."""
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda **_k: host)
def _current_install(
tmp_path: Path,
monkeypatch,
*,
install_host: HostInfo | None = None,
published_repo: str = "unslothai/llama.cpp",
**marker_overrides,
) -> Path:
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir(parents = True)
write_linux_install_shape(install_dir)
for name in ("llama-server", "llama-quantize"):
for parent in (install_dir, install_dir / "build" / "bin"):
(parent / name).chmod(0o755)
choice = asset_choice(repo = published_repo)
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
if published_repo != checksums.repo:
checksums = dataclasses.replace(checksums, repo = published_repo)
host = install_host if install_host is not None else linux_host()
write_prebuilt_metadata(
install_dir,
host = host,
requested_tag = "latest",
llama_tag = "b9001",
release_tag = "release-1",
choice = choice,
approved_checksums = checksums,
prebuilt_fallback_used = False,
backend_request = "auto",
)
if marker_overrides:
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
payload = json.loads(marker_path.read_text(encoding = "utf-8"))
for key, value in marker_overrides.items():
if value is None:
payload.pop(key, None)
else:
payload[key] = value
marker_path.write_text(json.dumps(payload, indent = 2), encoding = "utf-8")
_detects(monkeypatch, host)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: "release-1"
)
monkeypatch.delenv("UNSLOTH_PREBUILT_FULL_CHECK", raising = False)
monkeypatch.delenv("UNSLOTH_LLAMA_DISABLE_DOWNLOAD_HOST_RESOLVE", raising = False)
monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
monkeypatch.delenv("UNSLOTH_ROCM_GFX_REMEMBERED", raising = False)
return install_dir
def _check(install_dir: Path, **overrides) -> bool:
kwargs = dict(
llama_tag = "latest",
published_repo = "unslothai/llama.cpp",
published_release_tag = "",
backend_request = "auto",
force_cpu = False,
)
kwargs.update(overrides)
return existing_install_current_without_plan(install_dir, **kwargs)
def test_a_current_install_is_recognised_without_listing_the_release(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
def boom(*_a, **_k):
raise AssertionError("the no-network check must not reach the GitHub API")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "fetch_release_bundle", boom, raising = False)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "resolve_release_tag", boom, raising = False)
assert _check(install_dir) is True
def test_the_latest_lookup_is_one_head_on_the_download_host(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
calls: list[str] = []
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_download_host_latest_release_tag",
lambda repo: (calls.append(repo), "release-1")[1],
)
assert _check(install_dir) is True
assert calls == ["unslothai/llama.cpp"]
def test_a_newer_release_upstream_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: "release-2"
)
assert _check(install_dir) is False
def test_a_lookup_that_cannot_answer_takes_the_full_path(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
for answer in (None, ""):
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: answer
)
assert _check(install_dir) is False
def raises(_repo):
raise OSError("github.com unreachable")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", raises)
assert _check(install_dir) is False
def _release(
tag: str,
published_at: str,
release_id: int = 1,
**extra,
) -> dict:
payload = {
"tag_name": tag,
"published_at": published_at,
"created_at": published_at,
"id": release_id,
"draft": False,
"prerelease": False,
}
payload.update(extra)
return payload
def test_the_api_only_escape_hatch_uses_the_api_notion_of_latest(tmp_path, monkeypatch):
"""The API-only escape hatch answers latest from the API, ordered by published_at."""
install_dir = _current_install(tmp_path, monkeypatch)
monkeypatch.setenv("UNSLOTH_LLAMA_DISABLE_DOWNLOAD_HOST_RESOLVE", "1")
def boom(_repo):
raise AssertionError("the download-host HEAD is exactly what was turned off")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", boom)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda _repo, **_k: [
_release("release-0", "2026-01-01T00:00:00Z", 1),
_release("release-1", "2026-02-01T00:00:00Z", 2),
],
)
assert _check(install_dir) is True
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda _repo, **_k: [
_release("release-2", "2026-03-01T00:00:00Z", 3),
_release("release-1", "2026-02-01T00:00:00Z", 2),
],
)
assert _check(install_dir) is False
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda _repo, **_k: [_release("release-9", "2026-04-01T00:00:00Z", 4, draft = True)],
)
assert _check(install_dir) is False
def raises(_repo, **_k):
raise OSError("api.github.com unreachable")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "github_releases", raises)
assert _check(install_dir) is False
def test_a_custom_repo_is_answered_the_way_the_selector_orders_it(tmp_path, monkeypatch):
"""A custom repo must be ordered by published_at through the API, not by /releases/latest."""
install_dir = _current_install(tmp_path, monkeypatch, published_repo = "someone/llama.cpp")
def boom(_repo):
raise AssertionError("a custom repo never resolves through the download host")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", boom)
listed = {"tags": ["release-1"]}
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda _repo, **_k: [
_release(tag, f"2026-0{i + 1}-01T00:00:00Z", i + 1)
for i, tag in enumerate(listed["tags"])
],
)
assert _check(install_dir, published_repo = "someone/llama.cpp") is True
listed["tags"] = ["release-1", "release-2"]
assert _check(install_dir, published_repo = "someone/llama.cpp") is False
def test_a_release_payload_this_run_already_has_overrides_the_latest_pointer(tmp_path, monkeypatch):
"""/releases/latest resolves by make_latest and created_at but macOS orders by published_at; a
payload in hand that disagrees with the pointer wins at no request cost."""
install_dir = _current_install(tmp_path, monkeypatch)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: "release-1"
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_METADATA_MEMO",
{
(
"json",
"https://api.github.com/repos/unslothai/llama.cpp/releases?per_page=100&page=1",
): [
_release("release-1", "2026-02-01T00:00:00Z", 2),
_release("release-2", "2026-03-01T00:00:00Z", 3),
]
},
)
assert _check(install_dir) is False
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_METADATA_MEMO",
{
(
"json",
"https://api.github.com/repos/unslothai/llama.cpp/releases?per_page=100&page=1",
): [
_release("release-1", "2026-02-01T00:00:00Z", 2),
]
},
)
assert _check(install_dir) is True
def test_an_empty_metadata_memo_never_reaches_the_api(tmp_path, monkeypatch):
"""The install path leaves _METADATA_MEMO at None; only --resolve-backends fills it,
so the cross-check must never turn into a request of its own."""
install_dir = _current_install(tmp_path, monkeypatch)
def boom(_repo, **_k):
raise AssertionError("the memo cross-check must not fetch anything")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "github_releases", boom)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_METADATA_MEMO", None)
assert _check(install_dir) is True
def test_a_pinned_release_tag_needs_no_lookup_at_all(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
def boom(_repo):
raise AssertionError("a pinned release tag names the answer outright")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", boom)
assert _check(install_dir, published_release_tag = "release-1") is True
assert _check(install_dir, published_release_tag = "release-9") is False
def test_an_upstream_pin_is_answered_by_the_recorded_upstream_tag(tmp_path, monkeypatch):
"""The marker records the pinned upstream build, and the release installed is the fork's newest
packaging of it since the fork can republish; /releases/latest says nothing of pins."""
install_dir = _current_install(tmp_path, monkeypatch)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
def boom(_repo):
raise AssertionError("an upstream pin never asks /releases/latest")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", boom)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda repo, **kw: [
{"tag_name": marker["release_tag"], "published_at": "2026-01-01T00:00:00Z", "id": 1}
],
)
assert _check(install_dir, llama_tag = "b9001") is True
assert _check(install_dir, llama_tag = "b9999") is False
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"github_releases",
lambda repo, **kw: [
{"tag_name": marker["release_tag"], "published_at": "2026-01-01T00:00:00Z", "id": 1},
{"tag_name": "b9001-mix-newer", "published_at": "2026-02-01T00:00:00Z", "id": 2},
],
)
assert _check(install_dir, llama_tag = "b9001") is False
def test_a_full_check_request_always_does_the_work(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
for value in ("1", "true", "YES", "on"):
monkeypatch.setenv("UNSLOTH_PREBUILT_FULL_CHECK", value)
assert _check(install_dir) is False
for value in ("0", "false", "", "maybe"):
monkeypatch.setenv("UNSLOTH_PREBUILT_FULL_CHECK", value)
assert _check(install_dir) is True
def test_a_different_repo_or_backend_request_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
assert _check(install_dir, published_repo = "someone/else") is False
assert _check(install_dir, backend_request = "vulkan") is False
assert _check(install_dir, force_cpu = True) is False
def test_a_marker_written_before_this_existed_takes_the_full_path_once(tmp_path, monkeypatch):
"""runtime_sha256, runtime_files and host_profile are new keys; without them the
marker cannot be verified against itself, against the disk, or against the box it
is running on, and guessing yes would keep an install nobody has checked."""
for missing in ("runtime_sha256", "runtime_files", "install_fingerprint", "host_profile"):
install_dir = _current_install(tmp_path / missing, monkeypatch, **{missing: None})
assert _check(install_dir) is False, missing
def test_a_gpu_added_since_the_install_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
assert _check(install_dir) is True
_detects(monkeypatch, linux_host(**_CUDA_HOST_FIELDS))
assert _check(install_dir) is False
def test_a_gpu_removed_since_the_install_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(
tmp_path, monkeypatch, install_host = linux_host(**_CUDA_HOST_FIELDS)
)
assert _check(install_dir) is True
_detects(monkeypatch, linux_host())
assert _check(install_dir) is False
_detects(monkeypatch, linux_host(**{**_CUDA_HOST_FIELDS, "driver_cuda_version": (12, 4)}))
assert _check(install_dir) is False
def test_a_new_gpu_outside_the_recorded_coverage_is_not_current(tmp_path, monkeypatch):
"""A bundle carries kernels only for its supported_sms; a card outside that set leaves an
install that starts but cannot run a model, which is worse than a reinstall."""
install_dir = _current_install(
tmp_path, monkeypatch, install_host = linux_host(**_CUDA_HOST_FIELDS)
)
_detects(monkeypatch, linux_host(**{**_CUDA_HOST_FIELDS, "compute_caps": ["12.0"]}))
assert _check(install_dir) is False
_detects(
monkeypatch, linux_host(**{**_CUDA_HOST_FIELDS, "compute_caps": ["8.9", "8.9", " 8.9 "]})
)
assert _check(install_dir) is True
def test_a_rocm_gfx_change_is_not_current(tmp_path, monkeypatch):
rocm = dict(has_rocm = True, rocm_gfx_target = "gfx1100", rocm_gfx_targets = ["gfx1100"])
install_dir = _current_install(tmp_path, monkeypatch, install_host = linux_host(**rocm))
assert _check(install_dir) is True
_detects(
monkeypatch,
linux_host(has_rocm = True, rocm_gfx_target = "gfx1030", rocm_gfx_targets = ["gfx1030"]),
)
assert _check(install_dir) is False
_detects(
monkeypatch,
linux_host(
has_rocm = True,
rocm_gfx_target = "gfx1100",
rocm_gfx_targets = ["gfx1100", "gfx1030"],
),
)
assert _check(install_dir) is False
def test_the_recorded_profile_is_the_routed_host_not_the_raw_one(tmp_path, monkeypatch):
"""The check re-derives the host through route_backend_request, the same no-network
routing _select uses. Comparing a raw detect_host against a routed profile would
never match and would take the slow path forever."""
install_dir = _current_install(tmp_path, monkeypatch)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
route = INSTALL_LLAMA_PREBUILT.route_backend_request(
backend = "auto",
published_repo = "unslothai/llama.cpp",
published_release_tag = "",
)
assert marker["host_profile"] == host_profile(route.host)
def test_a_marker_naming_a_backend_this_platform_cannot_hold_is_not_current(tmp_path, monkeypatch):
"""A directory copied off another machine keeps its marker. backend "metal" has no
Linux install kind, so _kept_install_payload_is_healthy has no shared payload to
require and answers yes to a tree it has never seen."""
install_dir = _current_install(tmp_path, monkeypatch, backend = "metal")
assert _check(install_dir) is False
def test_a_marker_whose_request_and_backend_disagree_is_not_current(tmp_path, monkeypatch):
"""A concrete backend request must name the bundle's own backend unless the marker flags it
unsatisfied; a bare disagreement was not written by this installer."""
install_dir = _current_install(tmp_path, monkeypatch, backend_request = "vulkan")
assert _check(install_dir, backend_request = "vulkan") is False
_UNSATISFIED = dict(backend_request = "vulkan", backend_request_unsatisfied = True)
def test_an_unsatisfied_choice_read_off_the_marker_does_not_reinstall_every_update(
tmp_path, monkeypatch
):
"""Nothing moved, so the install on disk is still the one this run would produce. The
request stays recorded, owed a retry, not retried here."""
install_dir = _current_install(tmp_path, monkeypatch, **_UNSATISFIED)
assert _check(install_dir, backend_request = "vulkan") is True
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert marker["backend_request"] == "vulkan"
def test_an_unsatisfied_choice_named_by_this_run_is_re_asserted(tmp_path, monkeypatch):
"""An explicit --llama-backend vulkan (or Settings) takes the full path, re-asserting the
request and failing loudly rather than silently keeping an unrequested bundle."""
install_dir = _current_install(tmp_path, monkeypatch, **_UNSATISFIED)
assert _check(install_dir, backend_request = "vulkan", backend_request_mandatory = True) is False
def test_an_unsatisfied_choice_is_retried_when_the_release_moves(tmp_path, monkeypatch):
"""The "something changed" half: a new release republishes the bundles, so the choice
gets another go. Same for new hardware, which the host_profile check already covers."""
install_dir = _current_install(tmp_path, monkeypatch, **_UNSATISFIED)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "_download_host_latest_release_tag", lambda _repo: "release-2"
)
assert _check(install_dir, backend_request = "vulkan") is False
def test_an_old_marker_is_read_as_a_satisfied_choice(tmp_path, monkeypatch):
"""No flag means satisfied, so every install made before the field behaves exactly as
it did: a recorded choice that names the installed backend stays current."""
install_dir = _current_install(tmp_path, monkeypatch, backend_request = "cpu", backend = "cpu")
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert "backend_request_unsatisfied" not in marker
assert _check(install_dir, backend_request = "cpu") is True
assert _check(install_dir, backend_request = "cpu", backend_request_mandatory = True) is True
def test_a_truncated_shared_library_is_not_current(tmp_path, monkeypatch):
"""The payload scan only checks that files exist, so a half-written libggml shared library
passes; most CUDA bundle bytes live there and a full disk leaves exactly this shape."""
install_dir = _current_install(tmp_path, monkeypatch)
library = install_dir / "build" / "bin" / "libggml-cpu-x64.so.0"
assert library.is_file()
library.write_bytes(b"")
assert _check(install_dir) is False
def test_the_payload_records_cover_the_bundles_own_allowlist(tmp_path, monkeypatch):
"""Not just the three binaries: every file runtime_patterns_for_install_kind names."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
patterns = INSTALL_LLAMA_PREBUILT.runtime_patterns_for_install_kind("linux-cpu")
records = runtime_file_records(install_dir, linux_host(), patterns)
assert "build/bin/libggml-base.so.0" in records
assert records["build/bin/libggml-base.so.0"]["size"] == 3
assert "sha256" not in records["build/bin/libggml-base.so.0"]
assert len(records["build/bin/llama-server"]["sha256"]) == 64
real_sha256_file = INSTALL_LLAMA_PREBUILT.sha256_file
def denied(path):
if path.name == "llama-server":
raise PermissionError("held by a scanner")
return real_sha256_file(path)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "sha256_file", denied)
assert runtime_file_records(install_dir, linux_host(), patterns) == {}
def test_the_reuse_path_backfills_what_the_no_network_check_needs(tmp_path, monkeypatch):
"""Installs from before the new evidence existed would take the slow path on every update, so
the reuse path, the only place that sees them, backfills the record once."""
install_dir = _current_install(
tmp_path,
monkeypatch,
runtime_sha256 = None,
runtime_files = None,
host_profile = None,
)
assert _check(install_dir) is False
sync_marker_selection(
install_dir,
choice = asset_choice(),
backend_request = "auto",
host = linux_host(),
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert "runtime_sha256" in marker
assert marker["host_profile"] == host_profile(linux_host())
assert "build/bin/libggml-base.so.0" in marker["runtime_files"]
assert _check(install_dir) is True
def test_an_empty_runtime_record_is_backfilled_like_an_absent_one(tmp_path, monkeypatch):
"""runtime_file_records answers {} for an unreadable binary; a persisted empty record would fail
the no-network check closed forever, so reuse must backfill it."""
install_dir = _current_install(tmp_path, monkeypatch, runtime_files = {})
assert _check(install_dir) is False
sync_marker_selection(
install_dir,
choice = asset_choice(),
backend_request = "auto",
host = linux_host(),
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert marker["runtime_files"]
assert _check(install_dir) is True
def test_the_backfill_never_overwrites_evidence_a_run_already_recorded(tmp_path, monkeypatch):
"""Added only, for the hashes: a key already present was written by a run that
hashed the bytes, and a reuse decision must not re-bless them."""
install_dir = _current_install(tmp_path, monkeypatch)
before = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
(install_dir / "build" / "bin" / "libggml-base.so.0").write_bytes(b"replaced after install")
sync_marker_selection(
install_dir,
choice = asset_choice(),
backend_request = "auto",
host = linux_host(),
)
after = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert after["runtime_files"] == before["runtime_files"]
assert after["runtime_sha256"] == before["runtime_sha256"]
def test_the_reuse_path_refreshes_a_stale_host_profile(tmp_path, monkeypatch):
"""Reuse must refresh a stale host profile, or every later update takes the full path."""
install_dir = _current_install(
tmp_path, monkeypatch, install_host = linux_host(**_CUDA_HOST_FIELDS)
)
_detects(monkeypatch, linux_host())
assert _check(install_dir) is False
sync_marker_selection(
install_dir,
choice = asset_choice(),
backend_request = "auto",
host = linux_host(),
)
marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8"))
assert marker["host_profile"] == host_profile(linux_host())
assert _check(install_dir) is True
def test_a_fallback_bundle_is_retried_rather_than_kept(tmp_path, monkeypatch):
"""A bundle that landed because the preferred one could not be fetched is recorded
with prebuilt_fallback_used; the full path is what retries the preferred bundle."""
install_dir = _current_install(tmp_path, monkeypatch, prebuilt_fallback_used = True)
assert _check(install_dir) is False
install_dir = _current_install(tmp_path / "again", monkeypatch, prebuilt_fallback_used = False)
assert _check(install_dir) is True
def test_a_release_pin_still_honours_an_upstream_pin(tmp_path, monkeypatch):
"""The full path checks a pinned release against a concrete UNSLOTH_LLAMA_TAG too."""
install_dir = _current_install(tmp_path, monkeypatch)
assert _check(install_dir, published_release_tag = "release-1", llama_tag = "b9001") is True
assert _check(install_dir, published_release_tag = "release-1", llama_tag = "b9999") is False
def test_a_different_cpu_architecture_is_not_current(tmp_path, monkeypatch):
"""Every GPU field can be equal across an x86_64 and an arm64 box; the profile has
to carry the architecture the bundle was built for."""
assert host_profile(linux_host())["machine"] == "x86_64"
stale = dict(host_profile(linux_host()), machine = "aarch64")
install_dir = _current_install(tmp_path, monkeypatch, host_profile = stale)
assert _check(install_dir) is False
def test_a_hand_edited_marker_is_not_trusted(tmp_path, monkeypatch):
"""The fingerprint is recomputed from the marker's own fields, so a field changed
without the fingerprint no longer adds up."""
install_dir = _current_install(tmp_path, monkeypatch, asset = "some-other-bundle.tar.gz")
assert _check(install_dir) is False
def test_a_truncated_binary_is_not_current(tmp_path, monkeypatch):
"""The check this replaces started llama-server. Hashing the recorded binaries
answers the same question in ~100 ms."""
install_dir = _current_install(tmp_path, monkeypatch)
assert _check(install_dir) is True
(install_dir / "build" / "bin" / "llama-server").write_text("", encoding = "utf-8")
assert _check(install_dir) is False
def test_a_swapped_binary_of_the_same_size_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
target = install_dir / "build" / "bin" / "llama-quantize"
original = target.read_text(encoding = "utf-8")
target.write_text("X" * len(original), encoding = "utf-8")
target.chmod(0o755)
assert _check(install_dir) is False
def test_a_deleted_binary_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
(install_dir / "llama-server").unlink()
assert _check(install_dir) is False
def test_a_gutted_runtime_payload_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
(install_dir / "build" / "bin" / "libggml-base.so.0").unlink()
assert _check(install_dir) is False
@pytest.mark.skipif(os.name == "nt", reason = "os.chmod cannot clear an execute bit Windows lacks")
def test_a_non_executable_binary_is_not_current(tmp_path, monkeypatch):
install_dir = _current_install(tmp_path, monkeypatch)
(install_dir / "build" / "bin" / "llama-server").chmod(0o644)
assert _check(install_dir) is False
def test_no_marker_at_all_is_not_current(tmp_path, monkeypatch):
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda **_k: linux_host())
assert _check(install_dir) is False
def test_the_records_cover_both_copies_of_each_binary(tmp_path):
"""_find_llama_server_binary reaches the root copy first and, without a symlink,
the two can rot independently."""
install_dir = tmp_path / "llama.cpp"
install_dir.mkdir()
write_linux_install_shape(install_dir)
records = runtime_file_records(install_dir, linux_host())
assert set(records) == {
"llama-server",
"llama-quantize",
"build/bin/llama-server",
"build/bin/llama-quantize",
}
for record in records.values():
assert record["size"] > 0 and len(record["sha256"]) == 64
def test_the_skip_log_carries_the_string_the_setup_scripts_grep_for(tmp_path, monkeypatch, capsys):
"""setup.sh and setup.ps1 both match the loose substring "already matches" to
report "prebuilt up to date and validated" rather than "installed and validated"."""
install_dir = _current_install(tmp_path, monkeypatch)
assert _check(install_dir) is True
captured = capsys.readouterr()
assert "already matches" in captured.out + captured.err
def test_a_route_the_caller_already_made_is_not_recomputed(tmp_path, monkeypatch):
"""Routing runs nvidia-smi and the ROCm probes. install_prebuilt routes once and
hands the same answer to this check and to the selector, so an update that does find
a new release does not probe the host twice."""
install_dir = _current_install(tmp_path, monkeypatch)
route = INSTALL_LLAMA_PREBUILT.route_backend_request(
backend = "auto",
published_repo = "unslothai/llama.cpp",
published_release_tag = "",
)
def boom(**_kwargs):
raise AssertionError("the caller already routed this host")
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "route_backend_request", boom)
assert _check(install_dir, route = route) is True
def test_the_profile_sees_an_nvidia_adapter_that_is_present_but_not_usable():
"""Intel and ROCm-less AMD routes go to Vulkan only when no NVIDIA adapter is present at all, so
the profile must track has_physical_nvidia apart from has_usable_nvidia."""
host = linux_host(has_intel_gpu = True)
assert host_profile(host)["has_physical_nvidia"] is False
with_adapter = dataclasses.replace(host, has_physical_nvidia = True)
assert host_profile(with_adapter)["has_physical_nvidia"] is True
assert host_profile(with_adapter) != host_profile(host)
def test_the_full_path_holds_a_marker_to_the_runtime_files_it_recorded(tmp_path, monkeypatch):
"""The Linux and macOS preflights read the executable images; Windows has no such
probe, so a truncated llama-server.exe used to keep its fingerprint match on the
full path and be reused. The recorded sizes and digests answer on every platform."""
install_dir = _current_install(tmp_path, monkeypatch)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT, "preflight_linux_installed_binaries", lambda *a, **k: None
)
choice = asset_choice()
checksums = release_checksums((choice.name, choice.expected_sha256, UPSTREAM))
kwargs = dict(
llama_tag = "b9001", release_tag = "release-1", choice = choice, approved_checksums = checksums
)
assert existing_install_matches_choice(install_dir, linux_host(), **kwargs) is True
server = install_dir / "build" / "bin" / "llama-server"
original = server.read_bytes()
server.write_bytes(original[: max(1, len(original) // 2)])
assert existing_install_matches_choice(install_dir, linux_host(), **kwargs) is False
server.write_bytes(original)
assert existing_install_matches_choice(install_dir, linux_host(), **kwargs) is True
marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
marker = json.loads(marker_path.read_text(encoding = "utf-8"))
marker.pop("runtime_files", None)
marker_path.write_text(json.dumps(marker), encoding = "utf-8")
server.write_bytes(original[: max(1, len(original) // 2)])
assert existing_install_matches_choice(install_dir, linux_host(), **kwargs) is True
def test_the_api_latest_lookup_scans_the_pages_the_selector_scans(monkeypatch):
"""published_at ordering: a release drafted early and published late sits on a later
page of a big repository, and one page would report an older marker current."""
seen = {}
def fake_releases(repo, max_pages = 0):
seen["max_pages"] = max_pages
return [{"tag_name": "release-2", "published_at": "2026-01-02T00:00:00Z"}]
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "github_releases", fake_releases)
assert INSTALL_LLAMA_PREBUILT._api_newest_release_tag("someone/else") == "release-2"
assert seen["max_pages"] == INSTALL_LLAMA_PREBUILT.DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES
def test_latest_on_an_older_mac_expects_the_pinned_upstream_fallback(monkeypatch):
"""On an older Mac, latest is the pinned fallback release, so a current install takes the fast path."""
host = macos_host(macos_version = (15, 5))
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_api_newest_release_tag",
lambda repo: pytest.fail("listed releases"),
)
monkeypatch.setattr(
INSTALL_LLAMA_PREBUILT,
"_download_host_latest_release_tag",
lambda repo: pytest.fail("resolved latest"),
)
marker = {"release_tag": INSTALL_LLAMA_PREBUILT._PINNED_MACOS_FALLBACK_TAG}
assert (
INSTALL_LLAMA_PREBUILT._expected_release_tag_without_plan(
marker, "latest", INSTALL_LLAMA_PREBUILT.UPSTREAM_REPO, "", host = host
)
== INSTALL_LLAMA_PREBUILT._PINNED_MACOS_FALLBACK_TAG
)
newer = macos_host(macos_version = (26, 0))
monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_api_newest_release_tag", lambda repo: "b9999")
assert (
INSTALL_LLAMA_PREBUILT._expected_release_tag_without_plan(
marker, "latest", INSTALL_LLAMA_PREBUILT.UPSTREAM_REPO, "", host = newer
)
== "b9999"
)
def test_a_pinned_upstream_build_expects_the_newest_fork_packaging_of_it(monkeypatch):
"""The fork can republish a build (b9596-mix-aaa, then b9596-mix-bbb) and the selector installs
the newest packaging, so the marker check must ask the same question."""
M = INSTALL_LLAMA_PREBUILT
releases = [
{"tag_name": "b9600-mix-ccc", "published_at": "2026-03-01T00:00:00Z", "id": 3},
{"tag_name": "b9596-mix-bbb", "published_at": "2026-02-01T00:00:00Z", "id": 2},
{"tag_name": "b9596-mix-aaa", "published_at": "2026-01-01T00:00:00Z", "id": 1},
]
monkeypatch.setattr(M, "github_releases", lambda repo, **kw: releases)
marker = {"tag": "b9596", "release_tag": "b9596-mix-aaa"}
expected = M._expected_release_tag_without_plan(marker, "b9596", M.DEFAULT_PUBLISHED_REPO, "")
assert expected == "b9596-mix-bbb"
assert expected != marker["release_tag"]
assert (
M._expected_release_tag_without_plan(
{"tag": "b9500", "release_tag": "x"}, "b9596", M.DEFAULT_PUBLISHED_REPO, ""
)
is None
)
monkeypatch.setattr(M, "github_releases", lambda repo, **kw: pytest.fail("listed upstream"))
assert (
M._expected_release_tag_without_plan(
{"tag": "b9596", "release_tag": "b9596"}, "b9596", M.UPSTREAM_REPO, ""
)
== "b9596"
)
monkeypatch.setattr(M, "github_releases", lambda repo, **kw: pytest.fail("listed the repo"))
assert (
M._expected_release_tag_without_plan(
{"tag": "b9596", "release_tag": "b9596"}, "b9596", "someone/else", ""
)
== "b9596"
)
monkeypatch.setattr(
M,
"github_releases",
lambda repo, **kw: [
{"tag_name": "abc1234-mix-1", "published_at": "2026-01-01T00:00:00Z"},
{"tag_name": "abc1234-mix-2", "published_at": "2026-01-02T00:00:00Z"},
],
)
assert (
M._expected_release_tag_without_plan(
{"tag": "abc1234", "release_tag": "abc1234-mix-1"}, "abc1234", "someone/else", ""
)
== "abc1234-mix-2"
)
def test_a_moved_torch_cuda_preference_declines_the_marker_fast_path(monkeypatch):
"""torch moving from a CUDA 12 to a CUDA 13 build leaves the GPU and driver, and so
the host profile, unchanged; the selector would still reorder the bundles around it."""
M = INSTALL_LLAMA_PREBUILT
from types import SimpleNamespace
host = SimpleNamespace(has_usable_nvidia = True, is_linux = True, is_windows = False)
monkeypatch.setattr(
M,
"detect_torch_cuda_runtime_preference",
lambda _host: SimpleNamespace(runtime_line = "cuda13", selection_log = []),
)
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda12", "cuda13"], {}))
monkeypatch.setattr(M, "compatible_linux_runtime_lines", lambda _h: ["cuda12", "cuda13"])
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, host) is True
assert M._runtime_preference_moved({"runtime_line": "cuda13"}, host) is False
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda12", "torch_runtime_preference": "cuda13"}, host
)
is False
)
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda13", "torch_runtime_preference": "cuda12"}, host
)
is True
)
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda12", "torch_runtime_preference": None}, host
)
is True
)
monkeypatch.setattr(
M,
"detect_torch_cuda_runtime_preference",
lambda _host: SimpleNamespace(runtime_line = None, selection_log = []),
)
monkeypatch.setattr(M, "_host_is_blackwell", lambda _h: False)
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda13", "cuda12"], {}))
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda12", "torch_runtime_preference": "cuda12"}, host
)
is True
)
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda13", "torch_runtime_preference": "cuda12"}, host
)
is False
)
monkeypatch.setattr(M, "_host_is_blackwell", lambda _h: True)
assert (
M._runtime_preference_moved(
{"runtime_line": "cuda12", "torch_runtime_preference": "cuda12"}, host
)
is False
)
monkeypatch.setattr(M, "_host_is_blackwell", lambda _h: False)
monkeypatch.setattr(
M,
"detect_torch_cuda_runtime_preference",
lambda _host: SimpleNamespace(runtime_line = "cuda13", selection_log = []),
)
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda12"], {}))
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, host) is False
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda12", "cuda13"], {}))
monkeypatch.setattr(M, "compatible_linux_runtime_lines", lambda _h: ["cuda12"])
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, host) is False
monkeypatch.setattr(M, "compatible_linux_runtime_lines", lambda _h: ["cuda12", "cuda13"])
windows = SimpleNamespace(has_usable_nvidia = True, is_linux = False, is_windows = True)
monkeypatch.setattr(M, "detected_windows_runtime_lines", lambda: ([], {}))
monkeypatch.setattr(M, "compatible_windows_runtime_lines", lambda _h: ["cuda12", "cuda13"])
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, windows) is True
monkeypatch.setattr(M, "compatible_windows_runtime_lines", lambda _h: ["cuda12"])
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, windows) is False
assert M._runtime_preference_moved({"runtime_line": "vulkan"}, host) is False
monkeypatch.setattr(
M,
"detect_torch_cuda_runtime_preference",
lambda _host: SimpleNamespace(runtime_line = None, selection_log = []),
)
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, host) is False
cpu_host = SimpleNamespace(has_usable_nvidia = False, is_linux = True, is_windows = False)
assert M._runtime_preference_moved({"runtime_line": "cuda12"}, cpu_host) is False
def test_the_host_profile_carries_the_cuda_runtimes_on_disk(monkeypatch):
"""CUDA selectors order bundles by the runtimes on disk too; a runtime that appeared since
install changes selection with GPU and driver unchanged, so the profile must carry it."""
M = INSTALL_LLAMA_PREBUILT
host = linux_host(compute_caps = ["8.9"], has_physical_nvidia = True, has_usable_nvidia = True)
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda12"], {}))
before = M.host_profile(host)
assert before["cuda_runtime_lines"] == ["cuda12"]
monkeypatch.setattr(M, "detected_linux_runtime_lines", lambda: (["cuda13", "cuda12"], {}))
after = M.host_profile(host)
assert after["cuda_runtime_lines"] == ["cuda12", "cuda13"]
assert before != after
cpu = linux_host(has_physical_nvidia = False, has_usable_nvidia = False)
assert M.host_profile(cpu)["cuda_runtime_lines"] is None
def test_the_host_profile_records_the_rocm_runtime_the_upstream_selector_reads(monkeypatch):
"""resolve_upstream_asset_choice picks among ROCm 6.4 and 7.2 assets by the runtime's
major.minor; a profile without it kept the old asset current across a ROCm move."""
import dataclasses
from types import SimpleNamespace
M = INSTALL_LLAMA_PREBUILT
host = linux_host()
try:
rocm_host = dataclasses.replace(host, has_rocm = True)
except TypeError:
rocm_host = SimpleNamespace(
**{k: getattr(host, k) for k in dir(host) if not k.startswith("_")}
)
rocm_host.has_rocm = True
monkeypatch.setattr(M, "_detect_host_rocm_version", lambda: (6, 4))
assert M.host_profile(rocm_host)["rocm_runtime"] == [6, 4]
monkeypatch.setattr(M, "_detect_host_rocm_version", lambda: (7, 2))
assert M.host_profile(rocm_host)["rocm_runtime"] == [7, 2]
monkeypatch.setattr(M, "_detect_host_rocm_version", lambda: None)
assert M.host_profile(rocm_host)["rocm_runtime"] is None
monkeypatch.setattr(M, "_detect_host_rocm_version", lambda: pytest.fail("probed the runtime"))
assert M.host_profile(host)["rocm_runtime"] is None
def test_the_marker_fast_path_accepts_a_recorded_macos_walk_back():
"""A recorded macOS walk-back satisfies the check, but a release newer than the record does not."""
met = INSTALL_LLAMA_PREBUILT._release_expectation_met
marker = {"release_tag": "r1", "walked_back_from": "r2", "walked_back_on_macos": "14.7"}
mac = macos_host(macos_version = (14, 7))
assert met(marker, "r1", mac) is True
assert met(marker, "r2", mac) is True
assert met(marker, "r3", mac) is False
assert met(marker, None, mac) is False
assert met(marker, "r2", macos_host(macos_version = (15, 0))) is False
assert met(marker, "r2", macos_host(macos_version = None)) is False
assert met(marker, "r2", linux_host()) is False
assert met({"release_tag": "r1"}, "r2", mac) is False
assert met({"release_tag": "r1", "walked_back_from": "r2"}, "r2", mac) is False
assert (
met({"release_tag": "r1", "walked_back_from": "", "walked_back_on_macos": "14.7"}, "", mac)
is False
)
def test_the_planner_records_the_newest_release_a_mac_walked_past(monkeypatch):
module = INSTALL_LLAMA_PREBUILT
bundles = [
module.PublishedReleaseBundle(
repo = "unslothai/llama.cpp", release_tag = "r2", upstream_tag = "b9002"
),
module.PublishedReleaseBundle(
repo = "unslothai/llama.cpp", release_tag = "r1", upstream_tag = "b9001"
),
]
monkeypatch.setattr(
module,
"iter_resolved_published_releases",
lambda *args, **kwargs: [
module.ResolvedPublishedRelease(
bundle = bundle,
checksums = release_checksums(
release_tag = bundle.release_tag, upstream_tag = bundle.upstream_tag
),
)
for bundle in bundles
],
)
def choose(host, resolved_tag, bundle, checksums):
if bundle.release_tag == "r2":
raise module.PrebuiltFallback("macOS 15.0 or newer required")
return [types.SimpleNamespace(selection_log = [])]
monkeypatch.setattr(module, "resolve_release_asset_choice", choose)
host = macos_host(macos_version = (14, 7))
_, plans = module._fork_manifest_release_plans("latest", host, "unslothai/llama.cpp", "")
assert [plan.release_tag for plan in plans] == ["r1"]
assert plans[0].walk_back == module._core.WalkBack(release_tag = "r2", macos_version = "14.7")
monkeypatch.setattr(
module,
"resolve_release_asset_choice",
lambda *args, **kwargs: [types.SimpleNamespace(selection_log = [])],
)
_, plans = module._fork_manifest_release_plans("latest", host, "unslothai/llama.cpp", "")
assert plans[0].release_tag == "r2"
assert plans[0].walk_back is None
def test_a_late_rocm_listing_failure_keeps_the_vulkan_plan(monkeypatch):
module = INSTALL_LLAMA_PREBUILT
vulkan = release_plan([asset_choice(install_kind = "linux-vulkan")], release_checksums())
def rocm_plans():
yield vulkan
raise urllib.error.URLError("CDN down, API timed out")
monkeypatch.setattr(
module,
"resolve_simple_install_release_plans",
lambda *args: ("latest", module.LazyReleasePlans(rocm_plans())),
)
kept = module._with_rocm_behind_vulkan([vulkan], "latest", linux_host(), "", "")
assert [plan.release_tag for plan in kept] == [vulkan.release_tag]
def test_a_reused_marker_takes_the_walk_back_this_run_made():
"""sync_marker_selection: a kept install on a Mac gains the walk-back record a
marker written before it existed lacks (both keys), and a plan that no longer
walks back retires a stale one."""
choice = asset_choice(
name = "llama-b9001-bin-macos-arm64.tar.gz", tag = "r1", source_label = "published"
)
walk_back = INSTALL_LLAMA_PREBUILT._core.WalkBack(release_tag = "r2", macos_version = "14.7")
def patch(marker, walk_back):
return INSTALL_LLAMA_PREBUILT._marker_selection_patch(
marker,
choice = choice,
backend_request = None,
persist_force_cpu = False,
persist_llama_backend = None,
ggml_tree = None,
rocm_gfx = None,
walk_back = walk_back,
)
marker = {"release_tag": "r1", "runtime_sha256": None}
gained = patch(marker, walk_back)
assert gained["walked_back_from"] == "r2" and gained["walked_back_on_macos"] == "14.7"
recorded = {**marker, **walk_back.marker_fields()}
assert not set(patch(recorded, walk_back)) & {"walked_back_from", "walked_back_on_macos"}
keys = {"walked_back_from", "walked_back_on_macos"}
def walk_back_part(result):
return {key: value for key, value in result.items() if key in keys}
assert walk_back_part(patch({**marker, "walked_back_from": "r2"}, walk_back)) == {
"walked_back_on_macos": "14.7"
}
upgraded = INSTALL_LLAMA_PREBUILT._core.WalkBack(release_tag = "r2", macos_version = "15.0")
assert walk_back_part(patch(recorded, upgraded)) == {"walked_back_on_macos": "15.0"}
assert not set(patch(marker, None)) & {"walked_back_from", "walked_back_on_macos"}
retired = patch(recorded, None)
assert retired["walked_back_from"] is None and retired["walked_back_on_macos"] is None