Skip to content

Studio: stop the macOS launcher killing a warming backend, and the Mac tab blackout - #8076

Merged
danielhanchen merged 40 commits into
mainfrom
fix/mac-studio-startup
Aug 7, 2026
Merged

danielhanchen merged 40 commits into
mainfrom
fix/mac-studio-startup

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Two crash reports from Unsloth Desktop 0.1.524-beta on Apple Silicon, plus the log noise that made them hard to read.

The crash

Server stopped unexpectedly, twice, about a minute after launch. terminal_reason=unresponsive_health_check.

The launcher's health watchdog bypassed its own five-minute startup grace:

let should_count_failure =
    port.is_some() || should_count_watchdog_failure(has_seen_healthy, started_at.elapsed());

port.is_some() is always true on the health-check branch, so the grace only ever applied before the port was validated. The reported timeline shows exactly that seam:

t event
+0s start_managed_server spawned generation=1
+15s port not yet validated, grace applies: backend has not reported a validated port yet
+30s port validated, grace gone; the 2s probe times out: failure 1/3
+47s failure 2/3
+64s failure 3/3, SIGTERM

#7958 removed that clause and is already on main. It landed about ten hours after the 0.1.524-beta binary was built, so the shipped build has the bug and main does not. This PR does not redo it; it fixes what remained.

What remained is that the probes were failing at all. Since #7607 the ML stack imports on a background warm thread, which holds the GIL through its C-extension imports. In the reported logs /api/health took 3735ms and 1177ms, and the process went silent for 27 seconds. Three consecutive 2s probes inside that window are guaranteed. So:

  • The watchdog probes /api/liveness, not /api/health. Health deliberately waits on hardware detection; liveness reads module-level globals. It falls back to health on a 404 so an older backend still validates, matching the pattern already in process.rs:742.
  • The per-probe timeout goes from 2s to 10s, still inside the 15s interval. preflight/backend.rs keeps its own 2s, and the cross-language guard in test_health_answers_within_probe_budget.py still holds.
  • A single early success no longer ends the grace. has_seen_healthy is set only when the reply is not still warming, so /api/liveness now carries hardware_detecting the way health does.

This last one is bounded to the startup window, not a general fix: the elapsed >= BACKEND_STARTUP_GRACE_PERIOD clause is permanently true from 300s on and that clock never resets, so a GIL stall from a large model load ten minutes into a session still counts three failures. The 2s-to-10s raise is what buys headroom there. A rolling grace would be the complete fix and is not in this PR.

The regression test #7958 landed without is here: the_startup_grace_survives_the_mac_cold_start_timeline replays 15s/30s/47s/64s with has_seen_healthy=false.

Train and Video blacked out

Both rows greyed out for minutes on every Mac launch, then came back. config/env.ts seeded the store from a browser-UA guess:

chatOnly: localDeviceType === "mac",   // before /api/health has answered
fetched: false,

A guessed grey-out is pixel-identical to a measured one, and after #7607 the measurement can take a long time to arrive. fetched already existed as the "capabilities loaded" flag and no component read it.

Rows now carry a pending state and spin instead of greying out while the verdict is unmeasured, folded in by resolveNavRowState so the inline rows and the More flyout cannot drift. The chat-only route guard no longer bounces /studio and /video while the verdict is unknown.

The unknown state is !fetched && !detectionDeferred, not !fetched: under UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 a deferred reply carries no device_type, so fetched never flips and the rows would spin for the whole session.

Video on macOS

On healthy Apple Silicon chat_only is false, so the Video tab was enabled while its tooltip said "Video generation needs an NVIDIA or AMD GPU". Neither half was right. There is no supported Apple path for video: resolve_diffusion_device_target() does fall through to an MPS probe, so it is untested rather than structurally absent, but nothing gates on it.

video_capability() now mirrors export_capability() and is spliced into /api/system and /api/system/hardware. The tab stays enabled and the page shows a "coming soon" panel. Only an explicit false hides the generator, so an older backend's absent field keeps the page it has always served.

Logs

The diagnostics bundle was 293KB, and roughly half of it was the same exceptions twice: once as a structured request_failed with a traceback in the exception field, then again as uvicorn's Exception in ASGI application on stderr, which the launcher writes to tauri.log one [backend] [stderr] line at a time. One exception cost about 90 lines.

