Skip to content

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

Studio: install the pinned Diffusers build on startup when an old installer skipped it (#11579)

oobabooga55b6b07da0d6
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index b08ae0ab9a8..fb7b815bc65 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -1376,6 +1376,17 @@ def _too_old_message(pipeline_class: str, family_name: str, installed: str) -> s
f"diffusers {installed}. Upgrade with: pip install -U diffusers."
)
if minimum in _UNRELEASED_MIN_DIFFUSERS:
+ try:
+ from utils.diffusers_repair import diffusers_repair_installed
+ installed_since = diffusers_repair_installed()
+ except Exception: # noqa: BLE001 - no self-heal module is no repair
+ installed_since = False
+ if installed_since:
+ return (
+ f"'{family_name}' needs diffusers >= {minimum} ({pipeline_class}). Unsloth has just "
+ f"installed it, but this session already loaded diffusers {installed}. Restart "
+ "Unsloth Studio to use it."
+ )
remedy = _diffusers_main_archive_remedy()
return (
f"'{family_name}' needs diffusers >= {minimum} ({pipeline_class}), which has not been "
@@ -1460,6 +1471,16 @@ def assert_pipeline_class_available(
except Exception: # noqa: BLE001, S110 - optimisation only, and this module has no logger
pass
+ if "diffusers" not in sys.modules:
+ try:
+ from utils.diffusers_repair import IN_FLIGHT_MESSAGE, diffusers_repair_in_flight
+ repairing = diffusers_repair_in_flight()
+ except Exception: # noqa: BLE001 - no self-heal module is no repair
+ repairing = False
+ # Importing now would read files the install is replacing, and pin the release for the session.
+ if repairing:
+ raise ValueError(IN_FLIGHT_MESSAGE)
+
try:
import diffusers
present = hasattr(diffusers, pipeline_class)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 997a7991583..c515d60e150 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -662,7 +662,11 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
if _post_warm_retired(generation):
return
try:
- prewarm_diffusers_if_image_models_exist()
+ from utils.diffusers_repair import diffusers_repair_in_flight
+
+ # Importing the release now would pin it in this process for the whole session.
+ if not diffusers_repair_in_flight():
+ prewarm_diffusers_if_image_models_exist()
except Exception as _prewarm_exc: # noqa: BLE001 -- latency work must never end the worker
import structlog as _structlog
_structlog.get_logger(__name__).debug("diffusers prewarm skipped: %s", _prewarm_exc)
@@ -878,6 +882,14 @@ async def lifespan(app: FastAPI):
+ "\n"
)
+ # Before the socket binds, or a first diffusion load can import the release the repair is replacing.
+ # A metadata read and a thread start; the install itself runs on that thread.
+ try:
+ from utils.diffusers_repair import start_diffusers_autorepair_if_needed
+ start_diffusers_autorepair_if_needed()
+ except Exception as _diffusers_exc: # noqa: BLE001 -- a self-heal must never block startup
+ _lifespan_log.warning("diffusers autorepair skipped: %s", _diffusers_exc)
+
# Last, so it never contends for the GIL: the socket binds as soon as this returns, so the login
# screen is up while torch/transformers/datasets load.
start_background_warm()
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 0f27a617733..f20fbbd52df 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -14220,6 +14220,11 @@ async def _preflight_native_audio_placement(
"Load a merged checkpoint instead."
),
)
+ if audio_type == "minimax_music3":
+ # Its worker imports diffusers, and cannot see this process's repair.
+ from utils.diffusers_repair import IN_FLIGHT_MESSAGE, diffusers_repair_in_flight
+ if diffusers_repair_in_flight():
+ raise HTTPException(status_code = 400, detail = IN_FLIGHT_MESSAGE)
if audio_type in ("higgs_tts2", "higgs_tts3") and sys.version_info < (3, 10):
raise HTTPException(
status_code = 400,
diff --git a/studio/backend/tests/test_diffusers_repair.py b/studio/backend/tests/test_diffusers_repair.py
new file mode 100644
index 00000000000..50817d1ffdd
--- /dev/null
+++ b/studio/backend/tests/test_diffusers_repair.py
@@ -0,0 +1,290 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Diffusers self-heal: an install updated by an installer without the Diffusers main step gets the
+pinned build from the backend on its next start, instead of needing a second update."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import utils.diffusers_repair as dr # noqa: E402
+
+_REAL_PEER_HOLDS_PASS = dr._peer_holds_pass
+
+
+class _Dist:
+ def __init__(self, direct_url):
+ self._direct_url = direct_url
+
+ def read_text(self, name):
+ if name != "direct_url.json" or self._direct_url is None:
+ return None
+ return json.dumps(self._direct_url)
+
+
[email protected](autouse = True)
+def _reset(monkeypatch):
+ monkeypatch.setattr(dr, "_thread", None)
+ monkeypatch.setattr(dr, "_installed", False)
+ monkeypatch.delenv(dr.DISABLE_ENV_VAR, raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSERS_MAIN", raising = False)
+ monkeypatch.setattr(dr, "_peer_holds_pass", lambda: False)
+
+
+def _installed_diffusers(monkeypatch, direct_url):
+ import importlib.metadata
+ monkeypatch.setattr(importlib.metadata, "distribution", lambda name: _Dist(direct_url))
+
+
+ "direct_url, expected",
+ [
+ (None, True), # a PyPI wheel records no direct_url.json
+ # A local checkout, editable or not, is the user's own build.
+ ({"url": "file:///src/diffusers", "dir_info": {"editable": True}}, False),
+ ({"url": "https://github.com/huggingface/diffusers", "vcs_info": {"vcs": "git"}}, False),
+ (
+ {"url": "https://github.com/huggingface/diffusers/archive/x.zip", "archive_info": {}},
+ False,
+ ),
+ ],
+)
+def test_only_an_index_release_is_a_candidate(monkeypatch, direct_url, expected):
+ _installed_diffusers(monkeypatch, direct_url)
+ assert dr._diffusers_is_an_index_install() is expected
+
+
+class _Proc:
+ """A finished installer, for the Popen the repair starts."""
+
+ def __init__(
+ self,
+ returncode,
+ wait = None,
+ ):
+ self.pid, self.returncode, self._wait = 0, returncode, wait
+
+ def communicate(self, timeout = None):
+ if self._wait is not None:
+ self._wait.wait(5)
+ return "", None
+
+ def poll(self):
+ return self.returncode
+
+
+def test_a_release_install_starts_one_repair_and_records_success(monkeypatch):
+ _installed_diffusers(monkeypatch, None)
+ calls = []
+ release = threading.Event()
+
+ def fake_popen(argv, **kwargs):
+ calls.append((argv, kwargs["env"]))
+ return _Proc(dr._INSTALLED, wait = release)
+
+ monkeypatch.setattr(dr.subprocess, "Popen", fake_popen)
+ assert dr.start_diffusers_autorepair_if_needed() is True
+ assert dr.diffusers_repair_in_flight() is True
+ assert dr.start_diffusers_autorepair_if_needed() is False, "at most once per process"
+ release.set()
+ dr._thread.join(5)
+ assert dr.diffusers_repair_in_flight() is False
+ assert dr.diffusers_repair_installed() is True
+ argv, env = calls[0]
+ assert argv == [sys.executable, str(dr._INSTALLER), "--repair-diffusers-main"]
+ assert env["VIRTUAL_ENV"] == sys.prefix
+
+
+def test_nothing_to_do_and_failure_do_not_report_an_install(monkeypatch):
+ _installed_diffusers(monkeypatch, None)
+ for code in (dr._NOTHING_TO_DO, 2):
+ monkeypatch.setattr(dr, "_thread", None)
+ monkeypatch.setattr(dr.subprocess, "Popen", lambda argv, code = code, **kw: _Proc(code))
+ assert dr.start_diffusers_autorepair_if_needed() is True
+ dr._thread.join(5)
+ assert dr.diffusers_repair_installed() is False
+
+
[email protected](sys.platform == "win32", reason = "POSIX process tree")
+def test_a_timed_out_repair_stops_the_installers_children_too(monkeypatch, tmp_path):
+ """uv, not the installer, rewrites diffusers, so killing only the installer on timeout would
+ reopen the load gate while the files are still being replaced."""
+ from utils.process_lifetime import _pid_alive, _pid_is_zombie
+
+ pid_file = tmp_path / "child.pid"
+ installer = tmp_path / "installer.py"
+ installer.write_text(
+ "import pathlib, subprocess, sys, time\n"
+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"
+ f"pathlib.Path({str(pid_file)!r}).write_text(str(child.pid))\n"
+ "time.sleep(60)\n",
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(dr, "_INSTALLER", installer)
+ monkeypatch.setattr(dr, "_REPAIR_TIMEOUT_S", 3)
+ waited = []
+ monkeypatch.setattr(dr, "_wait_for_peer_pass", lambda: waited.append(True))
+ dr._run_repair()
+ assert waited == [True], "a timed-out repair must hold the gate for a peer still in the pass"
+ child = int(pid_file.read_text())
+ for _ in range(50):
+ if not _pid_alive(child) or _pid_is_zombie(child):
+ break
+ time.sleep(0.1)
+ else:
+ os.kill(child, 9)
+ pytest.fail("the installer's child outlived the timed-out repair")
+ assert dr.diffusers_repair_installed() is False
+
+
+def _peer_pass(monkeypatch, *uncontended):
+ import contextlib
+ import types
+
+ monkeypatch.setattr(dr, "_peer_holds_pass", _REAL_PEER_HOLDS_PASS)
+ held = iter(uncontended)
+ fake = types.SimpleNamespace(pass_lock = lambda: contextlib.nullcontext(next(held)))
+ monkeypatch.setitem(sys.modules, "studio.install_manifest", fake)
+
+
+def test_the_gate_waits_for_a_peer_to_leave_the_pass(monkeypatch):
+ """The repair's installer may have been waiting behind a sibling's repair or an update when it
+ timed out; that peer can still be rewriting diffusers."""
+ _peer_pass(monkeypatch, False, False, True)
+ polls = []
+ monkeypatch.setattr(dr.time, "sleep", lambda seconds: polls.append(seconds))
+ dr._wait_for_peer_pass()
+ assert polls == [dr._PEER_POLL_S] * 2
+
+
+def test_a_start_during_a_peers_pass_waits_it_out(monkeypatch):
+ """A peer swapping diffusers can have removed its metadata, which reads as no index release."""
+ _peer_pass(monkeypatch, False)
+ _installed_diffusers(
+ monkeypatch, {"url": "https://github.com/huggingface/diffusers", "vcs_info": {}}
+ )
+ started = []
+ monkeypatch.setattr(dr.subprocess, "Popen", lambda argv, **kw: started.append(argv) or _Proc(1))
+ assert dr.start_diffusers_autorepair_if_needed() is True
+ dr._thread.join(5)
+ assert started and started[0][-1] == "--repair-diffusers-main"
+
+
+ "env",
+ [{dr.DISABLE_ENV_VAR: "1"}, {"UNSLOTH_DIFFUSERS_MAIN": "0"}, {"UNSLOTH_DIFFUSERS_MAIN": "off"}],
+)
+def test_opt_outs_start_nothing(monkeypatch, env):
+ _installed_diffusers(monkeypatch, None)
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+ monkeypatch.setattr(dr.subprocess, "Popen", lambda *a, **k: pytest.fail("started a repair"))
+ assert dr.start_diffusers_autorepair_if_needed() is False
+
+
+def test_the_pinned_build_starts_nothing(monkeypatch):
+ _installed_diffusers(
+ monkeypatch, {"url": "https://github.com/huggingface/diffusers", "vcs_info": {}}
+ )
+ monkeypatch.setattr(dr.subprocess, "Popen", lambda *a, **k: pytest.fail("started a repair"))
+ assert dr.start_diffusers_autorepair_if_needed() is False
+
+
+def test_secrets_and_index_redirects_stay_out_of_the_installer_env(monkeypatch):
+ monkeypatch.setenv("HF_TOKEN", "secret")
+ monkeypatch.setenv("UV_INDEX_URL", "https://evil.example/simple")
+ monkeypatch.setenv("UNSLOTH_DIFFUSERS_MAIN", "1")
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ env = dr._repair_env()
+ assert "HF_TOKEN" not in env and "UV_INDEX_URL" not in env
+ assert env["UNSLOTH_DIFFUSERS_MAIN"] == "1"
+ assert env["UV_OFFLINE"] == "1", "an offline install must not reach GitHub from the repair"
+
+
+def test_the_load_gate_waits_for_a_running_repair(monkeypatch):
+ """Importing diffusers mid-install reads half-replaced files and pins the release for the
+ session, so a load during the repair is refused with a retry message instead."""
+ from core.inference import diffusion_families as fam
+
+ monkeypatch.setattr(dr, "diffusers_repair_in_flight", lambda: True)
+ monkeypatch.delitem(sys.modules, "diffusers", raising = False)
+ with pytest.raises(ValueError, match = "installing the pinned diffusers build"):
+ fam.assert_pipeline_class_available("QwenImage21Pipeline", "qwen-image-2.1")
+
+
+def test_minimax_music3_is_refused_before_eviction_while_the_repair_runs(monkeypatch):
+ """Its worker is a separate process that imports diffusers and never sees this one's repair."""
+ import asyncio
+ import types
+
+ from fastapi import HTTPException
+
+ import routes.inference as ri
+
+ monkeypatch.setattr(dr, "diffusers_repair_in_flight", lambda: True)
+ config = types.SimpleNamespace(audio_type = "minimax_music3", is_lora = False, identifier = "x/y")
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(
+ ri._preflight_native_audio_placement(
+ config,
+ types.SimpleNamespace(audio_device = None),
+ types.SimpleNamespace(requested_gpu_ids = None),
+ )
+ )
+ assert excinfo.value.status_code == 400
+ assert excinfo.value.detail == dr.IN_FLIGHT_MESSAGE
+
+
+def test_the_repair_is_decided_before_the_socket_binds():
+ """The lifespan yields, and the server accepts requests, before the post-warm thread runs, so a
+ repair started there leaves a window where a load imports the release being replaced. Checked on
+ the source because running the real lifespan brings up the whole backend."""
+ import ast
+
+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))
+ functions = {
+ node.name: node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+ def first_call(function, name):
+ lines = [
+ node.lineno
+ for node in ast.walk(function)
+ if isinstance(node, ast.Call) and getattr(node.func, "id", None) == name
+ ]
+ return min(lines) if lines else None
+
+ lifespan = functions["lifespan"]
+ start = first_call(lifespan, "start_diffusers_autorepair_if_needed")
+ assert start is not None
+ assert start < first_call(lifespan, "_start_post_warm_thread")
+ assert start < min(n.lineno for n in ast.walk(lifespan) if isinstance(n, ast.Yield))
+ post_warm = functions["_post_warm_background_work"]
+ assert first_call(post_warm, "start_diffusers_autorepair_if_needed") is None
+
+
+def test_a_finished_repair_behind_a_loaded_release_asks_for_a_restart(monkeypatch):
+ from core.inference import diffusion_families as fam
+
+ monkeypatch.setattr(dr, "_installed", True)
+ message = fam._too_old_message("QwenImage21Pipeline", "qwen-image-2.1", "0.40.0")
+ assert "Restart Unsloth Studio" in message
+
+
+def test_the_installer_exposes_the_repair_flag():
+ source = dr._INSTALLER.read_text(encoding = "utf-8")
+ assert '["--repair-diffusers-main"]' in source
diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.py
index d64f0534060..8d896ec1820 100644
--- a/studio/backend/tests/test_orchestrator_unload_cancel.py
+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py
@@ -3450,6 +3450,7 @@ def test_every_long_lived_spawner_consults_the_shutdown_latch():
"core/inference/stt_download_worker.py",
"core/inference/tools.py",
"core/training/diffusion_training_service.py",
+ "utils/diffusers_repair.py",
"utils/prebuilt/update_flow.py",
"utils/process_lifetime.py",
"utils/torch_device_probe.py",
diff --git a/studio/backend/utils/diffusers_repair.py b/studio/backend/utils/diffusers_repair.py
new file mode 100644
index 00000000000..1b04c779c6d
--- /dev/null
+++ b/studio/backend/utils/diffusers_repair.py
@@ -0,0 +1,225 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Startup self-heal for the pinned Diffusers main build.
+
+An update from a release that predates the installer's Diffusers main step runs that release's
+installer, so the build never goes in and Qwen-Image-2.1 refuses to load until a second update. The
+backend is the first new code such a host runs, so it runs the installer's own step here, on a
+background thread (git, or the zip route without git). Opt out with
+UNSLOTH_DISABLE_DIFFUSERS_AUTOREPAIR=1.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Optional
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+DISABLE_ENV_VAR = "UNSLOTH_DISABLE_DIFFUSERS_AUTOREPAIR"
+_STUDIO_DIR = Path(__file__).resolve().parents[2]
+_INSTALLER = _STUDIO_DIR / "install_python_stack.py"
+_MAIN_PIN = _STUDIO_DIR / "backend" / "requirements" / "diffusers-main.txt"
+_REPAIR_TIMEOUT_S = 900
+_PEER_POLL_S = 5
+# The installer's exit codes for --repair-diffusers-main.
+_INSTALLED, _NOTHING_TO_DO = 0, 1
+
+# Unattended, so secrets and index redirects stay out, as in mlx_repair. The Windows names are what
+# Python, git and uv need to start at all there; UV_OFFLINE is the operator's no-network switch.
+_ENV_ALLOWLIST = frozenset(
+ {
+ "PATH",
+ "HOME",
+ "USER",
+ "LOGNAME",
+ "TMPDIR",
+ "TMP",
+ "TEMP",
+ "LANG",
+ "LC_ALL",
+ "LC_CTYPE",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "NO_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "no_proxy",
+ "all_proxy",
+ "SSL_CERT_FILE",
+ "SSL_CERT_DIR",
+ "REQUESTS_CA_BUNDLE",
+ "CURL_CA_BUNDLE",
+ "UV_SYSTEM_CERTS",
+ "UV_NATIVE_TLS",
+ "UV_OFFLINE",
+ "SYSTEMROOT",
+ "WINDIR",
+ "COMSPEC",
+ "PATHEXT",
+ "USERPROFILE",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "PROGRAMDATA",
+ "PROGRAMFILES",
+ "UNSLOTH_DIFFUSERS_MAIN",
+ }
+)
+
+_lock = threading.Lock()
+_thread: Optional[threading.Thread] = None
+_installed = False
+
+
+def _opted_out() -> bool:
+ if os.environ.get(DISABLE_ENV_VAR) == "1":
+ return True
+ value = (os.environ.get("UNSLOTH_DIFFUSERS_MAIN") or "").strip().lower()
+ return value in ("0", "false", "no", "off")
+
+
+def _diffusers_is_an_index_install() -> bool:
+ """True when diffusers came from an index, the only state the repair acts on.
+
+ Read from metadata, so the common healthy boot spawns nothing: the pinned build is a direct
+ reference (git or zip) and records one in direct_url.json.
+ """
+ try:
+ from importlib.metadata import distribution
+ dist = distribution("diffusers")
+ except Exception: # noqa: BLE001 - no diffusers at all is the installer's job, not this one
+ return False
+ try:
+ payload = json.loads(dist.read_text("direct_url.json") or "{}")
+ except (ValueError, OSError):
+ payload = {}
+ if not isinstance(payload, dict):
+ return True
+ # dir_info is a local checkout, `pip install -e` included: the user's, not ours to replace.
+ return not ("vcs_info" in payload or "archive_info" in payload or "dir_info" in payload)
+
+
+def _repair_env() -> dict[str, str]:
+ env = {key: os.environ[key] for key in _ENV_ALLOWLIST if key in os.environ}
+ env["VIRTUAL_ENV"] = sys.prefix
+ try:
+ from utils.mlx_repair import _uv_executable
+ uv = _uv_executable()
+ except Exception: # noqa: BLE001 - without uv the installer falls back to pip
+ uv = None
+ # A GUI launch starts with a minimal PATH, and the installer looks uv up there.
+ if uv:
+ env["PATH"] = os.pathsep.join(filter(None, (str(Path(uv).parent), env.get("PATH"))))
+ return env
+
+
+def _peer_holds_pass() -> bool:
+ """Whether another process (a sibling's repair, an update) is inside the dependency pass."""
+ try:
+ from studio.install_manifest import pass_lock
+ except Exception: # noqa: BLE001 - no lock to read is no peer to wait for
+ return False
+ with pass_lock() as uncontended:
+ return not uncontended
+
+
+def _wait_for_peer_pass() -> None:
+ """Hold the gate until no process holds the dependency pass. Killing our installer released it,
+ but the pass it was waiting behind may still be writing."""
+ while _peer_holds_pass():
+ time.sleep(_PEER_POLL_S)
+
+
+def _run_repair() -> None:
+ global _installed
+ from utils.child_stdio import utf8_child_env
+ from utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pid, terminate_pid
+
+ kwargs = child_popen_kwargs()
+ if os.name == "nt":
+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ try:
+ proc = subprocess.Popen(
+ [sys.executable, str(_INSTALLER), "--repair-diffusers-main"],
+ env = utf8_child_env(_repair_env()),
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ **kwargs,
+ )
+ except OSError as exc:
+ logger.warning("diffusers self-heal could not start the installer: %s", exc)
+ return
+ # Tracked, so a backend that exits mid-install takes the installer and its uv/git children down.
+ adopt_pid(proc.pid)
+ try:
+ output, _ = proc.communicate(timeout = _REPAIR_TIMEOUT_S)
+ except subprocess.TimeoutExpired:
+ # The whole tree, before the gate reopens: uv keeps rewriting diffusers after its parent dies.
+ terminate_pid(proc.pid, owner_verified = True)
+ proc.kill()
+ proc.wait()
+ logger.warning("diffusers self-heal timed out after %ss", _REPAIR_TIMEOUT_S)
+ _wait_for_peer_pass()
+ return
+ finally:
+ if proc.poll() is not None:
+ forget_pid(proc.pid)
+ if proc.returncode == _INSTALLED:
+ _installed = True
+ logger.info("diffusers self-heal installed the pinned Diffusers main build")
+ elif proc.returncode != _NOTHING_TO_DO:
+ logger.warning(
+ "diffusers self-heal could not install the pinned build; run `unsloth studio "
+ "update` to retry. Installer output:\n%s",
+ (output or "")[-4000:],
+ )
+
+
+def start_diffusers_autorepair_if_needed() -> bool:
+ """Start the background install when diffusers is an index release and the pin wants main.
+ True iff a repair thread was started; at most once per process."""
+ global _thread
+ if _opted_out() or not _MAIN_PIN.is_file() or not _INSTALLER.is_file():
+ return False
+ # A peer mid-install can have removed the metadata, so its pass also starts the installer, which
+ # waits the pass out and keeps loads refused meanwhile.
+ if not _diffusers_is_an_index_install() and not _peer_holds_pass():
+ return False
+ with _lock:
+ if _thread is not None:
+ return False
+ _thread = threading.Thread(target = _run_repair, daemon = True, name = "diffusers-autorepair")
+ _thread.start()
+ logger.info(
+ "checking for the pinned Diffusers main build in the background. Set %s=1 to disable.",
+ DISABLE_ENV_VAR,
+ )
+ return True
+
+
+IN_FLIGHT_MESSAGE = (
+ "Unsloth is installing the pinned diffusers build in the background, which takes a few "
+ "minutes on the first start after an update. Try again shortly."
+)
+
+
+def diffusers_repair_in_flight() -> bool:
+ thread = _thread
+ return thread is not None and thread.is_alive()
+
+
+def diffusers_repair_installed() -> bool:
+ return _installed
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 62871cf1c92..aada7778eb1 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -10644,6 +10644,53 @@ def _diffusers_main_needs_dependency_pass() -> bool:
return last != "failed"
+# The backend's startup repair records its failure here, read by the repair alone so an explicit
+# update still retries; that pass rewrites the manifest without it.
+_DIFFUSERS_MAIN_REPAIR_KEY = "diffusers_main_repair"
+
+
+def _startup_repair_failed() -> bool:
+ try:
+ return (install_manifest.read_manifest() or {}).get(_DIFFUSERS_MAIN_REPAIR_KEY) == "failed"
+ except Exception: # noqa: BLE001 - an unreadable manifest is no record of a failed try
+ return False
+
+
+_REPAIR_LOCK_POLL_S = 5
+
+
+def _repair_diffusers_main() -> int:
+ """11c on its own, for the backend's startup self-heal: 0 installed, 1 nothing to do, 2 failed.
+
+ An update from a release that predates 11c runs that release's installer, which never installs
+ the build; the backend that starts afterwards is the first new code such a host runs.
+ """
+ import time
+
+ global USE_UV, _STEP, _TOTAL
+ while True:
+ with install_manifest.pass_lock() as uncontended:
+ # Every "nothing to do" answer waits for the lock too: until a sibling backend's repair or an
+ # update leaves the pass it may be rewriting diffusers, and returning would let the backend
+ # that started this import it.
+ if uncontended:
+ if (
+ not _diffusers_main_requested()
+ or not _diffusers_main_needs_dependency_pass()
+ or _startup_repair_failed()
+ ):
+ return 1
+ USE_UV = _bootstrap_uv()
+ _STEP, _TOTAL = 0, 1
+ _diffusers_main_step()
+ if _diffusers_main_resident():
+ return 0
+ # Or every start retries a fetch this host cannot make, refusing diffusion loads meanwhile.
+ install_manifest.update_manifest(**{_DIFFUSERS_MAIN_REPAIR_KEY: "failed"})
+ return 2
+ time.sleep(_REPAIR_LOCK_POLL_S)
+
+
def _diffusers_main_step() -> None:
"""Install the pinned Diffusers commit, or leave the release pin alone.
@@ -11929,6 +11976,8 @@ if __name__ == "__main__":
if sys.argv[1:] == ["--missing-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _missing_torch_needs_dependency_pass() else 1)
+ if sys.argv[1:] == ["--repair-diffusers-main"]:
+ sys.exit(_repair_diffusers_main())
if sys.argv[1:] == ["--diffusers-main-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _diffusers_main_needs_dependency_pass() else 1)
diff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.py
index ea8217dcc84..e6c33b3413d 100644
--- a/tests/studio/install/test_diffusers_pin.py
+++ b/tests/studio/install/test_diffusers_pin.py
@@ -788,3 +788,105 @@ def test_the_probe_flag_answers_without_a_traceback():
)
assert result.returncode in (0, 1), result.stderr
assert "Traceback" not in result.stderr, result.stderr
+
+
+def _repair_module(
+ monkeypatch,
+ *,
+ needed,
+ resident_after,
+ uncontended = (True,),
+):
+ """``uncontended`` is read once per poll of the pass lock, ``needed`` once the lock is free."""
+ import contextlib
+
+ module = _probe_module("install_python_stack_repair_probe")
+ monkeypatch.delenv("UNSLOTH_DIFFUSERS_MAIN", raising = False)
+ needed, uncontended = iter(needed), iter(uncontended)
+ monkeypatch.setattr(module, "_diffusers_main_needs_dependency_pass", lambda: next(needed))
+ monkeypatch.setattr(module, "_bootstrap_uv", lambda: True)
+ monkeypatch.setattr(module, "_diffusers_main_resident", lambda *a, **k: resident_after)
+ monkeypatch.setattr(
+ module.install_manifest,
+ "pass_lock",
+ lambda *a, **k: contextlib.nullcontext(next(uncontended)),
+ )
+ monkeypatch.setattr(module, "_REPAIR_LOCK_POLL_S", 0)
+ recorded = []
+ monkeypatch.setattr(
+ module.install_manifest, "update_manifest", lambda **extra: recorded.append(extra)
+ )
+ module.recorded = recorded
+ module.lock_polls = lambda: len(polls)
+ polls = []
+ lock = module.install_manifest.pass_lock
+ monkeypatch.setattr(
+ module.install_manifest, "pass_lock", lambda *a, **k: polls.append(1) or lock()
+ )
+ ran = []
+ monkeypatch.setattr(module, "_diffusers_main_step", lambda: ran.append(True))
+ return module, ran
+
+
+def test_the_startup_repair_runs_only_the_main_step(monkeypatch):
+ """The backend's self-heal: 0 once the build is in, 2 when the step could not install it."""
+ module, ran = _repair_module(monkeypatch, needed = [True], resident_after = True)
+ assert module._repair_diffusers_main() == 0 and ran == [True]
+ assert module.recorded == []
+ module, ran = _repair_module(monkeypatch, needed = [True], resident_after = False)
+ assert module._repair_diffusers_main() == 2 and ran == [True]
+ assert module.recorded == [{module._DIFFUSERS_MAIN_REPAIR_KEY: "failed"}]
+
+
+def test_a_failed_startup_repair_stops_startup_retries_but_not_an_update(monkeypatch):
+ """Every start would otherwise refuse diffusion loads through another fetch this host cannot
+ make, while the update the backend's warning points at must still retry."""
+
+ def failed_repair(module):
+ monkeypatch.setattr(
+ module.install_manifest,
+ "read_manifest",
+ lambda *a, **k: {module._DIFFUSERS_MAIN_REPAIR_KEY: "failed"},
+ )
+
+ module, ran = _repair_module(monkeypatch, needed = [True], resident_after = False)
+ failed_repair(module)
+ assert module._repair_diffusers_main() == 1 and ran == []
+ probe = _fast_path_probe_module(monkeypatch, resident = False)
+ failed_repair(probe)
+ assert probe._diffusers_main_needs_dependency_pass() is True
+
+
+def test_the_startup_repair_leaves_a_healthy_install_alone(monkeypatch):
+ module, ran = _repair_module(monkeypatch, needed = [False], resident_after = True)
+ assert module._repair_diffusers_main() == 1 and ran == []
+
+
+def test_the_startup_repair_waits_out_a_peer_holding_the_pass(monkeypatch):
+ """Returning at once would let the backend that started it import diffusers while a sibling
+ backend's repair, or an update, is still replacing it."""
+ # The peer installed the build: nothing left to do once it lets go.
+ module, ran = _repair_module(
+ monkeypatch, needed = [False], resident_after = True, uncontended = [False, False, True]
+ )
+ assert module._repair_diffusers_main() == 1 and ran == []
+ assert module.lock_polls() == 3
+ # The peer's pass ended without the build: install it now.
+ module, ran = _repair_module(
+ monkeypatch, needed = [True], resident_after = True, uncontended = [False, True]
+ )
+ assert module._repair_diffusers_main() == 0 and ran == [True]
+
+
+def test_a_recorded_repair_failure_still_waits_for_a_peer(monkeypatch):
+ """An update retrying the failed build holds the pass while it rewrites diffusers."""
+ module, ran = _repair_module(
+ monkeypatch, needed = [True], resident_after = False, uncontended = [False, True]
+ )
+ monkeypatch.setattr(
+ module.install_manifest,
+ "read_manifest",
+ lambda *a, **k: {module._DIFFUSERS_MAIN_REPAIR_KEY: "failed"},
+ )
+ assert module._repair_diffusers_main() == 1 and ran == []
+ assert module.lock_polls() == 2