Skip to content

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

Studio: resolve upstream llama.cpp releases, assets and digests without the GitHub API (#5886)

Daniel Han1fd6b42d0777
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index b7eeca428f9..648c6a1ceb9 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -1021,12 +1021,67 @@ def github_releases(
return releases
+def web_release_tags(repo: str, *, limit: int = 30) -> list[str]:
+ return _core.web_release_tags(_OPS, repo, limit = limit)
+
+
+def web_release_payload(repo: str, tag: str) -> dict[str, Any]:
+ # Upstream publishes every bNNNN build as a prerelease, so the tag already answers
+ # the label question if its page cannot be reached.
+ default = True if repo == UPSTREAM_REPO and is_release_tag_like(tag) else None
+ return _core.web_release_payload(_OPS, repo, tag, prerelease_default = default)
+
+
+def upstream_web_release_tags(repo: str, *, limit: int = 30) -> list[str]:
+ """Recent upstream build tags, newest first, resolved without api.github.com.
+
+ Filtered to bNNNN: upstream's designated latest is a versioned pointer release
+ whose only asset is nightly-tag.txt, so it never names a release carrying binaries.
+ """
+ return [tag for tag in web_release_tags(repo, limit = limit) if is_release_tag_like(tag)]
+
+
def latest_upstream_release_tag() -> str:
- payload = fetch_json(UPSTREAM_RELEASES_API)
- tag = payload.get("tag_name")
- if not isinstance(tag, str) or not tag:
- raise RuntimeError(f"latest release tag was missing from {UPSTREAM_RELEASES_API}")
- return tag
+ """The newest upstream build tag, which the source-build fallback compiles.
+
+ Only a bNNNN REST answer is taken: /releases/latest resolves by make_latest, which
+ upstream points at a pointer release packaging no prebuilt, and the source build
+ must compile the version the prebuilt path would have installed.
+ """
+ rest_tag = ""
+ try:
+ payload = fetch_json(UPSTREAM_RELEASES_API)
+ tag = payload.get("tag_name")
+ if isinstance(tag, str) and tag:
+ rest_tag = tag
+ if is_release_tag_like(tag):
+ return tag
+ reason: Exception = RuntimeError(
+ f"{UPSTREAM_RELEASES_API} named {tag}, which is not a build release"
+ )
+ else:
+ reason = RuntimeError(f"latest release tag was missing from {UPSTREAM_RELEASES_API}")
+ except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
+ # A tokenless 403 surfaces as the RuntimeError fetch_json raises for a rate limit.
+ reason = exc
+ if not _web_fallback_eligible(UPSTREAM_REPO):
+ if rest_tag:
+ return rest_tag
+ raise reason
+ try:
+ tags = upstream_web_release_tags(UPSTREAM_REPO, limit = 10)
+ except Exception as exc: # noqa: BLE001 - the REST cause is the one worth reporting
+ if rest_tag:
+ log(f"could not resolve a build tag from the release feed ({exc}); using {rest_tag}")
+ return rest_tag
+ raise RuntimeError(f"{reason}; release feed fallback also failed: {exc}") from reason
+ if tags:
+ log(f"resolved the latest upstream build tag {tags[0]} from the release feed")
+ return tags[0]
+ if rest_tag:
+ log(f"the release feed listed no build tag; using {rest_tag}")
+ return rest_tag
+ raise reason
def is_release_tag_like(value: str | None) -> bool:
@@ -1051,13 +1106,91 @@ def release_time_sort_key(release: dict[str, Any]) -> tuple[str, int]:
return (timestamp, normalized_id)
+def release_is_selectable(repo: str, release: dict[str, Any]) -> bool:
+ """Whether a listed release may be planned against. A draft never is.
+
+ Nor is a prerelease, except an upstream bNNNN build: ggml-org marks every one of
+ them prerelease, so the plain rule strands the upstream path hundreds of builds
+ back on the newest release that is not one, and those publish no prebuilt at all.
+ """
+ if release.get("draft"):
+ return False
+ if repo == UPSTREAM_REPO:
+ # Upstream ships binaries only under bNNNN, and marks every one of them
+ # prerelease. Both halves matter: accepting the prerelease is what stops the
+ # path stranding hundreds of builds back, and refusing the versioned pointer
+ # releases is what stops one of them being named newest by the freshness check
+ # while the planner walks past it for want of an asset.
+ return is_release_tag_like(release.get("tag_name"))
+ return not release.get("prerelease")
+
+
+def _web_fallback_eligible(repo: str) -> bool:
+ """Whether <repo> may be resolved through github.com when the REST API is down.
+
+ Upstream only. The fork already has its own API-free path through the download
+ host (_download_host_resolved_release), and any other repo could publish assets
+ this parser has never seen.
+ """
+ return repo == UPSTREAM_REPO and _download_host_resolve_enabled()
+
+
+def _web_release_or_raise(repo: str, tag: str, reason: Exception) -> dict[str, Any]:
+ try:
+ release = web_release_payload(repo, tag)
+ except Exception as exc: # noqa: BLE001 - report both causes, neither alone explains it
+ raise RuntimeError(f"{reason}; release page fallback also failed: {exc}") from reason
+ log(
+ f"GitHub REST release listing failed ({reason}); resolved {repo}@{tag} "
+ "from its release page instead"
+ )
+ return release
+
+
+def _web_release_payloads(repo: str, reason: Exception) -> Iterable[dict[str, Any]]:
+ """Recent upstream releases, newest first, with no api.github.com call.
+
+ Lazy, one page at a time, so the caller's older-release walk-back still works and
+ only the releases actually looked at cost a request.
+ """
+ try:
+ tags = upstream_web_release_tags(repo, limit = DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES * 4)
+ except Exception as exc: # noqa: BLE001 - report both causes
+ raise RuntimeError(f"{reason}; release feed fallback also failed: {exc}") from reason
+ if not tags:
+ raise RuntimeError(
+ f"{reason}; the release feed for {repo} listed no build tags"
+ ) from reason
+ log(
+ f"GitHub REST release listing failed ({reason}); resolved {len(tags)} recent "
+ f"{repo} releases from the release feed instead"
+ )
+ for tag in tags:
+ try:
+ release = web_release_payload(repo, tag)
+ except Exception as exc: # noqa: BLE001 - one unreadable release is not the end of the walk
+ log(f"skipping {repo}@{tag}: {exc}")
+ continue
+ # The REST listing's rule, on a status read rather than assumed, so the two
+ # paths cannot select differently.
+ if not release_is_selectable(repo, release):
+ log(f"skipping {repo}@{tag}: not selectable (prerelease or draft)")
+ continue
+ yield release
+
+
def iter_release_payloads_by_time(
repo: str,
published_release_tag: str = "",
requested_tag: str = "",
) -> Iterable[dict[str, Any]]:
if published_release_tag:
- yield github_release(repo, published_release_tag)
+ try:
+ yield github_release(repo, published_release_tag)
+ except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
+ if not _web_fallback_eligible(repo):
+ raise
+ yield _web_release_or_raise(repo, published_release_tag, exc)
return
if requested_tag and requested_tag != "latest" and is_release_tag_like(requested_tag):
@@ -1065,17 +1198,37 @@ def iter_release_payloads_by_time(
yield github_release(repo, requested_tag)
return
except urllib.error.HTTPError as exc:
+ # HTTPError subclasses URLError, so this clause shadows the one below and
+ # must route the fallback itself; a 404 tag has no page to read either.
if exc.code == 404:
log(f"release tag {requested_tag} not found in {repo}; scanning recent releases")
+ elif _web_fallback_eligible(repo):
+ yield _web_release_or_raise(repo, requested_tag, exc)
+ return
else:
raise
+ except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
+ # A named release is one page, so a pin is what this path serves best; the
+ # macOS-floor pin (b9415) reaches here.
+ if not _web_fallback_eligible(repo):
+ raise
+ yield _web_release_or_raise(repo, requested_tag, exc)
+ return
except Exception:
raise
+ try:
+ listing = github_releases(repo, max_pages = DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES)
+ except RELEASE_LISTING_TRANSPORT_ERRORS as exc:
+ if not _web_fallback_eligible(repo):
+ raise
+ yield from _web_release_payloads(repo, exc)
+ return
+
releases = [
release
- for release in github_releases(repo, max_pages = DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES)
- if isinstance(release, dict) and not release.get("draft") and not release.get("prerelease")
+ for release in listing
+ if isinstance(release, dict) and release_is_selectable(repo, release)
]
releases.sort(key = release_time_sort_key, reverse = True)
for release in releases:
@@ -8460,18 +8613,18 @@ def prebuilt_full_check_requested() -> bool:
)
-def _newest_release_tag_from_releases(releases: "Iterable[Any]") -> "str | None":
+def _newest_release_tag_from_releases(repo: str, releases: "Iterable[Any]") -> "str | None":
"""The newest published release tag by published_at, the ordering _select uses.
- Mirrors iter_release_payloads_by_time's sort (release_time_sort_key, drafts and
- prereleases dropped) so the two cannot answer differently from the same payload.
+ Mirrors iter_release_payloads_by_time's sort and its repo-aware selectability rule,
+ hence the repo: answering differently here reports the freshly installed build as
+ stale and reinstalls it on every update run.
"""
published = [
release
for release in releases
if isinstance(release, dict)
- and not release.get("draft")
- and not release.get("prerelease")
+ and release_is_selectable(repo, release)
and isinstance(release.get("tag_name"), str)
and release.get("tag_name")
]
@@ -8489,7 +8642,7 @@ def _api_newest_release_tag(repo: str) -> "str | None":
"""
try:
return _newest_release_tag_from_releases(
- github_releases(repo, max_pages = DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES)
+ repo, github_releases(repo, max_pages = DEFAULT_GITHUB_RELEASE_SCAN_MAX_PAGES)
)
except Exception as exc: # noqa: BLE001 - unreachable is a reason to do the work
log(f"could not resolve the latest release from the GitHub API ({exc})")
@@ -8521,7 +8674,7 @@ def _api_newest_release_tag_for_upstream(
or release["tag_name"] == recorded_release
)
]
- return _newest_release_tag_from_releases(matching)
+ return _newest_release_tag_from_releases(repo, matching)
def _memoized_api_newest_release_tag(repo: str) -> "str | None":
@@ -8543,7 +8696,7 @@ def _memoized_api_newest_release_tag(repo: str) -> "str | None":
url = key[1]
if isinstance(url, str) and url.startswith(prefix) and isinstance(payload, list):
releases.extend(payload)
- return _newest_release_tag_from_releases(releases) if releases else None
+ return _newest_release_tag_from_releases(repo, releases) if releases else None
def _runtime_preference_moved(marker: "dict[str, Any]", host: HostInfo) -> bool:
diff --git a/studio/install_whisper_prebuilt.py b/studio/install_whisper_prebuilt.py
index 2b92a47ac02..6a455e3af6a 100644
--- a/studio/install_whisper_prebuilt.py
+++ b/studio/install_whisper_prebuilt.py
@@ -1932,7 +1932,9 @@ def _api_newest_release_tag_for_upstream(
or packaged.startswith(wanted + _PACKAGING_SUFFIX)
):
matching.append(release)
- return llama._newest_release_tag_from_releases(matching)
+ # Repo-aware selectability: whisper is never ggml-org/llama.cpp, so this is the
+ # plain drafts-and-prereleases-dropped rule it has always had.
+ return llama._newest_release_tag_from_releases(repo, matching)
def existing_install_current_without_plan(
diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.py
index 1f950f95272..0bc1d3b324d 100644
--- a/studio/prebuilt_core.py
+++ b/studio/prebuilt_core.py
@@ -1034,6 +1034,157 @@ def fetch_download_host_json(ops: ModuleOps, url: str) -> Any:
return json.loads(data.decode("utf-8"))
+_WEB_METADATA_MAX_BYTES = 4 * 1024 * 1024
+
+_ATOM_RELEASE_TAG_RE = re.compile(
+ r"<link[^>]+href=\"[^\"]*/releases/tag/(?P<tag>[^\"/?#]+)\"", re.IGNORECASE
+)
+
+_DOWNLOAD_HREF_RE = re.compile(
+ r"href=\"[^\"]*?/releases/download/(?P<tag>[^\"/]+)/(?P<name>[^\"/]+)\"", re.IGNORECASE
+)
+
+_CLIPBOARD_TAG_RE = re.compile(r"<clipboard-copy\b(?P<attrs>[^>]*)>", re.IGNORECASE)
+
+_ARIA_DIGEST_FOR_RE = re.compile(
+ r"aria-label=\"Copy to clipboard digest for (?P<name>[^\"]+)\"", re.IGNORECASE
+)
+
+_ATTR_DIGEST_RE = re.compile(r"value=\"sha256:(?P<hex>[0-9a-f]{64})\"", re.IGNORECASE)
+
+
+def _fetch_web_metadata(ops: ModuleOps, url: str) -> str:
+ """GET a github.com (not api.github.com) metadata page, unauthenticated.
+
+ The web host is outside the anonymous API's hourly budget, which is the whole point
+ of the callers below. No token is ever attached.
+ """
+ data = ops.download_bytes(
+ url,
+ timeout = 30,
+ headers = {"User-Agent": ops.USER_AGENT},
+ )
+ if len(data) > _WEB_METADATA_MAX_BYTES:
+ raise RuntimeError(f"release metadata page at {url} was implausibly large")
+ return data.decode("utf-8", "replace")
+
+
+def web_release_tags(
+ ops: ModuleOps,
+ repo: str,
+ *,
+ limit: int = 30,
+) -> list[str]:
+ """Recent release tags, newest first, from github.com/<repo>/releases.atom.
+
+ The only tokenless surface that ORDERS releases, so it is what restores the
+ older-release walk-back, and the only one that can name the newest nightly.
+ """
+ url = f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases.atom"
+ body = _fetch_web_metadata(ops, url)
+ tags: list[str] = []
+ for match in _ATOM_RELEASE_TAG_RE.finditer(body):
+ tag = urllib.parse.unquote(match.group("tag")).strip()
+ if tag and tag not in tags:
+ tags.append(tag)
+ if len(tags) >= limit:
+ break
+ return tags
+
+
+_PRERELEASE_LABEL_RE = re.compile(r"Label--warning[^>]*>\s*Pre-release\s*<", re.IGNORECASE)
+
+
+def web_release_prerelease(ops: ModuleOps, repo: str, tag: str) -> bool:
+ """Whether <repo>@<tag> is marked pre-release, read from its release page.
+
+ The feed and the asset fragment both omit it, and asserting a value we did not read
+ would let the web path select a release the REST path filters out. Draft is not
+ asked: a draft is not served anonymously, so reaching this page proves publication.
+ """
+ url = (
+ f"https://github.com/{urllib.parse.quote(repo, safe = '/')}/releases/tag/"
+ f"{urllib.parse.quote(tag, safe = '')}"
+ )
+ return _PRERELEASE_LABEL_RE.search(_fetch_web_metadata(ops, url)) is not None
+
+
+def _web_release_prerelease_or_default(
+ ops: ModuleOps, repo: str, tag: str, default: bool | None
+) -> bool:
+ """The release's prerelease flag, or *default* when the page cannot be read.
+
+ The assets and their digests have already loaded by this point, so discarding them
+ because one more request failed would drop a usable release for a fact the caller
+ may already know from the tag.
+ """
+ try:
+ return web_release_prerelease(ops, repo, tag)
+ except Exception as exc: # noqa: BLE001 - a known answer beats losing the release
+ if default is None:
+ raise
+ ops.log(f"could not read the release label for {repo}@{tag} ({exc}); assuming {default}")
+ return default
+
+
+def web_release_payload(
+ ops: ModuleOps,
+ repo: str,
+ tag: str,
+ *,
+ prerelease_default: bool | None = None,
+) -> dict[str, Any]:
+ """An ordinary release payload for <repo>@<tag>, built without api.github.com.
+
+ Shaped like the REST payload on purpose: release_asset_map and release_asset_digests
+ keep reading the same fields, so digest enforcement stays authoritative instead of
+ being bypassed by a second code path. An asset whose link is not for this exact repo
+ and tag, or whose digest is absent or not a sha256, is dropped rather than guessed
+ at, since these archives are extracted, chmod 0o755'd and executed.
+ """
+ quoted_repo = urllib.parse.quote(repo, safe = "/")
+ url = (
+ f"https://github.com/{quoted_repo}/releases/expanded_assets/"
+ f"{urllib.parse.quote(tag, safe = '')}"
+ )
+ body = _fetch_web_metadata(ops, url)
+ published = {
+ urllib.parse.unquote(row.group("name")).strip()
+ for row in _DOWNLOAD_HREF_RE.finditer(body)
+ if urllib.parse.unquote(row.group("tag")).strip() == tag
+ }
+ # The copy-to-clipboard control names its asset in the same element; pairing two
+ # lists by position would misassign a hash the first time a row moves or is omitted.
+ digests: dict[str, str] = {}
+ conflicting: set[str] = set()
+ for control in _CLIPBOARD_TAG_RE.finditer(body):
+ attrs = control.group("attrs")
+ labelled = _ARIA_DIGEST_FOR_RE.search(attrs)
+ value = _ATTR_DIGEST_RE.search(attrs)
+ if labelled is None or value is None:
+ continue
+ name = labelled.group("name").strip()
+ digest = value.group("hex").lower()
+ if digests.setdefault(name, digest) != digest:
+ conflicting.add(name)
+ assets = [
+ {
+ "name": name,
+ "browser_download_url": release_asset_download_url(repo, tag, name),
+ "digest": f"sha256:{digests[name]}",
+ }
+ for name in sorted(published & (digests.keys() - conflicting))
+ ]
+ if not assets:
+ raise RuntimeError(f"no digest-bearing assets were published for {repo}@{tag}")
+ return {
+ "tag_name": tag,
+ "draft": False,
+ "prerelease": _web_release_prerelease_or_default(ops, repo, tag, prerelease_default),
+ "assets": assets,
+ }
+
+
# ── Archive extraction (traversal/symlink guarded) ──
def extract_archive(archive_path: Path, destination: Path) -> None:
def safe_extract_path(base: Path, member_name: str) -> Path:
diff --git a/tests/studio/install/test_tokenless_release_resolution.py b/tests/studio/install/test_tokenless_release_resolution.py
new file mode 100644
index 00000000000..07208fce05f
--- /dev/null
+++ b/tests/studio/install/test_tokenless_release_resolution.py
@@ -0,0 +1,865 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for tokenless (no GH_TOKEN) llama.cpp release resolution.
+
+Cover the github.com fallback that resolves upstream releases, their assets and
+their sha256 digests when the rate-limited api.github.com REST surface is
+unavailable. All I/O is monkeypatched.
+"""
+
+import sys
+import urllib.error
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[3]
+STUDIO_DIR = ROOT / "studio"
+if str(STUDIO_DIR) not in sys.path:
+ sys.path.insert(0, str(STUDIO_DIR))
+
+import install_llama_prebuilt as INSTALL_LLAMA_PREBUILT # noqa: E402
+import prebuilt_core as PREBUILT_CORE # noqa: E402
+from install_llama_prebuilt import HostInfo # noqa: E402
+
+MOD = INSTALL_LLAMA_PREBUILT
+CORE = PREBUILT_CORE
+UPSTREAM = MOD.UPSTREAM_REPO
+
+DIGEST_A = "8a3a5d19721cbb5cfef58a28eb197d39ffc19a8cbf8a9a9927ecbff36d5c5806"
+DIGEST_B = "758b9df442bf57eb68f1aee566a9c6582601386703dc993ecc68b8fa91a5e3bc"
+
+
+def _host(**overrides) -> HostInfo:
+ base = dict(
+ system = "Darwin",
+ machine = "arm64",
+ is_windows = False,
+ is_linux = False,
+ is_macos = True,
+ is_x86_64 = False,
+ is_arm64 = True,
+ nvidia_smi = None,
+ driver_cuda_version = None,
+ compute_caps = [],
+ visible_cuda_devices = None,
+ has_physical_nvidia = False,
+ has_usable_nvidia = False,
+ has_rocm = False,
+ rocm_gfx_target = None,
+ )
+ base.update(overrides)
+ return HostInfo(**base)
+
+
+def _linux_cpu(**overrides) -> HostInfo:
+ return _host(
+ system = "Linux",
+ machine = "x86_64",
+ is_linux = True,
+ is_macos = False,
+ is_x86_64 = True,
+ is_arm64 = False,
+ **overrides,
+ )
+
+
+def _asset_row(repo: str, tag: str, name: str, digest: str | None) -> str:
+ """One asset row shaped like the fragment github.com serves for a release."""
+ row = (
+ f'<a href="/{repo}/releases/download/{tag}/{name}" rel="nofollow" '
+ f'class="wb-break-all"><span class="text-bold">{name}</span></a>'
+ )
+ if digest is not None:
+ row += (
+ f'<span class="Truncate-text">sha256:{digest}</span>'
+ f'<clipboard-copy id="clipboard-button-sha256:{digest}" '
+ f'aria-label="Copy to clipboard digest for {name}" type="button" '
+ f'value="sha256:{digest}" class="Button--invisible">copy</clipboard-copy>'
+ )
+ return row
+
+
+def _expanded_assets(repo: str, tag: str, assets: dict[str, str | None]) -> str:
+ rows = "".join(_asset_row(repo, tag, name, digest) for name, digest in assets.items())
+ return f'<div class="Box">{rows}</div>'
+
+
+def _atom(repo: str, tags: list[str]) -> str:
+ entries = "".join(
+ f'<entry><link rel="alternate" type="text/html" '
+ f'href="https://github.com/{repo}/releases/tag/{tag}"/><title>{tag}</title></entry>'
+ for tag in tags
+ )
+ return f'<?xml version="1.0"?><feed>{entries}</feed>'
+
+
+class _Web:
+ """Stands in for the github.com web host, recording every URL fetched."""
+
+ def __init__(self, pages: dict[str, str]):
+ self.pages = pages
+ self.urls: list[str] = []
+
+ def __call__(self, url: str, **kwargs) -> bytes:
+ self.urls.append(url)
+ for suffix, body in self.pages.items():
+ if url.endswith(suffix):
+ return body.encode("utf-8")
+ raise urllib.error.HTTPError(url, 404, "Not Found", None, None)
+
+
+def _tag_page(prerelease: bool = True) -> str:
+ """A release page, labelled the way github.com labels one.
+
+ Prerelease by default because ggml-org marks every bNNNN build release that way.
+ """
+ label = (
+ '<span class="Label Label--warning Label--large">Pre-release</span>'
+ if prerelease
+ else '<span class="Label Label--success Label--large">Latest</span>'
+ )
+ return f"<html><h1>release</h1>{label}</html>"
+
+
+def _install_web(
+ monkeypatch,
+ pages: dict[str, str],
+ *,
+ prerelease: bool = True,
+) -> _Web:
+ # Every release whose assets are served needs its release page served too, since
+ # that is where the prerelease status is read from.
+ pages = dict(pages)
+ for suffix in [key for key in pages if "expanded_assets/" in key]:
+ tag = suffix.rsplit("/", 1)[-1]
+ pages.setdefault(f"releases/tag/{tag}", _tag_page(prerelease))
+ web = _Web(pages)
+ monkeypatch.setattr(CORE, "download_bytes", lambda ops, url, **kw: web(url, **kw))
+ return web
+
+
+def _rest_403(*args, **kwargs):
+ raise RuntimeError(
+ "GitHub API returned 403 for "
+ "https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=100&page=1"
+ "; set GH_TOKEN or GITHUB_TOKEN to avoid GitHub API rate limits"
+ )
+
+
+def _boom(*args, **kwargs):
+ raise AssertionError("the tokenless path must not be used here")
+
+
+# ── the release feed ──
+
+
+class TestWebReleaseTags:
+ def test_parses_tags_newest_first(self, monkeypatch):
+ _install_web(monkeypatch, {"releases.atom": _atom(UPSTREAM, ["b11070", "b11069"])})
+ assert MOD.web_release_tags(UPSTREAM) == ["b11070", "b11069"]
+
+ def test_skips_the_versioned_pointer_release(self, monkeypatch):
+ # Upstream's /releases/latest points at v0.4.1, whose only asset is a text
+ # file naming a nightly. Selecting it would build 404-bound archive URLs.
+ _install_web(
+ monkeypatch, {"releases.atom": _atom(UPSTREAM, ["v0.4.1", "b11070", "b11069"])}
+ )
+ assert MOD.web_release_tags(UPSTREAM)[0] == "v0.4.1"
+ assert MOD.upstream_web_release_tags(UPSTREAM) == ["b11070", "b11069"]
+
+ def test_honours_the_limit(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {"releases.atom": _atom(UPSTREAM, [f"b{n}" for n in range(11070, 11060, -1)])},
+ )
+ assert MOD.web_release_tags(UPSTREAM, limit = 3) == ["b11070", "b11069", "b11068"]
+
+
+# ── the release page ──
+
+
+class TestWebReleasePayload:
+ def test_binds_each_digest_to_its_own_asset(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM,
+ "b11070",
+ {
+ "llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A,
+ "llama-b11070-bin-ubuntu-x64.tar.gz": DIGEST_B,
+ },
+ )
+ },
+ )
+ release = MOD.web_release_payload(UPSTREAM, "b11070")
+ assert release["tag_name"] == "b11070"
+ assert MOD.release_asset_digests(release) == {
+ "llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A,
+ "llama-b11070-bin-ubuntu-x64.tar.gz": DIGEST_B,
+ }
+
+ def test_urls_are_the_deterministic_release_asset_urls(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ )
+ release = MOD.web_release_payload(UPSTREAM, "b11070")
+ assert release["assets"][0]["browser_download_url"] == (
+ "https://github.com/ggml-org/llama.cpp/releases/download/b11070/"
+ "llama-b11070-bin-macos-arm64.tar.gz"
+ )
+
+ def test_drops_an_asset_with_no_published_digest(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM,
+ "b11070",
+ {
+ "llama-b11070-bin-macos-arm64.tar.gz": None,
+ "llama-b11070-bin-ubuntu-x64.tar.gz": DIGEST_B,
+ },
+ )
+ },
+ )
+ release = MOD.web_release_payload(UPSTREAM, "b11070")
+ assert [asset["name"] for asset in release["assets"]] == [
+ "llama-b11070-bin-ubuntu-x64.tar.gz"
+ ]
+
+ def test_drops_an_asset_whose_digest_is_stated_twice_and_differs(self, monkeypatch):
+ page = _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ) + (
+ '<clipboard-copy aria-label="Copy to clipboard digest for '
+ f'llama-b11070-bin-macos-arm64.tar.gz" value="sha256:{DIGEST_B}"></clipboard-copy>'
+ )
+ _install_web(monkeypatch, {"expanded_assets/b11070": page})
+ with pytest.raises(RuntimeError, match = "no digest-bearing assets"):
+ MOD.web_release_payload(UPSTREAM, "b11070")
+
+ def test_ignores_a_link_belonging_to_another_release(self, monkeypatch):
+ page = _expanded_assets(
+ UPSTREAM, "b11069", {"llama-b11069-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ _install_web(monkeypatch, {"expanded_assets/b11070": page})
+ with pytest.raises(RuntimeError, match = "no digest-bearing assets"):
+ MOD.web_release_payload(UPSTREAM, "b11070")
+
+ def test_a_digest_without_a_published_asset_is_not_invented(self, monkeypatch):
+ page = (
+ '<clipboard-copy aria-label="Copy to clipboard digest for ghost.tar.gz" '
+ f'value="sha256:{DIGEST_A}"></clipboard-copy>'
+ )
+ _install_web(monkeypatch, {"expanded_assets/b11070": page})
+ with pytest.raises(RuntimeError, match = "no digest-bearing assets"):
+ MOD.web_release_payload(UPSTREAM, "b11070")
+
+ def test_refuses_an_implausibly_large_page(self, monkeypatch):
+ monkeypatch.setattr(CORE, "download_bytes", lambda ops, url, **kw: b"x" * (8 * 1024 * 1024))
+ with pytest.raises(RuntimeError, match = "implausibly large"):
+ MOD.web_release_payload(UPSTREAM, "b11070")
+
+ def test_never_sends_an_authorization_header(self, monkeypatch):
+ seen = {}
+
+ def capture(ops, url, **kwargs):
+ seen[url] = kwargs.get("headers") or {}
+ return _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ).encode("utf-8")
+
+ monkeypatch.setattr(CORE, "download_bytes", capture)
+ MOD.web_release_payload(UPSTREAM, "b11070")
+ assert seen
+ for headers in seen.values():
+ assert not any(key.lower() == "authorization" for key in headers)
+
+
+# ── latest_upstream_release_tag ──
+
+
+class TestLatestUpstreamReleaseTag:
+ def test_uses_the_rest_api_first(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "b500"})
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ assert MOD.latest_upstream_release_tag() == "b500"
+
+ def test_falls_back_to_the_feed_on_a_rate_limit(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", _rest_403)
+ _install_web(monkeypatch, {"releases.atom": _atom(UPSTREAM, ["v0.4.1", "b11070"])})
+ assert MOD.latest_upstream_release_tag() == "b11070"
+
+ def test_falls_back_when_rest_states_no_tag(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {})
+ _install_web(monkeypatch, {"releases.atom": _atom(UPSTREAM, ["b11070"])})
+ assert MOD.latest_upstream_release_tag() == "b11070"
+
+ def test_both_paths_failing_reports_both_causes(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", _rest_403)
+ _install_web(monkeypatch, {})
+ with pytest.raises(RuntimeError) as excinfo:
+ MOD.latest_upstream_release_tag()
+ assert "403" in str(excinfo.value)
+ assert "feed fallback also failed" in str(excinfo.value)
+
+
+# ── iter_release_payloads_by_time ──
+
+
+class TestIterReleasePayloads:
+ def test_rest_listing_wins_when_it_answers(self, monkeypatch):
+ rest = {"tag_name": "b1234", "assets": []}
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: [rest])
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ assert list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest")) == [rest]
+
+ def test_rate_limited_listing_walks_the_feed_newest_first(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070", "b11069"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ "expanded_assets/b11069": _expanded_assets(
+ UPSTREAM, "b11069", {"llama-b11069-bin-macos-arm64.tar.gz": DIGEST_B}
+ ),
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert [release["tag_name"] for release in got] == ["b11070", "b11069"]
+
+ def test_the_walk_is_lazy(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ web = _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070", "b11069"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ "expanded_assets/b11069": _expanded_assets(
+ UPSTREAM, "b11069", {"llama-b11069-bin-macos-arm64.tar.gz": DIGEST_B}
+ ),
+ },
+ )
+ releases = MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest")
+ assert next(iter(releases))["tag_name"] == "b11070"
+ assert not any("b11069" in url for url in web.urls)
+
+ def test_an_unreadable_release_is_skipped_not_fatal(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070", "b11069"]),
+ "expanded_assets/b11069": _expanded_assets(
+ UPSTREAM, "b11069", {"llama-b11069-bin-macos-arm64.tar.gz": DIGEST_B}
+ ),
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert [release["tag_name"] for release in got] == ["b11069"]
+
+ def test_a_pinned_tag_resolves_through_its_release_page(self, monkeypatch):
+ # The macOS floor pin (b9415) arrives here as requested_tag, and is exactly the
+ # population the pin exists to serve, so it must not be left on the source build.
+ monkeypatch.setattr(MOD, "github_release", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b9415": _expanded_assets(
+ UPSTREAM, "b9415", {"llama-b9415-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "b9415"))
+ assert [release["tag_name"] for release in got] == ["b9415"]
+
+ def test_the_fork_never_uses_the_upstream_web_path(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ with pytest.raises(RuntimeError, match = "403"):
+ list(MOD.iter_release_payloads_by_time(MOD.DEFAULT_PUBLISHED_REPO, "", "latest"))
+
+ def test_the_escape_hatch_disables_the_web_path(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_LLAMA_DISABLE_DOWNLOAD_HOST_RESOLVE", "1")
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ with pytest.raises(RuntimeError, match = "403"):
+ list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+
+ def test_both_paths_failing_reports_both_causes(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(monkeypatch, {})
+ with pytest.raises(RuntimeError) as excinfo:
+ list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert "403" in str(excinfo.value)
+ assert "feed fallback also failed" in str(excinfo.value)
+
+
+# ── end to end, through the real planner ──
+
+
+def _plans(host, requested = "latest"):
+ return MOD.resolve_simple_install_release_plans(requested, host, UPSTREAM, "")
+
+
+class TestEndToEnd:
+ def test_macos_installs_a_digest_verified_prebuilt_when_rest_is_rate_limited(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["v0.4.1", "b11070"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ },
+ )
+ requested, plans = _plans(_host())
+ assert requested == "latest"
+ assert len(plans) == 1
+ attempt = plans[0].attempts[0]
+ assert attempt.name == "llama-b11070-bin-macos-arm64.tar.gz"
+ assert attempt.url == (
+ "https://github.com/ggml-org/llama.cpp/releases/download/b11070/"
+ "llama-b11070-bin-macos-arm64.tar.gz"
+ )
+ # The point of the whole path: the archive is still bound to a published digest.
+ assert attempt.expected_sha256 == DIGEST_A
+
+ def test_linux_x64_installs_a_digest_verified_prebuilt(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-ubuntu-x64.tar.gz": DIGEST_B}
+ ),
+ },
+ )
+ _requested, plans = _plans(_linux_cpu())
+ attempt = plans[0].attempts[0]
+ assert attempt.name == "llama-b11070-bin-ubuntu-x64.tar.gz"
+ assert attempt.expected_sha256 == DIGEST_B
+
+ def test_an_asset_with_no_digest_is_refused_not_installed(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": None}
+ ),
+ },
+ )
+ with pytest.raises(MOD.PrebuiltFallback):
+ _plans(_host())
+
+ def test_a_release_without_this_hosts_archive_falls_back_to_an_older_one(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070", "b11069"]),
+ # b11070 published Linux only, so a macOS host must walk back.
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-ubuntu-x64.tar.gz": DIGEST_B}
+ ),
+ "expanded_assets/b11069": _expanded_assets(
+ UPSTREAM, "b11069", {"llama-b11069-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ },
+ )
+ _requested, plans = _plans(_host())
+ assert plans[0].attempts[0].name == "llama-b11069-bin-macos-arm64.tar.gz"
+
+
+# ── prerelease parity between the two paths ──
+
+
+class TestPrereleaseStatus:
+ def test_the_payload_states_the_status_it_read(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ prerelease = True,
+ )
+ assert MOD.web_release_payload(UPSTREAM, "b11070")["prerelease"] is True
+
+ def test_a_release_without_the_label_is_not_reported_as_prerelease(self, monkeypatch):
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ prerelease = False,
+ )
+ assert MOD.web_release_payload(UPSTREAM, "b11070")["prerelease"] is False
+
+ def test_an_upstream_build_release_stays_selectable_when_marked_prerelease(self):
+ # ggml-org marks every bNNNN build prerelease; excluding them strands the
+ # upstream path on the newest release that is not one, which ships no prebuilt.
+ assert MOD.release_is_selectable(UPSTREAM, {"tag_name": "b11070", "prerelease": True})
+
+ def test_a_non_build_prerelease_is_still_refused(self):
+ assert not MOD.release_is_selectable(
+ UPSTREAM, {"tag_name": "v0.5.0-rc1", "prerelease": True}
+ )
+
+ def test_the_fork_keeps_the_plain_rule(self):
+ assert not MOD.release_is_selectable(
+ MOD.DEFAULT_PUBLISHED_REPO, {"tag_name": "b11070", "prerelease": True}
+ )
+
+ def test_a_draft_is_never_selectable(self):
+ assert not MOD.release_is_selectable(UPSTREAM, {"tag_name": "b11070", "draft": True})
+
+ def test_the_rest_path_keeps_a_prerelease_build(self, monkeypatch):
+ rest = {"tag_name": "b11070", "prerelease": True, "draft": False, "assets": []}
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: [rest])
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert [release["tag_name"] for release in got] == ["b11070"]
+
+ def test_the_web_path_keeps_the_same_prerelease_build(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ },
+ prerelease = True,
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert [release["tag_name"] for release in got] == ["b11070"]
+ assert got[0]["prerelease"] is True
+
+ def test_the_web_walk_skips_a_release_the_rest_path_would_filter(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11070"]),
+ "expanded_assets/b11070": _expanded_assets(
+ UPSTREAM, "b11070", {"llama-b11070-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ },
+ )
+ monkeypatch.setattr(MOD, "release_is_selectable", lambda repo, release: False)
+ assert list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest")) == []
+
+
+# ── a pinned published release ──
+
+
+class TestPinnedPublishedRelease:
+ def test_a_pinned_published_release_resolves_through_its_release_page(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_release", _rest_403)
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b9415": _expanded_assets(
+ UPSTREAM, "b9415", {"llama-b9415-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "b9415", "latest"))
+ assert [release["tag_name"] for release in got] == ["b9415"]
+
+ def test_a_pinned_published_release_on_the_fork_still_re_raises(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_release", _rest_403)
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ with pytest.raises(RuntimeError, match = "403"):
+ list(MOD.iter_release_payloads_by_time(MOD.DEFAULT_PUBLISHED_REPO, "b9415", "latest"))
+
+ def test_rest_still_wins_for_a_pinned_published_release(self, monkeypatch):
+ rest = {"tag_name": "b9415", "assets": []}
+ monkeypatch.setattr(MOD, "github_release", lambda repo, tag: rest)
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ assert list(MOD.iter_release_payloads_by_time(UPSTREAM, "b9415", "latest")) == [rest]
+
+
+class TestPinnedTagHttpFailures:
+ """HTTPError subclasses URLError, so the HTTPError clause must route the fallback."""
+
+ def _http(self, code):
+ def call(*args, **kwargs):
+ raise urllib.error.HTTPError("https://api.github.com/x", code, "boom", None, None)
+
+ return call
+
+ @pytest.mark.parametrize("code", [500, 502, 503, 504])
+ def test_a_retryable_http_failure_reaches_the_release_page(self, monkeypatch, code):
+ monkeypatch.setattr(MOD, "github_release", self._http(code))
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b9415": _expanded_assets(
+ UPSTREAM, "b9415", {"llama-b9415-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "b9415"))
+ assert [release["tag_name"] for release in got] == ["b9415"]
+
+ def test_a_404_still_scans_rather_than_reading_the_page(self, monkeypatch):
+ # The tag does not exist, so its release page cannot answer either.
+ monkeypatch.setattr(MOD, "github_release", self._http(404))
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: [])
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ assert list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "b9415")) == []
+
+ def test_the_fork_still_re_raises_a_retryable_http_failure(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_release", self._http(503))
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ with pytest.raises(urllib.error.HTTPError):
+ list(MOD.iter_release_payloads_by_time(MOD.DEFAULT_PUBLISHED_REPO, "", "b9415"))
+
+
+class TestFreshnessAgreesWithSelection:
+ """The update-currency check and the planner must answer from the same rule.
+
+ They disagreed live before this was threaded: the check reported v0.4.1 newest
+ while the planner installed b11071, so every update run would have reinstalled.
+ """
+
+ RELEASES = [
+ {
+ "tag_name": "v0.4.1",
+ "prerelease": False,
+ "draft": False,
+ "published_at": "2026-09-14T00:00:00Z",
+ },
+ {
+ "tag_name": "b11071",
+ "prerelease": True,
+ "draft": False,
+ "published_at": "2026-09-21T00:00:00Z",
+ },
+ {
+ "tag_name": "b11070",
+ "prerelease": True,
+ "draft": False,
+ "published_at": "2026-09-20T00:00:00Z",
+ },
+ ]
+
+ def test_upstream_freshness_names_the_build_the_planner_installs(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: self.RELEASES)
+ assert MOD._api_newest_release_tag(UPSTREAM) == "b11071"
+
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ planned = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert planned[0]["tag_name"] == "b11071"
+
+ def test_the_fork_still_drops_prereleases_in_the_freshness_check(self, monkeypatch):
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: self.RELEASES)
+ assert MOD._api_newest_release_tag(MOD.DEFAULT_PUBLISHED_REPO) == "v0.4.1"
+
+ def test_a_draft_is_never_newest(self, monkeypatch):
+ releases = self.RELEASES + [
+ {
+ "tag_name": "b11072",
+ "prerelease": True,
+ "draft": True,
+ "published_at": "2026-09-22T00:00:00Z",
+ }
+ ]
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: releases)
+ assert MOD._api_newest_release_tag(UPSTREAM) == "b11071"
+
+
+class TestLatestTagNamesABuild:
+ """The source build must compile the version the prebuilt path would install.
+
+ /releases/latest resolves by make_latest, and upstream points it at v0.4.1, a
+ pointer release that packages no prebuilt.
+ """
+
+ def test_a_non_build_rest_tag_consults_the_feed(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "v0.4.1"})
+ _install_web(monkeypatch, {"releases.atom": _atom(UPSTREAM, ["v0.4.1", "b11071"])})
+ assert MOD.latest_upstream_release_tag() == "b11071"
+
+ def test_a_build_rest_tag_is_taken_without_consulting_the_feed(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "b11071"})
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ assert MOD.latest_upstream_release_tag() == "b11071"
+
+ def test_the_rest_tag_is_kept_when_the_feed_cannot_answer(self, monkeypatch):
+ # Better a released version than no source ref at all.
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "v0.4.1"})
+ _install_web(monkeypatch, {})
+ assert MOD.latest_upstream_release_tag() == "v0.4.1"
+
+ def test_the_rest_tag_is_kept_when_the_feed_lists_no_build(self, monkeypatch):
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "v0.4.1"})
+ _install_web(monkeypatch, {"releases.atom": _atom(UPSTREAM, ["v0.4.1", "v0.4.0"])})
+ assert MOD.latest_upstream_release_tag() == "v0.4.1"
+
+
+class TestUpstreamPointerReleasesAreNeverSelectable:
+ """Upstream ships binaries only under bNNNN; a versioned pointer release has none.
+
+ Accepting one lets the freshness check name it newest while the planner walks past
+ it for want of an asset, which reinstalls the same build on every update run.
+ """
+
+ def test_a_newer_pointer_release_is_not_newest(self, monkeypatch):
+ releases = [
+ {
+ "tag_name": "v0.4.2",
+ "prerelease": False,
+ "draft": False,
+ "published_at": "2026-09-30T00:00:00Z",
+ },
+ {
+ "tag_name": "b11071",
+ "prerelease": True,
+ "draft": False,
+ "published_at": "2026-09-21T00:00:00Z",
+ },
+ ]
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: releases)
+ assert MOD._api_newest_release_tag(UPSTREAM) == "b11071"
+
+ def test_the_planner_never_considers_a_pointer_release(self, monkeypatch):
+ releases = [
+ {
+ "tag_name": "v0.4.2",
+ "prerelease": False,
+ "draft": False,
+ "published_at": "2026-09-30T00:00:00Z",
+ "assets": [],
+ },
+ {
+ "tag_name": "b11071",
+ "prerelease": True,
+ "draft": False,
+ "published_at": "2026-09-21T00:00:00Z",
+ "assets": [],
+ },
+ ]
+ monkeypatch.setattr(MOD, "github_releases", lambda repo, **kw: releases)
+ monkeypatch.setattr(MOD, "web_release_payload", _boom)
+ monkeypatch.setattr(MOD, "web_release_tags", _boom)
+ got = [r["tag_name"] for r in MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest")]
+ assert got == ["b11071"]
+
+ def test_another_repo_keeps_the_plain_prerelease_rule(self):
+ fork = MOD.DEFAULT_PUBLISHED_REPO
+ assert MOD.release_is_selectable(fork, {"tag_name": "v1.2.3", "prerelease": False})
+ assert not MOD.release_is_selectable(fork, {"tag_name": "v1.2.3", "prerelease": True})
+
+
+class TestTransportFailuresReachTheWebPath:
+ """A stalled or reset read is a transport failure like a 403, not a reason to stop."""
+
+ @pytest.mark.parametrize(
+ "exc",
+ [TimeoutError("read timed out"), ConnectionResetError("reset by peer")],
+ )
+ def test_the_listing_recovers(self, monkeypatch, exc):
+ def raise_it(*args, **kwargs):
+ raise exc
+
+ monkeypatch.setattr(MOD, "github_releases", raise_it)
+ _install_web(
+ monkeypatch,
+ {
+ "releases.atom": _atom(UPSTREAM, ["b11071"]),
+ "expanded_assets/b11071": _expanded_assets(
+ UPSTREAM, "b11071", {"llama-b11071-bin-macos-arm64.tar.gz": DIGEST_A}
+ ),
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "latest"))
+ assert [r["tag_name"] for r in got] == ["b11071"]
+
+ def test_a_pinned_tag_recovers_from_a_timeout(self, monkeypatch):
+ def raise_it(*args, **kwargs):
+ raise TimeoutError("read timed out")
+
+ monkeypatch.setattr(MOD, "github_release", raise_it)
+ _install_web(
+ monkeypatch,
+ {
+ "expanded_assets/b9415": _expanded_assets(
+ UPSTREAM, "b9415", {"llama-b9415-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ },
+ )
+ got = list(MOD.iter_release_payloads_by_time(UPSTREAM, "", "b9415"))
+ assert [r["tag_name"] for r in got] == ["b9415"]
+
+
+class TestTheOptOutIsHonouredEverywhere:
+ def test_latest_tag_does_not_consult_the_feed_when_opted_out(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_LLAMA_DISABLE_DOWNLOAD_HOST_RESOLVE", "1")
+ monkeypatch.setattr(MOD, "fetch_json", lambda url: {"tag_name": "v0.4.1"})
+ monkeypatch.setattr(MOD, "upstream_web_release_tags", _boom)
+ # The REST answer stands rather than nothing at all.
+ assert MOD.latest_upstream_release_tag() == "v0.4.1"
+
+ def test_latest_tag_raises_when_opted_out_and_rest_is_down(self, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_LLAMA_DISABLE_DOWNLOAD_HOST_RESOLVE", "1")
+ monkeypatch.setattr(MOD, "fetch_json", _rest_403)
+ monkeypatch.setattr(MOD, "upstream_web_release_tags", _boom)
+ with pytest.raises(RuntimeError, match = "403"):
+ MOD.latest_upstream_release_tag()
+
+
+class TestABadgeFailureKeepsTheRelease:
+ def test_assets_survive_an_unreadable_release_page(self, monkeypatch):
+ pages = {
+ "expanded_assets/b11071": _expanded_assets(
+ UPSTREAM, "b11071", {"llama-b11071-bin-macos-arm64.tar.gz": DIGEST_A}
+ )
+ }
+ # No releases/tag/b11071 page: the badge request 404s.
+ web = _Web(pages)
+ monkeypatch.setattr(CORE, "download_bytes", lambda ops, url, **kw: web(url, **kw))
+ release = MOD.web_release_payload(UPSTREAM, "b11071")
+ assert release["prerelease"] is True
+ assert MOD.release_asset_digests(release) == {
+ "llama-b11071-bin-macos-arm64.tar.gz": DIGEST_A
+ }
+
+ def test_a_non_build_tag_still_fails_closed(self, monkeypatch):
+ pages = {
+ "expanded_assets/v0.4.1": _expanded_assets(
+ UPSTREAM, "v0.4.1", {"nightly-tag.txt": DIGEST_B}
+ )
+ }
+ web = _Web(pages)
+ monkeypatch.setattr(CORE, "download_bytes", lambda ops, url, **kw: web(url, **kw))
+ with pytest.raises(urllib.error.HTTPError):
+ MOD.web_release_payload(UPSTREAM, "v0.4.1")