The middleware marks the exception instance and a filter on uvicorn.error drops only records carrying that mark. Not a blanket match on the message: LoggingMiddleware is not the outermost layer, so a blanket filter would hide exceptions the structured logger never saw. --verbose restores both copies.

Measured on the reported bundle with a real uvicorn server and a route raising the same sqlite-vec error: 83 stderr lines to 9.

The sqlite-vec failure itself was the trigger. sqlite_vec.load(conn) fails per connection even though import sqlite_vec succeeded, so RAG_AVAILABLE stayed true and every /api/rag/knowledge-bases poll 500'd with two tracebacks. It now warns once and degrades to an empty list; genuine DB errors still propagate.

Also: tauri.log only checked its 5MiB rotation threshold at startup, so a long session grew unbounded. It now rotates on write.

Together, 964 of 2063 lines and 137 of 293KB off the reported bundle.

Why Train was actually off on that machine

Not the tab bug. unsloth_zoo and datasets were missing from the venv, MLX only arrives transitively through unsloth-zoo, and the self-heal that should have repaired it failed:

error: No virtual environment or system Python installation found for path
`<studio_home>/unsloth_studio/bin/python`; run `uv venv` to create an environment

It ran uv with --python sys.executable and nothing else. A venv's bin/python is a symlink into the base interpreter, and a macOS Python point-upgrade leaves it dangling; the running process never notices because it mapped the binary at exec time. It now falls back to the venv root, sets VIRTUAL_ENV from sys.prefix, and retries once on that specific error. When both attempts fail it names unsloth studio update rather than uv's uv venv, which would build an environment Unsloth does not manage.

Tests

tests/studio/playwright_mac_tab_capabilities.py drives a live Studio on macOS: samples Train and Video from first paint and fails if either renders disabled while /api/health still reports hardware_detecting, walks Chat/Hub/Images/Train/Video/Export clicking each row, and polls /api/liveness and /api/health on a background thread for 330s, deliberately past the 300s grace. The reported crash landed at t+66s, so a watchdog kill fails the run instead of looking like a slow boot.

cargo test                    143 passed
studio/backend pytest         137 passed   (watchdog, liveness, mlx_repair, logging, rag, video/export capability)
studio/frontend npm test      740 passed
npm run typecheck / build     clean

…erpreter

On Apple Silicon the self-heal reinstalls mlx/mlx-lm/mlx-vlm to re-enable
Train/Export. It ran uv with --python sys.executable and nothing else, so when uv
declined that path the repair gave up and Train stayed disabled for good:

  MLX self-heal failed (staying chat-only):
  error: No virtual environment or system Python installation found for path
  `<studio_home>/unsloth_studio/bin/python`; run `uv venv` to create an environment

A venv's bin/python is a symlink into the base interpreter, and macOS breaks that
link routinely: a Homebrew or python.org point upgrade moves the target and the
venv keeps a dangling symlink. The running process never notices, because it
mapped the binary at exec time, so uv is the first thing to fail.

Name the environment as well as the interpreter. _uv_python_target prefers
sys.executable and falls back to the venv root when the interpreter no longer
re-resolves, _mlx_install_env sets VIRTUAL_ENV from sys.prefix, and a uv run that
still reports an unresolvable interpreter is retried once against the venv
directory. Only that specific failure retries; an ordinary resolution failure
stays a single run.

VIRTUAL_ENV is set from sys.prefix rather than forwarded from os.environ, matching
how UV_OVERRIDE is already handled: it names the install target, so inheriting it
would let a caller redirect the install.

When both attempts fail the venv itself is broken rather than merely missing MLX.
uv's own text says to run `uv venv`, which would build an environment Unsloth does
not manage, so the warning now names `unsloth studio update` instead.

Reported on macOS 0.1.524-beta.
A macOS diagnostics bundle came back at ~300KB, and roughly half of it was the
same tracebacks written twice.

LoggingMiddleware logs request_failed with exc_info, which structlog renders as
a full traceback inside the JSON "exception" field, then re-raises. Uvicorn logs
that same exception again on stderr as "Exception in ASGI application", and the
desktop shell mirrors every stderr line into tauri.log individually, so one
failure cost about 90 log lines. Mark the exception once request_failed has
reported it and filter uvicorn's duplicate on the uvicorn.error logger, the same
technique run.py already uses for the startup line. An exception raised above
the middleware carries no marker and keeps its traceback, and --verbose restores
both copies.

