Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Serialise sd.cpp installs against the binaries they replace (#8274)
Daniel Han2f096a6b1ac0
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 7b21643b521..a5eb83df74d 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -24,6 +24,7 @@ does not drag the heavy GPU stack into the process.from __future__ import annotations+import contextlibimport loggingimport osimport re@@ -86,6 +87,91 @@ _STEP_RE = re.compile(r"(\d+)\s*/\s*(\d+)")# Serialises the one-time binary install so concurrent first-loads don't race._install_lock = threading.Lock()+# Admission control over the managed tree, because "is anything running in there?" and "start+# replacing it" have to be ONE decision. _managed_tree_in_use() alone is a point-in-time sample,+# and an install spends seconds to minutes downloading before it extracts: a one-shot generation+# admitted inside that window launches the very sd-cli the extraction then overwrites. Installs are+# the writers, one-shot sd-cli runs are the readers. Held only across the state change, never+# across a download or a generation, and the readers never take _install_lock, so there is no cycle.+_tree_state = threading.Condition()+_tree_readers = 0+_tree_installing = False+# A download can legitimately take minutes; wait rather than run a binary that is being replaced.+_TREE_WAIT_TIMEOUT_S = 900.0+# How often the wait re-checks for cancellation. Nothing notifies the condition when a request is+# cancelled, so a single long wait would hold the generate lock past an unload.+_TREE_WAIT_TICK_S = 0.5+++def _tree_claimed_for_install():+ """Claim the managed tree for an install. Yields False when something is running in it, in+ which case the caller keeps what is on disk and retries on a later load."""+ global _tree_installing+ with _tree_state:+ if _tree_readers or _tree_installing or _managed_tree_in_use():+ yield False+ return+ _tree_installing = True+ try:+ yield True+ finally:+ with _tree_state:+ _tree_installing = False+ _tree_state.notify_all()+++def _tree_reader(+ binary: Optional[str],+ cancel_event: Optional[threading.Event] = None,+ cancelled_message: str = DIFFUSION_CANCELLED_MSG,+):+ """Run ``binary`` out of the managed tree, holding off any install for the duration.++ Only a MANAGED copy needs this. An sd-cli from ``SD_CLI_PATH`` / ``UNSLOTH_SD_CPP_PATH``, an+ in-tree build or ``PATH`` is one the installer never touches, so claiming for it would block+ that generation behind an unrelated bundle download for nothing (and, on a timeout, fail it).++ A timeout is NOT admission: the install still holds the tree, and starting the binary it is+ replacing is the exact race this exists to prevent.++ The wait is cancellable. The caller already holds the generate lock here, so an unload or a+ cancel that could not get out of this would read as a hung Studio for up to the whole timeout+ while nothing has even started. Nothing notifies the condition on cancel, so the wait is+ re-checked on a short tick rather than once."""+ global _tree_readers+ if not is_managed_binary(binary):+ yield+ return+ with _tree_state:+ if _tree_installing:+ logger.info("waiting for the sd.cpp install to finish before starting a generation")+ deadline = time.monotonic() + _TREE_WAIT_TIMEOUT_S+ while _tree_installing:+ if cancel_event is not None and cancel_event.is_set():+ # The caller's own sentinel: the video path recognises only its own, and an+ # image message reaching it reads as "Video generation failed" for what is an+ # ordinary cancellation.+ raise RuntimeError(cancelled_message)+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise RuntimeError(+ f"the stable-diffusion.cpp install is still replacing its binaries after "+ f"{int(_TREE_WAIT_TIMEOUT_S)}s. Try again once it has finished."+ )+ _tree_state.wait_for(+ lambda: not _tree_installing, timeout = min(remaining, _TREE_WAIT_TICK_S)+ )+ _tree_readers += 1+ try:+ yield+ finally:+ with _tree_state:+ _tree_readers -= 1+ _tree_state.notify_all()++# Max images per img_gen job; larger Studio batches (up to 32) are split into these chunks._MAX_SERVER_BATCH = 8@@ -263,14 +349,28 @@ def ensure_h3_sd_cpp_binary(# 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)return None- logger.warning(- "managed sd.cpp binary %s predates MiniMax-H3 support; removing it so it reinstalls", binary- )- try:- Path(binary).unlink()- except OSError as exc:- logger.warning("could not remove the stale managed sd.cpp binary %s: %s", binary, exc)- 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+ # unlink but the next image in the batch can no longer resolve it, and on Windows the unlink+ # fails outright and the H3 load is refused. Held only across the unlink -- ensure_sd_cpp_binary+ # below claims the tree itself, and the claim is not reentrant.+ 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",+ binary,+ )+ return None+ logger.warning(+ "managed sd.cpp binary %s predates MiniMax-H3 support; removing it so it reinstalls",+ binary,+ )+ try:+ Path(binary).unlink()+ except OSError as exc:+ logger.warning("could not remove the stale managed sd.cpp binary %s: %s", binary, exc)+ return Nonebinary = ensure_sd_cpp_binary(allow_install = True, accelerator = accelerator)if binary and not sd_cpp_supports_minimax_h3(binary):return None@@ -303,6 +403,19 @@ def _note_failed_upgrade(accelerator: str) -> None:pass+def _incomplete_tree_replacement(exc: BaseException) -> bool:+ """True when an install failed PART WAY through replacing the managed tree.++ That leaves a mixture of two bundles, and the installer withholds the record precisely so the+ next load retries the sweep. Memoising it as a failed upgrade would do the opposite: the+ mismatch is then suppressed for the rest of the process and the mixed tree is served as if it+ were the accelerator that was asked for."""+ try:+ return isinstance(exc, _installer_module().SupersededBinaryError)+ except Exception: # noqa: BLE001 -- cannot tell -> treat as an ordinary failure, as before+ return False++def _tree_in_use(backend: Any) -> bool:"""True while ``backend`` may still have a native process executing out of the managed tree.@@ -374,6 +487,26 @@ def _accelerator_changed(binary: str, accelerator: str) -> bool:return False+def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:+ """The accelerator class recorded for the managed install ``binary`` belongs to.++ None for a binary the installer does not own (SD_CLI_PATH, UNSLOTH_SD_CPP_PATH, an in-tree+ build, PATH) and for a record that cannot be read: neither is an answer, and the only caller+ uses this to notice that the answer CHANGED, never to decide what to install.++ Deliberately not ``_accelerator_changed``: that one answers "should an install run", so it+ stands down while the tree is in use and while an upgrade for this accelerator has already+ failed, and a load that keeps a usable wrong-accelerator build on purpose would be refused by+ it on every single load. What the load needs is narrower -- did the tree it resolved this+ binary out of get replaced underneath it."""+ if not is_managed_binary(binary):+ return None+ try:+ return _installer_module().installed_accelerator(managed_install_root())+ except Exception: # noqa: BLE001 -- cannot tell; the comparison sees None on both sides+ return None++def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu") -> Optional[str]:"""Path to a usable ``sd-cli`` binary, installing the prebuilt once if needed.@@ -396,27 +529,38 @@ def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu"# A usable binary of the wrong accelerator is still better than none, so an install that# cannot deliver the right one (no such asset for this host, no network) keeps it.fallback = found if usable else None- # An install REPLACES the binaries in the managed tree, so refuse it while a native- # process is still executing out of that tree. _accelerator_changed answers this for a- # mismatch, but "no binary found" never reaches it: a legacy serverless install has no- # sd-server at all, while its sd-cli may be mid-generation. Nothing can be in use before- # anything is installed, so a first install is unaffected. The load retries after teardown.- if _managed_tree_in_use():- return fallbacktry:_install = _installer_module().installexcept Exception as exc: # noqa: BLE001 -- import path / module issues are non-fatallogger.warning("sd-cli installer import failed: %s", exc)return fallback- try:- path = _install(accelerator = accelerator)- logger.info("sd-cli installed at %s", path)- return str(path)- except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back- logger.warning("sd-cli auto-install failed: %s", exc)- if fallback is not None:- _note_failed_upgrade(accelerator)- return fallback+ # Claim the tree for the whole install, download included: a point-in-time check would+ # let a generation start during the download and be overwritten by the extraction.+ with _tree_claimed_for_install() as claimed:+ if not claimed:+ return fallback # something is running in there; retry on a later load+ try:+ path = _install(accelerator = accelerator)+ logger.info("sd-cli installed at %s", path)+ return str(path)+ except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back+ logger.warning("sd-cli auto-install failed: %s", exc)+ if _incomplete_tree_replacement(exc):+ # The sweep got part way, and it takes sd-cli before sd-server, so the+ # fallback resolved before the install may be one of the copies it already+ # removed. Re-find, so this returns a file that exists -- often the one the+ # new bundle just extracted -- or None, never a path that is gone.+ #+ # Through the usability gate, not raw: the raise came BEFORE install()'s+ # _make_executable, so on POSIX a freshly extracted copy has no execute bit+ # and find_sd_cpp_binary only checks that the path is a file. The gate probes+ # it and, being ours, removes it if it cannot run, so the next load reinstalls+ # rather than being handed a binary that fails to launch.+ refound = find_sd_cpp_binary()+ return refound if refound and _usable_or_discard_managed(refound) else None+ if fallback is not None:+ _note_failed_upgrade(accelerator)+ return fallbackdef ensure_sd_server_binary(@@ -443,28 +587,29 @@ def ensure_sd_server_binary(return found# Keep a usable wrong-accelerator server if the matching one cannot be fetched.fallback = found if usable else None- # An install REPLACES the binaries in the managed tree, so refuse it while a native- # process is still executing out of that tree. _accelerator_changed answers this for a- # mismatch, but "no binary found" never reaches it: a legacy serverless install has no- # sd-server at all, while its sd-cli may be mid-generation. Nothing can be in use before- # anything is installed, so a first install is unaffected. The load retries after teardown.- if _managed_tree_in_use():- return fallbacktry:_install = _installer_module().installexcept Exception as exc: # noqa: BLE001 -- import path / module issues are non-fatallogger.warning("sd-server installer import failed: %s", exc)return fallback- try:- _install(accelerator = accelerator) # extracts sd-cli AND sd-server- except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back- logger.warning("sd-server auto-install failed: %s", exc)- # Also when only the CLI survives (a legacy server-less tree): the router probes- # ensure_sd_cpp_binary immediately after this, and without the record that probe- # resolves and downloads the same bundle a second time inside one selection.- if fallback is not None or find_sd_cpp_binary() is not None:- _note_failed_upgrade(accelerator)- return fallback+ with _tree_claimed_for_install() as claimed:+ if not claimed:+ return fallback # something is running in there; retry on a later load+ try:+ _install(accelerator = accelerator) # extracts sd-cli AND sd-server+ except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back+ logger.warning("sd-server auto-install failed: %s", exc)+ # Also when only the CLI survives (a legacy server-less tree): the router probes+ # ensure_sd_cpp_binary immediately after this, and without the record that probe+ # resolves and downloads the same bundle a second time inside one selection.+ if _incomplete_tree_replacement(exc):+ # As above: the fallback may name a copy the partial sweep removed, and a+ # freshly extracted one never reached _make_executable.+ refound = find_sd_server_binary()+ return refound if refound and _usable_or_discard_managed(refound) else None+ if fallback is not None or find_sd_cpp_binary() is not None:+ _note_failed_upgrade(accelerator)+ return fallbackreturn find_sd_server_binary() or fallback@@ -496,6 +641,12 @@ class _SdState:# The FLUX.2 inner_dim this load read out of the checkpoint's own header, when it could. Kept# so the delete guard reconstructs the SAME encoder pick without re-probing under the lock.flux2_inner_dim: Optional[int] = None+ # The managed tree's recorded accelerator when this load chose its binary. The one-shot path+ # re-resolves sd-cli per image, so without this it would silently adopt an install that landed+ # between images even when that install is for a DIFFERENT accelerator, while ``device`` and+ # ``offload_flags`` still describe the build the load committed to. None on the server path,+ # which asks the same question at start time against its own local copy.+ sd_accelerator: Optional[str] = Nonedef _memory_policy(memory_mode: Optional[str], cpu_offload: bool) -> str:@@ -876,6 +1027,10 @@ class SdCppDiffusionBackend:) -> None:# This load's own event: a later load replaces self._cancel_event rather than clearing it.cancel_event = _cancel_event if _cancel_event is not None else self._cancel_event+ # The server this load publishes to _pending_server, out here so the backstop below can+ # always unpublish it. A leaked _pending_server reads as "the managed tree is busy" for+ # the rest of the process and blocks every later install.+ started: Optional[SdCppServer] = Nonetry:# Resolve mode (server preferred, one-shot fallback) + binary up front so an install failure surfaces before the multi-GB pull.mode, server_binary, engine = self._resolve_backend()@@ -887,13 +1042,31 @@ class SdCppDiffusionBackend:"sd-server at %s is present but not runnable; trying one-shot sd-cli.",server_binary,)+ # Resolve ONCE and keep it: two calls can answer with two different+ # binaries if an install lands between them, and the state below reads the+ # accelerator off whichever object it ends up holding.+ fallback: Optional[SdCppEngine] = Nonetry:- usable = self._resolve_engine().version() is not None+ fallback = self._resolve_engine()+ usable = fallback.version() is not Noneexcept Exception: # noqa: BLE001usable = False- if not usable:+ if not usable or fallback is None:raise RuntimeError("sd-server binary is present but not runnable.")- mode, server_binary, engine = "oneshot", None, self._resolve_engine()+ mode, server_binary, engine = "oneshot", None, fallback+ # The accelerator the managed tree held when THIS binary was chosen, taken where the+ # choice is made rather than sampled again later. The asset download below runs for+ # minutes with no claim on the tree, and an install that lands in that window replaces+ # sd-server in place: same path, still runnable, a different build. "It exists and it+ # runs" is therefore not evidence that it is the build this load resolved its device+ # and offload policy for, so the answer is re-asked under the reader claim.+ server_accelerator = _installed_accelerator_of(server_binary)+ # The same pin for the one-shot CLI, and for the same reason. Sampling it only at+ # state construction, after the download, would record whatever an install left in+ # the tree in that window and the first generation -- which re-reads the tree and+ # compares -- would then agree with the replacement, so the check that exists to+ # notice a swap could never fire for one that landed during the download.+ engine_accelerator = _installed_accelerator_of(getattr(engine, "binary", None))if mode == "oneshot":# version() is None when a present binary can't run; fail now, not on the first generation.assert engine is not None@@ -985,20 +1158,106 @@ class SdCppDiffusionBackend:upgraded = self._upgrade_server_after_teardown(server_binary)if mode == "server":server_binary = upgraded+ # This load's own install just rewrote the tree, under the install claim, so+ # what it left behind IS the decision here -- comparing against the answer+ # from before it would fail the load on the upgrade it asked for. Both pins+ # move: a serverless upgrade lands the sd-cli out of the same archive.+ server_accelerator = _installed_accelerator_of(server_binary)+ engine_accelerator = _installed_accelerator_of(getattr(engine, "binary", None))# A new checkpoint earns a fresh attempt on the GPU backend: the previous abort says nothing about this graph.self._cpu_backend_forced = Falseserver: Optional[SdCppServer] = Noneif mode == "server":assert server_binary is not None- server = SdCppServer(server_binary)- # The object to clear from _pending_server below. ``server`` itself is set to- # None when start() fails and the load falls back to one-shot, and comparing- # THAT against _pending_server left the stopped server published forever --- # which now reads as "the managed tree is busy" for the rest of the process.- started = server- # Publish the uncommitted server so unload() / a superseding load can stop it mid-startup instead of waiting out the timeout.- with self._lock:- self._pending_server = server+ # _fetch_assets above runs for minutes with no claim on the tree (there is+ # nothing executing in it yet to claim for), so an install can have swept this+ # path between layouts since _resolve_backend picked it. Re-resolve before+ # starting: the stale path would drop the load to one-shot for nothing, or+ # start a build this load did not select.+ #+ # Under the READER, and held until _pending_server is published. Re-resolving+ # alone does not close the race: allow_install=False only declines to install,+ # it does not wait for or claim the tree, so an installer that has already+ # passed its in-use check can sweep this executable between the re-read and+ # the start. Once _pending_server is published, _tree_in_use covers it and the+ # claim is no longer what is holding the installer off.+ with _tree_reader(server_binary, cancel_event):+ refreshed = ensure_sd_server_binary(+ allow_install = False, accelerator = self._resolved_accelerator()+ )+ if refreshed and refreshed != server_binary:+ logger.info(+ "sd-server moved during the asset download: %s -> %s",+ server_binary,+ refreshed,+ )+ server_binary = refreshed+ if not server_binary or not _server_binary_runnable(server_binary):+ # Nothing runnable survived the replacement; the one-shot CLI is the+ # documented fallback and _resolve_engine re-resolves it from scratch.+ logger.warning(+ "sd-server is no longer usable after the asset download; "+ "falling back to one-shot sd-cli."+ )+ mode, server_binary, engine = "oneshot", None, self._resolve_engine()+ # And pin off THIS engine. The one-shot pin above was taken while the+ # mode was still "server", i.e. off an engine of None, so leaving it+ # would compare the sd-cli just resolved against None and refuse the+ # documented fallback on every load that reaches it. Resolved here,+ # inside the claim, so it is vetted at the moment it is pinned.+ engine_accelerator = _installed_accelerator_of(+ getattr(engine, "binary", None)+ )+ elif _installed_accelerator_of(server_binary) != server_accelerator:+ # Runnable, and at the same path -- and still not the build this load+ # resolved. An install that landed during the download (an H3 load+ # putting the CPU fallback in, say) leaves a server that starts+ # perfectly well on a device this load has already committed elsewhere,+ # so it would generate on the CPU while the GPU offload policy and the+ # arbiter's accounting both describe a GPU run. Asked here, inside the+ # claim, where no further install can start: refusing costs a retry+ # that re-resolves device, accelerator and install from scratch.+ raise RuntimeError(+ "The stable-diffusion.cpp server binary was replaced by an install "+ "for a different accelerator while this model was loading. Try the "+ "load again."+ )+ else:+ server = SdCppServer(server_binary)+ # Published INSIDE the claim: _tree_in_use reads _pending_server, so+ # this is the handover from "a reader holds the tree" to "a starting+ # server does", with no gap between them.+ #+ # Cancellation is re-read in the SAME block. The revalidation above+ # can sit for 20s in _server_binary_runnable, and an unload arriving+ # in that window finds no _pending_server to stop, so without this the+ # load would go on to spawn the process anyway and hold the device for+ # the whole start() timeout before the commit below noticed. Asked+ # under the lock that publishes, so an unload either stops this server+ # or is seen here; it cannot fall between the two.+ with self._lock:+ if self._load_token != _load_token or cancel_event.is_set():+ server = None+ else:+ started = server+ self._pending_server = server+ if server is None:+ raise SdCppCancelled()+ if mode == "server":+ assert server_binary is not None+ assert server is not None+ # ``started`` (set with _pending_server above) is the object to clear below.+ # ``server`` itself is set to None when start() fails and the load falls back+ # to one-shot, and comparing THAT against _pending_server left the stopped+ # server published forever, which reads as "the managed tree is busy" for the+ # rest of the process.+ #+ # A server that DID start stays published until _state takes it over, under the+ # same lock. Clearing it here would leave a window in which the tree reads as+ # idle -- no reader, no pending, no state -- while the process is up and+ # running out of it, and an ensure_* landing in that window admits an install+ # that later overwrites the executable underneath the live server.+ started_ok = Falsetry:# Blocks until the model is loaded and answering; raises with the log tail on failure.server.start(@@ -1009,6 +1268,7 @@ class SdCppDiffusionBackend:# Pin to physical cores (sd.cpp's default oversubscribes; see _default_threads).threads = _default_threads(),)+ started_ok = Trueexcept SdCppCancelled:# Aborted by unload / superseding load: stop the half-started server and bail.server.stop()@@ -1027,17 +1287,43 @@ class SdCppDiffusionBackend:if self._pending_server is server:self._pending_server = Noneserver = None+ # KEEP the engine this fallback resolved. Discarding it left the local+ # `engine` at the server path's None, so state.sd_accelerator was recorded+ # as None and the first one-shot generation, which re-resolves sd-cli and+ # reads its real accelerator, rejected it as a different-accelerator+ # replacement: the load reports success and then cannot generate.+ fallback: Optional[SdCppEngine] = Nonetry:- usable = self._resolve_engine().version() is not None+ fallback = self._resolve_engine()+ usable = fallback.version() is not Noneexcept Exception: # noqa: BLE001usable = False- if not usable:+ if not usable or fallback is None:raise start_exc+ engine = fallback+ # Vetted here, so pinned here: this engine was resolved after the+ # download, inside the claim, and holding it to the pre-download answer+ # would refuse the fallback on an install this load already lived through.+ engine_accelerator = _installed_accelerator_of(+ getattr(fallback, "binary", None)+ )mode = "oneshot"finally:- with self._lock:- if self._pending_server is started:- self._pending_server = None+ if not started_ok:+ with self._lock:+ if self._pending_server is started:+ self._pending_server = None+ if mode == "oneshot" and (+ _installed_accelerator_of(getattr(engine, "binary", None)) != engine_accelerator+ ):+ # Runnable, at the same path, and still not the build this load vetted -- the+ # one-shot half of the check the server path makes just above. Refused at load+ # rather than recorded, because recording the replacement is what makes the+ # per-generation comparison agree with it forever after.+ 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."+ )state = _SdState(repo_id = repo_id,base_repo = base,@@ -1056,15 +1342,32 @@ class SdCppDiffusionBackend:hf_token = hf_token,gguf_filename = gguf_filename,flux2_inner_dim = inner_dim,+ # Only the one-shot path needs to carry it: it re-resolves sd-cli per image,+ # long after this decision, and has nothing else to check the answer against.+ sd_accelerator = engine_accelerator if mode == "oneshot" else None,)+ superseded = False+ orphan: Optional[SdCppServer] = Nonewith self._lock:if self._load_token != _load_token:- # Superseded / unloaded while loading: discard the started server so it doesn't leak.+ # Superseded / unloaded while loading: discard the started server so it+ # doesn't leak. Reserved in the SAME block that unpublishes it, so the tree+ # never reads as idle while the process is still coming down.+ superseded = Trueif server is not None:- server.stop()- return- self._state = state- self._loading = None+ self._reserve_stop()+ orphan = server+ else:+ self._state = state+ self._loading = None+ # The exchange the started server stayed published for: it is _state's now, or+ # reserved for the stop below, and either way _tree_in_use still sees it.+ if self._pending_server is started:+ self._pending_server = None+ if orphan is not None:+ self._stop_reserved(orphan)+ if superseded:+ returnexcept SdCppCancelled:returnexcept Exception as exc: # noqa: BLE001 -- surfaced via load_progress@@ -1077,6 +1380,14 @@ class SdCppDiffusionBackend:with self._lock:if self._load_token == _load_token and self._loading is not None:self._loading.error = redact_native_paths(str(exc))+ finally:+ # Backstop for the window the started server is deliberately left published across+ # (start() -> _state). Every path through that window unpublishes it itself; this only+ # catches an unexpected raise in between, which would otherwise wedge the tree as busy.+ if started is not None:+ with self._lock:+ if self._pending_server is started:+ self._pending_server = Nonedef download_plan(self,@@ -1842,17 +2153,44 @@ class SdCppDiffusionBackend:lora_dir = lora_dir,lora_apply_mode = "auto" if lora_dir else None,)- engine.generate(- state.files,- params,- output_path = out_path,- offload = list(state.offload_flags) or None,- native_speed = state.native_speed,- threads = state.threads,- extra_args = extra_args or None,- on_log = self._on_log,- cancel_event = cancel,- )+ # Each sd-cli run executes out of the managed tree, so hold installs off for its+ # duration (and wait here if one is already extracting).+ # getattr: an INJECTED engine is the unit-test seam / escape hatch and need not+ # name a file at all, and nothing without a path is a binary an install replaces.+ with _tree_reader(getattr(engine, "binary", None), cancel):+ # Re-resolve INSIDE the claim. An install that finished while this image was+ # waiting can have put its sd-cli somewhere else and swept the copy resolved+ # above, so the cached path would launch a file that is no longer there. Also+ # covers a batch, which releases the claim between images. Cheap when nothing+ # moved: _resolve_engine returns the cached engine whose binary still exists.+ engine = self._resolve_engine()+ # Existence is not identity here either. The install that moved the CLI may+ # have been for a different accelerator (an H3 load putting the CPU fallback+ # in, say), and this state's device and offload policy were chosen for the+ # other one, so running it would either spend unaccounted VRAM or drop the+ # whole generation onto the CPU while the arbiter's accounting says otherwise.+ # The server path refuses exactly this mismatch before it starts; refusing here+ # costs a reload, which re-resolves device, accelerator and install together.+ if (+ _installed_accelerator_of(getattr(engine, "binary", None))+ != state.sd_accelerator+ ):+ raise RuntimeError(+ "The stable-diffusion.cpp binary was replaced by an install for a "+ "different accelerator while this model was loaded. Load the model "+ "again."+ )+ engine.generate(+ state.files,+ params,+ output_path = out_path,+ offload = list(state.offload_flags) or None,+ native_speed = state.native_speed,+ threads = state.threads,+ extra_args = extra_args or None,+ on_log = self._on_log,+ cancel_event = cancel,+ )with Image.open(out_path) as im:images.append(im.copy())seeds.append(seed_i)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex b3a655e09c4..89101fade06 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -505,6 +505,21 @@ class _VideoLoadingState:asset_repos: tuple[str, ...] = ()+def _sd_cli_identity(binary: Optional[str]) -> Optional[tuple[int, int]]:+ """``(size, mtime_ns)`` of an sd.cpp binary, or None when it cannot be read.++ Enough to tell "the build we vetted at load" from "whatever an install left at that path",+ without a subprocess on every generation. Never raises: an unreadable path is None, which the+ caller reads as a change."""+ if not binary:+ return None+ try:+ stat = Path(binary).stat()+ except OSError:+ return None+ return (stat.st_size, stat.st_mtime_ns)++def _h3_te_canonical(repo_id: Optional[str]) -> str:"""A repo id normalised for an EXACT identity compare: mirrors folded onto the id they copy,then trimmed and lowercased. Deliberately no tail-segment tolerance -- ``someone/MiniMax-H3``@@ -1366,7 +1381,20 @@ class VideoBackend:accelerator = _install_accelerator_for(target.backend),)native_device = target.device- if target.backend not in ("cpu", "mps") and not sd_cpp_lists_accelerator_device(binary):+ # 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.@@ -1379,11 +1407,52 @@ class VideoBackend:# 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 = Falseengine = SdCppEngine(binary)- if not binary or engine.version() is None:- raise RuntimeError(- "stable-diffusion.cpp could not be installed or started for MiniMax-H3."- )+ # 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+ # in-place replacement would then become the recorded identity without ever having been+ # 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_engine import is_managed_binary++ with _tree_reader(binary, cancel_event, VIDEO_CANCELLED_MSG):+ if not binary or engine.version() is None:+ 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):+ raise RuntimeError(+ "The stable-diffusion.cpp binary was replaced by an install that does not "+ "support MiniMax-H3. 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+ # native_device is about to be committed for the life of this runtime. A CPU fallback+ # committed around a CUDA executable runs on VRAM nothing accounted for, next to+ # whatever the arbiter let in on the strength of this load claiming the CPU.+ #+ # 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.+ if (+ listed_accelerator is not None+ and is_managed_binary(binary)+ and sd_cpp_lists_accelerator_device(binary) != 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."+ )+ binary_identity = _sd_cli_identity(binary)requested_mode = normalize_memory_mode(memory_mode) or "auto"policy = {"auto": "none" if native_device == "cpu" else "group",@@ -1417,6 +1486,10 @@ class VideoBackend:runtime = MiniMaxH3NativeRuntime(engine = engine,+ # Pinned under the reader claim above, where this exact file answered --help with the+ # H3 options. Taking it at generation time instead would compare a replacement against+ # itself.+ binary_identity = binary_identity,files = SdCppModelFiles(diffusion_model = str(resolved[0]),llm = str(resolved[1]),@@ -4884,32 +4957,66 @@ class VideoBackend:init_img = stage(first_frame, "first")end_img = stage(last_frame, "last")staged = stage_h3_references(references, Path(scratch))+ # An H3 native run is an sd-cli run out of the managed tree, exactly like a one-shot+ # image generation, so it takes the same reader claim. Without it an image-engine+ # request sees no readers, starts an install, and the sweep unlinks the CLI this+ # runtime resolved at load: on Linux this process survives on the open inode but the+ # next video request launches a path that is gone, and on Windows the unlink fails and+ # leaves a mixed tree. A claim held here also makes the install stand down instead.+ from .sd_cpp_backend import _tree_reader++ binary = getattr(runtime.engine, "binary", None)+ # Identity, not existence, and the identity RECORDED AT LOAD. An install can replace+ # the binary in place, leaving a file that still exists but is not the build+ # ensure_h3_sd_cpp_binary vetted: a different accelerator, or one predating the H3+ # options, which aborts partway through a render nobody wants to repeat. Comparing two+ # reads taken now would miss that entirely whenever the install landed before this+ # generation started, since both would see the replacement and agree.+ binary_identity = getattr(runtime, "binary_identity", None)try:try:- generated = runtime.engine.generate_video(- runtime.files,- SdCppVideoGenParams(- prompt = prompt,- width = width,- height = height,- num_frames = frames,- fps = fps,- steps = steps,- cfg_scale = 1.0,- seed = int(seed),- init_img = init_img,- end_img = end_img,- ref_images = staged.images,- ref_videos = staged.videos,- ref_video_audios = staged.video_audios,- ref_audios = staged.audios,- flow_shift = flow_shift,- ),- output_path = str(output_path),- offload = list(runtime.offload_flags),- on_log = on_log,- cancel_event = cancel,- )+ with _tree_reader(binary, cancel, VIDEO_CANCELLED_MSG):+ current_identity = _sd_cli_identity(binary)+ # Unreadable now (swept), or readable but not what the load vetted. A+ # runtime carrying no recorded identity cannot answer the second question,+ # so it is held to the first rather than refused outright.+ if binary and (+ current_identity is None+ or (binary_identity is not None and current_identity != binary_identity)+ ):+ # The engine is committed at load, so this cannot be re-resolved+ # underneath a live generation the way the image path can. Say so+ # plainly instead of running an unvetted build or surfacing an ENOENT+ # from the subprocess.+ raise RuntimeError(+ "The stable-diffusion.cpp binary this model was loaded with was "+ "replaced by an install, so it is no longer the build this model "+ "was checked against. Reload the model and try again."+ )+ generated = runtime.engine.generate_video(+ runtime.files,+ SdCppVideoGenParams(+ prompt = prompt,+ width = width,+ height = height,+ num_frames = frames,+ fps = fps,+ steps = steps,+ cfg_scale = 1.0,+ seed = int(seed),+ init_img = init_img,+ end_img = end_img,+ ref_images = staged.images,+ ref_videos = staged.videos,+ ref_video_audios = staged.video_audios,+ ref_audios = staged.audios,+ flow_shift = flow_shift,+ ),+ output_path = str(output_path),+ offload = list(runtime.offload_flags),+ on_log = on_log,+ cancel_event = cancel,+ )except SdCppCancelled:raise RuntimeError(VIDEO_CANCELLED_MSG) from Noneif cancel.is_set():diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.pyindex efd2bac8f4d..0e2370b7fb2 100644--- a/studio/backend/core/inference/video_minimax_h3.py+++ b/studio/backend/core/inference/video_minimax_h3.py@@ -715,6 +715,13 @@ class MiniMaxH3NativeRuntime:engine: Anyfiles: Anyoffload_flags: tuple[str, ...]+ # (size, mtime_ns) of the sd-cli this runtime was built on, taken at load, right after+ # ensure_h3_sd_cpp_binary vetted it for H3 support and accelerator. Every generation compares+ # against THIS, not against whatever the path holds when it starts: an install that lands+ # between the load and a generation replaces the binary in place, and two reads taken after it+ # agree with each other while agreeing with nothing that was ever checked. None means the+ # identity could not be taken, which reads as "cannot vouch" rather than "unchanged".+ binary_identity: Optional[tuple[int, int]] = Nonedef transcode_video_to_mp4(source: Path, *, fps: int) -> bytes:diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex c11bc6a34fa..ca2d507fd5d 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -765,6 +765,36 @@ def test_generate_passes_vae_format_for_flux2():assert kw.get("extra_args") == ["--vae-format", "flux2"]+def test_oneshot_generate_refuses_a_binary_swapped_for_another_accelerator(monkeypatch):+ # The one-shot path re-resolves sd-cli per image, so an install landing between two images of+ # a batch is adopted silently. Existence is not identity: the install may have been for a+ # DIFFERENT accelerator (an H3 load dropping the CPU fallback in, say), while this state's+ # device and offload flags were chosen for the other build. Running it would either spend+ # unaccounted VRAM or put the whole generation on the CPU with the arbiter's accounting still+ # claiming the GPU. The server path already refuses exactly this before it starts.+ import dataclasses++ b = _loaded_backend()+ b._state = dataclasses.replace(b._state, sd_accelerator = "cuda")+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda _binary: "cpu")+ with pytest.raises(RuntimeError, match = "different accelerator"):+ b.generate(prompt = "x", steps = 4, seed = 1)+++def test_oneshot_generate_accepts_a_binary_for_the_same_accelerator(monkeypatch):+ # The control for the test above: the guard must not fire on the ordinary case, where the+ # re-resolved binary is the build this load committed to. Without this a reload-on-every-image+ # regression would look exactly like a passing guard.+ import dataclasses++ eng = _FakeEngine()+ b = _loaded_backend(engine = eng)+ b._state = dataclasses.replace(b._state, sd_accelerator = "cuda")+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda _binary: "cuda")+ b.generate(prompt = "x", steps = 4, seed = 1)+ assert len(eng.calls) == 1++def test_generate_cancellation_raises_cancelled_not_failure():# The engine cancels mid-run; the backend surfaces a cancellation, not a crash.eng = _FakeEngine(cancel_on_call = True)@@ -968,6 +998,32 @@ def test_h3_binary_gate_replaces_a_stale_managed_install(monkeypatch, tmp_path):assert not stale.exists()+def test_h3_binary_gate_defers_while_a_generation_holds_the_tree(monkeypatch, tmp_path):+ # Dropping the stale copy WRITES to the managed tree, so it takes the same admission an install+ # does. A one-shot image generation may be executing that very file: on Linux the running child+ # survives the unlink but the next image in the batch can no longer resolve it, and on Windows+ # the unlink fails outright. Deferring costs one retry on a later load.+ stale = tmp_path / "stale" / "sd-cli"+ stale.parent.mkdir()+ stale.write_text("binary")+ ensures: list[bool] = []++ monkeypatch.setattr(+ bk,+ "ensure_sd_cpp_binary",+ lambda **kwargs: (ensures.append(kwargs.get("allow_install", True)), str(stale))[1],+ )+ monkeypatch.setattr(bk, "is_managed_binary", lambda _b: True)+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_args: _PRE_H3_HELP)+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)++ with bk._tree_reader(str(stale)):+ assert bk.ensure_h3_sd_cpp_binary() is None+ # The binary the generation is running is still there, and no reinstall was attempted behind it.+ assert stale.exists()+ assert ensures == [True]++def test_h3_binary_gate_refuses_but_keeps_a_user_supplied_build(monkeypatch, tmp_path):# Same ownership split as _usable_or_discard_managed: the user's own build is not ours to# delete (install() then refuses the still non-empty unmarked directory, leaving no binary at@@ -1367,6 +1423,66 @@ def test_server_reload_stops_old_server_before_new(monkeypatch):assert b._state.server is servers[1] and servers[1].stopped is False+def test_a_cancel_during_server_revalidation_stops_before_the_process_spawns(monkeypatch):+ # _server_binary_runnable re-probes the binary and can sit there for 20s. An unload arriving+ # in that window finds no _pending_server to stop, because the publish happens after the+ # probe returns. Without a recheck inside the SAME lock that publishes, the load goes on to+ # spawn sd-server anyway and holds the device for the whole start() timeout before anything+ # notices. Asking under the publishing lock is what closes the gap: an unload either stops+ # this server or is seen here, and it cannot fall between the two.+ b = SdCppDiffusionBackend()+ cancel = threading.Event()+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")++ def _revalidate_then_cancel(*_a, **_k):+ cancel.set() # the unload lands while we were probing+ return True++ monkeypatch.setattr(bk, "_server_binary_runnable", _revalidate_then_cancel)++ started: list[str] = []++ class _RecordingServer:+ def __init__(self, binary):+ self.stopped = False++ def start(self, *a, **k):+ started.append("start")++ def stop(self):+ self.stopped = True++ monkeypatch.setattr(bk, "SdCppServer", _RecordingServer)+ fake = _FakeEngine()+ monkeypatch.setattr(b, "_resolve_engine", lambda: fake)+ monkeypatch.setattr(b, "_asset_specs", lambda *a, **k: [])+ monkeypatch.setattr(b, "_set_expected_bytes", lambda *a, **k: None)+ monkeypatch.setattr(+ b,+ "_fetch_assets",+ lambda *a, **k: {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"},+ )+ monkeypatch.setattr(+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cpu")+ )+ fam = detect_family("z-image")+ b._load_token = 1+ b._run_load(+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z.gguf",+ base = fam.base_repo,+ fam = fam,+ hf_token = None,+ _load_token = 1,+ _cancel_event = cancel,+ )+ assert started == [], "a cancelled load must not spawn the server process"+ # Same contract as the start-failure path: a leaked _pending_server reads as "the managed+ # tree is busy" for the rest of the process and blocks every later install.+ assert b._pending_server is None+ assert bk._tree_in_use(b) is False++def test_server_start_failure_falls_back_to_oneshot(monkeypatch):# A present-but-broken sd-server must not fail the load when sd-cli works.b = SdCppDiffusionBackend()@@ -1418,6 +1534,160 @@ def test_server_start_failure_falls_back_to_oneshot(monkeypatch):assert len(out["images"]) == 1 and len(fake.calls) == 1+def test_server_start_failure_keeps_the_engine_the_fallback_resolved(monkeypatch):+ # The fallback resolved an sd-cli and then threw it away, keeping the server path's engine of+ # None. state.sd_accelerator was recorded off that None, so the first one-shot generation --+ # which re-resolves sd-cli and reads its REAL accelerator -- saw a mismatch and refused the+ # binary it had just fallen back to. The documented start-failure fallback loaded fine and+ # then could not generate at all.+ b = SdCppDiffusionBackend()+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)++ class _BadServer:+ def __init__(self, binary):+ pass++ def start(self, *a, **k):+ raise RuntimeError("sd-server broken")++ def stop(self):+ pass++ monkeypatch.setattr(bk, "SdCppServer", _BadServer)+ fake = _FakeEngine()+ fake.binary = "/x/sd-cli"+ monkeypatch.setattr(b, "_resolve_engine", lambda: fake)+ monkeypatch.setattr(b, "_asset_specs", lambda *a, **k: [])+ monkeypatch.setattr(b, "_set_expected_bytes", lambda *a, **k: None)+ monkeypatch.setattr(+ b,+ "_fetch_assets",+ lambda *a, **k: {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"},+ )+ monkeypatch.setattr(+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cpu")+ )+ # Keyed on the binary, not constant: the whole bug is that the recorded accelerator was read+ # off None, so a stub that answers the same for every argument would pass either way.+ monkeypatch.setattr(+ bk, "_installed_accelerator_of", lambda binary: "cuda" if binary == "/x/sd-cli" else None+ )+ fam = detect_family("z-image")+ b._load_token = 1+ b._run_load(+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z.gguf",+ base = fam.base_repo,+ fam = fam,+ hf_token = None,+ _load_token = 1,+ )+ assert b._state is not None and b._state.mode == "oneshot"+ assert b._state.sd_accelerator == "cuda"+ # The check the recorded value exists for: the per-image re-resolution must accept the very+ # binary this load fell back to.+ out = b.generate(prompt = "x", steps = 4, seed = 1)+ assert len(out["images"]) == 1 and len(fake.calls) == 1+++def test_server_unusable_after_the_download_keeps_the_engine_the_fallback_resolved(monkeypatch):+ # The other server -> one-shot fallback, the one taken when the re-resolution under the reader+ # claim finds sd-server no longer usable. It resolves an sd-cli, but the one-shot accelerator+ # pin was taken back when the mode was still "server", i.e. off an engine of None. The pin is+ # then compared against the sd-cli the fallback just resolved, so a load that should have+ # dropped cleanly to one-shot is refused as a swapped binary instead.+ b = SdCppDiffusionBackend()+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")+ # Runnable up front so the pre-download fallback is not the path under test; unusable by the+ # time the claim re-checks it, which is what sends the load to sd-cli after the download.+ runnable = [True]++ def _runnable(*_a, **_k):+ answer = runnable[0]+ runnable[0] = False+ return answer++ monkeypatch.setattr(bk, "_server_binary_runnable", _runnable)+ monkeypatch.setattr(bk, "ensure_sd_server_binary", lambda **_k: "/x/sd-server")+ fake = _FakeEngine()+ fake.binary = "/x/sd-cli"+ monkeypatch.setattr(b, "_resolve_engine", lambda: fake)+ monkeypatch.setattr(b, "_asset_specs", lambda *a, **k: [])+ monkeypatch.setattr(b, "_set_expected_bytes", lambda *a, **k: None)+ monkeypatch.setattr(+ b,+ "_fetch_assets",+ lambda *a, **k: {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"},+ )+ monkeypatch.setattr(+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cpu")+ )+ # One tree, one accelerator, and nothing replaces it during this load: every refusal this test+ # can see is the pin being read off the wrong engine, never a genuine swap.+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: "cuda" if binary else None)+ fam = detect_family("z-image")+ b._load_token = 1+ b._loading = bk._SdLoading(repo_id = "unsloth/Z-Image-Turbo-GGUF", base_repo = fam.base_repo)+ b._run_load(+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z.gguf",+ base = fam.base_repo,+ fam = fam,+ hf_token = None,+ _load_token = 1,+ )+ assert b._state is not None, f"the fallback was refused: {b.load_progress().get('error')}"+ assert b._state.mode == "oneshot" and b._state.server is None+ assert b._state.sd_accelerator == "cuda"+ out = b.generate(prompt = "x", steps = 4, seed = 1)+ assert len(out["images"]) == 1 and len(fake.calls) == 1+++def test_a_oneshot_load_refuses_a_cli_swapped_during_the_asset_download(monkeypatch):+ # The one-shot accelerator was sampled at state construction, AFTER the multi-minute asset+ # download, so an install landing in that window was recorded as this load's own answer. The+ # per-image check then re-read the same replacement and agreed with it forever, which is the+ # one swap it exists to catch. Pinned where the engine is vetted instead, and refused here.+ b = SdCppDiffusionBackend()+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: None)+ monkeypatch.setattr(bk, "_install_allowed", lambda: False)+ fake = _FakeEngine()+ fake.binary = "/x/sd-cli"+ monkeypatch.setattr(b, "_resolve_engine", lambda: fake)+ monkeypatch.setattr(b, "_asset_specs", lambda *a, **k: [])+ monkeypatch.setattr(b, "_set_expected_bytes", lambda *a, **k: None)+ monkeypatch.setattr(+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cpu")+ )+ # cuda when the engine is chosen, cpu by the time the download finishes: an H3 load putting+ # the CPU fallback in is the documented way this happens.+ installed = ["cuda"]+ monkeypatch.setattr(+ bk, "_installed_accelerator_of", lambda binary: installed[0] if binary else None+ )++ def _fetch(*a, **k):+ installed[0] = "cpu"+ return {"diffusion_model": "/m/z.gguf", "vae": "/m/vae.sft", "llm": "/m/llm.sft"}++ monkeypatch.setattr(b, "_fetch_assets", _fetch)+ fam = detect_family("z-image")+ b._load_token = 1+ b._loading = bk._SdLoading(repo_id = "unsloth/Z-Image-Turbo-GGUF", base_repo = fam.base_repo)+ b._run_load(+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z.gguf",+ base = fam.base_repo,+ fam = fam,+ hf_token = None,+ _load_token = 1,+ )++ assert b._state is None+ assert "different accelerator" in (b.load_progress()["error"] or "")++def test_run_load_redacts_paths_in_progress_error(monkeypatch):# A load failure surfaced via load_progress() must run through redact_native_paths, the same scrub the diffusers path applies.from utils import native_path_leases as npldiff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.pyindex fe2af041ef0..ff73d226dab 100644--- a/studio/backend/tests/test_sd_cpp_install.py+++ b/studio/backend/tests/test_sd_cpp_install.py@@ -21,6 +21,7 @@ import hashlib # noqa: E402import builtins # noqa: E402import types # noqa: E402import threading # noqa: E402+import time # noqa: E402import io # noqa: E402import re # noqa: E402import json # noqa: E402@@ -1521,38 +1522,189 @@ def test_a_failed_server_upgrade_is_not_retried_by_the_cli_probe(tmp_path, monkeassert attempts == ["cuda"], "the same bundle must not be resolved twice in one selection"-def test_an_archive_without_a_server_drops_the_previous_one(tmp_path, monkeypatch):- """An upgrade whose archive ships only sd-cli left the OLD accelerator's sd-server in place,- while the record labelled the whole tree as the new accelerator: the backend then rediscovered- that stale server, trusted the record, and ran a CUDA request on the old CPU build forever."""+def test_a_bundle_drops_the_binaries_it_did_not_supply(tmp_path, monkeypatch):+ """Extraction MERGES, so a bundle whose layout differs from the previous one (or that ships no+ server at all) leaves the old accelerator's executables behind -- and _layout_candidates+ prefers build/bin over the prebuilt's versioned subdirectory, so the stale copy keeps winning+ while the record claims the new accelerator."""target = tmp_path / "sd"- (target / "sd-bin").mkdir(parents = True)- stale = target / "sd-bin" / ("sd-server.exe" if sys.platform == "win32" else "sd-server")- stale.write_bytes(b"old-cpu-server")+ suffix = ".exe" if sys.platform == "win32" else ""+ old_dir = target / "build" / "bin"+ old_dir.mkdir(parents = True)+ (old_dir / f"sd-cli{suffix}").write_bytes(b"old-cpu-cli")+ (old_dir / f"sd-server{suffix}").write_bytes(b"old-cpu-server")+ new_dir = target / "sd-bundle-cuda12" / "bin"+ new_dir.mkdir(parents = True)+ (new_dir / f"sd-cli{suffix}").write_bytes(b"new-cuda-cli")- cli_name = "sd-cli.exe" if sys.platform == "win32" else "sd-cli"buf = io.BytesIO()with zipfile.ZipFile(buf, "w") as zf:- zf.writestr(f"bin/{cli_name}", "new")+ zf.writestr(f"sd-bundle-cuda12/bin/sd-cli{suffix}", "new")buf.seek(0)with zipfile.ZipFile(buf) as zf:- assert sdmod._archive_ships_sd_server(zf) is False+ supplied = sdmod._archive_binary_paths(zf, target)- sdmod._discard_stale_sd_server(target)- assert not stale.exists()- assert sdmod._locate_sd_server(target) is None+ sdmod._discard_superseded_binaries(target, supplied)+ # Everything this bundle did not write is gone, whatever its path or name.+ assert not (old_dir / f"sd-cli{suffix}").exists()+ assert not (old_dir / f"sd-server{suffix}").exists()+ # What it did write stays.+ assert (new_dir / f"sd-cli{suffix}").read_bytes() == b"new-cuda-cli"-def test_an_archive_that_does_ship_a_server_keeps_it(tmp_path):- """The removal must key on the archive's member list, not on what is on disk: a bundle that- ships its own sd-server has just written it, and deleting that would break every upgrade."""- server_name = "sd-server.exe" if sys.platform == "win32" else "sd-server"+def test_a_bundle_keeps_every_binary_it_wrote(tmp_path):+ """The sweep must key on the archive's member list, not on what is on disk: deleting a copy+ the bundle just extracted would break every install."""+ target = tmp_path / "sd"+ suffix = ".exe" if sys.platform == "win32" else ""+ d = target / "bin"+ d.mkdir(parents = True)+ (d / f"sd-cli{suffix}").write_bytes(b"new")+ (d / f"sd-server{suffix}").write_bytes(b"new")+buf = io.BytesIO()with zipfile.ZipFile(buf, "w") as zf:- zf.writestr(f"bin/{server_name}", "new")+ zf.writestr(f"bin/sd-cli{suffix}", "new")+ zf.writestr(f"bin/sd-server{suffix}", "new")buf.seek(0)with zipfile.ZipFile(buf) as zf:- assert sdmod._archive_ships_sd_server(zf) is True+ supplied = sdmod._archive_binary_paths(zf, target)++ sdmod._discard_superseded_binaries(target, supplied)+ assert (d / f"sd-cli{suffix}").exists() and (d / f"sd-server{suffix}").exists()+++def test_a_superseded_binary_that_cannot_be_removed_fails_the_install(tmp_path, monkeypatch):+ """A leftover binary is still RUNNABLE, so no downstream probe repairs it, and a record naming+ the new accelerator would make _accelerator_changed trust it forever. Withhold both."""+ target = tmp_path / "sd"+ target.mkdir()+ suffix = ".exe" if sys.platform == "win32" else ""+ (target / f"sd-server{suffix}").write_bytes(b"old-cpu-server")++ def _no_unlink(self, *a, **k):+ raise OSError("permission denied")++ monkeypatch.setattr(Path, "unlink", _no_unlink)+ with pytest.raises(sdmod.SupersededBinaryError) as exc:+ sdmod._discard_superseded_binaries(target, set())+ assert "superseded binary" in str(exc.value)+++def test_a_bundle_with_no_cli_is_refused_before_anything_is_swept(tmp_path, monkeypatch, capsys):+ """The sweep deletes every managed binary the bundle did not write, so an archive that ships+ no sd-cli would take the working one with it -- and only then would the malformed-bundle check+ fire. ensure_sd_cpp_binary keeps that copy precisely so a failed upgrade still leaves something+ to generate with, so the refusal has to come first."""+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("build/bin/sd-server", b"#!/bin/sh\necho sd-server\n")+ zb = buf.getvalue()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())++ target = tmp_path / "sd"+ (target / "build" / "bin").mkdir(parents = True)+ working = target / "build" / "bin" / "sd-cli"+ working.write_bytes(b"old-but-working")+ (target / ".unsloth-studio-owned").touch()++ with pytest.raises(RuntimeError) as exc:+ install(install_dir = target)+ assert "no sd-cli" in str(exc.value)+ # The fallback the caller was counting on is still there.+ assert working.read_bytes() == b"old-but-working"+ # And nothing claimed the tree is the new accelerator.+ assert "removed a superseded binary" not in capsys.readouterr().out+++def test_an_unreadable_record_does_not_retire_the_memo(tmp_path, monkeypatch):+ """The memo exists for a record this process could not WRITE. A record it cannot READ right+ now (another writer holding it open, a permission blip) is not evidence that someone else+ rewrote it, and retiring the memo on that hands the next selection the stale accelerator --+ a multi-GB reinstall on every load."""+ root = tmp_path / "sd"+ root.mkdir()+ with open(root / sdmod.INSTALL_RECORD, "w", encoding = "utf-8") as f:+ json.dump({"accelerator": "cpu", "repo": "r", "tag": "old"}, f)+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()++ real_open = builtins.open++ def _readonly_record(+ file,+ mode = "r",+ *a,+ **k,+ ):+ if str(file).endswith(sdmod.INSTALL_RECORD) and "w" in mode:+ raise OSError("permission denied")+ return real_open(file, mode, *a, **k)++ monkeypatch.setattr(builtins, "open", _readonly_record)+ sdmod._write_install_record(root, accelerator = "cuda", repo = "r", tag = "t")+ monkeypatch.setattr(builtins, "open", real_open)+ assert sdmod.installed_accelerator(root) == "cuda"++ def _unreadable(+ file,+ mode = "r",+ *a,+ **k,+ ):+ if str(file).endswith(sdmod.INSTALL_RECORD):+ raise PermissionError("the file is open in another process")+ return real_open(file, mode, *a, **k)++ monkeypatch.setattr(builtins, "open", _unreadable)+ assert sdmod.installed_accelerator(root) == "cuda" # still the memo+ monkeypatch.setattr(builtins, "open", real_open)+ # And once the record is readable again and unchanged, the memo is still the answer.+ assert sdmod.installed_accelerator(root) == "cuda"+ assert str(root) in sdmod._INSTALLED_ACCELERATOR_MEMO+++def test_an_external_record_update_retires_the_memo(tmp_path, monkeypatch):+ """The memo speaks only for the record it could not replace. Once the installer CLI or another+ Studio rewrites that file, the file is the newer answer -- otherwise this process would keep+ reporting its own stale accelerator and treat the other one's CUDA binaries as a CPU match."""+ root = tmp_path / "sd"+ root.mkdir()+ with open(root / sdmod.INSTALL_RECORD, "w", encoding = "utf-8") as f:+ json.dump({"accelerator": "cpu", "repo": "r", "tag": "old"}, f)+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()++ real_open = builtins.open++ def _readonly_record(+ file,+ mode = "r",+ *a,+ **k,+ ):+ if str(file).endswith(sdmod.INSTALL_RECORD) and "w" in mode:+ raise OSError("permission denied")+ return real_open(file, mode, *a, **k)++ monkeypatch.setattr(builtins, "open", _readonly_record)+ sdmod._write_install_record(root, accelerator = "cuda", repo = "r", tag = "t")+ monkeypatch.setattr(builtins, "open", real_open)+ assert sdmod.installed_accelerator(root) == "cuda" # the memo answers for the record it saw++ # Someone else installs into the same root and DOES write the record.+ with open(root / sdmod.INSTALL_RECORD, "w", encoding = "utf-8") as f:+ json.dump({"accelerator": "vulkan", "repo": "r", "tag": "newer"}, f)+ assert sdmod.installed_accelerator(root) == "vulkan"+ assert str(root) not in sdmod._INSTALLED_ACCELERATOR_MEMO # and the memo is retired+++def test_a_successful_record_write_retires_an_earlier_memo(tmp_path, monkeypatch):+ """A memo from a failed write must not outlive the write that succeeds after it."""+ root = tmp_path / "sd"+ root.mkdir()+ sdmod._INSTALLED_ACCELERATOR_MEMO[str(root)] = ("cuda", "")+ sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t")+ assert str(root) not in sdmod._INSTALLED_ACCELERATOR_MEMO+ assert sdmod.installed_accelerator(root) == "cpu"def test_the_stop_is_reserved_before_the_server_is_unpublished(tmp_path, monkeypatch):@@ -1643,18 +1795,560 @@ def test_a_stale_unwritable_record_does_not_outrank_what_was_just_installed(tmp_assert sdmod.installed_accelerator(root) == "cuda"-def test_a_stale_server_that_cannot_be_removed_fails_the_install(tmp_path, monkeypatch):- """A leftover server is still RUNNABLE, so no downstream probe repairs it, and a record naming- the new accelerator would make _accelerator_changed trust it forever. Withhold both."""- root = tmp_path / "sd"- root.mkdir()- stale = root / ("sd-server.exe" if sys.platform == "win32" else "sd-server")- stale.write_bytes(b"old-cpu-server")+def test_a_generation_cannot_start_inside_the_install_window(tmp_path, monkeypatch):+ """The window a point-in-time check leaves open: the tree is idle when the install is decided,+ then the download runs for seconds or minutes, and a generation admitted in that gap launches+ the very sd-cli the extraction overwrites. Admission and the install are one decision, held+ across the whole install, not sampled before the download."""+ import core.inference.sd_cpp_backend as bk- def _no_unlink(self, *a, **k):- raise OSError("permission denied")+ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cpu")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cpu-build")+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)- monkeypatch.setattr(Path, "unlink", _no_unlink)+ started = threading.Event()+ release = threading.Event()+ admitted_during_install: list = []++ def _slow_install(**kwargs):+ started.set() # standing in for the multi-GB download+ release.wait(5)+ server.write_bytes(b"cuda-build")+ sdmod._write_install_record(root, accelerator = kwargs["accelerator"], repo = "r", tag = "t")+ return root / "sd-bin" / "sd-cli"++ monkeypatch.setattr(sdmod, "install", _slow_install)++ installer = threading.Thread(+ target = lambda: bk.ensure_sd_server_binary(accelerator = "cuda"), daemon = True+ )+ installer.start()+ assert started.wait(5), "the install did not start"++ def _try_generate():+ with bk._tree_reader(str(server)):+ admitted_during_install.append(bk._tree_installing)++ generator = threading.Thread(target = _try_generate, daemon = True)+ generator.start()+ generator.join(1.0)+ assert (+ generator.is_alive()+ ), "a generation must not be admitted while the tree is being replaced"+ assert admitted_during_install == []++ release.set()+ installer.join(5)+ generator.join(5)+ assert not generator.is_alive(), "the generation must be admitted once the install is done"+ assert admitted_during_install == [False]+ assert server.read_bytes() == b"cuda-build"+++def test_an_install_stands_down_while_a_generation_is_running(tmp_path, monkeypatch):+ """The other direction of the same handshake, so the two can never interleave."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cpu")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cpu-build")+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ monkeypatch.setattr(+ sdmod, "install", lambda **_k: pytest.fail("no install while a generation is running")+ )++ with bk._tree_reader(str(server)):+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)+ assert server.read_bytes() == b"cpu-build"+++def test_an_unmanaged_binary_never_waits_for_a_managed_install(tmp_path, monkeypatch):+ """An sd-cli from SD_CLI_PATH / UNSLOTH_SD_CPP_PATH / an in-tree build / PATH is one the+ installer cannot replace, so an install in flight is nothing to it. Claiming for it would stall+ the generation behind an unrelated multi-GB download for the whole timeout."""+ import core.inference.sd_cpp_backend as bk++ _managed_tree(tmp_path, monkeypatch)+ outside = tmp_path / "mine" / "sd-cli"+ outside.parent.mkdir(parents = True)+ outside.write_bytes(b"my own build")++ monkeypatch.setattr(bk, "_tree_installing", True) # an install is extracting right now+ monkeypatch.setattr(bk, "_TREE_WAIT_TIMEOUT_S", 0.2)+ with bk._tree_reader(str(outside)):+ pass # returns immediately, and does not register as a reader+ assert bk._tree_readers == 0+++def test_a_reader_is_never_admitted_when_the_install_wait_times_out(tmp_path, monkeypatch):+ """wait_for returns False on a timeout while _tree_installing is still true. Ignoring that and+ admitting anyway recreates the overwrite/ETXTBSY race this admission control exists for."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch)+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"managed")++ monkeypatch.setattr(bk, "_tree_installing", True)+ monkeypatch.setattr(bk, "_TREE_WAIT_TIMEOUT_S", 0.2)with pytest.raises(RuntimeError) as exc:- sdmod._discard_stale_sd_server(root)- assert "superseded sd-server" in str(exc.value)+ with bk._tree_reader(str(managed)):+ pytest.fail("a generation must not run against binaries an install still holds")+ assert "still replacing its binaries" in str(exc.value)+ assert bk._tree_readers == 0+++def test_an_incomplete_tree_replacement_is_retried_not_memoised(tmp_path, monkeypatch):+ """_discard_superseded_binaries withholds the record so the NEXT load retries the sweep.+ Recording the accelerator as a failed upgrade defeats exactly that: _accelerator_changed then+ suppresses the mismatch for the rest of the process and the mixed tree is served forever."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cpu")+ cli = root / "sd-bin" / "sd-cli"+ cli.write_bytes(b"old-cpu-cli")+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))+ monkeypatch.setattr(bk, "_usable_or_discard_managed", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)++ def _install_that_cannot_finish_the_swap(**_kwargs):+ raise sdmod.SupersededBinaryError("could not remove the superseded binary /x/sd-cli")++ monkeypatch.setattr(sdmod, "install", _install_that_cannot_finish_the_swap)+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)+ assert bk._failed_accelerator_upgrades == set()+ # So the mismatch is still visible and the next load tries the swap again.+ assert bk._accelerator_changed(str(cli), "cuda") is True++ # An ordinary install failure (no asset, no network) is still memoised, as before.+ monkeypatch.setattr(sdmod, "install", lambda **_k: (_ for _ in ()).throw(RuntimeError("404")))+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)+ assert bk._failed_accelerator_upgrades == {"cuda"}+++def test_a_generation_re_resolves_the_cli_the_install_moved(tmp_path, monkeypatch):+ """The engine is resolved before the wait, and an install that lands during it can put its+ sd-cli somewhere else and sweep the copy that was resolved. Launching the cached path then+ fails on a file that is no longer there, which is the failure the wait exists to prevent."""+ import core.inference.sd_cpp_backend as bk+ from core.inference.sd_cpp_engine import SdCppEngine++ root = _managed_tree(tmp_path, monkeypatch)+ old = root / "build" / "bin" / "sd-cli"+ old.parent.mkdir(parents = True)+ old.write_bytes(b"old-cpu-cli")+ new = root / "sd-bundle-cuda12" / "bin" / "sd-cli"+ new.parent.mkdir(parents = True)+ new.write_bytes(b"new-cuda-cli")++ backend = bk.SdCppDiffusionBackend()+ backend._engine = SdCppEngine(binary = str(old))+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(new))+ monkeypatch.setattr(bk, "_usable_or_discard_managed", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_install_allowed", lambda: False)++ # The install landed while this generation was waiting: the old layout is gone.+ old.unlink()+ with bk._tree_reader(str(old)):+ engine = backend._resolve_engine()+ assert engine.binary == str(new)+ assert backend._engine.binary == str(new)+++def test_a_partial_sweep_never_returns_the_file_it_deleted(tmp_path, monkeypatch):+ """_discard_superseded_binaries takes sd-cli before sd-server, so it can remove the old CLI and+ then raise on the old server. The fallback resolved before the install then names a file that+ is gone, and native routing fails on a path nothing can execute."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cpu")+ old = root / "build" / "bin" / "sd-cli"+ old.parent.mkdir(parents = True)+ old.write_bytes(b"old-cpu-cli")+ new = root / "sd-bundle-cuda12" / "bin" / "sd-cli"+ new.parent.mkdir(parents = True)++ resolved = {"path": str(old)}+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: resolved["path"])+ monkeypatch.setattr(bk, "_usable_or_discard_managed", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)++ def _sweep_gets_part_way(**_kwargs):+ old.unlink() # the old CLI went+ new.write_bytes(b"new-cuda-cli") # the new bundle did extract one+ resolved["path"] = str(new)+ raise sdmod.SupersededBinaryError("could not remove the superseded binary sd-server")++ monkeypatch.setattr(sdmod, "install", _sweep_gets_part_way)+ got = bk.ensure_sd_cpp_binary(accelerator = "cuda")+ assert got == str(new), "must not hand back the copy the sweep deleted"+ assert Path(got).is_file()+ # And it is still not memoised, so the next load retries the sweep.+ assert bk._failed_accelerator_upgrades == set()+++def test_a_re_found_cli_goes_through_the_usability_gate(tmp_path, monkeypatch):+ """The partial-sweep raise happens BEFORE install()'s _make_executable, so on POSIX a freshly+ extracted copy has no execute bit, and find_sd_cpp_binary only checks that the path is a file.+ Handing that back gives the next load a binary that cannot launch."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cpu")+ old = root / "build" / "bin" / "sd-cli"+ old.parent.mkdir(parents = True)+ old.write_bytes(b"old-cpu-cli")+ new = root / "sd-bundle-cuda12" / "bin" / "sd-cli"+ new.parent.mkdir(parents = True)++ resolved = {"path": str(old)}+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: resolved["path"])+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ # Runnable before the install (the old CLI), not runnable after (the un-chmodded new one).+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda binary: binary == str(old))++ def _sweep_gets_part_way(**_kwargs):+ old.unlink()+ new.write_bytes(b"new-cuda-cli")+ resolved["path"] = str(new)+ raise sdmod.SupersededBinaryError("could not remove the superseded binary sd-server")++ monkeypatch.setattr(sdmod, "install", _sweep_gets_part_way)+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") is None+ # Ours and unrunnable, so the gate removed it and the next load reinstalls cleanly.+ assert not new.exists()+ assert bk._failed_accelerator_upgrades == set()+++def test_a_cancelled_request_leaves_the_install_wait(tmp_path, monkeypatch):+ """The caller holds the generate lock across this wait, so a cancel or unload that could not+ get out of it reads as a hung Studio for up to the whole 900s while nothing has even started.+ Nothing notifies the condition on cancel, so the wait has to re-check rather than block once."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch)+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"managed")++ monkeypatch.setattr(bk, "_tree_installing", True) # a long install is extracting+ monkeypatch.setattr(bk, "_TREE_WAIT_TICK_S", 0.02)+ cancel = threading.Event()+ threading.Timer(0.1, cancel.set).start()++ started = time.monotonic()+ with pytest.raises(RuntimeError) as exc:+ with bk._tree_reader(str(managed), cancel):+ pytest.fail("a cancelled request must not be admitted either")+ # Out in well under the 900s timeout, and reported as a cancellation, not a timeout.+ assert time.monotonic() - started < 30+ assert "cancel" in str(exc.value).lower()+ assert bk._tree_readers == 0+++def test_the_cuda_runtime_is_fetched_before_anything_is_swept(tmp_path, monkeypatch, capsys):+ """A cudart download / digest / extract failure after the sweep leaves the old binaries gone,+ is not a SupersededBinaryError, and so gets memoised as a failed accelerator with the caller+ holding paths that no longer exist. Fetching it first removes the window entirely."""+ order: list[str] = []+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())++ real_sweep = sdmod._discard_superseded_binaries+ monkeypatch.setattr(+ sdmod,+ "_discard_superseded_binaries",+ lambda root, supplied: (order.append("sweep"), real_sweep(root, supplied))[1],+ )+ monkeypatch.setattr(+ sdmod,+ "_maybe_fetch_windows_cudart",+ lambda *_a, **_k: order.append("cudart"),+ )+ install(install_dir = tmp_path)+ assert order == ["cudart", "sweep"]+++def test_a_failure_after_the_sweep_is_an_incomplete_replacement(tmp_path, monkeypatch):+ """Everything from the sweep onwards leaves a tree that is a mixture of two bundles. Reported+ as anything else, ensure_* memoises the accelerator and suppresses the retry that repairs it."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())++ def _boom(_root, _supplied):+ raise OSError("the filesystem went away mid-sweep")++ monkeypatch.setattr(sdmod, "_discard_superseded_binaries", _boom)+ with pytest.raises(sdmod.SupersededBinaryError) as exc:+ install(install_dir = tmp_path)+ assert "part way through a replacement" in str(exc.value)+++def test_a_failure_finalising_the_new_tree_is_an_incomplete_replacement(tmp_path, monkeypatch):+ """The boundary has to reach past the sweep itself. A chmod or a locate failure after the old+ binaries are gone is still a mixed tree, and reported as an ordinary error it makes ensure_*+ memoise the accelerator and return a pre-install path the sweep may already have removed."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())++ def _chmod_fails(_path):+ raise OSError("read-only filesystem")++ monkeypatch.setattr(sdmod, "_make_executable", _chmod_fails)+ with pytest.raises(sdmod.SupersededBinaryError) as exc:+ install(install_dir = tmp_path)+ assert "part way through a replacement" in str(exc.value)+++def test_a_failure_before_the_sweep_is_an_ordinary_install_failure(tmp_path, monkeypatch):+ """The other side of the boundary: nothing has been removed yet, so this really is "this+ accelerator is unavailable" and memoising it is right."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())+ monkeypatch.setattr(+ sdmod,+ "_maybe_fetch_windows_cudart",+ lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("cudart 404")),+ )+ with pytest.raises(RuntimeError) as exc:+ install(install_dir = tmp_path)+ assert not isinstance(exc.value, sdmod.SupersededBinaryError)+ assert "cudart 404" in str(exc.value)+++def _owned_tree_holding(tmp_path, rel: str) -> Path:+ """A Studio-owned install dir already carrying a previous bundle's sd-cli at ``rel``."""+ (tmp_path / ".unsloth-studio-owned").touch()+ old = tmp_path / rel+ old.parent.mkdir(parents = True, exist_ok = True)+ old.write_bytes(b"the previous build")+ return old+++def test_an_upgrade_is_a_replacement_from_the_extract_on(tmp_path, monkeypatch):+ """The boundary has to open at the EXTRACT, not at the sweep. Extraction merges and zipfile+ rewrites each member in place, so an archive that lands its executables where the previous+ bundle's are has already destroyed them by the time the cudart fetch runs -- and the new+ sd-cli.exe cannot start without those DLLs. Called an ordinary failure, ensure_* memoises the+ accelerator and hands the caller back that very path."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())+ _owned_tree_holding(tmp_path, "build/bin/sd-cli") # the path _zip_with_sd_cli writes to+ monkeypatch.setattr(+ sdmod,+ "_maybe_fetch_windows_cudart",+ lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("cudart 404")),+ )+ with pytest.raises(sdmod.SupersededBinaryError) as exc:+ install(install_dir = tmp_path)+ assert "part way through a replacement" in str(exc.value)+ assert "cudart 404" in str(exc.value)+++def test_a_different_layout_upgrade_is_a_replacement_too(tmp_path, monkeypatch):+ """Same path is not the only way to mix two bundles. This archive writes to build/bin while+ the previous copy sits in a versioned subdirectory, so the old one survives the extract -- and+ loses anyway, because _layout_candidates puts build/bin first. The next lookup therefore+ resolves a copy that has had neither the sweep, nor _make_executable, nor the cudart DLLs, and+ calling the failure ordinary memoises the accelerator and suppresses the retry that repairs+ it."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())+ old = _owned_tree_holding(tmp_path, "sd-master-old/bin/sd-cli")+ monkeypatch.setattr(+ sdmod,+ "_maybe_fetch_windows_cudart",+ lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("cudart 404")),+ )+ with pytest.raises(sdmod.SupersededBinaryError) as exc:+ install(install_dir = tmp_path)+ assert "part way through a replacement" in str(exc.value)+ # Both copies are on disk now, which is exactly why this is not an ordinary failure.+ assert old.read_bytes() == b"the previous build"+ assert (tmp_path / "build" / "bin" / "sd-cli").is_file()+++def test_a_first_install_failing_before_the_sweep_is_an_ordinary_failure(tmp_path, monkeypatch):+ """The other side of it: an empty target has nothing for the new copy to compete with, so no+ lookup can resolve a half-finished binary and "this accelerator is unavailable" is the true+ answer. Memoising it is what stops every later load re-downloading the same failing bundle."""+ zb = _zip_with_sd_cli()+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())+ (tmp_path / ".unsloth-studio-owned").touch()+ monkeypatch.setattr(+ sdmod,+ "_maybe_fetch_windows_cudart",+ lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("cudart 404")),+ )+ with pytest.raises(RuntimeError) as exc:+ install(install_dir = tmp_path)+ assert not isinstance(exc.value, sdmod.SupersededBinaryError)+ assert "cudart 404" in str(exc.value)+++def _server_load_backend(tmp_path, monkeypatch, root, server, on_fetch):+ """A native image backend wired to load out of ``root`` with the download stubbed.++ ``on_fetch`` stands in for the multi-GB asset pull: minutes during which this load holds no+ claim on the tree, which is exactly where an install lands."""+ import core.inference.sd_cpp_backend as bk+ from core.inference.diffusion_families import detect_family++ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())+ monkeypatch.setattr(bk, "_install_allowed", lambda: False)+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ monkeypatch.setattr(+ bk,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cuda", device = "cuda"),+ )+ started: list = []++ class _Server:+ def __init__(self, binary):+ self.binary = binary+ started.append(binary)++ def start(self, *_a, **_k):+ return None++ def stop(self):+ return None++ monkeypatch.setattr(bk, "SdCppServer", _Server)++ fam = detect_family("z-image")+ backend = bk.SdCppDiffusionBackend()+ monkeypatch.setattr(backend, "_asset_specs", lambda *a, **k: [])+ monkeypatch.setattr(backend, "_set_expected_bytes", lambda *a, **k: None)++ def _fetch(*_a, **_k):+ on_fetch()+ return {"diffusion_model": "/m/z.gguf"}++ monkeypatch.setattr(backend, "_fetch_assets", _fetch)+ backend._load_token = 1+ backend._loading = bk._SdLoading(repo_id = "unsloth/Z-Image-Turbo-GGUF", base_repo = fam.base_repo)++ def _run():+ backend._run_load(+ repo_id = "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z.gguf",+ base = fam.base_repo,+ fam = fam,+ hf_token = None,+ _load_token = 1,+ )++ return backend, started, _run+++def test_a_same_path_accelerator_swap_is_refused_before_the_server_starts(tmp_path, monkeypatch):+ """The asset download runs for minutes with no claim on the tree, so an install can replace+ sd-server IN PLACE while it does: same path, still runnable, a different build. The re-resolve+ under the reader claim asks ensure_sd_server_binary, and with allow_install=False that returns+ whatever it found, mismatch included -- so the CPU server was published and started while this+ load had already committed the CUDA device and its offload policy. Existence is not identity."""+ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cuda")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cuda-build")++ def _an_h3_load_installs_the_cpu_fallback():+ server.write_bytes(b"cpu-build")+ sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t")++ backend, started, run = _server_load_backend(+ tmp_path, monkeypatch, root, server, _an_h3_load_installs_the_cpu_fallback+ )+ run()++ assert started == [], "a CPU server may not be started for a load that committed CUDA"+ assert backend._state is None+ assert backend._pending_server is None+ err = backend.load_progress()["error"] or ""+ assert "different accelerator" in err+++def test_an_untouched_tree_still_starts_the_server_after_the_download(tmp_path, monkeypatch):+ """The other side of it: nothing replaced the binary, so the re-validation must be invisible.+ A load refused because the tree merely stayed the same would take the server away entirely."""+ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cuda")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cuda-build")++ backend, started, run = _server_load_backend(tmp_path, monkeypatch, root, server, lambda: None)+ run()++ assert started == [str(server)]+ assert backend._state is not None and backend._state.mode == "server"+ assert backend.load_progress()["error"] is None+++def test_a_started_server_holds_the_tree_until_state_is_published(tmp_path, monkeypatch):+ """The started server stays in _pending_server until _state takes it over, under one lock.++ Clearing it as soon as start() returned left a window in which nothing published says the tree+ is busy -- no reader, no pending server, no resident state -- while the process is up and+ running out of it. An ensure_* landing there is admitted, downloads for minutes and then+ extracts over the executable of a live server."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cuda")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cuda-build")++ backend, started, run = _server_load_backend(tmp_path, monkeypatch, root, server, lambda: None)+ # _default_threads() is evaluated once in the server.start() kwargs and once building the+ # _SdState the load commits, so it samples both ends of that window for free.+ seen: list[bool] = []+ real_threads = bk._default_threads+ monkeypatch.setattr(+ bk,+ "_default_threads",+ lambda: (seen.append(bk._tree_in_use(backend)), real_threads())[1],+ )+ run()++ assert started == [str(server)]+ assert backend._state is not None and backend._state.server is not None+ assert backend._pending_server is None # exchanged for _state, not leaked+ assert len(seen) >= 2 and all(seen), "the tree read as idle while the server was running"+++def test_a_superseded_load_unpublishes_the_server_it_stops(tmp_path, monkeypatch):+ """The other end of holding it longer: a load that finds itself superseded must still take the+ started server back out. Left published it reads as "the managed tree is busy" for the rest of+ the process and no install can ever run again."""+ import core.inference.sd_cpp_backend as bk++ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cuda")+ server = root / "sd-bin" / "sd-server"+ server.write_bytes(b"cuda-build")++ backend, started, run = _server_load_backend(tmp_path, monkeypatch, root, server, lambda: None)+ real_threads = bk._default_threads++ def _supersede_mid_commit():+ # Between start() returning and the state commit, which is exactly the window the server+ # is now left published across.+ backend._load_token = 2+ return real_threads()++ monkeypatch.setattr(bk, "_default_threads", _supersede_mid_commit)+ run()++ assert started == [str(server)]+ assert backend._state is None+ assert backend._pending_server is None+ assert backend._stopping_servers == 0+ assert not bk._tree_in_use(backend)diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 7836848812a..61c2466ce81 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -3190,6 +3190,92 @@ def test_h3_native_accelerator_load_keeps_the_video_gpu_claim(monkeypatch, tmp_passert gpu_arbiter.current_owner() == gpu_arbiter.VIDEO+def test_the_load_time_accelerator_probe_runs_under_the_reader_claim(monkeypatch, tmp_path):+ """--list-devices SPAWNS the managed sd-cli, so it needs the same claim the run takes.++ Unclaimed, an install started by another in-process load sees no reader and extracts 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 compares answers; it cannot undo damage+ this first probe already allowed.+ """+ from core.inference import gpu_arbiter+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ (root / "sd-bin").mkdir(parents = True)+ (root / ".unsloth-studio-owned").touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"managed")++ 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 = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: str(managed),+ )++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ 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)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)++ held: list = []++ def _watching_probe(binary):+ held.append(sd_cpp_backend._tree_readers)+ # An install decided at this instant must stand down rather than replace what is running.+ with sd_cpp_backend._tree_claimed_for_install() as claimed:+ held.append(claimed)+ return True++ # video.py imports this inside the load function, so the name must be replaced at its source+ # module; patching the video module misses it entirely and the test would pass vacuously.+ monkeypatch.setattr(sd_cpp_backend, "sd_cpp_lists_accelerator_device", _watching_probe)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ 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",+ )++ # First two entries are the load-time probe; the claimed recheck later in the load adds its+ # own pair, so assert on the opening ones rather than the whole list.+ assert held[:2] == [1, False], f"probe ran unclaimed: {held}"+ assert sd_cpp_backend._tree_readers == 0, "the claim must be released after the probe"++def test_h3_native_reused_cpu_binary_still_commits_to_cpu(monkeypatch, tmp_path):"""The second load on a Linux CUDA host. The first one installed the CPU prebuilt (upstreampublishes no Linux CUDA asset for the pinned tag), and from then on ensure_sd_cpp_binary finds@@ -3264,6 +3350,112 @@ def test_h3_native_reused_cpu_binary_still_commits_to_cpu(monkeypatch, tmp_path)assert gpu_arbiter.current_owner() is None+def _h3_managed_cpu_fallback_load(monkeypatch, tmp_path, *, swap_on_fallback):+ """An H3 native load on a CUDA target whose first probe drops it to the CPU build.++ The binary is a MANAGED one, i.e. one an install may replace at the same path.+ ``swap_on_fallback`` makes that install land the moment the fallback's ensure returns, which+ is the window the second probe used to be sampled in."""+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ (root / "sd-bin").mkdir(parents = True)+ (root / ".unsloth-studio-owned").touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"the cpu build the fallback asked for")++ 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 = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)++ swapped: list = []++ def _ensure(*, allow_install, accelerator):+ if accelerator == "cpu" and swap_on_fallback:+ # The CPU bundle this call asked for is what came back; the install that replaces it+ # with a GPU build lands immediately afterwards, before anything probes it again.+ swapped.append(True)+ return str(managed)++ monkeypatch.setattr(sd_cpp_backend, "ensure_sd_cpp_binary", _ensure)++ def _probe(_binary, *args):+ if args == ("--list-devices",):+ 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"++ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", _probe)++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ 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++ def _run():+ 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",+ )++ return backend, _run+++def test_h3_native_cpu_fallback_refuses_a_gpu_build_that_replaced_it(monkeypatch, tmp_path):+ """The CPU fallback's baseline is the DECISION, not a second probe. Sampling the binary again+ after the fallback's ensure records whatever an install has just put at that path, so the+ re-check under the reader claim compared a CUDA executable against itself and passed -- with+ native_device already forced to "cpu" and CPU resource accounting committed around a build+ that runs on VRAM nothing accounted for."""+ backend, run = _h3_managed_cpu_fallback_load(monkeypatch, tmp_path, swap_on_fallback = True)+ with pytest.raises(RuntimeError, match = "different accelerator"):+ run()+ assert backend._state is None+++def test_h3_native_cpu_fallback_still_commits_to_a_managed_cpu_build(monkeypatch, tmp_path):+ """The control: nothing replaced the binary, so the fallback has to load exactly as before.+ A CPU fallback refused for the accelerator it deliberately chose would take H3 away from every+ GPU host with no matching prebuilt, which is the common case this fallback exists for."""+ backend, run = _h3_managed_cpu_fallback_load(monkeypatch, tmp_path, swap_on_fallback = False)+ run()+ assert backend._state is not None+ assert backend._state.device == "cpu"+ assert backend._state.offload_policy == "none"++def test_h3_native_load_publishes_the_companion_repos_while_downloading(monkeypatch, tmp_path):"""The in-flight twin of loaded_repo_ids(). An H3 load downloads from the GGUF and componentcompanion repos as well as repo_id, but loading_repo_ids() reported only repo_id and base_repo,@@ -4532,8 +4724,15 @@ def test_h3_keyframe_fit_stretches_the_first_and_crops_the_last():fit_h3_keyframe(source, 64, 64, anchor = "middle")-def _h3_native_backend(monkeypatch, calls):- """A backend with an H3 sd.cpp state whose engine records the params it was handed."""+def _h3_native_backend(+ monkeypatch,+ calls,+ binary = None,+):+ """A backend with an H3 sd.cpp state whose engine records the params it was handed.++ ``binary`` stands in for what _run_load_h3_native resolves and vets: the engine gets the path+ and the runtime records that file's identity, exactly as the real load does."""from core.inference.video import _VideoLoadStatefrom core.inference.video_minimax_h3 import MiniMaxH3NativeRuntime@@ -4561,8 +4760,18 @@ def _h3_native_backend(monkeypatch, calls):backend = VideoBackend()fam = _detect_load_family("unsloth/MiniMax-H3-GGUF", None, "minimax-h3")+ from core.inference.video import _sd_cli_identity++ engine = _Engine()+ if binary is not None:+ engine.binary = str(binary)backend._state = _VideoLoadState(- pipe = MiniMaxH3NativeRuntime(engine = _Engine(), files = object(), offload_flags = ()),+ pipe = MiniMaxH3NativeRuntime(+ engine = engine,+ files = object(),+ offload_flags = (),+ binary_identity = _sd_cli_identity(str(binary)) if binary is not None else None,+ ),family = fam,repo_id = "unsloth/MiniMax-H3-GGUF",base_repo = fam.base_repo,@@ -6089,6 +6298,149 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat)+def test_a_managed_h3_native_run_holds_the_install_off(monkeypatch, tmp_path):+ """An H3 native run is an sd-cli run out of the managed tree, so it takes the same reader claim+ the one-shot image path takes. Without it an image-engine request sees no readers, starts an+ install, and the sweep unlinks the CLI this runtime resolved at load."""+ pytest.importorskip("PIL.Image")+ import core.inference.sd_cpp_backend as bk++ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ (root / "sd-bin").mkdir(parents = True)+ (root / ".unsloth-studio-owned").touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"managed")++ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls, binary = managed)++ held: list = []+ inner = backend._state.pipe.engine.generate_video++ def _watching(files, params, **kwargs):+ held.append(bk._tree_readers)+ # An install decided right now must stand down rather than replace what is executing.+ with bk._tree_claimed_for_install() as claimed:+ held.append(claimed)+ return inner(files, params, **kwargs)++ backend._state.pipe.engine.generate_video = _watching+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ backend.generate(prompt = "p", width = 960, height = 544)+ assert held == [1, False]+ # And the claim is released afterwards, so the next install is not blocked forever.+ assert bk._tree_readers == 0+++def test_an_unmanaged_h3_native_run_takes_no_claim(monkeypatch, tmp_path):+ """A user-supplied sd-cli is one the installer cannot replace, so it must not be blocked+ behind an unrelated managed install."""+ pytest.importorskip("PIL.Image")+ import core.inference.sd_cpp_backend as bk++ outside = tmp_path / "mine" / "sd-cli"+ outside.parent.mkdir(parents = True)+ outside.write_bytes(b"my own build")++ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls, binary = outside)++ held: list = []+ inner = backend._state.pipe.engine.generate_video++ def _watching(files, params, **kwargs):+ held.append(bk._tree_readers)+ return inner(files, params, **kwargs)++ backend._state.pipe.engine.generate_video = _watching+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ backend.generate(prompt = "p", width = 960, height = 544)+ assert held == [0]+++def test_an_in_place_binary_swap_stops_the_h3_run(monkeypatch, tmp_path):+ """Existence is not identity, and the identity has to be the one recorded when+ ensure_h3_sd_cpp_binary vetted the file. An install that lands at the SAME path leaves a build+ that is not the one this runtime was checked against: a different accelerator, or one predating+ the H3 options, which aborts partway through a render nobody wants to repeat."""+ pytest.importorskip("PIL.Image")+ import contextlib+ import os++ import core.inference.sd_cpp_backend as bk++ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ (root / "sd-bin").mkdir(parents = True)+ (root / ".unsloth-studio-owned").touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"the build the load checked")++ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls, binary = managed)+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)++ # Unchanged since the load: the run goes ahead.+ backend.generate(prompt = "p", width = 960, height = 544)+ assert len(calls) == 1++ # The install landed BEFORE this generation, not during it. Two reads taken now would agree+ # with each other, which is exactly why the comparison is against the load-time value.+ managed.write_bytes(b"some other accelerator's build")+ os.utime(managed, (1, 1))+ with pytest.raises(RuntimeError, match = "Reload the model"):+ backend.generate(prompt = "p", width = 960, height = 544)+ assert len(calls) == 1, "the run must not reach a build the load never checked"++ # A replacement that lands DURING the wait is caught the same way.+ @contextlib.contextmanager+ def _install_lands_during_the_wait(+ _binary,+ _cancel = None,+ _msg = None,+ ):+ managed.write_bytes(b"yet another build")+ os.utime(managed, (2, 2))+ yield++ backend = _h3_native_backend(monkeypatch, calls, binary = managed)+ monkeypatch.setattr(bk, "_tree_reader", _install_lands_during_the_wait)+ with pytest.raises(RuntimeError, match = "Reload the model"):+ backend.generate(prompt = "p", width = 960, height = 544)+ assert len(calls) == 1+++def test_a_cancelled_h3_install_wait_reads_as_a_cancellation(monkeypatch, tmp_path):+ """The reader is shared with the image path, whose sentinel _run_generate does not recognise.+ Left untranslated, an ordinary H3 cancellation surfaces as "Video generation failed"."""+ pytest.importorskip("PIL.Image")+ import threading++ import core.inference.sd_cpp_backend as bk+ from core.inference.video_families import VIDEO_CANCELLED_MSG++ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ (root / "sd-bin").mkdir(parents = True)+ (root / ".unsloth-studio-owned").touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ managed = root / "sd-bin" / "sd-cli"+ managed.write_bytes(b"managed")++ calls: list = []+ backend = _h3_native_backend(monkeypatch, calls, binary = managed)+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)+ monkeypatch.setattr(bk, "_tree_installing", True)+ monkeypatch.setattr(bk, "_TREE_WAIT_TICK_S", 0.02)++ # Cancel shortly after the generation parks in the install wait.+ threading.Timer(0.1, lambda: backend.cancel_generate()).start()+ with pytest.raises(RuntimeError) as exc:+ backend.generate(prompt = "p", width = 960, height = 544)+ assert str(exc.value) == VIDEO_CANCELLED_MSG+ assert calls == []++# ── the refusal reads the plan the load will actually take ────────────────────# Two ways the hard unified-memory refusal added in PR #8213 can read a number the load never# occupies, both of which turn it from a guard into a false rejection.diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex 56c6bd59cc0..c3bffc97122 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -88,21 +88,49 @@ def read_install_record(root: Path) -> dict:def installed_accelerator(root: Path) -> Optional[str]:"""The accelerator class the install in ``root`` was built for, or None when unrecorded.- The memo WINS over the file. It is only ever set by an install that completed in this process,- so it is strictly newer than whatever is on disk -- and the case it exists for is precisely a- record that could not be overwritten, which then still reads as the PREVIOUS accelerator.- Preferring the file there would keep reporting cpu after a successful cuda install, and every- later selection would download the bundle again."""- val = _INSTALLED_ACCELERATOR_MEMO.get(str(root)) or read_install_record(root).get("accelerator")+ The memo wins over the file, but only while the file is exactly the one it could not replace.+ It exists for a record that stayed readable and stale (still naming the PREVIOUS accelerator)+ after a successful install, where trusting the file re-downloads the bundle on every selection.+ Once anything else rewrites that file -- the installer CLI, another Studio -- the content no+ longer matches the snapshot and the file is the newer answer again.++ Only a SUCCESSFUL read that disagrees retires the memo. A record we cannot read right now is+ not a newer answer: the memo's own reason for existing is a record this process could not+ write, and on Windows another writer holding that file open reads as a failure. Dropping the+ memo on it would hand the next selection the stale accelerator it was protecting against, and+ that is a multi-GB reinstall on every load."""+ memo = _INSTALLED_ACCELERATOR_MEMO.get(str(root))+ val = None+ if memo is not None:+ raw = _raw_install_record(root)+ if raw is None or raw == memo[1]:+ val = memo[0]+ else:+ _INSTALLED_ACCELERATOR_MEMO.pop(str(root), None)+ val = val or read_install_record(root).get("accelerator")return val if isinstance(val, str) and val else None-# What THIS process installed, per install root. The on-disk record is the durable answer, but an-# unwritable one (read-only file, a directory in its place) used to mean the accelerator was-# unknown forever, and unknown reads as a mismatch for a GPU target: every later engine selection-# would re-resolve and re-download the same multi-GB bundle. Remembering it in-process keeps a-# successful install from being repeated, without failing an install whose binaries are fine.-_INSTALLED_ACCELERATOR_MEMO: dict[str, str] = {}+# Set ONLY when the on-disk record could not be written: install root -> (accelerator, the raw+# record bytes seen at that moment). An unwritable record (a read-only file, a directory in its+# place) otherwise means the accelerator reads as the PREVIOUS one, or as unknown, forever -- and+# either is a mismatch for a GPU target, so every later engine selection re-downloads the same+# multi-GB bundle. Keyed on the snapshot so it only speaks for the record it saw: once anything+# else updates that file (the installer CLI, another Studio), the file is newer and wins again.+_INSTALLED_ACCELERATOR_MEMO: dict[str, tuple[str, Optional[str]]] = {}+++def _raw_install_record(root: Path) -> Optional[str]:+ """The record file's bytes as text, or None when it cannot be read. Never raises.++ None is "cannot tell", NOT empty content: an absent file, a directory in its place and a+ transient permission/sharing failure all land here, and none of them proves the record was+ rewritten. Callers must not treat it as a value that differs from a snapshot."""+ try:+ with open(root / INSTALL_RECORD, "r", encoding = "utf-8") as f:+ return f.read()+ except Exception: # noqa: BLE001 -- absent / unreadable / a directory: all "cannot tell"+ return Nonedef _write_install_record(root: Path, *, accelerator: str, repo: str, tag: Optional[str]) -> None:@@ -112,16 +140,20 @@ def _write_install_record(root: Path, *, accelerator: str, repo: str, tag: Optioextracted correctly -- but the answer is memoised either way, so this process never re-installswhat it just installed."""klass = accelerator_class(accelerator)- _INSTALLED_ACCELERATOR_MEMO[str(root)] = klasstry:with open(root / INSTALL_RECORD, "w", encoding = "utf-8") as f:json.dump({"accelerator": klass, "repo": repo, "tag": tag}, f)except OSError as exc:+ # Remember it, pinned to the record we could not replace.+ _INSTALLED_ACCELERATOR_MEMO[str(root)] = (klass, _raw_install_record(root))print(f"sd-cli: WARNING could not write the install record in {root}: {exc}; "f"remembering {klass} for this process only",flush = True,)+ else:+ # The file is authoritative again, so a memo from an earlier failed write must not outlive it.+ _INSTALLED_ACCELERATOR_MEMO.pop(str(root), None)def _repo() -> str:@@ -325,32 +357,70 @@ def _locate_sd_cli(root: Path) -> Optional[Path]:return None-def _archive_ships_sd_server(zf: zipfile.ZipFile) -> bool:- """Whether ``zf`` carries an sd-server binary. Read from the MEMBER LIST, never from the- extracted tree: a leftover sd-server from an earlier install looks identical on disk, which is- exactly the confusion this answers."""- name = "sd-server.exe" if sys.platform == "win32" else "sd-server"- return any(n.rsplit("/", 1)[-1] == name for n in zf.namelist())+class SupersededBinaryError(RuntimeError):+ """An install failed PART WAY through replacing the managed tree.+ Distinct from every other install failure because the tree is now a mixture of two bundles.+ ``ensure_*`` must not record it as a failed accelerator upgrade: that memo suppresses the+ mismatch for the whole process, so the mixed tree would be accepted forever instead of being+ retried, which is the opposite of what withholding the install record is for."""-def _discard_stale_sd_server(root: Path) -> None:- """Remove an sd-server left behind by a previous, different bundle.- Raises when it cannot go. A leftover server is still RUNNABLE, so nothing downstream repairs- it: _usable_or_discard_managed only removes binaries that fail to run, and once the record- below names the new accelerator, _accelerator_changed trusts it and keeps handing back that- stale server. Failing here withholds the record, which is what makes the next load retry."""- stale = _locate_sd_server(root)- if stale is None:- return- try:- stale.unlink()- except OSError as exc:- raise RuntimeError(- f"could not remove the superseded sd-server {stale}: {exc}. It was built for a "- f"different accelerator than this bundle, and leaving it would keep serving it."- ) from exc- print(f"removed the previous sd-server -> {stale}", flush = True)+def _binary_names() -> tuple[str, ...]:+ """The executables the managed tree may hold, in both platform spellings."""+ suffix = ".exe" if sys.platform == "win32" else ""+ return (f"sd-cli{suffix}", f"sd-server{suffix}")+++def _archive_binary_paths(zf: zipfile.ZipFile, target: Path) -> set[Path]:+ """Where this archive puts its executables, resolved to absolute paths under ``target``.++ Read from the MEMBER LIST, never from the extracted tree: a leftover binary from an earlier+ install looks identical on disk once extraction has run, which is the whole confusion here."""+ names = _binary_names()+ out: set[Path] = set()+ for member in zf.namelist():+ if member.rsplit("/", 1)[-1] in names:+ out.add((target / member).resolve())+ return out+++def _tree_has_binaries(root: Path) -> bool:+ """True when ``root`` already holds an sd-cli / sd-server from an earlier bundle.++ Asked BEFORE extraction, because that is the only moment the answer is about the previous+ bundle alone."""+ for name in _binary_names():+ for found in root.rglob(name):+ if found.is_file():+ return True+ return False+++def _discard_superseded_binaries(root: Path, supplied: set[Path]) -> None:+ """Remove managed sd-cli / sd-server copies this bundle did NOT write.++ Extraction MERGES into the tree, so a bundle whose layout differs from the previous one (or+ that ships no server at all) leaves the old accelerator's executables behind -- and+ ``_layout_candidates`` prefers ``build/bin`` over the prebuilt's versioned subdirectory, so the+ stale one keeps winning. Nothing downstream repairs that: a leftover binary is still RUNNABLE,+ so ``_usable_or_discard_managed`` keeps it, and once the record below names the new accelerator+ ``_accelerator_changed`` trusts the tree and serves the old build forever.++ Raises when a copy cannot go, which withholds the record and makes the next load retry."""+ names = _binary_names()+ for name in names:+ for found in sorted(root.rglob(name)):+ if not found.is_file() or found.resolve() in supplied:+ continue+ try:+ found.unlink()+ except OSError as exc:+ raise SupersededBinaryError(+ f"could not remove the superseded binary {found}: {exc}. It was not written by "+ f"this bundle, and leaving it would keep serving the previous accelerator."+ ) from exc+ print(f"removed a superseded binary -> {found}", flush = True)def _locate_sd_server(root: Path) -> Optional[Path]:@@ -574,6 +644,10 @@ def install(except OSError:passarchive = target / chosen+ # Set the moment the tree stops being purely the OLD bundle. From then on it is a mixture of+ # two bundles and every later failure has to be reported as an incomplete replacement, not as+ # "this accelerator is unavailable".+ replacing = Falseprint(f"downloading {chosen} -> {archive}", flush = True)try:_download(url, archive)@@ -581,31 +655,90 @@ def install(_verify_sha256(archive, asset.get("digest"))print("extracting ...", flush = True)with zipfile.ZipFile(archive) as zf:- ships_server = _archive_ships_sd_server(zf)+ supplied = _archive_binary_paths(zf, target)+ # The boundary opens HERE, not at the sweep, whenever an existing bundle is about+ # to gain a SECOND copy of a binary. Same path is the obvious case: zipfile rewrites+ # each member in place, so an interrupted extract leaves the old sd-cli truncated.+ # A different layout is the same problem one step removed, because the new copy WINS+ # the next lookup -- _layout_candidates prefers build/bin, then the newest+ # subdirectory by mtime -- while still having had neither the sweep, nor+ # _make_executable, nor (on a Windows CUDA upgrade) the cudart DLLs the fetch below+ # can still fail to get. Either way, calling that an ordinary failure makes ensure_*+ # memoise the accelerator and serve the half-finished copy for the rest of the+ # process. A first install has nothing to compete with, so it stays ordinary and the+ # accelerator really is the thing that was unavailable.+ replacing = bool(supplied) and _tree_has_binaries(target)_safe_extractall(zf, target)- # An archive that carries no sd-server leaves the PREVIOUS accelerator's one in place, and- # the record written below would then label the whole tree as this accelerator: the backend- # rediscovers that stale server, trusts the record and runs a CUDA request on the old CPU- # build forever. Drop what this bundle did not provide, so the tree and its record agree.- if _may_own and not ships_server:- _discard_stale_sd_server(target)- # Windows CUDA builds need the separately-published cudart runtime DLLs.+ # Nothing is swept until this bundle is known to have supplied the one binary the install+ # cannot do without. A malformed archive is caught below either way, but only AFTER the+ # sweep would have deleted the working sd-cli that ensure_sd_cpp_binary keeps precisely so+ # a failed upgrade still leaves something to generate with.+ cli_name = _binary_names()[0]+ if not any(p.name == cli_name for p in supplied):+ raise RuntimeError(f"archive {chosen} contained no sd-cli binary")+ # Windows CUDA builds need the separately-published cudart runtime DLLs. Still before the+ # sweep, so a failure here costs nothing extra when the old copies are still in place;+ # when the extract above already overwrote them, ``replacing`` is what makes this report+ # as an incomplete replacement instead of a missing accelerator. Nothing it writes is an+ # sd-cli or an sd-server, so the sweep below cannot take it._maybe_fetch_windows_cudart(release, chosen, target)+ # Extraction merges, so anything the previous bundle put somewhere this one does not write+ # survives -- and it outranks the new copy whenever its path sorts higher. Drop what this+ # bundle did not supply, so the tree and the record written below agree.+ #+ # LAST, and past it the tree is mixed whatever the layout was: the caller has to retry the+ # sweep rather than memoise the accelerator as unavailable.+ if _may_own:+ # Set BEFORE the call, not after: the sweep removes copies one at a time, so a failure+ # inside it has already changed the tree.+ replacing = True+ _discard_superseded_binaries(target, supplied)+ except SupersededBinaryError:+ raise+ except Exception as exc: # noqa: BLE001 -- past the boundary, every failure is a mixed tree+ if not replacing:+ raise+ raise SupersededBinaryError(+ f"the managed tree was left part way through a replacement: {exc}"+ ) from excfinally:# Always drop the archive: a corrupt or partial one must not linger and defeat a later retry.- archive.unlink(missing_ok = True)- sd_cli = _locate_sd_cli(target)- if not sd_cli:- raise RuntimeError(f"archive {chosen} contained no sd-cli binary")- if sys.platform != "win32":- _make_executable(sd_cli)- print(f"installed sd-cli -> {sd_cli}", flush = True)- # The same archive ships the persistent sd-server; make it runnable so the native backend can prefer it.- sd_server = _locate_sd_server(target)- if sd_server is not None and sys.platform != "win32":- _make_executable(sd_server)- if sd_server is not None:- print(f"installed sd-server -> {sd_server}", flush = True)+ # Inside the boundary too: an unlink failure after the sweep is still a mixed tree.+ try:+ archive.unlink(missing_ok = True)+ except OSError as exc:+ if replacing:+ raise SupersededBinaryError(+ f"the managed tree was left part way through a replacement: {exc}"+ ) from exc+ raise+ # EVERYTHING from the sweep on is finalisation of a tree that is now a mixture of two bundles:+ # locating the new binaries, chmod-ing them, and the record. Reported as an ordinary failure,+ # any of these makes ensure_* memoise the accelerator as unavailable and hand back a+ # pre-install path the sweep may already have removed. Reported as an incomplete replacement,+ # the caller re-finds what survived and the next load retries.+ try:+ sd_cli = _locate_sd_cli(target)+ if not sd_cli:+ raise RuntimeError(f"archive {chosen} contained no sd-cli binary")+ if sys.platform != "win32":+ _make_executable(sd_cli)+ print(f"installed sd-cli -> {sd_cli}", flush = True)+ # The same archive ships the persistent sd-server; make it runnable so the native backend+ # can prefer it.+ sd_server = _locate_sd_server(target)+ if sd_server is not None and sys.platform != "win32":+ _make_executable(sd_server)+ if sd_server is not None:+ print(f"installed sd-server -> {sd_server}", flush = True)+ except SupersededBinaryError:+ raise+ except Exception as exc: # noqa: BLE001 -- past the sweep, every failure is a mixed tree+ if not replacing:+ raise+ raise SupersededBinaryError(+ f"the managed tree was left part way through a replacement: {exc}"+ ) from exc# Written only now, on a complete install: a record naming an accelerator whose binaries never# finished extracting would suppress the very reinstall that repairs it. Only for a directory we# own -- an unowned one is the user's build, which we never claim to have installed.