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
Read quoted annotations in the import lint, and build the video load doubles off the real backend (#9601)
Daniel Han3c998cc8f3fa
diff --git a/scripts/verify_import_hoist.py b/scripts/verify_import_hoist.pyindex 9611aa81ff6..66dc56e9725 100644--- a/scripts/verify_import_hoist.py+++ b/scripts/verify_import_hoist.py@@ -118,6 +118,13 @@ def _import_target(node: ast.AST, alias: ast.alias) -> tuple[str, str]:return bound, f"from:{mod}:{alias.name}"+def _is_literal_ref(node: ast.AST) -> bool:+ """Whether `node` names `Literal`, however it was imported (`Literal`, `t.Literal`)."""+ if isinstance(node, ast.Name):+ return node.id == "Literal"+ return isinstance(node, ast.Attribute) and node.attr == "Literal"++class _Builder(ast.NodeVisitor):"""Builds the scope tree + bindings, and records every (scope, Name-load)."""@@ -127,14 +134,44 @@ class _Builder(ast.NodeVisitor):# annotations: count as "used" but never as "unresolved" (forward refs)self.soft_uses: list[tuple[Scope, str, int]] = []- def _visit_annotation(self, node, scope: Scope) -> None:+ # `Optional["Dict[str, 'T']"]` is two deep; nothing real goes further.+ _FORWARD_REF_DEPTH = 3++ def _visit_annotation(+ self,+ node,+ scope: Scope,+ _depth: int = 0,+ _lineno: int = 0,+ ) -> None:"""Record annotation names as SOFT uses: an import used only in an annotation- counts as used, but a forward-ref name is never 'unresolved'."""+ counts as used, but a forward-ref name is never 'unresolved'.++ A QUOTED annotation is one too: `Optional["T"]` keeps the name in an ast.Constant,+ invisible to a Name walk, so a TYPE_CHECKING import reached only that way read as+ unused and blocked correct code. Parse the string and walk what it denotes.+ """if node is None:return- for n in ast.walk(node):- if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):- self.soft_uses.append((scope, n.id, n.lineno))+ # Literal[...] holds values, not type names. Skipping its args is what keeps this+ # from crediting an unrelated import, the one direction that loses a real finding.+ if isinstance(node, ast.Subscript) and _is_literal_ref(node.value):+ self._visit_annotation(node.value, scope, _depth, _lineno)+ return+ if isinstance(node, ast.Constant):+ if not isinstance(node.value, str) or _depth >= self._FORWARD_REF_DEPTH:+ return+ try:+ inner = ast.parse(node.value.strip(), mode = "eval").body+ except (SyntaxError, ValueError):+ return # Prose, as in Annotated[int, "docs"]. Nothing to credit.+ # Report against the string's own line; the parsed tree numbers from 1.+ self._visit_annotation(inner, scope, _depth + 1, _lineno or node.lineno)+ return+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):+ self.soft_uses.append((scope, node.id, _lineno or node.lineno))+ for child in ast.iter_child_nodes(node):+ self._visit_annotation(child, scope, _depth, _lineno)# -- binding helpers --def _bind_targets(self, scope: Scope, target: ast.AST) -> None:@@ -733,6 +770,45 @@ _SELF_TESTS = {"BLOCKER","pkg/__init__.py",),+ # --- quoted annotations are annotations ---+ # A TYPE_CHECKING import reached only through a forward reference IS used.+ "forward_ref_string_annotation_counts_as_a_use": (+ "from typing import TYPE_CHECKING, Optional\ndef f(x) -> Optional[int]:\n return x\n",+ "from typing import TYPE_CHECKING, Optional\n"+ "if TYPE_CHECKING:\n"+ " from .m import T\n"+ 'def f(x) -> Optional["T"]:\n'+ " return x\n",+ None,+ ),+ # Two strings deep; each layer is parsed.+ "nested_forward_ref_counts_as_a_use": (+ "from typing import TYPE_CHECKING, Optional\ndef f(x) -> Optional[int]:\n return x\n",+ "from typing import TYPE_CHECKING, Optional\n"+ "if TYPE_CHECKING:\n"+ " from .m import T\n"+ "def f(x) -> Optional[\"Optional['T']\"]:\n"+ " return x\n",+ None,+ ),+ # The other direction: Literal['T'] is a VALUE, so it must NOT credit an import T.+ "a_literal_value_is_not_a_use_of_that_name": (+ "from typing import TYPE_CHECKING, Literal\ndef f(x) -> Literal['a']:\n return x\n",+ "from typing import TYPE_CHECKING, Literal\n"+ "if TYPE_CHECKING:\n"+ " from .m import T\n"+ "def f(x) -> Literal['T']:\n"+ " return x\n",+ "BLOCKER",+ ),+ # Prose is not a type, and a parse error there is not a finding.+ "unparseable_annotation_string_is_ignored": (+ "from typing import Annotated\ndef f(x: Annotated[int, 'ok']) -> int:\n return x\n",+ "from typing import Annotated\n"+ "def f(x: Annotated[int, 'not a type at all']) -> int:\n"+ " return x\n",+ None,+ ),}diff --git a/studio/backend/tests/test_media_auto_switch.py b/studio/backend/tests/test_media_auto_switch.pyindex 05841adb244..a5ec34fe871 100644--- a/studio/backend/tests/test_media_auto_switch.py+++ b/studio/backend/tests/test_media_auto_switch.py@@ -35,6 +35,43 @@ from core.inference.openai_auto_download import preferred_quantfrom utils.api_errors import install_api_error_handlers+def _a_real_video_family(name = "wan2.2-ti2v-5b"):+ """A real ``VideoFamily``, for tests that just need the route to carry one.++ A bare ``object()`` stands in for a forty-field frozen dataclass, so the first field+ nobody hand-copied fails the test on an AttributeError about nothing it asserts.+ """+ from core.inference.video_families import detect_video_family++ # By name, not repo id: which tokens a repo id matches is its own rule, tested elsewhere.+ fam = detect_video_family("", override = name)+ assert fam is not None, f"the video family registry no longer has {name!r}"+ return fam+++def _video_load_backend(**overrides):+ """A real ``VideoBackend`` with only the asserted methods replaced.++ Every other call the route makes runs the real implementation, which for the load+ route's preflight and reservation helpers is pure registry resolution: no hub, no GPU,+ no weights, and ``__init__`` only allocates locks. A hand-rolled stub instead needs+ extending every time the route grows a call, and until it is, unrelated tests fail on a+ missing attribute rather than on what they assert.++ ``overrides`` are checked against the class, so a stub for a method that does not exist+ fails loudly instead of quietly never being called.+ """+ from core.inference.video import VideoBackend++ unknown = sorted(name for name in overrides if not hasattr(VideoBackend, name))+ assert not unknown, f"not part of the video backend's surface: {unknown}"++ backend = VideoBackend()+ for name, impl in overrides.items():+ setattr(backend, name, impl)+ return backend++def _info(model_id,path,@@ -1134,20 +1171,45 @@ def test_a_local_video_pipeline_is_still_planned(h3_modular, enabled, backend, lassert loads == []+def test_every_backend_call_the_video_route_makes_exists_on_the_backend():+ """``backend.<name>`` in routes/video.py must name something ``VideoBackend`` has.++ ``get_video_backend()`` is untyped at the call site, so a method renamed on the class or+ misspelled in the route is no syntax error, no lint finding, and invisible to any double+ stubbing the old name. It is an AttributeError on a real load, and the route's own tests+ mock the backend out. Read off the parse tree, not the text.+ """+ import ast+ import inspect++ import routes.video as video_route+ from core.inference.video import VideoBackend++ tree = ast.parse(inspect.getsource(video_route))+ asked = {+ node.attr+ for node in ast.walk(tree)+ if isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id == "backend"+ and isinstance(node.ctx, ast.Load)+ }+ assert asked, "no backend calls found -- the route was restructured, so this guard is blind"+ missing = sorted(name for name in asked if not hasattr(VideoBackend, name))+ assert not missing, f"routes/video.py calls backend methods that do not exist: {missing}"++def test_the_video_load_route_records_provenance_without_raising(monkeypatch):# The provenance call is made positionally from both load routes, so a signature that drifts# from them 500s every load after the background work has already been accepted.import core.inference.video as video_modulefrom routes.video import router as video_router- class _Backend:- def validate_load_request(self, *a, **k):- return object()-- def begin_load(self, *a, **k):- return {"loaded": False, "repo_id": None}-- monkeypatch.setattr(video_module, "get_video_backend", lambda: _Backend())+ backend = _video_load_backend(+ validate_load_request = lambda *a, **k: _a_real_video_family(),+ begin_load = lambda *a, **k: {"loaded": False, "repo_id": None},+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)monkeypatch.setattr(video_module, "resolve_video_model_kind", lambda *a, **k: "gguf")monkeypatch.setattr(video_module, "assert_video_precision_available", lambda *a, **k: None)monkeypatch.setattr("routes.video._guard_video_load_against_training", lambda: None)@@ -2436,22 +2498,29 @@ def _capture_begin_load(monkeypatch, route):"""Record the local_files_only begin_load is called with, for either media route."""seen: list = []- class _Backend:- def validate_load_request(self, *a, **k):- return types.SimpleNamespace(name = "z-image", base_repo = None)-- def begin_load(self, *a, **k):- seen.append(k.get("local_files_only"))- return {"loaded": False, "repo_id": None}+ def _begin_load(*a, **k):+ seen.append(k.get("local_files_only"))+ return {"loaded": False, "repo_id": None}if route == "images":import core.inference.diffusion_engine_router as router_module++ class _Backend:+ def validate_load_request(self, *a, **k):+ return types.SimpleNamespace(name = "z-image", base_repo = None)++ begin_load = staticmethod(_begin_load)+monkeypatch.setattr(router_module, "select_and_activate_engine", lambda *a, **k: _Backend())monkeypatch.setattr(router_module, "get_active_diffusion_engine", lambda: _Backend())else:import core.inference.video as video_module- monkeypatch.setattr(video_module, "get_video_backend", lambda: _Backend())+ backend = _video_load_backend(+ validate_load_request = lambda *a, **k: _a_real_video_family(),+ begin_load = _begin_load,+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)monkeypatch.setattr(video_module, "resolve_video_model_kind", lambda *a, **k: "gguf")monkeypatch.setattr(video_module, "assert_video_precision_available", lambda *a, **k: None)monkeypatch.setattr("routes.video._guard_video_load_against_training", lambda: None)