The bundle's own failure was a missing sqlite_vec/vec0.dylib, which the import
check does not catch: every /api/rag/knowledge-bases poll opened a connection,
failed to load the extension and 500ed. rag_db now warns once per process and
raises RagExtensionUnavailable (a RuntimeError subclass, so existing handlers
are unaffected), and list_knowledge_bases degrades to an empty list for that
case only. A locked or corrupt database still surfaces as before.

Also quiet the 2xx line for four boot-burst catalog reads (/api/providers/
registry, /api/providers/, /api/models/loras, /api/settings/personalization);
4xx/5xx and every mutation still log. And tauri.log only checked its 5MiB
rotation threshold at startup, so a long session grew unbounded: the file logger
now writes through a size-tracking handle that rotates in place.

On the reported bundle this removes 945 of 2063 lines (89KB of duplicate stderr
traceback) plus the 9 sqlite-vec request_failed events (48KB), leaving one
warning line.
The platform store seeds chatOnly from the browser user agent, so on every Mac
both rows rendered disabled from first paint, visually identical to a measured
"this machine cannot do that", until /api/health answered. Since the hardware
detection went lazy that reply can take seconds to minutes.

Add capabilitiesUnknown() next to isChatOnly(), derived from the fetched flag
that already means "a server-reported verdict is stored" (a deferred reply
counts as settled: under the torch-warm kill switch nothing else is coming).
NavRowDef gains a pending field, folded in by a small import-free resolver both
render sites go through, so an unmeasured row stays enabled and reuses the
existing spinner column instead of graying out. The root guard lets /studio and
/video wait the verdict out rather than one-way redirecting them to /chat, and
each page shows its own loading state while it does.

Video also gets a real capability answer. There is no Apple path in the video
backend, but a healthy Apple Silicon host is not chat-only, so the tab was
enabled and would just fail at load. video_capability() mirrors
export_capability() and is spliced into GET /api/system and
GET /api/system/hardware as additive fields; the page renders a coming-soon
panel on an authoritative false, and the sidebar tooltip is now derived from the
reason instead of hardcoding "needs an NVIDIA or AMD GPU".

Also retry a failed hardware probe in useHardwareInfo: it resolved to the
unloaded default with nothing scheduled to run again, which would have left the
new Video gate spinning for the session.
Covers the two things reported on Apple Silicon 0.1.524-beta in one live run:
Train and Video rendering blacked out for minutes after launch, and the desktop
launcher killing the backend about a minute in with "Server stopped unexpectedly".

The nav button now carries data-testid="nav-row-<id>" and data-spinner, so the
smoke can tell a spinning row from a greyed-out one. Nothing reads them at
runtime; resolveNavRowState still owns the behaviour.

tests/studio/playwright_mac_tab_capabilities.py drives a live Studio: it samples
the Train and Video rows from first paint and fails if either renders disabled
while /api/health still reports hardware_detecting, walks Chat, Hub, Images,
Train, Video and Export clicking each row and screenshotting the result, and
polls /api/liveness and /api/health on a background thread for the whole run.

The poll window is 330s by default, deliberately past the launcher's 300s startup
grace: the reported crash landed at t+66s, so a backend that dies to the watchdog
fails here rather than looking like a slow boot. Redirects away from /studio and
/video are allowed only once the verdict is measured.
…orting torch

The macOS "Server stopped unexpectedly" report was three probe timeouts inside the
first 64s of a normal cold start. #7958 fixed the grace period being bypassed; this is
the rest of it, on the probe itself.

Probe /api/liveness instead of /api/health. Health awaits hardware detection through
_await_hardware_detection on purpose, so probing it every 15s bills the watchdog for the
warm thread's torch import. Liveness reads module-level caches only, which is what it was
added for. Backends older than the route answer 404, so fall back to health, in the same
order process::generic_backend_health_ok and desktop_backend_owner::fetch_liveness use,
and accept "alive" or "healthy" so a downgrade still validates.

