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.

Overturn a chat-only MLX verdict the stack contradicts (#9124)

yzxcj7977b54b42318a3
diff --git a/studio/backend/main.py b/studio/backend/main.py
index bdbad179ad0..0dc4038d950 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -606,7 +606,11 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
start_mlx_autorepair_if_needed()
except Exception as _mlx_exc:
import structlog as _structlog
- _structlog.get_logger(__name__).debug("mlx autorepair skipped: %s", _mlx_exc)
+
+ # Warning, not debug: this decides the MLX verdict on every healthy Apple Silicon
+ # boot, so a half-applied update (new mlx_repair.py over older hardware.py) arrives
+ # here and would silently leave Train/Export greyed out for the session.
+ _structlog.get_logger(__name__).warning("mlx autorepair skipped: %s", _mlx_exc)
if _post_warm_retired(generation):
return
diff --git a/studio/backend/tests/test_mlx_repair.py b/studio/backend/tests/test_mlx_repair.py
index 09d4977720e..7ee020a9601 100644
--- a/studio/backend/tests/test_mlx_repair.py
+++ b/studio/backend/tests/test_mlx_repair.py
@@ -1,14 +1,16 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""MLX self-heal: on Apple Silicon with MLX missing, reinstall it by name on a
-background thread (off the startup critical path). No-op elsewhere / when present
-/ when disabled. Models on core.training.worker's runtime backend self-heal.
+"""MLX self-heal: on Apple Silicon with MLX missing, reinstall it by name on a background
+thread (off the startup critical path). No-op elsewhere, but a present stack still overturns
+a chat-only verdict that contradicts it, even when the reinstall is disabled. Models on
+core.training.worker's runtime backend self-heal.
"""
from __future__ import annotations
import sys
+import threading
from pathlib import Path
import pytest
@@ -23,7 +25,20 @@ import utils.mlx_repair as mr # noqa: E402
@pytest.fixture(autouse = True)
def _reset_attempt_guard(monkeypatch):
monkeypatch.setattr(mr, "_attempted", False)
+ # Both halves, or a worker takes _run_repair_and_redetect's "install ran" branch on a
+ # latch an earlier test left set and re-detects for real against the next test.
+ monkeypatch.setattr(mr, "_environment_mutated", False)
monkeypatch.delenv(mr.DISABLE_ENV_VAR, raising = False)
+ yield
+ # Join inside the test's stubs: an outliving worker would run the real detect_hardware()
+ # against the next test's globals.
+ for thread in threading.enumerate():
+ if thread.name == "mlx-autorepair":
+ thread.join(timeout = 5)
+ assert not thread.is_alive(), (
+ "an mlx-autorepair worker outlived its test; once these stubs are "
+ "restored it runs the real repair and detection against another test"
+ )
def test_uv_cmd_targets_this_interpreter_with_mlx_packages(monkeypatch):
@@ -470,3 +485,221 @@ def test_an_unresolvable_interpreter_is_diagnosed_not_retried(monkeypatch, tmp_p
assert (
"--target" not in flat and "--prefix" not in flat
), f"a corrupting install target reached the uv command line: {flat}"
+
+
+# ── Overturning a verdict a first-import race left behind (issue #9120) ───────
+
+
+def _published_verdict(monkeypatch, *, chat_only: bool, reason):
+ """Settled means a device and a set event beside the reason (a chat-only Mac measured its
+ way to CPU, not to nothing), or a success check ignoring the verdict would pass. The state
+ is monkeypatched, so nothing leaks to the next test."""
+ import utils.hardware.hardware as hw
+
+ settled = threading.Event()
+ settled.set()
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU if chat_only else hw.DeviceType.MLX)
+ monkeypatch.setattr(hw, "CHAT_ONLY", chat_only)
+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", reason)
+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", settled)
+ monkeypatch.setattr(hw, "DETECTION_GENERATION", 0)
+
+ redetects = []
+
+ def _redetect():
+ redetects.append(1)
+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = hw.DeviceType.MLX, False, None
+ return hw.DEVICE
+
+ monkeypatch.setattr(hw, "_detect_hardware_locked", _redetect)
+ return redetects
+
+
+def _recorded_announcements(monkeypatch):
+ lines = []
+
+ class _Recorder:
+ def info(self, message, *args, **kwargs):
+ lines.append(message)
+
+ def __getattr__(self, _name):
+ return lambda *a, **k: None
+
+ monkeypatch.setattr(mr, "logger", _Recorder())
+ return lines
+
+
+def _join_the_repair_worker():
+ for thread in threading.enumerate():
+ if thread.name == "mlx-autorepair":
+ thread.join(timeout = 5)
+ assert not thread.is_alive()
+
+
+def test_a_stack_that_measures_usable_overturns_the_verdict(monkeypatch):
+ # The #9120 shape: chat-only cached from a race the warm has since finished importing.
+ import utils.hardware.hardware as hw
+
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: True)
+ redetects = _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+ announced = _recorded_announcements(monkeypatch)
+
+ assert mr.start_mlx_autorepair_if_needed() is False
+ assert len(redetects) == 1, "the verdict the stack contradicts was left published"
+ assert (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON) == (hw.DeviceType.MLX, False, None)
+ assert any("Train/Export are back" in line for line in announced)
+
+
+def test_a_stack_that_is_really_unusable_keeps_its_verdict(monkeypatch):
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: False)
+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_k: False)
+ redetects = _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+
+ assert mr.start_mlx_autorepair_if_needed() is True
+ _join_the_repair_worker()
+ assert redetects == []
+
+
+def test_a_settled_verdict_that_does_not_blame_mlx_is_left_alone(monkeypatch):
+ # Both were measured by something this cannot re-run.
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: True)
+
+ for chat_only, reason in ((True, "no_gpu"), (False, None)):
+ redetects = _published_verdict(monkeypatch, chat_only = chat_only, reason = reason)
+ assert mr.start_mlx_autorepair_if_needed() is False
+ assert redetects == [], f"re-detected over a {reason!r} verdict"
+
+
+def test_declining_the_reinstall_does_not_mean_keeping_a_wrong_verdict(monkeypatch):
+ # The opt-out declines changing the environment; re-detecting changes nothing on disk.
+ monkeypatch.setenv(mr.DISABLE_ENV_VAR, "1")
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: True)
+ redetects = _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+
+ assert mr.start_mlx_autorepair_if_needed() is False
+ assert len(redetects) == 1
+
+
[email protected]("usable", (True, False))
+def test_the_stack_is_measured_once_before_the_decision(monkeypatch, usable):
+ """Two would disagree with each other, not only with the verdict: "not usable" then
+ "usable" leaves it standing with no reinstall and nothing left to revisit it."""
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(mr, "attempt_mlx_repair", lambda **_k: False)
+ _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+ probes = []
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: probes.append(1) or usable)
+
+ mr.start_mlx_autorepair_if_needed()
+ _join_the_repair_worker()
+ assert probes == [1]
+
+
+def test_the_overturn_cannot_republish_into_a_stopped_lifespan(monkeypatch):
+ """detect_hardware() reads the current epoch when it owns none, so an unscoped re-detect
+ adopts the one shutdown moved to and publishes for a dead lifespan, which the next then
+ inherits instead of measuring for itself."""
+ import utils.hardware.hardware as hw
+
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+ settled = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON)
+
+ def _measure_while_shutdown_lands():
+ hw.invalidate_detection()
+ return True
+
+ monkeypatch.setattr(mr, "mlx_stack_available", _measure_while_shutdown_lands)
+
+ assert mr.start_mlx_autorepair_if_needed() is False
+ assert (
+ hw.DEVICE,
+ hw.CHAT_ONLY,
+ hw.CHAT_ONLY_REASON,
+ ) == settled, "a retired lifespan's re-detect was published"
+
+
+def test_a_redetect_that_publishes_nothing_is_not_announced(monkeypatch):
+ """Nothing is published either way, and #9120 was diagnosed entirely from these lines:
+ one claiming a recovery that did not happen is worse than silence."""
+ import utils.hardware.hardware as hw
+
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+ announced = _recorded_announcements(monkeypatch)
+
+ def _measure_while_shutdown_lands():
+ hw.invalidate_detection()
+ return True
+
+ monkeypatch.setattr(mr, "mlx_stack_available", _measure_while_shutdown_lands)
+
+ assert mr.start_mlx_autorepair_if_needed() is False
+ assert announced == [], f"announced an overturn that never published: {announced}"
+
+ # Retired mid-probe instead: the pass discards its healthy answer and leaves the reason
+ # cleared, which "no longer the MLX verdict" reads as a win.
+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = None, True, "mlx_unavailable"
+ hw.DETECTION_COMPLETE.set()
+
+ def _retired_under_the_probe():
+ hw.invalidate_detection()
+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = hw.DeviceType.MLX, False, None
+ return hw.DEVICE
+
+ monkeypatch.setattr(hw, "_detect_hardware_locked", _retired_under_the_probe)
+
+ assert hw.overturn_the_mlx_verdict(hw.current_detection_epoch()) is False
+ assert (hw.DEVICE, hw.CHAT_ONLY) == (None, True), "the discarded pass left state behind"
+
+ # And shutdown clears DEVICE, then the event, then the verdict, unlocked: a read between
+ # the first two sees a set event beside a device already gone.
+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = None, True, "mlx_unavailable"
+ hw.DETECTION_COMPLETE.set()
+
+ def _torn_by_a_concurrent_shutdown():
+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = None, False, None
+ hw.DETECTION_COMPLETE.set()
+ return None
+
+ monkeypatch.setattr(hw, "_detect_hardware_locked", _torn_by_a_concurrent_shutdown)
+
+ assert hw.overturn_the_mlx_verdict(hw.current_detection_epoch()) is False
+
+
+def test_an_opted_out_host_with_nothing_to_overturn_imports_nothing(monkeypatch):
+ """Under the warm's own kill switch join_background_warm() is a no-op, so detection has not
+ run and this would be the process's first MLX import, for a reinstall that is opted out."""
+ monkeypatch.setenv(mr.DISABLE_ENV_VAR, "1")
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ _published_verdict(monkeypatch, chat_only = True, reason = None)
+ monkeypatch.setattr(mr, "mlx_stack_available", lambda: pytest.fail("imported MLX for no one"))
+
+ assert mr.start_mlx_autorepair_if_needed() is False
+
+
+def test_the_repair_worker_is_scoped_to_the_epoch_read_before_the_measurement(monkeypatch):
+ """The measurement imports the MLX runtime, so shutdown can land inside it: reading the
+ epoch afterwards binds the repair to the one shutdown moved to."""
+ import utils.hardware.hardware as hw
+
+ monkeypatch.setattr(mr, "is_apple_silicon", lambda: True)
+ _published_verdict(monkeypatch, chat_only = True, reason = "mlx_unavailable")
+ before = hw.current_detection_epoch()
+
+ def _measure_while_shutdown_lands():
+ hw.invalidate_detection()
+ return False
+
+ monkeypatch.setattr(mr, "mlx_stack_available", _measure_while_shutdown_lands)
+ scoped_to = []
+ monkeypatch.setattr(mr, "_run_repair_and_redetect", lambda epoch = None: scoped_to.append(epoch))
+
+ assert mr.start_mlx_autorepair_if_needed() is True
+ _join_the_repair_worker()
+ assert scoped_to == [before]
+ assert hw.current_detection_epoch() != before, "the shutdown under test never happened"
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 0837b22fd39..3e95eae8793 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -362,6 +362,29 @@ def verdict_pending_mlx_repair(chat_only: bool, reason: Optional[str]) -> bool:
return False
+def verdict_blames_the_mlx_stack() -> bool:
+ """Unlocked deliberately: _DETECT_LOCK spans a whole detection pass, imports included, so
+ taking it would park the post-warm worker behind an early request's first import. The
+ overturn re-reads under the lock, so a straddling read costs one needless measurement."""
+ return bool(CHAT_ONLY) and CHAT_ONLY_REASON == "mlx_unavailable"
+
+
+def overturn_the_mlx_verdict(epoch: Optional[int] = None) -> bool:
+ """For a caller that has just measured the stack as usable.
+
+ Read and re-detect share one locked section, or a forced pass landing between them loses
+ its answer to this one. ``epoch`` predates the measurement, so a shutdown since discards
+ the pass instead of republishing for a dead lifespan. True is /api/health's three-part
+ settled read, not "a re-detect ran": callers announce it, and shutdown clears DEVICE
+ before the event and the verdict."""
+ with _DETECT_LOCK:
+ if not CHAT_ONLY or CHAT_ONLY_REASON != "mlx_unavailable":
+ return False
+ with owning_detection_epoch(epoch):
+ detect_hardware()
+ return DEVICE is not None and DETECTION_COMPLETE.is_set() and not CHAT_ONLY
+
+
def _print_cuda_device_list(is_rocm: bool) -> None:
"""List every visible CUDA/ROCm GPU with its index at startup.
diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.py
index 0b7da1bd1ae..bbbef8a0a2c 100644
--- a/studio/backend/utils/mlx_repair.py
+++ b/studio/backend/utils/mlx_repair.py
@@ -545,19 +545,38 @@ def _run_repair_and_redetect(epoch: Optional[int] = None) -> None:
def start_mlx_autorepair_if_needed() -> bool:
- """If this is an Apple Silicon host whose MLX stack is missing or too old,
- reinstall it on a daemon thread (off the startup critical path) and re-detect
- on success. Returns True iff a repair thread was started. No-op (returns False)
- off Apple Silicon, when the stack is already adequate, when already attempted
- this process, or when disabled via UNSLOTH_DISABLE_MLX_AUTOREPAIR=1."""
+ """If this is an Apple Silicon host whose MLX stack is missing or too old, reinstall it on
+ a daemon thread (off the startup critical path) and re-detect on success. True iff a repair
+ thread was started; False off Apple Silicon, when already attempted this process, or when
+ disabled via UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. An adequate stack starts no repair but still
+ overturns a verdict that contradicts it."""
global _attempted, _repair_thread, _repair_started_at
- if os.environ.get(DISABLE_ENV_VAR) == "1":
- return False
if not is_apple_silicon():
return False
+ from utils.hardware import hardware as _hw
+
+ # Opting out declines a reinstall, not a correct verdict, so the overturn still runs, but
+ # only when one waits on it: under the warm's kill switch it would be a first MLX import
+ # for no one.
+ opted_out = os.environ.get(DISABLE_ENV_VAR) == "1"
+ if opted_out and not _hw.verdict_blames_the_mlx_stack():
+ return False
+ # Read before the measurement, so a shutdown during it discards whatever is published on
+ # the strength of it. The repair worker shares this epoch rather than a later one.
+ epoch = _hw.current_detection_epoch()
if mlx_stack_available():
+ # Detection asks this as the warm's first stage, early enough to race another thread's
+ # first transformers import: CPython hands the loser a partially initialised module, so
+ # mlx_lm's chain raises on a healthy install (#9120). Usable here means the verdict was
+ # raced. Only the warm's is reachable; with the warm off, a later one stands unreconciled.
+ if _hw.overturn_the_mlx_verdict(epoch):
+ logger.info(
+ "MLX stack measures usable after the warm, against a chat-only verdict "
+ "from before it; re-detected. Train/Export are back (reload the page)."
+ )
+ return False
+ if opted_out:
return False
- from utils.hardware import hardware as _hw
with _attempted_lock:
if _attempted:
@@ -567,11 +586,9 @@ def start_mlx_autorepair_if_needed() -> bool:
# half-published: a reader landing between the two sees "attempted, nothing alive"
# and settles the very verdict this repair is about to overturn. The worker never
# takes this lock, so the start() handshake cannot deadlock against it.
- # The epoch is read here rather than in the thread: it may not run for a while, and
- # reading it there would bind the pass to a later shutdown.
_repair_thread = threading.Thread(
target = _run_repair_and_redetect,
- args = (_hw.current_detection_epoch(),),
+ args = (epoch,),
daemon = True,
name = "mlx-autorepair",
)