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
test(studio): stop the backend suite depending on a live Hub (#8174)
Daniel Hana6914ed832fc
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 9c359dfb8ec..03667d527da 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -11,6 +11,8 @@ Model/variant for the managed mode resolve from ``--unsloth-model`` /``--unsloth-gguf-variant``, then env vars, then ``test_studio_api.py`` defaults."""+import contextlib+import errnoimport itertoolsimport osimport sys@@ -58,6 +60,13 @@ def _isolate_studio_home(_studio_home_root, monkeypatch):# Pytest CLI options+def pytest_configure(config):+ config.addinivalue_line(+ "markers",+ "allow_network: let this test make non-loopback connections (see _no_outbound_network)",+ )++def pytest_addoption(parser):group = parser.getgroup("unsloth-e2e",@@ -210,6 +219,378 @@ def _assume_bare_metal(monkeypatch):)+_LOOPBACK_HOSTS = frozenset({"::1", "localhost", "localhost.localdomain", "0.0.0.0", "::", ""})++# The spellings worth writing into NO_PROXY. Same set as above minus the wildcards and+# the empty string, which mean "every interface" to bind() and nothing to a proxy rule.+_LOOPBACK_PROXY_BYPASS = ("localhost", "localhost.localdomain", "127.0.0.1", "::1")++_PROXY_ENV_VARS = (+ "HTTP_PROXY",+ "http_proxy",+ "HTTPS_PROXY",+ "https_proxy",+ "ALL_PROXY",+ "all_proxy",+)+++def no_proxy_with_test_servers(*existing) -> str:+ """Every *existing* NO_PROXY value, plus the servers this suite must reach directly.++ Takes all the spellings at once rather than one at a time. A host that exports only+ ``NO_PROXY`` would otherwise have its entries read for that variable and dropped+ from the ``no_proxy`` written beside it, and most clients read the lowercase one+ first -- so a bypass the developer had configured would quietly stop applying.+ """+ bypass = list(_LOOPBACK_PROXY_BYPASS) + sorted(_configured_server_hosts())+ parts = [+ part.strip() for value in existing for part in (value or "").split(",") if part.strip()+ ]+ return ",".join(dict.fromkeys(parts + bypass))+++# Server URLs the suite is explicitly configured to talk to. Both documented external-server+# modes may name a remote host, and neither suite carries the allow_network marker, so+# blocking them would make a deliberately configured integration run unusable.+_EXTERNAL_SERVER_ENV_VARS = ("UNSLOTH_E2E_BASE_URL", "STUDIO_TEST_URL")+++def _configured_server_hosts() -> frozenset:+ """Hostnames from the external-server env vars, so a configured endpoint stays dialable."""+ from urllib.parse import urlsplit++ hosts = set()+ for name in _EXTERNAL_SERVER_ENV_VARS:+ raw = (os.environ.get(name) or "").strip()+ if not raw:+ continue+ try:+ host = urlsplit(raw).hostname+ except ValueError:+ continue+ if host:+ hosts.add(host.lower())+ return frozenset(hosts)+++# What those hostnames resolved to during this test. socket.create_connection looks the+# name up and then dials the numeric result, so allowing the name alone still refuses the+# connect that follows: by then the destination is an address that matches no name rule.+# Filled in at resolution time, and only for names the rules already allowed, so the+# address-literal exemption below cannot widen anything through it.+_RESOLVED_SERVER_ADDRESSES: set = set()++# Lifted only by allow_outbound(), below. A module global rather than something a+# fixture holds, because the callers that need it run before any per-test fixture+# exists to hold it for them.+_outbound_permitted = False+++def allow_outbound():+ """Permit real outbound traffic for the duration of the block.++ For a session- or module-scoped fixture that has to fetch something for real. Those+ are built before the per-test fixtures, so ``@pytest.mark.allow_network`` on the+ test that happens to trigger one cannot reach back and lift the guard in time; the+ fixture has to say so itself. A test body should still use the marker.+ """+ global _outbound_permitted++ previous = _outbound_permitted+ _outbound_permitted = True+ try:+ yield+ finally:+ _outbound_permitted = previous+++def _decoded_host(host):+ """*host* as a comparable string, or None when it is not a name these rules can read.++ The socket API takes a hostname as ``str`` or ``bytes``. Comparing the bytes form+ against a set of strings matches nothing, so it has to be decoded before the rules+ see it, or every rule below silently says no and the caller-facing default decides.+ """+ if isinstance(host, (bytes, bytearray)):+ try:+ return bytes(host).decode("ascii")+ except UnicodeDecodeError:+ return None+ if isinstance(host, str):+ return host+ return None+++def _host_is_allowed(host) -> bool:+ """True for loopback and for any host the suite was explicitly pointed at.++ Anything that is not a readable hostname is refused rather than allowed. Defaulting+ the other way made ``getaddrinfo(b"huggingface.co", 443)`` a complete way around the+ guard: the byte string missed every rule, the non-string default let it through to+ the real resolver, and the address it returned was then dialable.+ """+ if host is None:+ # getaddrinfo(None, port) asks for a local address to bind, not a destination.+ return True+ decoded = _decoded_host(host)+ if decoded is None:+ return False+ lowered = decoded.strip().lower()+ return (+ lowered.startswith("127.")+ or lowered in _LOOPBACK_HOSTS+ or lowered in _configured_server_hosts()+ or lowered in _RESOLVED_SERVER_ADDRESSES+ )+++def _is_ip_literal(host) -> bool:+ """True when *host* is already an address, so resolving it consults no resolver."""+ import ipaddress++ decoded = _decoded_host(host)+ if decoded is None:+ return False+ try:+ ipaddress.ip_address(decoded.strip().strip("[]"))+ except ValueError:+ return False+ return True+++def _is_local_endpoint(sock, address) -> bool:+ """True for anything the suite may dial: local IPC and loopback addresses.++ Family first, because AF_UNIX carries a filesystem path rather than a host and+ multiprocessing's pools connect over exactly that -- reading ``address[0]`` there+ yields a directory name that matches no host rule and blocks process pools.+ """+ import socket as _socket++ if getattr(sock, "family", None) not in (_socket.AF_INET, _socket.AF_INET6):+ return True+ try:+ host = address[0]+ except Exception:+ return True+ return _host_is_allowed(host)+++class _RealSocketCalls:+ """The unpatched socket entry points, kept so a test can hand them back out."""++ def __init__(self, connect, connect_ex, getaddrinfo):+ self.connect = connect+ self.connect_ex = connect_ex+ self.getaddrinfo = getaddrinfo++[email protected](scope = "session", autouse = True)+def _outbound_network_guard():+ """Refuse every non-loopback connect, so no test depends on a live Hub.++ Several routes probe huggingface.co on paths these tests exercise, and every one+ of them fails open, so the traffic never showed up as a failure -- it only showed+ up as time. When the Hub answers slowly rather than refusing (a rate-limited CI+ egress IP is the usual way), huggingface_hub retries with backoff and a file that+ normally runs in six seconds sits there for minutes, until the job hits its cap+ and is killed having reported nothing.++ Blocking the socket keeps the online code path intact -- unlike HF_HUB_OFFLINE,+ which flips the branch and changes what is under test -- while making the call+ fail immediately instead of hanging. Mark a test ``allow_network`` if it genuinely+ needs to dial out; the e2e ``studio_server`` tests reach their server on loopback+ and are unaffected.++ Installed for the session rather than per test. pytest builds a test's fixtures+ widest scope first, so a function-scoped guard is not in place yet while session-+ and module-scoped fixtures are setting up, and those are as able to dial out as any+ test body. A fixture that wants out says so with ``allow_outbound()``, since by then+ it is too late for a marker on the test to reach back and lift anything.++ Reaches this interpreter only. A test that spawns a Python process gets a child with+ ordinary sockets, which is deliberate for the one fixture that does it: ``studio_server``+ starts a real server in managed mode, and that server is supposed to fetch the GGUF+ it serves. Blocking the child would break the e2e tests this suite runs on rather+ than remove a dependency they do not want. Those tests live in ``test_studio_api.py``,+ which CI skips, and are the only place a child is spawned.+ """+ import socket++ real = _RealSocketCalls(socket.socket.connect, socket.socket.connect_ex, socket.getaddrinfo)+ patch = pytest.MonkeyPatch()++ def blocked_connect(self, address, *args, **kwargs):+ if _outbound_permitted or _is_local_endpoint(self, address):+ return real.connect(self, address, *args, **kwargs)+ raise OSError(+ errno.ENETUNREACH,+ f"outbound network blocked in tests (tried {address!r}); "+ f"stub the call, or mark the test with @pytest.mark.allow_network",+ )++ def blocked_connect_ex(self, address, *args, **kwargs):+ if _outbound_permitted or _is_local_endpoint(self, address):+ return real.connect_ex(self, address, *args, **kwargs)+ # Returned, not raised: connect_ex reports failure with an errno and callers+ # branch on it (run.py probes a port that way). Raising here would send code+ # that only handles a non-zero result down a path a real failure never takes.+ return errno.ENETUNREACH++ # Resolution runs before either of those: socket.create_connection, which is what the+ # Hub's HTTP stack ends up in, calls getaddrinfo first. Left live, an uncached request+ # still hits the host resolver and can stall there, so the dependency is not actually+ # gone. Refuse the lookup too, which is also where a real resolver would fail.+ def guarded_getaddrinfo(host, port, *args, **kwargs):+ # An address literal consults no resolver, so it cannot stall and is left alone;+ # the SSRF guards resolve private literals on purpose to prove they reject them,+ # and connect() still refuses anything non-loopback afterwards.+ allowed_by_name = _outbound_permitted or _host_is_allowed(host)+ if not (allowed_by_name or _is_ip_literal(host)):+ raise socket.gaierror(+ socket.EAI_NONAME,+ f"name resolution blocked in tests ({host!r}); "+ f"stub the call, or mark the test with @pytest.mark.allow_network",+ )+ infos = real.getaddrinfo(host, port, *args, **kwargs)+ if allowed_by_name and not _outbound_permitted:+ # Carry the permission across the lookup, so the numeric address this hands+ # back is still dialable. Deliberately not done on the literal branch: that+ # one exists so a private literal can be resolved and then refused.+ for info in infos:+ try:+ _RESOLVED_SERVER_ADDRESSES.add(str(info[4][0]).lower())+ except Exception:+ continue+ return infos++ patch.setattr(socket.socket, "connect", blocked_connect)+ patch.setattr(socket.socket, "connect_ex", blocked_connect_ex)+ patch.setattr(socket, "getaddrinfo", guarded_getaddrinfo)++ # A refused connection still looks retryable to huggingface_hub, which backs off+ # 1+2+4+8+8s over five attempts before giving up -- so blocking the socket without+ # this turns a fast failure back into a ~23s one per call. Swap the clock only+ # inside that module, since `time` is shared and real sleeps elsewhere matter.+ try:+ from huggingface_hub.utils import _http as hf_http+ except Exception:+ hf_http = None+ if hf_http is not None and getattr(hf_http, "time", None) is not None:+ import time as _time+ class _NoBackoffClock:+ def __getattr__(self, name):+ return getattr(_time, name)++ @staticmethod+ def sleep(_seconds):+ return None++ patch.setattr(hf_http, "time", _NoBackoffClock())++ # A proxy, where one is configured, is dialled instead of the server the request+ # names -- so the guard sees the proxy, which is not what the run was pointed at,+ # refuses it, and the server is unreachable after all. That applies to the managed+ # loopback server as much as to a configured remote one: a proxy with no loopback+ # entry in NO_PROXY swallows localhost requests too.+ #+ # Bypassed rather than allowed, since allowing the proxy host would let that same+ # proxy carry Hub traffic straight through, which is the thing being stopped here.+ # Done at session scope with everything else: the fixtures that dial these servers+ # (test_providers_api's auth_headers and public_key_pem) are session-scoped, so a+ # per-test version would be set up long after they had already tried and failed.+ if any(os.environ.get(name) for name in _PROXY_ENV_VARS):+ # Both spellings merged once and written back identically, so neither variable+ # loses what the other one carried.+ combined = no_proxy_with_test_servers(+ os.environ.get("NO_PROXY"), os.environ.get("no_proxy")+ )+ for name in ("NO_PROXY", "no_proxy"):+ patch.setenv(name, combined)++ try:+ yield real+ finally:+ patch.undo()+++def forget_resolved_servers():+ """Drop the addresses resolved so far, so a test can check something is refused."""+ return _RESOLVED_SERVER_ADDRESSES.clear++[email protected](scope = "session")+def no_proxy_bypass_value():+ """Hand out the NO_PROXY builder, which is otherwise only reachable as a fixture."""+ return no_proxy_with_test_servers++[email protected](scope = "session")+def allow_outbound_network(_outbound_network_guard):+ """Hand a fixture the context manager that lifts the guard around a real fetch."""+ return allow_outbound++[email protected](autouse = True)+def _no_outbound_network(request, monkeypatch, _outbound_network_guard):+ """Per-test half of the guard: reset what the last test was allowed to reach.++ Also lifts the guard for the whole of an ``allow_network`` test, which is where a+ marker can still do the job: the test body has not started yet.+ """+ # Per test, so a name a test pointed the env vars at itself does not stay dialable+ # for the rest of the run.+ _RESOLVED_SERVER_ADDRESSES.clear()++ if request.node.get_closest_marker("allow_network") is not None:+ import socket++ real = _outbound_network_guard+ monkeypatch.setattr(socket.socket, "connect", real.connect)+ monkeypatch.setattr(socket.socket, "connect_ex", real.connect_ex)+ monkeypatch.setattr(socket, "getaddrinfo", real.getaddrinfo)++[email protected](autouse = True)+def _hub_reachable_without_probing(monkeypatch):+ """Report the Hub as reachable without dialling it.++ The reachability probes are themselves network calls, so with outbound traffic+ blocked they would report the Hub down and send every caller into its offline+ branch -- which is a different code path from the one these tests mean to cover.+ Pinning them to "reachable" keeps the online path selected; the individual+ request that follows is still blocked, and the callers already fail open on it.+ Tests about offline behaviour patch these back.++ Seeded through the memo rather than by patching ``hf_dns_dead`` /+ ``hf_unreachable``: callers ``from utils.utils import`` those names, so patching+ the source module leaves already-imported bindings pointing at the real probes.+ Every caller reaches the memo through a function that reads the module global at+ call time, so seeding it covers them all regardless of import style.++ The verdict is also pinned fresh for the whole test. The memo expires after+ ``_HF_REACHABILITY_TTL_S`` (five seconds), so a seed stamped now would lapse in any+ test that reaches a Hub-guarded operation later than that, and the real probe would+ run into the blocked socket and select the offline branch this fixture exists to+ avoid. The stamp is dated far ahead instead, which keeps it fresh under the real+ freshness rule rather than disabling that rule for every test.+ """+ import time++ from utils import utils as utils_utils++ # Dated far ahead rather than by overriding _reachability_fresh: the freshness rule is+ # itself under test (test_verdict_expires_so_a_disconnect_is_noticed shortens the TTL and+ # asserts the verdict lapses), so it has to keep working. A future stamp keeps this seed+ # fresh under the real rule, and a test that writes its own verdict replaces it.+ monkeypatch.setattr(+ utils_utils, "_hf_reachability", (time.monotonic() + 10**6, False), raising = False+ )++@pytest.fixture(scope = "session")def studio_server(request):"""Yield ``(base_url, api_key)`` for e2e tests.diff --git a/studio/backend/tests/test_outbound_network_guard.py b/studio/backend/tests/test_outbound_network_guard.pynew file mode 100644index 00000000000..589372fd046--- /dev/null+++ b/studio/backend/tests/test_outbound_network_guard.py@@ -0,0 +1,229 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: the suite's outbound-network guard blocks the Hub without blocking the suite.++``conftest._no_outbound_network`` exists so no test depends on huggingface.co being up and+fast. It has to hold two things apart that look alike from inside a socket call: traffic+nobody asked for, which must fail immediately, and the server an integration run was+deliberately pointed at, which must stay reachable.++The ways it got that wrong were only visible end to end, so this covers it there:+resolution and connection are separate hooks, and a rule enforced on one of them says+nothing about the other. CPU-only, and every connection here is to this same machine.+"""++from __future__ import annotations++import errno+import socket+import threading++import pytest+++def _own_routable_address(hostname: str) -> str | None:+ """This host's own non-loopback IPv4, or None if it does not have a usable one."""+ try:+ infos = socket.getaddrinfo(hostname, None, socket.AF_INET, socket.SOCK_STREAM)+ except OSError:+ return None+ for info in infos:+ address = info[4][0]+ if not address.startswith("127.") and address != "0.0.0.0":+ return address+ return None+++def offbox_server(monkeypatch):+ """Yield ``(hostname, address, port)`` for a listener on this host's routable address.++ That address stands in for a remote server: it is off loopback, so the guard treats+ it exactly as it would treat somebody else's machine, while no packet leaves the box.++ The name is configured before it is resolved, because the guard blocks resolution of+ anything unconfigured -- including, correctly, this machine's own name.++ Skips where the stand-in is not available: a runner with only loopback configured, or+ one whose hostname does not resolve, cannot express "a server that is not local".+ """+ hostname = socket.gethostname()+ monkeypatch.setenv("UNSLOTH_E2E_BASE_URL", f"http://{hostname}")++ address = _own_routable_address(hostname)+ if address is None:+ pytest.skip("host has no non-loopback IPv4 to stand in for a remote server")++ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ server.bind((address, 0))+ except OSError:+ server.close()+ pytest.skip(f"cannot bind {address} on this runner")+ server.listen(8)+ port = server.getsockname()[1]++ def _accept_quietly():+ while True:+ try:+ conn, _ = server.accept()+ except OSError:+ return+ conn.close()++ threading.Thread(target = _accept_quietly, daemon = True).start()+ try:+ yield hostname, address, port+ finally:+ server.close()+++def test_a_server_configured_by_name_is_reachable(monkeypatch, offbox_server):+ """The regression: allowing the hostname alone is not enough.++ ``socket.create_connection`` resolves first and then dials the numeric result, so a+ rule that only knows the name refuses the connect that follows it -- the destination+ is by then an address that matches nothing. A configured endpoint was unusable.+ """+ hostname, _address, port = offbox_server+ monkeypatch.setenv("UNSLOTH_E2E_BASE_URL", f"http://{hostname}:{port}")++ socket.create_connection((hostname, port), timeout = 10).close()+++def test_a_server_configured_by_address_is_reachable(monkeypatch, offbox_server):+ """The same endpoint written as an address, which skips the resolver entirely."""+ _hostname, address, port = offbox_server+ monkeypatch.setenv("STUDIO_TEST_URL", f"http://{address}:{port}")++ socket.create_connection((address, port), timeout = 10).close()+++def test_resolving_an_address_literal_does_not_make_it_dialable():+ """The literal exemption must not become a way through.++ Literals are exempt from the resolution rule because the SSRF tests resolve private+ ones on purpose to prove they get rejected. That exemption is about the lookup only:+ the connect has to stay refused, or those tests would start reaching the address+ they are asserting is unreachable.+ """+ socket.getaddrinfo("169.254.169.254", 80, socket.AF_INET, socket.SOCK_STREAM)++ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ with pytest.raises(OSError, match = "outbound network blocked"):+ sock.connect(("169.254.169.254", 80))+ finally:+ sock.close()+++def test_an_unconfigured_name_fails_at_resolution():+ """Blocked names fail the way an unresolvable name does, which callers already handle."""+ with pytest.raises(socket.gaierror, match = "name resolution blocked"):+ socket.getaddrinfo("huggingface.co", 443, socket.AF_INET, socket.SOCK_STREAM)+++def test_a_byte_hostname_is_read_rather_than_waved_through():+ """The regression: bytes are a hostname too.++ ``socket`` takes a name as ``str`` or ``bytes``. Compared as-is, the byte form+ matched no rule and fell through to whatever the non-string case did -- which was+ to allow it. That made ``getaddrinfo(b"huggingface.co", 443)`` a way straight out:+ real resolution, and the address it returned dialable afterwards.+ """+ with pytest.raises(socket.gaierror, match = "name resolution blocked"):+ socket.getaddrinfo(b"huggingface.co", 443, socket.AF_INET, socket.SOCK_STREAM)+++def test_a_byte_hostname_for_a_configured_server_still_works(monkeypatch, offbox_server):+ """Reading the byte form must mean reading it, not refusing it."""+ hostname, _address, port = offbox_server+ monkeypatch.setenv("UNSLOTH_E2E_BASE_URL", f"http://{hostname}:{port}")++ infos = socket.getaddrinfo(hostname.encode(), port, socket.AF_INET, socket.SOCK_STREAM)+ assert infos+++def test_connect_ex_reports_the_block_the_way_it_reports_a_failure():+ """connect_ex answers with an errno; callers branch on it rather than catching.++ ``run.py`` probes a port exactly that way. Raising here would send code that only+ handles a non-zero result down a path an ordinary failed connect_ex never takes.+ """+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ assert sock.connect_ex(("169.254.169.254", 80)) == errno.ENETUNREACH+ finally:+ sock.close()+++def test_a_fixture_can_ask_for_the_traffic_it_needs(+ monkeypatch, allow_outbound_network, offbox_server, forget_resolved_servers+):+ """The escape hatch for fixtures built before the per-test guard exists.++ Dialled by address, at a listener on this machine: no resolver is consulted and no+ packet leaves the box. Checking the lift against a real hostname would have meant a+ live lookup with the guard down, which on a runner with slow or blackholed DNS is+ the stall this whole change exists to remove.+ """+ _hostname, address, port = offbox_server+ # Undo what the fixture configured, so the address is a stranger again.+ monkeypatch.delenv("UNSLOTH_E2E_BASE_URL", raising = False)+ forget_resolved_servers()++ with pytest.raises(OSError, match = "outbound network blocked"):+ socket.create_connection((address, port), timeout = 10)++ with allow_outbound_network():+ socket.create_connection((address, port), timeout = 10).close()++ with pytest.raises(OSError, match = "outbound network blocked"):+ socket.create_connection((address, port), timeout = 10)+++def test_the_proxy_bypass_covers_the_local_server_too(monkeypatch, no_proxy_bypass_value):+ """A proxy swallows loopback requests as readily as remote ones.++ With ``HTTP_PROXY`` set and no loopback entry in ``NO_PROXY``, a request to the+ managed ``studio_server`` is sent to the proxy instead. The guard then refuses the+ proxy, correctly, and the server on 127.0.0.1 is unreachable through no fault of+ its own. Naming only the configured external servers left that case out.+ """+ monkeypatch.setenv("UNSLOTH_E2E_BASE_URL", "http://studio.example.internal:8000")+ bypass = no_proxy_bypass_value("corp.example, 10.0.0.1").split(",")++ assert "127.0.0.1" in bypass+ assert "localhost" in bypass+ assert "studio.example.internal" in bypass, "the configured server must still be bypassed"+ assert bypass[:2] == ["corp.example", "10.0.0.1"], "an existing NO_PROXY must survive"+ assert len(bypass) == len(set(bypass)), "entries must not be duplicated on re-entry"+++def test_neither_no_proxy_spelling_loses_what_the_other_carried(no_proxy_bypass_value):+ """A host that exports only one spelling must not have the other overwrite it.++ Reading one variable and writing both drops the entries the developer set, and+ clients generally read the lowercase one first -- so the bypass silently stops+ applying to the host it was written for.+ """+ bypass = no_proxy_bypass_value("only-in-uppercase.example", "").split(",")+ assert "only-in-uppercase.example" in bypass++ both = no_proxy_bypass_value("upper.example", "lower.example").split(",")+ assert "upper.example" in both and "lower.example" in both+ assert len(both) == len(set(both))+++def test_loopback_stays_open():+ """The guard must not disturb the in-process servers most of the suite runs on."""+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ server.bind(("127.0.0.1", 0))+ server.listen(1)+ try:+ socket.create_connection(server.getsockname(), timeout = 10).close()+ finally:+ server.close()diff --git a/studio/backend/tests/test_providers_api.py b/studio/backend/tests/test_providers_api.pyindex 7cac3a9e991..b7c13ccf9ec 100644--- a/studio/backend/tests/test_providers_api.py+++ b/studio/backend/tests/test_providers_api.py@@ -163,13 +163,18 @@ def public_key_pem(auth_headers: dict[str, str]) -> str:@pytest.fixture(scope = "session")-def vision_image_data_url() -> str:+def vision_image_data_url(allow_outbound_network) -> str:"""Download the sloth image once per session as a base64 data URI.A data URI sends the image inline; Gemini's OpenAI-compatible layer doesn'tfetch external HTTP URLs, so raw image_url links give empty Gemini replies.++ This one genuinely fetches, so it says so: the suite otherwise blocks outbound+ traffic, and a session fixture is built before the per-test guard can be told to+ make an exception for it."""- resp = requests.get(_VISION_IMAGE_URL, timeout = 30)+ with allow_outbound_network():+ resp = requests.get(_VISION_IMAGE_URL, timeout = 30)resp.raise_for_status()content_type = resp.headers.get("Content-Type", "image/jpeg").split(";")[0].strip()b64 = base64.b64encode(resp.content).decode("utf-8")diff --git a/studio/backend/tests/test_stt_review_fixes_4.py b/studio/backend/tests/test_stt_review_fixes_4.pyindex c7600dae35f..3853138d18b 100644--- a/studio/backend/tests/test_stt_review_fixes_4.py+++ b/studio/backend/tests/test_stt_review_fixes_4.py@@ -182,12 +182,18 @@ def test_status_reads_do_not_block_during_a_llama_cpp_update():), "a status read blocked for the length of the llama.cpp install"-def test_ggml_download_drops_its_adopted_pid(monkeypatch):+def test_ggml_download_drops_its_adopted_pid(monkeypatch, tmp_path):"""spawn_download() adopts a PID; left adopted it can be reused, andterminate_all would then signal whatever inherited it."""forgotten = []+ # Once metadata resolves, _run() prepares the repo's cache for HTTP before it+ # reaches the stubbed worker, and that writes: it creates the repo directory and+ # a .transport marker. The session conftest deliberately pins HF_HUB_CACHE to the+ # developer's real cache, so without a cache of its own this test edits it.+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))+class _Finished:pid = 7777returncode = 0@@ -196,6 +202,28 @@ def test_ggml_download_drops_its_adopted_pid(monkeypatch):return 0monkeypatch.setattr(ggml_mod, "_cached_model_path", lambda model_id: None)+ # _run() opens with a HEAD to the Hub for the size and etag. It is best-effort and+ # swallows its own errors, but leaving it live makes this test depend on a network+ # round trip it does not care about, so answer it locally.+ import huggingface_hub++ class _Metadata:+ """Stands in for HfFileMetadata; unset fields read as None, as they may on the Hub.++ ``commit_hash`` has to be a real-looking sha: _run() pins the download to an+ immutable revision and refuses anything that is not one.+ """++ size = 1+ etag = "stub"+ commit_hash = "0" * 40++ def __getattr__(self, _name):+ return None++ monkeypatch.setattr(+ huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _Metadata(), raising = False+ )import core.inference.stt_download_worker as worker_modmonkeypatch.setattr(worker_mod, "spawn_download", lambda *a, **k: _Finished())diff --git a/studio/backend/tests/test_training_streaming_mlx_warm.py b/studio/backend/tests/test_training_streaming_mlx_warm.pyindex 3a76ba69098..f23fca35d11 100644--- a/studio/backend/tests/test_training_streaming_mlx_warm.py+++ b/studio/backend/tests/test_training_streaming_mlx_warm.py@@ -61,6 +61,27 @@ def hardware_globals():hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved[email protected](autouse = True)+def _hub_preflight_passes(monkeypatch):+ """Let the Hub preflights succeed without asking the Hub.++ This file is about the MLX guard, and its docstring already promises no network,+ but ``start_training`` verifies the model and dataset against huggingface.co on+ the way past validation. That call used to reach the real Hub, so the tests were+ quietly online and would 503 whenever it was slow or unreachable.+ """+ monkeypatch.setattr(training_routes, "_preflight_hf_dataset_request", lambda request: None)+ monkeypatch.setattr(+ training_routes,+ "_reject_untrainable_model_request",+ lambda request, *args, **kwargs: training_routes._ModelPreflightResult(+ model_name = request.model_name,+ model_local_path = None,+ cached_model_pin = None,+ ),+ )++@pytest.fixturedef spawn_calls(monkeypatch):"""Stub the backend so a start past validation is observable without a worker."""