Raise the per-probe budget from 2s to 10s. The C-extension imports hold the GIL and the
process can go quiet for seconds at a time on a cold start (3735ms measured on /api/health,
with a ~27s silence around it). preflight::backend keeps its own 2s: a timeout there
dead-ends the launch instead of retrying, and the backend derives _HEALTH_DETECT_BUDGET_S
from that number.

Stop one early reply ending the startup grace for good. A backend that answers now can
still miss the next three probes while it loads a large model, so has_seen_healthy is set
only once a reply says the hardware verdict has settled. /api/liveness now carries the same
hardware_detecting marker health publishes, plus hardware_detection_deferred when the warm
is switched off and nothing will ever settle it; a backend too old to send either reads as
settled, which is what the launcher assumed before.

Adds the regression test #7958 landed without: the failure policy replayed against the
reported timeline, and the probe covered against a stub backend on both routes.
The repo's macOS workflow exports STUDIO_OLD_PW; the staging harness exports
STUDIO_PW. Reading only the first made the script KeyError before it reached the
backend under staging CI.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two assumptions that hold on this dev box but not on a bare macos-15 runner:

studio_root_id is environment-derived and is legitimately empty on a fresh
runner, so the liveness test asserts the key is present (which is what the
launcher reads) rather than that it is truthy.

python.org macOS builds ship a sqlite3 without enable_load_extension, so the
healthy-path RAG test cannot open a connection at all and errored in fixture
setup. It skips there. The unavailable-path tests, which are the ones this PR
changes behaviour for, still run everywhere.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
pre-commit-ci Bot and others added 2 commits August 7, 2026 03:55
Codex was right that passing the venv root to uv does not recover a dangling
bin/python. Confirmed against uv directly, with a venv whose interpreter symlink
was pointed at a missing target:

  --python <venv>/bin/python    error: No virtual environment or system Python
                                installation found for path ...
  --python <venv>               error: No virtual environment or system Python
                                installation found for directory ...
  VIRTUAL_ENV set, no --python  error: Failed to inspect Python interpreter from
                                active virtual environment

All three fail the same way, so the fallback and the retry were a placebo: when
the first attempt already resolved to the venv root the retry was skipped, and
when it ran it repeated a call that cannot succeed.

Keep the part that does work. uv refusing the environment means the venv is
broken rather than merely missing MLX, and nothing this process can pass to an
install command fixes that, so the warning names 'unsloth studio update' (which
rebuilds the environment) instead of uv's own 'uv venv' suggestion, which would
build one Unsloth does not manage.

_venv_root stays: it names the environment in that message.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…detection

The health watchdog ends its five minute startup grace once a liveness reply says
the backend is no longer warming, and that signal was `hardware_detecting`. But
hardware detection is only the first of utils/torch_warmup.py's stages: the marker
disappears while inference_backend, transformers, datasets and unsloth_zoo are still
importing, and those are the C-extension imports that hold the GIL longest. So the
grace could end mid warm and a stall spanning three 10s probes would count as three
dead probes against a backend that was starting normally, which is the
unresponsive_health_check kill the grace exists to prevent.

Publish `torch_warm_in_progress` on /api/liveness and /api/health, derived from
warm_status(), and read that in the launcher.

A new field rather than a wider `hardware_detecting`: that marker also means "this
hardware verdict is provisional, re-read it", and config/hardware-verdict.ts keeps
the UI provisional and polling while it is set, so keeping it lit through datasets
would hide Train for the whole warm over a verdict that settled seconds in.

Additive and backwards compatible both ways. The launcher keeps its
`hardware_detecting` path as a fallback, so a backend that predates the new field
still gets the grace it gets today, and a backend that sends it talks to an older
launcher exactly as before.

The deferred case is preserved by construction: the field is published only while a
warm thread is actually running, so it is absent both when the warm finished and
when none is coming. UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 never starts one, and a
warm retired mid stage by a shutdown never sets finished; deriving the field from
"not finished" would have reported either as warming forever and held the grace
open until it expired on its own.
…latform

Train and Video now spin instead of graying out while the verdict is unmeasured,
so something has to end the spin. fetchDeviceType spends its bounded wait at most
once per page load, so a host that detects slower than that keeps the provisional
reply and `fetched` stays false. The sidebar's recovery poll returned early unless
the host was chat-only or deferred, which off macOS it is not: the store seeds
chatOnly from the user agent, so on Linux and Windows nothing re-read /api/health.
A cold GPU host importing torch sits squarely in that window, and there the rows
spun and /studio held its loading panel until the user navigated or reloaded.

