Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: hold the Mac capability verdict while an MLX repair can still overturn it (#8152)
Daniel Han7103733d7b86
diff --git a/.github/scripts/boot-studio-api-only.sh b/.github/scripts/boot-studio-api-only.shindex ffffd2dd7a7..f052bd911af 100755--- a/.github/scripts/boot-studio-api-only.sh+++ b/.github/scripts/boot-studio-api-only.sh@@ -2,11 +2,23 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.#-# Wipe Studio's auth state and boot `unsloth studio` in API-only mode in the-# background, exporting the pid so a later step can stop it.+# Wipe Studio's auth state and boot `unsloth studio` in the background, exporting+# the pid so a later step can stop it.## Usage:# boot-studio-api-only.sh --port 18888 [--log logs/studio.log] [--pid-var STUDIO_PID]+# [--api-only]+#+# On the name, and on --api-only being a flag rather than the default. The+# UNSLOTH_API_ONLY=1 below reads like the switch and is not: nothing in unsloth_cli+# takes it as input. Whether the web UI is served is decided by the CLI's --api-only+# flag alone, and the backend only ever reads that variable back out (main.py, to pick+# a CORS profile) after run.py has set it from the flag. So every caller here has in+# fact been booting a server that serves the frontend, and the Playwright UI smokes+# depend on exactly that -- passing --api-only unconditionally would leave them+# driving a browser at a backend with no UI. Hence opt-in: callers with no built+# `studio/frontend/dist` (mlx-ci.yml boots on a bare pip install) must ask for it, or+# the server prints "Unsloth frontend build not found" and exits before it binds.## Twenty steps across eight workflows ran this same five-line body, varying only# in those three values. Extracted so the three easy-to-get-wrong parts have one@@ -36,12 +48,14 @@ set -uo pipefailPORT=""LOG="logs/studio.log"PID_VAR="STUDIO_PID"+API_ONLY=""while [ "$#" -gt 0 ]; docase "$1" in- --port) PORT="$2"; shift 2 ;;- --log) LOG="$2"; shift 2 ;;- --pid-var) PID_VAR="$2"; shift 2 ;;+ --port) PORT="$2"; shift 2 ;;+ --log) LOG="$2"; shift 2 ;;+ --pid-var) PID_VAR="$2"; shift 2 ;;+ --api-only) API_ONLY="--api-only"; shift ;;*) echo "boot-studio-api-only.sh: unknown arg '$1'" >&2; exit 2 ;;esacdone@@ -53,10 +67,11 @@ donerm -rf ~/.unsloth/studio/authmkdir -p "$(dirname "$LOG")"-UNSLOTH_API_ONLY=1 unsloth studio -H 127.0.0.1 -p "$PORT" > "$LOG" 2>&1 &+# shellcheck disable=SC2086 # $API_ONLY is one flag or empty, and must not become ''+UNSLOTH_API_ONLY=1 unsloth studio -H 127.0.0.1 -p "$PORT" $API_ONLY > "$LOG" 2>&1 &SERVER_PID=$!-echo "[boot] unsloth studio --api-only on 127.0.0.1:${PORT}, pid ${SERVER_PID}, log ${LOG}"+echo "[boot] unsloth studio ${API_ONLY:---with-frontend} on 127.0.0.1:${PORT}, pid ${SERVER_PID}, log ${LOG}"if [ -n "${GITHUB_ENV:-}" ]; thenecho "${PID_VAR}=${SERVER_PID}" >> "$GITHUB_ENV"elsediff --git a/.github/workflows/mlx-ci.yml b/.github/workflows/mlx-ci.ymlindex 3ae34672220..6c1bab66fb1 100644--- a/.github/workflows/mlx-ci.yml+++ b/.github/workflows/mlx-ci.yml@@ -28,7 +28,18 @@# environment (the test fixture installs a MetaPathFinder that# blocks `import mlx.core` for "no-mlx" profiles, faithfully# simulating a Mac without mlx even when mlx IS installed).-# 4. End-to-end MLX training + inference smoke test:+# 4. The Mac capability verdict /api/health publishes. Whether+# the sidebar's Train and Video rows are enabled, greyed out+# behind "Training needs MLX", or still spinning is decided by+# that one reply, and the decision reads a real `import+# mlx.core` and a real background reinstall. The unit tests+# drive it with a fake clock and a stand-in worker; only here+# is the host Apple Silicon and the MLX stack genuinely+# present or genuinely absent. mac_capability_verdict_smoke.py+# boots the server and judges every reply from the first one,+# because the reported bug was a verdict that was wrong for a+# while and right afterwards.+# 5. End-to-end MLX training + inference smoke test:# run_real_mlx_smoke.py trains unsloth/gemma-3-270m-it for 7# deterministic LoRA steps on a single repeated text row, then# verifies the trained model can complete the prompt and that@@ -68,6 +79,13 @@ on:- 'studio/backend/utils/hardware/**'- 'studio/backend/core/training/worker.py'- 'studio/backend/core/inference/mlx_inference.py'+ # The capability verdict is decided across these three: hardware/** measures it,+ # mlx_repair.py says whether a self-heal can still overturn it, and main.py holds+ # it back while one can. main.py is the studio's front door and is edited often,+ # so listing it does cost macOS slots on PRs that never touch the verdict -- but a+ # gate that cannot be triggered by the file the logic lives in is not a gate.+ - 'studio/backend/main.py'+ - 'studio/backend/utils/mlx_repair.py'# test_hardware_dispatch_matrix.py and test_is_mlx_dispatch_gate.py are# deliberately absent: this workflow no longer runs them (see the AST# contract step below), so booting a macOS runner when only those files@@ -76,7 +94,12 @@ on:# already triggers on them.- 'tests/studio/test_mlx_training_worker_behaviors.py'- 'tests/studio/run_real_mlx_smoke.py'+ - 'tests/studio/mac_capability_verdict_smoke.py'- 'tests/conftest.py'+ # Every capability-verdict boot below shells out to these two, so an edit to+ # either changes what this workflow actually runs.+ - '.github/scripts/boot-studio-api-only.sh'+ - '.github/scripts/wait-for-health.sh'- '.github/workflows/mlx-ci.yml'push:branches: [main]@@ -86,9 +109,14 @@ on:- 'studio/backend/utils/hardware/**'- 'studio/backend/core/training/worker.py'- 'studio/backend/core/inference/mlx_inference.py'+ - 'studio/backend/main.py'+ - 'studio/backend/utils/mlx_repair.py'- 'tests/studio/test_mlx_training_worker_behaviors.py'- 'tests/studio/run_real_mlx_smoke.py'+ - 'tests/studio/mac_capability_verdict_smoke.py'- 'tests/conftest.py'+ - '.github/scripts/boot-studio-api-only.sh'+ - '.github/scripts/wait-for-health.sh'- '.github/workflows/mlx-ci.yml'concurrency:@@ -106,10 +134,14 @@ jobs:dispatch:name: dispatchruns-on: macos-15- # 25 min: dispatch + spoofed matrix + 7-step real LoRA training is+ # 40 min: dispatch + spoofed matrix + 7-step real LoRA training is# under 2 min; GGUF export builds llama.cpp via cmake on Apple- # Silicon (~5-7 min), so we budget headroom.- timeout-minutes: 25+ # Silicon (~5-7 min), so we budget headroom. The capability-verdict+ # boots add roughly ten more: two settle in seconds, but the in-flight+ # one has to wait out the whole torch warm before the self-heal is even+ # scheduled, and then the length of the install it is holding a verdict+ # against.+ timeout-minutes: 40steps:# harden-runner v2.20.0 supports blocking mode on GitHub-hosted macOS# runners. Keep this job in audit while its egress destinations are@@ -342,6 +374,82 @@ jobs:echodone+ # ---------------------------------------------------------------+ # The Mac capability verdict, on a real Apple Silicon host.+ #+ # /api/health is what decides whether the sidebar's Train and Video rows+ # are enabled, greyed out behind "Training needs MLX. Run `unsloth studio+ # update`", or still spinning. That decision reads a real `import+ # mlx.core` and waits on a real background reinstall, and the unit tests+ # for it necessarily fake both. Here the host is Apple Silicon and the+ # MLX stack is genuinely present (first step) or genuinely unimportable+ # (last two), so this is the only place the verdict is judged against the+ # thing it is a verdict about.+ #+ # Three boots, one per step: the self-heal is once per process, so the+ # opted-out and the in-flight cases cannot share a server.+ # ---------------------------------------------------------------+ - name: Provision a Studio venv for the capability-verdict boots+ run: |+ set -euo pipefail+ # `unsloth studio` re-execs into $STUDIO_HOME/unsloth_studio and refuses to+ # start without it ("Unsloth Studio not set up. Run install.sh first."), so a+ # bare `pip install -e .` cannot boot a server. install.sh --local builds that+ # venv, but it also reinstalls the whole stack for ten minutes, and+ # studio-mac-ui-smoke.yml already pays that on every studio/** PR. Building the+ # venv over this job's site-packages gets the same launch path -- no re-exec,+ # the real run.py, the real uvicorn -- for the cost of a virtualenv.+ STUDIO_VENV="$HOME/.unsloth/studio/unsloth_studio"+ rm -rf "$STUDIO_VENV"+ python -m venv --system-site-packages "$STUDIO_VENV"+ "$STUDIO_VENV/bin/pip" install --no-deps -e .+ "$STUDIO_VENV/bin/unsloth" --help > /dev/null+ echo "studio venv ready at $STUDIO_VENV"++ # PATH is set per step rather than through $GITHUB_PATH: the llama.cpp steps+ # below deliberately run under the job's own interpreter, and a venv exported+ # for the rest of the job would quietly move them.+ - name: "Mac capability verdict: real MLX must never look chat-only"+ env:+ UNSLOTH_COMPILE_DISABLE: '1'+ run: |+ export PATH="$HOME/.unsloth/studio/unsloth_studio/bin:$PATH"+ python tests/studio/mac_capability_verdict_smoke.py real-mlx \+ --port 18901 \+ --log logs/studio_verdict_real_mlx.log \+ --workdir logs/verdict_real_mlx++ - name: "Mac capability verdict: no MLX, self-heal opted out, must still settle"+ env:+ UNSLOTH_COMPILE_DISABLE: '1'+ run: |+ export PATH="$HOME/.unsloth/studio/unsloth_studio/bin:$PATH"+ python tests/studio/mac_capability_verdict_smoke.py no-mlx-settles \+ --port 18902 \+ --log logs/studio_verdict_no_mlx.log \+ --workdir logs/verdict_no_mlx++ - name: "Mac capability verdict: no MLX, self-heal in flight, must not publish"+ env:+ UNSLOTH_COMPILE_DISABLE: '1'+ run: |+ export PATH="$HOME/.unsloth/studio/unsloth_studio/bin:$PATH"+ python tests/studio/mac_capability_verdict_smoke.py no-mlx-repair \+ --port 18903 \+ --log logs/studio_verdict_repairing.log \+ --workdir logs/verdict_repairing++ - name: "Mac capability verdict: server logs"+ if: always()+ run: |+ for f in logs/studio_verdict_real_mlx.log \+ logs/studio_verdict_no_mlx.log \+ logs/studio_verdict_repairing.log; do+ echo "=== $f ==="+ tail -60 "$f" 2>/dev/null || echo "(missing)"+ echo+ done+# Validates the macOS prebuilt path Unsloth's setup.sh uses (#5963): install the# unslothai/llama.cpp fork's latest release, download a small public GGUF, and# check llama-server /completion end to end. Split and placed last so thediff --git a/studio/backend/main.py b/studio/backend/main.pyindex 272223e4531..0bca224f89e 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -8,6 +8,7 @@ Main FastAPI application for Unsloth UI Backendimport osimport sysimport threading+import timefrom pathlib import Path as _Pathimport asynciofrom dataclasses import asdict@@ -1293,6 +1294,98 @@ def _hardware_snapshot() -> Optional[tuple[bool, Optional[str]]]:return None+# How long a self-heal that has not started yet may keep holding a verdict back once the+# warm that schedules it is over. start_mlx_autorepair_if_needed() runs in+# _post_warm_background_work, immediately after join_background_warm(), so the handoff is+# the gap this covers; the warm itself is covered by _torch_warm_in_progress(), which is+# minutes on a cold Mac and cannot be replaced by any fixed number.+_MLX_PRESTART_GRACE_AFTER_WARM_S = 30.0+# Absolute backstop, measured from the first hold. _torch_warm_in_progress() goes false when+# the warm thread dies for any reason, but a warm parked forever inside an import never+# does, and "the scheduler is still coming" would then be a permanent answer: Train and+# Video would spin for the whole session instead of settling into the greyed state a broken+# MLX stack has genuinely earned. Well above the warm's own worst case, since firing this on+# a healthy boot would reintroduce the bug the hold exists to fix.+_MLX_PRESTART_CEILING_S = 900.0++_MLX_PRESTART_LOCK = threading.Lock()+# (detection generation, first hold, first tick the warm was seen STOPPED, None while it+# runs). Keyed by generation because detection is not once-per-process: a re-detect that+# republishes mlx_unavailable is a new verdict and gets its own window rather than+# inheriting a spent one. Guarded rather than atomic only because the three move together.+#+# The third field is when the warm was first seen stopped, not when it was last seen+# running, because nothing guarantees a health request lands near the end of the warm. The+# final stages are C-extension imports that hold the GIL for seconds at a time, so requests+# queue behind them and the next one served can be the first in a minute. Measuring the+# grace from the last observed poll would then start it in the past and expire it before+# the handoff it exists to cover, publishing the mlx_unavailable verdict the frontend+# stores as final -- the exact bug this hold prevents.+_mlx_prestart_hold: Optional[tuple[int, float, Optional[float]]] = None++# Indirected so tests can drive the windows without sleeping through them.+_mlx_prestart_clock = time.monotonic+++def _mlx_prestart_hold_ok(generation: int) -> bool:+ """True while a self-heal that has not started yet may still hold a verdict back."""+ global _mlx_prestart_hold+ now = _mlx_prestart_clock()+ warming = _torch_warm_in_progress()+ with _MLX_PRESTART_LOCK:+ held = _mlx_prestart_hold+ if held is None or held[0] != generation:+ _mlx_prestart_hold = (generation, now, None if warming else now)+ return True+ _, first, stopped_seen = held+ if now - first >= _MLX_PRESTART_CEILING_S:+ return False+ if warming:+ # Still (or again) running, so the handoff has not happened yet and any earlier+ # stopped reading was a lull, not the end.+ _mlx_prestart_hold = (generation, first, None)+ return True+ if stopped_seen is None:+ # First time this pass has seen it stopped: the grace starts here, whenever the+ # warm actually ended, so a gap in polling cannot spend it before it opens.+ stopped_seen = now+ _mlx_prestart_hold = (generation, first, stopped_seen)+ return now - stopped_seen < _MLX_PRESTART_GRACE_AFTER_WARM_S+++def _superseded_by_mlx_repair(snapshot: Optional[tuple[bool, Optional[str]]]) -> bool:+ """True when the MLX self-heal is about to replace this settled verdict.++ Scoped to /api/health rather than folded into ``_hardware_snapshot()``: the launcher's+ watchdog reads /api/liveness and holds its startup grace open while hardware_detecting+ is set, so a 15-minute reinstall must not stretch that grace. Only the UI reads+ chat_only, and only the UI has a row to grey out on it.++ Bounded, never open-ended. A live worker holds the verdict for as long as its install+ takes, capped by mlx_repair._WORKER_BUDGET_S: the repair's own subprocess timeout plus+ an allowance for the post-install imports that verify it, which are not themselves+ timed, so a worker parked in one cannot hold the verdict for the rest of the process.+ A repair that has not started yet is only a promise, and this is where that promise+ expires: the scheduler runs after the warm, so the hold lasts while the warm does and+ a short handoff beyond it, under an absolute ceiling for the warm that never ends.+ Past that the verdict settles exactly as it did before any of this existed.+ """+ if snapshot is None:+ return False+ if not _hw_module.verdict_pending_mlx_repair(snapshot[0], snapshot[1]):+ return False+ try:+ from utils.mlx_repair import mlx_repair_started++ # Read after the predicate, so a repair that claims the latch between the two calls+ # resolves the safe way: still held, and now on the worker rather than on a clock.+ if mlx_repair_started():+ return True+ except Exception as exc:+ logger.debug("MLX repair start check failed, holding on the pre-start window: %s", exc)+ return _mlx_prestart_hold_ok(_hw_module.DETECTION_GENERATION)++def _torch_warm_in_progress() -> bool:"""True while the coordinated warm thread is still working through its stages.@@ -1367,6 +1460,12 @@ async def health_check(request: Request):await _await_hardware_detection(_HEALTH_DETECT_BUDGET_S)# Snapshot, not a bare global read: a forced re-detect can start at any moment.snapshot = _hardware_snapshot()+ # A chat-only verdict the MLX self-heal is about to overturn is not an answer yet. Hold+ # it back and keep replying provisionally, or the Mac gets Train and Video greyed out+ # under a tooltip the reinstall makes wrong minutes later.+ mlx_repairing = _superseded_by_mlx_repair(snapshot)+ if mlx_repairing:+ snapshot = Nonebase = {"status": "healthy","timestamp": datetime.now().isoformat(),@@ -1391,7 +1490,9 @@ async def health_check(request: Request):if snapshot is None:# chat_only above is the pre-detection default, not a measurement; clients should re-read.base["hardware_detecting"] = True- if os.environ.get(DISABLE_ENV_VAR) == "1":+ # Not for a held-back verdict: the repair settles it on its own, and "deferred" means+ # nothing ever will, which env.ts answers by storing the conservative chat_only.+ if os.environ.get(DISABLE_ENV_VAR) == "1" and not mlx_repairing:# Nothing is detecting until a hardware-dependent operation runs; say so instead of making clients poll.base["hardware_detection_deferred"] = Trueauth = request.headers.get("authorization", "")@@ -1413,6 +1514,9 @@ async def health_check(request: Request):# Re-read: the bearer check awaits, so a forced re-detect can land in between.snapshot = _hardware_snapshot()+ if _superseded_by_mlx_repair(snapshot):+ mlx_repairing = True+ snapshot = Noneplatform_map = {"darwin": "mac", "win32": "windows", "linux": "linux"}device_type = platform_map.get(sys.platform, sys.platform)@@ -1443,6 +1547,10 @@ async def health_check(request: Request):# client reading this as measured would store reason null and stop the sidebar's recovery# poll. Mark provisional and omit device_type: env.ts treats it as authoritative.authed["hardware_detecting"] = True+ if mlx_repairing:+ # base was built before the repair was noticed, so drop a marker that now+ # contradicts it: the repair will settle this verdict, deferred means nothing will.+ authed.pop("hardware_detection_deferred", None)return autheddiff --git a/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.py b/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.pynew file mode 100644index 00000000000..328c9340e8b--- /dev/null+++ b/studio/backend/tests/test_health_holds_verdict_during_mlx_repair.py@@ -0,0 +1,542 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: /api/health does not publish a verdict the MLX self-heal is about to overturn.++Detection settles before utils.mlx_repair gets its turn, so an Apple Silicon host whose MLX+stack is missing or unreadable answers chat_only=true with reason "mlx_unavailable" first.+The frontend reads that as measured, greys Train and Video and explains them with "run+`unsloth studio update`"; the background reinstall then lands, chat_only flips false and the+sidebar's recovery poll enables both rows. That is the reported "greyed out on launch, then+they come out". Health keeps replying provisionally for that window instead, through the+existing hardware_detecting shape, so the rows spin until there is a real answer.++Everything a chat-only host relies on must be unchanged: an Intel Mac, a CPU-only Linux box,+a Mac with the self-heal opted out, and a Mac whose repair has finished must all still get a+settled verdict and the tooltip that goes with it.++The hold is bounded in both halves. A live worker is waited on for as long as its install+takes; a repair that has not started is only a promise, and a promise nothing ever keeps must+expire, or the rows spin for the whole session instead of settling into the greyed state a+broken MLX stack has genuinely earned.++CPU-only, no network, no GPU, no weights.+"""++from __future__ import annotations++import sys+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.hardware.hardware as hw # noqa: E402+import utils.mlx_repair as mlx_repair # noqa: E402+++class _Worker:+ """Stand-in for the mlx-autorepair thread, alive or finished."""++ def __init__(self, alive: bool) -> None:+ self._alive = alive+ self.started = False++ def start(self) -> None:+ self.started = True++ def is_alive(self) -> bool:+ return self._alive+++def apple_silicon(monkeypatch):+ """An Apple Silicon host with the self-heal enabled and nothing attempted yet."""+ monkeypatch.delenv(mlx_repair.DISABLE_ENV_VAR, raising = False)+ # Both modules ask the question, and hardware.py has its own copy of the helper.+ monkeypatch.setattr(mlx_repair, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(mlx_repair, "_attempted", False, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", None, raising = False)+ # Same reason as the hold below: a stamp left by an earlier test would decide whether+ # this one's worker still counts as in flight.+ monkeypatch.setattr(mlx_repair, "_repair_started_at", None, raising = False)+ # start_mlx_autorepair_if_needed() gates on this, and the real one imports mlx_vlm,+ # which is not installed here anyway.+ monkeypatch.setattr(mlx_repair, "mlx_stack_available", lambda: False)+ # The pre-start hold is stamped on first use and keyed by detection generation, so a+ # stamp left by an earlier test would decide this one's answer.+ import main as main_mod++ monkeypatch.setattr(main_mod, "_mlx_prestart_hold", None)+++class _Clock:+ """A monotonic clock the test drives, so the hold windows cost no wall time."""++ def __init__(self) -> None:+ self.now = 1_000.0++ def __call__(self) -> float:+ return self.now++ def advance(self, seconds: float) -> None:+ self.now += seconds+++def clock(monkeypatch):+ import main as main_mod++ fake = _Clock()+ monkeypatch.setattr(main_mod, "_mlx_prestart_clock", fake)+ return fake+++# ------------------------------------------------------------- the predicate+++def test_a_running_repair_is_in_flight(apple_silicon, monkeypatch):+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ assert mlx_repair.mlx_repair_in_flight() is True+++def test_a_finished_repair_is_not_in_flight(apple_silicon, monkeypatch):+ """The worker exits only after it has published whatever it is going to publish: a+ successful re-detect, or nothing at all on a failed install. Either way the verdict+ standing when it exits is final, so a chat-only Mac gets its greyed rows and tooltip."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = False), raising = False)+ assert mlx_repair.mlx_repair_in_flight() is False+++def test_a_repair_that_has_not_started_yet_is_in_flight(apple_silicon):+ """The half the window is mostly made of. The self-heal is scheduled after the torch+ warm (main._post_warm_background_work), so detection has published "mlx_unavailable"+ tens of seconds before the worker exists."""+ assert mlx_repair.mlx_repair_in_flight() is True+++def test_a_worker_that_could_not_be_started_settles_the_verdict(apple_silicon, monkeypatch):+ """The latch is claimed before the thread exists, so a start() that raises must read as+ finished rather than as forever pending."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", None, raising = False)+ assert mlx_repair.mlx_repair_in_flight() is False+++def test_the_opt_out_settles_the_verdict_immediately(apple_silicon, monkeypatch):+ """UNSLOTH_DISABLE_MLX_AUTOREPAIR=1 means no repair is coming, so holding the verdict+ back would spin Train and Video for the rest of the session."""+ monkeypatch.setenv(mlx_repair.DISABLE_ENV_VAR, "1")+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ assert mlx_repair.mlx_repair_in_flight() is False+++def test_a_non_apple_host_is_never_in_flight(apple_silicon, monkeypatch):+ """The self-heal is Apple Silicon only, Intel Macs included."""+ monkeypatch.setattr(mlx_repair, "is_apple_silicon", lambda: False)+ assert mlx_repair.mlx_repair_in_flight() is False+++def test_the_worker_is_published_together_with_the_latch(apple_silicon, monkeypatch):+ """A gap between claiming _attempted and recording the thread is a window where the+ predicate reads "attempted, nothing alive" and settles the verdict the repair is+ about to overturn -- the exact bug, just narrower."""+ workers: list[_Worker] = []++ def _thread(*_a, **kwargs):+ assert kwargs.get("name") == "mlx-autorepair"+ workers.append(_Worker(alive = True))+ return workers[-1]++ monkeypatch.setattr(mlx_repair.threading, "Thread", _thread)++ assert mlx_repair.start_mlx_autorepair_if_needed() is True+ assert workers and workers[0].started, "the self-heal worker was never started"+ assert mlx_repair._repair_thread is workers[0]+ assert mlx_repair.mlx_repair_in_flight() is True+ # Still one attempt per process.+ assert mlx_repair.start_mlx_autorepair_if_needed() is False+ assert len(workers) == 1+++def test_started_splits_the_two_halves_of_in_flight(apple_silicon, monkeypatch):+ """The distinction the pre-start window is built on: both halves are in flight, but+ only one of them has a worker to wait for."""+ assert mlx_repair.mlx_repair_in_flight() is True+ assert mlx_repair.mlx_repair_started() is False++ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ assert mlx_repair.mlx_repair_in_flight() is True+ assert mlx_repair.mlx_repair_started() is True+++# ---------------------------------------------------------- the hardware gate+++def test_only_the_mlx_reason_holds_a_verdict_back(apple_silicon):+ """Every other chat-only host settles exactly as it does today: no self-heal is+ coming for an Intel Mac or a box with no GPU, and saying "still checking" would spin+ their rows forever."""+ assert hw.verdict_pending_mlx_repair(True, "mlx_unavailable") is True+ for reason in ("intel_mac", "no_gpu", "detection_failed", None):+ assert hw.verdict_pending_mlx_repair(True, reason) is False, reason+++def test_a_training_capable_verdict_is_never_held_back(apple_silicon):+ """chat_only false is the answer the repair is trying to reach; publish it."""+ assert hw.verdict_pending_mlx_repair(False, None) is False+ assert hw.verdict_pending_mlx_repair(False, "mlx_unavailable") is False+++def test_an_intel_mac_verdict_is_not_held_back(apple_silicon, monkeypatch):+ """Belt and braces on the platform check: the reason is derived from+ is_apple_silicon() in the first place, so the two must not disagree."""+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: False)+ assert hw.verdict_pending_mlx_repair(True, "mlx_unavailable") is False+++# --------------------------------------------------- the pre-start hold window+#+# The scheduler runs in main._post_warm_background_work, after join_background_warm(), so+# on a cold Mac "not started yet" is legitimately minutes and no fixed number can stand in+# for it. main bounds that half with the warm's own progress plus a handoff grace, under an+# absolute ceiling for the warm that never ends.+++def _superseded(monkeypatch, *, warming: bool) -> bool:+ """Ask main's gate directly against a settled mlx_unavailable verdict."""+ import main as main_mod++ monkeypatch.setattr(main_mod, "_torch_warm_in_progress", lambda: warming)+ return main_mod._superseded_by_mlx_repair((True, "mlx_unavailable"))+++def _spend_the_handoff_grace(monkeypatch, clock) -> None:+ """Run the grace out the way a caller must: observe the warm stopped, then wait.++ The grace opens on the first stopped reading, not on the clock, so advancing time+ without asking spends nothing. Tests that want an expired window have to ask twice.+ """+ import main as main_mod++ assert _superseded(monkeypatch, warming = False) is True+ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S + 1)+++def test_a_repair_that_has_not_started_holds_the_verdict_while_the_warm_runs(+ apple_silicon, clock, monkeypatch+):+ """The normal case, and the one no timeout could serve: the warm imports transformers+ and datasets before the scheduler gets its turn, which is minutes on a cold Mac."""+ assert _superseded(monkeypatch, warming = True) is True+ import main as main_mod++ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S * 10)+ assert _superseded(monkeypatch, warming = True) is True+++def test_the_handoff_grace_covers_the_gap_after_the_warm(apple_silicon, clock, monkeypatch):+ """start_mlx_autorepair_if_needed() is the next statement after join_background_warm(),+ so the verdict must not settle in the instant between the two."""+ import main as main_mod++ assert _superseded(monkeypatch, warming = True) is True+ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S - 1)+ assert _superseded(monkeypatch, warming = False) is True+++def test_a_repair_that_never_starts_stops_holding_the_verdict(apple_silicon, clock, monkeypatch):+ """The risk this window exists for. The warm finished and the scheduler never claimed+ the latch (its import raised and _post_warm_background_work swallowed it), so "not+ started yet" would otherwise be a permanent answer and the rows would spin for the whole+ session. Instead the Mac gets the greyed rows and the tooltip its stack has earned."""+ assert _superseded(monkeypatch, warming = True) is True+ _spend_the_handoff_grace(monkeypatch, clock)+ assert _superseded(monkeypatch, warming = False) is False+++def test_a_gap_in_polling_does_not_spend_the_grace_before_the_handoff(+ apple_silicon, clock, monkeypatch+):+ """The grace has to start when the warm stops, not when a poll last saw it running.++ The warm's final stages are C-extension imports that hold the GIL for seconds at a+ time, so health requests queue behind them and the next one served can be the first in+ minutes. Measured from the last observed poll the grace would already be spent by the+ time anyone could ask, and the gate would publish the mlx_unavailable verdict during+ the very handoff it exists to cover -- the frontend then stores that as final and greys+ Train and Video until the repair flips them back, which is the reported bug.+ """+ import main as main_mod++ assert _superseded(monkeypatch, warming = True) is True+ # Nobody asks for far longer than the grace, because the warm is holding the GIL.+ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S * 6)+ assert _superseded(monkeypatch, warming = False) is True+ # And it still expires normally once the handoff has actually had its window.+ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S + 1)+ assert _superseded(monkeypatch, warming = False) is False+++def test_a_warm_that_resumes_reopens_the_handoff_grace(apple_silicon, clock, monkeypatch):+ """A stopped reading between two running ones was a lull, not the handoff, so it must+ not leave a countdown running that expires while the warm is still working."""+ import main as main_mod++ assert _superseded(monkeypatch, warming = True) is True+ assert _superseded(monkeypatch, warming = False) is True+ assert _superseded(monkeypatch, warming = True) is True+ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S + 1)+ assert _superseded(monkeypatch, warming = False) is True+++def test_a_warm_that_never_ends_hits_the_ceiling(apple_silicon, clock, monkeypatch):+ """_torch_warm_in_progress() goes false when the warm thread dies, but one parked+ forever inside an import never does. The ceiling is the backstop for exactly that."""+ import main as main_mod++ assert _superseded(monkeypatch, warming = True) is True+ clock.advance(main_mod._MLX_PRESTART_CEILING_S + 1)+ assert _superseded(monkeypatch, warming = True) is False+++def test_a_live_worker_holds_the_verdict_past_every_window(apple_silicon, clock, monkeypatch):+ """A real reinstall is capped by _REPAIR_TIMEOUT_S, not by these windows. Expiring under+ a working install would grey the rows moments before the repair flips them back."""+ import main as main_mod++ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ clock.advance(main_mod._MLX_PRESTART_CEILING_S * 10)+ assert _superseded(monkeypatch, warming = False) is True+++def test_a_worker_parked_past_its_budget_stops_holding_the_verdict(+ apple_silicon, clock, monkeypatch+):+ """attempt_mlx_repair times the uv subprocess, but not the mlx_stack_available()+ imports that verify the install nor the detect_hardware() pass after it. Those import+ mlx.core, mlx_lm and mlx_vlm, which this module already assumes can park forever on a+ broken stack, so an alive thread was an unbounded answer: the rows would spin for the+ whole session rather than settle into the chat-only verdict the stack has earned."""+ worker_clock = _Clock()+ monkeypatch.setattr(mlx_repair, "_repair_clock", worker_clock, raising = False)+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_started_at", worker_clock.now, raising = False)++ assert mlx_repair.mlx_repair_in_flight() is True+ worker_clock.advance(mlx_repair._WORKER_BUDGET_S - 1)+ assert mlx_repair.mlx_repair_in_flight() is True+ worker_clock.advance(2)+ assert mlx_repair.mlx_repair_in_flight() is False+ # And the gate follows it, so the reply settles instead of staying provisional.+ assert _superseded(monkeypatch, warming = False) is False+++def test_a_worker_inside_its_budget_is_never_cut_short(apple_silicon, monkeypatch):+ """The budget is a backstop for a parked worker, not a cap on a working reinstall: a+ slow but healthy uv install must keep the verdict held for its whole run."""+ worker_clock = _Clock()+ monkeypatch.setattr(mlx_repair, "_repair_clock", worker_clock, raising = False)+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_started_at", worker_clock.now, raising = False)++ worker_clock.advance(mlx_repair._REPAIR_TIMEOUT_S)+ assert mlx_repair.mlx_repair_in_flight() is True+++def test_a_worker_that_starts_late_takes_over_an_expired_window(apple_silicon, clock, monkeypatch):+ """The windows bound the promise, not the repair. A scheduler that arrives after the+ grace still gets the verdict held for as long as it is installing."""+ assert _superseded(monkeypatch, warming = True) is True+ _spend_the_handoff_grace(monkeypatch, clock)+ assert _superseded(monkeypatch, warming = False) is False++ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)+ assert _superseded(monkeypatch, warming = False) is True+++def test_a_re_detected_verdict_gets_its_own_window(apple_silicon, clock, monkeypatch):+ """Detection is not once-per-process. A later pass that republishes mlx_unavailable is+ a new verdict, so it must not inherit the spent window of the one before it."""+ assert _superseded(monkeypatch, warming = True) is True+ _spend_the_handoff_grace(monkeypatch, clock)+ assert _superseded(monkeypatch, warming = False) is False++ monkeypatch.setattr(hw, "DETECTION_GENERATION", hw.DETECTION_GENERATION + 1, raising = False)+ assert _superseded(monkeypatch, warming = False) is True+++def test_a_spent_window_does_not_revive_a_settled_host(apple_silicon, clock, monkeypatch):+ """The windows only ever settle a verdict earlier; they must not hold one the opt-out,+ an Intel Mac or a non-Mac had already settled."""+ import main as main_mod++ monkeypatch.setenv(mlx_repair.DISABLE_ENV_VAR, "1")+ assert _superseded(monkeypatch, warming = True) is False+ clock.advance(main_mod._MLX_PRESTART_CEILING_S + 1)+ assert _superseded(monkeypatch, warming = True) is False+++def test_health_settles_the_verdict_once_the_window_is_spent(apple_silicon, clock, monkeypatch):+ """End to end: the held-back reply must not be permanent on a host whose repair never+ arrives, or Train and Video spin for the session instead of explaining themselves."""+ import main as main_mod++ monkeypatch.setattr(main_mod, "_torch_warm_in_progress", lambda: False)+ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")+ assert body["hardware_detecting"] is True++ clock.advance(main_mod._MLX_PRESTART_GRACE_AFTER_WARM_S + 1)+ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert "hardware_detecting" not in body+ assert body["device_type"]+ assert body["chat_only"] is True+ assert body["chat_only_reason"] == "mlx_unavailable"+++def test_an_unaskable_self_heal_settles_the_verdict(apple_silicon, monkeypatch):+ """If mlx_repair cannot even be consulted, settle rather than spin forever."""++ def _boom() -> bool:+ raise RuntimeError("mlx_repair is unimportable")++ monkeypatch.setattr(mlx_repair, "mlx_repair_in_flight", _boom)+ assert hw.verdict_pending_mlx_repair(True, "mlx_unavailable") is False+++# ----------------------------------------------------------------- the route+++def _health(monkeypatch, *, chat_only: bool, reason: str | None) -> dict:+ """Drive /api/health as an authed caller against a settled verdict."""+ import auth.authentication as _authmod+ import main as main_mod+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", hw_mod.DeviceType.CPU, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY", chat_only, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY_REASON", reason, raising = False)+ was_complete = hw_mod.DETECTION_COMPLETE.is_set()+ hw_mod.DETECTION_COMPLETE.set()++ async def _subject(_creds):+ return "tester"++ # health_check imports get_current_subject inside the function, so patching the module+ # attribute is enough and keeps this off the real JWT/storage path.+ monkeypatch.setattr(_authmod, "get_current_subject", _subject)+ app = FastAPI()+ app.add_api_route("/api/health", main_mod.health_check, methods = ["GET"])+ app.add_api_route("/api/liveness", main_mod.liveness_check, methods = ["GET"])+ try:+ with TestClient(app) as client:+ body = client.get("/api/health", headers = {"Authorization": "Bearer probe"}).json()+ body["_liveness"] = client.get("/api/liveness").json()+ return body+ finally:+ if not was_complete:+ hw_mod.DETECTION_COMPLETE.clear()+++def test_health_replies_provisionally_while_the_repair_runs(apple_silicon, monkeypatch):+ """The fix. config/env.ts keys `fetched` on device_type, so omitting it keeps+ capabilitiesUnknown() true and resolveNavRowState spins the rows instead of greying+ them behind a tooltip the reinstall is about to make wrong."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert body["hardware_detecting"] is True, "the held-back verdict was published as measured"+ assert "device_type" not in body, (+ "the frontend caches the first reply carrying device_type as authoritative, so "+ "this one greys Train and Video for the rest of the session"+ )+ assert "chat_only_reason" not in body+ # Conservative direction, unchanged: never offer Train on a host that may not have it.+ assert body["chat_only"] is True+ assert body["version"], "the launcher-facing fields are unaffected"+++def test_health_settles_the_verdict_once_the_repair_has_finished(apple_silicon, monkeypatch):+ """A Mac the self-heal could not fix must still end up with genuinely disabled rows+ and the "run `unsloth studio update`" tooltip that explains them."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = False), raising = False)++ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert "hardware_detecting" not in body+ assert body["device_type"]+ assert body["chat_only"] is True+ assert body["chat_only_reason"] == "mlx_unavailable"+++def test_a_chat_only_host_with_another_reason_still_settles(apple_silicon, monkeypatch):+ """No self-heal exists for these, so nothing may hold their verdict back."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ for reason in ("intel_mac", "no_gpu"):+ body = _health(monkeypatch, chat_only = True, reason = reason)+ assert "hardware_detecting" not in body, reason+ assert body["chat_only_reason"] == reason+ assert body["device_type"]+++def test_a_training_capable_verdict_still_settles(apple_silicon, monkeypatch):+ """Negative control: a repaired host publishes immediately, or Train never comes back."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ body = _health(monkeypatch, chat_only = False, reason = None)++ assert "hardware_detecting" not in body+ assert body["chat_only"] is False+ assert body["device_type"]+++def test_a_held_back_verdict_is_not_reported_as_deferred(apple_silicon, monkeypatch):+ """The torch-warm kill switch does not disable the MLX self-heal, so the two can be on+ at once. "Deferred" tells env.ts nothing will ever settle, and it answers by storing the+ conservative chat_only -- which greys the rows, the outcome this change exists to stop."""+ monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", "1")+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert body["hardware_detecting"] is True+ assert "hardware_detection_deferred" not in body+++def test_the_liveness_route_keeps_its_settled_verdict(apple_silicon, monkeypatch):+ """Scoped to health on purpose. The desktop watchdog probes /api/liveness and holds its+ startup grace open while hardware_detecting is set, so a 15-minute reinstall must not+ stretch that grace. Only the UI reads chat_only, and only the UI greys a row on it."""+ monkeypatch.setattr(mlx_repair, "_attempted", True, raising = False)+ monkeypatch.setattr(mlx_repair, "_repair_thread", _Worker(alive = True), raising = False)++ body = _health(monkeypatch, chat_only = True, reason = "mlx_unavailable")++ assert body["hardware_detecting"] is True+ assert "hardware_detecting" not in body["_liveness"], (+ "the repair hold reached /api/liveness; the launcher's health watchdog would "+ "keep its startup grace open for the whole reinstall"+ )diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 15156140ed6..2e835c0d8a8 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -262,6 +262,36 @@ def _has_usable_mlx_stack() -> bool:return _has_mlx()+def verdict_pending_mlx_repair(chat_only: bool, reason: Optional[str]) -> bool:+ """True when this settled verdict is one the MLX self-heal is about to overturn.++ Detection gets its answer before utils.mlx_repair gets its turn, so an Apple Silicon+ host whose MLX stack is missing or unreadable settles chat-only first and flips only+ once the background reinstall lands. Published as final, that greys Train and Video+ behind a "run `unsloth studio update`" tooltip the repair makes wrong a minute later,+ and the rows then enable themselves on the frontend's recovery poll -- the reported+ "greyed out, then they come out". Callers report it as still-detecting instead.++ The "mlx_unavailable" check is also what lets mlx_repair_in_flight() be cheap: that+ reason means this pass has just measured the stack as unusable, so the self-heal only+ has to report whether it has finished, not re-probe whether it is needed.++ Takes the verdict as arguments rather than reading the globals, so a caller that+ already holds a consistent snapshot does not re-read them mid-pass."""+ if not chat_only or reason != "mlx_unavailable":+ return False+ if not is_apple_silicon():+ return False+ try:+ from utils.mlx_repair import mlx_repair_in_flight+ return mlx_repair_in_flight()+ except Exception as exc:+ # A self-heal we cannot even ask about is one that cannot be relied on, so let the+ # verdict settle rather than hold Train and Video spinning for the whole session.+ logger.debug("MLX repair progress check failed, treating the verdict as final: %s", exc)+ return False++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.pyindex f3879acf5e2..3912923ff0a 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -32,6 +32,7 @@ import subprocessimport sysimport tempfileimport threading+import timefrom pathlib import Pathfrom typing import Optional@@ -112,6 +113,22 @@ _REPAIR_TIMEOUT_S = 900# guard short-circuits on the next boot)._attempted = False_attempted_lock = threading.Lock()+# The worker started by start_mlx_autorepair_if_needed, so callers can tell "still+# installing" from "done, whichever way it went". Written under _attempted_lock together+# with the latch above, since mlx_repair_in_flight() reads the pair as one state.+_repair_thread: Optional[threading.Thread] = None+# When that worker started, and the total it is allowed. attempt_mlx_repair times the uv+# subprocess, but not the mlx_stack_available() imports that verify the install nor the+# detect_hardware() pass after it -- and those import mlx.core, mlx_lm and mlx_vlm, the+# imports this module already assumes can park indefinitely on a broken stack. An alive+# thread was therefore an unbounded answer: a worker parked in them would hold the verdict+# provisional for the whole session, spinning Train and Video instead of settling into the+# chat-only state a broken stack has earned. The subprocess keeps its full timeout; this+# adds the post-install work on top.+_repair_started_at: Optional[float] = None+_WORKER_BUDGET_S = _REPAIR_TIMEOUT_S + 300+# Indirected so the tests can drive the budget without sleeping through it.+_repair_clock = time.monotonicdef is_apple_silicon() -> bool:@@ -164,6 +181,57 @@ def mlx_stack_available() -> bool:return _mlx_runtime_imports_available()+def mlx_repair_in_flight() -> bool:+ """True while the one-time self-heal can still overturn a chat-only verdict.++ Ask only about a host whose MLX stack has just been measured as unusable, which is+ what detect_hardware's "mlx_unavailable" verdict means. This answers "has the repair+ finished", not "does this host need one": the not-yet-started branch would otherwise+ have to re-probe the stack, and on the host that matters that means re-running the+ failing mlx imports on the event loop for every health poll.++ Detection runs on the warm thread and the repair is scheduled after it, so such a host+ settles chat-only first and only flips once the reinstall lands. Both halves of that+ window count, since both publish an answer the repair is about to replace: the stretch+ before the worker starts, and the worker itself. False the moment it has finished,+ whichever way it went, so a host that genuinely cannot train still gets a final+ verdict -- as it does when the self-heal is opted out of, or cannot apply at all, or+ when a worker outlives _WORKER_BUDGET_S without finishing.++ The not-yet-started half is unbounded here on purpose: this module cannot tell a+ repair that is moments away from starting from one whose scheduler never arrives.+ Callers holding a verdict back on the strength of it pair this with+ mlx_repair_started() and bound that half themselves."""+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return False+ if not is_apple_silicon():+ return False+ with _attempted_lock:+ attempted, thread, started_at = _attempted, _repair_thread, _repair_started_at+ if not attempted:+ return True+ if thread is None or not thread.is_alive():+ return False+ # Alive is not the same as making progress. See _WORKER_BUDGET_S: the uv call is timed,+ # the imports that follow it are not, so a worker parked in them would otherwise answer+ # True for the rest of the process.+ if started_at is not None and _repair_clock() - started_at >= _WORKER_BUDGET_S:+ return False+ return True+++def mlx_repair_started() -> bool:+ """True once start_mlx_autorepair_if_needed() has claimed the one-time latch.++ Splits mlx_repair_in_flight()'s True into its two halves for callers that treat them+ differently: a live worker is a reinstall that legitimately runs for many minutes,+ while "not started yet" is a promise nothing has kept yet. Reads the latch rather+ than the thread handle, so a worker whose start() blew up still counts as started and+ falls through to in_flight's aliveness check."""+ with _attempted_lock:+ return _attempted++def _uv_executable() -> str | None:"""Find uv even when macOS GUI launchers start with a minimal PATH."""found = shutil.which("uv")@@ -388,31 +456,41 @@ def start_mlx_autorepair_if_needed() -> bool: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 attemptedthis process, or when disabled via UNSLOTH_DISABLE_MLX_AUTOREPAIR=1."""- global _attempted+ global _attempted, _repair_thread, _repair_started_atif os.environ.get(DISABLE_ENV_VAR) == "1":return Falseif not is_apple_silicon():return Falseif mlx_stack_available():return False+ from utils.hardware import hardware as _hw+with _attempted_lock:if _attempted:return False_attempted = True+ # Built and started inside the lock that claims the latch, so the pair is never+ # 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(),),+ daemon = True,+ name = "mlx-autorepair",+ )+ # Stamped before start() so the budget covers the worker's whole life, and under the+ # same lock as the pair above so a reader never sees a live thread with no deadline.+ _repair_started_at = _repair_clock()+ _repair_thread.start()+ # Logged outside the lock: a blocked stdout must not hold up mlx_repair_in_flight(),+ # which /api/health calls on the event loop.logger.warning("Apple Silicon without a usable MLX stack; attempting a one-time background ""reinstall of mlx/mlx-lm/mlx-vlm to re-enable Train/Export. ""Set %s=1 to disable.",DISABLE_ENV_VAR,)- # Read before start(): the thread may not run for a while, so reading the epoch- # inside it would bind the pass to a later shutdown.- from utils.hardware import hardware as _hw-- threading.Thread(- target = _run_repair_and_redetect,- args = (_hw.current_detection_epoch(),),- daemon = True,- name = "mlx-autorepair",- ).start()return Truediff --git a/tests/studio/mac_capability_verdict_smoke.py b/tests/studio/mac_capability_verdict_smoke.pynew file mode 100644index 00000000000..1be0995a837--- /dev/null+++ b/tests/studio/mac_capability_verdict_smoke.py@@ -0,0 +1,948 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does /api/health ever publish a Mac capability verdict it is about to take back?++The unit tests around this invariant drive main._superseded_by_mlx_repair with a fake+clock and a stand-in worker. Nothing there boots a server, and nothing there runs on a+host where `import mlx.core` succeeds or fails for real. This does: it boots the real+`unsloth studio` on Apple Silicon, polls /api/health from the first reply the socket+gives, and judges the whole sequence rather than the last answer.++Three scenarios, one per boot (the self-heal is once per process, so they cannot share+one):++ real-mlx A healthy Apple Silicon host. The verdict must settle to chat_only+ false with device_backend "mlx", and no reply on the way there may+ publish chat_only true. This is the regression that matters most:+ the hold must not fire on a Mac that can train.++ no-mlx-settles MLX made unimportable, self-heal opted out with+ UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. The verdict must settle promptly to+ chat_only true / "mlx_unavailable". Nothing is coming to overturn it,+ so a hold here would spin Train and Video for the whole session --+ the failure mode the hold's bounds exist to prevent.++ no-mlx-repair MLX made unimportable, self-heal left on. While the reinstall is+ running, no reply may publish the verdict; once it has failed, the+ verdict must settle exactly as in no-mlx-settles.++What is real here and what is not, stated plainly, because an integration test that+quietly asserts against its own mock is worth less than no test:++ * The host, the Apple Silicon check, hardware detection, the torch warm, the+ post-warm scheduler, the self-heal thread and its latch, the /api/health route and+ every window in main.py are all the shipped code, running in a real server process.+ * "MLX is missing" is simulated the same way tests/studio/test_hardware_dispatch_matrix.py+ simulates it, by making the import fail. That test patches inside its own process;+ this one has a server to boot, so the block is a sitecustomize on PYTHONPATH. It+ hides `mlx` from PathFinder, which is what an uninstalled package looks like: the+ spec lookup unsloth/__init__.py does returns None instead of raising, and every+ `import mlx.core` in the stack check raises ModuleNotFoundError.+ * In no-mlx-repair the installer is a stub `uv` first on PATH that records its argv,+ sleeps, and fails. utils.mlx_repair is untouched: it finds uv through+ shutil.which(), builds the real command, spawns the real subprocess and waits for+ it on the real worker thread. Only the third-party binary at the far end of that+ subprocess is ours, and it is a stub because a genuine `uv pip install mlx mlx-lm+ mlx-vlm --reinstall-package ...` on a CI runner is minutes of network for a result+ the shim would reject anyway. The stub's recorded argv is asserted, so a run where+ the self-heal never actually reached the installer fails instead of passing quietly.++Boot and the health wait are the repo's own scripts (.github/scripts/boot-studio-api-only.sh,+.github/scripts/wait-for-health.sh). The poll below is not a reimplementation of the+latter: wait-for-health.sh answers "is it up yet" and keeps no history, and every+assertion here is about replies it would have thrown away.++Apple Silicon only; invoked from .github/workflows/mlx-ci.yml. No GPU work, no weights,+and no network beyond localhost.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+BOOT_SCRIPT = REPO / ".github" / "scripts" / "boot-studio-api-only.sh"+WAIT_FOR_HEALTH = REPO / ".github" / "scripts" / "wait-for-health.sh"+AUTH_DIR = Path(+ os.environ.get("STUDIO_AUTH_DIR", str(Path.home() / ".unsloth" / "studio" / "auth"))+)++# Fast enough that a verdict published for a moment cannot slip between two reads, slow+# enough that minutes of polling stay a rounding error next to the warm. While detection+# is unsettled /api/health spends up to its own 1s budget per call anyway, so the real+# rate over the interesting window is set by the server, not by this.+POLL_INTERVAL_S = float(os.environ.get("STUDIO_MAC_VERDICT_POLL_S", "0.25"))+# How long a verdict is watched after it settles. A verdict that settles and then goes+# back to provisional is the same bug wearing a different hat.+STABLE_HOLD_S = float(os.environ.get("STUDIO_MAC_VERDICT_STABLE_S", "15"))+# Detection is stage one of the warm, so this covers a cold `import torch` and no more.+SETTLE_BUDGET_S = float(os.environ.get("STUDIO_MAC_VERDICT_SETTLE_S", "300"))+# The self-heal is scheduled after join_background_warm(), i.e. behind transformers,+# datasets and unsloth_zoo as well. Minutes on a cold runner, hence the separate budget.+REPAIR_START_BUDGET_S = float(os.environ.get("STUDIO_MAC_VERDICT_REPAIR_START_S", "600"))+# How long the stub installer runs. Must clear main._MLX_PRESTART_GRACE_AFTER_WARM_S with+# room to spare: samples taken after that grace would have expired are the only ones that+# prove the LIVE WORKER is holding the verdict rather than the pre-start window.+UV_SLEEP_S = float(os.environ.get("STUDIO_MAC_VERDICT_UV_SLEEP_S", "75"))+# Where "the grace has certainly expired" starts, measured from the installer's first+# breath. Comfortably past the 30s grace so a slow scheduler cannot blur the two.+WORKER_PROOF_MARGIN_S = float(os.environ.get("STUDIO_MAC_VERDICT_WORKER_PROOF_S", "45"))+# Once the worker is gone nothing holds the verdict, so this is a settle, not a wait.+SETTLE_AFTER_REPAIR_S = float(os.environ.get("STUDIO_MAC_VERDICT_POST_REPAIR_S", "120"))++_failed: list[str] = []+++def info(msg: str) -> None:+ print(f"[verdict] {msg}", flush = True)+++def step(msg: str) -> None:+ print(f"[verdict] STEP {msg}", flush = True)+++def fail(msg: str) -> None:+ """Record a failure and keep going, so one run reports every broken invariant."""+ print(f"[verdict] FAIL {msg}", flush = True)+ _failed.append(msg)+++def ok(msg: str) -> None:+ print(f"[verdict] OK {msg}", flush = True)+++# --------------------------------------------------------------------------- HTTP+++def _get(+ url: str,+ token: str | None = None,+ timeout: float = 15.0,+):+ """(status, parsed body) for a GET, or (None, None) when the socket is not there yet."""+ headers = {"Authorization": f"Bearer {token}"} if token else {}+ req = urllib.request.Request(url, method = "GET", headers = headers)+ try:+ with urllib.request.urlopen(req, timeout = timeout) as resp:+ return resp.status, json.loads(resp.read())+ except urllib.error.HTTPError as exc:+ return exc.code, None+ except Exception:+ # Connection refused before the socket binds, and read timeouts while a+ # C-extension import holds the GIL. Neither is a reply, so neither is a sample.+ return None, None+++def _post(+ url: str,+ body: dict,+ token: str | None = None,+ timeout: float = 30.0,+):+ data = json.dumps(body).encode()+ headers = {"Content-Type": "application/json"}+ if token:+ headers["Authorization"] = f"Bearer {token}"+ req = urllib.request.Request(url, data = data, method = "POST", headers = headers)+ try:+ with urllib.request.urlopen(req, timeout = timeout) as resp:+ return resp.status, json.loads(resp.read())+ except urllib.error.HTTPError as exc:+ return exc.code, None+ except Exception:+ return None, None+++# --------------------------------------------------------------- the reply timeline+++@dataclass(frozen = True)+class Sample:+ t: float # seconds since the poller started, i.e. since just before boot+ token_sent: bool+ body: dict++ @property+ def authed(self) -> bool:+ """True when the bearer was accepted, read off the reply rather than assumed.++ /api/health answers an unusable bearer with the unauthenticated body instead of+ 401, and that body carries no chat_only_reason -- which reads exactly like a+ training-capable Mac. `version` is authed-only and present in both the settled+ and the provisional authed shapes, so it is the marker that cannot lie.+ """+ return "version" in self.body++ @property+ def published(self) -> bool:+ """True when this reply is a measurement rather than a placeholder.++ `hardware_detecting` is exactly the marker config/hardware-verdict.ts reads to+ keep the UI provisional, so its absence is what "the frontend will act on this"+ means. chat_only is present either way and is the pre-detection default (True)+ while the marker is up, which is why its value alone proves nothing.+ """+ return "hardware_detecting" not in self.body++ @property+ def chat_only(self):+ return self.body.get("chat_only")++ @property+ def reason(self):+ return self.body.get("chat_only_reason")++ def state(self) -> tuple:+ return (+ self.published,+ self.authed,+ self.token_sent,+ self.chat_only,+ self.reason,+ self.body.get("device_type"),+ self.body.get("hardware_detection_deferred"),+ self.body.get("torch_warm_in_progress"),+ )+++class HealthPoller(threading.Thread):+ """Reads /api/health in a loop and keeps every reply.++ Started before the boot, so the first reply the server is capable of giving is the+ first one recorded. A verdict that is wrong for two seconds and right afterwards is+ the bug being guarded against, and only the sequence can show it.+ """++ def __init__(self, base: str) -> None:+ super().__init__(daemon = True, name = "health-poller")+ self.base = base+ self.samples: list[Sample] = []+ self.token: str | None = None+ self.first_reply_at: float | None = None+ # Filled in once the boot script reports it, so the waits below can tell "still+ # starting" from "already dead".+ self.server_pid: int | None = None+ self._lock = threading.Lock()+ self._stop = threading.Event()+ self.t0 = time.monotonic()++ def run(self) -> None:+ while not self._stop.is_set():+ token = self.token+ status, body = _get(f"{self.base}/api/health", token)+ if status == 200 and isinstance(body, dict):+ now = time.monotonic() - self.t0+ with self._lock:+ if self.first_reply_at is None:+ self.first_reply_at = now+ self.samples.append(Sample(now, token is not None, body))+ elif status is not None and status != 200:+ # A non-200 from /api/health is not a verdict, but it is worth seeing:+ # the route has no failure mode that should ever produce one.+ info(f"/api/health answered {status}")+ self._stop.wait(POLL_INTERVAL_S)++ def stop(self) -> None:+ self._stop.set()++ def snapshot(self) -> list[Sample]:+ with self._lock:+ return list(self.samples)++ def wait_for(self, predicate, budget: float, what: str) -> Sample | None:+ """First sample satisfying ``predicate``, or None once ``budget`` is spent.++ Gives up early on a server that has exited. A boot that dies on a missing+ dependency otherwise burns the whole budget answering nothing, and the timeout+ message blames the verdict for a process that was never there to publish one.+ """+ deadline = time.monotonic() + budget+ seen = 0+ while time.monotonic() < deadline:+ samples = self.snapshot()+ for sample in samples[seen:]:+ if predicate(sample):+ return sample+ seen = len(samples)+ if self.server_pid and not _process_alive(self.server_pid):+ info(f"the server (pid {self.server_pid}) exited while waiting for {what}")+ return None+ time.sleep(POLL_INTERVAL_S)+ info(f"gave up waiting {budget:.0f}s for {what}")+ return None++ def report(self) -> None:+ """Print one line per state change. Thousands of identical replies say nothing;+ the transitions between them are the whole evidence."""+ samples = self.snapshot()+ first = f"t+{self.first_reply_at:.2f}s" if self.first_reply_at is not None else "never"+ info(f"{len(samples)} health replies recorded, first at {first}")+ previous = None+ for sample in samples:+ state = sample.state()+ if state == previous:+ continue+ previous = state+ info(+ f" t+{sample.t:7.2f}s "+ f"{'PUBLISHED ' if sample.published else 'provisional'} "+ f"{'authed ' if sample.authed else 'unauthed'} "+ f"chat_only={sample.chat_only} reason={sample.reason} "+ f"device_type={sample.body.get('device_type')} "+ f"deferred={sample.body.get('hardware_detection_deferred')} "+ f"warm={sample.body.get('torch_warm_in_progress')}"+ )+++class TokenGetter(threading.Thread):+ """Logs in with the bootstrap password and hands the poller a bearer.++ device_type and chat_only_reason are authed-only fields, so without this the run can+ see THAT a verdict was published but not WHICH one. Runs concurrently with the poll+ rather than before it: waiting for a login would spend the opening seconds of the+ very window under test, and an unauthed reply already reveals a published verdict.+ """++ def __init__(self, base: str, poller: HealthPoller) -> None:+ super().__init__(daemon = True, name = "token-getter")+ self.base = base+ self.poller = poller+ self._stop = threading.Event()+ self.error: str | None = None++ def _login(self, password: str) -> str | None:+ status, body = _post(+ f"{self.base}/api/auth/login", {"username": "unsloth", "password": password}+ )+ if status == 200 and isinstance(body, dict):+ return body.get("access_token")+ return None++ def run(self) -> None:+ pw_file = AUTH_DIR / ".bootstrap_password"+ deadline = time.monotonic() + 240+ password = None+ while time.monotonic() < deadline and not self._stop.is_set():+ try:+ password = pw_file.read_text(encoding = "utf-8").strip()+ except OSError:+ self._stop.wait(0.5)+ continue+ if password:+ break+ self._stop.wait(0.5)+ if not password:+ self.error = f"no bootstrap password appeared at {pw_file}"+ return+ token = None+ while time.monotonic() < deadline and not self._stop.is_set():+ token = self._login(password)+ if token:+ break+ self._stop.wait(1.0)+ if not token:+ self.error = "bootstrap login never returned a token"+ return+ # The seeded password is must-change, and its token only opens+ # /api/auth/change-password: everything else, /api/health's authed half included,+ # sees no subject and silently answers with the unauthenticated body. Read+ # chat_only_reason off that and it is always None, which looks exactly like a+ # training-capable Mac. So rotate first, the same way studio_api_smoke.py does.+ rotated = f"{password}-Rotated1!"+ status, _ = _post(+ f"{self.base}/api/auth/change-password",+ {"current_password": password, "new_password": rotated},+ token = token,+ )+ if status == 200:+ token = self._login(rotated) or token+ self.poller.token = token++ def stop(self) -> None:+ self._stop.set()+++# ------------------------------------------------------------------- the simulations+++def _write_mlx_block_shim(directory: Path) -> Path:+ """A sitecustomize that hides mlx from the import system, for the server we boot.++ tests/studio/test_hardware_dispatch_matrix.py does this with monkeypatch inside one+ process. A booted server is a different process (and spawns more), so the block has+ to arrive through PYTHONPATH, which `site` reads for every interpreter that starts+ under it.++ PathFinder rather than a meta_path finder that raises: unsloth/__init__.py decides+ _IS_MLX with importlib.util.find_spec("mlx") and does not guard it, so a finder that+ raised would turn `import unsloth` into a crash instead of a Mac without MLX.+ Returning None from the path finder is what an uninstalled package genuinely looks+ like -- find_spec answers None, and `import mlx.core` raises ModuleNotFoundError,+ which is the ImportError both _has_mlx() and the stack check already handle.+ """+ directory.mkdir(parents = True, exist_ok = True)+ shim = directory / "sitecustomize.py"+ shim.write_text(+ "# Generated by tests/studio/mac_capability_verdict_smoke.py. Simulates a Mac\n"+ "# whose MLX stack is missing, on a runner where it is installed.\n"+ "import importlib.machinery\n"+ "import sys\n"+ "\n"+ "_real_find_spec = importlib.machinery.PathFinder.find_spec\n"+ "\n"+ "\n"+ "def _find_spec(fullname, path = None, target = None):\n"+ " if fullname == 'mlx' or fullname.startswith('mlx.'):\n"+ " return None\n"+ " return _real_find_spec(fullname, path, target)\n"+ "\n"+ "\n"+ "importlib.machinery.PathFinder.find_spec = staticmethod(_find_spec)\n"+ "for _name in [n for n in sys.modules if n == 'mlx' or n.startswith('mlx.')]:\n"+ " del sys.modules[_name]\n",+ encoding = "utf-8",+ )+ return shim+++def _write_stub_uv(directory: Path, marker: Path) -> Path:+ """A `uv` that records how it was called, takes its time, and fails.++ utils.mlx_repair reaches its installer through shutil.which("uv"), so putting this+ first on PATH is enough to drive the real self-heal without a real install. It fails+ (exit 1) because a success would re-run the stack check, which the shim above still+ refuses -- so the verdict settles chat-only either way, and failing gets there+ without pretending an install happened.++ The marker is written twice, atomically, so a reader can tell "installing" from+ "finished" without racing a partial file. It carries argv because a run where the+ self-heal never reached the installer would otherwise pass this file's assertions+ while proving nothing.+ """+ directory.mkdir(parents = True, exist_ok = True)+ stub = directory / "uv"+ stub.write_text(+ f"#!{sys.executable}\n"+ "# Generated by tests/studio/mac_capability_verdict_smoke.py.\n"+ "import json\n"+ "import os\n"+ "import sys\n"+ "import time\n"+ "\n"+ f"MARKER = {str(marker)!r}\n"+ f"SLEEP = {UV_SLEEP_S!r}\n"+ "\n"+ "\n"+ "def write(record):\n"+ " tmp = MARKER + '.tmp'\n"+ " with open(tmp, 'w', encoding = 'utf-8') as handle:\n"+ " json.dump(record, handle)\n"+ " os.replace(tmp, MARKER)\n"+ "\n"+ "\n"+ "record = {'argv': sys.argv[1:], 'started': time.time()}\n"+ "write(record)\n"+ "time.sleep(SLEEP)\n"+ "record['ended'] = time.time()\n"+ "write(record)\n"+ "sys.exit(1)\n",+ encoding = "utf-8",+ )+ stub.chmod(0o755)+ return stub+++def _read_marker(marker: Path) -> dict | None:+ try:+ return json.loads(marker.read_text(encoding = "utf-8"))+ except Exception:+ return None+++# ------------------------------------------------------------------- boot / teardown+++def boot(port: int, log: Path, env: dict) -> int | None:+ """Run the repo's boot script and return the server pid.++ --api-only because mlx-ci.yml boots on a bare `pip install -e .` with no built+ studio/frontend/dist, and without the flag the server prints "Unsloth frontend build+ not found" and exits before it binds. The workflows that run install.sh do have a+ dist and deliberately serve it, which is why the flag is theirs to pass, not the+ script's to assume.++ GITHUB_ENV is dropped for this call on purpose: with it set the script exports the+ pid into the workflow environment instead of printing it, and this file needs the pid+ in hand to stop the server before the next scenario boots on the next port.+ """+ child_env = dict(env)+ child_env.pop("GITHUB_ENV", None)+ log.parent.mkdir(parents = True, exist_ok = True)+ result = subprocess.run(+ ["bash", str(BOOT_SCRIPT), "--port", str(port), "--log", str(log), "--api-only"],+ env = child_env,+ capture_output = True,+ text = True,+ timeout = 120,+ )+ sys.stdout.write(result.stdout)+ sys.stderr.write(result.stderr)+ # Flushed here, not left to the next print: everything else in this file flushes as+ # it goes, so an unflushed boot banner surfaces minutes later next to the timeout it+ # preceded, and reads like the boot itself took that long.+ sys.stdout.flush()+ sys.stderr.flush()+ match = re.search(r"pid (\d+)", result.stdout)+ return int(match.group(1)) if match else None+++def wait_for_health(port: int, log: Path) -> bool:+ """The repo's own health wait, used for what this file has no answer for: when the+ server never comes up at all, it tails that server's log and says so."""+ result = subprocess.run(+ [+ "bash",+ str(WAIT_FOR_HEALTH),+ "--port",+ str(port),+ "--log",+ str(log),+ "--tmp",+ str(log.with_suffix(".health.json")),+ ],+ capture_output = True,+ text = True,+ )+ sys.stdout.write(result.stdout)+ sys.stderr.write(result.stderr)+ return result.returncode == 0+++def _process_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except OSError:+ return False+ return True+++def stop(pid: int | None) -> None:+ if not pid:+ return+ try:+ os.kill(pid, 15)+ except OSError:+ return+ for _ in range(40):+ try:+ os.kill(pid, 0)+ except OSError:+ return+ time.sleep(0.25)+ try:+ os.kill(pid, 9)+ except OSError:+ pass+++def tail_log(log: Path, lines: int = 80) -> None:+ try:+ content = log.read_text(encoding = "utf-8", errors = "replace").splitlines()+ except OSError:+ info(f"no server log at {log}")+ return+ info(f"last {min(lines, len(content))} lines of {log}:")+ for line in content[-lines:]:+ print(f" | {line}", flush = True)+++# ------------------------------------------------------------------ shared assertions+++def assert_watched_the_window(poller: HealthPoller) -> None:+ """The poll has to have produced replies, or nothing below was actually tested."""+ samples = poller.snapshot()+ if not samples:+ fail("no /api/health reply was ever recorded; nothing below was actually tested")+ return+ provisional = [s for s in samples if not s.published]+ if provisional:+ ok(f"{len(provisional)} provisional replies seen before the verdict settled")+ return+ # Not a failure. Detection is stage one of the warm and the socket binds right after+ # the lifespan starts it, so on a quick host the verdict can be settled before the+ # first connection succeeds. It does not make the run vacuous: the verdict this file+ # guards against stands for as long as the reinstall takes, i.e. minutes, so a first+ # reply carrying it would be caught by the same check that catches a later one.+ info(+ f"no provisional reply was observed; detection settled within "+ f"{poller.first_reply_at:.2f}s, before the socket answered"+ )+++def assert_never_published(poller: HealthPoller, predicate, what: str) -> None:+ for sample in poller.snapshot():+ if sample.published and predicate(sample):+ fail(+ f"{what} was published at t+{sample.t:.2f}s "+ f"(chat_only={sample.chat_only} reason={sample.reason} "+ f"authed={sample.authed}); the frontend treats this as measured"+ )+ return+ ok(f"{what} was never published")+++def assert_settled_and_stable(poller: HealthPoller, chat_only: bool, reason, label: str) -> None:+ """Watch a settled verdict for a while and require it to stay settled and unchanged."""+ step(f"holding {STABLE_HOLD_S:.0f}s to confirm the {label} verdict stays settled")+ mark = len(poller.snapshot())+ time.sleep(STABLE_HOLD_S)+ tail = poller.snapshot()[mark:]+ if not tail:+ fail(f"the poller stopped producing replies while holding the {label} verdict")+ return+ for sample in tail:+ if not sample.published:+ fail(+ f"the {label} verdict went back to provisional at t+{sample.t:.2f}s; "+ "the rows would spin again after settling"+ )+ return+ if sample.chat_only != chat_only:+ fail(f"chat_only flipped to {sample.chat_only} at t+{sample.t:.2f}s")+ return+ if sample.authed and sample.reason != reason:+ fail(f"chat_only_reason became {sample.reason!r} at t+{sample.t:.2f}s")+ return+ ok(f"the {label} verdict held for {STABLE_HOLD_S:.0f}s across {len(tail)} replies")+++def first_authed_published(+ poller: HealthPoller, getter: TokenGetter, budget: float+) -> Sample | None:+ """The first published reply that also carries the authed-only fields.++ chat_only_reason and device_type are what the greyed-row tooltip is built from, so a+ scenario that only ever saw an unauthenticated published reply has not checked the+ thing the user actually reads.+ """+ sample = poller.wait_for(+ lambda s: s.published and s.authed,+ budget,+ "a published reply on an authenticated read",+ )+ if sample is None:+ fail(f"no authenticated published reply ({getter.error or 'login had not landed yet'})")+ return sample+++def assert_settled_verdict(sample: Sample, chat_only: bool, reason, label: str) -> bool:+ """The fields the sidebar renders a row from, checked together."""+ before = len(_failed)+ if sample.chat_only is not chat_only:+ fail(f"the settled {label} verdict is chat_only={sample.chat_only}, expected {chat_only}")+ if sample.reason != reason:+ fail(f"chat_only_reason is {sample.reason!r}, expected {reason!r}")+ if sample.body.get("device_type") != "mac":+ fail(f"device_type is {sample.body.get('device_type')!r}, expected 'mac'")+ if sample.body.get("hardware_detection_deferred"):+ fail(+ "the settled reply is marked detection-deferred; env.ts reads that as "+ "'nothing will ever measure this' and stores the conservative chat_only"+ )+ return len(_failed) == before+++@contextmanager+def booted(port: int, log: Path, env: dict):+ """Boot a Studio with ``env``, polling /api/health from before it can answer."""+ base = f"http://127.0.0.1:{port}"+ poller = HealthPoller(base)+ poller.start()+ pid = None+ getter = TokenGetter(base, poller)+ try:+ pid = boot(port, log, env)+ poller.server_pid = pid+ # Started only now: the boot script wipes the auth directory, so a login thread+ # running before it would read the previous scenario's bootstrap password and+ # spend its retries on a credential this server has never heard of.+ getter.start()+ yield poller, getter+ finally:+ getter.stop()+ poller.stop()+ poller.report()+ stop(pid)+++# ---------------------------------------------------------------------- the scenarios+++def scenario_real_mlx(port: int, log: Path) -> None:+ """A healthy Apple Silicon host must never look chat-only, not even briefly."""+ step("scenario real-mlx: the verdict on a Mac whose MLX stack works")++ # Preflight in this process, with the product's own criterion. On a host where the+ # stack is genuinely broken the boot below would take the chat-only path, quietly+ # test nothing this scenario claims, and set a real 15-minute reinstall going.+ sys.path.insert(0, str(REPO / "studio" / "backend"))+ from utils.mlx_repair import mlx_stack_available # noqa: PLC0415++ if not mlx_stack_available():+ fail(+ "the MLX stack on this host is missing or below unsloth-zoo's minimums, so "+ "the healthy-Mac scenario cannot run here; fix the runner's install rather "+ "than reading this run as a pass"+ )+ return++ with booted(port, log, dict(os.environ)) as (poller, getter):+ settled = poller.wait_for(lambda s: s.published, SETTLE_BUDGET_S, "the verdict to settle")+ if settled is None:+ wait_for_health(port, log)+ tail_log(log)+ fail("the verdict never settled on a host with a working MLX stack")+ return+ info(f"verdict settled at t+{settled.t:.2f}s")++ assert_watched_the_window(poller)+ # The reported bug in the exact shape it reached users: a settled chat-only answer+ # on a Mac that can train, greying Train and Video until the self-heal takes it+ # back. Checked over every reply, because it was only ever true for a while.+ assert_never_published(+ poller,+ lambda s: s.chat_only is True,+ "a chat-only verdict on a training-capable Mac",+ )++ authed = first_authed_published(poller, getter, 120)+ if authed is not None and assert_settled_verdict(authed, False, None, "training-capable"):+ ok("the settled verdict is chat_only=false with device_type mac")++ # device_type names the platform; which backend detection actually selected lives+ # on /api/system, and "mlx" there is the only proof it took the MLX branch rather+ # than falling through to CPU with training switched off.+ if poller.token:+ status, body = _get(f"http://127.0.0.1:{port}/api/system", poller.token, timeout = 60)+ if status != 200 or not isinstance(body, dict):+ fail(f"/api/system returned {status}")+ elif body.get("device_backend") != "mlx":+ fail(+ f"/api/system reports device_backend={body.get('device_backend')!r}; "+ "detection did not select the MLX backend on Apple Silicon"+ )+ else:+ ok("/api/system reports device_backend mlx")++ assert_settled_and_stable(poller, False, None, "training-capable")+++def scenario_no_mlx_settles(port: int, log: Path, work: Path) -> None:+ """A Mac nothing is coming to repair must still get a final answer, and quickly."""+ step("scenario no-mlx-settles: MLX blocked, self-heal opted out")++ shim_dir = work / "mlx_block"+ _write_mlx_block_shim(shim_dir)+ env = dict(os.environ)+ env["PYTHONPATH"] = os.pathsep.join(+ [str(shim_dir)] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])+ )+ env["UNSLOTH_DISABLE_MLX_AUTOREPAIR"] = "1"++ with booted(port, log, env) as (poller, getter):+ # The window under test opens once detection settles, not at the first byte, so+ # gating on the repo's health wait here costs nothing and buys its log tail.+ if not wait_for_health(port, log):+ fail("the server never became healthy")+ return+ settled = poller.wait_for(lambda s: s.published, SETTLE_BUDGET_S, "the verdict to settle")+ if settled is None:+ tail_log(log)+ fail(+ "the verdict never settled with the self-heal opted out; Train and Video "+ "would spin for the whole session on a Mac that has no repair coming"+ )+ return+ info(f"verdict settled at t+{settled.t:.2f}s")++ assert_watched_the_window(poller)+ if settled.chat_only is not True:+ fail(+ f"the settled verdict is chat_only={settled.chat_only} with mlx blocked; "+ "the import shim did not take, so this scenario tested nothing"+ )+ authed = first_authed_published(poller, getter, 120)+ if authed is not None and assert_settled_verdict(+ authed, True, "mlx_unavailable", "chat-only"+ ):+ ok("chat_only true / mlx_unavailable, settled and explained")+ assert_settled_and_stable(poller, True, "mlx_unavailable", "chat-only")+++def scenario_no_mlx_repair(port: int, log: Path, work: Path) -> None:+ """While the self-heal is installing, the verdict it would overturn stays unpublished."""+ step("scenario no-mlx-repair: MLX blocked, self-heal running")++ shim_dir = work / "mlx_block"+ _write_mlx_block_shim(shim_dir)+ stub_dir = work / "stub_bin"+ marker = work / "uv_invocation.json"+ marker.unlink(missing_ok = True)+ _write_stub_uv(stub_dir, marker)++ env = dict(os.environ)+ env["PYTHONPATH"] = os.pathsep.join(+ [str(shim_dir)] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else [])+ )+ env["PATH"] = os.pathsep.join([str(stub_dir), env.get("PATH", "")])+ env.pop("UNSLOTH_DISABLE_MLX_AUTOREPAIR", None)++ with booted(port, log, env) as (poller, getter):+ if not wait_for_health(port, log):+ fail("the server never became healthy")+ return++ step(f"waiting up to {REPAIR_START_BUDGET_S:.0f}s for the self-heal to reach the installer")+ deadline = time.monotonic() + REPAIR_START_BUDGET_S+ record = None+ while time.monotonic() < deadline:+ record = _read_marker(marker)+ if record and "started" in record:+ break+ time.sleep(0.5)+ if not record or "started" not in record:+ tail_log(log)+ fail(+ "the self-heal never invoked the installer, so nothing here exercised the "+ "in-flight hold; check that the post-warm scheduler ran"+ )+ return+ # Anchor the installer's clock to the poller's, so the two timelines can be+ # compared. Both come from this host; only the origin differs.+ uv_started = record["started"] - (time.time() - time.monotonic()) - poller.t0+ argv = " ".join(record.get("argv", []))+ info(f"installer invoked at t+{uv_started:.2f}s: uv {argv[:300]}")+ for token in ("pip", "install", "mlx", "mlx-lm", "mlx-vlm"):+ if token not in argv:+ fail(f"the installer was invoked without {token!r}; this is not the MLX self-heal")++ step(f"waiting for the installer to finish ({UV_SLEEP_S:.0f}s)")+ deadline = time.monotonic() + UV_SLEEP_S + 120+ while time.monotonic() < deadline:+ record = _read_marker(marker)+ if record and "ended" in record:+ break+ time.sleep(0.5)+ if not record or "ended" not in record:+ fail("the stub installer never finished; the run below would prove nothing")+ return+ uv_ended = record["ended"] - (time.time() - time.monotonic()) - poller.t0+ info(f"installer finished at t+{uv_ended:.2f}s")++ in_flight = [s for s in poller.snapshot() if uv_started <= s.t <= uv_ended]+ if not in_flight:+ fail("no health reply landed while the installer was running")+ else:+ published = [s for s in in_flight if s.published]+ if published:+ first = published[0]+ fail(+ f"the verdict was published at t+{first.t:.2f}s while the self-heal was "+ f"still installing (chat_only={first.chat_only} reason={first.reason}); "+ "this is the greyed-out Train and Video the repair then takes back"+ )+ else:+ ok(f"{len(in_flight)} replies during the install, none published")++ # The pre-start window would have expired 30s after the warm ended, and the+ # warm ends before the scheduler runs. A reply this late that is still held+ # back can only be held by the live worker, which is the half of the hold no+ # clock bounds.+ proof = [s for s in in_flight if s.t >= uv_started + WORKER_PROOF_MARGIN_S]+ if not proof:+ fail(+ f"no reply landed more than {WORKER_PROOF_MARGIN_S:.0f}s into the install, "+ "so the hold observed above cannot be told apart from the pre-start grace"+ )+ elif any(s.published for s in proof):+ fail("the verdict was published while a live repair worker was still installing")+ else:+ ok(+ f"{len(proof)} replies held back past the pre-start grace, "+ "so a live worker is what is holding them"+ )++ step("the install has failed; the verdict must now settle on its own")+ settled = poller.wait_for(+ lambda s: s.published, SETTLE_AFTER_REPAIR_S, "the verdict to settle"+ )+ if settled is None:+ tail_log(log)+ fail(+ "the verdict never settled after the self-heal finished; the hold is "+ "unbounded, which spins Train and Video for the rest of the session"+ )+ return+ info(+ f"verdict settled at t+{settled.t:.2f}s, "+ f"{settled.t - uv_ended:.2f}s after the install gave up"+ )+ authed = first_authed_published(poller, getter, 120)+ if authed is not None:+ assert_settled_verdict(authed, True, "mlx_unavailable", "post-repair chat-only")+ assert_settled_and_stable(poller, True, "mlx_unavailable", "post-repair chat-only")+++SCENARIOS = {+ "real-mlx": scenario_real_mlx,+ "no-mlx-settles": scenario_no_mlx_settles,+ "no-mlx-repair": scenario_no_mlx_repair,+}+++def main() -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("scenario", choices = sorted(SCENARIOS))+ parser.add_argument("--port", type = int, required = True)+ parser.add_argument("--log", default = None, help = "server log path")+ parser.add_argument(+ "--workdir",+ default = None,+ help = "where the generated import shim and stub installer are written",+ )+ args = parser.parse_args()++ log = Path(args.log) if args.log else Path("logs") / f"studio_verdict_{args.scenario}.log"+ work = Path(args.workdir) if args.workdir else Path("logs") / f"verdict_{args.scenario}"+ work.mkdir(parents = True, exist_ok = True)++ if args.scenario == "real-mlx":+ scenario_real_mlx(args.port, log)+ else:+ SCENARIOS[args.scenario](args.port, log, work)++ if _failed:+ print(f"[verdict] {len(_failed)} FAILURE(S)", flush = True)+ for message in _failed:+ print(f"[verdict] - {message}", flush = True)+ return 1+ print("[verdict] PASS", flush = True)+ return 0+++if __name__ == "__main__":+ sys.exit(main())