Repository navigation
Studio macOS: faster startup, MLX self-heal, drop obsolete prebuilt pins - #6494
Conversation
Two macOS startup problems shared one root area in the FastAPI lifespan: - The llama.cpp capability + freshness probes ran inline before the server yielded, so a cold/slow/flaky network on the GitHub freshness check blocked 'Application startup complete' (~34s on CI, longer in the field). Move both probes to a daemon thread; app.state stays None until ready (status routes already re-probe at request time). Opt out with UNSLOTH_DISABLE_UPDATE_CHECK=1. - Train and Export were greyed out because mlx/mlx-lm/mlx-vlm arrive only transitively and a resolver backtrack silently drops them, so CHAT_ONLY stayed true. Add utils/mlx_repair.py: when Apple Silicon is detected without MLX, reinstall mlx/mlx-lm/mlx-vlm by name on a daemon thread and re-run hardware detection (opt out UNSLOTH_DISABLE_MLX_AUTOREPAIR=1). Surface a chat_only_reason in /api/health plus a sidebar tooltip so a greyed Train/Export explains itself instead of failing silently.
load_model_defaults(None) called model_name.lower() with no guard, raising 'Error loading model defaults for None' before any model is selected. Return an empty dict for a falsy/non-str name.
Both pins worked around gaps in ggml-org upstream prebuilts, but Studio now routes every GPU host and all of macOS to the unslothai/llama.cpp fork (published_repo_for_host), which ships the needed bundles, so both pins are dead code on the default install path: - macOS b9415: macOS always routes to the fork (its own macOS bundles), and host_supports_macos_minos() is the backstop. The pin only fired under an explicit --published-repo ggml-org override. - Windows Blackwell b9360: Windows-NVIDIA routes to the fork, whose windows-x64-cuda13 bundle covers Blackwell (manifest max_sm 120, toolkit 13.3), so the pin's self-disable check makes it dormant on every default install; it could only activate under the same upstream override on a 13.0-13.2 driver. Remove the pin constants, functions, and call sites. Keep the Blackwell capability detection (_drop_blackwell_incapable_windows_cuda, _host_is_blackwell, _windows_cuda_attempt_covers_blackwell) that still drops a non-sm_120 cuda-12.4 build on a Blackwell host. After this, an explicit --published-repo ggml-org override on a Blackwell 13.0-13.2 host loses its GPU fallback and lands on CPU; the default fork path is unaffected. Update the install selection-logic and macOS-compat unit tests for the new no-pin behavior.
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dcb0e8aba2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # release-by-release walk-back below plus the post-download Mach-O minos | ||
| # backstop (macos_binary_minos_issues / host_supports_macos_minos) handle a | ||
| # too-new macOS build. |
There was a problem hiding this comment.
Restore deep macOS upstream walk-back
For the explicit --published-repo ggml-org/llama.cpp macOS path described here, the replacement walk-back still uses the normal DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS limit of 2 at line 1578, not the macOS-specific 16-release limit used by _fork_manifest_release_plans. On pre-macOS-26 hosts, upstream can have many consecutive macOS-26-only releases before the compatible b9415-era build, so validation will exhaust only the first two too-new plans and fall back to source rather than reaching a loadable prebuilt. Please apply the macOS fallback depth here too if this path is meant to replace the removed pin.
Useful? React with 👍 / 👎.
| upstream_attempts = _drop_blackwell_incapable_windows_cuda( | ||
| host, | ||
| resolve_windows_cuda_choices(host, llama_tag, upstream_assets), | ||
| checksums, | ||
| ) | ||
| return apply_approved_hashes(upstream_attempts, upstream_checksums) | ||
| return apply_approved_hashes(upstream_attempts, checksums) |
There was a problem hiding this comment.
Restore the Blackwell CUDA fallback before filtering
When this fallback path is reached on a Windows Blackwell host whose driver reports CUDA 13.0-13.2, upstream releases that only offer cuda13.3 plus cuda12.4 leave no GPU attempt: cuda13.3 is gated out by _published_windows_cuda_runtime, and _drop_blackwell_incapable_windows_cuda removes cuda12.4 because it cannot offload sm_120. Removing the b9360 cuda13.1 pin here therefore turns the old GPU fallback into a CPU/source fallback for exactly those hosts if the fork bundle is unavailable or rejected, so keep a CUDA>=12.8 fallback before filtering the upstream attempts.
Useful? React with 👍 / 👎.
| def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool: | ||
| """Install mlx + mlx-lm + mlx-vlm by name into the running venv. Best-effort; | ||
| returns True iff `import mlx.core` works afterwards.""" | ||
| cmd = _pip_install_cmd("--upgrade", *MLX_PACKAGES) |
There was a problem hiding this comment.
Constrain the MLX repair install
On the Apple-Silicon repair path this installs mlx-lm/mlx-vlm with --upgrade but without the single-env constraints or the Darwin override; studio/backend/requirements/single-env/overrides-darwin-arm64.txt documents that those packages declare transformers>=5 while Studio pins transformers==4.57.6, and pip help confirms --upgrade may upgrade dependencies when needed. In the missing-MLX scenario this can upgrade transformers in the running venv and break the rest of Studio just to make import mlx.core pass, so reuse the installer constraints/overrides or avoid dependency upgrades here.
Useful? React with 👍 / 👎.
After removing the b9415 macOS pin, the explicit --published-repo ggml-org upstream path still used the default 2-release fallback, so a pre-macOS-26 host behind a run of macOS-26-only builds would exhaust two too-new plans (minos is only checked post-download) and drop to a source build before reaching a loadable older release. Walk back as deep as the fork macOS path (DEFAULT_MAX_MACOS_RELEASE_FALLBACKS), turning the removed static pin into dynamic discovery. Addresses review feedback on the macOS upstream fallback.
mlx-lm/mlx-vlm declare transformers>=5, but the single-env install pins transformers==4.57.6. The self-heal used --upgrade with no constraint, so it could upgrade transformers in the live venv and break the rest of Studio just to make import mlx.core pass. Pin transformers to the installed version via a constraint file: the resolver either finds an mlx build compatible with it or fails (we stay chat-only), never upgrading transformers underneath Studio. Addresses review feedback on the MLX repair install.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8148f25a9a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| returns True iff `import mlx.core` works afterwards. transformers is pinned so | ||
| the install can never upgrade it underneath the rest of Studio.""" | ||
| constraint_args, constraint_path = _transformers_constraint_args() | ||
| cmd = _pip_install_cmd("--upgrade", *constraint_args, *MLX_PACKAGES) |
There was a problem hiding this comment.
Include the MLX override in the repair install
In this revision the repair command pins transformers through a constraint but still runs a plain uv/pip install without the Apple-Silicon UV_OVERRIDE used by install_python_stack.py; that override is what relaxes mlx-lm/mlx-vlm's transformers>=5 metadata while constraints.txt pins Studio to transformers==4.57.6. On a missing-MLX Apple Silicon venv the resolver therefore fails instead of reinstalling the MLX stack, so the background repair returns false and Train/Export remain chat-only; pass the same override/constraints as the installer for this command.
Useful? React with 👍 / 👎.
Pinning transformers alone made uv backtrack mlx-vlm to 0.3.9 (below unsloth-zoo's mlx-vlm>=0.4.4), which imports but breaks VLM Train/Export -- so the self-heal could clear chat-only onto a broken stack. Mirror the main installer: set UV_OVERRIDE=overrides-darwin-arm64.txt so a current mlx-vlm coexists with the transformers pin, require the same minimum versions unsloth-zoo declares, and gate/validate on a full mlx_stack_available() check (not a bare import) so an old or partial stack stays chat-only. Addresses PR review.
resolve_upstream_asset_choice returned the first windows-cuda choice unfiltered, so a Blackwell host could be handed an sm_120-incapable cuda-12.4 build while the sibling planners drop it. Apply _drop_blackwell_incapable_windows_cuda here too and fall through to the CPU bundle on a Blackwell host with no capable GPU asset. Addresses PR review.
The sidebar cached the initial /api/health, so a successful background MLX self-heal (chat_only flips false) did not re-enable Train/Export until a manual reload. While chat-only for the recoverable mlx_unavailable reason, re-poll /api/health and stop once Train/Export become available. Addresses PR review.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad55320b1d
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # elsewhere; opt out with UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. | ||
| try: | ||
| from utils.mlx_repair import start_mlx_autorepair_if_needed | ||
| start_mlx_autorepair_if_needed() |
There was a problem hiding this comment.
Gate Train/Export on the full MLX stack
On Apple Silicon where mlx.core imports but mlx-lm/mlx-vlm is missing or below the new minimums, detect_hardware() has already set CHAT_ONLY=False before this repair starts because the hardware gate only checks mlx.core. If the background repair fails/times out, or a user starts Train/Export before it completes, the UI enables a stack that mlx_stack_available() itself treats as unhealthy; keep the host chat-only until the full MLX stack check passes, or have hardware detection use the same stack predicate.
Useful? React with 👍 / 👎.
| # is no pinned b9360 fallback anymore, so no usable windows-cuda attempt remains | ||
| # and the manifest resolver walks back instead of selecting cuda-12.4. | ||
| with pytest.raises(PrebuiltFallback): | ||
| resolve_release_asset_choice(host, self.TAG, release, checksums) |
There was a problem hiding this comment.
Mock the upstream fetch in this unit test
When this test runs without GitHub access, the call does not deterministically raise PrebuiltFallback: after the Blackwell filter removes the published attempts, resolve_release_asset_choice() falls through to github_release_assets(UPSTREAM_REPO, self.TAG), so the unit test performs a live GitHub request and fails on blocked/offline runners instead of exercising only the resolver logic. Stub the upstream asset lookup (or assert the earlier helper directly) so the selection suite remains hermetic.
Useful? React with 👍 / 👎.
The greyed Train/Export items pass a tooltip explaining why (e.g. MLX missing), but a disabled <button> fires no pointer events and SidebarMenuButton only showed tooltips while collapsed, so the explanation never appeared. Wrap a disabled button in a focusable span and show its tooltip while expanded too; enabled items keep the collapsed-only behavior. Addresses PR review.
detect_hardware enabled MLX training whenever `import mlx.core` worked, but the MLX self-heal (utils/mlx_repair) treats a stack without mlx-lm/mlx-vlm at the versions unsloth-zoo requires as inadequate. That asymmetry let the UI enable Train/Export on exactly the partial/backtracked stack the self-heal is trying to repair (greyed-in-but-broken VLM export). Gate on the same mlx_stack_available() criterion so a partial stack stays chat-only (reason mlx_unavailable) and the background repair restores it. Addresses PR review.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e41d9747b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| (so a backtracked old mlx-vlm is rejected, not accepted). transformers is held | ||
| at its pinned version so the install can never upgrade it underneath Studio.""" | ||
| constraint_args, constraint_path = _transformers_constraint_args() | ||
| cmd = _pip_install_cmd("--upgrade", *constraint_args, *MLX_PACKAGES) |
There was a problem hiding this comment.
Handle the pip fallback in MLX repair
Fresh evidence in this revision is that _pip_install_cmd() still falls back to python -m pip, but this repair command only supplies the Darwin metadata relaxation through UV_OVERRIDE, which plain pip ignores, while the temp constraint pins transformers==4.57.6. On Apple Silicon installs where uv is not on PATH, the mlx-lm/mlx-vlm transformers>=5 metadata documented in overrides-darwin-arm64.txt conflicts with that constraint, so the autorepair returns false and Train/Export remain chat-only. Please either require/bootstrap uv for this repair or use a pip-compatible constrained/metadata-patched path.
Useful? React with 👍 / 👎.
| "chat_only": _hw_module.CHAT_ONLY, | ||
| # Why chat_only is set (None when training is enabled). Lets the UI explain | ||
| # greyed-out Train/Export, e.g. "mlx_unavailable" on Apple Silicon. | ||
| "chat_only_reason": getattr(_hw_module, "CHAT_ONLY_REASON", None), |
There was a problem hiding this comment.
Keep chat-only reason behind auth
For unauthenticated /api/health requests this field is included in base, which is returned before the bearer-token check, even though the same endpoint deliberately withholds device_type because it fingerprints the host. The new values distinguish cases like Apple Silicon missing MLX, Intel Mac, and non-Mac no-GPU hosts, so any unauthenticated caller that can reach the port can infer platform/GPU details; only include this reason after auth or return a non-fingerprinting generic reason pre-auth.
Useful? React with 👍 / 👎.
|
Pushed follow-up commit Changes:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a6b565674e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17cfb20f30
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| A bare `import mlx.core` is not enough: a backtracked old mlx-vlm imports | ||
| fine but breaks VLM Train/Export, so it must not count as a healthy stack | ||
| (otherwise the self-heal would clear chat-only onto a broken install).""" | ||
| if not mlx_available(): |
There was a problem hiding this comment.
Check MLX package versions before importing mlx.core
When an Apple Silicon environment has an importable but below-minimum mlx package, this call imports the old mlx.core module before the version check returns false and starts the repair. The subsequent uv pip install --upgrade updates files on disk, but the running Python process keeps the old mlx/extension module in sys.modules; _run_repair_and_redetect() can then enable Train/Export while training/inference still uses the stale MLX code until a restart. Check distribution versions before importing mlx.core, or avoid enabling the repaired stack in-process after upgrading an already-imported package.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in f46667474. mlx_stack_available() now validates distribution versions before any MLX runtime import, so a below-minimum mlx is not loaded into the process before repair. Added regression coverage for version-before-import ordering.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 39123cab60
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7bb7fbd817
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| "published Windows CUDA assets ignored for install planning: " | ||
| f"{release.repo}@{release.release_tag} ({exc})" | ||
| ) | ||
| upstream_assets = github_release_assets(UPSTREAM_REPO, llama_tag) |
There was a problem hiding this comment.
Avoid fetching upstream after dropping every CUDA attempt
For a Windows Blackwell host whose published CUDA artifacts are all removed by _drop_blackwell_incapable_windows_cuda (for example a 13.0–13.2 driver with only cuda-12.4 left), pin_attempts is empty, apply_approved_hashes raises, and this falls through to a live GitHub fetch. If that fetch is unavailable, the installer aborts with a URL error instead of raising PrebuiltFallback so the release-walkback path can continue; the new test_no_cuda_attempt_on_published_path_for_13_1 hits this path. Please raise PrebuiltFallback when the filtered list is empty before calling GitHub.
Useful? React with 👍 / 👎.
| _MLX_MIN_VERSIONS = {"mlx": "0.22.0", "mlx-lm": "0.22.0", "mlx-vlm": "0.4.4"} | ||
| _MLX_PACKAGE_NAMES = tuple(_MLX_MIN_VERSIONS) | ||
| _MLX_RUNTIME_IMPORTS = ("mlx.core", "mlx_lm", "mlx_lm.sample_utils", "mlx_vlm") | ||
| MLX_PACKAGES = tuple(f"{name}>={version}" for name, version in _MLX_MIN_VERSIONS.items()) |
There was a problem hiding this comment.
Include mlx-metal in the repair package set
On Apple Silicon where an update removed mlx-metal but left mlx, mlx-lm, and mlx-vlm at the required versions, mlx_stack_available() returns true and the autorepair never runs; if repair runs for another missing package, the uv command built from this set still won't reinstall mlx-metal. The main installer installs mlx-metal as part of the MLX stack, so this can leave Train/Export enabled against an incomplete MLX runtime.
Useful? React with 👍 / 👎.
- test_chat_only_reason.py: detect_hardware() assigns module globals directly, which monkeypatch does not revert; the autouse fixture now saves and restores DEVICE/CHAT_ONLY/CHAT_ONLY_REASON/IS_ROCM so a chat-only verdict here cannot leak into other backend tests (e.g. test_utils.py) on a GPU host. - mlx_repair.py: read the transformers version from importlib.metadata instead of importing transformers, so the install pin is not silently dropped when transformers has valid metadata but fails to import.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d0331bc285
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # the gate matches utils.mlx_repair: a partial/backtracked stack stays | ||
| # chat-only (reason "mlx_unavailable") and the background self-heal repairs it. | ||
| if is_apple_silicon() and _has_usable_mlx_stack(): | ||
| DEVICE = DeviceType.MLX |
There was a problem hiding this comment.
Update the spoofed MLX hardware tests
With this stricter gate, the existing tests/studio/test_hardware_dispatch_matrix.py Apple-Silicon profile that only injects fake mlx/mlx.core will no longer detect MLX: mlx_stack_available() requires mlx-lm/mlx-vlm distribution metadata and imports, so detect_hardware() falls through to CPU while that test still expects DeviceType.MLX. Please update the spoof fixture to provide the full fake MLX stack or adjust the expectation, otherwise the repo-wide Studio hardware test matrix fails even though the runtime behavior is intentional.
Useful? React with 👍 / 👎.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces an MLX self-heal mechanism for Apple Silicon hosts to background-reinstall missing or outdated MLX packages, and moves the llama.cpp startup probes to a daemon thread to prevent macOS startup delays. It also removes the obsolete pinned Windows CUDA fallback for Blackwell hosts and adds a guard to prevent errors when loading defaults for unselected models. The code review feedback suggests several robustness improvements in mlx_repair.py, including correcting the requirements directory path resolution, handling potential RuntimeError exceptions on Path.home(), using NamedTemporaryFile to prevent file descriptor leaks, and wrapping the constraint argument generation in a try block to avoid background thread crashes.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| override = ( | ||
| Path(__file__).resolve().parents[1] | ||
| / "requirements" | ||
| / "single-env" | ||
| / "overrides-darwin-arm64.txt" | ||
| ) |
There was a problem hiding this comment.
The path to the requirements directory is resolved using Path(file).resolve().parents[1]. Since mlx_repair.py is located at studio/backend/utils/mlx_repair.py, parents[1] resolves to studio/backend. This means the code is looking for studio/backend/requirements/single-env/overrides-darwin-arm64.txt. However, the requirements directory is typically located at the root of the repository (or under studio/ directly), which would correspond to parents[3] or parents[2]. If the file is not found, override.is_file() will silently evaluate to False, and UV_OVERRIDE will not be set, causing the self-heal to silently fail or install an incompatible/backtracked version of mlx-vlm. Please verify the location of the requirements directory and adjust the parent level accordingly.
| override = ( | |
| Path(__file__).resolve().parents[1] | |
| / "requirements" | |
| / "single-env" | |
| / "overrides-darwin-arm64.txt" | |
| ) | |
| override = ( | |
| Path(__file__).resolve().parents[3] | |
| / "requirements" | |
| / "single-env" | |
| / "overrides-darwin-arm64.txt" | |
| ) |
| def _uv_executable() -> str | None: | ||
| """Find uv even when macOS GUI launchers start with a minimal PATH.""" | ||
| found = shutil.which("uv") | ||
| if found: | ||
| return found | ||
| for candidate in ( | ||
| Path.home() / ".local" / "bin" / "uv", | ||
| Path.home() / ".cargo" / "bin" / "uv", | ||
| Path("/opt/homebrew/bin/uv"), | ||
| Path("/usr/local/bin/uv"), | ||
| ): | ||
| try: | ||
| if candidate.is_file() and os.access(candidate, os.X_OK): | ||
| return str(candidate) | ||
| except OSError: | ||
| continue | ||
| return None |
There was a problem hiding this comment.
Path.home() can raise a RuntimeError if the home directory cannot be resolved (e.g., in certain containerized, headless, or restricted environments where the HOME environment variable is missing or invalid). Wrapping the Path.home() call in a try-except block catching RuntimeError specifically and logging it ensures the application remains robust and falls back to other system paths without silently swallowing errors.
def _uv_executable() -> str | None:
"""Find uv even when macOS GUI launchers start with a minimal PATH."""
found = shutil.which("uv")
if found:
return found
try:
home = Path.home()
home_candidates = [
home / ".local" / "bin" / "uv",
home / ".cargo" / "bin" / "uv",
]
except RuntimeError as e:
import logging
logging.getLogger(__name__).debug("Failed to resolve home directory: %s", e)
home_candidates = []
candidates = home_candidates + [
Path("/opt/homebrew/bin/uv"),
Path("/usr/local/bin/uv"),
]
for candidate in candidates:
try:
if candidate.is_file() and os.access(candidate, os.X_OK):
return str(candidate)
except OSError:
continue
return NoneReferences
- When handling exceptions, avoid broad except Exception: pass clauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting.
| try: | ||
| transformers_version = _dist_version("transformers") | ||
| except PackageNotFoundError: | ||
| return [], None | ||
| except Exception: | ||
| return [], None | ||
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | ||
| with os.fdopen(fd, "w") as fh: | ||
| fh.write(f"transformers=={transformers_version}\n") | ||
| return ["--constraint", path], path |
There was a problem hiding this comment.
Using tempfile.mkstemp and os.fdopen can lead to file descriptor leaks if an exception occurs before the file descriptor is successfully wrapped and closed. A cleaner, safer, and more idiomatic approach in Python is to use tempfile.NamedTemporaryFile with delete=False inside a with block. Ensure any exceptions caught during this process are logged (at least at a debug level) to aid in troubleshooting.
| try: | |
| transformers_version = _dist_version("transformers") | |
| except PackageNotFoundError: | |
| return [], None | |
| except Exception: | |
| return [], None | |
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | |
| with os.fdopen(fd, "w") as fh: | |
| fh.write(f"transformers=={transformers_version}\n") | |
| return ["--constraint", path], path | |
| try: | |
| transformers_version = _dist_version("transformers") | |
| with tempfile.NamedTemporaryFile(mode="w", prefix="mlx_repair_", suffix=".txt", delete=False) as fh: | |
| fh.write(f"transformers=={transformers_version}\n") | |
| path = fh.name | |
| return ["--constraint", path], path | |
| except Exception as e: | |
| import logging | |
| logging.getLogger(__name__).debug("Failed to create transformers constraint: %s", e) | |
| return [], None |
References
- Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.
| constraint_args, constraint_path = _transformers_constraint_args() | ||
| try: |
There was a problem hiding this comment.
_transformers_constraint_args() is called outside of the try...except block in attempt_mlx_repair(). If _transformers_constraint_args() raises an exception (for example, if tempfile.mkstemp or NamedTemporaryFile raises an OSError due to a full disk or permission issues), the exception will propagate unhandled and crash the background thread. Wrapping this call inside the try block ensures that any preparation errors are caught and handled gracefully, allowing the self-heal process to log the failure instead of dying silently. Additionally, initializing constraint_path = None before the try block prevents a NameError in the finally block if the preparation fails.
| constraint_args, constraint_path = _transformers_constraint_args() | |
| try: | |
| constraint_path = None | |
| try: | |
| constraint_args, constraint_path = _transformers_constraint_args() |
…ffline dispatch (macOS) job: - detect_hardware now gates MLX on the full stack (mlx_stack_available imports mlx_lm/mlx_vlm and checks dist versions), so faking only mlx.core makes the apple_silicon_mlx profile resolve to CPU. The dispatch tests assert the routing decision when the stack IS usable, so model a complete stack: test_hardware_dispatch_matrix patches utils.mlx_repair.mlx_stack_available and test_is_mlx_dispatch_gate patches hardware._has_usable_mlx_stack. The stack predicate's own internals stay covered by test_mlx_repair.py. Repo tests (CPU) job: - test_no_cuda_attempt_on_published_path_for_13_1 fell through to a live github_release_assets() upstream fetch after the Blackwell filter dropped every published attempt, which the offline security scanner blocks. Stub that fetch so the walk-back deterministically finds no usable CUDA build and raises PrebuiltFallback without network.
|
@codex review |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces an MLX self-heal mechanism for Apple Silicon that reinstalls the MLX stack in the background if it is missing or outdated, and updates the UI to explain why training/exporting is disabled using a new chat_only_reason field. It also moves the llama.cpp startup probes to a background daemon thread to prevent blocking application startup. Additionally, the pinned Blackwell Windows CUDA fallback logic was removed as upstream now supports Blackwell natively. The review feedback suggests wrapping Path.home() in a try-except block to prevent crashes in restricted environments and improving resource cleanup and exception handling when writing the temporary transformers constraint file.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| for candidate in ( | ||
| Path.home() / ".local" / "bin" / "uv", | ||
| Path.home() / ".cargo" / "bin" / "uv", | ||
| Path("/opt/homebrew/bin/uv"), | ||
| Path("/usr/local/bin/uv"), | ||
| ): |
There was a problem hiding this comment.
In environments where the user's home directory cannot be resolved (e.g., certain restricted containers, sandbox environments, or system services running without a HOME environment variable set), calling Path.home() will raise a RuntimeError. Wrapping the home directory resolution in a try...except block ensures that fallback paths (like /opt/homebrew/bin/uv and /usr/local/bin/uv) can still be checked even if Path.home() fails.
| for candidate in ( | |
| Path.home() / ".local" / "bin" / "uv", | |
| Path.home() / ".cargo" / "bin" / "uv", | |
| Path("/opt/homebrew/bin/uv"), | |
| Path("/usr/local/bin/uv"), | |
| ): | |
| try: | |
| home = Path.home() | |
| candidates = [ | |
| home / ".local" / "bin" / "uv", | |
| home / ".cargo" / "bin" / "uv", | |
| Path("/opt/homebrew/bin/uv"), | |
| Path("/usr/local/bin/uv"), | |
| ] | |
| except Exception: | |
| candidates = [ | |
| Path("/opt/homebrew/bin/uv"), | |
| Path("/usr/local/bin/uv"), | |
| ] | |
| for candidate in candidates: |
| try: | ||
| transformers_version = _dist_version("transformers") | ||
| except PackageNotFoundError: | ||
| return [], None | ||
| except Exception: | ||
| return [], None | ||
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | ||
| with os.fdopen(fd, "w") as fh: | ||
| fh.write(f"transformers=={transformers_version}\n") | ||
| return ["--constraint", path], path |
There was a problem hiding this comment.
If tempfile.mkstemp succeeds but an exception occurs during writing to the file, the file descriptor should be closed and the temporary file removed. To avoid initializing fd and path to None before the try block (which creates dead stores), we can structure the exception handling so that the variables are only accessed when they are guaranteed to be bound.
try:
transformers_version = _dist_version("transformers")
except PackageNotFoundError:
return [], None
except Exception:
return [], None
try:
fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt")
except Exception as exc:
logger.warning("Failed to create transformers constraint file: %s", exc)
return [], None
try:
with os.fdopen(fd, "w") as fh:
fh.write(f"transformers=={transformers_version}\n")
return ["--constraint", path], path
except Exception as exc:
logger.warning("Failed to write transformers constraint file: %s", exc)
try:
os.close(fd)
except OSError:
pass
try:
os.remove(path)
except OSError:
pass
return [], NoneReferences
- Avoid initializing variables to an empty value before a try block if the variable is guaranteed to be bound on all execution paths. Such initialization can lead to dead stores and unnecessary code.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
attempt_mlx_repair runs on a daemon thread, but _transformers_constraint_args was called before the try. A failure there (e.g. tempfile.mkstemp on a full disk or a bad TMPDIR) would propagate unhandled and silently kill the self-heal thread. Move the call inside the try and initialize constraint_path so any such failure is caught and leaves Studio chat-only instead of crashing the thread.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d55834e05b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not _host_is_blackwell(host): | ||
| raise PrebuiltFallback("no compatible Windows CUDA asset was found") |
There was a problem hiding this comment.
Keep missing Windows CUDA assets on the hard-fallback path
In resolve_upstream_asset_choice, a Windows Blackwell host now falls through to the CPU bundle whenever the filtered CUDA attempt list is empty. This also covers releases where resolve_windows_cuda_choices() returned no CUDA attempt at all (for example, only a cuda-13.3 archive on a 13.1 driver, no driver version, or no Windows CUDA archive), not just the intended case where an sm_120-incapable cuda-12.4 attempt was deliberately dropped. In those cases the previous hard PrebuiltFallback let the installer walk back or source-build with CUDA, but this installs a CPU-only prebuilt on a GPU host.
Useful? React with 👍 / 👎.
|
Documenting the Blackwell Windows CUDA pin removal here, with a hardware validation, since it came up during review. This PR drops the pinned That gap only exists on the upstream-only path. Studio installs the Validated on real Blackwell hardware (NVIDIA RTX PRO 6000 Blackwell, sm_120, driver CUDA 13.0) by running this branch's installer end to end:
This run was on Linux; the removed pin was Windows-specific, but the mechanism is identical (the Windows |
|
@codex review |
|
/gemini review |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
There was a problem hiding this comment.
Code Review
This pull request introduces a background MLX self-heal mechanism on Apple Silicon to automatically reinstall or upgrade the MLX stack when missing or outdated, and refactors the llama.cpp startup probes to run on a background daemon thread to prevent blocking application startup. It also adds a chat_only_reason field to the /api/health endpoint, which is used by the frontend to display descriptive hover tooltips explaining why the Train and Export buttons are disabled. Review feedback suggests wrapping Path.home() and temporary file creation in try...except blocks in mlx_repair.py to prevent startup crashes and file descriptor leaks in restricted environments, and wrapping the new user-facing warning strings in app-sidebar.tsx in t() calls to support internationalization.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | ||
| with os.fdopen(fd, "w") as fh: | ||
| fh.write(f"transformers=={transformers_version}\n") | ||
| return ["--constraint", path], path |
There was a problem hiding this comment.
If os.fdopen or fh.write raises an exception (for example, due to a full disk or write permission issues), the temporary file created by tempfile.mkstemp will be leaked on disk because _transformers_constraint_args will raise an exception before returning the path to the caller, preventing the finally block in attempt_mlx_repair from cleaning it up.
Wrap the file writing in a try...except block to ensure that the temporary file is deleted and the file descriptor is closed if any error occurs during initialization.
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | |
| with os.fdopen(fd, "w") as fh: | |
| fh.write(f"transformers=={transformers_version}\n") | |
| return ["--constraint", path], path | |
| fd, path = tempfile.mkstemp(prefix = "mlx_repair_", suffix = ".txt") | |
| try: | |
| with os.fdopen(fd, "w") as fh: | |
| fh.write(f"transformers=={transformers_version}\n") | |
| except Exception: | |
| try: | |
| os.close(fd) | |
| except OSError: | |
| pass | |
| try: | |
| os.remove(path) | |
| except OSError: | |
| pass | |
| raise | |
| return ["--constraint", path], path |
| for candidate in ( | ||
| Path.home() / ".local" / "bin" / "uv", | ||
| Path.home() / ".cargo" / "bin" / "uv", | ||
| Path("/opt/homebrew/bin/uv"), | ||
| Path("/usr/local/bin/uv"), | ||
| ): |
There was a problem hiding this comment.
Path.home() can raise a RuntimeError (e.g., RuntimeError: Base directory undetermined) in certain headless, containerized, or restricted daemon environments where the HOME environment variable is not set or accessible. Since this runs during application startup, such an unhandled exception would crash the startup sequence.
Wrap the Path.home() resolution in a try...except block to gracefully fall back to system-wide paths if the home directory cannot be determined. Additionally, ensure that the exception is logged (even at a debug level) rather than silently ignored, and avoid initializing candidates to an empty list before the try block since it can be bound on all execution paths.
| for candidate in ( | |
| Path.home() / ".local" / "bin" / "uv", | |
| Path.home() / ".cargo" / "bin" / "uv", | |
| Path("/opt/homebrew/bin/uv"), | |
| Path("/usr/local/bin/uv"), | |
| ): | |
| try: | |
| home = Path.home() | |
| candidates = [ | |
| home / ".local" / "bin" / "uv", | |
| home / ".cargo" / "bin" / "uv", | |
| ] | |
| except Exception as e: | |
| import logging | |
| logging.getLogger(__name__).debug("Failed to resolve home directory: %s", e) | |
| candidates = [] | |
| candidates.extend([ | |
| Path("/opt/homebrew/bin/uv"), | |
| Path("/usr/local/bin/uv"), | |
| ]) | |
| for candidate in candidates: |
References
- Avoid using broad, silent exception handlers like
except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging. - Avoid initializing variables to an empty value before a try block if the variable is guaranteed to be bound on all execution paths. Such initialization can lead to dead stores and unnecessary code.
| : chatOnlyReason === "mlx_unavailable" | ||
| ? "Training needs MLX. Run `unsloth studio update` to enable Train and Export." | ||
| : chatOnlyReason === "intel_mac" | ||
| ? "Training needs Apple Silicon or a GPU. Intel Macs are chat-only." | ||
| : chatOnlyReason === "no_gpu" | ||
| ? "Training needs an NVIDIA or AMD GPU." |
There was a problem hiding this comment.
The user-facing warning/informational messages explaining why the Train and Export options are disabled are hardcoded in English. To support internationalization (i18n) and maintain consistency with the rest of the sidebar (which uses the t translation function), these strings should be wrapped in t() calls with appropriate translation keys.
| : chatOnlyReason === "mlx_unavailable" | |
| ? "Training needs MLX. Run `unsloth studio update` to enable Train and Export." | |
| : chatOnlyReason === "intel_mac" | |
| ? "Training needs Apple Silicon or a GPU. Intel Macs are chat-only." | |
| : chatOnlyReason === "no_gpu" | |
| ? "Training needs an NVIDIA or AMD GPU." | |
| : chatOnlyReason === "mlx_unavailable" | |
| ? t("shell.navigation.training_needs_mlx", "Training needs MLX. Run 'unsloth studio update' to enable Train and Export.") | |
| : chatOnlyReason === "intel_mac" | |
| ? t("shell.navigation.training_needs_silicon_or_gpu", "Training needs Apple Silicon or a GPU. Intel Macs are chat-only.") | |
| : chatOnlyReason === "no_gpu" | |
| ? t("shell.navigation.training_needs_gpu", "Training needs an NVIDIA or AMD GPU.") |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…8975) * Stop six backend tests waiting on the clock instead of on a signal These six files spend most of their runtime asleep rather than working, and the waiting buys nothing: every one of them is waiting out a fixed window when it could be waiting for the event it actually cares about. Measured on a fresh worktree off main, the six files together: 118.0s and 118.8s before, 56.5s and 55.3s after. 404 passed and 3 skipped in every run, before and after. Backend tests runs on four Python versions, so that is about 4 runner-minutes a run. No production constant is lowered. The diff is six files, all under studio/backend/tests/. Where a delay was reachable from production code the test now passes an existing parameter at the call site: _terminate_validation_server already takes grace, defaulted to 5.0, and the sibling test in the same commit already passes 0.2, so this one passes 1.0 instead of taking the default four times over. The measured margin there is 25 to 50x, since with the kill mutated out the sentinel appears in 20 to 40ms. test_tool_output_streaming.py is the bulk of it, 61.5s to 32.1s. Seven grandchild processes were fused with sleep 3 and the test then waited 4s or 11s for them. The fuse is now a gate file the test owns, so the grandchild lives indefinitely and the assertion is stronger than "3 is greater than 1". test_cloudflare_tunnel.py is a correctness fix that happens to save 5s. monkeypatch.setattr(ct.threading, "Thread", ...) sets the attribute on the threading module itself, so it replaced threading.Thread process-wide rather than just the tunnel's stdout reader. utils/process_lifetime._Spawner then started a helper thread that never ran, burned its full 5s readiness backstop, and fell back to spawning inline, which silently gives up the PR_SET_PDEATHSIG guarantee that helper thread exists to provide. No assertion is masked today because Popen is faked too, but the patch reaches far outside what the test meant to stub. It is now a shim that overrides Thread and proxies the rest. Detection power is unchanged, and that is measured rather than asserted. Neutering _killpg_captured in core/inference/tools.py fails 7 of the 55 tests in test_tool_output_streaming.py on this branch, and the identical mutation on unpatched main fails the same 7 by name. Same for the others: the installer test fails when the post-SIGKILL group escalation goes, the probe test fails when the probe runs inline, the child-lifetime test fails when PDEATHSIG is dropped, and the cloudflare test fails when the pending-stop record is not cleared. Attribution, since these were deliberate in some cases and accidental in others: #7083 added the grandchild fuses, #8170 the installer grace and child lifetime, #6494 the startup probe, #7875 the cloudflare backstop, #7454 the cold scan. Two of those were sound decisions and are strengthened here rather than weakened. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…test (#15995) ## Summary `studio/backend/tests/test_mlx_repair.py::test_uv_executable_finds_installer_location_when_path_is_minimal` fails on Windows on main. It only shows when a PR touching the MLX repair code gets a Windows leg (the staging xplat run for #15861, whose change does not touch this lookup): ``` E AssertionError: assert None == 'C:\\...\\test_uv_executable_finds_insta0\\.local\\bin\\uv' E + where None = <function _uv_executable at 0x...>() ``` `_uv_executable()` looks for `_UV_NAME`, which is `uv.exe` on Windows, under `~/.local/bin`; the test (from #6494) always plants a file named `uv`. The product is right (Windows' uv installer writes `uv.exe` there); the test planted the POSIX name. ## What changed The test plants `mr._UV_NAME`, so it checks the same lookup on every platform. ## Verification - Linux: `tests/test_mlx_repair.py` 41 passed. - With the `~/.local/bin` candidate removed from `_uv_executable()`, the test fails, so it still guards the minimal-PATH lookup. - Windows: the staging `windows-latest` leg for this PR runs the file.
Summary
A bundle of macOS Unsloth Studio fixes from a focused diagnosis of slow installs/startup and a greyed-out Train/Export. Each was validated end to end on a real Apple Silicon runner (GitHub
macos-14, M1, macOS 14.8.7).1. Faster startup: defer the llama.cpp update probes off the critical path
The llama.cpp capability probe and the GitHub freshness check ran inline in the FastAPI
lifespanbefore the server yielded, so a cold/slow/flaky network on the freshness call blockedApplication startup complete. Both probes now run on a daemon thread;app.state.llama_cpp_*staysNoneuntil ready (the status routes already re-probe at request time, so this is backwards compatible). Opt out of all at-boot update network withUNSLOTH_DISABLE_UPDATE_CHECK=1.Measured on
macos-14(boot to/api/healthhealthy): inline probe 34s -> deferred probe 18s, matching the pre-probe baseline (also 18s). The real-world win is larger since the blocking network call is removed from the path entirely.2. Self-heal MLX so Train/Export stop greying out on macOS
Train and Export are gated by
CHAT_ONLY, which is only false when Apple Silicon has MLX importable.mlx/mlx-lm/mlx-vlmarrive only transitively via unsloth-zoo, and a resolver backtrack can silently drop them, leaving the app chat-only after a reinstall. Newutils/mlx_repair.pyreinstalls those three by name on a daemon thread when Apple Silicon is detected without MLX, then re-runs hardware detection (opt outUNSLOTH_DISABLE_MLX_AUTOREPAIR=1). To make the gate diagnosable instead of silent,/api/healthnow reports achat_only_reasonand the sidebar shows a tooltip on a greyed Train/Export explaining why.Verified on
macos-14: a clean install reportschat_only: falsewith Train/Export enabled, andchat_only_reasonis live in/api/health.3. Drop obsolete upstream prebuilt pins (macOS b9415 + Windows Blackwell b9360)
Both pins existed to work around gaps in ggml-org upstream prebuilts, but Studio now routes any GPU host and all of macOS to the
unslothai/llama.cppfork (published_repo_for_host), and the fork ships the needed bundles:host_supports_macos_minos()is the real backstop. The pin only fired under an explicit--published-repo ggml-org/llama.cppoverride.windows-x64-cuda13bundle covers Blackwell (supported_smsincludes 120,max_sm = 120, toolkit 13.3). The pin's own self-disable check (return Noneonce an in-release attempt covers Blackwell) therefore fires on every default install, so it is already dormant; it could only ever activate under the same--published-repo ggml-orgoverride on a 13.0-13.2 driver.Both are dead code on the default path. This removes the pin constants/functions/call sites while keeping the Blackwell capability detection (
_drop_blackwell_incapable_windows_cuda,_host_is_blackwell,_windows_cuda_attempt_covers_blackwell) that drops a non-sm_120 cuda-12.4 build on a Blackwell host. Note: after this, an explicit--published-repo ggml-org/llama.cppoverride on a Blackwell host with a 13.0-13.2 driver loses the GPU fallback and would land on CPU; the default fork path is unaffected.4. Guard model defaults against a None model name
load_model_defaults(None)calledmodel_name.lower()with no guard, loggingError loading model defaults for Nonebefore any model is selected. It now returns{}for a falsy/non-str name.Tests
New backend tests:
test_startup_llama_probe_non_blocking.py,test_chat_only_reason.py,test_mlx_repair.py,test_model_defaults_none_guard.py, plus additions totest_install_resolve_prebuilt.py(macOS x86_64 and arm64 both route to the fork; the removed pin symbols are gone). The install selection-logic + macOS-compat unit tests are updated for the pin removals.