Poll while the verdict is unknown too, on any platform, and keep the mlx_unavailable
and deferred cases as they were. The poll re-reads with force, which is what gets
past the cached provisional reply and the spent wait latch, and the effect re-runs
when the verdict lands, so the interval is cleared as soon as it is known. Re-reads
are skipped while one is outstanding, bounded so a request that never settles cannot
hold the poll off.

studio-page and video-page gate on the same store value, and the sidebar is mounted
on both routes, so they recover with it rather than growing a second poll.

Covered by tests/hardware-verdict-recovery.test.ts, which drives the real store
through a slow non-Mac detection and asserts the guard arms on the unknown state.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

run.py imports install_uvicorn_duplicate_exception_filter at module scope, and
load_studio_run_module replaces 'loggers' with a stub module carrying only
get_logger, so importing run raised ImportError before any test body ran:

  ImportError: cannot import name 'install_uvicorn_duplicate_exception_filter'
  from 'loggers' (unknown location)

A no-op is the right stub here. The filter only de-duplicates uvicorn's copy of a
traceback and this module never starts a server.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
Codex was right that the script was dead code: nothing under .github invoked
playwright_mac_tab_capabilities.py, so the regression coverage it claims never
executed and the tab blackout could come back unnoticed.

It gets its own boot on a cold port. The assertion is that Train and Video spin
rather than grey out while the verdict is unmeasured, and that window only exists
on a backend that has not warmed yet, so reusing the already-warm 18897 server
would have passed vacuously. For the same reason this phase deliberately does not
wait for a healthy backend first, unlike every other phase here: waiting is how
you miss the window. The script does its own wait, and health answers
provisionally inside a 1s budget.

The liveness poll is cut from its 330s default to 120s here. The full window
exists to outlive the launcher's 300s startup grace, and nothing in this job runs
that watchdog; it boots 'unsloth studio' directly. Spending five macOS-runner
minutes to prove something this job cannot observe is not worth it, and the
watchdog is covered by the Rust tests in commands.rs.
…he guard

Two review findings on this branch.

/video was still outside CHAT_ONLY_ALLOWED, so on a measured chat-only host, a
CPU-only box or a Mac without usable MLX, a direct link or a reload bounced to
/chat before VideoPage could render. That is exactly where the unsupported
explanation this branch added has something to say, so the message was
unreachable in the only cases it was written for. Video now follows /export: the
route is allowed through and the page self-gates on the backend's video verdict,
so nothing loads on a host that cannot run it.

The recovery poll's no-stacking guard could be freed by a read that no longer
held it. A read outliving the 30s stall window is abandoned and the next tick
starts a replacement, but the abandoned read's finally still zeroed the shared
marker, so every following tick saw a free guard and fired another forced
/api/health. On the backend this poll exists for, one still importing torch, that
is a read every three seconds piled onto the process being waited for. A
generation counter now means only the owning read can clear it.

Both regressions verified to fail without the fix: 3 of 754 tests go red.
The first staging run went green having tested nothing. The log tells the story:

  [mac-tabs] spinner observed during warm: {'train': False, 'video': False}
  [mac-tabs] Train: redirected to http://127.0.0.1:8888/login ... (allowed)
  [mac-tabs] Train: nav row not pinned inline; reached by route instead
  [mac-tabs] PASS

The login form takes a username as well as a password and the script filled only
the password, so the submit was a no-op and the browser stayed signed out. Every
later check then read an empty shell: no sidebar, so no nav row, so no assertion
had anything to act on. The redirect check called the bounce to /login 'allowed'
because it only asked whether the verdict was measured, and the row checks
downgraded a total miss to an info line.

Three changes, all so this run would have gone red:

log_in fills the username, then proves the session took by navigating to /chat
and checking it stayed; a failure there aborts rather than continuing into checks
that cannot mean anything.

A bounce to /login, /onboarding or /change-password during the tab walk is a
failure. The session was proven live before the walk started, so losing it
mid-walk is never an allowed redirect.

A walk that never locates a single nav row now fails. That is the shape a
signed-out or unrendered run takes, and it has to be loud.

