Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Require every declared denoiser, and every shard of it, before a cached pipeline reads as complete (#7871)

Daniel Han73d54964b480
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index d3aef8cc526..0c3eb634727 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -1022,7 +1022,11 @@ def test_cached_models_scan_keeps_a_complete_pipeline_loadable(monkeypatch, tmp_
_file("model_index.json", 900),
_file("vae/diffusion_pytorch_model.safetensors", 300_000_000),
_file("text_encoder/model.safetensors", 900_000_000),
- _file("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 4_000_000_000),
+ # Unsharded, because this fixture stands for a COMPLETE pipeline. It used to name a
+ # lone "-00001-of-00002" shard with no index, which is not loadable at all: with no
+ # index diffusers reads the component as unsharded and asks for the plain name, never
+ # the numbered file. The scan now calls that partial, as it always should have.
+ _file("transformer/diffusion_pytorch_model.safetensors", 4_000_000_000),
],
task = "text-to-image",
)
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index 798c6a39dbd..d43d6772f9a 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -19,7 +19,7 @@ import re
import threading
import time
from dataclasses import dataclass, replace
-from pathlib import Path, PurePosixPath
+from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Callable, NamedTuple, Optional
from loggers import get_logger
@@ -1077,7 +1077,10 @@ def _index_cannot_serve_its_shards(index_path: Path, family_files: set[str]) ->
return True
with index_path.open(encoding = "utf-8") as handle:
index = json.load(handle)
- except (OSError, UnicodeDecodeError, ValueError):
+ except (OSError, UnicodeDecodeError, ValueError, RecursionError):
+ # RecursionError (deeply nested json) escapes every caller's fail-open guard. The loader
+ # parses this index with the same json module, so one too deep to parse there cannot serve
+ # its shards here either.
return True
weight_map = index.get("weight_map") if isinstance(index, dict) else None
if not isinstance(weight_map, dict) or not weight_map:
@@ -1096,7 +1099,11 @@ def _index_cannot_serve_its_shards(index_path: Path, family_files: set[str]) ->
if not isinstance(shard, str) or not shard:
return True
parts = PurePosixPath(shard.replace("\\", "/"))
- if parts.is_absolute() or ".." in parts.parts:
+ # is_absolute() is per flavour: PurePosixPath reads "C:/weights/x.safetensors" as a relative
+ # subdirectory called "C:", but the join below is a platform Path, so on Windows that name
+ # replaces the index directory outright. A drive is never part of a shard name.
+ windows = PureWindowsPath(shard)
+ if parts.is_absolute() or ".." in parts.parts or windows.is_absolute() or windows.drive:
return True
try:
named = index_path.parent / parts
@@ -1492,6 +1499,15 @@ def _current_revisions(repo_info):
# check so the two cannot drift into disagreeing about the same directory.
_DENOISER_DIRS = ("transformer", "unet")
_DENOISER_WEIGHT_SUFFIXES = (".safetensors", ".bin")
+# The two names a default load can end up opening at the component root: the safetensors one
+# _get_model_file is asked for first, and the .bin the pickle fallback under it drops to.
+_DEFAULT_DENOISER_WEIGHTS = frozenset(
+ f"diffusion_pytorch_model{suffix}" for suffix in _DENOISER_WEIGHT_SUFFIXES
+)
+# The one sharded index a default load resolves: use_safetensors unset coerces to True, and
+# _fetch_index_file then builds only _add_variant(SAFE_WEIGHTS_INDEX_NAME, variant), so with
+# variant unset this exact name. Our load path passes neither (core/inference/{diffusion,video}.py).
+_SELECTED_DENOISER_INDEX = "diffusion_pytorch_model.safetensors.index.json"
def snapshot_has_pipeline_index(snapshot: Optional[Path]) -> bool:
@@ -1509,28 +1525,145 @@ def snapshot_has_pipeline_index(snapshot: Optional[Path]) -> bool:
return False
+def _manifest_denoiser_components(snapshot: Path) -> Optional[tuple[str, ...]]:
+ """The denoiser subdirs this pipeline's own ``model_index.json`` declares, or None.
+
+ Read off the manifest rather than the fixed ``_DENOISER_DIRS`` pair because multi-DiT pipelines
+ carry more than one (Ideogram 4 adds ``unconditional_transformer/``, Wan 2.2's A14B experts
+ ``transformer_2/``) and would otherwise pass on whichever the loop reached first.
+
+ None means the manifest could not be READ and the caller keeps the fixed-pair rule. An EMPTY
+ tuple is the different answer that it read fine and names no denoiser under either spelling
+ (Stable Cascade and Wuerstchen call theirs ``decoder``/``prior``), so there is nothing here to
+ prove absent and the caller must not hunt for directories that layout never had.
+ """
+ try:
+ with (snapshot / "model_index.json").open("r", encoding = "utf-8") as fh:
+ manifest = json.load(fh)
+ except (OSError, ValueError, RecursionError):
+ # RecursionError (deeply nested json) would escape the caller's fail-open guard.
+ return None
+ if not isinstance(manifest, dict):
+ return None
+ found = []
+ for key, value in manifest.items():
+ if not isinstance(key, str) or key.startswith("_"):
+ continue
+ name = key.lower()
+ if name != "unet" and "transformer" not in name:
+ continue
+ # A component is a [library, class] pair keyed by its directory; [null, null] means
+ # deliberately absent (Wan 2.2's 5B transformer_2). Anything else names no directory to
+ # infer (ACE-STEP maps "transformer" to a config dict), so leave it to the loader.
+ if not isinstance(value, (list, tuple)) or not any(v for v in value):
+ continue
+ found.append(key)
+ return tuple(found)
+
+
+def _denoiser_index_shards(index: Path) -> Optional[set[str]]:
+ """The shard names *index* maps, or None when it is absent, unparseable or maps nothing.
+
+ None is "no evidence" rather than "incomplete": an index we cannot read proves nothing either
+ way, so the caller keeps looking.
+ """
+ try:
+ with index.open("r", encoding = "utf-8") as fh:
+ weight_map = json.load(fh).get("weight_map")
+ except (OSError, ValueError, AttributeError, RecursionError):
+ # RecursionError (deeply nested json) would escape the caller's fail-open guard.
+ return None
+ if not isinstance(weight_map, dict):
+ return None
+ return {str(v) for v in weight_map.values() if v} or None
+
+
+def _component_weights_complete(component: Path) -> bool:
+ """Whether *component* holds a denoiser the loader could actually read.
+
+ Presence of ONE weight file is not enough: a sharded denoiser is described by an
+ ``*.index.json`` naming every shard, and a fetch that landed shard 1 of 2 alone satisfies a
+ first-match test while failing at load.
+
+ ``_SELECTED_DENOISER_INDEX`` settles the question on its own whenever it EXISTS: it is the only
+ sharded name diffusers resolves here, its presence alone makes the component sharded, and what
+ follows is unconditional -- ``_get_checkpoint_shard_files`` opens exactly what it maps, while
+ the ``except IOError`` branch and the pickle fallback under it are both gated on ``not
+ is_sharded``. So a short set fails, and so does an index too corrupt to parse.
+
+ Every OTHER index vouches for nothing, because a default load never opens it:
+ ``_fetch_index_file`` builds the safetensors name only, and the non-sharded fallback under it
+ asks for the UNSHARDED ``diffusion_pytorch_model.bin``, never a ``.bin.index.json`` set beside
+ it. Repos ship exactly that leftover (``stablediffusionapi/sdrealdream``), and our own download
+ plan manufactures it (``core/inference/diffusion.py``).
+
+ Nor does a dtype variant, whole or not. ``_add_variant`` inserts the variant before the last
+ part, so a bf16 set is ``diffusion_pytorch_model.safetensors.index.bf16.json`` over
+ ``diffusion_pytorch_model-00001-of-00002.bf16.safetensors`` -- the real names
+ ``genmo/mochi-1-preview`` ships beside its default weights. A load passing no ``variant`` asks
+ for the plain name and has no fallback the other way, and the download plan skips those files
+ for the same reason, so a cache holding only them was filled by something else.
+
+ So with no selected index there are exactly two names left, the pair ``_get_model_file`` is
+ handed, and every other weight in the directory is one ``from_pretrained`` never resolves.
+ """
+ # iterdir() raises on an unreadable dir, reaching the caller's fail-open guard; glob() would
+ # swallow that OSError and read as "no weights".
+ next(component.iterdir(), None)
+ # Existence alone makes the component sharded (``is_sharded`` comes from ``is_file()``), so an
+ # index we cannot read is not no-evidence here, it IS the failure. ``is_file()`` is also the
+ # loader's own test, so a dangling snapshot symlink is absent to both.
+ selected = component / _SELECTED_DENOISER_INDEX
+ if selected.is_file():
+ if _index_cannot_serve_its_shards(selected, set()):
+ return False
+ # The loader opens exactly what ``weight_map`` lists and reads each one as a checkpoint,
+ # so a map naming something that is not a weight file -- a ``config.json`` a corrupt fetch
+ # left behind -- fails at load however present that file is.
+ shards = _denoiser_index_shards(selected)
+ return bool(shards) and all(
+ name.lower().endswith(_DENOISER_WEIGHT_SUFFIXES) for name in shards
+ )
+ # No index, so the component is not sharded to the loader either, and ``_get_model_file`` is
+ # asked for the safetensors default and then the ``.bin`` under it and opens nothing else. A
+ # weight under any other name is one ``from_pretrained`` never resolves: a numbered shard is
+ # reachable only THROUGH an index, a dtype twin only under a matching ``variant``, and a
+ # ``model.safetensors`` or adapter sidecar never at all.
+ return any((component / name).is_file() for name in _DEFAULT_DENOISER_WEIGHTS)
+
+
def snapshot_pipeline_missing_denoiser(snapshot: Optional[Path]) -> bool:
"""The companion-only-prefetch check scoped to ONE snapshot dir.
Same signal as :func:`repo_pipeline_missing_denoiser` -- a root ``model_index.json`` with no
- weight under ``transformer/`` or ``unet/`` -- but judged on the directory the caller's row
- actually loads, not on whichever revision this module would have picked for itself. Two
- snapshot selectors disagree: a row pinned to (or resolving through ``refs/main`` to) a complete
- revision would otherwise be marked partial by a newer companion-only one sitting beside it.
+ usable weights under the pipeline's denoiser component(s) -- but judged on the directory the
+ caller's row actually loads, not on whichever revision this module would have picked for
+ itself. Two snapshot selectors disagree: a row pinned to (or resolving through ``refs/main``
+ to) a complete revision would otherwise be marked partial by a newer companion-only one
+ sitting beside it.
+
+ Stricter than the repo-wide twin, since this decides whether a row is advertised as runnable:
+ EVERY denoiser the manifest declares must be present, each with every shard its index names.
Best-effort in the same direction: a read error reports not-missing.
"""
if not snapshot_has_pipeline_index(snapshot):
return False
try:
- for denoiser in _DENOISER_DIRS:
- component = Path(snapshot) / denoiser
- if not component.is_dir():
- continue
- for entry in component.rglob("*"):
- # is_file() follows the snapshot symlink, so a dangling blob is correctly absent.
- if entry.is_file() and entry.name.lower().endswith(_DENOISER_WEIGHT_SUFFIXES):
- return False
- return True
+ root = Path(snapshot)
+ declared = _manifest_denoiser_components(root)
+ if declared is not None:
+ # all(()) is True: a manifest declaring no denoiser has none to prove absent, so it
+ # reads complete rather than being hunted for one it never had.
+ return not all(
+ (root / name).is_dir() and _component_weights_complete(root / name)
+ for name in declared
+ )
+ # Unreadable manifest: either fixed name will do, since a UNet pipeline has no
+ # transformer/ and a DiT one no unet/.
+ return not any(
+ (root / name).is_dir() and _component_weights_complete(root / name)
+ for name in _DENOISER_DIRS
+ )
except OSError:
return False
@@ -1566,11 +1699,21 @@ def repo_pipeline_missing_denoiser(repo_info) -> bool:
multi-GB transformer (the GGUF supplies it). :func:`is_snapshot_partial` misses this (every
file the manifest expected did arrive), so callers OR the two signals together and mark such
rows partial. Best-effort: any scan error reports not-missing so a glitch never hides a
- genuinely complete pipeline."""
+ genuinely complete pipeline.
+
+ Judged by :func:`snapshot_pipeline_missing_denoiser` on the revision the loader opens, so the
+ compatibility ``/api/models/cached-models`` listing and the Hub inventory agree on a row. The
+ walk below it is only for a scan that records no ``snapshot_path``: with no directory there is
+ no manifest to read and no shard index to check."""
if not repo_has_pipeline_index(repo_info):
return False
try:
- for rev in _current_revisions(repo_info):
+ revisions = list(_current_revisions(repo_info))
+ scoped = [getattr(rev, "snapshot_path", None) for rev in revisions]
+ scoped = [snapshot for snapshot in scoped if snapshot is not None]
+ if scoped:
+ return all(snapshot_pipeline_missing_denoiser(Path(snapshot)) for snapshot in scoped)
+ for rev in revisions:
snapshot = getattr(rev, "snapshot_path", None)
for f in rev.files:
name = str(getattr(f, "file_name", "") or "")
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 4007597891d..1a075fc99c1 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -2,6 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import asyncio
+import json
import sys
import threading
import time
@@ -2833,8 +2834,20 @@ def test_pipeline_scans_read_the_snapshot_the_loader_will_open(tmp_path):
new_snap = repo_dir / "snapshots" / "new"
for d in (old_snap / "transformer", new_snap / "vae"):
d.mkdir(parents = True)
- (old_snap / "model_index.json").write_text("{}", encoding = "utf-8")
- (new_snap / "model_index.json").write_text("{}", encoding = "utf-8")
+ # A real manifest, not "{}": the scan reads the denoiser names off it, and one declaring none
+ # has nothing it can prove absent.
+ manifest = json.dumps(
+ {
+ "_class_name": "FluxPipeline",
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKL"],
+ }
+ )
+ (old_snap / "model_index.json").write_text(manifest, encoding = "utf-8")
+ (new_snap / "model_index.json").write_text(manifest, encoding = "utf-8")
+ # Real weights, not just the dirs: an empty transformer/ is a torn denoiser, not a present one.
+ (old_snap / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+ (new_snap / "vae" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
# Make "new" unambiguously newer than "old" for the mtime rule both this and the loader use.
os.utime(old_snap, (1_000_000, 1_000_000))
os.utime(new_snap, (2_000_000, 2_000_000))
@@ -2866,6 +2879,71 @@ def test_pipeline_scans_read_the_snapshot_the_loader_will_open(tmp_path):
assert scan.repo_pipeline_missing_denoiser(info) is False
+ "extra_files, manifest_extra",
+ [
+ # A dual-denoiser pipeline whose second expert never landed.
+ ({}, {"transformer_2": ["diffusers", "WanTransformer3DModel"]}),
+ # A single denoiser whose shard index names two shards and got one.
+ (
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {
+ "weight_map": {
+ "a": "diffusion_pytorch_model-00001-of-00002.safetensors",
+ "b": "diffusion_pytorch_model-00002-of-00002.safetensors",
+ }
+ }
+ ).encode(),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ },
+ {},
+ ),
+ ],
+ ids = ["dual-denoiser", "half-sharded"],
+)
+def test_both_cached_listings_agree_on_a_torn_pipeline(extra_files, manifest_extra, tmp_path):
+ # /api/models/cached-models ORs the repo-wide helper while the hub inventory calls the snapshot
+ # one, so a disagreement leaves a row the hub hides as partial still advertised as runnable.
+ import hub.utils.inventory_scan as scan
+
+ manifest = {
+ "_class_name": "WanPipeline",
+ "transformer": ["diffusers", "WanTransformer3DModel"],
+ "vae": ["diffusers", "AutoencoderKLWan"],
+ }
+ manifest.update(manifest_extra)
+ repo_dir = tmp_path / "models--Org--Repo"
+ snapshot = repo_dir / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ files = {
+ "model_index.json": json.dumps(manifest).encode(),
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ }
+ if not extra_files:
+ files["transformer/diffusion_pytorch_model.safetensors"] = b"\0" * 256
+ files.update(extra_files)
+ for name, blob in files.items():
+ target = snapshot / name
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_bytes(blob)
+ info = SimpleNamespace(
+ repo_id = "Org/Repo",
+ repo_path = repo_dir,
+ revisions = [
+ SimpleNamespace(
+ snapshot_path = snapshot,
+ last_modified = float(snapshot.stat().st_mtime),
+ files = [
+ SimpleNamespace(file_name = Path(n).name, file_path = snapshot / n) for n in files
+ ],
+ )
+ ],
+ )
+ assert scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+ assert scan.repo_pipeline_missing_denoiser(info) is True
+
+
def test_list_cached_models_flags_single_file_diffusion_repos(monkeypatch, tmp_path):
# A diffusion-tagged repo with NO top-level model_index.json is a single-file checkpoint (single_file=True); a full pipeline or chat repo carries no flag.
single = _repo(
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index b0fbfc3d8cc..9219c8fe94c 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import dataclasses
import json
import os
+import shutil
import stat
import tracemalloc
from pathlib import Path
@@ -3159,6 +3160,555 @@ def test_a_newer_companion_only_snapshot_does_not_make_the_ref_snapshot_partial(
assert rows[0]["single_file"] is False
+def _pipeline_snapshot(tmp_path, manifest: dict, files: dict) -> Path:
+ """A diffusers pipeline snapshot: root ``model_index.json`` plus component subdirs."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "model_index.json").write_bytes(json.dumps(manifest).encode())
+ for name, blob in files.items():
+ target = snapshot / name
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_bytes(blob)
+ return snapshot
+
+
+_FLUX_INDEX = {
+ "_class_name": "FluxPipeline",
+ "transformer": ["diffusers", "FluxTransformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKL"],
+ "safety_checker": [None, None],
+}
+# Trimmed from the real manifests of CalamitousFelicitousness/Ideogram-4-bf16-Diffusers and
+# Wan-AI/Wan2.2-T2V-A14B-Diffusers, which each ship two denoiser directories.
+_IDEOGRAM_INDEX = {
+ "_class_name": "Ideogram4Pipeline",
+ "transformer": ["diffusers", "Ideogram4Transformer2DModel"],
+ "unconditional_transformer": ["diffusers", "Ideogram4Transformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKLFlux2"],
+}
+_WAN_INDEX = {
+ "_class_name": "WanPipeline",
+ "transformer": ["diffusers", "WanTransformer3DModel"],
+ "transformer_2": ["diffusers", "WanTransformer3DModel"],
+ "vae": ["diffusers", "AutoencoderKLWan"],
+}
+# Wan-AI/Wan2.2-TI2V-5B-Diffusers declares transformer_2 as [null, null] and ships no such dir.
+_WAN_SINGLE_EXPERT_INDEX = dict(_WAN_INDEX, transformer_2 = [None, None])
+# Stable Cascade and friends call theirs "decoder"/"prior", so no key matches either fixed name.
+_CASCADE_INDEX = {
+ "_class_name": "StableCascadeDecoderPipeline",
+ "decoder": ["diffusers", "StableCascadeUNet"],
+ "text_encoder": ["transformers", "CLIPTextModelWithProjection"],
+ "vqgan": ["wuerstchen", "PaellaVQModel"],
+}
+
+
+def test_a_denoiser_missing_half_its_shards_is_not_a_present_denoiser(tmp_path):
+ """Shard 1 of 2 alone is not a present denoiser, and the last shard completes it."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {
+ "weight_map": {
+ "a": "diffusion_pytorch_model-00001-of-00002.safetensors",
+ "b": "diffusion_pytorch_model-00002-of-00002.safetensors",
+ }
+ }
+ ).encode(),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / "transformer" / "diffusion_pytorch_model-00002-of-00002.safetensors").write_bytes(
+ b"\0" * 256
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def _dual_format_shard_index(fmt: str) -> bytes:
+ return json.dumps(
+ {
+ "weight_map": {
+ "a": f"diffusion_pytorch_model-00001-of-00002{fmt}",
+ "b": f"diffusion_pytorch_model-00002-of-00002{fmt}",
+ }
+ }
+ ).encode()
+
+
+def test_an_unused_alternate_format_index_does_not_tear_a_whole_snapshot(tmp_path):
+ """Each index is judged on its own shard set, so a whole safetensors set stays whole beside the
+ orphan ``.bin.index.json`` a dual-format repo leaves behind."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": _dual_format_shard_index(
+ ".safetensors"
+ ),
+ "transformer/diffusion_pytorch_model.bin.index.json": _dual_format_shard_index(".bin"),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00002-of-00002.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_neither_format_being_whole_is_still_torn(tmp_path):
+ """The other direction: any-index-SATISFIED, not any-index-present."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": _dual_format_shard_index(
+ ".safetensors"
+ ),
+ "transformer/diffusion_pytorch_model.bin.index.json": _dual_format_shard_index(".bin"),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00001-of-00002.bin": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+# diffusers' _add_variant inserts the variant before the LAST extension, so a bf16 shard index is
+# "...safetensors.index.bf16.json", not "...bf16.safetensors.index.json".
+_VARIANT_INDEX_NAME = "diffusion_pytorch_model.safetensors.index.bf16.json"
+
+
+ "orphan_index, orphan_suffix",
+ [
+ ("diffusion_pytorch_model.bin.index.json", ".bin"),
+ (_VARIANT_INDEX_NAME, ".bf16.safetensors"),
+ ],
+)
+def test_an_orphan_variant_index_does_not_veto_the_default_weight(
+ orphan_index, orphan_suffix, tmp_path
+):
+ """An orphan variant index must not hide the unsharded default weight beside it."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ f"transformer/{orphan_index}": _dual_format_shard_index(orphan_suffix),
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_variant_only_component_is_missing_its_denoiser_whole_or_not(tmp_path):
+ """A dtype twin is not the weight a default load asks for, so a bf16 set does not make the
+ component readable -- not half landed, and not even whole.
+
+ ``from_pretrained`` without ``variant`` resolves the plain name and has no fallback to the
+ twin, raising ``Error no file named diffusion_pytorch_model.safetensors``. The download plan
+ skips those files for that reason, so a cache holding only them cannot serve this row.
+ """
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ f"transformer/{_VARIANT_INDEX_NAME}": _dual_format_shard_index(".bf16.safetensors"),
+ "transformer/diffusion_pytorch_model-00001-of-00002.bf16.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (
+ snapshot / "transformer" / "diffusion_pytorch_model-00002-of-00002.bf16.safetensors"
+ ).write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
[email protected]("whole_suffix", [".safetensors", ".bin"])
+def test_a_corrupt_selected_index_hides_the_whole_weight_beside_it(whole_suffix, tmp_path):
+ """An unreadable selected index is the failure, not an absence of evidence.
+
+ ``is_sharded`` is set from that file merely existing, so the parse then raises with neither the
+ ``except IOError`` branch nor the pickle fallback reachable. The whole weight beside it is
+ never opened.
+ """
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": b"{not json",
+ f"transformer/diffusion_pytorch_model{whole_suffix}": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_a_sharded_bin_set_is_not_what_a_default_load_resolves(tmp_path):
+ """``.bin`` shards behind their own index answer no default load: ``use_safetensors`` unset
+ coerces to True, so only the safetensors index name is built, and with none found the loader
+ asks for the UNSHARDED ``diffusion_pytorch_model.bin``, which a sharded set does not provide."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.bin.index.json": _dual_format_shard_index(".bin"),
+ "transformer/diffusion_pytorch_model-00001-of-00002.bin": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00002-of-00002.bin": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_the_legacy_variant_index_spelling_does_not_vouch_either(tmp_path):
+ """``_fetch_index_file_legacy`` spells the variant BEFORE ``.index``, so a deprecated fp16 set
+ ends in ``.index.json`` and a load passing no ``variant`` still never resolves it."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.fp16.index.json": (
+ _dual_format_shard_index(".fp16.safetensors")
+ ),
+ "transformer/diffusion_pytorch_model-00001-of-00002.fp16.safetensors": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00002-of-00002.fp16.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_shards_whose_index_never_landed_do_not_stand_in_for_the_whole_weight(tmp_path):
+ """A numbered shard is only ever reached THROUGH an index, so a complete set whose index is
+ missing -- or, as here, a dangling blob symlink the cache already collected -- is wreckage
+ rather than a loose weight."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00002-of-00002.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ dangling = snapshot / "transformer" / "diffusion_pytorch_model.safetensors.index.json"
+ dangling.symlink_to(tmp_path / "blobs" / "collected")
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+ "default_name", ["diffusion_pytorch_model.safetensors", "diffusion_pytorch_model.bin"]
+)
+def test_an_ignored_index_cannot_claim_the_default_weight(default_name, tmp_path):
+ """A map naming the file a default load opens does not hide it.
+
+ Every index that gets to claim shards here is one ``_fetch_index_file`` never builds, so a
+ stale or malformed ``.bin`` map naming the default weight would otherwise suppress the only
+ file ``_get_model_file`` asks for and report a loadable component torn.
+ """
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ f"transformer/{default_name}": b"\0" * 256,
+ "transformer/diffusion_pytorch_model.bin.index.json": json.dumps(
+ {"weight_map": {"a": default_name}}
+ ).encode(),
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_weight_under_a_name_the_loader_never_asks_for_does_not_count(tmp_path):
+ """With no index the component is unsharded to the loader too, and ``_get_model_file`` is
+ handed ``diffusion_pytorch_model.safetensors`` and then the ``.bin`` under it and opens nothing
+ else. A transformers-style ``model.safetensors``, or an adapter sidecar, is never resolved."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/model.safetensors": b"\0" * 256,
+ "transformer/adapter_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / "transformer" / "diffusion_pytorch_model.bin").write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_selected_index_naming_a_non_weight_file_is_not_a_checkpoint(tmp_path):
+ """The loader reads every mapped name as a checkpoint, so a map pointing at the ``config.json``
+ beside it fails at load however present that file is."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/config.json": b"{}",
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {"weight_map": {"a": "config.json"}}
+ ).encode(),
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_an_unsharded_dtype_twin_alone_is_not_the_default_weight(tmp_path):
+ """The same rule with no index in sight: the twin a ``variant = "fp16"`` load left behind is
+ the only weight here, and the default load this app issues cannot open it."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {"transformer/diffusion_pytorch_model.fp16.safetensors": b"\0" * 256},
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / "transformer" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_pipeline_declaring_no_denoiser_key_is_not_hunted_for_one(tmp_path):
+ """Stable Cascade names its denoiser ``decoder``, so neither fixed name is in the manifest.
+ Nothing here can be proved absent, and the complete pipeline must not be hidden as partial."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _CASCADE_INDEX,
+ {
+ "decoder/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ "vqgan/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_manifest_entry_that_is_not_a_component_pair_is_left_to_the_loader(tmp_path):
+ """JaiDalmotra/ACE-STEP-Stereo-Finetuned maps "transformer" to a dict pointing at
+ ace_step_transformer/ and ships no transformer/ at all. An entry that is not a
+ [library, class] pair names no directory, so demanding one would hide the whole repo."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ {
+ "_class_name": "ACEStepPipeline",
+ "transformer": {
+ "_class_name": "ACEStepTransformer2DModel",
+ "config": "ace_step_transformer/config.json",
+ },
+ },
+ {"ace_step_transformer/diffusion_pytorch_model.safetensors": b"\0" * 256},
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+ "denoisers",
+ [
+ # weizhou03/HunyuanVideo-1.5-Diffusers-1080p-2SR runs three.
+ ("transformer", "transformer_2", "transformer_3"),
+ # BoyuanJiang/FitDiT has no "transformer" key at all.
+ ("transformer_garm", "transformer_vton"),
+ ],
+)
+def test_the_manifest_keys_generalise_past_the_names_we_knew(denoisers, tmp_path):
+ """Reading the names off the manifest keeps this right for layouts no hardcoded list
+ anticipated, without another edit here."""
+ manifest = {"_class_name": "SomePipeline", "vae": ["diffusers", "AutoencoderKL"]}
+ manifest.update({name: ["diffusers", "SomeTransformer2DModel"] for name in denoisers})
+ files = {f"{name}/diffusion_pytorch_model.safetensors": b"\0" * 256 for name in denoisers}
+ snapshot = _pipeline_snapshot(tmp_path, manifest, files)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+ shutil.rmtree(snapshot / denoisers[-1])
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_a_declared_but_null_second_expert_is_not_a_missing_denoiser(tmp_path):
+ """Wan 2.2's 5B sibling declares ``transformer_2`` as [null, null] and ships no such directory:
+ the manifest saying the slot is deliberately empty, not a torn download."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _WAN_SINGLE_EXPERT_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_half_landed_shard_set_is_not_rescued_by_the_loose_scan(tmp_path):
+ """The loose fallback skips claimed names, so shard 1 of 2 cannot pose as the whole set."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": (
+ _dual_format_shard_index(".safetensors")
+ ),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
[email protected]("escape", ["../vae/diffusion_pytorch_model.safetensors", "/absolute"])
+def test_a_denoiser_index_naming_a_shard_outside_the_component_is_not_a_denoiser(escape, tmp_path):
+ """``component / shard`` follows ``..`` to a sibling and drops the component entirely for an
+ absolute name, so a corrupt map could be satisfied by the vae next door."""
+ outside = tmp_path / "outside.safetensors"
+ outside.write_bytes(b"\0" * 256)
+ shard = str(outside) if escape == "/absolute" else escape
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {"weight_map": {"a": shard}}
+ ).encode(),
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
[email protected](os.name == "nt", reason = "a directory called C: cannot exist on Windows")
+def test_a_drive_qualified_shard_name_is_outside_the_component_everywhere(tmp_path):
+ """The escape above, spelled the way a Windows-written index spells it.
+
+ ``PurePosixPath`` reads ``C:/pipe/...`` as a subdirectory literally called ``C:``, so without a
+ drive check the name resolves to a real file here, while on Windows the same join discards the
+ component and reaches the drive root. It has to read as the escape on both.
+ """
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {"weight_map": {"a": "C:/pipe/diffusion_pytorch_model.safetensors"}}
+ ).encode(),
+ "transformer/C:/pipe/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_a_denoiser_index_short_of_the_total_its_shard_names_declare_is_torn(tmp_path):
+ """An index truncated to shard 1 of 2 satisfies every name it maps, but the loader opens the
+ map and nothing else, so the omitted half is dropped silently."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": json.dumps(
+ {"weight_map": {"a": "diffusion_pytorch_model-00001-of-00002.safetensors"}}
+ ).encode(),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / "transformer" / "diffusion_pytorch_model-00002-of-00002.safetensors").write_bytes(
+ b"\0" * 256
+ )
+ (snapshot / "transformer" / "diffusion_pytorch_model.safetensors.index.json").write_bytes(
+ _dual_format_shard_index(".safetensors")
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+def test_a_whole_bin_set_does_not_stand_in_for_the_selected_safetensors_index(tmp_path):
+ """Only diffusion_pytorch_model.safetensors.index.json is resolved here, and finding it makes
+ the component sharded, gating out the IOError handler and the pickle fallback below it. The
+ whole .bin set beside it is never opened, so it cannot vouch for the component."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors.index.json": (
+ _dual_format_shard_index(".safetensors")
+ ),
+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": b"\0" * 256,
+ "transformer/diffusion_pytorch_model.bin.index.json": _dual_format_shard_index(".bin"),
+ "transformer/diffusion_pytorch_model-00001-of-00002.bin": b"\0" * 256,
+ "transformer/diffusion_pytorch_model-00002-of-00002.bin": b"\0" * 256,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+
+def test_an_unsharded_denoiser_still_passes_on_presence_alone(tmp_path):
+ """No index, so nothing to be incomplete against: presence alone stands."""
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {"transformer/diffusion_pytorch_model.safetensors": b"\0" * 256},
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+ "manifest, second",
+ [
+ (_IDEOGRAM_INDEX, "unconditional_transformer"),
+ (_WAN_INDEX, "transformer_2"),
+ ],
+)
+def test_a_multi_denoiser_pipeline_needs_every_denoiser_it_declares(manifest, second, tmp_path):
+ """Ideogram 4 and the dual-expert video pipelines declare two denoisers, so both must be on
+ disk before the snapshot reads as complete."""
+ files = {
+ "transformer/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ "vae/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ }
+ snapshot = _pipeline_snapshot(tmp_path, manifest, files)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / second).mkdir()
+ (snapshot / second / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
+ "target, missing",
+ [
+ ("model_index.json", False),
+ ("transformer/diffusion_pytorch_model.safetensors.index.json", True),
+ ],
+)
+def test_json_too_deep_to_parse_is_contained_rather_than_raising(target, missing, tmp_path):
+ """json.load raises RecursionError, which is neither a ValueError nor an OSError, so an
+ unguarded parse would escape past the caller and drop the row from the scan entirely.
+
+ Contained is not ignored, and which one it is depends on the file. An unreadable MANIFEST
+ proves nothing about the denoiser, so the row stays. An unreadable SELECTED INDEX is the
+ failure itself, since the whole weight lying beside it is then never opened.
+ """
+ snapshot = _pipeline_snapshot(
+ tmp_path,
+ _FLUX_INDEX,
+ {
+ "transformer/diffusion_pytorch_model.safetensors": b"\0" * 256,
+ target: b"[" * 20000 + b"]" * 20000,
+ },
+ )
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is missing
+
+
+def test_an_unreadable_manifest_keeps_the_fixed_denoiser_pair(tmp_path):
+ """A corrupt manifest falls back to the fixed pair, rather than reading as a pipeline that
+ declares no denoiser and is complete by default."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "model_index.json").write_bytes(b"{not json")
+ (snapshot / "vae").mkdir()
+ (snapshot / "vae" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is True
+
+ (snapshot / "unet").mkdir()
+ (snapshot / "unet" / "diffusion_pytorch_model.safetensors").write_bytes(b"\0" * 256)
+ assert inventory_scan.snapshot_pipeline_missing_denoiser(snapshot) is False
+
+
def _snapshot_with(tmp_path, files: dict) -> Path:
snapshot = tmp_path / "snap"
snapshot.mkdir()