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: warn when a custom Hub endpoint redirects downloads to huggingface.co (#15329)
Daniel Han241bba98137a
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex faefeabe5e1..7f89cccf804 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -804,6 +804,12 @@ def _hub_reachable_without_probing(monkeypatch):)[email protected](autouse = True)+def _no_hub_mirror_probe(monkeypatch):+ """Saving a mirror endpoint would start a background probe; test_hub_mirror_probe.py turns it back on."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HUB_PROBE", "0")++@pytest.fixture(scope = "session")def studio_server(request):"""Yields (base_url, api_key): UNSLOTH_E2E_BASE_URL if set, else a managed server started lazily."""diff --git a/studio/backend/tests/test_hub_mirror_probe.py b/studio/backend/tests/test_hub_mirror_probe.pynew file mode 100644index 00000000000..05638dc7ca2--- /dev/null+++ b/studio/backend/tests/test_hub_mirror_probe.py@@ -0,0 +1,216 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A custom Hub endpoint that hands traffic back to huggingface.co is named in the server log."""++from __future__ import annotations++from pathlib import Path+import logging+import sys+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: logging.getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import httpx+import pytest++import utils.hub_mirror_probe as probe+import utils.hub_settings as hub_settings++MIRROR = "https://mirror.example.com"+API = f"/api/models/{probe.PROBE_REPO}"+FILE = f"/{probe.PROBE_REPO}/resolve/main/{probe.PROBE_FILE}"++[email protected](autouse = True)+def _probe_on(monkeypatch):+ monkeypatch.delenv(probe.PROBE_ENV, raising = False)+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setattr(probe, "_probed", set())+++def _serve(monkeypatch, routes):+ """Answer each path with ``routes[path]`` = (status, location); record every request."""+ seen = []++ def handler(request):+ seen.append(+ (+ request.method,+ request.url.host,+ request.url.path,+ request.headers.get("authorization"),+ )+ )+ status, location = routes.get(request.url.path, (404, None))+ return httpx.Response(status, headers = {"location": location} if location else {})++ monkeypatch.setattr(probe, "transport", httpx.MockTransport(handler))+ return seen+++def test_whole_site_redirect_is_found_without_contacting_huggingface(monkeypatch):+ # hf-mirror.com outside mainland China: every path is a 308 to huggingface.co.+ seen = _serve(+ monkeypatch,+ {+ API: (308, f"https://huggingface.co{API}"),+ FILE: (308, f"https://huggingface.co{FILE}"),+ },+ )+ findings = probe.find_official_redirects(MIRROR)+ assert [what for what, _ in findings] == ["Hub API calls", "model downloads"]+ assert {host for _, host, _, _ in seen} == {"mirror.example.com"}+ assert all(auth is None for *_, auth in seen)+ assert [method for method, *_ in seen] == ["GET", "HEAD"]+++def test_a_mirror_serving_files_from_its_own_cdn_is_quiet(monkeypatch):+ _serve(monkeypatch, {API: (200, None), FILE: (302, "https://cdn.mirror.example.com/blob")})+ assert probe.find_official_redirects(MIRROR) == []+++def test_relative_redirects_stay_on_the_mirror(monkeypatch):+ _serve(monkeypatch, {API: (200, None), FILE: (307, "/blobs/abc")})+ assert probe.find_official_redirects(MIRROR) == []+++def test_a_pass_through_mirror_sending_files_to_the_official_cdn_is_found(monkeypatch):+ _serve(monkeypatch, {API: (200, None), FILE: (302, "https://cas-bridge.xethub.hf.co/x")})+ findings = probe.find_official_redirects(MIRROR)+ assert findings == [("model downloads", "https://cas-bridge.xethub.hf.co/x")]+++def test_a_lookalike_host_is_not_official():+ assert probe.is_official_host("huggingface.co") and probe.is_official_host("cdn-lfs.hf.co")+ assert not probe.is_official_host("huggingface.co.evil.example")+ assert not probe.is_official_host("nothf.co")+++class _Log:+ def __init__(self):+ self.warnings = []++ def warning(self, message, *args):+ self.warnings.append(message % args)++ def debug(self, *_):+ pass+++def test_the_warning_names_the_endpoint_and_the_route(monkeypatch):+ log = _Log()+ monkeypatch.setattr(probe, "logger", log)+ _serve(+ monkeypatch,+ {API: (308, f"https://huggingface.co{API}"), FILE: (308, f"https://huggingface.co{FILE}")},+ )+ probe._probe(MIRROR)+ assert len(log.warnings) == 1+ assert MIRROR in log.warnings[0]+ assert "Hub API calls and model downloads to huggingface.co," in log.warnings[0]+++def test_an_unreachable_mirror_logs_no_warning(monkeypatch):+ def handler(request):+ raise httpx.ConnectError("refused", request = request)++ log = _Log()+ monkeypatch.setattr(probe, "logger", log)+ monkeypatch.setattr(probe, "transport", httpx.MockTransport(handler))+ probe._probe(MIRROR)+ assert log.warnings == []+++ "endpoint",+ [+ "",+ "https://huggingface.co",+ "https://hf.co",+ "http://127.0.0.1:9000",+ "http://localhost:1234",+ ],+)+def test_nothing_to_probe(endpoint):+ assert not probe.should_probe(endpoint)+++def test_offline_and_opt_out_skip_the_probe(monkeypatch):+ assert probe.should_probe(MIRROR)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ assert not probe.should_probe(MIRROR)+ monkeypatch.delenv("HF_HUB_OFFLINE")+ monkeypatch.setenv(probe.PROBE_ENV, "0")+ assert not probe.should_probe(MIRROR)+++def test_each_endpoint_is_probed_once_per_process():+ started = []+ for endpoint in (MIRROR, MIRROR + "/", MIRROR, "https://other.example.com"):+ probe.warn_if_mirror_redirects_to_official(endpoint, start = started.append)+ assert [t.daemon for t in started] == [True, True]+ assert [t._args for t in started] == [(MIRROR,), ("https://other.example.com",)]+++def test_saving_a_mirror_probes_it_and_modelscope_does_not(monkeypatch):+ import storage.studio_db as studio_db+ import hub.modelscope.router as modelscope++ values: dict = {}+ monkeypatch.setattr(+ studio_db, "get_app_settings", lambda keys: {k: values[k] for k in keys if k in values}+ )+ monkeypatch.setattr(+ studio_db, "upsert_app_settings", lambda updates, **_: values.update(updates) or values+ )+ monkeypatch.setattr(hub_settings, "_operator_env", None)+ monkeypatch.setattr(hub_settings, "_operator_endpoints", None, raising = False)+ monkeypatch.setattr(modelscope, "internal_endpoint", lambda: "http://127.0.0.1:1234")+ monkeypatch.delenv(hub_settings.SOURCE_ENV, raising = False)+ monkeypatch.delenv("HF_ENDPOINT", raising = False)+ asked = []+ monkeypatch.setattr(probe, "warn_if_mirror_redirects_to_official", asked.append)+ try:+ hub_settings.set_hub_settings(MIRROR, False)+ assert asked == [MIRROR]+ hub_settings.set_hub_source("modelscope")+ assert asked == [MIRROR]+ finally:+ monkeypatch.undo()+ hub_settings._refresh_imported_hub_libraries()+++def test_the_default_hub_never_imports_the_probe(monkeypatch):+ monkeypatch.delenv("HF_ENDPOINT", raising = False)+ monkeypatch.setattr(hub_settings, "_operator_env", None)+ monkeypatch.setattr(hub_settings, "_operator_endpoints", None, raising = False)+ monkeypatch.setattr(hub_settings, "_saved_only_endpoints", frozenset(), raising = False)+ monkeypatch.setattr(+ hub_settings, "get_hub_settings", lambda: hub_settings.HubSettings("", False, False)+ )+ monkeypatch.delitem(sys.modules, "utils.hub_mirror_probe")+ try:+ hub_settings.apply_hub_settings()+ assert "utils.hub_mirror_probe" not in sys.modules+ finally:+ sys.modules["utils.hub_mirror_probe"] = probe+++def test_one_failing_route_does_not_hide_the_other(monkeypatch):+ def handler(request):+ if request.method == "HEAD":+ raise httpx.ConnectTimeout("timed out", request = request)+ return httpx.Response(308, headers = {"location": f"https://huggingface.co{API}"})++ monkeypatch.setattr(probe, "transport", httpx.MockTransport(handler))+ assert probe.find_official_redirects(MIRROR) == [+ ("Hub API calls", f"https://huggingface.co{API}")+ ]diff --git a/studio/backend/utils/hub_mirror_probe.py b/studio/backend/utils/hub_mirror_probe.pynew file mode 100644index 00000000000..3ab723046db--- /dev/null+++ b/studio/backend/utils/hub_mirror_probe.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Log a warning when a custom Hub endpoint redirects to huggingface.co (hf-mirror.com does outside+mainland China), which huggingface_hub otherwise follows silently. No token, no redirect followed."""++from __future__ import annotations++import os+import threading+from typing import Callable, Optional+from urllib.parse import urljoin, urlsplit++import httpx++from loggers import get_logger+from utils.hf_endpoint import is_loopback_host++logger = get_logger(__name__)++PROBE_REPO = "openai-community/gpt2"+PROBE_FILE = "model.safetensors"+_OFFICIAL_DOMAINS = ("huggingface.co", "hf.co")+_TIMEOUT = httpx.Timeout(10.0)+PROBE_ENV = "UNSLOTH_STUDIO_HUB_PROBE"++# Tests swap in an httpx.MockTransport.+transport: Optional[httpx.BaseTransport] = None++_probed: set[str] = set()+_probed_lock = threading.Lock()+++def is_official_host(hostname: Optional[str]) -> bool:+ host = (hostname or "").lower().rstrip(".")+ return any(host == domain or host.endswith("." + domain) for domain in _OFFICIAL_DOMAINS)+++def _official_redirect(client: httpx.Client, method: str, url: str) -> Optional[str]:+ """The huggingface.co URL ``url`` redirects to, or None when the endpoint answers itself."""+ response = client.request(method, url)+ location = response.headers.get("location")+ if not response.is_redirect or not location:+ return None+ target = urljoin(url, location)+ return target if is_official_host(urlsplit(target).hostname) else None+++def find_official_redirects(endpoint: str) -> list[tuple[str, str]]:+ """``(what, target)`` for each probed route the endpoint sends to huggingface.co."""+ findings = []+ with httpx.Client(+ timeout = _TIMEOUT,+ follow_redirects = False,+ transport = transport,+ headers = {"User-Agent": "unsloth-studio"},+ ) as client:+ for what, method, url in (+ ("Hub API calls", "GET", f"{endpoint}/api/models/{PROBE_REPO}"),+ ("model downloads", "HEAD", f"{endpoint}/{PROBE_REPO}/resolve/main/{PROBE_FILE}"),+ ):+ try:+ target = _official_redirect(client, method, url)+ except httpx.HTTPError as exc:+ logger.debug("Hugging Face endpoint probe of %s failed: %s", url, exc)+ continue+ if target is not None:+ findings.append((what, target))+ return findings+++def _probe(endpoint: str) -> None:+ try:+ findings = find_official_redirects(endpoint)+ except Exception as exc: # noqa: BLE001 - an unreachable mirror is not this probe's finding+ logger.debug("Hugging Face endpoint probe of %s failed: %s", endpoint, exc)+ return+ if not findings:+ return+ logger.warning(+ "Hugging Face endpoint %s redirects %s to %s, so they do not go through the mirror "+ "from this network. They still work while huggingface.co is reachable; if it is not, "+ "use a mirror that serves this region, or ModelScope as the model source.",+ endpoint,+ " and ".join(what for what, _ in findings),+ ", ".join(sorted({urlsplit(target).hostname for _, target in findings})),+ )+++def should_probe(endpoint: str) -> bool:+ host = urlsplit(endpoint or "").hostname+ if not host or is_official_host(host) or is_loopback_host(host):+ return False+ off = ("1", "true", "yes", "on")+ if os.environ.get("HF_HUB_OFFLINE", "").strip().lower() in off:+ return False+ return os.environ.get(PROBE_ENV, "").strip().lower() not in ("0", "false", "no", "off")+++def warn_if_mirror_redirects_to_official(+ endpoint: str, *, start: Callable[[threading.Thread], None] = threading.Thread.start+) -> bool:+ """Probe ``endpoint`` in the background once per process. True when a probe was started."""+ endpoint = (endpoint or "").rstrip("/")+ if not should_probe(endpoint):+ return False+ with _probed_lock:+ if endpoint in _probed:+ return False+ _probed.add(endpoint)+ start(threading.Thread(target = _probe, args = (endpoint,), name = "hub-mirror-probe", daemon = True))+ return Truediff --git a/studio/backend/utils/hub_settings.py b/studio/backend/utils/hub_settings.pyindex ba36c155de5..68618000e0d 100644--- a/studio/backend/utils/hub_settings.py+++ b/studio/backend/utils/hub_settings.py@@ -240,6 +240,13 @@ def apply_hub_settings() -> None:utils_module = sys.modules.get("utils.utils")if utils_module is not None:utils_module.reset_hf_reachability_cache()+ endpoint = get_hf_endpoint()+ if source == HUGGINGFACE and endpoint != DEFAULTS_BY_HEALTH_KEY["hf_endpoint"]:+ try:+ from utils.hub_mirror_probe import warn_if_mirror_redirects_to_official+ warn_if_mirror_redirects_to_official(endpoint)+ except Exception: # noqa: BLE001 - a log-only probe must never fail applying settings+ logger.debug("Hugging Face endpoint probe did not start", exc_info = True)def saved_only_endpoints() -> frozenset[str]: