Skip to content

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

Install the Linux CUDA sd-cli, and bump the pin two releases forward (#8208)

Daniel Hanba1faf07cf83
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 8ccfb05f9c3..cd3c66c752e 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -71,6 +71,7 @@ from core.inference.sd_cpp_engine import (
find_sd_cpp_binary,
find_sd_server_binary,
is_managed_binary,
+ managed_install_root,
runtime_env,
)
from core.inference.sd_cpp_server import SdCppServer
@@ -160,6 +161,103 @@ def _usable_or_discard_managed(binary: str) -> bool:
return False
+def _installer_module():
+ """The installer module, importable from the backend's sys.path. None if unavailable."""
+ import sys
+
+ studio_dir = Path(__file__).resolve().parents[3] # .../studio
+ if str(studio_dir) not in sys.path:
+ sys.path.insert(0, str(studio_dir))
+ import install_sd_cpp_prebuilt
+
+ return install_sd_cpp_prebuilt
+
+
+# Accelerators whose upgrade install already failed this process. Without this, a host that asks
+# for a GPU build it has no asset for would re-resolve (and re-download) on every single load,
+# because the wrong-accelerator binary it keeps still does not match the request.
+_failed_accelerator_upgrades: set[str] = set()
+
+
+def _note_failed_upgrade(accelerator: str) -> None:
+ """Stop retrying an accelerator upgrade that just failed while a usable binary is kept."""
+ try:
+ _failed_accelerator_upgrades.add(_installer_module().accelerator_class(accelerator))
+ except Exception: # noqa: BLE001 -- best effort
+ pass
+
+
+def _tree_in_use(backend: Any) -> bool:
+ """True while ``backend`` may still have a native process executing out of the managed tree.
+
+ Three windows, and all three are live processes running the files an install would replace:
+ the resident sd-server; a server that has been spawned but has not committed to ``_state``
+ yet (``_pending_server``, which is exactly the ``SdCppServer.start()`` span -- minutes on a
+ large checkpoint, and the load that owns it has published nothing else to look at); and a
+ generation that has been signalled to cancel but has not finished."""
+ if backend is None:
+ return False
+ state = getattr(backend, "_state", None)
+ if state is not None and getattr(state, "server", None) is not None:
+ return True # the resident sd-server is executing its own file
+ if getattr(backend, "_pending_server", None) is not None:
+ return True # a server is starting from that same file
+ if getattr(backend, "_stopping_servers", 0):
+ return True # unpublished, but stop() has not returned: the process is still alive
+ return getattr(backend, "_active_generate_cancel", None) is not None
+
+
+def _managed_tree_in_use() -> bool:
+ """True while a native process may still be executing out of the managed install tree.
+
+ An accelerator upgrade REPLACES the binaries in that tree, and Linux refuses to open a running
+ executable for writing (ETXTBSY) while Windows locks it, so an install attempted now fails and
+ can leave the tree half-written. The load path knows when it is safe and retries after its own
+ teardown, but it is not the only entry point: the engine router calls ``ensure_sd_server_binary``
+ / ``ensure_sd_cpp_binary`` directly, BEFORE ``begin_load`` stops anything. Answering here, at
+ the one place that decides an install is needed, covers every caller instead of one.
+
+ Reads the singleton without a lock on purpose: a stale answer either defers an upgrade to the
+ next load (harmless) or lets one through in a window the load path guards anyway."""
+ return _tree_in_use(_sd_cpp_backend)
+
+
+def _accelerator_changed(binary: str, accelerator: str) -> bool:
+ """True when ``binary`` is a managed install built for a DIFFERENT accelerator than the one
+ now asked for, so reusing it would silently run the wrong build.
+
+ The case that matters: a host that installed the CPU bundle (the default when the device
+ target resolves to CPU) later forces the native engine on a CUDA/ROCm/Vulkan GPU. Both
+ ``ensure_*`` return any runnable binary they find, so without this the CPU sd-server is
+ reused forever and generation stays on the CPU even though a matching GPU build now exists.
+
+ The reverse matters too: a host with a recorded GPU install whose device target later
+ resolves to CPU keeps running on the GPU, because nothing in the sd-server/sd-cli command
+ line asks for a CPU backend -- the build itself is the choice. So a recorded accelerator
+ that is not the one now wanted is a change in either direction.
+
+ Deliberately conservative -- only a copy the installer owns is ever replaced (the user's own
+ build or an in-tree checkout is left alone), and an install with NO record is left alone when
+ the CPU build is wanted: unrecorded is unknown (GPU assets shipped before the record did), and
+ reinstalling every legacy install on a CPU target would redownload the bundle for the common
+ case, where the install almost certainly is the CPU one already."""
+ if not is_managed_binary(binary):
+ return False
+ if _managed_tree_in_use():
+ return False # an install now would overwrite a running binary; the load retries after teardown
+ try:
+ mod = _installer_module()
+ want = mod.accelerator_class(accelerator)
+ if want in _failed_accelerator_upgrades:
+ return False
+ have = mod.installed_accelerator(managed_install_root())
+ if want == "cpu":
+ return have is not None and have != "cpu"
+ return have != want
+ except Exception: # noqa: BLE001 -- cannot tell -> keep the existing binary, as before
+ return False
+
+
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.
@@ -168,32 +266,41 @@ def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu"
return is the router's signal to fall back to diffusers.
"""
found = find_sd_cpp_binary()
- if found and _usable_or_discard_managed(found):
+ usable = bool(found) and _usable_or_discard_managed(found)
+ if usable and not _accelerator_changed(found, accelerator):
return found
if not allow_install:
return found
with _install_lock:
# Re-check inside the lock: a concurrent first-load may have installed it.
found = find_sd_cpp_binary()
- if found and _usable_or_discard_managed(found):
+ usable = bool(found) and _usable_or_discard_managed(found)
+ if usable and not _accelerator_changed(found, accelerator):
return found
+ # 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 fallback
try:
- import sys
-
- studio_dir = Path(__file__).resolve().parents[3] # .../studio
- if str(studio_dir) not in sys.path:
- sys.path.insert(0, str(studio_dir))
- from install_sd_cpp_prebuilt import install as _install
+ _install = _installer_module().install
except Exception as exc: # noqa: BLE001 -- import path / module issues are non-fatal
logger.warning("sd-cli installer import failed: %s", exc)
- return None
+ 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)
- return None
+ if fallback is not None:
+ _note_failed_upgrade(accelerator)
+ return fallback
def ensure_sd_server_binary(
@@ -208,30 +315,41 @@ def ensure_sd_server_binary(
uses the one-shot fallback. Never raises.
"""
found = find_sd_server_binary()
- if found and _usable_or_discard_managed(found):
+ usable = bool(found) and _usable_or_discard_managed(found)
+ if usable and not _accelerator_changed(found, accelerator):
return found
if not allow_install:
return found
with _install_lock:
found = find_sd_server_binary()
- if found and _usable_or_discard_managed(found):
+ usable = bool(found) and _usable_or_discard_managed(found)
+ if usable and not _accelerator_changed(found, accelerator):
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 fallback
try:
- import sys
-
- studio_dir = Path(__file__).resolve().parents[3] # .../studio
- if str(studio_dir) not in sys.path:
- sys.path.insert(0, str(studio_dir))
- from install_sd_cpp_prebuilt import install as _install
+ _install = _installer_module().install
except Exception as exc: # noqa: BLE001 -- import path / module issues are non-fatal
logger.warning("sd-server installer import failed: %s", exc)
- return None
+ 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)
- return None
- return find_sd_server_binary()
+ # 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
+ return find_sd_server_binary() or fallback
@dataclass(frozen = True)
@@ -385,6 +503,13 @@ class SdCppDiffusionBackend:
# sd-server started for an in-flight load, before it commits to _state; tracked so an unload can stop it mid-startup.
self._pending_server: Optional[SdCppServer] = None
self._gen: Optional[_SdGen] = None
+ # Set by _resolve_backend when it had to skip an accelerator install because the managed
+ # tree was still in use; the load retries it once the tree is free.
+ self._deferred_accelerator_install = False
+ # Servers taken out of _state/_pending_server whose stop() has not returned yet. unload()
+ # deliberately stops outside the lock (terminate can take seconds), so between the clear
+ # and the stop the fields say idle while the process is still running its own executable.
+ self._stopping_servers = 0
# Set once this load's graph proved unrunnable on the GPU backend (a ggml unsupported-op abort), so the CPU restart happens once per load. Cleared by each load.
self._cpu_backend_forced = False
@@ -392,11 +517,50 @@ class SdCppDiffusionBackend:
def is_loaded(self) -> bool:
return self._state is not None
+ def _reserve_stop(self, count: int = 1) -> None:
+ """Claim ``count`` pending stops. MUST be called under ``_lock`` in the same block that
+ unpublishes the servers: incrementing afterwards leaves a gap in which _state,
+ _pending_server and the count are all empty while the process is still running."""
+ self._stopping_servers += count
+
+ def _stop_reserved(self, server: Any) -> None:
+ """Stop a server whose pending stop was already reserved by ``_reserve_stop``. Never
+ raises: a teardown may not fail a load or an unload."""
+ try:
+ server.stop()
+ except Exception as exc: # noqa: BLE001 -- a stop that fails must not fail the caller
+ logger.warning("sd-server stop failed: %s", exc)
+ finally:
+ with self._lock:
+ self._stopping_servers -= 1
+
+ def _stop_server(self, server: Any) -> None:
+ """Reserve and stop in one go, for a caller that is not already holding ``_lock``."""
+ with self._lock:
+ self._reserve_stop()
+ self._stop_reserved(server)
+
+ @staticmethod
+ def _resolved_accelerator() -> str:
+ """The installer accelerator this host's device target resolves to (cpu / cuda / rocm /
+ vulkan). Lazy import avoids an import cycle with the engine router."""
+ from core.inference.diffusion_engine_router import _install_accelerator_for
+ return _install_accelerator_for(
+ getattr(resolve_diffusion_device_target(), "backend", "cpu")
+ )
+
def _resolve_engine(self) -> SdCppEngine:
"""The SdCppEngine, installing the binary on first use. Raises if unusable."""
if self._engine is not None and self._engine.is_available():
return self._engine
- binary = ensure_sd_cpp_binary(allow_install = _install_allowed())
+ # The accelerator this host resolves to, never the "cpu" default: this is also the
+ # one-shot FALLBACK path (a GPU sd-server that would not start lands here), and asking
+ # for the CPU build there would reinstall the plain bundle over the working GPU one and
+ # run the whole generation on the CPU.
+ binary = ensure_sd_cpp_binary(
+ allow_install = _install_allowed() and not _tree_in_use(self),
+ accelerator = self._resolved_accelerator(),
+ )
if not binary:
raise RuntimeError("sd-cli (stable-diffusion.cpp) binary is unavailable.")
self._engine = SdCppEngine(binary = binary)
@@ -415,14 +579,20 @@ class SdCppDiffusionBackend:
"""
if self._engine_injected and self._engine is not None:
return "oneshot", None, self._resolve_engine()
- # Install the server build matching the resolved backend (ROCm/Vulkan/CUDA), not the default CPU build. Lazy import avoids an import cycle.
- from core.inference.diffusion_engine_router import _install_accelerator_for
-
- accelerator = _install_accelerator_for(
- getattr(resolve_diffusion_device_target(), "backend", "cpu")
- )
+ accelerator = self._resolved_accelerator()
+ # An accelerator upgrade REPLACES the binaries in the managed tree, and this runs before
+ # the load stops the resident server (which is executing its own file) or waits out an
+ # in-flight one-shot sd-cli. Linux refuses to open a running executable for writing
+ # (ETXTBSY) and Windows locks it, so an install here fails and can leave the tree
+ # half-written. _accelerator_changed refuses the upgrade while the tree is in use, whoever
+ # asks; record that it did, so this load retries it after its own teardown, when the tree
+ # is the only thing that has changed.
+ # _managed_tree_in_use covers the singleton for callers that never see this instance (the
+ # engine router); this load's own state is the authority for this load.
+ upgrade_pending = _tree_in_use(self) or _managed_tree_in_use()
+ self._deferred_accelerator_install = upgrade_pending
server_binary = ensure_sd_server_binary(
- allow_install = _install_allowed(), accelerator = accelerator
+ allow_install = _install_allowed() and not upgrade_pending, accelerator = accelerator
)
if server_binary is not None:
return "server", server_binary, None
@@ -431,6 +601,35 @@ class SdCppDiffusionBackend:
)
return "oneshot", None, self._resolve_engine()
+ def _upgrade_server_after_teardown(self, server_binary: Optional[str]) -> Optional[str]:
+ """Land the install this load deferred, now the managed tree is free.
+
+ Called under both locks with the old server stopped and the previous generation finished,
+ which is the only moment nothing is executing out of the tree. ``server_binary`` is None on
+ a serverless install (one-shot sd-cli only): the install still has to run, since the same
+ archive carries the sd-cli this load is about to generate with -- skipping it there is what
+ left a CUDA request committing the old CPU CLI. Returns the upgraded path, the one passed
+ in when nothing changed or the install could not deliver, or None when there was no server
+ and the archive has none: never worse than what the load already had."""
+ if not _install_allowed():
+ return server_binary
+ try:
+ accelerator = self._resolved_accelerator()
+ # Judge the tree by whatever binary it holds: on a serverless install that is the
+ # sd-cli, and without this the retry would reinstall on every deferred load, matching
+ # accelerator or not.
+ probe = server_binary or find_sd_cpp_binary()
+ if probe is None or not _accelerator_changed(probe, accelerator):
+ return server_binary
+ logger.info("installing the %s sd.cpp build now the managed tree is free", accelerator)
+ return (
+ ensure_sd_server_binary(allow_install = True, accelerator = accelerator)
+ or server_binary
+ )
+ except Exception as exc: # noqa: BLE001 -- an upgrade may never fail the load
+ logger.warning("sd.cpp accelerator upgrade failed: %s", exc)
+ return server_binary
+
# ── Background load + progress ─────────────────────────────────────────
def begin_load(
@@ -620,14 +819,32 @@ class SdCppDiffusionBackend:
return # superseded / cancelled while waiting
old_state = self._state
self._state = None # the old model is being torn down
+ # Same lock block as the clear, so the tree is never briefly readable as idle.
+ if old_state is not None and old_state.server is not None:
+ self._reserve_stop()
if old_state is not None and old_state.server is not None:
- old_state.server.stop()
+ self._stop_reserved(old_state.server)
+ # The tree is free now, so an install deferred in _resolve_backend can land: this
+ # runs under both locks, the old server is stopped, the previous generation has
+ # finished and no new one can start. Not gated on the resolved mode: a serverless
+ # install resolves to one-shot precisely BECAUSE the deferral suppressed the
+ # install, and its sd-cli comes out of the same archive.
+ if self._deferred_accelerator_install:
+ self._deferred_accelerator_install = False
+ upgraded = self._upgrade_server_after_teardown(server_binary)
+ if mode == "server":
+ server_binary = upgraded
# A new checkpoint earns a fresh attempt on the GPU backend: the previous abort says nothing about this graph.
self._cpu_backend_forced = False
server: Optional[SdCppServer] = None
if 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
@@ -652,6 +869,12 @@ class SdCppDiffusionBackend:
start_exc,
)
server.stop()
+ # Unpublish BEFORE resolving the one-shot engine: _pending_server means "a
+ # process is running out of the tree", and leaving this stopped one there
+ # would block the very sd-cli install this fallback needs.
+ with self._lock:
+ if self._pending_server is server:
+ self._pending_server = None
server = None
try:
usable = self._resolve_engine().version() is not None
@@ -662,7 +885,7 @@ class SdCppDiffusionBackend:
mode = "oneshot"
finally:
with self._lock:
- if self._pending_server is server:
+ if self._pending_server is started:
self._pending_server = None
state = _SdState(
repo_id = repo_id,
@@ -1506,11 +1729,20 @@ class SdCppDiffusionBackend:
# Grab a mid-start() uncommitted server too so we can stop it (startup is abortable).
pending = self._pending_server
self._pending_server = None
+ # Reserved HERE, not at the stop below: the fields are already empty by then, and a
+ # router probe landing in that gap would read an idle tree and reinstall over a
+ # process that is still running.
+ to_stop = [
+ srv
+ for srv in (state.server if state is not None else None, pending)
+ if srv is not None
+ ]
+ if pending is not None and state is not None and pending is state.server:
+ to_stop = to_stop[:1]
+ self._reserve_stop(len(to_stop))
# Stop the resident server outside the lock (terminate can take seconds); a mid-flight generation unwinds as the process goes away.
- if state is not None and state.server is not None:
- state.server.stop()
- if pending is not None and pending is not (state.server if state else None):
- pending.stop()
+ for srv in to_stop:
+ self._stop_reserved(srv)
# Barrier: wait for a signalled one-shot generation to exit before reporting unloaded, since callers treat this return as "device is free".
with self._generate_lock:
pass
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index d0e627dbf72..b977247ce75 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1083,6 +1083,11 @@ def test_server_start_failure_falls_back_to_oneshot(monkeypatch):
_load_token = 1,
)
assert b._state is not None and b._state.mode == "oneshot" and b._state.server is None
+ # The server it started and stopped must not stay published: _pending_server means "a native
+ # process is running out of the managed tree", which suppresses every later accelerator
+ # install, so a stale one would pin this process to the wrong build until a restart.
+ assert b._pending_server is None
+ assert bk._tree_in_use(b) is False
# and it can still generate via the one-shot engine
out = b.generate(prompt = "x", steps = 4, seed = 1)
assert len(out["images"]) == 1 and len(fake.calls) == 1
diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.py
index 2356f534ab7..2eea8b95063 100644
--- a/studio/backend/tests/test_sd_cpp_install.py
+++ b/studio/backend/tests/test_sd_cpp_install.py
@@ -18,7 +18,11 @@ if str(_STUDIO) not in sys.path:
sys.path.insert(0, str(_STUDIO))
import hashlib # noqa: E402
+import builtins # noqa: E402
+import types # noqa: E402
+import threading # noqa: E402
import io # noqa: E402
+import re # noqa: E402
import json # noqa: E402
import urllib.error # noqa: E402
import zipfile # noqa: E402
@@ -37,6 +41,7 @@ from install_sd_cpp_prebuilt import ( # noqa: E402
default_install_dir,
install,
resolve_release_asset,
+ upstream_tag_for,
)
# A real stable-diffusion.cpp latest-release asset list.
@@ -400,10 +405,19 @@ def test_find_sd_cpp_binary_honors_studio_home(tmp_path, monkeypatch):
# The shipped pin, not a copy of it: a hardcoded tag here silently stops describing what users
# actually install the moment DEFAULT_TAG moves.
_TAG = DEFAULT_TAG
-# Exactly what unslothai/stable-diffusion.cpp's CI publishes (CPU + Apple only; GPU hosts run diffusers).
+# Exactly what unslothai/stable-diffusion.cpp's CI publishes. It was CPU and Apple only, on the
+# premise that a GPU host runs diffusers instead. MiniMax-H3 falsified that: its diffusers path
+# wants more VRAM than a consumer card has, so those hosts fall back to the native engine, and on
+# Linux there was no accelerated build to fall back to. The CUDA leg is best effort and outside the
+# publisher's coverage gate, so it can be absent from a release; every test below has to hold
+# either way.
_MIRROR_ASSETS = [
f"sd-{_TAG}-bin-Darwin-macOS-arm64.zip",
f"sd-{_TAG}-bin-Darwin-macOS-x86_64.zip",
+ # Before the plain build, which is the order a real release lists them in ("-cuda12.zip"
+ # sorts ahead of ".zip"). It matters: if auto picked by position rather than by the
+ # accelerator-marker filter, this ordering is what would expose it.
+ f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip",
f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64.zip",
f"sd-{_TAG}-bin-Linux-Ubuntu-24.04-aarch64.zip",
f"sd-{_TAG}-bin-win-cpu-x64.zip",
@@ -435,6 +449,95 @@ def test_mirror_matrix_resolves_every_cpu_apple_host():
assert _mresolve("Windows", "AMD64", "cpu") == f"sd-{_TAG}-bin-win-cpu-x64.zip"
+def test_mirror_linux_cuda_resolves_the_cuda_bundle():
+ """A CUDA host asking for cuda gets the accelerated build. This is what makes MiniMax-H3
+ usable there: its GGUF path was running on the CPU because no Linux CUDA asset existed, and
+ video.py falls back to the CPU prebuilt whenever the accelerated one cannot be resolved."""
+ assert (
+ _mresolve("Linux", "x86_64", "cuda")
+ == f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip"
+ )
+
+
+def test_mirror_linux_auto_still_takes_the_plain_cpu_build():
+ """The CUDA bundle ships the CUDA runtime and is roughly 25x the size of the CPU one. A host
+ that did not ask for a GPU build must not be handed it by accident."""
+ assert _mresolve("Linux", "x86_64") == f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64.zip"
+ assert _mresolve("Linux", "x86_64", "cpu") == f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64.zip"
+
+
+def test_mirror_linux_cuda_refuses_a_release_without_one():
+ """The CUDA leg is best effort, so a release can lack the asset. Returning None lets the
+ caller fall back deliberately; handing back the CPU build would leave the caller believing it
+ had a GPU binary, keep the load on the GPU device, and run sd-cli wholly on the CPU."""
+ without = [a for a in _MIRROR_ASSETS if "cuda" not in a]
+ assert (
+ resolve_release_asset(without, system = "Linux", machine = "x86_64", accelerator = "cuda") is None
+ )
+
+
+# ── the pin translates to upstream ───────────────────────────────────────────
+
+
+def test_upstream_tag_drops_the_mirror_fork_suffix():
+ """A mirror release built on an upstream one is that tag plus "-u<fork sha>", and only the
+ base half exists upstream. The suffix has to come off before the fallback asks for it."""
+ assert upstream_tag_for("master-813-bfbef5b-u13b9d92") == "master-813-bfbef5b"
+ assert upstream_tag_for("master-813-bfbef5b-u0665242") == "master-813-bfbef5b"
+ # A plain upstream tag, and a tag whose trailing segment is not a fork sha, pass through.
+ assert upstream_tag_for("master-809-eb7f35c") == "master-809-eb7f35c"
+ assert upstream_tag_for("v1.2.3-ubuntu") == "v1.2.3-ubuntu"
+ assert upstream_tag_for(None) is None
+
+
+def test_shipped_pin_translates_to_a_plain_upstream_tag():
+ """Guards the pin itself: whatever DEFAULT_TAG becomes, the string handed upstream must not
+ still carry a fork suffix, or the fallback is asking for a release that cannot exist."""
+ assert re.search(r"-u[0-9a-f]{7,}$", upstream_tag_for(DEFAULT_TAG)) is None
+
+
+def test_upstream_fallback_asks_for_the_translated_pin_not_latest(monkeypatch):
+ """A Linux Vulkan host: the mirror has no such asset, so resolution falls to upstream. It must
+ ask upstream for the pin's upstream base tag and stop there -- reaching an unpinned upstream
+ "latest" is exactly the reproducibility loss the translation exists to prevent."""
+ monkeypatch.delenv("UNSLOTH_SD_CPP_REPO", raising = False)
+ monkeypatch.setenv("UNSLOTH_SD_CPP_TAG", "master-813-bfbef5b-u13b9d92")
+ monkeypatch.setattr(sdmod.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(sdmod.platform, "machine", lambda: "x86_64")
+ seen = []
+
+ def fake_fetch(
+ tag = None,
+ *,
+ repo = None,
+ token = None,
+ timeout = 30.0,
+ allow_latest = True,
+ ):
+ seen.append((repo, tag))
+ if repo == sdmod.UPSTREAM_FALLBACK_REPO and tag == "master-813-bfbef5b":
+ return {
+ "tag_name": tag,
+ "assets": [{"name": "sd-master-bfbef5b-bin-Linux-Ubuntu-24.04-x86_64-vulkan.zip"}],
+ }
+ # The mirror serves the pin but builds no Vulkan asset; every other request 404s.
+ if repo == sdmod.DEFAULT_REPO and tag == "master-813-bfbef5b-u13b9d92":
+ return {
+ "tag_name": tag,
+ "assets": [{"name": f"sd-{tag}-bin-Linux-Ubuntu-22.04-x86_64.zip"}],
+ }
+ raise urllib.error.HTTPError(f"https://api/{repo}", 404, "not found", None, None)
+
+ monkeypatch.setattr(sdmod, "_fetch_release", fake_fetch)
+ repo, release, chosen = sdmod._resolve_with_fallback("vulkan", None)
+ assert repo == sdmod.UPSTREAM_FALLBACK_REPO
+ assert release["tag_name"] == "master-813-bfbef5b"
+ assert chosen.endswith("-vulkan.zip")
+ # The raw fork tag is never sent upstream, and no unpinned latest is ever requested.
+ assert (sdmod.UPSTREAM_FALLBACK_REPO, "master-813-bfbef5b-u13b9d92") not in seen
+ assert not any(tag is None for _repo_name, tag in seen)
+
+
# ── mirror -> upstream fallback in install() ─────────────────────────────────
@@ -534,7 +637,10 @@ def test_mirror_windows_gpu_accel_is_no_match_not_cpu():
def test_mirror_linux_gpu_accel_is_no_match_not_cpu():
- for accel in ("cuda", "vulkan", "rocm"):
+ # cuda is no longer in this list: the mirror publishes a Linux CUDA bundle now, and
+ # test_mirror_linux_cuda_resolves_the_cuda_bundle pins that. vulkan and rocm are still
+ # unbuilt, and must return None rather than quietly resolving to the CPU zip.
+ for accel in ("vulkan", "rocm"):
assert _mresolve("Linux", "x86_64", accel) is None
assert _mresolve("Linux", "x86_64", "cpu") == f"sd-{_TAG}-bin-Linux-Ubuntu-22.04-x86_64.zip"
@@ -776,3 +882,708 @@ def test_a_reinstall_over_an_owned_root_keeps_the_repair_loop_closed(tmp_path, m
sd_cli = install(install_dir = target)
assert (target / ".unsloth-studio-owned").is_file()
assert eng.is_managed_binary(str(sd_cli)) is True
+
+
+# ── the install records its accelerator, and a change reinstalls ─────────────
+
+
+def test_install_records_the_accelerator_it_installed(tmp_path, monkeypatch):
+ """The record is what lets a later ensure_* tell a CPU bundle from a GPU one."""
+ zb = _zip_with_sd_cli()
+ _stub_release(monkeypatch, zip_bytes = zb, digest = "sha256:" + hashlib.sha256(zb).hexdigest())
+ target = tmp_path / "sd-home" / "stable-diffusion.cpp"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))
+
+ install(install_dir = target)
+ assert sdmod.installed_accelerator(target) == "cpu"
+ # "auto" resolves to the same plain build, so it must not read as a different install.
+ assert sdmod.accelerator_class("auto") == sdmod.accelerator_class("cpu") == "cpu"
+ assert sdmod.accelerator_class("CUDA") == "cuda"
+ # No record at all is "unknown", not "cpu".
+ assert sdmod.installed_accelerator(tmp_path / "nothing-here") is None
+
+
+def _managed_tree(
+ tmp_path,
+ monkeypatch,
+ accelerator = None,
+):
+ """A Studio-owned install tree, optionally carrying an install record."""
+ 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"))
+ if accelerator is not None:
+ sdmod._write_install_record(root, accelerator = accelerator, repo = "r", tag = "t")
+ return root
+
+
+def test_a_cpu_install_is_reinstalled_when_cuda_is_requested(tmp_path, monkeypatch):
+ """The P1: an upgraded Linux CUDA host already holding the managed CPU bundle. Both ensure_*
+ returned any runnable binary they found, so the new CUDA asset was never installed and native
+ generation silently stayed entirely on the CPU."""
+ 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())
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert [k["accelerator"] for k in installs] == ["cuda"], "the CUDA build must be installed"
+ assert server.read_bytes() == b"cuda-build"
+ # Now that the record says cuda, the next load reuses it instead of reinstalling.
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert len(installs) == 1
+
+
+def test_asking_for_the_cpu_build_never_reinstalls(tmp_path, monkeypatch):
+ """Only an upgrade reinstalls. A CPU/auto request must reuse whatever is there, including an
+ install predating the record, or every CPU host would re-download on its next load."""
+ import core.inference.sd_cpp_backend as bk
+
+ root = _managed_tree(tmp_path, monkeypatch, accelerator = None) # no record: an older install
+ server = root / "sd-bin" / "sd-server"
+ server.write_bytes(b"cpu-build")
+ cli = root / "sd-bin" / "sd-cli"
+ cli.write_bytes(b"cpu-build")
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: str(server))
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+
+ def _install(**_kwargs):
+ raise AssertionError("a CPU request must not reinstall")
+
+ monkeypatch.setattr(sdmod, "install", _install)
+ assert bk.ensure_sd_server_binary(accelerator = "cpu") == str(server)
+ assert bk.ensure_sd_cpp_binary(accelerator = "auto") == str(cli)
+
+
+def test_a_user_supplied_binary_is_never_reinstalled_over_on_an_accelerator_change(
+ tmp_path, monkeypatch
+):
+ """An unmarked root is the user's own build. install() would refuse it anyway, so attempting
+ the upgrade would only cost a download and end with no binary at all."""
+ import core.inference.sd_cpp_backend as bk
+
+ root = tmp_path / "sd-home" / "stable-diffusion.cpp" # deliberately NOT marked
+ (root / "sd-bin").mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))
+ server = root / "sd-bin" / "sd-server"
+ server.write_bytes(b"users-own-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())
+
+ def _install(**_kwargs):
+ raise AssertionError("an unmarked (user-owned) root must not be reinstalled over")
+
+ monkeypatch.setattr(sdmod, "install", _install)
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+
+
+def test_a_failed_upgrade_keeps_the_working_binary_and_stops_retrying(tmp_path, monkeypatch):
+ """A host with no asset for the requested accelerator must keep the binary it has (returning
+ None would drop native inference entirely) and must not re-resolve on every later load."""
+ 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())
+ attempts: list = []
+
+ def _install(**kwargs):
+ attempts.append(kwargs)
+ raise RuntimeError("No prebuilt sd-cli for this host")
+
+ monkeypatch.setattr(sdmod, "install", _install)
+
+ assert bk.ensure_sd_server_binary(accelerator = "vulkan") == str(server)
+ assert bk.ensure_sd_server_binary(accelerator = "vulkan") == str(server)
+ assert len(attempts) == 1, "the hopeless upgrade must be attempted once, not once per load"
+ assert server.read_bytes() == b"cpu-build"
+
+
+def test_the_upgrade_waits_for_the_resident_server_to_stop(tmp_path, monkeypatch):
+ """The install replaces the sd-server file, and the resident server is executing that exact
+ path: Linux refuses to open a running executable for writing (ETXTBSY) and Windows locks it.
+ Resolving must therefore NOT install while a server is up; the load retries once it is
+ stopped, which is the only moment the file is free."""
+ 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, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ backend = bk.SdCppDiffusionBackend()
+ # A resident server is up: resolving must hand back the existing binary and install nothing.
+ backend._state = types.SimpleNamespace(server = object())
+ mode, resolved, _engine = backend._resolve_backend()
+ assert mode == "server" and resolved == str(server)
+ assert installs == [], "no install may run while the server holds its own executable"
+ assert server.read_bytes() == b"cpu-build"
+
+ # Once it is stopped, the deferred upgrade lands.
+ backend._state = None
+ upgraded = backend._upgrade_server_after_teardown(str(server))
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+ assert upgraded == str(server) and server.read_bytes() == b"cuda-build"
+ # Now that the record matches, a later teardown does not reinstall again.
+ assert backend._upgrade_server_after_teardown(str(server)) == str(server)
+ assert len(installs) == 1
+
+
+def test_a_failed_post_teardown_upgrade_keeps_the_existing_server(tmp_path, monkeypatch):
+ """An upgrade may never cost the load the binary it already had."""
+ 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, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+
+ def _boom(**_kwargs):
+ raise RuntimeError("no prebuilt for this host")
+
+ monkeypatch.setattr(sdmod, "install", _boom)
+
+ backend = bk.SdCppDiffusionBackend()
+ backend._state = None
+ assert backend._upgrade_server_after_teardown(str(server)) == str(server)
+ assert server.read_bytes() == b"cpu-build"
+
+
+def test_a_recorded_gpu_install_is_replaced_when_the_cpu_build_is_wanted(tmp_path, monkeypatch):
+ """The mirror image of the CPU-to-CUDA upgrade. Nothing on the sd-server/sd-cli command line
+ selects a backend -- the build itself is the choice -- so a recorded CUDA install keeps running
+ on the GPU after the device target resolves to CPU. Only a RECORDED mismatch reinstalls: an
+ unrecorded install stays put, else every legacy CPU host would redownload on a CPU target."""
+ 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")
+ 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())
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ server.write_bytes(b"cpu-build")
+ sdmod._write_install_record(root, accelerator = kwargs["accelerator"], repo = "r", tag = "t")
+ return root / "sd-bin" / "sd-cli"
+
+ monkeypatch.setattr(sdmod, "install", _install)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cpu") == str(server)
+ assert [k["accelerator"] for k in installs] == ["cpu"]
+ assert server.read_bytes() == b"cpu-build"
+ # The record now says cpu, so the next CPU load reuses it.
+ assert bk.ensure_sd_server_binary(accelerator = "cpu") == str(server)
+ assert len(installs) == 1
+
+
+def test_the_upgrade_waits_for_an_active_one_shot_generation(tmp_path, monkeypatch):
+ """A one-shot load holds the managed tree just as hard as a resident server: begin_load only
+ signals the in-flight generation to cancel, and _resolve_backend runs before the load waits on
+ _generate_lock, so the old sd-cli can still be executing from the tree an install would
+ overwrite. Defer there too, and land the upgrade after the teardown."""
+ 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, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ backend = bk.SdCppDiffusionBackend()
+ # One-shot: no resident server, but a generation is still running out of the tree.
+ backend._state = types.SimpleNamespace(server = None)
+ backend._active_generate_cancel = threading.Event()
+ mode, resolved, _engine = backend._resolve_backend()
+ assert mode == "server" and resolved == str(server)
+ assert installs == [], "no install may run while a one-shot sd-cli is executing"
+ assert server.read_bytes() == b"cpu-build"
+ assert backend._deferred_accelerator_install is True
+
+ # After the teardown the generation is over and the tree is free.
+ backend._state = None
+ backend._active_generate_cancel = None
+ assert backend._upgrade_server_after_teardown(str(server)) == str(server)
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+ assert server.read_bytes() == b"cuda-build"
+
+
+def test_an_idle_backend_installs_the_matching_build_immediately(tmp_path, monkeypatch):
+ """The deferral is only for a tree in use: with nothing running, resolving installs at once."""
+ 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, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ backend = bk.SdCppDiffusionBackend()
+ mode, resolved, _engine = backend._resolve_backend()
+ assert mode == "server" and resolved == str(server)
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+ assert backend._deferred_accelerator_install is False
+
+
+def test_the_router_entry_point_cannot_replace_a_running_server(tmp_path, monkeypatch):
+ """select_and_activate_engine calls ensure_sd_server_binary DIRECTLY, before begin_load stops
+ anything, so a deferral that lives only in _resolve_backend does not cover it: a /images/load
+ that resolves to CUDA while the managed CPU server is resident would extract over the running
+ executable. The refusal therefore lives in _accelerator_changed, where every caller passes."""
+ 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())
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ resident = bk.SdCppDiffusionBackend()
+ resident._state = types.SimpleNamespace(server = object())
+ monkeypatch.setattr(bk, "_sd_cpp_backend", resident)
+
+ # The router's own call, verbatim: no backend instance in sight.
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert installs == [], "the running server's file may not be overwritten"
+ assert server.read_bytes() == b"cpu-build"
+
+ # With nothing resident the same call upgrades as before.
+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+
+
+def test_the_one_shot_fallback_keeps_the_requested_accelerator(tmp_path, monkeypatch):
+ """_resolve_engine is also the fallback a GPU sd-server that would not start lands on. It
+ asked for the default "cpu", which -- now that a recorded GPU install counts as a mismatch
+ against a CPU request -- would reinstall the plain bundle over the working GPU one and run the
+ whole generation on the CPU because of an unrelated server startup failure."""
+ import core.inference.sd_cpp_backend as bk
+
+ root = _managed_tree(tmp_path, monkeypatch, accelerator = "cuda")
+ cli = root / "sd-bin" / "sd-cli"
+ cli.write_bytes(b"cuda-build")
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ monkeypatch.setattr(bk, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+ monkeypatch.setattr(
+ bk,
+ "SdCppEngine",
+ lambda binary: types.SimpleNamespace(
+ binary = binary, is_available = lambda: True, version = lambda: "x"
+ ),
+ )
+
+ def _install(**kwargs):
+ raise AssertionError(f"no reinstall may happen here (asked for {kwargs['accelerator']})")
+
+ monkeypatch.setattr(sdmod, "install", _install)
+
+ backend = bk.SdCppDiffusionBackend()
+ assert backend._resolve_engine().binary == str(cli)
+ assert cli.read_bytes() == b"cuda-build"
+
+
+def test_a_serverless_deferred_install_still_lands_after_teardown(tmp_path, monkeypatch):
+ """The serverless branch: only sd-cli is installed, so the deferral resolves the load to
+ one-shot, and gating the post-teardown retry on mode == "server" skipped it for good. The
+ archive carries the sd-cli this load generates with, so the install has to run anyway."""
+ 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"cpu-build")
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: None) # serverless install
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ monkeypatch.setattr(bk, "_install_allowed", lambda: True)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(backend = "cuda")
+ )
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ cli.write_bytes(b"cuda-build")
+ sdmod._write_install_record(root, accelerator = kwargs["accelerator"], repo = "r", tag = "t")
+ return cli
+
+ monkeypatch.setattr(sdmod, "install", _install)
+
+ backend = bk.SdCppDiffusionBackend()
+ backend._state = types.SimpleNamespace(server = None)
+ backend._active_generate_cancel = threading.Event() # a one-shot sd-cli is still running
+ mode, server_binary, _engine = backend._resolve_backend()
+ assert mode == "oneshot" and server_binary is None
+ assert installs == [] and backend._deferred_accelerator_install is True
+
+ # After the teardown the tree is free, and the install lands even though the load resolved to
+ # one-shot: sd-cli comes out of the same archive.
+ backend._state = None
+ backend._active_generate_cancel = None
+ assert backend._upgrade_server_after_teardown(None) is None # this archive ships no server
+ assert [k["accelerator"] for k in installs] == ["cuda"], "the sd-cli still has to be upgraded"
+ assert cli.read_bytes() == b"cuda-build"
+
+ # And a matching tree is not reinstalled on the next deferred load.
+ assert backend._upgrade_server_after_teardown(None) is None
+ assert len(installs) == 1
+
+
+def test_a_server_still_starting_also_holds_the_tree(tmp_path, monkeypatch):
+ """The startup window: between spawning sd-server and committing it to _state, the load has
+ published only _pending_server. A second /images/load asking for a different accelerator would
+ read the tree as idle and extract over the executable that is starting -- and start() blocks
+ for as long as the checkpoint takes to load, so the window is minutes, not milliseconds."""
+ 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())
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ 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", _install)
+
+ starting = bk.SdCppDiffusionBackend()
+ starting._state = None # not committed yet
+ starting._pending_server = object()
+ monkeypatch.setattr(bk, "_sd_cpp_backend", starting)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert installs == [], "the starting server's file may not be overwritten"
+ assert server.read_bytes() == b"cpu-build"
+
+ # Once it has committed and been torn down, the upgrade lands.
+ starting._pending_server = None
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+
+
+def test_a_serverless_install_is_not_replaced_under_a_running_cli(tmp_path, monkeypatch):
+ """The gap a mismatch-only guard leaves: on a legacy install with no sd-server,
+ find_sd_server_binary returns None, so _accelerator_changed is never consulted and the install
+ runs unconditionally. The router calls this directly with installs enabled, so a one-shot
+ sd-cli mid-generation would have the tree extracted over it."""
+ 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"cpu-build")
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: None) # serverless install
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ cli.write_bytes(b"cuda-build")
+ sdmod._write_install_record(root, accelerator = kwargs["accelerator"], repo = "r", tag = "t")
+ return cli
+
+ monkeypatch.setattr(sdmod, "install", _install)
+
+ generating = bk.SdCppDiffusionBackend()
+ generating._active_generate_cancel = threading.Event() # a one-shot sd-cli is running
+ monkeypatch.setattr(bk, "_sd_cpp_backend", generating)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") is None
+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)
+ assert installs == [], "no extraction over a running sd-cli"
+ assert cli.read_bytes() == b"cpu-build"
+
+ # With nothing running the install goes ahead, so a first install is never blocked.
+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)
+ bk.ensure_sd_server_binary(accelerator = "cuda")
+ assert [k["accelerator"] for k in installs] == ["cuda"]
+
+
+def test_the_tree_stays_in_use_until_a_stopping_server_is_gone(tmp_path, monkeypatch):
+ """unload() clears _state and _pending_server under the lock and stops OUTSIDE it, because
+ terminate can take seconds. In that window both fields say idle while the process is still
+ running its own executable, so a router call asking for another accelerator could extract over
+ it. The stop is counted, and the count keeps the tree marked in use."""
+ import core.inference.sd_cpp_backend as bk
+
+ backend = bk.SdCppDiffusionBackend()
+ seen: list = []
+
+ class _SlowServer:
+ def stop(self):
+ # What a concurrent router call would see while this process is still going down.
+ seen.append(bk._tree_in_use(backend))
+
+ backend._stop_server(_SlowServer())
+ assert seen == [True], "the tree must read busy until stop() returns"
+ assert bk._tree_in_use(backend) is False
+ assert backend._stopping_servers == 0
+
+ # A stop that raises must neither propagate nor leak the count.
+ class _BadServer:
+ def stop(self):
+ raise RuntimeError("terminate failed")
+
+ backend._stop_server(_BadServer())
+ assert backend._stopping_servers == 0 and bk._tree_in_use(backend) is False
+
+
+def test_a_failed_server_upgrade_is_not_retried_by_the_cli_probe(tmp_path, monkeypatch):
+ """The router probes the server first and the CLI immediately after. With only a usable CPU
+ sd-cli in the tree, the failed server upgrade left no record (fallback was None), so the CLI
+ probe resolved and downloaded the very same bundle a second time inside one selection."""
+ 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"cpu-build")
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: None)
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: str(cli))
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set())
+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)
+ attempts: list = []
+
+ def _boom(**kwargs):
+ attempts.append(kwargs["accelerator"])
+ raise RuntimeError("no cuda asset for this host")
+
+ monkeypatch.setattr(sdmod, "install", _boom)
+
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") is None
+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)
+ assert 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."""
+ 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")
+
+ 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")
+ buf.seek(0)
+ with zipfile.ZipFile(buf) as zf:
+ assert sdmod._archive_ships_sd_server(zf) is False
+
+ sdmod._discard_stale_sd_server(target)
+ assert not stale.exists()
+ assert sdmod._locate_sd_server(target) is None
+
+
+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"
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr(f"bin/{server_name}", "new")
+ buf.seek(0)
+ with zipfile.ZipFile(buf) as zf:
+ assert sdmod._archive_ships_sd_server(zf) is True
+
+
+def test_the_stop_is_reserved_before_the_server_is_unpublished(tmp_path, monkeypatch):
+ """The count has to be claimed in the SAME lock block that clears _state/_pending_server. Doing
+ it inside the stop leaves a gap where the resident, pending, stopping and generating fields are
+ all empty while the process is still executing out of the managed tree."""
+ import core.inference.sd_cpp_backend as bk
+
+ backend = bk.SdCppDiffusionBackend()
+ seen: list = []
+
+ class _Server:
+ def stop(self):
+ seen.append(bk._tree_in_use(backend))
+
+ def is_alive(self):
+ return True
+
+ server = _Server()
+ backend._state = types.SimpleNamespace(server = server, mode = "server")
+ monkeypatch.setattr(backend, "status", lambda: {"loaded": False})
+
+ backend.unload()
+ assert seen == [True], "the tree must still read busy while the old server is going down"
+ assert backend._stopping_servers == 0 and bk._tree_in_use(backend) is False
+
+
+def test_a_failed_start_does_not_block_its_own_cli_fallback(tmp_path, monkeypatch):
+ """The fallback resolves the one-shot engine after stopping the server it just started. With
+ that stopped server still in _pending_server the tree reads busy, so the lazy sd-cli install
+ the fallback depends on was disabled and the load re-raised the server error instead."""
+ import core.inference.sd_cpp_backend as bk
+
+ backend = bk.SdCppDiffusionBackend()
+ server = object()
+ backend._pending_server = server
+ assert bk._tree_in_use(backend) is True
+ # What the fallback now does before it resolves the engine.
+ with backend._lock:
+ if backend._pending_server is server:
+ backend._pending_server = None
+ assert bk._tree_in_use(backend) is False
+
+
+def test_an_unwritable_record_does_not_cost_the_install_or_repeat_it(tmp_path, monkeypatch):
+ """A GPU bundle that extracts fine but cannot write its record used to read as unrecorded
+ forever, and unrecorded is a mismatch for a GPU target: every later selection re-downloaded the
+ same bundle. The install still succeeds, and the accelerator is remembered for this process."""
+ root = tmp_path / "sd"
+ root.mkdir()
+ (root / sdmod.INSTALL_RECORD).mkdir() # a directory where the record file goes: open() fails
+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()
+
+ sdmod._write_install_record(root, accelerator = "cuda", repo = "r", tag = "t")
+ assert sdmod.read_install_record(root) == {} # nothing on disk, as expected
+ assert sdmod.installed_accelerator(root) == "cuda" # but not "unknown"
+
+
+def test_a_stale_unwritable_record_does_not_outrank_what_was_just_installed(tmp_path, monkeypatch):
+ """The nastier shape of the same failure: the old record is READABLE but cannot be replaced, so
+ it keeps answering "cpu" after a successful cuda install and every later selection downloads
+ the bundle again. What this process installed is strictly newer than what is on disk."""
+ 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)
+
+ # The stale file is still there and still says cpu ...
+ assert sdmod.read_install_record(root)["accelerator"] == "cpu"
+ # ... but the accelerator this tree actually holds is the one just installed.
+ 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 _no_unlink(self, *a, **k):
+ raise OSError("permission denied")
+
+ monkeypatch.setattr(Path, "unlink", _no_unlink)
+ with pytest.raises(RuntimeError) as exc:
+ sdmod._discard_stale_sd_server(root)
+ assert "superseded sd-server" in str(exc.value)
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index a880c558b47..e1d8caa49df 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -29,6 +29,7 @@ import hashlib
import json
import os
import platform
+import re
import shutil
import stat
import sys
@@ -43,11 +44,72 @@ DEFAULT_REPO = "unslothai/stable-diffusion.cpp"
# Fallback when the mirror cannot serve this host (release missing, or a host we do not build).
UPSTREAM_FALLBACK_REPO = "leejet/stable-diffusion.cpp"
# Pinned for reproducibility; UNSLOTH_SD_CPP_TAG overrides (empty tracks latest). A missing tag falls back to latest.
-DEFAULT_TAG = "master-809-eb7f35c"
+DEFAULT_TAG = "master-813-bfbef5b-u13b9d92"
# Back-compat alias (some callers/tests import REPO).
REPO = DEFAULT_REPO
+# What the managed directory records about the install it holds, so a later ensure_* can tell a CPU
+# bundle from a CUDA one instead of reusing whatever binary happens to be on disk.
+INSTALL_RECORD = ".unsloth-sd-cpp-install.json"
+
+
+def accelerator_class(accelerator: Optional[str]) -> str:
+ """The accelerator an install actually serves. ``auto`` resolves to the plain build, so it and
+ ``cpu`` are the same install and must not look like an upgrade to one another."""
+ accel = (accelerator or "auto").strip().lower()
+ return "cpu" if accel in ("auto", "cpu", "") else accel
+
+
+def read_install_record(root: Path) -> dict:
+ """The install record in ``root``, or ``{}`` when there is none (an install predating the
+ record, or a directory that is not ours). Never raises."""
+ try:
+ with open(root / INSTALL_RECORD, "r", encoding = "utf-8") as f:
+ rec = json.load(f)
+ return rec if isinstance(rec, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+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")
+ 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] = {}
+
+
+def _write_install_record(root: Path, *, accelerator: str, repo: str, tag: Optional[str]) -> None:
+ """Record what this install is, so a later ensure_* can tell a CPU bundle from a GPU one.
+
+ The write itself stays best-effort -- a metadata failure must not throw away binaries that
+ extracted correctly -- but the answer is memoised either way, so this process never re-installs
+ what it just installed."""
+ klass = accelerator_class(accelerator)
+ _INSTALLED_ACCELERATOR_MEMO[str(root)] = klass
+ try:
+ with open(root / INSTALL_RECORD, "w", encoding = "utf-8") as f:
+ json.dump({"accelerator": klass, "repo": repo, "tag": tag}, f)
+ except OSError as exc:
+ print(
+ f"sd-cli: WARNING could not write the install record in {root}: {exc}; "
+ f"remembering {klass} for this process only",
+ flush = True,
+ )
+
def _repo() -> str:
return (os.environ.get("UNSLOTH_SD_CPP_REPO") or DEFAULT_REPO).strip() or DEFAULT_REPO
@@ -59,6 +121,23 @@ def _pinned_tag() -> Optional[str]:
return val or None
+# A mirror release built on top of an upstream one carries a "-u<short sha>" suffix naming the
+# fork commit (master-813-bfbef5b-u13b9d92 is upstream master-813-bfbef5b plus fork commit 13b9d92).
+_MIRROR_TAG_SUFFIX = re.compile(r"-u[0-9a-f]{7,}$")
+
+
+def upstream_tag_for(tag: Optional[str]) -> Optional[str]:
+ """The upstream release ``tag`` was built from: the same tag with the mirror's fork suffix
+ dropped, or ``tag`` unchanged when it carries none.
+
+ Without this, pinning a fork-only tag silently costs every host the mirror does not build
+ (Linux Vulkan/ROCm, Windows GPU) its pinned install: the exact string 404s upstream and the
+ fallback settles for upstream *latest*, which is any build published since."""
+ if not tag:
+ return tag
+ return _MIRROR_TAG_SUFFIX.sub("", tag) or tag
+
+
# accelerator -> the token that must appear in a Linux/Windows asset name.
_LINUX_ACCEL_TOKEN = {"rocm": "rocm", "vulkan": "vulkan"}
_WINDOWS_ACCEL_TOKEN = {
@@ -225,6 +304,34 @@ 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())
+
+
+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 _locate_sd_server(root: Path) -> Optional[Path]:
"""The persistent ``sd-server`` binary in the extracted tree, if the archive ships
one (modern stable-diffusion.cpp releases do). Best-effort: the native backend
@@ -347,7 +454,10 @@ def _resolve_with_fallback(
if tag:
attempts.append((primary, tag, False))
if allow_upstream:
- attempts.append((UPSTREAM_FALLBACK_REPO, tag, False))
+ # The mirror's own tag does not exist upstream, so the pin has to be translated back
+ # to the upstream release it was built from -- otherwise this attempt always 404s and
+ # the pin degrades to upstream latest for every host the mirror does not build.
+ attempts.append((UPSTREAM_FALLBACK_REPO, upstream_tag_for(tag), False))
attempts.append((primary, None, True))
if allow_upstream:
attempts.append((UPSTREAM_FALLBACK_REPO, None, True))
@@ -434,7 +544,14 @@ 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)
_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.
_maybe_fetch_windows_cudart(release, chosen, target)
finally:
@@ -452,6 +569,16 @@ def install(
_make_executable(sd_server)
if sd_server is not None:
print(f"installed sd-server -> {sd_server}", flush = True)
+ # 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.
+ if _may_own:
+ _write_install_record(
+ target,
+ accelerator = accelerator,
+ repo = used_repo,
+ tag = release.get("tag_name"),
+ )
# The ownership marker was written before extraction, so a crashed partial install is still recognised as ours.
return sd_cli