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
Studio: keep working when GitHub rate limits or is down (#10670)
Nilayb84349a1f8e1
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex e7833636a52..7b6bd33970d 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -1370,9 +1370,10 @@ def _attempt_package_install(env = env,)+ wheel_available = url_exists(wheel_url) if wheel_url else Falseif wheel_url is None:logger.info("No compatible %s wheel candidate", display_name)- elif url_exists(wheel_url):+ elif wheel_available:_send_status(event_queue, f"Installing {display_name} for faster training...")for installer, result in install_wheel(wheel_url,@@ -1398,6 +1399,11 @@ def _attempt_package_install(display_name,result.stdout,)+ elif wheel_available is None:+ _send_status(+ event_queue,+ f"Could not check the {display_name} prebuilt wheel; installing from PyPI.",+ )else:logger.info("No published %s wheel found: %s", display_name, wheel_url)diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex e98c3b640fb..2b4d88d4896 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -1329,3 +1329,12 @@ def pin_installer_torch_vendor(monkeypatch):# __dict__: hasattr would trip a lazy __getattr__. _torchao_stub has its own probe.if "_rocm_torch_preferred" in (getattr(module, "__dict__", None) or {}):monkeypatch.setattr(module, "_installed_torch_is_rocm", lambda: None)++[email protected](autouse = True)+def _clear_github_rate_limit_lockout():+ from utils.prebuilt import freshness_flow++ freshness_flow._api_rate_limited_until = 0.0+ yield+ freshness_flow._api_rate_limited_until = 0.0diff --git a/studio/backend/tests/test_llama_cpp_changelog.py b/studio/backend/tests/test_llama_cpp_changelog.pyindex d3ffb31b30c..06d5ab9f8af 100644--- a/studio/backend/tests/test_llama_cpp_changelog.py+++ b/studio/backend/tests/test_llama_cpp_changelog.py@@ -381,3 +381,26 @@ def test_an_oversized_release_body_is_rejected(monkeypatch):monkeypatch.setattr(changes, "auth_safe_open", lambda *_a, **_k: _Response())assert changes._fetch_release_blocking("unslothai/llama.cpp", "b1", 5.0) is None+++def test_a_rate_limit_holds_the_changelog_even_for_a_forced_refresh(monkeypatch):+ import email.message+ import urllib.error++ from utils.prebuilt import freshness_flow++ for name in ("_release_memo", "_release_failed_at", "_release_forced_at"):+ monkeypatch.setattr(changes, name, {})+ headers = email.message.Message()+ headers["Retry-After"] = "90"+ calls = []++ def refused(*_args, **_kwargs):+ calls.append(1)+ raise urllib.error.HTTPError("url", 403, "rate limited", headers, None)++ monkeypatch.setattr(changes, "auth_safe_open", refused)+ assert changes._fetch_release_blocking("unslothai/llama.cpp", "b1", 5.0) is None+ assert 85 < freshness_flow.github_rate_limit_remaining() <= 90+ assert changes._release_for_tag("unslothai/llama.cpp", "b2", force_refresh = True) is None+ assert calls == [1]diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.pyindex 776a2786ede..19bce00ae68 100644--- a/studio/backend/tests/test_llama_cpp_freshness.py+++ b/studio/backend/tests/test_llama_cpp_freshness.py@@ -763,3 +763,68 @@ def test_release_fetch_cannot_outlive_its_deadline(monkeypatch, fetch):assert getattr(fr, fetch)("unslothai/llama.cpp", timeout = 0.25) is None# Pins the implemented timeout + 1, not merely "faster than the 30s stall".assert time.monotonic() - started < 2.0+++def _refusal(+ code: int,+ headers: dict | None = None,+ body: bytes = b"",+):+ import email.message+ import io+ import urllib.error++ message = email.message.Message()+ for name, value in (headers or {}).items():+ message[name] = value+ return urllib.error.HTTPError(+ "https://api.github.com/repos/x/y/releases", code, "refused", message, io.BytesIO(body)+ )+++ ("code", "headers", "body", "low", "high"),+ [+ (+ 403,+ {"X-RateLimit-Remaining": "4998"},+ b'{"message": "Resource not accessible"}',+ None,+ None,+ ),+ (404, {"X-RateLimit-Remaining": "0"}, b"", None, None),+ (403, {"Retry-After": "60"}, b"", 60, 60),+ (403, {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "+42"}, b"", 35, 42),+ (403, {}, b'{"message": "You have exceeded a secondary rate limit"}', 900, 900),+ (429, {"X-RateLimit-Remaining": "4998"}, b"", 900, 900),+ (403, {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "+21600"}, b"", 3600, 3600),+ ],+)+def test_rate_limit_wait(code, headers, body, low, high):+ headers = {+ k: str(int(time.time()) + int(v[1:])) if v.startswith("+") else v+ for k, v in headers.items()+ }+ wait = fr._flow.rate_limit_wait(_refusal(code, headers, body))+ assert wait is None if low is None else low <= wait <= high+++def test_a_rate_limit_parks_every_github_fetch_until_it_resets(monkeypatch):+ mono = [1000.0]+ monkeypatch.setattr(fr._flow.time, "monotonic", lambda: mono[0])+ calls = []++ def refuse(req, timeout = 5.0):+ calls.append(req.full_url)+ raise _refusal(403, {"Retry-After": "1800"})++ monkeypatch.setattr(fr._flow, "auth_safe_open", refuse)+ assert fr._fetch_latest_release_tag("unslothai/llama.cpp") is None+ assert fr._fetch_latest_release_tag("unslothai/llama.cpp") is None+ assert fr._fetch_latest_release_assets("unslothai/llama.cpp") is None+ assert len(calls) == 1+ fr._flow.hold_github_api(60)+ assert fr._flow.github_rate_limit_remaining() == 1800+ mono[0] += 1801+ assert fr._fetch_latest_release_tag("unslothai/llama.cpp") is None+ assert len(calls) == 2diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.pyindex 43201d72495..8ec69bda239 100644--- a/studio/backend/tests/test_sd_cpp_install.py+++ b/studio/backend/tests/test_sd_cpp_install.py@@ -3294,3 +3294,48 @@ def test_safe_extractall_rejects_symlink_escaping_target(tmp_path):with pytest.raises(RuntimeError, match = "unsafe symlink"):_safe_extractall(zf, target)assert not (tmp_path / "escape.txt").exists()+++ ("status", "remaining", "body", "throttled"),+ [+ (403, "0", b"", True),+ (429, "4998", b"", True),+ (403, "4998", b'{"message": "secondary rate limit"}', True),+ (403, "4998", b'{"message": "Resource not accessible"}', False),+ ],+)+def test_a_rate_limit_stops_the_fallback_ladder(+ monkeypatch, capsys, status, remaining, body, throttled+):+ import email.message++ seen = []+ headers = email.message.Message()+ headers["X-RateLimit-Remaining"] = remaining++ def fake_fetch(+ tag,+ *,+ repo,+ token,+ timeout = 30.0,+ allow_latest = True,+ ):+ seen.append(repo)+ raise urllib.error.HTTPError(+ f"https://api/{repo}", status, "refused", headers, io.BytesIO(body)+ )++ monkeypatch.delenv("GH_TOKEN", raising = False)+ monkeypatch.delenv("GITHUB_TOKEN", raising = False)+ monkeypatch.setattr(sdmod, "_fetch_release", fake_fetch)+ if not throttled:+ assert sdmod._resolve_with_fallback("auto", None)[2] is None+ assert len(seen) > 1+ return+ with pytest.raises(sdmod.GitHubRateLimited, match = "rate limiting.*GH_TOKEN"):+ sdmod._resolve_with_fallback("auto", None)+ assert len(seen) == 1+ assert sdmod.main(["--print-asset"]) == 2+ assert "rate limiting" in capsys.readouterr().errdiff --git a/studio/backend/tests/test_wheel_utils_url_exists.py b/studio/backend/tests/test_wheel_utils_url_exists.pynew file mode 100644index 00000000000..989cd22f708--- /dev/null+++ b/studio/backend/tests/test_wheel_utils_url_exists.py@@ -0,0 +1,37 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import urllib.error++import pytest++from utils import wheel_utils+++class _Ok:+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False+++ ("outcome", "expected"),+ [+ (None, True),+ (urllib.error.HTTPError("u", 404, "missing", None, None), False),+ (urllib.error.HTTPError("u", 403, "rate limited", None, None), None),+ (urllib.error.HTTPError("u", 503, "down", None, None), None),+ (urllib.error.URLError("offline"), None),+ (TimeoutError("stalled"), None),+ ],+)+def test_only_a_404_means_unpublished(monkeypatch, outcome, expected):+ def urlopen(request, timeout = None):+ if outcome is None:+ return _Ok()+ raise outcome++ monkeypatch.setattr(wheel_utils.urllib.request, "urlopen", urlopen)+ assert wheel_utils.url_exists("https://github.com/o/r/releases/download/t/w.whl") is expecteddiff --git a/studio/backend/utils/llama_cpp_changelog.py b/studio/backend/utils/llama_cpp_changelog.pyindex c8ab96844cd..a78a8f108ce 100644--- a/studio/backend/utils/llama_cpp_changelog.py+++ b/studio/backend/utils/llama_cpp_changelog.py@@ -21,6 +21,9 @@ from utils.auth_safe import auth_safe_openfrom utils.prebuilt.freshness_flow import (RELEASE_CACHE_TTL_SECONDS,RELEASE_FAILURE_CACHE_TTL_SECONDS,+ github_rate_limit_remaining,+ hold_github_api,+ rate_limit_wait,)logger = structlog.get_logger(__name__)@@ -80,6 +83,8 @@ def _fetch_release(def _fetch_release_blocking(repo: str, tag: str, timeout: float) -> Optional[dict]:+ if github_rate_limit_remaining() > 0:+ return Noneencoded_tag = urllib.parse.quote(tag, safe = "")headers = {"Accept": "application/vnd.github+json",@@ -100,9 +105,15 @@ def _fetch_release_blocking(repo: str, tag: str, timeout: float) -> Optional[diclogger.debug("llama changelog release too large", repo = repo, tag = tag)return Nonepayload = json.loads(raw.decode("utf-8"))+ except urllib.error.HTTPError as exc:+ wait = rate_limit_wait(exc)+ hold_github_api(wait)+ logger.debug(+ "llama changelog fetch failed", repo = repo, tag = tag, error = str(exc), backoff_seconds = wait+ )+ return Noneexcept (urllib.error.URLError,- urllib.error.HTTPError,OSError,# A truncated read raises HTTPException, which is not an OSError.http.client.HTTPException,@@ -124,6 +135,9 @@ def _release_for_tag(key = (repo, tag)# Memory-only, so monotonic throughout: a backward clock step must not be able to extend the TTL. freshness_flow uses wall time because it persists to disk.now = time.monotonic()+ # Retrying into a rate limit only delays the reset; checked before the debounce so the slot is not burnt.+ if github_rate_limit_remaining() > 0:+ force_refresh = Falseif force_refresh:forced_at = _release_forced_at.get(key)if forced_at is not None and now - forced_at < FORCE_REFRESH_MIN_INTERVAL_SECONDS:diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.pyindex 5cbe6d12cd9..d8b193e2315 100644--- a/studio/backend/utils/prebuilt/freshness_flow.py+++ b/studio/backend/utils/prebuilt/freshness_flow.py@@ -5,7 +5,9 @@from __future__ import annotations+import http.clientimport json+import threadingimport timefrom datetime import datetime, timezonefrom pathlib import Path@@ -22,6 +24,54 @@ logger = structlog.get_logger(__name__)RELEASE_CACHE_TTL_SECONDS = 24 * 60 * 60# Briefly memoize failed lookups so recurring status reads do not retry an unreachable GitHub endpoint on every request.RELEASE_FAILURE_CACHE_TTL_SECONDS = 60+GITHUB_RATE_LIMITED_DEFAULT_SECONDS = 15 * 60+# A skewed or proxied reset header is held to one primary window.+GITHUB_RATE_LIMIT_MAX_SECONDS = 60 * 60+# Secondary limits can 403 with no rate headers; only the body names them.+_RATE_LIMIT_BODY_MARKERS = ("rate limit", "abuse detection")++# One lockout for the whole process: the quota is per token or per IP, not per repo.+_api_rate_limited_lock = threading.Lock()+_api_rate_limited_until: float = 0.0+++def rate_limit_wait(exc: BaseException) -> Optional[float]:+ """Seconds a GitHub refusal asks us to wait, capped at one window; None when throttling does not explain it (an SSO or permission 403)."""+ code = getattr(exc, "code", None)+ if code not in (403, 429):+ return None+ headers = getattr(exc, "headers", None) or {}+ retry_after = str(headers.get("Retry-After") or "").strip()+ spent = str(headers.get("X-RateLimit-Remaining") or "").strip() == "0"+ if code != 429 and not retry_after and not spent:+ try:+ body = exc.read(2048).decode("utf-8", errors = "replace").lower() # type: ignore[attr-defined]+ except Exception: # noqa: BLE001 - an unreadable body names nothing+ body = ""+ if not any(marker in body for marker in _RATE_LIMIT_BODY_MARKERS):+ return None+ wait = float(GITHUB_RATE_LIMITED_DEFAULT_SECONDS)+ try:+ if retry_after:+ wait = float(retry_after)+ elif spent:+ wait = float(headers.get("X-RateLimit-Reset")) - time.time()+ except (TypeError, ValueError):+ pass+ return min(max(wait, 0.0), GITHUB_RATE_LIMIT_MAX_SECONDS)+++def hold_github_api(wait: Optional[float]) -> None:+ """Park every api.github.com caller for ``wait`` seconds; never shortens a lockout already in place."""+ global _api_rate_limited_until+ if wait is None:+ return+ with _api_rate_limited_lock:+ _api_rate_limited_until = max(_api_rate_limited_until, time.monotonic() + wait)+++def github_rate_limit_remaining() -> float:+ return max(_api_rate_limited_until - time.monotonic(), 0.0)def read_install_marker(@@ -116,11 +166,13 @@ def _fetch_newest_published_release(def _fetch_newest_published_release_blocking(repo: str, timeout: float, *, log_message: str) -> Optional[dict]:- """Newest published (non-draft, non-prerelease) release object for `repo`, by ``published_at``. Resolves "latest" the way the installers do, NOT via GitHub's ``/releases/latest`` pointer, which sorts by commit date and can lag the build the installer installs, making detection and apply disagree (the downgrade / sticky-banner bug). None on any failure (offline, rate-limited)."""+ """Newest published (non-draft, non-prerelease) release object for `repo`, by ``published_at``. Resolves "latest" the way the installers do, NOT via GitHub's ``/releases/latest`` pointer, which sorts by commit date and can lag the build the installer installs, making detection and apply disagree (the downgrade / sticky-banner bug). None on any failure (offline, rate-limited) and while the shared lockout holds."""import osimport urllib.errorimport urllib.request+ if github_rate_limit_remaining() > 0:+ return Noneurl = f"https://api.github.com/repos/{repo}/releases?per_page=30"headers = {"Accept": "application/vnd.github+json",@@ -133,10 +185,15 @@ def _fetch_newest_published_release_blocking(try:with auth_safe_open(req, timeout = timeout) as resp:data = json.loads(resp.read().decode("utf-8"))+ except urllib.error.HTTPError as exc:+ wait = rate_limit_wait(exc)+ hold_github_api(wait)+ logger.debug(log_message, repo = repo, error = str(exc), backoff_seconds = wait)+ return Noneexcept (urllib.error.URLError,- urllib.error.HTTPError,OSError,+ http.client.HTTPException,json.JSONDecodeError,) as exc:logger.debug(log_message, repo = repo, error = str(exc))diff --git a/studio/backend/utils/release_notes.py b/studio/backend/utils/release_notes.pyindex 6b88905433f..6ea8acfb913 100644--- a/studio/backend/utils/release_notes.py+++ b/studio/backend/utils/release_notes.py@@ -11,7 +11,14 @@ import reimport threadingimport timeimport urllib.error+import urllib.parseimport urllib.request++from utils.prebuilt.freshness_flow import (+ github_rate_limit_remaining,+ hold_github_api,+ rate_limit_wait,+)from dataclasses import dataclassfrom typing import Any@@ -587,6 +594,18 @@ def _fetch_latest_release() -> tuple[ReleaseSource, float]:RELEASES_FAILURE_TTL_SECONDS,)+ if urllib.parse.urlparse(url).hostname == "api.github.com":+ locked_out_for = github_rate_limit_remaining()+ if locked_out_for > 0:+ return (+ ReleaseSource(+ release = None,+ source = None,+ error = "GitHub is rate limiting release note requests.",+ ),+ locked_out_for,+ )+headers = {"User-Agent": "unsloth-studio-update-check","Accept": "application/vnd.github+json",@@ -598,6 +617,11 @@ def _fetch_latest_release() -> tuple[ReleaseSource, float]:headers["If-None-Match"] = _remote_etagrequest = urllib.request.Request(url, headers = headers)+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")+ parsed = urllib.parse.urlparse(url)+ # https only (the override accepts http://); unredirected, so a redirect off the API host drops it.+ if token and parsed.scheme == "https" and parsed.hostname == "api.github.com":+ request.add_unredirected_header("Authorization", f"Bearer {token}")deadline = time.monotonic() + RELEASES_TIMEOUT_SECONDStry:with urllib.request.urlopen(request, timeout = RELEASES_TIMEOUT_SECONDS) as response:@@ -634,7 +658,7 @@ def _fetch_latest_release() -> tuple[ReleaseSource, float]:)payload = json.loads(body.decode("utf-8", errors = "replace"))except urllib.error.HTTPError as error:- return _http_error_source(error)+ return _http_error_source(error, url = url)except TimeoutError:return (ReleaseSource(@@ -671,39 +695,27 @@ def _fetch_latest_release() -> tuple[ReleaseSource, float]:return source, RELEASES_SUCCESS_TTL_SECONDS-def _http_error_source(error: urllib.error.HTTPError) -> tuple[ReleaseSource, float]:- """The answer and TTL for an HTTP status GitHub refused the request with."""+def _http_error_source(+ error: urllib.error.HTTPError, *, url: str = RELEASES_API_URL+) -> tuple[ReleaseSource, float]:global _rate_limited_untilif error.code == 304 and _remote_last_good is not None:# Nothing changed, so the release already held still stands.return _remote_last_good, RELEASES_SUCCESS_TTL_SECONDS- if error.code in (403, 429):- now = time.time()- # GitHub's order: Retry-After, which is how a secondary limit states its wait, then the primary limit's reset, then a plain back-off. Every one records a deadline, or Retry requests straight back into the limit.- after = _epoch_header(error.headers.get("Retry-After"))- reset = (- _epoch_header(error.headers.get("X-RateLimit-Reset"))- if error.headers.get("X-RateLimit-Remaining") == "0"- else None- )- if after is not None:- deadline = now + after- elif reset is not None:- deadline = reset- else:- deadline = now + RELEASES_RATE_LIMITED_TTL_SECONDS- # The deadline itself is bounded, not just the first wait on it: the next fetch answers from it, so capping only the TTL left a skewed header parking the popup for as long as it liked.- _rate_limited_until = min(deadline, now + RELEASES_RATE_LIMIT_MAX_SECONDS)- ttl = max(_rate_limited_until - now, 0.0)+ wait = rate_limit_wait(error)+ if wait is not None:+ _rate_limited_until = time.time() + wait+ if urllib.parse.urlparse(url).hostname == "api.github.com":+ hold_github_api(wait)return (ReleaseSource(release = None,source = None,error = "GitHub is rate limiting release note requests.",),- ttl,+ wait,)return (@@ -712,13 +724,6 @@ def _http_error_source(error: urllib.error.HTTPError) -> tuple[ReleaseSource, fl)-def _epoch_header(value: str | None) -> float | None:- try:- return float((value or "").strip())- except ValueError:- return None--def select_release(payload: Any) -> Release | None:"""The newest published release in a GitHub releases response. Ordered by publication, never by tag: `v0.1.60-beta` was published after `v0.1.527-beta`, so sorting the tags numerically picks the wrong one."""if not isinstance(payload, list):diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.pyindex 163145116f4..0a94e6aba80 100644--- a/studio/backend/utils/ssm_runtime.py+++ b/studio/backend/utils/ssm_runtime.py@@ -290,7 +290,8 @@ def _install_kernel(release_base_url = release_base_url,env = env,)- if wheel_url and url_exists(wheel_url):+ wheel_available = url_exists(wheel_url) if wheel_url else False+ if wheel_available:_emit(status_cb, f"Installing {display_name} (prebuilt kernel) for this model...")# Keep quiet downloads and unpacks within the inactivity deadline (#9398).with _heartbeat(@@ -320,6 +321,11 @@ def _install_kernel(display_name,getattr(result, "stdout", ""),)+ elif wheel_available is None:+ _emit(+ status_cb,+ f"Could not check the {display_name} prebuilt wheel; building it from source.",+ )else:logger.info("No prebuilt %s wheel for this environment (%s); building from source",diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.pyindex 60ac6b679e9..b9deada7e8b 100644--- a/studio/backend/utils/wheel_utils.py+++ b/studio/backend/utils/wheel_utils.py@@ -3,6 +3,7 @@from __future__ import annotations+import http.clientimport jsonimport loggingimport os@@ -420,13 +421,17 @@ def install_wheel(return attempts-def url_exists(url: str) -> bool:+def url_exists(url: str) -> bool | None:+ """True if reachable, False on a 404, None when it cannot be checked: a refusal is no proof the wheel is unpublished."""try:request = urllib.request.Request(url, method = "HEAD")with urllib.request.urlopen(request, timeout = 10):return Trueexcept urllib.error.HTTPError as exc:- _logger.debug("url_exists(%s): HTTP %s", url, exc.code)- except (urllib.error.URLError, TimeoutError) as exc:- _logger.debug("url_exists(%s): %s", url, exc)- return False+ if exc.code == 404:+ return False+ reason = f"HTTP {exc.code}"+ except (OSError, http.client.HTTPException) as exc:+ reason = str(exc)+ _logger.warning("url_exists(%s): %s; could not check prebuilt wheel availability", url, reason)+ return Nonediff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 782f2e359bd..a049e2db331 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -4444,10 +4444,8 @@ def ensure_diffusion_visual_server(returntry:- assets = github_release_assets(DEFAULT_PUBLISHED_REPO, release_tag)match = None- unapproved_matches: list[str] = []- for asset_name, url in assets.items():+ for asset_name, approved in approved_checksums.artifacts.items():low = asset_name.lower()if "llama-diffusion-gemma-visual-server" not in low:continue@@ -4455,28 +4453,18 @@ def ensure_diffusion_visual_server(continueif (not host.is_windows) and low.endswith(".exe"):continue- # This binary is chmod'd executable and later launched by the- # backend, so it must be covered by the approved checksum manifest- # just like every other prebuilt artifact. An asset that matches the- # name but is missing from the manifest is refused rather than run.- approved = approved_checksums.artifacts.get(asset_name)- if approved is None:- unapproved_matches.append(asset_name)+ if approved.repo and approved.repo != DEFAULT_PUBLISHED_REPO:+ continue+ url = release_asset_download_url(DEFAULT_PUBLISHED_REPO, release_tag, asset_name)+ if not url:continuematch = (asset_name, url, approved.sha256)breakif match is None:- if unapproved_matches:- log(- "diffusion visual server asset(s) were present but omitted from the "- "approved checksum manifest; refusing unverified native executable: "- + ", ".join(unapproved_matches)- )- else:- log(- "diffusion visual server not found in the published release; native "- "DiffusionGemma serving needs DG_VISUAL_BIN or a source build"- )+ log(+ "diffusion visual server not in the approved checksum manifest for this "+ "release; native DiffusionGemma serving needs DG_VISUAL_BIN or a source build"+ )returnbin_dir.mkdir(parents = True, exist_ok = True)download_file_verified(diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 58b4c7f3f9f..2bbfe4c642a 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -7822,7 +7822,8 @@ def _ensure_flash_attn() -> None:env = probe_torch_wheel_env()wheel_url = _build_flash_attn_wheel_url(env) if env else None- if wheel_url and url_exists(wheel_url):+ wheel_available = url_exists(wheel_url) if wheel_url else False+ if wheel_available:# Counted: it lands a distribution, so the caches keyed on the counter must be rebuilt._count_install_action()for installer, wheel_result in install_wheel(@@ -7863,6 +7864,12 @@ def _ensure_flash_attn() -> None:if wheel_url is None:_step("warning", "No compatible flash-attn prebuilt wheel found", _cyan)+ elif wheel_available is None:+ _step(+ "warning",+ "Could not check the flash-attn prebuilt wheel; skipped it",+ _cyan,+ )else:_step("warning", "No published flash-attn prebuilt wheel found", _cyan)diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex ff9c8c13b99..0a2a99369be 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -272,6 +272,39 @@ def _fetch_latest_release(*, token: Optional[str] = None, timeout: float = 30.0)return _fetch_release(None, token = token, timeout = timeout)+class GitHubRateLimited(RuntimeError):+ pass+++def _is_rate_limited(exc: BaseException) -> bool:+ """Same rule as freshness_flow.rate_limit_wait, which this stdlib-only installer cannot import."""+ code = getattr(exc, "code", None)+ if code == 429:+ return True+ if code != 403:+ return False+ headers = getattr(exc, "headers", None) or {}+ if (+ str(headers.get("Retry-After") or "").strip()+ or str(headers.get("X-RateLimit-Remaining") or "").strip() == "0"+ ):+ return True+ try:+ body = exc.read(2048).decode("utf-8", errors = "replace").lower() # type: ignore[attr-defined]+ except Exception: # noqa: BLE001 - an unreadable body names nothing+ return False+ return "rate limit" in body or "abuse detection" in body+++def _rate_limit_message() -> str:+ hint = (+ ""+ if (os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN"))+ else "; set GH_TOKEN or GITHUB_TOKEN to lift the 60 requests/hour unauthenticated limit"+ )+ return f"GitHub API is rate limiting release lookups{hint}"++def _verify_sha256(path: Path, expected_digest: Optional[str]) -> None:"""Verify ``path`` against a GitHub asset ``digest`` ('sha256:<hex>'), an integrity check against a corrupted or tampered download before we extract and execute the binary. When the release publishes no digest (older releases), warn and proceed rather than hard-fail."""if not expected_digest:@@ -627,10 +660,12 @@ def _resolve_repo_asset(*,allow_latest: bool = True,) -> tuple[Optional[dict], Optional[str]]:- """Fetch ``repo``'s release and pick the asset for this host. Returns ``(release, asset_name)`` or ``(None, None)`` when the repo has no usable release (fetch failed, or the pinned tag is missing and ``allow_latest`` is False) or no asset for this host, so the caller can fall back."""+ """Fetch ``repo``'s release and pick the asset for this host. Returns ``(release, asset_name)`` or ``(None, None)`` when the repo has no usable release (fetch failed, or the pinned tag is missing and ``allow_latest`` is False) or no asset for this host, so the caller can fall back. A quota refusal raises ``GitHubRateLimited`` instead: every rung shares that quota."""try:release = _fetch_release(tag, repo = repo, token = token, allow_latest = allow_latest)- except Exception as exc: # noqa: BLE001 - network / rate limit -> fall back+ except Exception as exc: # noqa: BLE001 - network -> fall back+ if _is_rate_limited(exc):+ raise GitHubRateLimited(_rate_limit_message()) from excprint(f"sd-cli: {repo} release fetch failed ({exc})", flush = True)return None, Noneif release is None:@@ -833,7 +868,11 @@ def main(argv: Optional[list[str]] = None) -> int:if args.print_asset:# Same primary/fallback resolution as install(), so a host the mirror skips reports the upstream asset, not a false miss.- _used, _release, chosen = _resolve_with_fallback(args.accelerator, None)+ try:+ _used, _release, chosen = _resolve_with_fallback(args.accelerator, None)+ except GitHubRateLimited as exc:+ print(f"error: {exc}", file = sys.stderr)+ return 2print(chosen or "(no matching prebuilt; build from source)")return 0 if chosen else 2diff --git a/tests/python/test_flash_attn_install_python_stack.py b/tests/python/test_flash_attn_install_python_stack.pyindex 576e211149b..bb0d81a2ba5 100644--- a/tests/python/test_flash_attn_install_python_stack.py+++ b/tests/python/test_flash_attn_install_python_stack.py@@ -524,6 +524,38 @@ class TestEnsureFlashAttn:mock_install_wheel.assert_not_called()assert ("warning", "No published flash-attn prebuilt wheel found") in step_messages+ def test_an_unchecked_wheel_is_not_reported_as_unpublished(self):+ step_messages = []++ def fake_step(kind, message, *args, **kwargs):+ step_messages.append((kind, message))++ with (+ mock.patch.object(ips, "NO_TORCH", False),+ mock.patch.object(ips, "IS_WINDOWS", False),+ mock.patch.object(ips, "IS_MACOS", False),+ mock.patch.object(+ ips,+ "probe_torch_wheel_env",+ return_value = {+ "python_tag": "cp313",+ "torch_mm": "2.10",+ "cuda_major": "13",+ "cxx11abi": "TRUE",+ "platform_tag": "linux_x86_64",+ },+ ),+ mock.patch.object(ips, "url_exists", return_value = None),+ mock.patch.object(ips, "install_wheel") as mock_install_wheel,+ mock.patch.object(ips, "_step", side_effect = fake_step),+ mock.patch("subprocess.run", return_value = self._import_check()),+ ):+ ips._ensure_flash_attn()++ mock_install_wheel.assert_not_called()+ assert ("warning", "No published flash-attn prebuilt wheel found") not in step_messages+ assert any("could not" in message.lower() for _kind, message in step_messages)+def test_skip_env_disables_setup_install(self):with (mock.patch.object(ips, "NO_TORCH", False),diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 9abdb0ad814..35934eca860 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -4340,7 +4340,7 @@ def test_diffusion_visual_server_uses_approved_checksum_download(monkeypatch, tmmonkeypatch.setattr(INSTALL_LLAMA_PREBUILT,"github_release_assets",- lambda repo, tag: {asset_name: asset_url},+ lambda repo, tag: (_ for _ in ()).throw(AssertionError("listed the release over the API")),)def fake_download_file(url, destination):@@ -4375,15 +4375,16 @@ def test_diffusion_visual_server_uses_approved_checksum_download(monkeypatch, tmassert target.stat().st_mode & 0o777 == 0o755-def test_diffusion_visual_server_refuses_unapproved_release_asset(monkeypatch, tmp_path: Path):- asset_name = "llama-diffusion-gemma-visual-server-attacker-linux"+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: {asset_name: "https://example.test/" + asset_name},+ lambda repo, tag: (_ for _ in ()).throw(AssertionError("listed the release over the API")),)def fake_download_file(url, destination):diff --git a/tests/studio/test_update_release_notes.py b/tests/studio/test_update_release_notes.pyindex d151089f3cd..50764e10e28 100644--- a/tests/studio/test_update_release_notes.py+++ b/tests/studio/test_update_release_notes.py@@ -2936,3 +2936,112 @@ def test_a_paragraph_install_block_does_not_swallow_deeper_headings(notes_module)stripped = notes_module.strip_release_body(body)assert stripped == "Intro.\n\n###### Deeply nested announcement\n\n- a real change"++[email protected](autouse=True)+def github_lockout(notes_module):+ from utils.prebuilt import freshness_flow++ freshness_flow._api_rate_limited_until = 0.0+ notes_module.reset_release_notes_cache()+ yield freshness_flow+ freshness_flow._api_rate_limited_until = 0.0+ notes_module.reset_release_notes_cache()+++ ("url_override", "env", "expected"),+ [+ (None, {"GH_TOKEN": "ghp_gh", "GITHUB_TOKEN": "ghp_github"}, "Bearer ghp_github"),+ (None, {"GH_TOKEN": "ghp_gh"}, "Bearer ghp_gh"),+ ("https://mirror.example/releases", {"GH_TOKEN": "ghp_gh"}, None),+ ("http://api.github.com/repos/x/releases", {"GITHUB_TOKEN": "ghp_secret"}, None),+ ],+)+def test_where_the_release_notes_token_may_travel(+ notes_module, github_lockout, monkeypatch, url_override, env, expected+):+ import urllib.error++ seen = []++ def capture(request, timeout=None):+ seen.append(request)+ raise urllib.error.URLError("offline")++ monkeypatch.setattr(notes_module.urllib.request, "urlopen", capture)+ for name in ("GH_TOKEN", "GITHUB_TOKEN"):+ monkeypatch.delenv(name, raising=False)+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ if url_override is None:+ monkeypatch.delenv(notes_module.RELEASES_URL_ENV_VAR, raising=False)+ else:+ monkeypatch.setenv(notes_module.RELEASES_URL_ENV_VAR, url_override)+ notes_module._fetch_latest_release()+ assert seen[0].get_header("Authorization") == expected+ assert "Authorization" not in seen[0].headers+++ ("url_override", "status", "remaining", "body", "shared", "reported"),+ [+ (None, 403, "0", b"", True, True),+ (None, 429, "4998", b"", True, True),+ (None, 403, "4998", b'{"message": "secondary rate limit"}', True, True),+ (None, 403, "4998", b"", False, False),+ ("https://mirror.example/releases", 429, "0", b"", False, True),+ ],+)+def test_which_release_note_refusals_reach_the_shared_lockout(+ notes_module,+ github_lockout,+ monkeypatch,+ url_override,+ status,+ remaining,+ body,+ shared,+ reported,+):+ import email.message+ import io+ import urllib.error++ if url_override is None:+ monkeypatch.delenv(notes_module.RELEASES_URL_ENV_VAR, raising=False)+ else:+ monkeypatch.setenv(notes_module.RELEASES_URL_ENV_VAR, url_override)+ headers = email.message.Message()+ headers["X-RateLimit-Remaining"] = remaining+ headers["X-RateLimit-Reset"] = str(int(time.time() + 1800))++ def refuse(request, timeout=None):+ raise urllib.error.HTTPError(request.full_url, status, "refused", headers, io.BytesIO(body))++ monkeypatch.setattr(notes_module.urllib.request, "urlopen", refuse)+ result = notes_module.get_latest_release()+ assert (github_lockout.github_rate_limit_remaining() > 0) is shared+ assert ("rate limit" in (result.error or "").lower()) is reported++[email protected]("url_override", [None, "https://mirror.example/releases"])+def test_the_shared_lockout_parks_only_the_github_api(+ notes_module, github_lockout, monkeypatch, url_override+):+ import urllib.error++ if url_override is None:+ monkeypatch.delenv(notes_module.RELEASES_URL_ENV_VAR, raising=False)+ else:+ monkeypatch.setenv(notes_module.RELEASES_URL_ENV_VAR, url_override)+ github_lockout.hold_github_api(60)+ calls = []++ def capture(request, timeout=None):+ calls.append(request.full_url)+ raise urllib.error.URLError("offline")++ monkeypatch.setattr(notes_module.urllib.request, "urlopen", capture)+ notes_module.get_latest_release(refresh=True)+ assert calls == ([] if url_override is None else [url_override])