The survival poll was the one part that did mean something: 65 samples on each of
/api/liveness and /api/health, zero non-200, backend alive past 319s.
Degrading the KB list to an empty response when sqlite-vec's native library
cannot load stopped the 500-plus-traceback on every poll, but it left the rest
of the router behind: the frontend read the empty list as a working empty
state, offered Create, and the POST went straight to get_connection() and
raised. So the fix for the log spam reintroduced the log spam one click later,
and told the user nothing.

One contract now. The polled KB list still degrades, but carries ragAvailable
and ragUnavailableReason so a client can tell "no knowledge bases yet" from
"RAG cannot run on this machine". Every other endpoint answers 503 stating the
same reason, via a rag_available() gate up front and a _rag_connection()
wrapper that catches the case where the first request of a session is the one
that discovers the library is missing. That wrapper also reaches the
connections ingestion opens for itself, and removes an upload it had already
saved rather than orphaning it in the uploads root.

The two new fields are additive and the document listings are deliberately
left erroring rather than degrading, so a frontend that has not learned to read
the marker keeps every error surface it has today.

rag_available() remembers only that the extension loaded, never that it failed,
so a one-off cannot latch RAG off until restart. The warn-once stays: a 503
path that logged per request would be the same regression in a new place.
Genuine database errors are untouched and still surface as real errors.

reconcile_orphaned_ingestion_jobs() gates on rag_available() too, so it is the
no-op its docstring already claimed instead of raising out of startup to be
logged as a reconcile failure.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8bb8685694

ℹ️ 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".

Comment on lines +249 to +250
if (venv_root := _venv_root()) is not None:
env["VIRTUAL_ENV"] = venv_root

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retry uv with a resolvable environment target

When a macOS Python upgrade leaves sys.executable as the dangling venv symlink described here, setting VIRTUAL_ENV does not repair the install because _uv_install_cmd() still passes that invalid path explicitly via --python. The local uv pip install --help defines --python as “The Python interpreter into which packages should be installed,” and reproducing this combination shows uv still returns No virtual environment or system Python installation found; therefore the reported MLX self-heal continues to fail and Train/Export remain disabled. Retry with an actually resolvable target or invoke the managed environment rebuild instead of relying on VIRTUAL_ENV to override --python.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rejecting the operative request, but it did surface a real defect next to it, fixed in 8456594.

Your mechanistic premise is right: --python outranks VIRTUAL_ENV. I confirmed it positively with uv 0.10.7 against a venv whose bin/python was deliberately left dangling -- with VIRTUAL_ENV pointing at that venv and --python /usr/bin/python3.13, uv announced Using Python 3.13.12 environment at: /usr, ignoring VIRTUAL_ENV entirely.

Where I disagree is "retry with an actually resolvable target". There is no such target. Measured, same broken venv:

  • --python <venv>/bin/python, with and without VIRTUAL_ENV: No virtual environment or system Python installation found
  • --python <venv> (the directory): same error
  • --python <the pyvenv.cfg 'home' interpreter>: same error
  • bare VIRTUAL_ENV, no --python: Broken symlink at .../bin/python3, was the underlying Python interpreter removed?
  • --target <site-packages>: exit 0 -- and it resolved against an unrelated ambient 3.13, writing _speedups.cpython-313-...so into a 3.12 venv
  • --prefix <venv root>: exit 0 -- and it invented a lib/python3.13/site-packages the 3.12 venv never puts on sys.path

