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
Reject an incompatible GGUF and base pair before the download, not after (#8158)
Daniel Han1d116166e831
diff --git a/.github/workflows/model-catalog-network-check.yml b/.github/workflows/model-catalog-network-check.ymlnew file mode 100644index 00000000000..2dab2aa0013--- /dev/null+++ b/.github/workflows/model-catalog-network-check.yml@@ -0,0 +1,61 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+#+# Asks the Hub whether the preconfigured model catalog is still downloadable.+#+# The picker's catalog is a hand-maintained table of repo ids, filenames and+# `gated` flags. Nothing in the codebase can tell when one of them stops being+# true: a repo gets renamed, unpublished or switched to gated, and the entry+# keeps rendering as a one-click download that 404s or 401s partway through.+# That is precisely how several links shipped broken.+#+# This runs `catalog:check --network`, which HEADs every declared repo id and+# every declared filename anonymously (what a fresh install sees) and asserts+# each `gated` flag matches what the Hub reports.+#+# Schedule + manual only, never on pull_request. The check is opt-in for the+# same reason it lives here: it depends on huggingface.co being up, and a Hub+# hiccup must not fail an unrelated PR. Plain `npm run catalog:check` stays+# purely offline and keeps every assertion it had. A red run here means the+# catalog needs editing, not a re-run -- the script already retries 3x with+# backoff and ignores 429/5xx, so it only speaks when the Hub is definite.++name: Model catalog network check++on:+ schedule:+ - cron: '19 6 * * *' # 06:19 UTC daily, off the cron rush+ workflow_dispatch:++concurrency:+ # The event is part of the group so a manual dispatch and the nightly cannot+ # coalesce; both resolve to refs/heads/main.+ group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}+ cancel-in-progress: false++permissions:+ contents: read++jobs:+ catalog-network:+ name: catalog entries must still be downloadable+ runs-on: ubuntu-latest+ timeout-minutes: 10+ defaults:+ run:+ working-directory: studio/frontend+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: '22'++ # No `npm ci`: the check is a standalone node script over two data+ # modules and the built-in fetch, so it needs no dependencies at all.+ # Skipping the install also keeps this job away from the lockfile /+ # allowScripts machinery the frontend PR gate has to run.+ - name: Catalog entries must still resolve on the Hub+ run: npm run catalog:check:networkdiff --git a/pyproject.toml b/pyproject.tomlindex 92a43c681a3..4188fa9da67 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -104,6 +104,7 @@ studio = ["datasets==4.3.0","pyjwt","huggingface-hub==0.36.2",+ "urllib3>=2.3.0","structlog>=24.1.0","diceware","ddgs",diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1b655a3b384..dcc0f1b85bc 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -52,6 +52,7 @@ from .diffusion_families import (resolve_local_gguf_child,supported_family_names,)+from .diffusion_compat import assert_flux2_pick_compatible, flux2_pick_mismatchfrom .diffusion_device import (DiffusionDeviceTarget,diffusion_device_target_from_torch_device,@@ -1346,14 +1347,15 @@ class DiffusionBackend:base_repo: Optional[str] = None,hf_token: Optional[str] = None,) -> None:- """The gated/unreadable-base refusal, run by the route BEFORE it takes the GPU.-- ``_run_load`` and ``download_plan`` already make it, but ``_run_load`` runs on the load- thread, after the route evicted chat, and the plan's 400 does not stop the load: the images- page falls back to /images/load on ANY plan failure. Resolves the base exactly as those two- do, so all three agree. The one deliberate network step on the pre-eviction path- (``validate_load_request`` stays network-free): two metadata calls for a remote pick, none- for a local one, both already made by ``_run_load`` moments later. Fails open on+ """The gated/unreadable-base and FLUX.2 size-pairing refusals, run by the route BEFORE it+ takes the GPU.++ ``_run_load`` and ``download_plan`` already make them, but ``_run_load`` runs on the load+ thread, after the route evicted chat, and the plan's verdict does not stop the load: the+ images page falls back to /images/load on ANY plan failure. Resolves the base exactly as+ those two do, so all three agree. The one deliberate network step on the pre-eviction path+ (``validate_load_request`` stays network-free): a handful of metadata calls for a remote+ pick, none for a local one, all already made by ``_run_load`` moments later. Fails open onoffline/transient, so it can refuse a load but never block one that would have worked."""kind = resolve_model_kind(gguf_filename, model_kind)if kind == "pipeline":@@ -1364,6 +1366,12 @@ class DiffusionBackend:# picks the ungated mirror rescues, and the swap is pure, so it decides the same here as on# the load thread. Only the raise matters; _run_load recomputes the excused snapshot._assert_base_repo_accessible(prefer_ungated_mirror(base, hf_token), hf_token)+ # Same reasoning for the FLUX.2 size pairing, and this is the only place it can be caught+ # before a teardown: the loader's own guard opens the downloaded checkpoint, so it fires+ # after ~19 GB of base shards AND after the resident pipeline was freed. Metadata only (one+ # range request for the GGUF's tensor table), and fails open on anything it cannot read.+ # The UPSTREAM base, not the mirror: the size tables key on vendor ids.+ assert_flux2_pick_compatible(fam, repo_id, gguf_filename, base, hf_token)# ── Background load + progress ─────────────────────────────────────────@@ -1498,6 +1506,13 @@ class DiffusionBackend:# Everything above is metadata, so no byte has moved yet. Returns a snapshot dir when it# excused the base off a copy only the import-time root holds.base_snapshot = _assert_base_repo_accessible(fetch_base, kwargs.get("hf_token"))+ # And the same size-pairing preflight the plan and the route run, here because a direct+ # begin_load (a saved config, the deploy path) reaches neither. Still metadata only, so+ # it lands before _prefetch_files stages the base and before load_pipeline unloads the+ # resident pipeline -- the two costs the loader's backstop cannot avoid.+ assert_flux2_pick_compatible(+ fam, kwargs["repo_id"], kwargs.get("gguf_filename"), base, kwargs.get("hf_token")+ )with self._lock:# Stamp progress only if this load is still current (a superseder has its own token).if self._load_token == token and self._loading is not None:@@ -1829,6 +1844,11 @@ class DiffusionBackend:base = repo_id # the full pipeline IS the repoelse:base = _resolve_base_repo(repo_id, base_repo, fam, hf_token)+ # Reported, not raised. The images page falls back to /images/load on ANY plan failure, so+ # a 400 here would start the very download this is meant to prevent; carried in the+ # envelope instead, the picker can refuse at SELECTION time. Metadata only (one range+ # request for the GGUF's tensor table), and None whenever nothing is known to be wrong.+ incompatible = flux2_pick_mismatch(fam, repo_id, gguf_filename, base, hf_token)# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.te_files = self._te_prequant_plan_files(fam, text_encoder_quant, hf_token)sizes: dict[str, int] = {}@@ -1924,6 +1944,7 @@ class DiffusionBackend:return {"entries": entries,"total_bytes": int(sum(e["bytes"] for e in entries)),+ "incompatible_reason": incompatible,}@staticmethoddiff --git a/studio/backend/core/inference/diffusion_compat.py b/studio/backend/core/inference/diffusion_compat.pynew file mode 100644index 00000000000..2c55408dc27--- /dev/null+++ b/studio/backend/core/inference/diffusion_compat.py@@ -0,0 +1,385 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Metadata-only compatibility preflight for a diffusion pick.++A FLUX.2 GGUF only carries the transformer; its size (``inner_dim``) has to agree with the+companion diffusers base repo the loader assembles around it. ``assert_flux2_gguf_matches_base``+already catches a mismatch, but it opens the downloaded checkpoint, so it fires from inside+``load_pipeline`` -- after the prefetch pulled ~19 GB of base shards and after the resident+pipeline was torn down to make room. The user paid for both to be told the pick was never valid.++This module answers the same question from metadata alone: one HTTP range request for the first+few hundred KiB of the GGUF, which is where its tensor table lives. That is cheap enough to run+at SELECTION time (``/images/download-plan``) and again on the pre-eviction path, so the refusal+lands before a byte moves and before anything is unloaded.++Fail-open throughout, deliberately: an unreadable or truncated header, a base repo outside the+size table, an offline host, a server that ignores Range -- all yield "no opinion", and the load+proceeds exactly as it does today with the loader's own guard as the backstop. A false positive+here would refuse a pick that works, which is strictly worse than the download this saves.++(A known ungated MIRROR of a base is not an exception to that: it is byte-identical to what it+copies, ``canonical_base`` maps it back, and it is checked like its upstream.)+"""++from __future__ import annotations++import hashlib+import os+import threading+import time+from pathlib import Path+from typing import Any, Optional++from core.inference.diffusion_families import (+ flux2_base_inner_dim,+ flux2_mismatch_reason,+ gguf_flux2_inner_dim,+ gguf_flux2_inner_dim_from_header,+ resolve_local_gguf_child,+)++# The FLUX.2 tensor table sits in the first ~15 KiB (149 tensors for klein-4B, 201 for 9B). This+# is the ceiling on what the range request may buffer, not an expectation: a prefix that stops+# mid-table makes the parse raise, which reads as "no opinion".+_GGUF_HEADER_BYTES = 256 * 1024+# One short read. A pick is blocked on this in the UI, and a slow Hub must not stall the picker;+# a timeout is just another fail-open.+_HEADER_TIMEOUT_SECONDS = 15+# How long to wait for an interrupted read to notice before leaving it to the GC.+_ABANDON_GRACE_SECONDS = 0.5++# (repo_id, gguf_filename, token fingerprint, local file identity) -> inner_dim or None. Bounded+# and process-local. It memoises the MISS too -- the three checks on one pick would otherwise+# re-probe an unreachable Hub three times, and a sticky None is the degradation this module+# promises anyway. Which is exactly why the last two key parts exist: a sticky None must not+# outlive its cause.+#+# * the TOKEN, fingerprinted rather than stored. Keying on mere presence made every non-empty+# token one key, so a first probe with an expired credential poisoned the valid one that+# replaced it for the rest of the process.+# * the local file's IDENTITY (path, size, mtime). A checkpoint swapped in place keeps its path,+# so keying on the name alone answers the new file with the old file's dim -- refusing a valid+# 9B pairing, or handing sd.cpp the 4B text encoders. It also makes the file ARRIVING a new+# key, so a miss taken before a download finished re-probes off disk for free.+_INNER_DIM_CACHE: dict[tuple[str, str, str, Optional[tuple]], Optional[int]] = {}+_INNER_DIM_CACHE_MAX = 256+_CACHE_LOCK = threading.Lock()+++def _token_fingerprint(token: Optional[str]) -> str:+ """A stable, non-reversible tag for a token, or "" for none. Never the token itself: this+ lands in a process-global dict that a traceback or a heap dump would render."""+ if not token:+ return ""+ return hashlib.sha256(token.encode("utf-8", "replace")).hexdigest()[:16]+++def _file_identity(path: Optional[str]) -> Optional[tuple]:+ """(path, size, mtime_ns) for a local checkpoint, or None when the pick is remote.++ A file replaced under the same name is a different checkpoint, and stat is the cheapest thing+ that says so. An unreadable stat returns a unique object rather than a constant, so a file we+ cannot identify is never memoised as equal to anything else."""+ if path is None:+ return None+ try:+ stat = os.stat(path)+ except OSError:+ return (path, object())+ return (path, stat.st_size, stat.st_mtime_ns)+++def _local_gguf_path(repo_id: str, gguf_filename: str) -> Optional[str]:+ """The on-disk checkpoint for this pick, or None when it has to come off the Hub.++ Covers a local On Device directory and a Hub file already in either cache root: reading a file+ we hold beats a range request, and it is the same file ``_resolve_gguf_path`` will open."""+ try:+ local_root = Path(repo_id).expanduser()+ if local_root.exists():+ return str(resolve_local_gguf_child(local_root, gguf_filename))+ # OSError/RuntimeError: invalid path characters, or an unresolvable '~' -> a remote id.+ except (OSError, RuntimeError, ValueError):+ return None+ try:+ from huggingface_hub import try_to_load_from_cache+ from utils.hf_cache_settings import active_hf_hub_cache++ # The live root first, then huggingface_hub's import-time constant, the same pair the+ # loader resolves a staged file through. Read directly rather than through+ # ``diffusion.hub_cache_dir``: that module imports this one.+ for root in (active_hf_hub_cache(), None):+ hit = try_to_load_from_cache(repo_id, gguf_filename, cache_dir = root)+ if isinstance(hit, str) and Path(hit).is_file():+ return hit+ except Exception: # noqa: BLE001 — a cache we cannot read is not a verdict+ pass+ return None+++def _snapshot_revision(path: Optional[str]) -> Optional[str]:+ """The commit a cached Hub file was downloaded at, read off its ``snapshots/<sha>/`` parent.++ None for anything that is not an HF cache entry -- an On Device checkpoint is the file the+ loader opens, so there is no revision to be behind."""+ if not path:+ return None+ parts = Path(path).parts+ try:+ idx = len(parts) - 1 - parts[::-1].index("snapshots")+ except ValueError:+ return None+ return parts[idx + 1] if idx + 1 < len(parts) - 1 else None+++def _hub_revision(repo_id: str, gguf_filename: str, hf_token: Optional[str]) -> Optional[str]:+ """The commit the Hub currently serves this file at, or None when it cannot be asked.++ One HEAD, no body: the caller only needs to know whether the local copy is still the current+ one, and an offline or erroring host must leave today's verdict alone."""+ try:+ from huggingface_hub import get_hf_file_metadata, hf_hub_url+ meta = get_hf_file_metadata(+ hf_hub_url(repo_id, gguf_filename),+ token = hf_token,+ timeout = _HEADER_TIMEOUT_SECONDS,+ )+ except Exception: # noqa: BLE001 — a revision we cannot read is not a verdict+ return None+ return getattr(meta, "commit_hash", None) or None+++def _read_local_header(path: str) -> bytes:+ """The first ``_GGUF_HEADER_BYTES`` of a file on disk, or b"" when it cannot be read."""+ try:+ with open(path, "rb") as handle:+ return handle.read(_GGUF_HEADER_BYTES)+ # ValueError: open() rejects an embedded NUL rather than raising OSError.+ except (OSError, ValueError):+ return b""+++def _interrupt_read(response: Any) -> None:+ """Make a read parked on ``response`` return, so the whole-body deadline can be enforced.++ ``urllib3.HTTPResponse.shutdown`` half-closes the socket, which is the only thing that wakes a+ thread blocked inside ``iter_content``: ``Response.close`` drops the file object while the+ socket stays readable, so the read sits there regardless. Best effort -- and on a urllib3+ older than 2.3, which is where ``shutdown`` first appears, there is nothing here that can wake+ it. The caller does not depend on this working; it reads on a worker it can abandon.++ ``None`` means the worker has not got a response yet -- it is still inside connect or the+ header wait -- so there is nothing to half-close and abandoning it is the whole bound."""+ if response is None:+ return+ try:+ response.raw.shutdown()+ except Exception: # noqa: BLE001 — a deadline that cannot fire must not become a new failure+ try:+ response.close()+ except Exception: # noqa: BLE001+ pass+++def _read_gguf_header(repo_id: str, gguf_filename: str, hf_token: Optional[str]) -> bytes:+ """The first ``_GGUF_HEADER_BYTES`` of a Hub-hosted GGUF, or b"" when they cannot be read.++ One wall-clock bound over the WHOLE operation, request included. requests' timeout is an+ inactivity timeout: a peer (or an intermediary) that trickles response HEADERS resets it on+ every byte, so a deadline armed only once ``get()`` has returned leaves the caller blocked+ before the bounded body reader is ever reached -- and this runs on the /images/load route+ thread and on the download-plan path, both of which promised to fail open in seconds.++ So the request AND the drain run on a worker this call can walk away from. On timeout the+ response, if one exists by then, is half-closed to wake the worker; either way the caller+ returns with whatever arrived."""+ try:+ from huggingface_hub import hf_hub_url+ from huggingface_hub.utils import build_hf_headers, get_session+ except Exception: # noqa: BLE001 — an unexpected hub layout leaves today's behaviour+ return b""+ buffer = bytearray()+ # Published by the worker as soon as it has something interruptible; read by this thread on+ # timeout. A one-element list rather than a nonlocal, so the worker's assignment is visible.+ holder: list[Any] = [None]++ def _fetch() -> None:+ try:+ headers = dict(build_hf_headers(token = hf_token))+ headers["Range"] = f"bytes=0-{_GGUF_HEADER_BYTES - 1}"+ with get_session().get(+ hf_hub_url(repo_id, gguf_filename),+ headers = headers,+ timeout = _HEADER_TIMEOUT_SECONDS,+ stream = True,+ ) as response:+ holder[0] = response+ # 206 or nothing. A server (or a proxy) that ignored the Range header answers 200+ # with the WHOLE checkpoint, and streaming that into memory is the multi-GB+ # download this preflight exists to prevent.+ if response.status_code != 206:+ return+ deadline = time.monotonic() + _HEADER_TIMEOUT_SECONDS+ for chunk in response.iter_content(chunk_size = 65536):+ # extend, not `+=`: augmented assignment to a closed-over name would rebind+ # it as a local of _fetch and lose every byte.+ buffer.extend(chunk)+ if len(buffer) >= _GGUF_HEADER_BYTES or time.monotonic() > deadline:+ break+ # Keep what arrived rather than discarding it: the deadline firing on a merely SLOW link+ # still leaves the tensor table (the first ~15 KiB) in hand, and the parser is+ # truncation-safe -- swept over every prefix length of five header layouts, no cut ever+ # produces a wrong dim, so a short prefix is answered or ignored. TRUNCATION only: a+ # header with flipped bytes can still parse to a wrong dim (~0.6% under a 1-4 byte flip),+ # which the loader's own full-file backstop shares. TLS makes that unlikely on this path.+ except Exception: # noqa: BLE001 — offline, deadline fired, or the peer went away+ pass++ # The watchdog exists as well as the join because iter_content blocks inside urllib3 until a+ # whole 64 KiB chunk has arrived and every dribbled byte resets the socket timeout, so the+ # worker cannot notice its own deadline. Half-closing the socket is what makes that read+ # return -- on urllib3 >= 2.3, where HTTPResponse.shutdown exists. requirements/studio.txt+ # floors it, but an install predating that floor keeps whatever it resolved, so the bound+ # here cannot depend on the version underneath us: the worker is abandonable either way.+ watchdog = threading.Timer(_HEADER_TIMEOUT_SECONDS, lambda: _interrupt_read(holder[0]))+ watchdog.daemon = True+ watchdog.start()+ worker = threading.Thread(target = _fetch, name = "gguf-header-read", daemon = True)+ worker.start()+ worker.join(_HEADER_TIMEOUT_SECONDS)+ if worker.is_alive():+ _interrupt_read(holder[0])+ worker.join(_ABANDON_GRACE_SECONDS)+ watchdog.cancel()+ # bytes() snapshots under the GIL, so an abandoned worker still appending cannot tear the+ # copy; it can only lose a chunk that arrived too late to matter.+ return bytes(buffer[:_GGUF_HEADER_BYTES])+++def flux2_inner_dim_for_pick(+ repo_id: str,+ gguf_filename: Optional[str],+ hf_token: Optional[str] = None,+ *,+ allow_network: bool = True,+) -> Optional[int]:+ """``inner_dim`` of the GGUF this pick names, WITHOUT downloading it, or None.++ Reads the file when it is already on disk, otherwise range-reads its header off the Hub.+ Memoised per (repo, filename) so the plan, the pre-eviction preflight and the native asset+ resolver share one probe.++ ``allow_network = False`` answers from the memo or from disk and gives up rather than making+ the range request, for a caller that must not block: the range read is bounded but the bound+ is seconds, and a request thread that only wants a hint should not wear them. Nothing is+ memoised in that case, so the next caller that CAN wait still gets a real answer."""+ # A ".gguf" name only: a single_file load names a .safetensors, which has no GGUF header, and+ # spending a range request to learn that on every such load is pure waste.+ if not repo_id or not gguf_filename or not gguf_filename.lower().endswith(".gguf"):+ return None+ token = (hf_token or "").strip() or None+ # Resolved BEFORE the memo is consulted, because the file's identity is part of the key. Two+ # stats, against a probe that is otherwise an HTTP round trip.+ local = _local_gguf_path(repo_id, gguf_filename)+ key = (repo_id, gguf_filename, _token_fingerprint(token), _file_identity(local))+ # The memo FIRST, before the offline bail below. A plan-time probe has usually already+ # answered for this exact pick, and returning None here anyway made the caller that cannot+ # wait (begin_load, allow_network = False) fall back to the filename heuristic -- publishing+ # the 4B encoder repos for a renamed 9B checkpoint, so the delete-cached guard did not cover+ # its real companion repo until the worker re-probed.+ with _CACHE_LOCK:+ if key in _INNER_DIM_CACHE:+ return _INNER_DIM_CACHE[key]+ if local is None and not allow_network:+ return None+ if local is not None:+ # Same prefix parse as the remote path, so both read the file the same way: the loader's+ # backstop memory-maps the whole multi-GB checkpoint and builds a view over every tensor,+ # which is a lot of work for a table in the first 15 KiB. Fall back to it only if the+ # prefix said nothing, so a header past the cap is still answered.+ inner_dim = gguf_flux2_inner_dim_from_header(_read_local_header(local))+ if inner_dim is None:+ inner_dim = gguf_flux2_inner_dim(local)+ else:+ inner_dim = gguf_flux2_inner_dim_from_header(+ _read_gguf_header(repo_id, gguf_filename, token)+ )+ with _CACHE_LOCK:+ # Plain FIFO-ish eviction: this only bounds a session's worth of picks, and a re-probe+ # after an eviction costs one range request.+ if len(_INNER_DIM_CACHE) >= _INNER_DIM_CACHE_MAX:+ _INNER_DIM_CACHE.clear()+ _INNER_DIM_CACHE[key] = inner_dim+ return inner_dim+++def _revalidated_inner_dim(+ repo_id: str, gguf_filename: str, hf_token: Optional[str], got: int+) -> Optional[int]:+ """``got`` again, re-read off the Hub when it came from a cached copy the Hub has moved past.++ ``try_to_load_from_cache`` resolves the LOCAL ``refs/main``, so a checkpoint republished at the+ same filename would otherwise refuse a pick that the loader's own ``hf_hub_download`` refreshes+ and loads. Runs only on a would-be refusal; an unknown revision keeps ``got``, and a live+ header we cannot read is no opinion."""+ cached = _snapshot_revision(_local_gguf_path(repo_id, gguf_filename))+ if cached is None:+ return got+ token = (hf_token or "").strip() or None+ live = _hub_revision(repo_id, gguf_filename, token)+ if live is None or live == cached:+ return got+ return gguf_flux2_inner_dim_from_header(_read_gguf_header(repo_id, gguf_filename, token))+++def flux2_pick_mismatch(+ fam: Any,+ repo_id: str,+ gguf_filename: Optional[str],+ base_repo: Optional[str],+ hf_token: Optional[str] = None,+) -> Optional[str]:+ """Why this GGUF cannot load against this base, or None when nothing is known to be wrong.++ ``base_repo`` must be the RESOLVED upstream id (``_resolve_base_repo``), the same one the+ loader's own guard is handed, so all the checks on this pairing agree."""+ if not gguf_filename or not str(getattr(fam, "name", "")).startswith("flux.2"):+ return None+ want = flux2_base_inner_dim(base_repo)+ # Cheapest order: a base outside the size table (a local path, a repo we do not ship) leaves+ # nothing to compare against, so it must not cost a round trip either.+ if want is None:+ return None+ got = flux2_inner_dim_for_pick(repo_id, gguf_filename, hf_token)+ if got is not None and got != want:+ got = _revalidated_inner_dim(repo_id, gguf_filename, hf_token, got)+ return flux2_mismatch_reason(+ Path(str(gguf_filename)).name,+ str(base_repo),+ got,+ want,+ )+++def assert_flux2_pick_compatible(+ fam: Any,+ repo_id: str,+ gguf_filename: Optional[str],+ base_repo: Optional[str],+ hf_token: Optional[str] = None,+) -> None:+ """Refuse an incompatible FLUX.2 pick before anything is downloaded or unloaded.++ ``ValueError``, like every other unloadable-pick refusal: /images/load maps it to 400 and+ ``/images/download-plan`` catches it, whereas a RuntimeError escapes the plan as a bare 500."""+ reason = flux2_pick_mismatch(fam, repo_id, gguf_filename, base_repo, hf_token)+ if reason is not None:+ raise ValueError(reason)+++def _reset_inner_dim_cache() -> None:+ """Drop the memoised header probes. Tests only."""+ with _CACHE_LOCK:+ _INNER_DIM_CACHE.clear()diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex d97479e809f..a6afe37e809 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -16,9 +16,10 @@ from __future__ import annotationsimport osimport re+import tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPath-from typing import Optional, Sequence+from typing import NamedTuple, Optional, Sequence# Runtime->route contract: the /images/generate route matches these messages EXACTLY for a 409 (vs a 500), so both engines raise them verbatim.@@ -895,12 +896,25 @@ def sd_cpp_text_encoders_for(fam: DiffusionFamily,repo_id: Optional[str] = None,gguf_filename: Optional[str] = None,+ inner_dim: Optional[int] = None,) -> tuple[tuple[str, str, str], ...]:"""The sd.cpp text encoders for a specific load.- FLUX.2-klein picks by variant (9B needs Qwen3-8B, 4B the family default) keyed on the load- identity (repo id + GGUF filename); every other family returns its static table."""+ FLUX.2-klein picks by variant (9B needs Qwen3-8B, 4B the family default); every other family+ returns its static table.++ ``inner_dim`` is the checkpoint's own answer, read from the GGUF header+ (``gguf_flux2_inner_dim``): it decides whenever the caller has it, because a renamed or+ hand-picked file makes the load identity say nothing. The repo id + filename string match is+ the fallback for the callers that have no header to read (the delete guard reconstructs a+ committed load; the plan runs before a byte is fetched)."""if fam.name == "flux.2-klein":+ # A dim this family does not have (a FLUX.2-dev file, a misread) falls through to the+ # strings rather than guessing, exactly as the base-size guard fails open on one.+ if inner_dim == _FLUX2_KLEIN_9B_INNER_DIM:+ return _FLUX2_KLEIN_9B_SD_CPP_TEXT_ENCODERS+ if inner_dim == _FLUX2_KLEIN_4B_INNER_DIM:+ return fam.sd_cpp_text_encodersidentity = f"{repo_id or ''}/{gguf_filename or ''}".lower()# Match the size token on its own: klein-BASE-9B is 9B too, and matching "klein-9b"# literally handed it the 4B text encoder.@@ -919,6 +933,8 @@ _FLUX2_INNER_DIMS = {4096: "FLUX.2-klein-9B / klein-base-9B",6144: "FLUX.2-dev",}+_FLUX2_KLEIN_4B_INNER_DIM = 3072+_FLUX2_KLEIN_9B_INNER_DIM = 4096_FLUX2_BASE_INNER_DIM = {"black-forest-labs/flux.2-klein-4b": 3072,"black-forest-labs/flux.2-klein-base-4b": 3072,@@ -928,17 +944,131 @@ _FLUX2_BASE_INNER_DIM = {}+class _HeaderTensor(NamedTuple):+ """The two fields a FLUX.2 size probe reads off a GGUF tensor table entry."""++ name: str+ shape: Sequence[int]+++def flux2_base_inner_dim(base_repo: Optional[str]) -> Optional[int]:+ """The ``inner_dim`` a FLUX.2 base config expects, or None when the repo is not one we map.++ Keyed on UPSTREAM ids, reached through ``canonical_base``: a known ungated mirror is+ byte-identical to what it copies, so it maps back and is checked exactly like its upstream.+ Anything else -- a local path, a third-party repack, a base we do not ship -- misses, and+ every caller fails OPEN on the None rather than guessing."""+ return _FLUX2_BASE_INNER_DIM.get(canonical_base(base_repo or "").lower())+++def _flux2_inner_dim_from_tensors(tensors) -> Optional[int]:+ """``inner_dim`` from a parsed GGUF tensor table, or None when the probe tensor is absent."""+ for t in tensors:+ if t.name == _FLUX2_PROBE_TENSOR or t.name.endswith("." + _FLUX2_PROBE_TENSOR):+ # GGUF stores dims reversed relative to torch, so the input dim leads. A missing or+ # non-positive dim is a parse that went wrong, and "0" would be compared against the+ # base as a real answer and refuse a valid pick; say nothing instead.+ dim = int(t.shape[0]) if len(t.shape) else 0+ return dim if dim > 0 else None+ return None++def gguf_flux2_inner_dim(path) -> Optional[int]:"""``inner_dim`` of a FLUX.2 GGUF, read from its header, or None if it cannot be determined."""try:from gguf import GGUFReader- for t in GGUFReader(str(path)).tensors:- if t.name == _FLUX2_PROBE_TENSOR or t.name.endswith("." + _FLUX2_PROBE_TENSOR):- # GGUF stores dims reversed relative to torch, so the input dim leads.- return int(t.shape[0])+ return _flux2_inner_dim_from_tensors(GGUFReader(str(path)).tensors)except Exception:return None- return None+++def gguf_flux2_inner_dim_from_header(header: bytes) -> Optional[int]:+ """``inner_dim`` read from the leading bytes of a FLUX.2 GGUF, or None.++ Lets the selection-time preflight range-read a few hundred KiB over HTTP instead of pulling+ the whole multi-GB checkpoint: the tensor table it needs sits in the first ~15 KiB. Same+ parser as ``gguf_flux2_inner_dim``, with the two things a PREFIX changes:++ * ``_build_tensors`` is skipped. The base class builds a numpy view over every tensor's DATA,+ which a prefix does not carry -- and satisfying those reads would allocate the whole+ declared checkpoint (tens of GiB), which is exactly the cost this avoids. Only the name and+ shape from the table are wanted, and both are already parsed.+ * ``_get`` REFUSES a read past the end instead of returning short or zero-filled data. The+ table is read field by field, so a prefix cutting between a tensor's name and its dims+ would otherwise hand back a zero shape -- a wrong answer, not a missing one, and one that+ would refuse a perfectly valid pick.++ None on anything unreadable: too short a prefix, a non-GGUF file, an absent probe tensor."""+ if not header:+ return None+ tmp_path = None+ reader = None+ try:+ import numpy as np+ from gguf import GGUFReader++ class _HeaderOnlyGGUFReader(GGUFReader): # type: ignore[misc, valid-type]+ """``GGUFReader`` over a file that holds only the header."""++ def _get(+ self,+ offset,+ dtype,+ count = 1,+ override_order = None,+ ):+ itemsize = int(np.empty([], dtype = dtype).itemsize)+ if int(offset) < 0 or int(offset) + itemsize * int(count) > len(self.data):+ raise ValueError("GGUF header is truncated")+ return super()._get(offset, dtype, count, override_order)++ def _build_tensors(self, start_offs, fields):+ # ``field.name`` is the decoded tensor name and parts[3] its dims, both already+ # read from real bytes by ``_get_tensor_info_field``.+ self.tensors = [_HeaderTensor(field.name, field.parts[3]) for field in fields]++ # GGUFReader memory-maps a path, so the prefix has to land on disk. Bounded by the+ # caller's range request, so this is KiB, never the checkpoint.+ fd, tmp_path = tempfile.mkstemp(suffix = ".gguf-header")+ with os.fdopen(fd, "wb") as fh:+ fh.write(header)+ reader = _HeaderOnlyGGUFReader(tmp_path)+ # Belt and braces on top of the refusing ``_get``: ``data_offset`` is where the table+ # ends, so a table that ran past the prefix is not one to read a shape out of. The+ # alignment slack is for a header-only file, whose padding was never written.+ if reader.data_offset > len(header) + min(int(reader.alignment), 4096):+ return None+ return _flux2_inner_dim_from_tensors(reader.tensors)+ except Exception: # noqa: BLE001 — an unreadable header is not a verdict+ return None+ finally:+ # Drop the mmap before unlinking: Windows refuses to delete a mapped file.+ del reader+ if tmp_path:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+++def flux2_mismatch_reason(+ gguf_name: str, base_repo: str, got: Optional[int], want: Optional[int]+) -> Optional[str]:+ """Why this FLUX.2 GGUF cannot load against this base, or None when they agree.++ One message for all three checks on the pairing (the plan, the pre-eviction preflight and the+ loader's backstop), so the user reads the same sentence wherever it is caught. ``gguf_name`` is+ a display name the caller has already reduced to a basename. Returns None on any unknown -- an+ unreadable header, an unmapped base -- so every caller fails open."""+ if want is None or got is None or want == got:+ return None+ return (+ f"'{gguf_name}' is a "+ f"{_FLUX2_INNER_DIMS.get(got, f'FLUX.2 variant with inner_dim {got}')} "+ f"checkpoint, but it is being loaded against '{base_repo}', which is "+ f"{_FLUX2_INNER_DIMS.get(want, f'inner_dim {want}')}. Pass base_repo for the matching "+ f"variant, or pick the GGUF that matches the selected model."+ )def assert_flux2_gguf_matches_base(fam, base_repo: str, gguf_path) -> None:@@ -947,20 +1077,23 @@ def assert_flux2_gguf_matches_base(fam, base_repo: str, gguf_path) -> None:Without this the mismatch surfaces from inside the GGUF quantizer as a bare shape error("expected torch.Size([18432, 3072]), decodes to (24576, 4096)") that names neither the filenor the repo. Fail-open by construction: any unreadable file, non-FLUX.2 tensor set, or- unmapped base leaves the load exactly as it was."""+ unmapped base leaves the load exactly as it was.++ The LAST of three checks on the same pairing, and the only one that opens the downloaded file:+ ``diffusion_compat`` runs the same comparison off a range-read header at plan time and again+ before the resident pipeline is torn down, so a mismatch normally never reaches here."""if gguf_path is None or not str(getattr(fam, "name", "")).startswith("flux.2"):return- # Keyed on upstream ids, and this guard fails OPEN on a miss, so a mirror id would disable it.- want = _FLUX2_BASE_INNER_DIM.get(canonical_base(base_repo).lower())- got = gguf_flux2_inner_dim(gguf_path)- if want is None or got is None or want == got:+ # Short-circuit on the free half: an unmapped base fails open anyway, so a mirror id must not+ # cost a memory-map of the whole checkpoint.+ want = flux2_base_inner_dim(base_repo)+ if want is None:return- raise ValueError(- f"'{Path(str(gguf_path)).name}' is a {_FLUX2_INNER_DIMS.get(got, f'FLUX.2 variant with inner_dim {got}')} "- f"checkpoint, but it is being loaded against '{base_repo}', which is "- f"{_FLUX2_INNER_DIMS.get(want, f'inner_dim {want}')}. Pass base_repo for the matching "- f"variant, or pick the GGUF that matches the selected model."+ reason = flux2_mismatch_reason(+ Path(str(gguf_path)).name, base_repo, gguf_flux2_inner_dim(gguf_path), want)+ if reason is not None:+ raise ValueError(reason)def resolve_local_gguf_child(repo_root: Path, gguf_filename: str) -> Path:diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 5613844ee8b..a04d0a555eb 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -33,6 +33,7 @@ from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Any, Optional+from core.inference.diffusion_compat import flux2_inner_dim_for_pickfrom core.inference.diffusion_device import resolve_diffusion_device_targetfrom core.inference.diffusion_families import (DIFFUSION_CANCELLED_MSG,@@ -258,6 +259,9 @@ class _SdState:hf_token: Optional[str] = None# The GGUF basename this load committed: some variants pick their encoder by filename, and a local *klein-9B*.gguf carries that keyword only in the basename.gguf_filename: Optional[str] = None+ # The FLUX.2 inner_dim this load read out of the checkpoint's own header, when it could. Kept+ # so the delete guard reconstructs the SAME encoder pick without re-probing under the lock.+ flux2_inner_dim: Optional[int] = Nonedef _memory_policy(memory_mode: Optional[str], cpu_offload: bool) -> str:@@ -472,6 +476,15 @@ class SdCppDiffusionBackend:raise ValueError(f"Family '{fam.name}' has no native sd.cpp asset mapping.")base = resolve_base_repo(fam, base_repo)+ # Offline-only here, and deliberately so. begin_load returns at once by contract -- the+ # route thread answers the UI with a status and the pull happens on the worker -- so it+ # cannot afford the range request's bound, let alone hold _lock across it and stall+ # status()/unload() for the same span. Memo or on-disk header or nothing. This value only+ # seeds the delete-cached guard's repo list below; the worker re-asks WITH the network and+ # refreshes that list, so the guard converges within one round trip of the load starting.+ inner_dim = self._flux2_inner_dim(+ repo_id, gguf_filename, fam, hf_token, allow_network = False+ )with self._lock:if self._loading is not None and self._loading.error is None:raise RuntimeError("A diffusion load is already in progress.")@@ -490,7 +503,7 @@ class SdCppDiffusionBackend:asset_repos = tuple(dict.fromkeys(r- for r, _f, kind in self._asset_specs(repo_id, gguf_filename, fam)+ for r, _f, kind in self._asset_specs(repo_id, gguf_filename, fam, inner_dim)if kind != "diffusion_model")),@@ -557,9 +570,18 @@ class SdCppDiffusionBackend:# Swap ONCE so the size probe and the download agree: sizes come from paths-info, which# -- unlike model_info -- 401s anonymously on a gated repo, so probing the upstream# drops the VAE from the progress total the mirror then pulls.- specs = self._asset_specs(repo_id, gguf_filename, fam)+ inner_dim = self._flux2_inner_dim(repo_id, gguf_filename, fam, hf_token)+ specs = self._asset_specs(repo_id, gguf_filename, fam, inner_dim)fetch_repo = _fetch_repo_map(specs, hf_token)assets = [(fetch_repo[repo], fn, kind) for repo, fn, kind in specs]+ # begin_load could only guess the encoder repos (it may not have had the header yet);+ # now they are known, so publish them before a single byte is fetched. Otherwise+ # delete-cached would happily remove a companion this load is about to write into.+ with self._lock:+ if self._load_token == _load_token and self._loading is not None:+ self._loading.asset_repos = tuple(+ dict.fromkeys(r for r, _f, kind in specs if kind != "diffusion_model")+ )# Same preflight the plan runs, on POST-swap repos: catch a gated companion here, not# 15 GiB into the prefetch, without refusing one an ungated mirror stands in for. The# plan alone is not enough: the images page falls back to this load when it fails.@@ -659,6 +681,7 @@ class SdCppDiffusionBackend:mode = mode,hf_token = hf_token,gguf_filename = gguf_filename,+ flux2_inner_dim = inner_dim,)with self._lock:if self._load_token != _load_token:@@ -713,7 +736,12 @@ class SdCppDiffusionBackend:# Unreachable through the route, but a direct caller gets the same message begin_load would raise.raise ValueError(f"'{repo_id}' has no native sd.cpp asset mapping.")- specs = self._asset_specs(repo_id, gguf_filename, fam)+ specs = self._asset_specs(+ repo_id,+ gguf_filename,+ fam,+ self._flux2_inner_dim(repo_id, gguf_filename, fam, hf_token),+ )by_repo = self._assets_by_repo(specs)# STAGED before the load runs, so each entry must name the repo _fetch_assets will pull@@ -798,7 +826,12 @@ class SdCppDiffusionBackend:if fam is None or not gguf_filename:return# Post-swap, as the plan and the load are: the swap is pure, so all three decide alike.- specs = self._asset_specs(repo_id, gguf_filename, fam)+ specs = self._asset_specs(+ repo_id,+ gguf_filename,+ fam,+ self._flux2_inner_dim(repo_id, gguf_filename, fam, hf_token),+ )fetch_repo = _fetch_repo_map(specs, hf_token)self._preflight_companion_repos(self._assets_by_repo([(fetch_repo[r], fn, kind) for r, fn, kind in specs]),@@ -828,16 +861,41 @@ class SdCppDiffusionBackend:continuereturn out+ @staticmethod+ def _flux2_inner_dim(+ repo_id: str,+ gguf_filename: str,+ fam: DiffusionFamily,+ hf_token: Optional[str],+ *,+ allow_network: bool = True,+ ) -> Optional[int]:+ """The checkpoint's own FLUX.2 size, or None. Header-only and memoised, so the four+ ``_asset_specs`` callers share one probe; skipped outright for every other family, which+ has a single static encoder table and must stay network-free."""+ if fam.name != "flux.2-klein":+ return None+ return flux2_inner_dim_for_pick(+ repo_id, gguf_filename, hf_token, allow_network = allow_network+ )+def _asset_specs(- self, repo_id: str, gguf_filename: str, fam: DiffusionFamily+ self,+ repo_id: str,+ gguf_filename: str,+ fam: DiffusionFamily,+ inner_dim: Optional[int] = None,) -> list[tuple[str, str, str]]:"""(repo, filename, kind) for every file sd-cli needs. ``kind`` is theSdCppModelFiles field; the transformer reuses the diffusers GGUF."""specs: list[tuple[str, str, str]] = [(repo_id, gguf_filename, "diffusion_model")]if fam.sd_cpp_vae:specs.append((fam.sd_cpp_vae[0], fam.sd_cpp_vae[1], "vae"))- # Pick the encoder per variant from the load identity so a 9B GGUF fetches the right one.- for terepo, tefile, kind in sd_cpp_text_encoders_for(fam, repo_id, gguf_filename):+ # Pick the encoder per variant so a 9B GGUF fetches the right one: from the header when the+ # caller read it, else from the load identity, which a renamed file makes silent.+ for terepo, tefile, kind in sd_cpp_text_encoders_for(+ fam, repo_id, gguf_filename, inner_dim = inner_dim+ ):specs.append((terepo, tefile, kind))return specs@@ -949,11 +1007,16 @@ class SdCppDiffusionBackend:repos = [state.repo_id, state.base_repo]if fam.sd_cpp_vae:repos.append(fam.sd_cpp_vae[0])- # Same per-variant selection as _asset_specs (keyed on repo id AND GGUF filename) so the delete guard protects the encoder repo this load downloaded.+ # Same per-variant selection as _asset_specs (the header dim this load committed, else+ # repo id AND GGUF filename) so the delete guard protects the encoder repo this load+ # actually downloaded. Read off the state, never re-probed: this runs under _lock.repos.extend(terepofor terepo, _f, _k in sd_cpp_text_encoders_for(- fam, state.repo_id, state.gguf_filename+ fam,+ state.repo_id,+ state.gguf_filename,+ inner_dim = state.flux2_inner_dim,))return _with_mirrors(repos)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 8cac50c07fa..75b4b278f79 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2955,6 +2955,15 @@ class DiffusionDownloadPlanResponse(BaseModel):entries: List[DiffusionDownloadPlanEntry] = Field(default_factory = list)total_bytes: int = Field(0, description = "Sum across entries, 0 when the estimate failed")+ incompatible_reason: Optional[str] = Field(+ None,+ description = "Why this pick cannot load as selected (today: a FLUX.2 GGUF paired with a "+ "different-size base), so the picker can refuse at selection time instead of after a "+ "multi-GB download. Reported rather than raised: the images page falls back to "+ "/images/load on any plan failure, which would start that very download. Null means "+ "nothing is known to be wrong -- the check reads metadata only and stays silent on an "+ "unreadable header, an unmapped base or an offline host.",+ )class DiffusionStatusResponse(BaseModel):diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txtindex 4633c125aa9..df04306b53b 100644--- a/studio/backend/requirements/studio.txt+++ b/studio/backend/requirements/studio.txt@@ -12,6 +12,12 @@ pyjwt# gradio>=4.0.0 # 148 MB - Unsloth uses React + FastAPI, not Gradiohuggingface-hub==0.36.2# truststore is vendored at backend/vendor/, deliberately not a dependency.+# Transitive via requests, pinned here for one reason: the GGUF header range-read+# preflight bounds itself by half-closing the socket, and HTTPResponse.shutdown is+# the only thing that wakes a read parked inside iter_content. It landed in 2.3.0;+# below that the read is uninterruptible. The preflight abandons the reader either+# way, so this is defence in depth, not the bound itself.+urllib3>=2.3.0structlog>=24.1.0dicewareddgsdiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex f2b8eeb6f71..52c1cf05614 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -6138,7 +6138,9 @@ def test_download_plan_drops_a_repo_the_fallback_root_holds_whole(monkeypatch, t"unsloth/FLUX.1-dev-GGUF", gguf_filename = "flux1-dev-Q4_K_M.gguf")- assert plan == {"entries": [], "total_bytes": 0}+ # incompatible_reason rides in the same envelope: the plan is where a FLUX.2 GGUF/base+ # mismatch is reported, and None is "nothing known to be wrong".+ assert plan == {"entries": [], "total_bytes": 0, "incompatible_reason": None}def test_files_already_cached_survives_an_unreadable_root(monkeypatch, tmp_path):diff --git a/studio/backend/tests/test_diffusion_compat_preflight.py b/studio/backend/tests/test_diffusion_compat_preflight.pynew file mode 100644index 00000000000..4363b247522--- /dev/null+++ b/studio/backend/tests/test_diffusion_compat_preflight.py@@ -0,0 +1,1003 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hermetic tests for the FLUX.2 size-pairing preflight.++A FLUX.2 GGUF only carries the transformer, so its ``inner_dim`` has to match the companion base+repo the loader assembles around it. The loader's own guard opens the DOWNLOADED checkpoint, so it+fires after the base shards were pulled and after the resident pipeline was torn down; these tests+pin the cheap version that runs first, off a range-read header.++Every synthetic checkpoint here is a real GGUF header written by ``gguf.GGUFWriter`` -- the tensor+table and nothing else, which is exactly what the range request brings back. The HTTP layer is+stubbed at ``huggingface_hub.utils.get_session``, so nothing in this module touches the network,+and a stubbed ``hf_hub_download`` fails the test if anything tries to fetch a whole file.+"""++from __future__ import annotations++import threading+import time+import types++import pytest++from core.inference import diffusion_compat+from core.inference.diffusion import DiffusionBackend, _LoadingState+from core.inference.diffusion_families import (+ detect_family,+ gguf_flux2_inner_dim_from_header,+ sd_cpp_text_encoders_for,+)++KLEIN_4B_BASE = "black-forest-labs/FLUX.2-klein-4B"+KLEIN_9B_BASE = "black-forest-labs/FLUX.2-klein-9B"+KLEIN_4B_GGUF = "unsloth/FLUX.2-klein-4B-GGUF"+KLEIN_4B_FILE = "flux-2-klein-4b-Q4_K_M.gguf"++FLUX2_FAMILY = types.SimpleNamespace(name = "flux.2-klein", single_file_is_pipeline = False)+++def _gguf_header(+ inner_dim: int,+ tmp_path,+ *,+ name = "double_stream_modulation_img.lin.weight",+ siblings = 4,+ probe_last = False,+):+ """A real GGUF header (magic + kv + tensor table, no tensor DATA) for a FLUX.2 of this size.++ Written with the shipped writer rather than hand-rolled bytes, so a format change breaks the+ test the same way it would break production. ``write_tensor_data`` is deliberately never+ called: the bytes that come back are precisely the prefix a range request returns."""+ import numpy as np+ from gguf import GGMLQuantizationType, GGUFWriter++ path = tmp_path / f"header-{inner_dim}-{siblings}-{int(probe_last)}.gguf"+ writer = GGUFWriter(str(path), "flux")++ def _probe():+ # FLUX.2 sizes this projection as (6 * inner_dim, inner_dim); GGUF stores dims reversed.+ writer.add_tensor_info(+ name,+ [6 * inner_dim, inner_dim],+ np.dtype(np.float16),+ 6 * inner_dim * inner_dim * 2,+ raw_dtype = GGMLQuantizationType.F16,+ )++ if not probe_last:+ _probe()+ # Siblings so the probe tensor is not the whole table, as in a real checkpoint.+ for i in range(siblings):+ writer.add_tensor_info(+ f"blk.{i}.weight",+ [64, 64],+ np.dtype(np.float16),+ 64 * 64 * 2,+ raw_dtype = GGMLQuantizationType.F16,+ )+ if probe_last:+ _probe()+ writer.write_header_to_file()+ writer.write_kv_data_to_file()+ writer.write_ti_data_to_file()+ writer.close()+ return path.read_bytes()+++class _FakeResponse:+ """The slice of ``requests.Response`` the header read uses."""++ def __init__(+ self,+ status_code,+ body = b"",+ ):+ self.status_code = status_code+ self._body = body++ def iter_content(self, chunk_size = 1):+ for i in range(0, len(self._body), chunk_size):+ yield self._body[i : i + chunk_size]++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False+++def _stub_range_reads(+ monkeypatch,+ bodies,+ *,+ status = 206,+):+ """Serve ``{filename: header_bytes}`` over the stubbed Hub session; returns the request log.++ Also arms the negative assertions this whole module rests on: nothing may call+ ``hf_hub_download`` (that is the multi-GB pull), and nothing may read the ambient cache."""+ requests: list[tuple[str, str]] = []++ class _Session:+ def get(+ self,+ url,+ headers = None,+ timeout = None,+ stream = False,+ ):+ requests.append((url, (headers or {}).get("Range", "")))+ body = next((b for name, b in bodies.items() if url.endswith(name)), None)+ if body is None:+ return _FakeResponse(404)+ return _FakeResponse(status, body)++ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: _Session())+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)+ monkeypatch.setattr(+ "huggingface_hub.hf_hub_download",+ lambda *a, **k: pytest.fail("the compatibility preflight must not download the file"),+ )+ diffusion_compat._reset_inner_dim_cache()+ return requests++[email protected](autouse = True)+def _clean_probe_cache():+ # The memo is process-global by design; a leak between tests would hide a missing probe.+ diffusion_compat._reset_inner_dim_cache()+ yield+ diffusion_compat._reset_inner_dim_cache()+++# ── the header parser ──────────────────────────────────────────────────────────++[email protected]("inner_dim", [3072, 4096, 6144])+def test_the_inner_dim_is_read_from_a_header_with_no_tensor_data(inner_dim, tmp_path):+ # The whole premise: ~400 bytes of tensor table answer a question the 19 GB body would.+ assert gguf_flux2_inner_dim_from_header(_gguf_header(inner_dim, tmp_path)) == inner_dim+++def test_a_plain_reader_cannot_read_the_same_prefix(tmp_path):+ # Why the header-only reader exists at all: GGUFReader also builds numpy views over every+ # tensor's DATA, so on a prefix it raises -- feed it one and the guard silently never fires.+ from gguf import GGUFReader+ from core.inference.diffusion_families import gguf_flux2_inner_dim++ prefix = tmp_path / "prefix-only.gguf"+ prefix.write_bytes(_gguf_header(3072, tmp_path))++ with pytest.raises(Exception):+ GGUFReader(str(prefix))+ assert gguf_flux2_inner_dim(prefix) is None+ assert gguf_flux2_inner_dim_from_header(prefix.read_bytes()) == 3072+++ "header",+ [b"", b"not a gguf at all", b"GGUF" + b"\x00" * 64],+ ids = ["empty", "garbage", "truncated"],+)+def test_an_unreadable_header_yields_no_opinion(header):+ assert gguf_flux2_inner_dim_from_header(header) is None+++def test_a_header_without_the_probe_tensor_yields_no_opinion(tmp_path):+ # A non-FLUX.2 checkpoint parses fine and simply has nothing to say.+ header = _gguf_header(3072, tmp_path, name = "blk.0.attn.weight")+ assert gguf_flux2_inner_dim_from_header(header) is None++[email protected]("probe_last", [False, True], ids = ["probe-first", "probe-last"])+def test_no_truncation_of_a_valid_header_can_invent_a_dim(probe_last, tmp_path):+ # The sharp edge. The table is read field by field, so a cut BETWEEN a tensor's name and its+ # dims used to leave the name matching and the shape zero-filled -- "inner_dim 0", which is a+ # wrong answer rather than a missing one, and refuses a perfectly valid pick. A 206 body a few+ # bytes short, or a partially written On Device file, lands exactly there. Every prefix of a+ # real header must read as the real dim or as nothing at all.+ header = _gguf_header(4096, tmp_path, probe_last = probe_last)+ assert gguf_flux2_inner_dim_from_header(header) == 4096++ verdicts = {gguf_flux2_inner_dim_from_header(header[:cut]) for cut in range(1, len(header))}+ assert verdicts <= {None, 4096}, f"a truncated header invented {verdicts - {None, 4096}}"+++def test_a_header_declaring_a_huge_checkpoint_is_cheap(tmp_path):+ # The base reader also builds a numpy view over every tensor's DATA. Satisfying those from a+ # prefix would allocate the whole DECLARED size -- tens of GiB, which commits pagefile on+ # Windows and turns the preflight into a permanent no-op there. 1200 tensors declaring ~37 GiB.+ import time++ header = _gguf_header(4096, tmp_path, siblings = 1200)+ started = time.monotonic()+ assert gguf_flux2_inner_dim_from_header(header) == 4096+ assert time.monotonic() - started < 5.0+++# ── the preflight verdict ──────────────────────────────────────────────────────+++def test_a_mismatched_pair_is_refused_from_the_header_alone(monkeypatch, tmp_path):+ # P1-5: a 4B GGUF against the 9B base. Refused off one range request, with no base metadata+ # call and no download at all -- the 19.17 GB pull never starts.+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})++ with pytest.raises(ValueError) as excinfo:+ diffusion_compat.assert_flux2_pick_compatible(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ detail = str(excinfo.value)+ assert KLEIN_4B_FILE in detail and KLEIN_9B_BASE in detail+ assert "klein-4B" in detail and "klein-9B" in detail+ assert len(requests) == 1+ url, byte_range = requests[0]+ assert url.endswith(f"{KLEIN_4B_GGUF}/resolve/main/{KLEIN_4B_FILE}")+ # Bounded: the request must name an end offset, or a mis-set header streams the checkpoint.+ assert byte_range == f"bytes=0-{diffusion_compat._GGUF_HEADER_BYTES - 1}"+++def test_a_matching_pair_passes(monkeypatch, tmp_path):+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_4B_BASE+ )+ is None+ )+++def test_an_unreadable_header_fails_open(monkeypatch):+ # The contract: a false positive is worse than the bug it prevents, so a header we cannot+ # parse leaves the load exactly as it was, with the loader's own guard as the backstop.+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: b"not a gguf"})++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )+ is None+ )+++def test_an_offline_host_fails_open(monkeypatch):+ def _boom(*_a, **_k):+ raise OSError("no route to host")++ monkeypatch.setattr(+ "huggingface_hub.utils.get_session", lambda: types.SimpleNamespace(get = _boom)+ )+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )+ is None+ )+++def test_a_trickling_server_cannot_hold_the_picker_open(monkeypatch):+ # A pick is blocked on this read in the UI, and the pre-eviction preflight runs it on the+ # route's thread, so an unbounded read is a load request that never answers.+ #+ # Testing the deadline BETWEEN chunks is not enough, which is what this pins. iter_content+ # blocks inside urllib3 until a whole 64 KiB chunk has arrived, and requests' timeout is per+ # socket read, so a server dribbling a byte at a time resets it forever: measured against a+ # real loopback socket, one chunk at a byte a second is 18 hours and the loop never comes+ # back to look at the clock. Half-closing the socket is what ends it -- response.close() does+ # not, it drops the file object and leaves the socket readable -- and requests surfaces that+ # as a broken-connection error, which reads as "no opinion" like any other transport failure.+ interrupted = threading.Event()++ class _Trickle:+ status_code = 206++ def __init__(self):+ self.raw = types.SimpleNamespace(shutdown = interrupted.set)++ def iter_content(self, chunk_size = 1):+ if not interrupted.wait(10):+ raise AssertionError("the header read was never interrupted")+ raise OSError("Connection broken: IncompleteRead(12 bytes read)")++ def close(self):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False++ monkeypatch.setattr(diffusion_compat, "_HEADER_TIMEOUT_SECONDS", 0.5)+ monkeypatch.setattr(+ "huggingface_hub.utils.get_session",+ lambda: types.SimpleNamespace(get = lambda *a, **k: _Trickle()),+ )+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ out: list[bytes] = []+ reader = threading.Thread(+ target = lambda: out.append(+ diffusion_compat._read_gguf_header(KLEIN_4B_GGUF, KLEIN_4B_FILE, None)+ ),+ daemon = True,+ )+ reader.start()+ reader.join(8)++ assert not reader.is_alive(), "the header read outlived its own deadline"+ assert out == [b""]+++def test_an_old_urllib3_with_no_shutdown_still_cannot_hold_the_picker_open(monkeypatch):+ # HTTPResponse.shutdown landed in urllib3 2.3.0. requirements/studio.txt floors it there, but+ # an install that resolved its environment BEFORE that floor keeps whatever it already has,+ # and nothing re-resolves a transitive pin on upgrade. On that urllib3 the watchdog degrades+ # to Response.close(), which leaves the socket readable and the read parked -- measured+ # against a real trickling loopback socket, the reader was still alive after 40 s.+ #+ # So the bound cannot be the interrupt working. This pins the other half: the drain runs on a+ # worker the caller ABANDONS, so the picker answers on time no matter what is underneath.+ still_reading = threading.Event()++ class _Unwakeable:+ status_code = 206+ # No `raw`, exactly like a urllib3 predating shutdown: _interrupt_read falls through to+ # close(), and close() does not end a read already inside iter_content.+ raw = None++ def iter_content(self, chunk_size = 1):+ still_reading.set()+ time.sleep(30)+ yield b"never arrives"++ def close(self):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False++ monkeypatch.setattr(diffusion_compat, "_HEADER_TIMEOUT_SECONDS", 0.5)+ monkeypatch.setattr(+ "huggingface_hub.utils.get_session",+ lambda: types.SimpleNamespace(get = lambda *a, **k: _Unwakeable()),+ )+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ started = time.monotonic()+ assert diffusion_compat._read_gguf_header(KLEIN_4B_GGUF, KLEIN_4B_FILE, None) == b""+ elapsed = time.monotonic() - started++ assert still_reading.is_set(), "the fixture never got as far as blocking"+ # Deadline plus the abandon grace, with room for a loaded CI box. The point is that this is+ # bounded at all: without the worker it is the fixture's 30 s, and in the field it is forever.+ assert elapsed < 5, f"the picker waited {elapsed:.1f}s on a read it cannot interrupt"+++def test_a_server_that_ignores_the_range_header_is_abandoned(monkeypatch, tmp_path):+ # A 200 means the whole multi-GB checkpoint is on the wire. Reading it here would BE the+ # download this preflight exists to avoid, so the body is dropped unread and the check+ # fails open.+ body_reads: list[int] = []++ class _WholeFile(_FakeResponse):+ def iter_content(self, chunk_size = 1):+ body_reads.append(chunk_size)+ yield b""++ class _Session:+ def get(+ self,+ url,+ headers = None,+ timeout = None,+ stream = False,+ ):+ return _WholeFile(200, _gguf_header(3072, tmp_path))++ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: _Session())+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )+ is None+ )+ assert body_reads == []+++ "base",+ ["someone/a-base-we-do-not-ship", "/models/my-local-flux2"],+ ids = ["unknown-repo", "local-path"],+)+def test_a_base_outside_the_size_table_costs_no_request_at_all(base, monkeypatch, tmp_path):+ # Nothing to compare the header against, so the check must notice BEFORE a round trip.+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})++ assert (+ diffusion_compat.flux2_pick_mismatch(FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, base)+ is None+ )+ assert requests == []+++def test_a_known_ungated_mirror_is_checked_like_its_upstream(monkeypatch, tmp_path):+ # Not an exception to the rule above: an unsloth mirror is a byte-identical copy, canonical_base+ # maps it back, and skipping it would leave the mirror picks -- the ones an anonymous user+ # actually gets -- as the only unguarded path.+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})+ from core.inference.diffusion_families import canonical_base++ mirror = "unsloth/FLUX.2-klein-9B"+ assert canonical_base(mirror).lower() == KLEIN_9B_BASE.lower(), "mirror table changed"++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, mirror+ )++ assert reason is not None and mirror in reason+++def test_a_non_flux2_family_costs_no_request_at_all(monkeypatch, tmp_path):+ # The base is a mapped FLUX.2 one, so only the FAMILY gate can stop this.+ requests = _stub_range_reads(monkeypatch, {"z.gguf": _gguf_header(3072, tmp_path)})++ assert (+ diffusion_compat.flux2_pick_mismatch(+ types.SimpleNamespace(name = "z-image"),+ "unsloth/Z-Image-Turbo-GGUF",+ "z.gguf",+ KLEIN_9B_BASE,+ )+ is None+ )+ assert requests == []+++def test_a_non_gguf_single_file_costs_no_request_at_all(monkeypatch, tmp_path):+ # A single_file load names a .safetensors, which has no GGUF header to read.+ requests = _stub_range_reads(monkeypatch, {"model.safetensors": _gguf_header(3072, tmp_path)})++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, "model.safetensors", KLEIN_9B_BASE+ )+ is None+ )+ assert requests == []+++def test_pasting_a_token_re_probes_a_pick_that_missed_anonymously(monkeypatch, tmp_path):+ # The memo keeps a MISS so an unreachable Hub is not asked three times per load, which would+ # otherwise leave a gated GGUF permanently unguarded for the session once it 401d anonymously.+ bodies: dict[str, bytes] = {}+ requests = _stub_range_reads(monkeypatch, bodies)++ assert (+ diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )+ is None+ )+ assert len(requests) == 1+ # Same anonymous pick again: the miss is remembered, so no second round trip.+ diffusion_compat.flux2_pick_mismatch(FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE)+ assert len(requests) == 1++ bodies[KLEIN_4B_FILE] = _gguf_header(3072, tmp_path)+ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE, "hf_token_value"+ )++ assert len(requests) == 2+ assert reason is not None and KLEIN_9B_BASE in reason+++def test_the_header_probe_is_memoised_across_the_three_checks(monkeypatch, tmp_path):+ # The plan, the pre-eviction preflight and the loader all ask about the same pick; one probe.+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})++ for _ in range(3):+ with pytest.raises(ValueError):+ diffusion_compat.assert_flux2_pick_compatible(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ assert len(requests) == 1+++def test_a_remembered_hub_failure_does_not_outlive_the_download(monkeypatch, tmp_path):+ # The memo exists so three checks cost one probe, and a "no opinion" has to be remembered too+ # or a genuinely unreadable pick re-probes the Hub forever. But the ordinary sequence is:+ # plan probes while the file is NOT yet on disk (a blip, or simply an unfinished download) ->+ # download completes -> the pre-eviction preflight asks again. If the negative shadows the+ # local read, the guard is silent for the rest of the process on a file sitting right there,+ # which is exactly the mismatch-after-a-19-GB-pull this preflight exists to prevent.+ requests = _stub_range_reads(monkeypatch, {}) # the Hub has nothing to say: negative memoised++ assert diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE) is None+ assert len(requests) == 1++ # The download lands the blob in the cache, which is what try_to_load_from_cache reports.+ staged = tmp_path / "blobs" / KLEIN_4B_FILE+ staged.parent.mkdir(parents = True, exist_ok = True)+ staged.write_bytes(_gguf_header(4096, tmp_path))+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: str(staged))++ assert diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE) == 4096+ # ...and the retry is free: the negative still suppresses a second range request.+ assert len(requests) == 1+++def test_a_remembered_hub_failure_still_suppresses_a_re_probe_while_nothing_is_on_disk(+ monkeypatch, tmp_path+):+ # The other half of the memo's job, which the fix above must not cost: with no local file to+ # re-read, a remembered negative answers without touching the network again.+ requests = _stub_range_reads(monkeypatch, {})++ for _ in range(3):+ assert diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE) is None++ assert len(requests) == 1+++def test_a_checkpoint_swapped_in_place_is_read_again(monkeypatch, tmp_path):+ """Same directory, same filename, different checkpoint. Keying the memo on the name alone+ answers the new file with the old one's dim, which refuses a valid 9B pairing and hands the+ native backend the 4B text encoders until the process restarts."""+ local = tmp_path / "on-device"+ local.mkdir()+ target = local / KLEIN_4B_FILE+ target.write_bytes(_gguf_header(3072, tmp_path))+ _stub_range_reads(monkeypatch, {})++ assert diffusion_compat.flux2_inner_dim_for_pick(str(local), KLEIN_4B_FILE) == 3072++ # Rewritten in place. os.stat resolution is coarse enough that a same-size overwrite inside+ # one tick could tie, so the two headers differ in length as well -- which is also what a real+ # 4B-for-9B swap looks like.+ target.write_bytes(_gguf_header(4096, tmp_path, siblings = 9))++ assert (+ diffusion_compat.flux2_inner_dim_for_pick(str(local), KLEIN_4B_FILE) == 4096+ ), "the memo answered for the file that used to be at this path"+++def test_a_bad_token_does_not_poison_the_good_one_that_replaces_it(monkeypatch, tmp_path):+ """Keying on the token's mere PRESENCE made every non-empty credential one key. A first probe+ with an expired token cached its miss there, and pasting a working token afterwards inherited+ it for the rest of the process -- the preflight silently off for that pick."""+ served: dict[str, bytes] = {}+ requests: list[tuple[str, str]] = []++ class _GatedSession:+ def get(+ self,+ url,+ headers = None,+ timeout = None,+ stream = False,+ ):+ token = (headers or {}).get("authorization", "")+ requests.append((url, token))+ if "good" not in token:+ return _FakeResponse(401)+ return _FakeResponse(206, served[KLEIN_4B_FILE])++ served[KLEIN_4B_FILE] = _gguf_header(4096, tmp_path)+ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: _GatedSession())+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)+ diffusion_compat._reset_inner_dim_cache()++ assert (+ diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE, "expired") is None+ )+ assert diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE, "good") == 4096+ # ...and each token still memoises on its own: the second good probe costs nothing.+ before = len(requests)+ assert diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, KLEIN_4B_FILE, "good") == 4096+ assert len(requests) == before+++def test_the_memo_never_holds_the_token_itself():+ """It is a process-global dict; a traceback or a heap dump renders it."""+ diffusion_compat._reset_inner_dim_cache()+ secret = "hf_averyrealsecrettoken"+ assert secret not in diffusion_compat._token_fingerprint(secret)+ assert diffusion_compat._token_fingerprint(None) == ""+ assert diffusion_compat._token_fingerprint("a") != diffusion_compat._token_fingerprint("b")+++def test_a_gguf_already_on_disk_is_read_instead_of_fetched(monkeypatch, tmp_path):+ # A cached or On Device checkpoint answers for free, and it is the same file the loader opens.+ local = tmp_path / "local-repo"+ local.mkdir()+ (local / KLEIN_4B_FILE).write_bytes(_gguf_header(4096, tmp_path))+ requests = _stub_range_reads(monkeypatch, {})++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, str(local), KLEIN_4B_FILE, KLEIN_4B_BASE+ )++ assert reason is not None and "klein-9B" in reason+ assert requests == []+++def test_a_local_header_past_the_prefix_cap_falls_back_to_the_full_reader(monkeypatch, tmp_path):+ # The prefix parse is an optimisation, not a limit: a table longer than the 256 KiB cap must+ # still be answered off the complete file on disk, not silently give up.+ import numpy as np+ from gguf import GGUFWriter+ from core.inference.diffusion_families import gguf_flux2_inner_dim_from_header++ local = tmp_path / "big-header-repo"+ local.mkdir()+ path = local / "wide.gguf"+ writer = GGUFWriter(str(path), "flux")+ # Tiny weights, enormous NAMES: the table has to exceed the cap while the file stays small.+ writer.add_tensor(+ "double_stream_modulation_img.lin.weight", np.zeros((48, 8), dtype = np.float16)+ )+ for i in range(1200):+ writer.add_tensor(f"blk.{i}.{'x' * 220}.weight", np.zeros((8, 8), dtype = np.float16))+ writer.write_header_to_file()+ writer.write_kv_data_to_file()+ writer.write_tensors_to_file()+ writer.close()++ prefix = path.read_bytes()[: diffusion_compat._GGUF_HEADER_BYTES]+ assert gguf_flux2_inner_dim_from_header(prefix) is None, "fixture must overflow the cap"+ _stub_range_reads(monkeypatch, {})++ assert diffusion_compat.flux2_inner_dim_for_pick(str(local), "wide.gguf") == 8+++# ── wiring: the plan reports, the load refuses, nothing is torn down ───────────+++def test_the_download_plan_reports_the_mismatch_instead_of_raising(monkeypatch, tmp_path):+ # Reported, not raised: the images page falls back to /images/load on ANY plan failure, so a+ # 400 here would start the download the verdict is meant to prevent.+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: KLEIN_9B_BASE+ )+ monkeypatch.setattr(+ DiffusionBackend, "_te_prequant_plan_files", staticmethod(lambda *a, **k: {})+ )+ monkeypatch.setattr(+ DiffusionBackend, "_estimate_download_bytes", staticmethod(lambda *a, **k: (0, []))+ )+ monkeypatch.setattr(+ "core.inference.diffusion._assert_base_repo_accessible", lambda *a, **k: None+ )++ plan = DiffusionBackend().download_plan(KLEIN_4B_GGUF, gguf_filename = KLEIN_4B_FILE)++ assert KLEIN_9B_BASE in (plan["incompatible_reason"] or "")+ # And it survives the envelope the route returns, or the picker never sees it.+ from models.inference import DiffusionDownloadPlanResponse++ assert KLEIN_9B_BASE in (DiffusionDownloadPlanResponse(**plan).incompatible_reason or "")+++def test_a_planner_that_omits_the_field_still_answers():+ # The native and video planners share this envelope and have no base pairing to check, so the+ # response model must default the field rather than 500 on its absence.+ from models.inference import DiffusionDownloadPlanResponse+ assert DiffusionDownloadPlanResponse(entries = [], total_bytes = 0).incompatible_reason is None+++def test_a_compatible_plan_reports_nothing(monkeypatch, tmp_path):+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: KLEIN_4B_BASE+ )+ monkeypatch.setattr(+ DiffusionBackend, "_te_prequant_plan_files", staticmethod(lambda *a, **k: {})+ )+ monkeypatch.setattr(+ DiffusionBackend, "_estimate_download_bytes", staticmethod(lambda *a, **k: (0, []))+ )+ monkeypatch.setattr(+ "core.inference.diffusion._assert_base_repo_accessible", lambda *a, **k: None+ )++ plan = DiffusionBackend().download_plan(KLEIN_4B_GGUF, gguf_filename = KLEIN_4B_FILE)++ assert plan["incompatible_reason"] is None+++def test_the_pre_eviction_preflight_refuses_the_mismatch(monkeypatch, tmp_path):+ # The route's last refusal before it takes the GPU from chat.+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: KLEIN_9B_BASE+ )+ monkeypatch.setattr(+ "core.inference.diffusion._assert_base_repo_accessible", lambda *a, **k: None+ )++ with pytest.raises(ValueError, match = "klein"):+ DiffusionBackend().preflight_base_access(+ KLEIN_4B_GGUF,+ FLUX2_FAMILY,+ gguf_filename = KLEIN_4B_FILE,+ model_kind = "gguf",+ )+++def test_the_load_refuses_before_prefetching_or_unloading_anything(monkeypatch, tmp_path):+ # The regression this whole change is about: the old order downloaded the base AND freed the+ # resident pipeline, then raised. Nothing below may run.+ _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(3072, tmp_path)})+ monkeypatch.setattr(+ "core.inference.diffusion._resolve_base_repo", lambda *a, **k: KLEIN_9B_BASE+ )+ monkeypatch.setattr(+ "core.inference.diffusion._assert_base_repo_accessible", lambda *a, **k: None+ )+ monkeypatch.setattr(+ DiffusionBackend, "_te_prequant_plan_files", staticmethod(lambda *a, **k: {})+ )+ monkeypatch.setattr(+ DiffusionBackend, "_estimate_download_bytes", staticmethod(lambda *a, **k: (0, []))+ )+ monkeypatch.setattr(+ DiffusionBackend,+ "_prefetch_files",+ lambda self, *a, **k: pytest.fail("a rejected pick must not stage a single byte"),+ )+ monkeypatch.setattr(+ DiffusionBackend,+ "load_pipeline",+ lambda self, **k: pytest.fail("a rejected pick must not reach the load"),+ )+ backend = DiffusionBackend()+ monkeypatch.setattr(+ backend,+ "_unload_locked",+ lambda: pytest.fail("a rejected pick must not free the resident pipeline"),+ )+ # The model the user is already working with, and the marker begin_load would have set.+ resident = object()+ backend._state = resident+ backend._load_token = 7+ backend._loading = _LoadingState(repo_id = KLEIN_4B_GGUF, base_repo = "")++ backend._run_load(+ repo_id = KLEIN_4B_GGUF,+ gguf_filename = KLEIN_4B_FILE,+ model_kind = "gguf",+ _load_token = 7,+ )++ # _run_load swallows into load_progress rather than raising; the refusal lands there.+ progress = backend.load_progress()+ assert progress["phase"] == "error"+ assert KLEIN_9B_BASE in progress["error"]+ assert backend._state is resident+++# ── the sibling hole: the native text-encoder pick ─────────────────────────────+++def test_the_native_encoder_follows_the_header_over_the_filename():+ # A renamed or hand-picked 9B checkpoint says nothing in its id, and the 4B encoder fails deep+ # inside sd-cli. The header knows.+ fam = detect_family("unsloth/FLUX.2-klein-4B-GGUF")+ assert fam is not None and fam.name == "flux.2-klein"++ by_name = sd_cpp_text_encoders_for(fam, "unsloth/FLUX.2-klein-4B-GGUF", "my-checkpoint.gguf")+ by_header = sd_cpp_text_encoders_for(+ fam, "unsloth/FLUX.2-klein-4B-GGUF", "my-checkpoint.gguf", inner_dim = 4096+ )++ assert by_name == fam.sd_cpp_text_encoders # today's answer: the 4B encoder+ assert by_header != by_name+ assert any("9B" in repo for repo, _f, _k in by_header)+++def test_the_header_also_overrides_a_misleading_9b_filename():+ fam = detect_family("unsloth/FLUX.2-klein-9B-GGUF")+ assert fam is not None++ picked = sd_cpp_text_encoders_for(+ fam, "unsloth/FLUX.2-klein-9B-GGUF", "flux-2-klein-9b-Q4_K_M.gguf", inner_dim = 3072+ )++ assert picked == fam.sd_cpp_text_encoders # the file really is 4B+++def test_an_unmapped_or_absent_inner_dim_keeps_the_filename_rule():+ fam = detect_family("unsloth/FLUX.2-klein-9B-GGUF")+ assert fam is not None+ nine_b = sd_cpp_text_encoders_for(fam, "unsloth/FLUX.2-klein-9B-GGUF", "klein-9b.gguf")++ for inner_dim in (None, 1234):+ assert (+ sd_cpp_text_encoders_for(+ fam, "unsloth/FLUX.2-klein-9B-GGUF", "klein-9b.gguf", inner_dim = inner_dim+ )+ == nine_b+ )+ assert any("9B" in repo for repo, _f, _k in nine_b)+++def test_a_stalled_response_header_cannot_hold_the_picker_open(monkeypatch):+ """requests' timeout is an INACTIVITY timeout, not a wall clock.++ A peer that trickles response headers a byte at a time resets it forever, so a deadline+ armed only once get() has returned never gets armed at all -- and this call sits on the+ /images/load route thread and on the download-plan path, both of which promise to fail+ open in seconds. The request itself has to be on the abandonable worker.+ """+ import threading+ import types++ released = threading.Event()++ def _never_returns(*_args, **_kwargs):+ # Still inside connect / the header wait: no response object exists to interrupt.+ released.wait(30)+ raise AssertionError("the request should have been abandoned, not awaited")++ monkeypatch.setattr(diffusion_compat, "_HEADER_TIMEOUT_SECONDS", 0.5)+ monkeypatch.setattr(+ "huggingface_hub.utils.get_session",+ lambda: types.SimpleNamespace(get = _never_returns),+ )+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ out: list[bytes] = []+ caller = threading.Thread(+ target = lambda: out.append(+ diffusion_compat._read_gguf_header(KLEIN_4B_GGUF, KLEIN_4B_FILE, None)+ ),+ daemon = True,+ )+ caller.start()+ caller.join(8)+ released.set()++ assert not caller.is_alive(), "the caller waited on a request that never returned headers"+ assert out == [b""]+++def test_the_offline_caller_still_gets_a_memoised_remote_answer(monkeypatch, tmp_path):+ """begin_load probes with allow_network=False right after a plan-time probe answered.++ Returning None there anyway sent it to the filename heuristic, which publishes the 4B+ encoder repos for a renamed 9B checkpoint -- so the delete-cached guard did not cover the+ companion repo the load was about to use.+ """+ monkeypatch.setattr(diffusion_compat, "_INNER_DIM_CACHE", {})+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)+ monkeypatch.setattr(+ diffusion_compat,+ "_read_gguf_header",+ lambda *a, **k: _gguf_header(4096, tmp_path),+ )++ online = diffusion_compat.flux2_inner_dim_for_pick(KLEIN_4B_GGUF, "renamed-4b.gguf")+ assert online == 4096++ # Same pick, same token, no network allowed: the memo answers.+ monkeypatch.setattr(+ diffusion_compat,+ "_read_gguf_header",+ lambda *a, **k: pytest.fail("the offline caller made a range request"),+ )+ assert (+ diffusion_compat.flux2_inner_dim_for_pick(+ KLEIN_4B_GGUF, "renamed-4b.gguf", allow_network = False+ )+ == 4096+ )+++# ── a cached copy the Hub has moved past ──────────────────────────────────────+++def _cached_snapshot(+ tmp_path,+ sha,+ body,+ filename = KLEIN_4B_FILE,+):+ """A file where huggingface_hub puts it: ``models--org--repo/snapshots/<sha>/<file>``."""+ path = tmp_path / f"models--{KLEIN_4B_GGUF.replace('/', '--')}" / "snapshots" / sha / filename+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(body)+ return path+++def _stub_revision(monkeypatch, sha):+ def _meta(*_args, **_kwargs):+ if sha is None:+ raise OSError("offline")+ return types.SimpleNamespace(commit_hash = sha, etag = sha)++ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", _meta)+++def test_a_republished_checkpoint_is_not_refused_from_the_stale_cache(monkeypatch, tmp_path):+ """try_to_load_from_cache resolves the LOCAL refs/main, so a 4B file republished at the same+ name as a 9B one would refuse a pick the loader's own hf_hub_download refreshes and loads."""+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(4096, tmp_path)})+ cached = _cached_snapshot(tmp_path, "oldcommit", _gguf_header(3072, tmp_path))+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: str(cached))+ _stub_revision(monkeypatch, "newcommit")++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ assert reason is None, "a stale cached header refused a pick the loader would have loaded"+ assert requests, "the live header was never read"+++def test_a_cached_checkpoint_at_the_current_revision_is_still_refused(monkeypatch, tmp_path):+ # The refusal this preflight exists for: the cache is current, so its header is the verdict+ # and nothing has to be fetched to say so.+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(4096, tmp_path)})+ cached = _cached_snapshot(tmp_path, "oldcommit", _gguf_header(3072, tmp_path))+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: str(cached))+ _stub_revision(monkeypatch, "oldcommit")++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ assert reason is not None and "klein-9B" in reason+ assert requests == []+++def test_a_revision_check_that_cannot_run_keeps_the_cached_refusal(monkeypatch, tmp_path):+ # Offline is the case the cached copy answers best: unable to ask, the preflight keeps the+ # verdict it has rather than fetching or going silent.+ requests = _stub_range_reads(monkeypatch, {KLEIN_4B_FILE: _gguf_header(4096, tmp_path)})+ cached = _cached_snapshot(tmp_path, "oldcommit", _gguf_header(3072, tmp_path))+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: str(cached))+ _stub_revision(monkeypatch, None)++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, KLEIN_4B_GGUF, KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ assert reason is not None and "klein-9B" in reason+ assert requests == []+++def test_an_on_device_checkpoint_is_never_revalidated(monkeypatch, tmp_path):+ # An On Device file IS the file the loader opens, so there is no Hub revision to be behind+ # and a mismatch must be refused without a single network call.+ local = tmp_path / "on-device"+ local.mkdir()+ (local / KLEIN_4B_FILE).write_bytes(_gguf_header(3072, tmp_path))+ requests = _stub_range_reads(monkeypatch, {})+ monkeypatch.setattr(+ diffusion_compat,+ "_hub_revision",+ lambda *a, **k: pytest.fail("an On Device pick asked the Hub for a revision"),+ )++ reason = diffusion_compat.flux2_pick_mismatch(+ FLUX2_FAMILY, str(local), KLEIN_4B_FILE, KLEIN_9B_BASE+ )++ assert reason is not None and "klein-9B" in reason+ assert requests == []diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex 183dc8e3511..9227e2f0db6 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -1273,6 +1273,104 @@ def test_the_delete_guard_names_the_repack_as_well_as_the_mirror(monkeypatch):assert "Comfy-Org/z_image_turbo" in protected+def test_begin_load_answers_without_waiting_on_the_header_probe(monkeypatch):+ """begin_load returns at once by contract: the route thread hands the UI a status and the+ multi-gigabyte pull happens on the worker. The FLUX.2 encoder pick needs the checkpoint's+ inner_dim, which for an uncached pick means a range request over the wire -- bounded, but+ bounded in SECONDS, and the route would wear every one of them on a load button press.++ So the pre-lock probe is offline-only. The guard it feeds is a hint at that moment; the worker+ re-probes with the network and publishes the real repos before it fetches a byte, which is the+ second half of this test."""+ import time as _time++ from core.inference import diffusion_compat++ diffusion_compat._reset_inner_dim_cache()+ probed: list[str] = []++ class _Slow:+ def get(+ self,+ url,+ headers = None,+ timeout = None,+ stream = False,+ ):+ probed.append(url)+ _time.sleep(30)+ raise AssertionError("unreachable")++ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: _Slow())+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda *a, **k: None)++ b = SdCppDiffusionBackend(engine = _FakeEngine())+ monkeypatch.setattr(b, "_run_load", lambda **kwargs: None) # skip the download thread++ started = _time.monotonic()+ b.begin_load("unsloth/FLUX.2-klein-4B-GGUF", gguf_filename = "flux-2-klein-4b-Q4_K_M.gguf")+ elapsed = _time.monotonic() - started++ assert probed == [], "begin_load must not range-read the header on the route thread"+ assert elapsed < 5, f"begin_load blocked for {elapsed:.1f}s"+++def test_the_worker_publishes_the_real_encoder_repos_before_fetching(monkeypatch):+ # The delete-cached guard reads _loading.asset_repos. begin_load can only guess them for a+ # FLUX.2 pick it has no header for, so an unrefreshed list would leave the 9B encoders+ # deletable while the load is writing into them.+ from core.inference import diffusion_compat++ diffusion_compat._reset_inner_dim_cache()+ nine_b = {repo for repo, _f, _k in _FLUX2_KLEIN_9B_SD_CPP_TEXT_ENCODERS}+ # The discriminating pick: a repo and filename that name no size, so the string fallback the+ # offline probe leaves in place answers 4B, while the header says 9B. A hand-renamed file or a+ # local On Device directory lands exactly here.+ repo, filename = "unsloth/FLUX.2-klein-GGUF", "flux-2-klein-Q4_K_M.gguf"+ monkeypatch.setattr(+ bk.SdCppDiffusionBackend,+ "_flux2_inner_dim",+ staticmethod(+ lambda repo_id, fn, fam, tok, allow_network = True: 4096 if allow_network else None+ ),+ )++ b = SdCppDiffusionBackend(engine = _FakeEngine())+ monkeypatch.setattr(b, "_run_load", lambda **kwargs: None)+ b.begin_load(repo, gguf_filename = filename)+ token = b._load_token+ assert not nine_b & set(+ b.loading_repo_ids()+ ), "fixture is not discriminating: begin_load already guessed the 9B encoders"++ monkeypatch.setattr(b, "_resolve_backend", lambda: ("oneshot", None, _FakeEngine()))+ monkeypatch.setattr(b, "_preflight_companion_repos", lambda *a, **k: None)+ monkeypatch.setattr(b, "_set_expected_bytes", lambda *a, **k: None)+ seen_at_fetch: list[tuple[str, ...]] = []++ def _fetch(*_a, **_k):+ seen_at_fetch.append(b.loading_repo_ids())+ raise SdCppCancelled("stop here; the publish already had to happen")++ monkeypatch.setattr(b, "_fetch_assets", _fetch)+ # The class method, not the instance attribute: begin_load's thread is stubbed out above, so+ # the worker body has to be driven by hand.+ bk.SdCppDiffusionBackend._run_load(+ b,+ repo_id = repo,+ gguf_filename = filename,+ base = "black-forest-labs/FLUX.2-klein-9B",+ fam = detect_family(repo),+ hf_token = None,+ _load_token = token,+ )++ assert seen_at_fetch, "the fetch was never reached"+ assert nine_b <= set(+ seen_at_fetch[0]+ ), "the delete guard did not name the encoders this load is about to write"++def test_generate_reports_the_build_the_recipe_persists():# The route writes the recipe straight off these keys, so a key the native result omits is# persisted as null. The engine has no dense quant and no memory planner (honest nulls), butdiff --git a/studio/frontend/package.json b/studio/frontend/package.jsonindex 2d67e30a904..602ba6aee29 100644--- a/studio/frontend/package.json+++ b/studio/frontend/package.json@@ -16,6 +16,7 @@"i18n:check": "node --experimental-strip-types --no-warnings src/i18n/check-parity.ts","i18n:check:strict": "node --experimental-strip-types --no-warnings src/i18n/check-parity.ts --strict","catalog:check": "node --experimental-strip-types --no-warnings src/features/model-picker/components/model-selector/model-catalog.check.ts",+ "catalog:check:network": "node --experimental-strip-types --no-warnings src/features/model-picker/components/model-selector/model-catalog.check.ts --network","biome:check": "biome check","biome:fix": "biome check --write"},diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex d0856361c2a..d8c998b3bcd 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -279,6 +279,13 @@ export interface DiffusionDownloadPlan {gguf_filename: string | null;}[];total_bytes: number;+ /**+ * Why this pick cannot load as selected (a FLUX.2 GGUF paired with a different-size base), or+ * null/undefined when nothing is known to be wrong. The backend reads metadata only, so it stays+ * silent rather than guessing; when it does speak, refuse the pick here -- the alternative is the+ * loader saying the same thing after a ~19 GB download. Optional: an older backend omits it.+ */+ incompatible_reason?: string | null;}/** What to stage through the download manager before loading this pick. */diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 18106025036..5c54593ece6 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -2101,6 +2101,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);// ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.const advanced = currentLoadAdvanced(repoId);+ // Read inside the try, acted on outside it: refusing from in there would fall through to the+ // load on any throw from the refusal itself, which is the one outcome that must not happen.+ let incompatible: string | null = null;try {const plan = await getDiffusionDownloadPlan({model_path: repoId,@@ -2121,7 +2124,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {});// Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.if (!owns()) return false;- if (plan.entries.length > 0) {+ // Refuse an incompatible pairing HERE, at selection time. The backend also raises it from+ // the load, but only after staging the base repo: the whole point of checking it in the+ // plan is that no byte has moved yet. Returning false reverts the picker's optimistic+ // quant selection, exactly as a load that fails to start does.+ incompatible = plan.incompatible_reason ?? null;+ if (!incompatible && plan.entries.length > 0) {pendingStagedLoad.current = { repoId, opts, advanced, token: token ?? pickGuard.claim() };stage(plan.entries.map((e) => ({@@ -2137,6 +2145,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {// No plan (older backend, metadata hiccup): fall back to the load's own download.}if (!owns()) return false;+ if (incompatible) {+ toast.error(incompatible);+ return false;+ }return handleLoadRef.current(repoId, opts);},[stage, currentLoadAdvanced, pickGuard],diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.tsindex 546a22075c8..165b7be6980 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts@@ -2,9 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Assertions over the model catalog: keys, aliases, integrity, quant routing ladders, search matching. Plain node:assert like i18n:check. Run: npm run catalog:check+//+// `--network` adds an OPT-IN pass that asks the Hub whether every declared artifact is actually+// downloadable and whether each `gated` flag matches reality. It is deliberately not part of+// `npm run catalog:check`: it needs the network, and a Hub hiccup must never fail an unrelated PR.+// Run it on a schedule instead (.github/workflows/model-catalog-network-check.yml), or by hand+// with `npm run catalog:check:network`.import assert from "node:assert/strict";+import type { CatalogGroup, ModelArtifact } from "./model-catalog.ts";import {IMAGE_CATALOG,VIDEO_CATALOG,@@ -466,8 +473,15 @@ assert.equal("gguf",);// LTX-2.3 video carries the official BF16 single file (no FP8: the loader refuses its scaled-fp8 one), which keeps the ~50 GB Gemma3 encoder resident, so B200-class only.+// Looked up by the retired unsloth/LTX-2.3 id on purpose: it is no longer the canonicalId (that+// repo does not exist), and a pasted or persisted copy must still land on this group through the+// GGUF artifact's suffix-stripped key.const ltxGroup = groupForRepoId("unsloth/LTX-2.3", VIDEO_CATALOG);assert.ok(ltxGroup);+assert.equal(ltxGroup.canonicalId, "Lightricks/LTX-2.3");+assert.equal(groupForRepoId("Lightricks/LTX-2.3", VIDEO_CATALOG), ltxGroup);+// The retired id is not an artifact, so it can never be handed to a load as a repo to fetch.+assert.equal(loadSpecFor("unsloth/LTX-2.3", VIDEO_CATALOG), null);assert.equal(pickDefaultArtifact(ltxGroup, { gpuGb: 24, systemRamGb: 64, isDownloaded: notDownloaded }).format,@@ -552,3 +566,197 @@ assert.ok(groupMatchesQuery(ltx23, "ltx"));assert.ok(groupMatchesQuery(ltx23, "lightricks/ltx-2.3"));console.log("model-catalog check: all assertions passed");++// ── opt-in: does the Hub agree? (`--network`) ─────────────────────────────────+//+// Every failure this catches was reported by hand: a preconfigured link that 401s because its+// repo is gated and the entry never said so, or 404s because the repo/file was renamed or never+// published. Neither is visible to a pure-data check, and both surface to the user as a download+// that dies partway through.+//+// Anonymous on purpose: that is what a fresh install sees, and it is exactly the request whose+// 401 the `gated` flag exists to predict. Retries cover Hub flakiness; only a definitive verdict+// (a repo that answers "gone", a filename the repo does not list, a `gated` flag that disagrees+// with the API) fails the run.++const HF_API = "https://huggingface.co/api/models";+const HF_RESOLVE = "https://huggingface.co";+const NETWORK_ATTEMPTS = 3;+/** Per-attempt wall clock, headers and body together. */+const NETWORK_TIMEOUT_MS = 20_000;+/**+ * Wall clock for the whole network pass, comfortably under the workflow's 10-minute+ * timeout-minutes.+ *+ * Bounding each attempt is not enough on its own: ~53 repos at NETWORK_BATCH 4 is 14 serial+ * batches, and a peer that stalls every request costs 3 x 20s plus 1.5s of backoff per batch,+ * so a fully stalled Hub takes about 14.3 minutes to fail open -- and the job is killed at 10,+ * which is the red run this retry logic exists to avoid. Past this deadline every remaining+ * request short-circuits to "no opinion", so the check still reaches its warnings and exits 0.+ */+const NETWORK_DEADLINE_MS = 7 * 60 * 1000;+/** Set when the network pass starts; Infinity keeps the offline assertions unbounded. */+let networkDeadlineAt = Number.POSITIVE_INFINITY;+const NETWORK_BATCH = 4;++interface HubRepo {+ /** false for an open repo; "auto" / "manual" for a gated one. */+ gated?: boolean | string;+ siblings?: { rfilename: string }[];+}++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/**+ * Fetch with retries. Never throws and never rejects: an answer the Hub could not give is+ * `{ response: null }`, which callers must treat as "no opinion". A rate limit, a 5xx window or a+ * DNS blip is the Hub having a moment, and turning one of those into a red nightly is exactly+ * what this whole check promises not to do.+ */+async function fetchWithRetry(+ url: string,+ init?: RequestInit,+): Promise<{ response: Response | null; body: string; why: string }> {+ let why = "unknown";+ for (let attempt = 1; attempt <= NETWORK_ATTEMPTS; attempt++) {+ if (Date.now() >= networkDeadlineAt) {+ return { response: null, body: "", why: "the network check ran out of its overall budget" };+ }+ try {+ // A per-attempt deadline, or a peer that accepts the connection and then stalls has no+ // retry and no fail-open: fetch simply never settles, and the scheduled job dies on its own+ // 10-minute timeout as a RED run. Which is the one outcome this check promises not to+ // produce for a network blip.+ const response = await fetch(url, { ...init, signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS) });+ // Read the body HERE, under that same deadline. Headers can arrive promptly and the body+ // still stall, and the caller parses outside this function where an abort would surface as+ // "the Hub answered 200 with unreadable JSON" -- a catalog failure, for a stalled socket.+ // It also drains the 429/5xx responses we are about to retry, rather than leaking them.+ const body = init?.method === "HEAD" ? "" : await response.text();+ if (response.status !== 429 && response.status < 500) return { response, body, why: "" };+ why = `HTTP ${response.status}`;+ } catch (err) {+ why = String(err);+ }+ if (attempt < NETWORK_ATTEMPTS) await sleep(500 * 2 ** (attempt - 1));+ }+ return { response: null, body: "", why };+}++/** Run `work` over `items`, a few at a time: ~35 repos, and the Hub does not need a thundering herd. */+async function inBatches<T>(items: T[], work: (item: T) => Promise<void>): Promise<void> {+ for (let i = 0; i < items.length; i += NETWORK_BATCH) {+ await Promise.all(items.slice(i, i + NETWORK_BATCH).map(work));+ }+}++async function checkCatalogAgainstTheHub(catalogs: CatalogGroup[][]): Promise<string[]> {+ networkDeadlineAt = Date.now() + NETWORK_DEADLINE_MS;+ const failures: string[] = [];+ const groups = catalogs.flat();+ // One metadata call per repo id, however many artifacts share it.+ const artifactsByRepo = new Map<string, ModelArtifact[]>();+ for (const group of groups) {+ for (const artifact of group.artifacts) {+ const bucket = artifactsByRepo.get(artifact.repoId);+ if (bucket) bucket.push(artifact);+ else artifactsByRepo.set(artifact.repoId, [artifact]);+ }+ }++ await inBatches([...artifactsByRepo.entries()], async ([repoId, artifacts]) => {+ const { response, body, why } = await fetchWithRetry(`${HF_API}/${repoId}`);+ if (response === null) {+ console.warn(+ `::warning::${repoId}: the Hub did not answer after ${NETWORK_ATTEMPTS} attempts (${why}). Not a verdict about the catalog.`,+ );+ return;+ }+ if (!response.ok) {+ // 401 on the METADATA endpoint means private-or-absent (the Hub will not say which);+ // a gated-but-public repo answers 200 with gated set, so this is never just "needs a licence".+ failures.push(+ `${repoId}: HTTP ${response.status} from ${HF_API}/${repoId} -- the repo is missing, renamed or private, so no user can download it`,+ );+ return;+ }+ let repo: HubRepo;+ try {+ repo = JSON.parse(body) as HubRepo;+ } catch (err) {+ // A 200 that is not JSON is a captive portal or a proxy, not a catalog problem. Reject the+ // run rather than throwing out of Promise.all with a raw stack.+ failures.push(`${repoId}: the Hub answered 200 with unreadable JSON (${err})`);+ return;+ }+ const hubGated = Boolean(repo.gated);+ for (const artifact of artifacts) {+ const declaredGated = artifact.gated === true;+ if (hubGated && !declaredGated) {+ failures.push(+ `${repoId}: the Hub reports gated=${JSON.stringify(repo.gated)} but the catalog entry has no \`gated: true\`, so an anonymous download 401s`,+ );+ } else if (!hubGated && declaredGated) {+ failures.push(+ `${repoId}: marked \`gated: true\` but the Hub reports it open -- the router skips it for no reason`,+ );+ }+ }++ const declaredFiles = [+ ...new Set(artifacts.map((a) => a.filename).filter((f): f is string => Boolean(f))),+ ];+ if (declaredFiles.length === 0) return;+ const listed = new Set((repo.siblings ?? []).map((s) => s.rfilename));+ for (const filename of declaredFiles) {+ if (!listed.has(filename)) {+ failures.push(`${repoId}: declares '${filename}', which the repo does not contain`);+ continue;+ }+ if (hubGated) continue; // resolve/ 401s without a token; the sibling list is the check.+ // Listed is not the same as fetchable: resolve/ is the endpoint the download hits.+ const head = await fetchWithRetry(`${HF_RESOLVE}/${repoId}/resolve/main/${filename}`, {+ method: "HEAD",+ });+ if (head.response === null) {+ console.warn(+ `::warning::${repoId}: could not HEAD '${filename}' (${head.why}). Not a verdict.`,+ );+ } else if (!head.response.ok) {+ failures.push(+ `${repoId}: '${filename}' is listed but resolve/main returned HTTP ${head.response.status}`,+ );+ }+ }+ });++ // Advisory only. A canonicalId is a display/grouping key, and 15 of them are deliberately not+ // repos; but one that is BOTH `unsloth/*`-shaped and dead clears every owner guard in the app,+ // so it is worth naming without failing a scheduled job over it.+ const artifactIds = new Set([...artifactsByRepo.keys()].map((id) => id.toLowerCase()));+ const orphans = groups+ .map((g) => g.canonicalId)+ .filter((id) => !artifactIds.has(id.toLowerCase()));+ await inBatches(orphans, async (canonicalId) => {+ const { response } = await fetchWithRetry(`${HF_API}/${canonicalId}`);+ // A null response is an unreachable Hub, which is simply no advice.+ if (response !== null && !response.ok) {+ console.warn(+ `::warning::canonicalId '${canonicalId}' is not a real repo (HTTP ${response.status}). Harmless as a grouping key, but it must never reach a load.`,+ );+ }+ });++ return failures;+}++if (process.argv.includes("--network")) {+ console.log("model-catalog check: --network, asking the Hub about every declared artifact...");+ const failures = await checkCatalogAgainstTheHub([IMAGE_CATALOG, VIDEO_CATALOG]);+ if (failures.length > 0) {+ for (const failure of failures) console.error(`::error::${failure}`);+ console.error(`model-catalog network check: ${failures.length} problem(s)`);+ process.exit(1);+ }+ console.log("model-catalog network check: every declared repo, file and gated flag agrees with the Hub");+}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.tsindex e630bf8fd79..9dd9946a660 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts@@ -325,7 +325,13 @@ export const VIDEO_CATALOG: CatalogGroup[] = [{// The distilled 2.3 release: Lightricks' own bf16/fp8 single-file DiT checkpoints (loaded against the already-trusted LTX-2// base for the VAE / Gemma3 encoder) plus the GGUF quants. The single-file ones keep the ~50 GB encoder in bf16, so consumer GPUs route to GGUF.- canonicalId: "unsloth/LTX-2.3",+ // Keyed on the artifact that exists: unsloth/LTX-2.3 was never published (404), and an+ // `unsloth/*` id that is not an artifact clears both the picker's owner guard and the+ // backend's, so a pick that reached the fall-through was loaded as a pipeline and only died+ // at the Hub. Lightricks/LTX-2.3 IS an artifact below, so that fall-through cannot fire.+ // unsloth/LTX-2.3 still resolves to this group: the GGUF artifact claims the same+ // suffix-stripped key.+ canonicalId: "Lightricks/LTX-2.3",displayName: "LTX 2.3 distilled",description: "Text-to-video with audio",scope: "video",diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex a09a54a30ee..d536c981c12 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -1452,6 +1452,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {): Promise<boolean> => {const owns = () => token === undefined || pickGuard.holds(token);if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);+ // Read inside the try, acted on outside it, as on the images page.+ let incompatible: string | null = null;try {const plan = await getVideoDownloadPlan({model_path: repoId,@@ -1473,7 +1475,13 @@ function VideoGenerator({ active = true }: { active?: boolean }) {});// Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.if (!owns()) return false;- if (plan.entries.length > 0) {+ // Same selection-time refusal the images page makes: the plan is the last point at which+ // an incompatible pairing can be caught before the download it would waste. No video+ // family declares one today (the check is the FLUX.2 GGUF/base size pairing, and the video+ // planner has no diffusers base to pair against), so this is the shared envelope's half of+ // the contract rather than a live path -- keep it, or a future one lands unguarded.+ incompatible = plan.incompatible_reason ?? null;+ if (!incompatible && plan.entries.length > 0) {pendingStagedLoad.current = { repoId, opts, token: token ?? pickGuard.claim() };stage(plan.entries.map((e) => ({@@ -1489,6 +1497,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// No plan (older backend, metadata hiccup): fall back to the load's own download.}if (!owns()) return false;+ if (incompatible) {+ toast.error(incompatible);+ return false;+ }return handleLoadRef.current(repoId, opts);},[stage, pickGuard],diff --git a/studio/frontend/tests/model-catalog-network-budget.test.ts b/studio/frontend/tests/model-catalog-network-budget.test.tsnew file mode 100644index 00000000000..7e1056588f4--- /dev/null+++ b/studio/frontend/tests/model-catalog-network-budget.test.ts@@ -0,0 +1,62 @@+// 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 network catalog check promises that an unreachable Hub produces warnings, never a red run.+// Bounding each request is not enough to keep that promise: the batches are serial, so a peer+// that stalls every one of them can still outlive the workflow's own timeout and be killed --+// which is the red run, arriving by a different route. This pins the arithmetic.++import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++const CHECK = fileURLToPath(+ new URL(+ "../src/features/model-picker/components/model-selector/model-catalog.check.ts",+ import.meta.url,+ ),+);+const WORKFLOW = fileURLToPath(+ new URL("../../../.github/workflows/model-catalog-network-check.yml", import.meta.url),+);++function constant(name: string): number {+ const source = readFileSync(CHECK, "utf8");+ const match = source.match(new RegExp(`const ${name} = ([^;]+);`));+ assert.ok(match, `model-catalog.check.ts no longer defines ${name}`);+ // The literals are written for readers (7 * 60 * 1000, 20_000), so evaluate rather than parse.+ return Number(new Function(`return (${match[1].replaceAll("_", "")})`)());+}++test("the whole network pass is bounded, not just each request", () => {+ const source = readFileSync(CHECK, "utf8");+ assert.match(+ source,+ /Date\.now\(\) >= networkDeadlineAt/,+ "fetchWithRetry must short-circuit once the overall budget is spent",+ );+ assert.match(+ source,+ /networkDeadlineAt = Date\.now\(\) \+ NETWORK_DEADLINE_MS/,+ "the deadline has to be armed when the network pass starts",+ );+});++test("the overall budget leaves room inside the workflow timeout", () => {+ const workflow = readFileSync(WORKFLOW, "utf8");+ const timeout = workflow.match(/timeout-minutes:\s*(\d+)/);+ assert.ok(timeout, "the network-check workflow no longer declares timeout-minutes");+ const jobBudgetMs = Number(timeout[1]) * 60 * 1000;++ // Worst case after the deadline fires: the batch already in flight still has to unwind.+ const perBatchMs =+ constant("NETWORK_ATTEMPTS") * constant("NETWORK_TIMEOUT_MS") + 500 + 1000;+ const worstCaseMs = constant("NETWORK_DEADLINE_MS") + perBatchMs;++ assert.ok(+ worstCaseMs < jobBudgetMs,+ `a fully stalled Hub takes ${(worstCaseMs / 60000).toFixed(1)} min to fail open, and the ` ++ `job is killed at ${Number(timeout[1])} min -- the red run this retry logic exists to avoid`,+ );+});