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.

Studio: validate legacy sd binary discovery (#8560)

Long Yixing22cb12ec65c8
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index f0c3b92f9a8..ee7fd13c7fc 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -71,6 +71,7 @@ from core.inference.sd_cpp_engine import (
SdCppEngine,
find_sd_cpp_binary,
find_sd_server_binary,
+ help_text_identifies_sd_cpp,
is_managed_binary,
legacy_sibling_install_root,
managed_install_root,
@@ -294,7 +295,29 @@ def sd_cpp_supports_minimax_h3(binary: str) -> bool:
text = _sd_cpp_probe_output(binary, "--help")
if text is None:
return True
- return _H3_HELP_MARKER in text
+ return help_text_supports_minimax_h3(text)
+
+
+def help_text_supports_minimax_h3(help_text: str) -> bool:
+ """``sd_cpp_supports_minimax_h3``'s verdict on ``--help`` output that is already in hand."""
+ return _H3_HELP_MARKER in help_text
+
+
+def sd_cpp_binary_vets_for_h3(binary: str) -> bool:
+ """Both of ``ensure_h3_sd_cpp_binary``'s questions against a live binary, on ONE ``--help``.
+
+ The capability marker cannot stand alone here. ``--ref-video`` is a plain option name that
+ unrelated reference-video tools expose too, so a caller re-checking only capability would
+ accept a program the gate itself would have refused on identity -- the difference between
+ "an sd.cpp build too old for H3" and "not sd.cpp at all" (#8507).
+
+ Same conservative default as ``sd_cpp_supports_minimax_h3``: an unreadable ``--help`` is
+ "could not tell", and the caller's own ``version()`` gate already refuses a binary that will
+ not run."""
+ text = _sd_cpp_probe_output(binary, "--help")
+ if text is None:
+ return True
+ return help_text_identifies_sd_cpp(text) and help_text_supports_minimax_h3(text)
def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:
@@ -311,12 +334,23 @@ def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:
is nothing to run on the GPU at all."""
if not binary:
return False
+ verdict = sd_cpp_accelerator_device_verdict(binary)
+ return True if verdict is None else verdict
+
+
+def sd_cpp_accelerator_device_verdict(binary: str) -> Optional[bool]:
+ """``sd_cpp_lists_accelerator_device`` without the conservative default: None means the probe
+ said nothing usable, rather than being folded into "assume it has one".
+
+ A caller COMPARING two readings needs that apart. Against a recorded decision, the collapsed
+ True is indistinguishable from a real accelerator, so an unreadable re-probe would read as a
+ build that changed underneath the load and refuse it."""
text = _sd_cpp_probe_output(binary, "--list-devices")
if text is None:
- return True
+ return None
names = [line.split("\t", 1)[0].strip() for line in text.splitlines() if "\t" in line]
if not names:
- return True
+ return None
return any(name.upper() != "CPU" for name in names)
@@ -357,28 +391,69 @@ def ensure_h3_sd_cpp_binary(
``ensure_sd_cpp_binary`` hands back whatever ``find_sd_cpp_binary`` locates and only probes
runnability, so an install that predates H3 (an upgraded Studio still carrying an older managed
- sd-cli) is returned unchanged, the H3 load reports ready on it, and the first generation fails
- only AFTER the multi-tens-of-GB bundle has downloaded. Only this path is stricter: image
- generation must keep working on any user-supplied build.
+ sd-cli) is returned unchanged, the H3 load reports ready on it, and the first generation fails.
+ Only this path is stricter: image generation must keep working on any user-supplied build. Its
+ caller runs it BEFORE resolving the H3 assets, so a refusal costs no download.
A stale copy we own is deleted so the installer puts the pinned prebuilt back; a user's own
build is left alone and the load fails with a message naming it, the same ownership split
``_usable_or_discard_managed`` makes. Returns None when no H3-capable binary can be produced.
+
+ A user-supplied binary that is not stable-diffusion.cpp AT ALL gets its own message: "no H3
+ options" is true of every unrelated program, and reporting it as an outdated build is what sent
+ #8507 looking for a newer stable-diffusion.cpp that was never installed.
"""
binary = ensure_sd_cpp_binary(allow_install = allow_install, accelerator = accelerator)
- if not binary or sd_cpp_supports_minimax_h3(binary):
+ if not binary:
+ return binary
+ # ONE --help, two questions: is this stable-diffusion.cpp, and does this build carry H3. A
+ # second spawn would double the cost of the refusal path and could read a different build than
+ # the one just judged. None is "could not tell", which stays conservative on both counts.
+ #
+ # Conservative HERE means keeping the binary, the opposite of the engine's identity probe, which
+ # rejects on an unreadable one. Not an inconsistency to iron out: this decides whether to refuse
+ # a binary the user chose, where a probe failure must not take native video away from a working
+ # build, while the engine decides whether to ADOPT an ambiguously named PATH candidate on no
+ # evidence at all. Opposite questions, so opposite safe defaults.
+ help_text = _sd_cpp_probe_output(binary, "--help")
+ if help_text is None:
return binary
+ # Identity BEFORE capability, never the marker alone. --ref-video is a plain option name that
+ # unrelated reference-video tools also expose, so returning early on it would readmit exactly
+ # the class of program #8507 was about -- through SD_CLI_PATH instead of PATH. Upstream added
+ # H3 eight months after print_usage started with the project banner, so a genuine H3 build
+ # always answers both.
+ identified = help_text_identifies_sd_cpp(help_text)
+ if identified and help_text_supports_minimax_h3(help_text):
+ return binary
+ # What is wrong with it, for the log lines on the managed path below: a managed copy that is not
+ # sd.cpp at all is still deleted and reinstalled, but calling it an old build would be false.
+ fault = "does not advertise MiniMax-H3 support" if identified else "is not stable-diffusion.cpp"
if not is_managed_binary(binary):
+ # Not an old sd.cpp -- not sd.cpp at all. Worth its own message: the H3 marker is missing
+ # from EVERY program that is not stable-diffusion.cpp, so reporting the capability verdict
+ # here sent users hunting for a newer build of something they never installed (#8507, where
+ # the binary was Debian/Ubuntu's `sd` find-and-replace tool). Discovery already skips an
+ # unrelated PATH `sd`, so what reaches this line came from somewhere the identity gate does
+ # not cover -- an SD_CLI_PATH / UNSLOTH_SD_CPP_PATH override, an in-tree developer build, or
+ # a PATH `sd-cli`. None of them is ours to overwrite, so all four say so and stop.
+ if not identified:
+ raise RuntimeError(
+ f"The executable at {binary} is not stable-diffusion.cpp: its --help output does "
+ f"not identify the project. Point SD_CLI_PATH at a stable-diffusion.cpp build from "
+ f"master-812-ea7f0c8 or newer, or UNSLOTH_SD_CPP_PATH at the directory holding one"
+ f"{_h3_replacement_hint(binary)}."
+ )
raise RuntimeError(
f"The stable-diffusion.cpp binary at {binary} does not advertise MiniMax-H3 support "
- f"(its --help does not list the H3 options), so generation would fail after the whole "
- f"H3 bundle has downloaded. Point SD_CLI_PATH at a build from master-812-ea7f0c8 or "
+ f"(its --help does not list the H3 options), so generation would fail on it. "
+ f"Point SD_CLI_PATH at a build from master-812-ea7f0c8 or "
f"newer, or UNSLOTH_SD_CPP_PATH at the directory holding one"
f"{_h3_replacement_hint(binary)}."
)
if not allow_install:
# Ours, but replacing it is exactly what auto-install is switched off for.
- logger.warning("managed sd.cpp binary %s predates MiniMax-H3 support", binary)
+ logger.warning("managed sd.cpp binary %s %s", binary, fault)
return None
# Deleting it is a WRITE to the managed tree, so it takes the same admission an install does.
# An image one-shot may be executing this very file: on Linux the running child survives the
@@ -388,14 +463,16 @@ def ensure_h3_sd_cpp_binary(
with _tree_claimed_for_install() as claimed:
if not claimed:
logger.warning(
- "managed sd.cpp binary %s predates MiniMax-H3 support, but something is still "
- "running out of the managed install; retrying on a later load",
+ "managed sd.cpp binary %s %s, but something is still running out of the "
+ "managed install; retrying on a later load",
binary,
+ fault,
)
return None
logger.warning(
- "managed sd.cpp binary %s predates MiniMax-H3 support; removing it so it reinstalls",
+ "managed sd.cpp binary %s %s; removing it so it reinstalls",
binary,
+ fault,
)
try:
Path(binary).unlink()
diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.py
index faa19f6ed08..e7bb626b161 100644
--- a/studio/backend/core/inference/sd_cpp_engine.py
+++ b/studio/backend/core/inference/sd_cpp_engine.py
@@ -29,6 +29,7 @@ from typing import Callable, Iterator, Optional
from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid
from utils.native_path_leases import child_env_without_native_path_secret
+from utils.subprocess_compat import windows_hidden_subprocess_kwargs
from core.inference.sd_cpp_args import (
SdCppGenParams,
SdCppModelFiles,
@@ -45,6 +46,9 @@ logger = logging.getLogger(__name__)
# sd-cli (sd-cli.exe on Windows); older builds shipped ``sd`` -- both probed on PATH.
_BINARY_STEM = "sd-cli"
_LEGACY_STEM = "sd"
+# The first stable-diffusion.cpp release already exposed all three. Together they distinguish its
+# oldest help text (before it printed the project name) from unrelated tools also called ``sd``.
+_LEGACY_HELP_MARKERS = ("--negative-prompt", "--cfg-scale", "--steps")
# The persistent HTTP server target, shipped next to sd-cli in both prebuilt and cmake builds.
_SERVER_STEM = "sd-server"
@@ -229,6 +233,135 @@ def _first_file(paths: list[Path]) -> Optional[str]:
return None
+# Identity verdicts, keyed by the file itself rather than by the path alone, so replacing a binary
+# in place re-probes it while a rebuild elsewhere on PATH is unaffected. Bounded: a Studio session
+# sees a handful of candidates, and a runaway key set would only ever come from a path being
+# rewritten under us, which is exactly the case that must not be served from here.
+_IDENTITY_MEMO: dict[tuple[str, int, int, int], tuple[bool, float]] = {}
+_IDENTITY_MEMO_LOCK = threading.Lock()
+_IDENTITY_MEMO_MAX = 32
+# How long a verdict may answer for. The key catches the replacements it can SEE, but no stat tuple
+# is a content hash: on Windows ``st_ctime`` is the CREATION time, which an in-place overwrite
+# preserves, so a same-sized write that also restores mtime is invisible to it. Hashing the file on
+# every lookup would trade the exec this memo exists to avoid for a read of the whole binary, on a
+# path walked for every load. A short life is the cheaper guarantee and it is not platform-specific:
+# whatever the key misses, and whatever nobody has thought of, expires within a minute. Long enough
+# for its actual job, which is the several resolutions inside one load sequence.
+_IDENTITY_MEMO_TTL_S = 60.0
+
+
+def _identity_key(binary: str) -> Optional[tuple[str, int, int, int]]:
+ """A cache key that changes whenever ``binary``'s content is SEEN to change, or None when it
+ cannot be read -- an unreadable candidate is never memoized, so a file that appears later is
+ probed.
+
+ ``st_ctime`` as well as ``st_mtime``: metadata-preserving copies (``cp -p``, ``shutil.copy2``,
+ an archive carrying source timestamps) restore the modification time of the file they replace,
+ so on POSIX a same-sized replacement is otherwise indistinguishable from the binary it
+ overwrote, and the inode change time is not restorable that way. It is NOT a content revision
+ on Windows, where the field is the creation time and survives an in-place overwrite -- hence
+ the TTL above, which is what actually bounds a stale verdict."""
+ try:
+ st = os.stat(binary)
+ except OSError:
+ return None
+ return (str(Path(binary).resolve(strict = False)), st.st_mtime_ns, st.st_ctime_ns, st.st_size)
+
+
+def help_text_identifies_sd_cpp(help_text: str) -> bool:
+ """Whether ``--help`` output belongs to stable-diffusion.cpp.
+
+ Identity, NOT capability: "is this the right program at all", which is a different question
+ from ``sd_cpp_supports_minimax_h3``'s "does this build carry the H3 options". Accepts the
+ project banner (current upstream's ``print_usage`` prints ``stable-diffusion.cpp version ...``
+ first) or the full legacy option signature, which is what the pre-banner builds -- the ones
+ that shipped the binary as ``sd`` -- print instead.
+
+ Pure, so a caller that has already paid for the ``--help`` output can reuse it rather than
+ spawning the binary a second time.
+ """
+ return "stable-diffusion.cpp" in help_text.lower() or all(
+ marker in help_text for marker in _LEGACY_HELP_MARKERS
+ )
+
+
+def sd_cpp_binary_identifies(binary: str) -> bool:
+ """``help_text_identifies_sd_cpp`` against a live ``binary``.
+
+ Fails CLOSED: every caller is deciding whether to trust an ambiguously named executable, and a
+ probe that cannot be read is no evidence that it is the one we want. Memoized per file
+ revision -- discovery runs on every load and ``ensure_sd_cpp_binary`` alone resolves twice, so
+ without this a candidate that hangs costs its full timeout again on each one.
+
+ Only a DECISIVE verdict is memoized, because the key cannot see the difference. A timeout, a
+ failed spawn, or a non-zero exit with nothing identifying in the output are all "could not
+ tell", and none of them touches the file, so its key is unchanged -- caching that "no" would
+ blacklist a genuine build for the life of the process over one slow ``--help`` under memory
+ pressure, or over a missing shared library the user then installs. Same rule as
+ ``utils.node_runtime``, which memoizes only an adequate result so a runtime installed after the
+ first probe is still picked up.
+
+ A clean exit that simply is not stable-diffusion.cpp IS decisive, which is the case that
+ matters: Debian/Ubuntu's ``sd`` answers ``--help`` with rc 0, so the candidate this exists to
+ stop re-executing is still probed exactly once.
+ """
+ key = _identity_key(binary)
+ if key is not None:
+ now = time.monotonic()
+ with _IDENTITY_MEMO_LOCK:
+ cached = _IDENTITY_MEMO.get(key)
+ if cached is not None and now - cached[1] > _IDENTITY_MEMO_TTL_S:
+ _IDENTITY_MEMO.pop(key, None)
+ cached = None
+ if cached is not None:
+ return cached[0]
+ returncode = None
+ try:
+ result = subprocess.run(
+ [binary, "--help"],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 10,
+ check = False,
+ env = runtime_env(binary),
+ **windows_hidden_subprocess_kwargs(),
+ )
+ help_text = (result.stdout or "") + "\n" + (result.stderr or "")
+ returncode = result.returncode
+ except (OSError, subprocess.SubprocessError):
+ help_text = ""
+ identified = help_text_identifies_sd_cpp(help_text)
+ # Identifying output settles it whatever the exit code (old builds print usage and exit 1).
+ # Otherwise only a clean exit is evidence of anything; rc 127 from the dynamic loader is not.
+ decisive = identified or returncode == 0
+ if key is not None and decisive:
+ with _IDENTITY_MEMO_LOCK:
+ if len(_IDENTITY_MEMO) >= _IDENTITY_MEMO_MAX:
+ _IDENTITY_MEMO.clear()
+ _IDENTITY_MEMO[key] = (identified, time.monotonic())
+ return identified
+
+
+def _is_legacy_sd_cpp_binary(binary: str) -> bool:
+ """Whether an ambiguous PATH executable named ``sd`` identifies as stable-diffusion.cpp.
+
+ The PATH fallback is the one hop that picks a candidate purely by filename, and ``sd`` is a
+ name Debian and Ubuntu already ship an unrelated find-and-replace utility under, so accepting
+ it on the name alone pointed native diffusion at the wrong program AND suppressed the managed
+ install (#8507). Rejecting one is read-only: the unrelated command is left exactly as it is.
+ """
+ identified = sd_cpp_binary_identifies(binary)
+ if not identified:
+ logger.warning(
+ "ignoring PATH executable %s named sd because its --help output does not identify "
+ "stable-diffusion.cpp",
+ binary,
+ )
+ return identified
+
+
def managed_install_root() -> Path:
"""The directory the prebuilt installer owns, so callers can tell a Studio-managed binary
from a user-supplied one (SD_CLI_PATH / UNSLOTH_SD_CPP_PATH / PATH / an in-tree build).
@@ -407,7 +540,7 @@ def _find_binary(
# 5. PATH.
for stem in path_stems:
on_path = shutil.which(stem)
- if on_path:
+ if on_path and (stem != _LEGACY_STEM or _is_legacy_sd_cpp_binary(on_path)):
return on_path
return None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 30ac1ae37ff..706aec01d06 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1498,6 +1498,76 @@ class VideoBackend:
filename = gguf_filename or ""
qwen_filename = h3_text_encoder_filename(filename)
+
+ # BEFORE the download, not after it. The H3-gated ensure, not the plain one: a build that
+ # predates H3 runs fine and so clears the version() gate below, then aborts on the first
+ # generation. That is the whole reason this gate exists, and running it after the four-file
+ # bundle had already been fetched meant the user still paid tens of GB to be told no.
+ #
+ # Cancel first, though: the ensure below may download and extract the sd-cli prebuilt, and
+ # it takes no cancel_event, so a load cancelled before this thread got going would pay for
+ # an install nobody is waiting for. The download loop used to be the first check.
+ if cancel_event.is_set():
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
+ target = resolve_diffusion_device_target()
+ allow_install = _install_allowed()
+ binary = ensure_h3_sd_cpp_binary(
+ allow_install = allow_install,
+ accelerator = _install_accelerator_for(target.backend),
+ )
+ native_device = target.device
+ # What the accelerator decision below was made on, or None when it was never asked (a CPU
+ # or MPS target never consults it). Re-checked under the reader claim, so a replacement
+ # that arrives mid-load cannot silently change the answer this device choice rests on.
+ listed_accelerator: Optional[bool] = None
+ if target.backend not in ("cpu", "mps"):
+ # Under the claim, like the recheck. This probe SPAWNS the managed sd-cli, so leaving
+ # it unclaimed lets an install started by another in-process load extract over the
+ # executing binary: on Windows that fails on the locked file, on Linux it can leave
+ # the replacement half-written. The later claimed recheck cannot undo damage this
+ # first probe already allowed.
+ from .sd_cpp_backend import _tree_reader as _claim_tree
+ with _claim_tree(binary, cancel_event, VIDEO_CANCELLED_MSG):
+ listed_accelerator = sd_cpp_lists_accelerator_device(binary)
+ if target.backend not in ("cpu", "mps") and not listed_accelerator:
+ # Upstream currently publishes no Linux CUDA archive. Keep the picker
+ # functional with the CPU prebuilt when the user has not supplied a
+ # locally compiled CUDA binary through the normal sd.cpp discovery path.
+ #
+ # The test is what the binary actually offers, not whether one was returned: the
+ # accelerator install fails only ONCE, and every later load finds the CPU binary this
+ # branch put there and gets it back unchanged. "binary is truthy" therefore skipped
+ # the fallback from the second load on, left native_device on the GPU, and applied GPU
+ # offload policy and held the VIDEO claim while sd-cli ran wholly on the CPU -- so the
+ # next chat/image acquire evicted a model to make room for one that was never there.
+ binary = ensure_h3_sd_cpp_binary(allow_install = allow_install, accelerator = "cpu")
+ native_device = "cpu"
+ # The baseline this branch is compared against is the DECISION, not a fresh probe of
+ # what came back. An install can replace the returned CPU binary with a GPU build
+ # between that ensure and this line, and probing here would record ITS answer -- after
+ # which the re-check under the claim below compares the replacement against itself,
+ # passes, and commits CPU resource accounting around a CUDA executable that runs on
+ # VRAM nothing accounted for. native_device is "cpu" precisely because the build must
+ # offer no accelerator device, so that -- False -- is what the claim has to still find.
+ listed_accelerator = False
+ # And refuse a preflight that produced nothing, HERE rather than at the claimed re-vet
+ # below. ensure_h3_sd_cpp_binary legitimately returns None -- auto-install switched off, an
+ # unsupported platform, no network, or a stale managed copy something else is running out
+ # of -- and leaving the only `not binary` check after the download loop meant every one of
+ # those cases still fetched the four-file bundle first. The re-vet keeps its own check: it
+ # guards a replacement arriving mid-download, which is a different question.
+ if not binary:
+ raise RuntimeError(
+ "stable-diffusion.cpp could not be installed or started for MiniMax-H3."
+ )
+ # And again on the way out. The ensure above takes no cancel_event and can spend minutes
+ # downloading and extracting the prebuilt, so a cancel arriving during it is already late;
+ # without this a CPU or MPS target (which skips the claimed accelerator probe, the only
+ # other cancel-aware step here) would go on to make four sequential model_info calls before
+ # the download loop finally noticed.
+ if cancel_event.is_set():
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
+
requests = (
(repo_id, filename),
(self._h3_text_encoder_repo(repo_id, qwen_filename), qwen_filename),
@@ -1550,50 +1620,6 @@ class VideoBackend:
raise h3_download_error(repo, wanted, exc) from exc
resolved.append(local)
- target = resolve_diffusion_device_target()
- allow_install = _install_allowed()
- # The H3-gated ensure, not the plain one: a build that predates H3 runs fine and so clears
- # the version() gate below, then aborts on the first generation, i.e. after the whole
- # bundle has downloaded.
- binary = ensure_h3_sd_cpp_binary(
- allow_install = allow_install,
- accelerator = _install_accelerator_for(target.backend),
- )
- native_device = target.device
- # What the accelerator decision below was made on, or None when it was never asked (a CPU
- # or MPS target never consults it). Re-checked under the reader claim, so a replacement
- # that arrives mid-load cannot silently change the answer this device choice rests on.
- listed_accelerator: Optional[bool] = None
- if target.backend not in ("cpu", "mps"):
- # Under the claim, like the recheck. This probe SPAWNS the managed sd-cli, so leaving
- # it unclaimed lets an install started by another in-process load extract over the
- # executing binary: on Windows that fails on the locked file, on Linux it can leave
- # the replacement half-written. The later claimed recheck cannot undo damage this
- # first probe already allowed.
- from .sd_cpp_backend import _tree_reader as _claim_tree
- with _claim_tree(binary, cancel_event, VIDEO_CANCELLED_MSG):
- listed_accelerator = sd_cpp_lists_accelerator_device(binary)
- if target.backend not in ("cpu", "mps") and not listed_accelerator:
- # Upstream currently publishes no Linux CUDA archive. Keep the picker
- # functional with the CPU prebuilt when the user has not supplied a
- # locally compiled CUDA binary through the normal sd.cpp discovery path.
- #
- # The test is what the binary actually offers, not whether one was returned: the
- # accelerator install fails only ONCE, and every later load finds the CPU binary this
- # branch put there and gets it back unchanged. "binary is truthy" therefore skipped
- # the fallback from the second load on, left native_device on the GPU, and applied GPU
- # offload policy and held the VIDEO claim while sd-cli ran wholly on the CPU -- so the
- # next chat/image acquire evicted a model to make room for one that was never there.
- binary = ensure_h3_sd_cpp_binary(allow_install = allow_install, accelerator = "cpu")
- native_device = "cpu"
- # The baseline this branch is compared against is the DECISION, not a fresh probe of
- # what came back. An install can replace the returned CPU binary with a GPU build
- # between that ensure and this line, and probing here would record ITS answer -- after
- # which the re-check under the claim below compares the replacement against itself,
- # passes, and commits CPU resource accounting around a CUDA executable that runs on
- # VRAM nothing accounted for. native_device is "cpu" precisely because the build must
- # offer no accelerator device, so that -- False -- is what the claim has to still find.
- listed_accelerator = False
engine = SdCppEngine(binary)
# Re-vet and take the identity under ONE reader claim. ensure_h3_sd_cpp_binary checked the
# file it returned, but an install can start between that return and this line, and an
@@ -1601,7 +1627,11 @@ class VideoBackend:
# checked for H3 support or the selected accelerator -- after which every generation
# compares the replacement against itself and lets it through. Inside the claim no install
# can start, so the build that answers --help here is the build whose identity is stored.
- from .sd_cpp_backend import _tree_reader, sd_cpp_supports_minimax_h3
+ from .sd_cpp_backend import (
+ _tree_reader,
+ sd_cpp_accelerator_device_verdict,
+ sd_cpp_binary_vets_for_h3,
+ )
from .sd_cpp_engine import is_managed_binary
with _tree_reader(binary, cancel_event, VIDEO_CANCELLED_MSG):
@@ -1609,10 +1639,22 @@ class VideoBackend:
raise RuntimeError(
"stable-diffusion.cpp could not be installed or started for MiniMax-H3."
)
- if is_managed_binary(binary) and not sd_cpp_supports_minimax_h3(binary):
+ # EVERY binary, not just a managed one. The managed-only test was written when the
+ # ensure sat right here, so a user-supplied build had been vetted microseconds earlier
+ # and only a concurrent INSTALL could have moved underneath it. The preflight now runs
+ # before the multi-tens-of-GB download, so the window it has to cover is that whole
+ # download -- long enough for a user to rebuild or repoint their own SD_CLI_PATH copy,
+ # after which _sd_cli_identity below would record the replacement as the vetted build
+ # and every later generation would compare it against itself.
+ # Identity AND capability, the same pair the preflight applied. Capability alone is
+ # not enough: --ref-video is a plain option name unrelated reference-video tools also
+ # expose, so a swap to one of those would clear a marker-only re-check and then be
+ # recorded as the vetted identity.
+ if not sd_cpp_binary_vets_for_h3(binary):
raise RuntimeError(
- "The stable-diffusion.cpp binary was replaced by an install that does not "
- "support MiniMax-H3. Try the load again."
+ "The stable-diffusion.cpp binary changed while this model was loading, and the "
+ "one now at that path is not an sd.cpp build with MiniMax-H3 support. Try the "
+ "load again."
)
# And re-ask the question native_device was decided on. H3 support alone is not
# enough: a replacement can be H3-capable and still be a different accelerator, and
@@ -1622,14 +1664,33 @@ class VideoBackend:
#
# Only when the decision actually consulted it. A CPU or MPS target never asked, so
# there is no answer to have changed, and inventing one would refuse those loads.
+ #
+ # Ownership does not narrow it, for the same reason the H3 re-vet above dropped that
+ # test: the accelerator answer is recorded before the download now, so the window is
+ # the whole fetch, and a user's own build can be rebuilt inside it just as an install
+ # can land. The harm does not care who owns the file -- what gets committed is
+ # native_device, and a GPU one around a CPU binary is offload policy and an arbiter
+ # claim written against hardware nothing is running on.
+ # Only a DECISIVE re-reading, hence the verdict form rather than
+ # sd_cpp_lists_accelerator_device: that one folds "could not tell" into True, which
+ # against a recorded False would refuse the very CPU fallback that recorded it.
+ # Only when there is a baseline to compare against. A CPU or MPS target never asked
+ # the question, so this would spawn --list-devices for an answer the test below cannot
+ # use -- on every H3 load, and for the full probe timeout when the build hangs on it.
+ fresh_accelerator = (
+ sd_cpp_accelerator_device_verdict(binary)
+ if listed_accelerator is not None and binary
+ else None
+ )
if (
listed_accelerator is not None
- and is_managed_binary(binary)
- and sd_cpp_lists_accelerator_device(binary) != listed_accelerator
+ and fresh_accelerator is not None
+ and fresh_accelerator != listed_accelerator
):
raise RuntimeError(
- "The stable-diffusion.cpp binary was replaced by an install for a different "
- "accelerator while this model was loading. Try the load again."
+ "The stable-diffusion.cpp binary changed while this model was loading, and the "
+ "one now at that path was built for a different accelerator. Try the load "
+ "again."
)
binary_identity = _sd_cli_identity(binary)
requested_mode = normalize_memory_mode(memory_mode) or "auto"
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 779a04a86e3..6d6dc928d7f 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -251,8 +251,9 @@ def test_download_plan_skips_assets_already_in_the_cache(monkeypatch):
DiffusionBackend,
"_hub_file_is_cached",
staticmethod(
- lambda repo_id, filename, revision = None, expected_size = None, **kwargs: filename
- in cached
+ lambda repo_id, filename, revision = None, expected_size = None, **kwargs: (
+ filename in cached
+ )
),
)
@@ -966,6 +967,9 @@ def test_ensure_binary_install_disabled_returns_none(monkeypatch):
# A --help extract shaped like the real one: the mode list and --audio-vae are old enough to be in
# a pre-H3 build too (they came with LTX-2), so only the H3-only --ref-video separates the two.
_PRE_H3_HELP = (
+ # The banner is what upstream's print_usage() emits first, and it is also what separates "an
+ # sd.cpp build without H3" from "not sd.cpp at all" -- two outcomes the gate now distinguishes.
+ "stable-diffusion.cpp version unknown, commit unknown\n"
" -M, --mode run mode, one of [img_gen, vid_gen, upscale, convert]\n"
" --audio-vae <string> path to standalone LTX audio vae model\n"
)
@@ -1085,6 +1089,84 @@ def test_h3_binary_gate_never_offers_to_delete_the_in_tree_developer_build(monke
assert own.exists()
+def test_h3_binary_gate_logs_the_real_fault_for_a_managed_non_sd_cpp_binary(
+ monkeypatch, tmp_path, capsys
+):
+ # A managed tree holding something that is not sd.cpp is still replaced, but the log line has to
+ # say why. Calling that fault "does not advertise MiniMax-H3" is the same wrong diagnosis #8507
+ # was reported as, just written to the log instead of to the user.
+ own = tmp_path / "sd-cli"
+ own.write_text("binary")
+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: str(own))
+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: True)
+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_args: "sd 1.0.0\nFind & replace CLI\n")
+
+ assert bk.ensure_h3_sd_cpp_binary(allow_install = False) is None
+ # capsys, not caplog: the backend logs through structlog, which writes to stdout.
+ logged = capsys.readouterr().out
+ assert "is not stable-diffusion.cpp" in logged
+ assert "MiniMax-H3" not in logged
+ assert own.exists()
+
+
+def test_h3_binary_gate_names_a_binary_that_is_not_sd_cpp_at_all(monkeypatch, tmp_path):
+ # #8507: SD_CLI_PATH pointed at Debian/Ubuntu's `sd` find-and-replace tool, and the gate
+ # reported it as a stable-diffusion.cpp build predating MiniMax-H3. Every program that is not
+ # sd.cpp is missing --ref-video, so that verdict sent the user hunting for a newer build of
+ # something they had never installed. Identity and capability are separate answers.
+ own = tmp_path / "sd"
+ own.write_text("binary")
+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: str(own))
+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: False)
+ monkeypatch.setattr(
+ bk,
+ "_sd_cpp_probe_output",
+ lambda *_args: "sd 1.0.0\nFind & replace CLI\n\nUSAGE:\n sd <find> <replace-with>\n",
+ )
+
+ with pytest.raises(RuntimeError, match = "is not stable-diffusion.cpp"):
+ bk.ensure_h3_sd_cpp_binary()
+ assert own.exists() # never ours to delete
+
+
+def test_h3_binary_gate_requires_identity_not_just_the_h3_marker(monkeypatch, tmp_path):
+ # --ref-video is a plain option name, not a signature: unrelated reference-video tools expose
+ # it too. Returning early on the marker alone would readmit the #8507 class of program through
+ # SD_CLI_PATH -- accepted as H3-capable, bundle downloaded, failure deferred to generation.
+ own = tmp_path / "reference-video-cli"
+ own.write_text("binary")
+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: str(own))
+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: False)
+ monkeypatch.setattr(
+ bk,
+ "_sd_cpp_probe_output",
+ lambda *_args: "reference-video-cli 2.1\n --ref-video PATH reference clip\n",
+ )
+
+ with pytest.raises(RuntimeError, match = "is not stable-diffusion.cpp"):
+ bk.ensure_h3_sd_cpp_binary()
+
+
+def test_h3_binary_gate_probes_help_once_for_both_questions(monkeypatch, tmp_path):
+ # Identity is read off the capability probe's own output. A second spawn would double the cost
+ # of the refusal path and, worse, could read a DIFFERENT build than the one just judged.
+ own = tmp_path / "sd-cli"
+ own.write_text("binary")
+ calls: list[tuple] = []
+
+ def _probe(binary, *args):
+ calls.append((binary, args))
+ return "sd 1.0.0\nFind & replace CLI\n"
+
+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", lambda **_kwargs: str(own))
+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: False)
+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", _probe)
+
+ with pytest.raises(RuntimeError, match = "is not stable-diffusion.cpp"):
+ bk.ensure_h3_sd_cpp_binary()
+ assert [args for _b, args in calls] == [("--help",)]
+
+
def test_h3_binary_gate_keeps_a_binary_it_cannot_probe(monkeypatch):
# An unreadable --help is "cannot tell", not "no H3": the load's own version() gate already
# refuses a binary that will not run, and guessing here would strand a working build.
diff --git a/studio/backend/tests/test_sd_cpp_engine.py b/studio/backend/tests/test_sd_cpp_engine.py
index 4f7d338321d..9f3b3dbdaa2 100644
--- a/studio/backend/tests/test_sd_cpp_engine.py
+++ b/studio/backend/tests/test_sd_cpp_engine.py
@@ -50,6 +50,7 @@ def _isolate_binary_discovery(tmp_path_factory, monkeypatch):
Autouse rather than a helper because the failure does not need a fixture to reach it:
``SdCppEngine(binary = None)`` calls the finder from its constructor.
"""
+ eng._IDENTITY_MEMO.clear() # a verdict from another test must never answer for this one
root = tmp_path_factory.mktemp("no_sd_cpp")
monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(root / "studio"))
monkeypatch.delenv("STUDIO_HOME", raising = False)
@@ -92,6 +93,314 @@ def test_find_falls_back_to_path(tmp_path, monkeypatch):
assert find_sd_cpp_binary() == "/usr/bin/sd-cli"
+def test_find_rejects_unrelated_ubuntu_sd_on_path(tmp_path, monkeypatch, caplog):
+ _clear_env(monkeypatch)
+ monkeypatch.setattr(eng.Path, "home", staticmethod(lambda: tmp_path / "nohome"))
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: "/usr/bin/sd" if stem == "sd" else None)
+ run_kwargs = {}
+ hidden = object()
+
+ def _run(*_args, **kwargs):
+ run_kwargs.update(kwargs)
+ return types.SimpleNamespace(
+ stdout = "Find & replace occurrences of a pattern\nUsage: sd [OPTIONS] <FIND> <REPLACE>",
+ stderr = "",
+ returncode = 0,
+ )
+
+ monkeypatch.setattr(eng.subprocess, "run", _run)
+ monkeypatch.setattr(eng, "windows_hidden_subprocess_kwargs", lambda: {"startupinfo": hidden})
+
+ assert find_sd_cpp_binary() is None
+ assert "does not identify stable-diffusion.cpp" in caplog.text
+ assert run_kwargs["timeout"] == 10
+ assert run_kwargs["startupinfo"] is hidden
+
+
+def test_find_rejects_legacy_sd_when_identity_probe_times_out(tmp_path, monkeypatch):
+ _clear_env(monkeypatch)
+ monkeypatch.setattr(eng.Path, "home", staticmethod(lambda: tmp_path / "nohome"))
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: "/usr/bin/sd" if stem == "sd" else None)
+
+ def _timeout(*_args, **_kwargs):
+ raise eng.subprocess.TimeoutExpired("sd", 10)
+
+ monkeypatch.setattr(eng.subprocess, "run", _timeout)
+
+ assert find_sd_cpp_binary() is None
+
+
+def test_find_accepts_genuine_legacy_sd_on_path(tmp_path, monkeypatch):
+ _clear_env(monkeypatch)
+ monkeypatch.setattr(eng.Path, "home", staticmethod(lambda: tmp_path / "nohome"))
+ monkeypatch.setattr(
+ eng.shutil, "which", lambda stem: "/opt/sd.cpp/bin/sd" if stem == "sd" else None
+ )
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda *_a, **_k: types.SimpleNamespace(
+ stdout = (
+ "usage: /opt/sd.cpp/bin/sd [arguments]\n"
+ "--model [MODEL]\n--negative-prompt PROMPT\n--cfg-scale SCALE\n--steps STEPS"
+ ),
+ stderr = "",
+ returncode = 0,
+ ),
+ )
+
+ assert find_sd_cpp_binary() == "/opt/sd.cpp/bin/sd"
+
+
+def test_rejected_legacy_sd_allows_managed_install(tmp_path, monkeypatch):
+ import core.inference.sd_cpp_backend as backend
+
+ _clear_env(monkeypatch)
+ monkeypatch.setattr(eng.Path, "home", staticmethod(lambda: tmp_path / "nohome"))
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: "/usr/bin/sd" if stem == "sd" else None)
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda *_a, **_k: types.SimpleNamespace(
+ stdout = "Find & replace occurrences of a pattern\nUsage: sd [OPTIONS] <FIND> <REPLACE>",
+ stderr = "",
+ returncode = 0,
+ ),
+ )
+ installed = tmp_path / "managed" / "sd-cli"
+ installs = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ return installed
+
+ stub = types.ModuleType("install_sd_cpp_prebuilt")
+ stub.install = _install
+ monkeypatch.setitem(sys.modules, "install_sd_cpp_prebuilt", stub)
+
+ assert backend.ensure_sd_cpp_binary(accelerator = "cpu") == str(installed)
+ assert installs == [{"accelerator": "cpu"}]
+
+
+def test_identity_probe_is_memoized_per_file_revision(tmp_path, monkeypatch):
+ # Discovery runs on every load, and ensure_sd_cpp_binary resolves twice on its own, so an
+ # unrelated `sd` was re-executed several times per load -- once per full 10s timeout when the
+ # candidate hangs. The verdict is keyed on the file, not the path, so an in-place replacement
+ # is still re-probed rather than answered from a stale entry.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+ runs: list[list[str]] = []
+
+ def _run(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(
+ stdout = "Find & replace occurrences of a pattern\n", stderr = "", returncode = 0
+ )
+
+ monkeypatch.setattr(eng.subprocess, "run", _run)
+
+ assert find_sd_cpp_binary() is None
+ assert find_sd_cpp_binary() is None
+ assert len(runs) == 1
+
+ # Replaced in place by a genuine build: a new revision, so the old verdict does not apply.
+ candidate.write_text("#!/bin/sh\n# a real stable-diffusion.cpp build now\n")
+ os.utime(candidate, (0, 0))
+
+ def _run_real(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(
+ stdout = "stable-diffusion.cpp version unknown\n", stderr = "", returncode = 0
+ )
+
+ monkeypatch.setattr(eng.subprocess, "run", _run_real)
+ assert find_sd_cpp_binary() == str(candidate)
+ assert len(runs) == 2
+
+
+def test_identity_probe_rekeys_a_timestamp_preserving_replacement(tmp_path, monkeypatch):
+ # cp -p / shutil.copy2 / an archive carrying source timestamps restore the mtime of the file
+ # they overwrite, so path + mtime + size alone would serve the old verdict for a different
+ # program. The inode change time is not restorable that way.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("A" * 64)
+ stamp = os.stat(candidate)
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+ runs: list[list[str]] = []
+
+ def _reject(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(stdout = "Find & replace\n", stderr = "", returncode = 0)
+
+ monkeypatch.setattr(eng.subprocess, "run", _reject)
+ assert find_sd_cpp_binary() is None
+
+ # Same path, same size, mtime restored -- a different program underneath.
+ candidate.write_text("B" * 64)
+ os.utime(candidate, ns = (stamp.st_atime_ns, stamp.st_mtime_ns))
+ assert os.stat(candidate).st_mtime_ns == stamp.st_mtime_ns
+
+ def _accept(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(
+ stdout = "stable-diffusion.cpp version unknown\n", stderr = "", returncode = 0
+ )
+
+ monkeypatch.setattr(eng.subprocess, "run", _accept)
+ assert find_sd_cpp_binary() == str(candidate)
+ assert len(runs) == 2
+
+
+def test_identity_probe_does_not_memoize_a_nonzero_exit_it_learned_nothing_from(
+ tmp_path, monkeypatch
+):
+ # A genuine sd.cpp that cannot load an adjacent shared library exits 127 from the dynamic
+ # loader with nothing identifying on either stream. That is a CompletedProcess, not an
+ # exception, so it would otherwise be cached as a definitive "not stable-diffusion.cpp"
+ # against a file that never changed -- and installing the missing library would not get it
+ # re-probed until Studio restarted.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda *_a, **_k: types.SimpleNamespace(
+ stdout = "",
+ stderr = "sd: error while loading shared libraries: libggml.so: cannot open",
+ returncode = 127,
+ ),
+ )
+ assert find_sd_cpp_binary() is None
+ assert eng._IDENTITY_MEMO == {}
+
+ # The library is back. Same file, so the same key -- it must be probed again, not answered.
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda *_a, **_k: types.SimpleNamespace(
+ stdout = "stable-diffusion.cpp version unknown\n", stderr = "", returncode = 0
+ ),
+ )
+ assert find_sd_cpp_binary() == str(candidate)
+
+
+def test_identity_probe_memoizes_an_identifying_build_that_exits_nonzero(tmp_path, monkeypatch):
+ # The other half: older builds print usage and exit 1. Identifying output settles the question
+ # whatever the exit code, so that verdict is decisive and worth keeping.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+ runs = []
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda cmd, **_k: (
+ runs.append(cmd),
+ types.SimpleNamespace(
+ stdout = "usage: sd\n --negative-prompt P\n --cfg-scale S\n --steps N\n",
+ stderr = "",
+ returncode = 1,
+ ),
+ )[1],
+ )
+ assert find_sd_cpp_binary() == str(candidate)
+ assert find_sd_cpp_binary() == str(candidate)
+ assert len(runs) == 1
+
+
+def test_identity_verdict_expires(tmp_path, monkeypatch):
+ # No stat tuple is a content hash. On Windows st_ctime is the CREATION time, which an in-place
+ # overwrite preserves, so a same-sized write that also restores mtime leaves the whole key
+ # unchanged. Hashing the binary on every lookup would cost a full read on a path walked for
+ # every load; a short life bounds that staleness instead, and bounds whatever else the key
+ # cannot see.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+ runs = []
+
+ def _reject(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(stdout = "Find & replace\n", stderr = "", returncode = 0)
+
+ monkeypatch.setattr(eng.subprocess, "run", _reject)
+ assert find_sd_cpp_binary() is None
+ assert find_sd_cpp_binary() is None
+ assert len(runs) == 1 # inside the window, the verdict answers
+
+ clock = [time.monotonic() + eng._IDENTITY_MEMO_TTL_S + 1]
+ monkeypatch.setattr(eng.time, "monotonic", lambda: clock[0])
+
+ def _accept(cmd, **_kwargs):
+ runs.append(cmd)
+ return types.SimpleNamespace(
+ stdout = "stable-diffusion.cpp version unknown\n", stderr = "", returncode = 0
+ )
+
+ monkeypatch.setattr(eng.subprocess, "run", _accept)
+ # Past the window the same unchanged file is probed again, so a replacement the key could not
+ # see is picked up rather than being answered from a verdict about the binary it replaced.
+ assert find_sd_cpp_binary() == str(candidate)
+ assert len(runs) == 2
+
+
+def test_identity_probe_does_not_memoize_a_probe_that_failed(tmp_path, monkeypatch):
+ # A timeout or a failed spawn does not touch the file, so its memo key does not change either.
+ # Remembering that "no" would blacklist a genuine build for the life of the process over one
+ # slow --help under disk or memory pressure -- Studio would have to be restarted to see it.
+ _clear_env(monkeypatch)
+ candidate = tmp_path / "sd"
+ candidate.write_text("#!/bin/sh\n")
+ monkeypatch.setattr(eng.shutil, "which", lambda stem: str(candidate) if stem == "sd" else None)
+
+ def _timeout(*_args, **_kwargs):
+ raise eng.subprocess.TimeoutExpired("sd", 10)
+
+ monkeypatch.setattr(eng.subprocess, "run", _timeout)
+ assert find_sd_cpp_binary() is None
+ assert eng._IDENTITY_MEMO == {}
+
+ # Same file, unchanged on disk, and the probe now answers: the earlier failure must not stand in.
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda *_a, **_k: types.SimpleNamespace(
+ stdout = "stable-diffusion.cpp version unknown\n", stderr = "", returncode = 0
+ ),
+ )
+ assert find_sd_cpp_binary() == str(candidate)
+
+
+def test_identity_probe_does_not_memoize_a_candidate_it_cannot_stat(monkeypatch):
+ # No key means no cache entry: a path that does not resolve yet must be re-probed once it does,
+ # rather than being remembered as "not stable-diffusion.cpp" for the life of the process.
+ _clear_env(monkeypatch)
+ monkeypatch.setattr(
+ eng.shutil, "which", lambda stem: "/nonexistent/sd" if stem == "sd" else None
+ )
+ runs = []
+ monkeypatch.setattr(
+ eng.subprocess,
+ "run",
+ lambda cmd, **_k: (
+ runs.append(cmd),
+ types.SimpleNamespace(stdout = "unrelated\n", stderr = "", returncode = 0),
+ )[1],
+ )
+
+ assert find_sd_cpp_binary() is None
+ assert find_sd_cpp_binary() is None
+ assert len(runs) == 2
+ assert eng._IDENTITY_MEMO == {}
+
+
def test_find_returns_none_when_absent(tmp_path, monkeypatch):
_clear_env(monkeypatch)
monkeypatch.setattr(eng.Path, "home", staticmethod(lambda: tmp_path / "nohome"))
diff --git a/studio/backend/tests/test_sd_cpp_h3_matrix.py b/studio/backend/tests/test_sd_cpp_h3_matrix.py
new file mode 100644
index 00000000000..eec564e2d01
--- /dev/null
+++ b/studio/backend/tests/test_sd_cpp_h3_matrix.py
@@ -0,0 +1,432 @@
+# 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 MiniMax-H3 native preflight across the host matrix.
+
+``_run_load_h3_native`` decides three things before it commits a runtime: which binary to run,
+which device to commit it on, and -- since #8507 -- whether to spend the four-file download at all.
+Those interact: the accelerator probe only runs on a GPU target, the CPU fallback rewrites both the
+binary and the device, and every refusal has to happen before the bundle is fetched.
+
+Parametrised over ``platform x GPU vendor x binary state`` because the combinations are what broke:
+a CPU-only prebuilt on a CUDA host has its own fallback path, and a refusal reached through that
+fallback used to download the bundle first on the way to failing.
+"""
+
+from __future__ import annotations
+
+import threading
+import types
+from pathlib import Path
+
+import pytest
+
+from core.inference.video import VideoBackend, _detect_load_family
+from core.inference.video_families import VIDEO_CANCELLED_MSG
+
+
+H3_REPO = "leejet/MiniMax-H3-GGUF"
+H3_FILE = "minimax_h3_fl2va-Q4_K_M.gguf"
+
+_BANNER = "stable-diffusion.cpp version unknown, commit unknown\n"
+_H3_HELP = _BANNER + " --ref-video MiniMax-H3 Ref2VA reference video frame directory\n"
+_PRE_H3_HELP = _BANNER + " -M, --mode run mode, one of [img_gen, vid_gen, upscale]\n"
+# Debian/Ubuntu's find-and-replace `sd`, and Homebrew ships the same tool on macOS.
+_UNRELATED_HELP = "sd 1.0.0\nFind & replace CLI\n\nUSAGE:\n sd <find> <replace-with>\n"
+
+# (label, DiffusionDeviceTarget.backend, .device)
+HARDWARE = [
+ ("nvidia", "cuda", "cuda"),
+ ("amd", "rocm", "cuda"),
+ ("apple", "mps", "mps"),
+ ("cpu", "cpu", "cpu"),
+]
+# sys.platform values. WSL is a Linux platform string with a Windows kernel underneath, so it is
+# the linux row -- listed separately because it is where PATH picks up a Windows-side install.
+PLATFORMS = ["linux", "wsl", "darwin", "win32"]
+
+
+class _PlanInfo:
+ def __init__(self, siblings) -> None:
+ self.siblings = siblings
+
+
+class _Engine:
+ def __init__(self, binary) -> None:
+ self.binary = binary
+
+ def version(self):
+ return "stub-version"
+
+
+def h3_host(monkeypatch, tmp_path):
+ """Drive `_run_load_h3_native` on a chosen host with a chosen binary, recording downloads."""
+ from core.inference import video as video_mod
+ from core.inference import sd_cpp_backend, sd_cpp_engine
+
+ def _setup(
+ *,
+ platform: str,
+ backend: str,
+ device: str,
+ help_text: str | None,
+ managed: bool = False,
+ lists_accelerator: bool = True,
+ ):
+ monkeypatch.setattr(
+ sd_cpp_engine.sys, "platform", "linux" if platform == "wsl" else platform
+ )
+ monkeypatch.setattr(
+ video_mod,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(backend = backend, device = device, dtype = None),
+ )
+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)
+ monkeypatch.setattr(sd_cpp_backend, "is_managed_binary", lambda _b: managed)
+ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)
+
+ binary = None if help_text is None else "/opt/sd/sd-cli"
+ monkeypatch.setattr(sd_cpp_backend, "ensure_sd_cpp_binary", lambda **_kwargs: binary)
+
+ device_probes: list[str] = []
+
+ def _probe(_binary, *args):
+ if args == ("--list-devices",):
+ device_probes.append(_binary)
+ if lists_accelerator:
+ return "CUDA0\tNVIDIA H100 PCIe\nCPU\tIntel(R) Xeon(R)\n"
+ return "CPU\tIntel(R) Xeon(R)\n"
+ return help_text
+
+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
+
+ asset_calls: list[str] = []
+
+ class _Api:
+ def __init__(self, **_kwargs):
+ pass
+
+ def model_info(self, repo, *_args, **_kwargs):
+ asset_calls.append(repo)
+ return _PlanInfo([])
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+
+ downloads: list[str] = []
+
+ def _download(_repo, wanted, *_args, **_kwargs):
+ downloads.append(wanted)
+ path = tmp_path / Path(wanted).name
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+
+ def run(cancel_event: threading.Event | None = None):
+ fam = _detect_load_family(H3_REPO, None, "minimax-h3")
+ assert fam is not None
+ backend_obj = VideoBackend()
+ backend_obj._run_load_h3_native(
+ fam = fam,
+ token = None,
+ cancel_event = cancel_event or threading.Event(),
+ repo_id = H3_REPO,
+ gguf_filename = H3_FILE,
+ )
+ return backend_obj
+
+ return types.SimpleNamespace(
+ run = run,
+ downloads = downloads,
+ asset_calls = asset_calls,
+ device_probes = device_probes,
+ )
+
+ return _setup
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+ "state,help_text,expected",
+ [
+ ("unrelated_binary", _UNRELATED_HELP, "is not stable-diffusion.cpp"),
+ ("pre_h3_binary", _PRE_H3_HELP, "does not advertise MiniMax-H3"),
+ ("no_binary", None, "could not be installed or started"),
+ ],
+)
+def test_h3_preflight_refuses_before_downloading(
+ h3_host, platform, hw_label, backend, device, state, help_text, expected
+):
+ """Every refusal, on every host, costs zero downloads.
+
+ The bundle is tens of GB. A refusal that arrives after it has been fetched is the failure mode
+ the H3 gate was written to prevent, and it was reachable on all of these hosts: the gate ran
+ after the download loop, and a None binary was not rejected until later still.
+ """
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = help_text)
+ with pytest.raises(RuntimeError, match = expected):
+ host.run()
+ assert host.downloads == []
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_preflight_admits_a_capable_build_and_downloads_once(
+ h3_host, platform, hw_label, backend, device
+):
+ """The other direction: a genuine H3 build is not refused anywhere, and the load proceeds to
+ fetch exactly the four files. Guards against an identity check that is too strict."""
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+ backend_obj = host.run()
+ assert len(host.downloads) == 4
+ assert backend_obj._state is not None
+ # A GPU target keeps its device when the build offers an accelerator; CPU/MPS are unchanged.
+ assert backend_obj._state.device == device
+
+
[email protected]("platform", PLATFORMS)
+ "hw_label,backend,device", [h for h in HARDWARE if h[1] in ("cuda", "rocm")]
+)
+def test_h3_gpu_host_falls_back_to_the_cpu_build(h3_host, platform, hw_label, backend, device):
+ """Upstream publishes no Linux CUDA archive, so a GPU host routinely ends up on the CPU
+ prebuilt. It must still load, committed on the CPU rather than on a GPU it never ran on."""
+ host = h3_host(
+ platform = platform,
+ backend = backend,
+ device = device,
+ help_text = _H3_HELP,
+ lists_accelerator = False,
+ )
+ backend_obj = host.run()
+ assert len(host.downloads) == 4
+ assert backend_obj._state is not None
+ assert backend_obj._state.device == "cpu"
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_cancellation_during_the_preflight_stops_before_the_asset_calls(
+ h3_host, platform, hw_label, backend, device, monkeypatch
+):
+ """The ensure takes no cancel_event and can spend minutes installing the prebuilt, so a cancel
+ arriving during it is already late. It must not then cost four more model_info round trips."""
+ from core.inference import sd_cpp_backend
+
+ cancelled = threading.Event()
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+ original = sd_cpp_backend.ensure_h3_sd_cpp_binary
+
+ def _cancel_midway(**kwargs):
+ cancelled.set() # the user hits cancel while the install is running
+ return original(**kwargs)
+
+ monkeypatch.setattr(sd_cpp_backend, "ensure_h3_sd_cpp_binary", _cancel_midway)
+
+ with pytest.raises(RuntimeError, match = VIDEO_CANCELLED_MSG):
+ host.run(cancel_event = cancelled)
+ assert host.downloads == []
+ # The point is not that it eventually raises -- the download loop always would. It is that a
+ # cancelled load stops before paying for the four sequential size-estimate round trips.
+ assert host.asset_calls == []
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_revets_a_user_supplied_binary_swapped_during_the_download(
+ h3_host, platform, hw_label, backend, device, monkeypatch
+):
+ """Vetting before the download means the vet-to-commit window is now the whole download.
+
+ A user-supplied binary is not ours to reinstall, so nothing else guards it: if the file at that
+ path changes while the bundle is fetched, the re-vet is the only thing standing between the
+ replacement and being recorded as the identity every later generation compares against."""
+ from core.inference import sd_cpp_backend
+
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+
+ # The preflight sees an H3 build; by the time the download is done the path holds a pre-H3 one.
+ swapped = {"done": False}
+ real_probe = sd_cpp_backend._sd_cpp_probe_output
+
+ def _probe(binary, *args):
+ if args == ("--help",) and swapped["done"]:
+ return _PRE_H3_HELP
+ return real_probe(binary, *args)
+
+ def _download(*args, **kwargs):
+ swapped["done"] = True
+ return _real_download(*args, **kwargs)
+
+ _real_download = None
+ import utils.hf_xet_fallback as xet
+
+ _real_download = xet.hf_hub_download_with_xet_fallback
+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
+ monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
+
+ with pytest.raises(RuntimeError, match = "changed while this model was loading"):
+ host.run()
+ assert len(host.downloads) == 4 # the swap is caught after the fetch, not before it
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_revet_checks_identity_not_just_the_h3_marker(
+ h3_host, platform, hw_label, backend, device, monkeypatch
+):
+ """The post-download re-vet asks both of the preflight's questions, not only capability.
+
+ --ref-video is a plain option name that unrelated reference-video tools expose too, so a swap
+ to one of those would clear a marker-only re-check and then be recorded by _sd_cli_identity as
+ the vetted build every later generation compares against."""
+ from core.inference import sd_cpp_backend
+
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+
+ swapped = {"done": False}
+ real_probe = sd_cpp_backend._sd_cpp_probe_output
+
+ def _probe(binary, *args):
+ # Not sd.cpp, but it does carry the H3 marker -- capability alone would wave it through.
+ if args == ("--help",) and swapped["done"]:
+ return "reference-video-cli 2.1\n --ref-video PATH reference clip\n"
+ return real_probe(binary, *args)
+
+ import utils.hf_xet_fallback as xet
+
+ real_download = xet.hf_hub_download_with_xet_fallback
+
+ def _download(*args, **kwargs):
+ swapped["done"] = True
+ return real_download(*args, **kwargs)
+
+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
+ monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
+
+ with pytest.raises(RuntimeError, match = "changed while this model was loading"):
+ host.run()
+ assert len(host.downloads) == 4
+
+
[email protected]("platform", PLATFORMS)
+ "hw_label,backend,device", [h for h in HARDWARE if h[1] in ("cuda", "rocm")]
+)
+def test_h3_revet_catches_a_user_binary_whose_accelerator_changed(
+ h3_host, platform, hw_label, backend, device, monkeypatch
+):
+ """native_device is decided on the accelerator reading and then committed for the life of the
+ runtime, so the reading has to still hold at commit time -- for a user's own build too, not
+ only a managed one. A GPU device committed around a CPU binary means offload policy and an
+ arbiter claim written against hardware nothing is running on."""
+ from core.inference import sd_cpp_backend
+
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+
+ swapped = {"done": False}
+ real_probe = sd_cpp_backend._sd_cpp_probe_output
+
+ def _probe(binary, *args):
+ # Still an H3-capable sd.cpp, so identity and capability both pass; only the device list
+ # changed, which is exactly the case the H3 re-vet cannot see.
+ if args == ("--list-devices",) and swapped["done"]:
+ return "CPU\tIntel(R) Xeon(R)\n"
+ return real_probe(binary, *args)
+
+ import utils.hf_xet_fallback as xet
+
+ real_download = xet.hf_hub_download_with_xet_fallback
+
+ def _download(*args, **kwargs):
+ swapped["done"] = True
+ return real_download(*args, **kwargs)
+
+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
+ monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
+
+ with pytest.raises(RuntimeError, match = "built for a different accelerator"):
+ host.run()
+
+
[email protected]("platform", PLATFORMS)
+ "hw_label,backend,device", [h for h in HARDWARE if h[1] in ("cuda", "rocm")]
+)
+def test_h3_revet_tolerates_an_unreadable_accelerator_reprobe(
+ h3_host, platform, hw_label, backend, device, monkeypatch
+):
+ """ "Could not tell" is not "it changed". sd_cpp_lists_accelerator_device folds an unreadable
+ probe into True, so comparing THAT against a recorded False would refuse the CPU fallback that
+ recorded it -- the load must proceed on the reading it already has."""
+ from core.inference import sd_cpp_backend
+
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+
+ swapped = {"done": False}
+ real_probe = sd_cpp_backend._sd_cpp_probe_output
+
+ def _probe(binary, *args):
+ if args == ("--list-devices",) and swapped["done"]:
+ return None # older build that rejects the flag, or an unreadable probe
+ return real_probe(binary, *args)
+
+ import utils.hf_xet_fallback as xet
+
+ real_download = xet.hf_hub_download_with_xet_fallback
+
+ def _download(*args, **kwargs):
+ swapped["done"] = True
+ return real_download(*args, **kwargs)
+
+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
+ monkeypatch.setattr(xet, "hf_hub_download_with_xet_fallback", _download)
+
+ backend_obj = host.run()
+ assert backend_obj._state is not None
+ assert backend_obj._state.device == device
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_probes_devices_only_where_the_answer_is_used(
+ h3_host, platform, hw_label, backend, device
+):
+ """--list-devices costs a subprocess, and the full probe timeout when a build hangs on it.
+
+ A CPU or MPS target never records a baseline, so neither the decision nor the re-check can use
+ the answer -- it must not be asked. A GPU target asks exactly twice: once to decide, once under
+ the claim to confirm the decision still holds."""
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+ host.run()
+ expected = 2 if backend not in ("cpu", "mps") else 0
+ assert len(host.device_probes) == expected
+
+
[email protected]("platform", PLATFORMS)
[email protected]("hw_label,backend,device", HARDWARE)
+def test_h3_cancellation_precedes_the_binary_install(h3_host, platform, hw_label, backend, device):
+ """The preflight can download and extract the sd-cli prebuilt and takes no cancel_event, so a
+ load cancelled before its worker started must not reach it."""
+ from core.inference import sd_cpp_backend
+
+ host = h3_host(platform = platform, backend = backend, device = device, help_text = _H3_HELP)
+ ensures: list[str] = []
+ original = sd_cpp_backend.ensure_h3_sd_cpp_binary
+
+ def _spy(**kwargs):
+ ensures.append("called")
+ return original(**kwargs)
+
+ sd_cpp_backend.ensure_h3_sd_cpp_binary = _spy
+ try:
+ cancelled = threading.Event()
+ cancelled.set()
+ with pytest.raises(RuntimeError):
+ host.run(cancel_event = cancelled)
+ finally:
+ sd_cpp_backend.ensure_h3_sd_cpp_binary = original
+ assert ensures == []
+ assert host.downloads == []
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index a06986a178e..eea25fdb59b 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2497,8 +2497,9 @@ def test_download_plan_keeps_a_video_base_that_lives_wholly_in_the_other_root(mo
DiffusionBackend,
"_hub_file_is_cached",
staticmethod(
- lambda repo_id, filename, revision = None, expected_size = None, roots = None: roots
- != ("live",)
+ lambda repo_id, filename, revision = None, expected_size = None, roots = None: (
+ roots != ("live",)
+ )
),
)
monkeypatch.setattr("core.inference.video.hub_cache_dir", lambda: "live")
@@ -3323,7 +3324,12 @@ def test_h3_native_reused_cpu_binary_still_commits_to_cpu(monkeypatch, tmp_path)
if args == ("--list-devices",):
# What the CPU prebuilt answers: the one ggml device it was built with.
return "CPU\tIntel(R) Xeon(R) Platinum 8559C\n"
- return " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"
+ # The banner too: it is what identifies the binary AS stable-diffusion.cpp, and the gate
+ # asks that before it asks whether the build carries H3.
+ return (
+ "stable-diffusion.cpp version unknown, commit unknown\n"
+ " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"
+ )
monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
@@ -3409,7 +3415,12 @@ def _h3_managed_cpu_fallback_load(monkeypatch, tmp_path, *, swap_on_fallback):
if swapped:
return "CUDA0\tNVIDIA H100 PCIe\nCPU\tIntel(R) Xeon(R) Platinum 8559C\n"
return "CPU\tIntel(R) Xeon(R) Platinum 8559C\n"
- return " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"
+ # The banner too: it is what identifies the binary AS stable-diffusion.cpp, and the gate
+ # asks that before it asks whether the build carries H3.
+ return (
+ "stable-diffusion.cpp version unknown, commit unknown\n"
+ " --ref-video MiniMax-H3 Ref2VA reference video frame directory at 24 fps\n"
+ )
monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)
@@ -3541,7 +3552,10 @@ def test_h3_native_load_publishes_the_companion_repos_while_downloading(monkeypa
def test_h3_native_load_refuses_a_binary_that_predates_h3(monkeypatch, tmp_path):
"""ensure_sd_cpp_binary probes runnability only, so an sd.cpp build older than H3 support is
handed back and clears the version() gate: the load reported ready and the first generation
- failed, i.e. AFTER the multi-tens-of-GB bundle had downloaded. Gate on the capability."""
+ failed, i.e. AFTER the multi-tens-of-GB bundle had downloaded. Gate on the capability.
+
+ And gate BEFORE the download: the point of refusing early is lost if the four-file bundle has
+ already been fetched by the time the gate runs, which is what the ordering here asserts."""
from core.inference import video as video_mod
from core.inference import sd_cpp_backend, sd_cpp_engine
@@ -3572,6 +3586,9 @@ def test_h3_native_load_refuses_a_binary_that_predates_h3(monkeypatch, tmp_path)
sd_cpp_backend,
"_sd_cpp_probe_output",
lambda *_args: (
+ # The banner is what identifies it AS stable-diffusion.cpp. Without it the gate would
+ # (correctly) report a different failure: not an old build, not the project at all.
+ "stable-diffusion.cpp version unknown, commit unknown\n"
" -M, --mode run mode, one of [img_gen, vid_gen, upscale]\n"
" --audio-vae <string> path to standalone LTX audio vae model\n"
),
@@ -3587,7 +3604,10 @@ def test_h3_native_load_refuses_a_binary_that_predates_h3(monkeypatch, tmp_path)
monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)
+ downloads: list[str] = []
+
def _download(_repo, wanted, *_args, **_kwargs):
+ downloads.append(wanted)
path = tmp_path / Path(wanted).name
path.write_bytes(b"x")
return str(path)
@@ -3607,6 +3627,165 @@ def test_h3_native_load_refuses_a_binary_that_predates_h3(monkeypatch, tmp_path)
)
assert backend._state is None
+ # Not one byte of the bundle: the binary is vetted before the four files are resolved.
+ assert downloads == []
+
+
+def test_h3_native_load_refuses_a_missing_binary_before_downloading(monkeypatch, tmp_path):
+ """ensure_h3_sd_cpp_binary returns None whenever it cannot produce a binary -- auto-install off,
+ unsupported platform, no network, or a stale managed copy something else is running out of. The
+ only `not binary` check used to sit after the download loop, so every one of those cases still
+ fetched the four-file bundle first."""
+ from core.inference import video as video_mod
+ from core.inference import sd_cpp_backend
+
+ class _Api:
+ def __init__(self, **_kwargs):
+ pass
+
+ def model_info(self, *_args, **_kwargs):
+ return _PlanInfo([])
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+ monkeypatch.setattr(
+ video_mod,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),
+ )
+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: False)
+ monkeypatch.setattr(sd_cpp_backend, "ensure_h3_sd_cpp_binary", lambda **_kwargs: None)
+
+ downloads: list[str] = []
+
+ def _download(_repo, wanted, *_args, **_kwargs):
+ downloads.append(wanted)
+ path = tmp_path / Path(wanted).name
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+
+ backend = VideoBackend()
+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")
+ assert fam is not None
+ with pytest.raises(RuntimeError, match = "could not be installed or started"):
+ backend._run_load_h3_native(
+ fam = fam,
+ token = None,
+ cancel_event = threading.Event(),
+ repo_id = "leejet/MiniMax-H3-GGUF",
+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
+ )
+
+ assert backend._state is None
+ assert downloads == []
+
+
+def test_h3_native_load_checks_cancellation_before_the_binary_preflight(monkeypatch):
+ """The preflight may install the sd-cli prebuilt and takes no cancel_event, so a load cancelled
+ before this thread got going must not pay for it. The download loop used to be the first check;
+ moving the preflight above it put an uncancellable install in front of that."""
+ from core.inference import video as video_mod
+ from core.inference import sd_cpp_backend
+
+ ensures: list[str] = []
+ monkeypatch.setattr(
+ video_mod,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),
+ )
+ monkeypatch.setattr(
+ sd_cpp_backend,
+ "ensure_h3_sd_cpp_binary",
+ lambda **_kwargs: (ensures.append("ensure"), "/usr/local/bin/sd-cli")[1],
+ )
+
+ cancelled = threading.Event()
+ cancelled.set()
+ backend = VideoBackend()
+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")
+ assert fam is not None
+ with pytest.raises(RuntimeError, match = VIDEO_CANCELLED_MSG):
+ backend._run_load_h3_native(
+ fam = fam,
+ token = None,
+ cancel_event = cancelled,
+ repo_id = "leejet/MiniMax-H3-GGUF",
+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
+ )
+ assert ensures == []
+
+
+def test_h3_native_load_refuses_a_binary_that_is_not_sd_cpp_before_downloading(
+ monkeypatch, tmp_path
+):
+ """#8507: an unrelated executable named `sd` was reported as an sd.cpp build predating H3.
+
+ Discovery now skips it, so reaching the gate takes a deliberate SD_CLI_PATH override -- and
+ when it is reached the message says what is actually wrong, still before any download."""
+ from core.inference import video as video_mod
+ from core.inference import sd_cpp_backend, sd_cpp_engine
+
+ class _Api:
+ def __init__(self, **_kwargs):
+ pass
+
+ def model_info(self, *_args, **_kwargs):
+ return _PlanInfo([])
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+ monkeypatch.setattr(
+ video_mod,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),
+ )
+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ sd_cpp_backend,
+ "ensure_sd_cpp_binary",
+ lambda *, allow_install, accelerator: "/usr/bin/sd",
+ )
+ monkeypatch.setattr(sd_cpp_backend, "is_managed_binary", lambda _b: False)
+ # Debian/Ubuntu's find-and-replace `sd`, which is what /usr/bin/sd is on the reporter's box.
+ monkeypatch.setattr(
+ sd_cpp_backend,
+ "_sd_cpp_probe_output",
+ lambda *_args: "sd 1.0.0\nFind & replace CLI\n\nUSAGE:\n sd <find> <replace-with>\n",
+ )
+
+ class _Engine:
+ def __init__(self, binary):
+ self.binary = binary
+
+ def version(self):
+ return "stub-version"
+
+ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)
+
+ downloads: list[str] = []
+
+ def _download(_repo, wanted, *_args, **_kwargs):
+ downloads.append(wanted)
+ path = tmp_path / Path(wanted).name
+ path.write_bytes(b"x")
+ return str(path)
+
+ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)
+
+ backend = VideoBackend()
+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")
+ assert fam is not None
+ with pytest.raises(RuntimeError, match = "is not stable-diffusion.cpp"):
+ backend._run_load_h3_native(
+ fam = fam,
+ token = None,
+ cancel_event = threading.Event(),
+ repo_id = "leejet/MiniMax-H3-GGUF",
+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",
+ )
+
+ assert backend._state is None
+ assert downloads == []
def test_h3_native_generation_dispatch_does_not_import_torch(monkeypatch):
@@ -5058,10 +5237,10 @@ def test_h3_modular_load_pins_a_hosted_prequant_denoiser_out_of_the_offload_rota
monkeypatch.setattr(
prequant_module,
"pin_prequantized_module",
- lambda mgr, module, device, **kwargs: calls.setdefault(
- "pinned", {"manager": mgr, "module": module, "device": device}
- )
- is not None,
+ lambda mgr, module, device, **kwargs: (
+ calls.setdefault("pinned", {"manager": mgr, "module": module, "device": device})
+ is not None
+ ),
)
def load(scheme):