The last two are why this is not a near miss. They exit 0 while producing a wrong-ABI or unreachable install, so mlx_stack_available() stays False after a ~1 GB download and the failure becomes silent. That is strictly worse than staying chat-only. uv documents both: --target "does not require discovery of an existing Python environment... If a suitable Python interpreter cannot be found, uv will install one" (https://docs.astral.sh/uv/reference/cli/#uv-pip-install--target), and for --prefix, "prefer the use of --python... artifacts installed via --prefix will reference the installing interpreter... rendering them non-portable" (https://docs.astral.sh/uv/reference/cli/#uv-pip-install--prefix).

Only uv venv --allow-existing genuinely repairs it, and only at the same minor version -- at a different minor it exits 0 with no warning and orphans the entire environment (torch, transformers, unsloth, the running app). The realistic trigger is the old minor being removed, which is exactly when no same-minor interpreter is around. That is not something an unconfirmed background thread should do to the venv the live process is importing from.

On your second alternative, "invoke the managed environment rebuild": that is already what the code does. attempt_mlx_repair detects this exact uv error and tells the user to run unsloth studio update, rather than uv's own uv venv advice which would build an environment Unsloth does not manage.

The genuine part: _mlx_install_env's docstring still described VIRTUAL_ENV as "the second half of the dangling-symlink recovery", naming a helper deleted earlier in this PR when that retry was found not to work. The claim outlived the code, and it is what your item is describing. Fixed, with guards pinning that the helper stays deleted, the claim does not return, and the unresolved-interpreter path stays one attempt plus a diagnosis rather than a second install with a different target. 28 tests pass; restoring the old sentence fails the guard.

The repo's own macOS smoke hands this script the raw bootstrap password, and a
backend that still holds one injects it into the page and signs itself in, landing
on /change-password with no login form ever rendered. This script treats that as a
signed-out route, since it has no sidebar to assert against, so the run failed with
'could not sign in'. The staging harness rotates over the API before driving, which
is why the same script passed there and failed here.

Rotate it in the browser instead of giving up, and check for that screen before
waiting on the login field so an authenticated session does not spend a minute
waiting for a form that is correctly absent.

Verified against a live Studio on both paths: a fresh instance holding its
bootstrap password now reports 'password rotated' then 'signed in' where it
previously reported 'could not sign in', and an already-rotated instance still
signs in through the login form.
The warm-up read added for adopted backends is gated on ownership verifying, and
that probe runs every request at the 2s default. During the multi-second GIL stall
the watchdog exists to ride out, both requests inside it time out, the backend
comes back unverified, and the warm-up read never runs at all, so the grace never
reopens and three stalls still clear the backend. The longer budget has to be
applied before verification, not after it.

probe_owned_backend_state keeps its signature and delegates to a variant taking an
explicit budget, so only the watchdog changes. A guard binds that call site to
HEALTH_PROBE_TIMEOUT and fails if it drifts back to the default.

Also uploads the tab-capability phase's log and Playwright evidence, which the
artifact list did not name, so a red macOS run discarded the only record of it.
Matching either fragment meant the loose half carried the same weight as the
specific one: anything RAG-aware in front of the backend can answer a transient
503 saying RAG is unavailable without meaning the extension, and that persisted a
capability verdict which only a later successful gated request could clear.

Keep sqlite-vec and drop the English phrase. Nothing upstream emits a package name
by accident, and the capability being gated is exactly that extension, so this is
narrower than requiring both fragments would be while still tolerating a reworded
backend detail. Requiring both would have made the matcher brittle to precisely the
rewording the fragment match exists for.

Two proxy phrasings added to the generic-503 case, which restoring the loose marker
now fails.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
danielhanchen and others added 3 commits August 7, 2026 06:56
_mlx_install_env's docstring still described VIRTUAL_ENV as the second half of a
dangling-symlink recovery, and named the helper that performed the first half.
That helper was deleted earlier in this PR when the retry was found not to work,
but the claim outlived it and is false: an explicit --python outranks VIRTUAL_ENV,
so uv reports the same unresolved-interpreter error either way.

It is not a harmless stale comment. It is the tree asserting a repair that does not
happen, and a reviewer reading it asked for the mechanism to be restored. State
what uv actually does, and why --target and --prefix are not the escape hatch they
look like: both exit 0 against a broken venv but resolve against whatever ambient
interpreter uv finds, writing a wrong-ABI or off-sys.path install that leaves
mlx_stack_available() False while looking like success.

Two guards: the deleted helper must stay deleted and the claim must not come back,
and the unresolved-interpreter path must stay one attempt plus a diagnosis, never a
second install with a different target.
include_str! embeds the file exactly as checked out, so on Windows the source is
CRLF and the \n}\n search for the end of check_watchdog_health never matched. The
guard panicked on the Tauri CI runner while passing on every Linux and macOS job.
Normalise before searching.

Verified both ways: 149 tests pass on the LF tree, and the guard still passes after
converting the file to CRLF, which reproduced the runner failure before this.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: d38e9ec442

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 4f157101d5

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 8b34ace into main Aug 7, 2026
56 of 59 checks passed
@danielhanchen
danielhanchen deleted the fix/mac-studio-startup branch August 7, 2026 09:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant