Skip to content

Studio: detect an interrupted dependency install instead of launching a backend that cannot import - #7492

Merged
wasimysaid merged 14 commits into
mainfrom
fix/studio-incomplete-install-detection
Jul 28, 2026
Merged

wasimysaid merged 14 commits into
mainfrom
fix/studio-incomplete-install-detection

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

A macOS user on Studio Desktop 0.1.50-beta reported status=error / Server stopped unexpectedly, with the backend dying on import structlog. Same traceback as #4701, #5260, #7147 and #4856.

structlog>=24.1.0 is still line 14 of studio/backend/requirements/studio.txt and a complete install has it. The bug is that an incomplete install is indistinguishable from a good one, and three separate places all trusted the same too-weak signal.

What actually happened

From the reporter's diagnostics:

04:17:57  deps [==========----------] 5/10 studio deps
04:17:57  Stopping installer process group (pid 53801)
04:17:58  Installer exited gracefully with status: ExitStatus(unix_wait_status(15))
04:17:59  Unsloth Studio desktop app starting
04:18:02  desktop_preflight completed disposition=ManagedReady
04:18:02  ModuleNotFoundError: No module named 'structlog'

5/10 studio deps is studio/install_python_stack.py:3010, which runs pip install -r studio/backend/requirements/studio.txt. The SIGTERM landed inside that pip call, so steps 6 to 10 never ran either. record_install_intentional_stop and stop_install are only reachable from cleanup_child_processes (studio/src-tauri/src/main.rs:93), so the app exited mid-install and took the installer with it. Nothing recorded that.

Then:

  1. probe_managed_install() checks only unsloth -h (needs typer and rich) and unsloth studio desktop-capabilities --json (a hardcoded dict at unsloth_cli/commands/studio.py:2782). Neither touches studio.backend, so both pass on a venv with zero Studio dependencies, giving ManagedReady with can_auto_repair=false.
  2. studio/setup.sh:997 compares the installed unsloth version against PyPI. unsloth goes in early, so it matches on a half-built venv and unsloth studio update prints "up to date" and skips install_python_stack entirely.
  3. start_managed_repair (studio/src-tauri/src/commands.rs:490) runs that update and then re-checks with the same blind probes, so Repair would report success without fixing anything.

On crash the frontend only sets "Server stopped unexpectedly" (use-tauri-backend.ts:556); repair is wired solely to managed_stale and owned_stale, so the user has no way forward.

PR #6899 added the -h probe intending to catch "a runtime dependency is broken". It just does not reach far enough.

Changes

Installer completeness marker. New studio/install_manifest.py. install_python_stack.py drops the manifest before the dependency pass and writes it only after the final step, so an interrupted run leaves none. Stdlib only, since it has to import inside the half-built venv it is diagnosing.

CLI reports it. New unsloth studio verify-install (--json, exit 1 when incomplete), and desktop-capabilities gains studio_install_ok and studio_install_reason. Dependency presence is checked with importlib.metadata.distribution against distribution names, not import names, since studio.txt lists PyJWT, python-docx and pymupdf whose import names are jwt, docx and fitz.

Preflight consumes it. preflight/managed.rs turns a false answer into ManagedStale, so auto-repair runs instead of a crash the UI cannot act on. DESKTOP_MANAGEABILITY_VERSION goes 1 to 2, which also makes a CLI too old to answer report stale through the existing check rather than needing a new branch. studio/backend/main.py reports 2 on /api/health and /api/liveness in lockstep, since preflight/backend.rs:152 gates on the same constant.

Repair actually repairs. setup.sh and setup.ps1 get an escape hatch beside the existing anyio one: if the install is incomplete, force the dependency pass. Without this, the preflight fix alone converts a crash into a repair loop that claims to have worked.

CLI errors instead of tracebacks. New unsloth_cli/_studio_deps.py, applied at the export, train, studio and inference import sites:

Error: unsloth export needs the Unsloth Studio dependencies, which are not installed.
  missing: structlog

  Studio install:  unsloth studio update
  Plain pip:       pip install "unsloth[studio]"

Packaging. The wheel ships studio/ and studio.backend*, so train, export, chat, inference and studio all import the backend, and every one of those chains reaches structlog at module level. starlette in loggers/handlers.py was annotation-only, so it moves under TYPE_CHECKING and stops being a runtime dependency. structlog becomes a core dependency and the server stack becomes a studio extra mirroring studio.txt. Note this only fixes builds from main; the PyPI wheel is built from pip, where the same change landed in #7493.

Testing

Local end-to-end against a real install.sh --local: manifest written; complete install reports ready; manifest removed gives studio_install_ok=false and verify-install exit 1; the fast-path predicate forces the dependency pass; update repairs it; a missing dependency gives guidance rather than a traceback; and "deps removed after install" is distinguished from "never finished". All checks pass.

  • Rust: 74 of 74 cargo test, including 6 new cases in preflight/managed.rs. 7 pre-existing fixtures updated for the manageability bump.
  • Python: 18 new tests. Full tests/studio/install plus unsloth_cli/tests compared against a pristine worktree of this branch's parent: 33 failures before, 24 after, none introduced. The configure_quiet_logging guard incidentally fixes 9 previously failing test_inference_chat tests.
  • Cross-platform: a scratch workflow on a staging repo reproduced the original failure on macOS arm64 and Windows against the published wheel. Both preflight probes exit 0, then ModuleNotFoundError: No module named 'structlog', while structlog/fastapi/uvicorn/diceware/pyjwt are declared_anywhere=False and studio/backend/run.py is shipped=True.

New CI: a wheel-smoke.yml step that drops structlog from the existing venv and requires each entry point to explain itself, and studio-update-smoke.yml steps that remove the manifest and assert the install reports not-ready and that update repairs it.

Note for reviewers

The manageability bump means every existing install reports ManagedStale once and auto-repairs on next launch, since none of them have a manifest. That is intended, it is also how the already-broken installs get fixed, but it does mean a one-time unsloth studio update for the desktop install base.

Fixes #4701
Fixes #5260
Fixes #7147

… a backend that cannot import

An installer killed part-way leaves a venv with a working CLI but without
studio.txt's dependencies. Nothing recorded that, so three separate places all
reported it healthy:

- the desktop preflight probed only `unsloth -h` (typer + rich) and a hardcoded
  desktop-capabilities dict, neither of which touches studio.backend, so it
  returned ManagedReady and spawned a backend that died on `import structlog`;
- setup.sh's fast path compared the installed unsloth version against PyPI,
  which matches on a half-built venv because unsloth is installed early, so
  `unsloth studio update` printed "up to date" and repaired nothing;
- start_managed_repair calls that update and then re-checks with the same blind
  probes, so Repair reported success without fixing anything.

install_python_stack.py now clears a completion manifest before the dependency
pass and writes it only after the final step. `unsloth studio verify-install`
and desktop-capabilities' new studio_install_ok field read it, the preflight
turns a false answer into ManagedStale so auto-repair runs, and setup.sh /
setup.ps1 gain an escape hatch next to the existing anyio one.

Separately, the wheel ships studio/ and studio.backend* but declared none of
their dependencies, so `unsloth train`, `export`, `chat`, `inference` and
`studio` all ended in a rich traceback after a plain pip install. structlog is
the only hard module-level import that chain reaches once starlette's
annotation-only import moves under TYPE_CHECKING, so it becomes a core
dependency and the rest of the server stack becomes a [studio] extra mirroring
studio.txt. The CLI import sites now report missing dependencies as a sentence
with two remedies.

Fixes #4701, #5260, #7147

@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: 705bc8ca2a

ℹ️ 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 +14 to +15
// 3: the cached capability gained studio_install_ok / studio_install_reason.
const MANAGED_CAPABILITY_CACHE_SCHEMA: u16 = 3;

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 Invalidate cached readiness when the manifest changes

Include the venv-root unsloth_install_manifest.json in the managed fingerprint before caching studio_install_ok. After a successful probe is cached, install_python_stack() can remove the manifest and then be interrupted without changing the unsloth binary or any marker currently returned by marker_candidates_for_bin; the -h probe still succeeds and read_cached_capability() returns the old ready result without rerunning desktop-capabilities. This recreates the broken-backend launch this change is intended to prevent during an interrupted same-version repair or update.

Useful? React with 👍 / 👎.

Comment thread unsloth_cli/_studio_deps.py Outdated
Comment on lines +87 to +88
try:
return module.verify_install()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Verify the managed root rather than the caller's prefix

Pass the selected managed venv root to verify_install() here. When unsloth runs from an interpreter outside STUDIO_HOME/unsloth_studio, extra_roots only helps locate the helper module; calling it without root makes read_manifest() inspect the caller's sys.prefix instead. Consequently a complete managed installation is reported incomplete by desktop-capabilities and verify-install, despite _install_state() explicitly supporting this external-CLI layout.

Useful? React with 👍 / 👎.

Comment thread unsloth_cli/_inference.py Outdated
Comment on lines +441 to +443
from unsloth_cli._studio_deps import studio_backend_imports

with studio_backend_imports("unsloth inference"), quiet_if_nonzero_mlx_rank():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restrict the dependency guard to backend imports

End this context after the backend imports, or only translate packages proven missing from studio.txt. It currently also covers model resolution and backend.load_model(), so a later ModuleNotFoundError—for example the direct import mlx.core in the MLX backend—gets rewritten as a missing Studio-extra error. The suggested pip install "unsloth[studio]" does not install MLX, and the real traceback is suppressed, leaving affected inference users with an ineffective repair instruction.

Useful? React with 👍 / 👎.

Comment on lines 3 to +7
pub(crate) const DESKTOP_PROTOCOL_VERSION: u16 = 1;
pub(crate) const DESKTOP_MANAGEABILITY_VERSION: u16 = 1;
// 2: the CLI must report studio_install_ok from `studio desktop-capabilities`,
// so an interrupted install is caught before the backend is spawned. A CLI
// reporting 1 is Stale and gets repaired, which reinstalls what it missed.
pub(crate) const DESKTOP_MANAGEABILITY_VERSION: u16 = 2;

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 Keep legacy owned backends manageable during migration

Separate the new CLI install-check capability from the lifecycle-control version, or continue allowing a verified version-1 owned backend to be stopped. If a backend from the previous release is still alive when the desktop updates, probe_owned_backend_state() now rejects it in lifecycle_control_block_reason() because it reports manageability 1, so preflight returns ExternalConflict with can_auto_repair=false instead of stopping it and performing the intended one-time repair. This locks the user out until they manually locate and kill a backend whose root and ownership token already prove it belongs to this app.

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.

Correct, and worse than described. A backend already running cannot change what it reports, so bumping studio/backend/main.py in lockstep does not help one the previous app version spawned. lifecycle_control_block_reason returned Unmanageable, and that branch never calls adopt_verified_backend, so has_owned_backend() stayed false and Repair fell into block_external_conflict, which found the same process and refused: the app could no longer stop a backend it holds the ownership token for. Fixed in 6139f27 by splitting the constant, DESKTOP_BACKEND_MANAGEABILITY_VERSION = 1 for the two live-backend probes and DESKTOP_MANAGEABILITY_VERSION = 2 for the CLI probe. Three regression tests; reverting just the constant fails exactly those.

Comment thread studio/install_manifest.py Outdated
Comment on lines +98 to +99
except OSError:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Abort when the previous manifest cannot be removed

Do not continue into the dependency pass after an OSError here. If the existing manifest is read-only or temporarily locked, particularly on Windows, this silently leaves the old valid marker in place while pip mutates the environment. An interruption later in the same-version pass can then leave package/version and requirement digests unchanged enough for verify_install() to accept that old marker, so preflight may launch the partially updated backend instead of repairing it.

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.

Fixed in 6139f27: remove_manifest() now returns whether the marker is really gone and the installer stops when it is not, rather than running the dependency pass behind a manifest that still names this version and these digests.

Comment thread studio/install_python_stack.py Outdated
Comment on lines +3092 to +3096
install_manifest.write_manifest(
req_root = REQ_ROOT,
steps_total = _TOTAL,
package_name = package_name,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fail the installer when recording completion fails

Check the return value from write_manifest() and return a nonzero installer status when it is None. If the venv root cannot create or replace the marker because of permissions, locking, or exhausted storage, all dependency commands can succeed and this function still prints installed and exits 0; the desktop's post-repair probe then remains stale and users enter a repair loop even though the installer reported success.

Useful? React with 👍 / 👎.

The capability cache keyed the venv on pyvenv.cfg, uv.lock, requirements.txt,
the interpreter and site-packages/unsloth_cli/commands/studio.py, none of which
a repair touches when it only reinstalls studio.txt. So an entry cached while
the install was healthy stayed valid after the manifest was dropped, and the
probe returned Ready on exactly the half-built venv this is meant to catch.
@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

if let Some(fingerprint) = managed_bin_fingerprint(&bin) {
if read_cached_capability(&fingerprint).is_some() {
info!(
"Managed preflight: using cached desktop capability for {:?} in {}ms",
bin,
started.elapsed().as_millis()
);
return ManagedProbe::Ready { bin };

P2 Badge Revalidate dependencies before accepting a cached capability

After one healthy probe populates the capability cache, removing or corrupting a Studio dependency does not change any fingerprinted marker: the manifest, CLI script, interpreter, and requirements files remain untouched, and unsloth -h still succeeds because backend imports are lazy. This branch therefore returns Ready without rerunning desktop-capabilities, even though verify_install() would now report studio_deps_missing, and the desktop launches a backend that fails to import. Include installed-distribution state in the fingerprint or rerun the install verification before serving a cached ready result.

ℹ️ 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 thread unsloth_cli/_studio_deps.py Outdated
"reason": None,
}
try:
return module.verify_install()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Verify the managed venv instead of the invoking prefix

When desktop-capabilities or verify-install is invoked by a CLI outside the managed Studio venv, _install_state() supplies the managed venv through extra_roots, but this call still runs verify_install() without a root or matching requirements root. The loaded helper consequently reads the manifest from sys.prefix and hashes the invoking wheel's requirements, so a complete install under STUDIO_HOME/unsloth_studio is reported incomplete (or version-stale). Pass the selected managed root and its requirements directory through to the verifier.

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.

Partly fixed. c103387 passes the managed root to verify_install(), but _manifest_candidates() still yields the caller's own copy first, and the wheel ships studio/, so a CLI installed outside the managed venv still loads its own module. The desktop is unaffected (Tauri always invokes the managed bin) and so are setup.sh/setup.ps1 (they use the managed python directly); the remaining case is verify-install or desktop-capabilities run from a separate pip install. Tracking it rather than reordering the module search here, since that also changes the editable-install path and the deliberate shadowed-tree detection.

Comment thread studio/install_manifest.py Outdated
Comment on lines +235 to +238
installed = _installed_version(package_name)
recorded = manifest.get("package_version")
if installed and recorded and installed != recorded:
reason = "studio_install_version_changed"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate the package recorded in the manifest

For the supported unsloth studio update --package <name> testing path, the installer records <name> and its version in the manifest, but subsequent checks always query the default unsloth distribution. If the original unsloth installation remains alongside a differently versioned staging package, every capability probe reports studio_install_version_changed, causing the desktop and setup fast path to repeatedly repair an otherwise complete install. Use the manifest's package value when selecting the installed distribution.

Useful? React with 👍 / 👎.

Comment thread unsloth_cli/_studio_deps.py Outdated
Comment on lines +131 to +132
typer.echo(" Studio install: unsloth studio update", err = True)
typer.echo(' Plain pip: pip install "unsloth[studio]"', err = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recommend an extra that supplies the triggering dependency

For commands such as unsloth train, a lightweight core installation reaches the newly wrapped import of core.training.trainer and raises ModuleNotFoundError for torch (and can similarly fail on transformers or trl). The emitted plain-pip repair installs only unsloth[studio], whose new dependency list contains none of those ML packages, so following the instruction leaves the command failing in the same place; _missing_packages() can also omit the triggering module whenever any studio.txt dependency is absent. Preserve exc.name in the diagnostics and recommend the appropriate ML extra for these callers.

Useful? React with 👍 / 👎.

Comment thread studio/install_python_stack.py Outdated
Comment on lines +3092 to +3096
install_manifest.write_manifest(
req_root = REQ_ROOT,
steps_total = _TOTAL,
package_name = package_name,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fail installation when the completion manifest cannot be written

write_manifest() returns None on any write or replace failure, but the installer ignores that result and immediately reports the installation as successful. If the venv root is temporarily unwritable, full, locked by another concurrent update, or blocked by Windows file protection, setup exits zero without the marker that the new preflight requires; the next desktop launch therefore classifies the just-completed install as stale and starts another repair, potentially indefinitely. Treat a failed final manifest write as an installation error or at least a nonzero completion state.

Useful? React with 👍 / 👎.

Fail the install when the completion manifest cannot be written, instead of
exiting 0 without the record every later check requires, which is a repair
loop by construction.

Compare the version of the package the manifest names, so `studio update
--package X` does not read as a permanent version change.

Read the manifest from the venv that owns it when the CLI runs outside the
managed venv, and drop the dependency verdict in that case: the walk ran
against the wrong interpreter and says nothing about that venv.

Name the import that actually failed. `unsloth train` reaches torch through
the same guard, and the studio extra does not carry it, so recommending that
extra alone left the command failing in the same place.
unsloth_cli/commands/start.py imports click at module scope and
unsloth_cli/__init__.py imports that module, so every unsloth command needs
it. typer carried click through 0.19 and dropped it in 0.27, and the declared
floor is typer>=0.12.0, so a fresh resolve gets no click. On the published
wheel it still arrives because huggingface_hub requires click<9,>=8.4.2, which
is luck rather than a declaration. A wheel built from this branch's
dependency list has neither, and every command dies at import.

Verified: before, `unsloth --help` on a fresh venv raised ModuleNotFoundError
for click; after, it exits 0. The drift test now covers it.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Jul 27, 2026
The manageability bump gated two unrelated things through one constant. For
the managed CLI probe 2 is right: a CLI reporting 1 cannot answer
studio_install_ok. For a RUNNING backend it is wrong, because a process
already started cannot change what it reports, so bumping studio/backend/main.py
in lockstep does not help one the previous app version spawned.

That backend is proven ours by root id and ownership token, but
lifecycle_control_block_reason returned Unmanageable, and that branch never
calls adopt_verified_backend. has_owned_backend() stays false, so Repair falls
into block_external_conflict, which finds the same process and refuses: the app
could no longer stop a backend it owns the token for. The same regression in
backend.rs turned a terminal-launched same-root server from AttachedReady into
ExternalConflict.

Split the constant: DESKTOP_BACKEND_MANAGEABILITY_VERSION = 1 for the two
live-backend probes, DESKTOP_MANAGEABILITY_VERSION = 2 for the CLI probe. Every
real gate (protocol, auth, ownership, desktop-login, MIN_DESKTOP_BACKEND_VERSION)
is untouched, so an old backend still reaches OwnedStale, adopt, stop, repair.

Also stop the installer when the stale manifest cannot be removed. Windows
raises on a read-only or locked file, and the pass would then run behind a
marker that still names this version and these digests, so a run killed
part-way would verify as complete.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 6139f27239

ℹ️ 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 +33 to +34
yield _PACKAGE_ROOT / "studio" / "install_manifest.py"
roots: List[Path] = [Path(sys.prefix), *extra_roots]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Prefer the requested managed root when loading the manifest

When unsloth studio verify-install or desktop-capabilities is run from a CLI installed outside the managed Studio venv, this unconditional first candidate loads that CLI's own helper before any extra_roots entry. _venv_root_for_module() consequently verifies the current interpreter's prefix rather than STUDIO_HOME/unsloth_studio, so a healthy managed install can be reported as incomplete (or vice versa). Search the explicitly requested managed roots before falling back to _PACKAGE_ROOT/sys.prefix.

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.

Fixed properly in 0d32e58, and you were right that my earlier partial fix did not cover it. Selecting the root is not sufficient: _installed_version() reads the running interpreter and req_root defaulted to the caller's studio.txt, so even with the right root both checks still answered for the wrong venv, producing a false studio_install_version_changed and studio_install_requirements_changed. verify_install() now takes that venv's own metadata, enumerated with Distribution.discover(context = DistributionFinder.Context(path = [...])), which I verified reads a foreign site-packages (273 distributions) and returns 0 for a nonexistent path rather than falling back to sys.path. The candidate order is untouched, so the shadowed-tree detection behaves exactly as before.

Comment thread studio/install_python_stack.py Outdated
Comment on lines +2716 to +2720
# Drop it up front: if this run is interrupted, the missing manifest is what
# tells the CLI, setup.sh and the preflight that the venv is half-built.
# Stop if it survives rather than mutate the venv behind a marker that still
# reads as valid; that is the half-installed launch this is meant to prevent.
if not install_manifest.remove_manifest():

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 Remove the manifest before PowerShell mutates dependencies

On Windows updates that enter the dependency path, setup.ps1 upgrades pip and may reinstall PyTorch/Triton before invoking install_python_stack.py at line 3301, so this is not actually the first mutation. If the desktop terminates the updater during one of those earlier installs, the old manifest remains valid; the package version and studio.txt metadata can still pass verification even though Torch was left partially replaced, causing preflight to launch a broken backend instead of repairing it. Invalidate the marker in setup.ps1 before its first Fast-Install, or otherwise move all dependency mutations behind this removal.

Useful? React with 👍 / 👎.

Comment on lines +22 to +26
// Must be in the fingerprint, not just in the cached answer: a repair
// reinstalling only studio.txt leaves every other marker untouched, so a
// cache entry written while healthy would still be served after the
// manifest was dropped. Name mirrors install_manifest.MANIFEST_NAME.
"unsloth_install_manifest.json",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Invalidate cached readiness when dependencies change

After one healthy preflight has cached studio_install_ok=true, uninstalling or losing a Studio package such as fastmcp does not alter this manifest or any other fingerprinted marker. The subsequent unsloth -h probe still succeeds, so read_cached_capability() returns the old healthy result without rerunning desktop-capabilities; the backend then fails while importing the missing package. Either avoid caching the dependency-presence result or include the checked distributions' metadata in the fingerprint.

Useful? React with 👍 / 👎.

Comment thread unsloth_cli/_studio_deps.py Outdated
Comment on lines +141 to +142
trigger = exc.name or ""
from_studio = not trigger or trigger in studio_missing

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Map import names to their Studio distributions

When a dependency's import name differs from its distribution name, this membership test misclassifies it as a non-Studio dependency. For example, a missing PyJWT installation raises ModuleNotFoundError for jwt, while studio_missing contains pyjwt, so the CLI prominently recommends pip install jwt, which installs a different package and does not repair the backend; the same issue applies to names such as docx versus python-docx. Resolve import names to the owning requirement before constructing the remediation.

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.

Fixed in 0d32e58. Confirmed against PyPI that each import name is a real but unrelated project, so the advice actively installed the wrong thing: jwt is a different JWT library from PyJWT, docx is a 2007-era Word module rather than python-docx, and fitz is 'Workflow Mangement for neuroimaging data', nothing to do with pymupdf. The import is now mapped to its owning distribution before the from_studio decision, so the plain-pip line can never name an import owned by a Studio distribution, and a dotted name from a partial install (fastmcp.server) resolves to its top-level package instead of being offered verbatim.

The guard matched ModuleNotFoundError.name, an import name, against
missing_requirements(), which returns distribution names. So a missing PyJWT
printed 'pip install jwt', and jwt, docx and fitz are each a real but unrelated
PyPI project (fitz is a neuroimaging workflow tool), so following the advice
installed the wrong package and left the backend just as broken. Map the import
to its distribution before deciding, and never offer the import itself.

install_state() verified the caller's own prefix. The wheel ships studio/, so a
CLI installed outside the managed venv always finds its own copy of the helper
first, and a healthy managed install reported studio_install_incomplete with a
missing list copied from the wrong venv. Selecting the root is not enough:
_installed_version() reads the running interpreter and req_root defaults to the
caller's studio.txt, so both checks still answered for the wrong venv. Hand
verify_install() that venv's own metadata, enumerated through
Distribution.discover(context = ...path), which does not fall back to sys.path.
The candidate order is untouched, so shadowed-tree detection is unchanged.

setup.ps1 replaces pip, torch and triton before install_python_stack.py runs,
so the manifest it drops is not dropped before the first mutation. A run killed
in between kept a marker that still verifies while torch was half-replaced;
drop it at the top of the dependency pass instead. setup.sh is unaffected, the
stack is the first thing its pass runs, and a test now pins both.

pip uninstall rewrites nothing that was fingerprinted, and cache_matches
re-reads the cached studio_install_ok rather than re-checking, so a venv that
lost a studio.txt package kept being served the healthy verdict. Fold a sorted
hash of the installed dist-info names into the marker hash.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 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: d0c589883e

ℹ️ 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 thread unsloth_cli/_studio_deps.py Outdated
Comment on lines +160 to +163
module = load_install_manifest_module(extra_roots)
if module is None:
return {
"ok": True,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat a missing manifest helper as incomplete

When a current CLI survives but its bundled studio/install_manifest.py is absent—for example after a partial/corrupted package update—this branch reports studio_install_ok=true. Because this same CLI advertises manageability version 2, the Rust preflight accepts the result and launches a backend whose studio/backend/run.py may also be missing, recreating the unexpected-stop failure. An older installation cannot execute this newly added _studio_deps.py, so failure to load its required helper should be treated as an incomplete install rather than a permissive success.

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.

Correct, and the packaging settles it: studio is a real package in packages.find, so setuptools ships every top-level studio/*.py in the same wheel as unsloth_cli/_studio_deps.py. I listed the published 2026.7.5 wheel's central directory to check, and all six top-level studio modules are in it. Nothing legitimately has _studio_deps.py without install_manifest.py, and a CLI predating both never reaches this code at all, so the permissive branch could only ever describe a torn tree.

2e00001 reports studio_install_manifest_missing instead, which makes the capability studio_install_ok=false, so the preflight goes to ManagedStale and repair runs rather than launching a backend whose run.py may be just as absent. Regression test added; the suite is unchanged otherwise.

studio/install_manifest.py ships in the same wheel as _studio_deps.py, so
nothing legitimately has one without the other: a CLI predating both never
reaches this code, and the desktop already calls such a CLI stale on
desktop_manageability_version.

Returning ok=true there reported a healthy install for a tree the package
update had half replaced, and the preflight then launched a backend whose
own run.py could be just as absent. Report it incomplete so repair runs.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 27, 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. Chef's kiss.

Reviewed commit: 2e000019a3

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

@wasimysaid

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 35458aa9af

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

@wasimysaid
wasimysaid merged commit 1781770 into main Jul 28, 2026
72 of 76 checks passed
@wasimysaid
wasimysaid deleted the fix/studio-incomplete-install-detection branch July 28, 2026 08:57

@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

payload["version"] = package_version("unsloth")

P2 Badge Report the tested package version to preflight

For unsloth studio update --package <name>, the manifest now records and verifies <name>, but desktop-capabilities still publishes the hard-coded unsloth distribution version. Fresh evidence beyond the prior manifest-version issue is that the Rust preflight gates this version field after studio_install_ok, so a staging package install can verify complete and still be classified stale because the old/missing unsloth distribution is reported instead of the manifest package. Use the manifest package/version from _install_state() (or the same package selection) for this payload.

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

Comment thread pyproject.toml
# test_studio_extra_matches_requirements.py catches drift.
studio = [
"typer",
"fastapi",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add multipart support to the Studio extra

When users follow the new Plain pip: pip install "unsloth[studio]" remediation in an environment where nothing else has pulled it transitively, this extra installs bare fastapi but not python-multipart. The backend imports routes.data_recipe at startup, and seed.py declares UploadFile = FastAPIFile(...) plus Form(...); FastAPI raises during route construction if python-multipart is absent, which is why the new wheel smoke still installs python-multipart separately before importing studio.backend.main. Add it here (or use an extra that includes it) so the advertised repair actually produces a bootable Studio server.

Useful? React with 👍 / 👎.

Comment thread pyproject.toml
"uvicorn",
"pydantic",
"packaging",
"matplotlib==3.10.9",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the Studio extra installable on Python 3.9

The project still declares Python 3.9 support, and the new missing-dependency guidance tells plain-pip users to run pip install "unsloth[studio]"; on Python 3.9 this added extra cannot resolve because matplotlib==3.10.9 declares Requires-Python >=3.10. Either gate this pin with a Python-version marker and provide a 3.9-compatible alternative, or make the advertised Studio extra explicitly require Python >=3.10 so supported 3.9 CLI installs are not given an impossible repair command.

Useful? React with 👍 / 👎.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
The interrupted-install check had two implementations, and they diverged. The
PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could
not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact
signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no
matter how well they worked, and I nearly read that as "neither PR fixes it".

A probe that cannot observe the fix is worse than no probe, so there is now a
single Python implementation used on macOS, Linux and Windows. Python is
guaranteed present after an install, which is what makes one file viable.

It also owns the process tree it spawns. Terminating just the parent left
uvicorn/python children holding the port, which hung the healthy case outright --
the same process-group lesson as the interrupt driver.

Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest ->
REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Jul 28, 2026
The interrupted-install check had two implementations, and they diverged. The
PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could
not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact
signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no
matter how well they worked, and I nearly read that as "neither PR fixes it".

A probe that cannot observe the fix is worse than no probe, so there is now a
single Python implementation used on macOS, Linux and Windows. Python is
guaranteed present after an install, which is what makes one file viable.

It also owns the process tree it spawns. Terminating just the parent left
uvicorn/python children holding the port, which hung the healthy case outright --
the same process-group lesson as the interrupt driver.

Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest ->
REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv
that is already broken. Confirmed: neither PR touches cleanup_child_processes.

Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the
installer's process group. In the reported session that landed at "5/10 studio
deps", so the venv kept the CLI's dependencies and lost the server stack, and the
next launch died on `import structlog`. Three minutes of installing, destroyed
with no warning and no way back.

So ask. Only from the tray Quit item -- a deliberate action with a UI present. The
RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a
dialog nobody can answer. The call already runs off the menu callback thread,
which is also what blocking_show requires.

Closing the window was already safe (it hides to tray); this closes the remaining
way to lose an install by accident.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
Reported macOS session: the user quit the app during the dependency pass. That
SIGTERMs the installer process group (main.rs cleanup_child_processes ->
install::stop_install), and it landed in the "studio deps" step -- the one that
installs studio/backend/requirements/studio.txt, where structlog is declared. The
venv kept the CLI's own dependencies and lost the server stack.

On relaunch, preflight probed `unsloth -h` (ok in 1601ms) and
`studio desktop-capabilities` (ok in 143ms). Both passed, because typer/click/rich
are core deps -- so the app reported disposition=ManagedReady with
can_auto_repair=false. The backend then died with

    ModuleNotFoundError: No module named 'structlog'

and the UI showed "Server stopped unexpectedly": no cause, no action, no way out.

The evidence was already in hand. The app captures that stderr into proc.logs and
never read it. A failed import is ground truth in a way a probe cannot be -- a
probe only checks what someone thought to check, which is exactly how two passing
probes sat on top of an unbootable venv. So classify the exit from the traceback,
send an incomplete install to the existing repair flow, and keep the generic
message for everything else.

Two details worth keeping:

The traceback arrives on STDERR while crash detection runs in the STDOUT reader,
so they race. Reading immediately would usually miss it and mislabel a broken
install as a plain crash, hence the short bounded poll after the lock is released
-- once the process has exited the stderr pipe is at EOF and drains in
milliseconds.

The auto-repair is latched to once per session. A repair that does not fix the
import would otherwise crash -> repair -> crash forever.

Complementary to unslothai#7492 and unslothai#7490 rather than a replacement: they stop the venv
being reported ready, this makes the failure recoverable if anything still slips
through.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv
that is already broken. Confirmed: neither PR touches cleanup_child_processes.

Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the
installer's process group. In the reported session that landed at "5/10 studio
deps", so the venv kept the CLI's dependencies and lost the server stack, and the
next launch died on `import structlog`. Three minutes of installing, destroyed
with no warning and no way back.

So ask. Only from the tray Quit item -- a deliberate action with a UI present. The
RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a
dialog nobody can answer. The call already runs off the menu callback thread,
which is also what blocking_show requires.

Closing the window was already safe (it hides to tray); this closes the remaining
way to lose an install by accident.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
The interrupted-install lanes ran install.sh without --local, so install.sh:3996
resolved unsloth from PyPI and the venv got the published CLI. Every probe of
`studio verify-install` and `studio desktop-runtime-check" then reported
'absent' regardless of the branch, so the lanes could not observe the fixes they
exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490.

Also stand in for the desktop app's .desktop-install-in-progress marker. We kill
install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was
missing for a reason unrelated to unslothai#7490.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
The interrupted-install lanes ran install.sh without --local, so install.sh:3996
resolved unsloth from PyPI and the venv got the published CLI. Every probe of
`studio verify-install` and `studio desktop-runtime-check" then reported
'absent' regardless of the branch, so the lanes could not observe the fixes they
exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490.

Also stand in for the desktop app's .desktop-install-in-progress marker. We kill
install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was
missing for a reason unrelated to unslothai#7490.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
Reported macOS session: the user quit the app during the dependency pass. That
SIGTERMs the installer process group (main.rs cleanup_child_processes ->
install::stop_install), and it landed in the "studio deps" step -- the one that
installs studio/backend/requirements/studio.txt, where structlog is declared. The
venv kept the CLI's own dependencies and lost the server stack.

On relaunch, preflight probed `unsloth -h` (ok in 1601ms) and
`studio desktop-capabilities` (ok in 143ms). Both passed, because typer/click/rich
are core deps -- so the app reported disposition=ManagedReady with
can_auto_repair=false. The backend then died with

    ModuleNotFoundError: No module named 'structlog'

and the UI showed "Server stopped unexpectedly": no cause, no action, no way out.

The evidence was already in hand. The app captures that stderr into proc.logs and
never read it. A failed import is ground truth in a way a probe cannot be -- a
probe only checks what someone thought to check, which is exactly how two passing
probes sat on top of an unbootable venv. So classify the exit from the traceback,
send an incomplete install to the existing repair flow, and keep the generic
message for everything else.

Two details worth keeping:

The traceback arrives on STDERR while crash detection runs in the STDOUT reader,
so they race. Reading immediately would usually miss it and mislabel a broken
install as a plain crash, hence the short bounded poll after the lock is released
-- once the process has exited the stderr pipe is at EOF and drains in
milliseconds.

The auto-repair is latched to once per session. A repair that does not fix the
import would otherwise crash -> repair -> crash forever.

Complementary to unslothai#7492 and unslothai#7490 rather than a replacement: they stop the venv
being reported ready, this makes the failure recoverable if anything still slips
through.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
The interrupted-install check had two implementations, and they diverged. The
PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could
not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact
signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no
matter how well they worked, and I nearly read that as "neither PR fixes it".

A probe that cannot observe the fix is worse than no probe, so there is now a
single Python implementation used on macOS, Linux and Windows. Python is
guaranteed present after an install, which is what makes one file viable.

It also owns the process tree it spawns. Terminating just the parent left
uvicorn/python children holding the port, which hung the healthy case outright --
the same process-group lesson as the interrupt driver.

Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest ->
REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv
that is already broken. Confirmed: neither PR touches cleanup_child_processes.

Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the
installer's process group. In the reported session that landed at "5/10 studio
deps", so the venv kept the CLI's dependencies and lost the server stack, and the
next launch died on `import structlog`. Three minutes of installing, destroyed
with no warning and no way back.

So ask. Only from the tray Quit item -- a deliberate action with a UI present. The
RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a
dialog nobody can answer. The call already runs off the menu callback thread,
which is also what blocking_show requires.

Closing the window was already safe (it hides to tray); this closes the remaining
way to lose an install by accident.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 28, 2026
The interrupted-install lanes ran install.sh without --local, so install.sh:3996
resolved unsloth from PyPI and the venv got the published CLI. Every probe of
`studio verify-install` and `studio desktop-runtime-check" then reported
'absent' regardless of the branch, so the lanes could not observe the fixes they
exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490.

Also stand in for the desktop app's .desktop-install-in-progress marker. We kill
install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was
missing for a reason unrelated to unslothai#7490.
danielhanchen added a commit that referenced this pull request Jul 28, 2026
…lure (#7569)

The manifest-removal guard added in #7492 exits with a bare 'exit 1', so in
Tauri mode the installer never emits the [TAURI:ERROR] line and the desktop
UI falls back to a generic failure instead of naming the cause. Every other
failure path in studio/setup.ps1 goes through Exit-SetupFailure, and
tests/sh/test_tauri_retry_failure_context.sh asserts that invariant, so
'Repo tests (CPU)' has been red on main since that merge.

Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit that referenced this pull request Jul 29, 2026
* Desktop: ask before quitting on top of a running install

This is the trigger neither #7492 nor #7490 addresses -- both start from a venv
that is already broken. Confirmed: neither PR touches cleanup_child_processes.

Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the
installer's process group. In the reported session that landed at "5/10 studio
deps", so the venv kept the CLI's dependencies and lost the server stack, and the
next launch died on `import structlog`. Three minutes of installing, destroyed
with no warning and no way back.

So ask. Only from the tray Quit item -- a deliberate action with a UI present. The
RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a
dialog nobody can answer. The call already runs off the menu callback thread,
which is also what blocking_show requires.

Closing the window was already safe (it hides to tray); this closes the remaining
way to lose an install by accident.

* Tighten comments in desktop quit-during-install guard

* Condense comments in quit-during-install guard

---------

Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit that referenced this pull request Jul 29, 2026
#7552)

* CI: prove an interrupted install can never masquerade as a healthy one

Nothing in CI had ever interrupted an install, which is how the reported failure
shipped: quit the desktop app mid-install, the app SIGTERMs the installer process
group, and if that lands during 'studio deps' the venv loses structlog. Preflight
then probes 'unsloth -h' and 'studio desktop-capabilities', both of which succeed
because the CLI's own deps are core, so the app reported ManagedReady with
can_auto_repair=false while the backend died on import. A permanent dead end.

This kills the installer at each interesting phase and asserts the result is
either genuinely healthy or explicitly repairable, never silently ready. 13 legs
across macos-14, ubuntu-latest and windows: each of the dependency-pass steps
plus the coarse phases (venv, torch, unsloth, setup).

The kill targets the process GROUP, matching install.rs. Killing only the leader
leaves uv and python children to finish the dependency pass, and the test would
quietly prove nothing. Windows has no process groups, so that leg walks the CIM
parent links instead, which is the same reason the app carries windows_job.rs.

One shared probe for all platforms. The Windows check used to be bespoke inline
PowerShell that only ran -h and desktop-capabilities, so it could not observe
studio_install_ok, verify-install or desktop-runtime-check: it would have
reported FALSE_READY for the very PRs that add them, no matter how well they
worked. The probe boots the backend as ground truth and owns the whole process
tree, since terminating only the parent leaves children holding the port.

install.sh runs with --local, which is load-bearing rather than a convenience:
without it the installer resolves unsloth from PyPI and the venv gets the
PUBLISHED CLI, so no branch-side change is present and every deeper probe reports
'absent' regardless of what the branch does.

Verified: against a tree without the detection, windows kill@studio-deps reports
FALSE_READY, reproducing the user report exactly. With #7492 merged the same leg
reports REPAIRABLE, and all 13 legs pass.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the POSIX legs actually run the installer, and fail if they do not

install.sh --tauri rejects a custom UNSLOTH_STUDIO_HOME outright (the desktop app
still uses the legacy ~/.unsloth/studio root), and this workflow set one at
workflow level for every job. So all 11 macOS and Linux legs exited about a second
in with

    ERROR: UNSLOTH_STUDIO_HOME is not supported with --tauri.

produced no CLI, took the probe's NO_CLI 'safe' branch and reported success. They
were vacuously green. Only the two Windows legs were real, because install.ps1 has
no equivalent guard.

The override now applies to the Windows job only, and the POSIX legs read the
legacy root, which is where --tauri installs. The runner is ephemeral so the real
home is as disposable as the override.

Also adds the check that makes this class of mistake loud: a leg asserts its kill
actually landed on the marker it was aimed at, using the interrupt_reason the
driver already records. A leg that never reached its kill point proves nothing,
and NO_CLI made that indistinguishable from a pass.

* Make the interrupted-install legs able to fail

The probe treated a present .desktop-install-in-progress marker as proof of a
repairable state, but the drivers seed it unconditionally and never clear it, so
REPAIRABLE was unconditional and FALSE_READY unreachable. The Windows leg had no
kill-landed guard, blanket continue-on-error, and no repair re-run; -SkipTorch
was silently dropped, since install.ps1 parses only --no-torch.

Judge the re-run by whether the backend boots, on both platforms. The log grep
matched the frontend build printing "up to date" and failed a leg whose venv
was fine.

* Drop the interrupt cell that could never be interrupted

install.sh --local sets skip_base, so install_python_stack returns before any
"base packages" label is printed. The kill had nothing to land on and the
installer ran to completion, reaching [TAURI:DONE] in 62s.

* Fail the leg when the installer finished instead of being killed

The driver set reason=marker-hit before the post-marker sleep and never
rechecked, so a step whose work was already cached could run to completion
inside that beat and still be recorded as an interruption. The landing assertion
tests reason != marker-hit, so a fully completed install passed green having
interrupted nothing. Reproduced with a stub that exits during the delay:
reported marker-hit / killed=true / exit=0 next to "install finished fully".
Set the reason after the sleep, on both drivers.

Also trigger on _studio_deps.py and install_manifest.py, where the two decisions
the probe asserts on are actually implemented.

* Kill the group, and stop the probe blocking on a full pipe

The escalation was gated on the leader still being alive, so a leader that exits
promptly on SIGTERM while a uv or python descendant ignores it skipped the
SIGKILL entirely, and wait reaped only the leader. Proven with a descendant that
traps TERM: pre-fix its heartbeat keeps ticking while the probe would be running,
post-fix it stops. Signal the group unconditionally and drain it after the reap,
since an unreaped leader is still a member of its own group.

The probe started the backend on stdout=PIPE and read nothing until after the
poll loop, so a backend logging more than the pipe buffer during import blocked
before binding. Measured 65536 bytes here; a child emitting 200 KB never reaches
its bind line, which would make backend_ok false for a healthy install. Write
straight to the artefact file.

Also trigger on studio/backend/requirements/**, where structlog is declared.

* Make the NO_CLI legs assert repair, and fix the Windows straggler sweep

Two of the interrupted-install legs were passing without testing anything.

The re-run assertion skipped verdict=NO_CLI, but a kill at "venv" or "torch"
lands before install.sh ever prints "Installing Unsloth" (:2125, :3667, :3961),
so those legs can only ever produce NO_CLI. Three non-gating-exempt cells
(macos-14 kill@venv, macos-14 kill@torch, ubuntu-latest kill@torch) therefore
asserted nothing beyond a marker appearing in a log. NO_CLI is now included:
a re-run must produce a booting backend regardless of how little the first run
managed to install. Each re-run step grows an existence check first, because
the probe exits without writing verdict.json when the binary is absent and the
json.load would crash rather than report.

The Windows straggler sweep matched nothing at all. UNSLOTH_STUDIO_HOME arrives
as D:\a\r\r/.studio-home, since the workflow joins ${{ github.workspace }} with
a forward slash, while Process.Path is all backslashes, so the literal -like
missed even the venv's own python.exe. uv is never under the studio home in any
case: install.ps1 takes it from winget or astral.sh. Normalise the separators,
match uv by name (the runner is ephemeral and runs no other uv), and skip the
home comparison entirely when the variable is empty, which would otherwise turn
the pattern into "**" and kill every python on the runner.

* Run the Windows legs as the desktop does, and judge repair by what preflight reads

The Windows matrix set a workspace-scoped UNSLOTH_STUDIO_HOME, which forces
install.ps1 down the shell-install path: install.ps1:189-215 rejects a custom
root under --tauri, so those legs ran with UNSLOTH_TAURI_MODE=0, the frontend
build on and no bundled-file overlay, while the desktop always spawns the
installer as --tauri with the variable scrubbed (install.rs:202 and :356). The
torch leg could not even reach its marker: "Installing PyTorch" is printed only
by Write-TauriLog (install.ps1:2440), so it was killed at the deadline. Both
legs now run --tauri --local at the default root, and the probe and re-run
resolve the CLI under %USERPROFILE%\.unsloth\studio.

The probe counted `studio verify-install` and `studio desktop-runtime-check`
failures as proof the app can repair, but preflight/managed.rs runs only `-h`
and `studio desktop-capabilities --json` (:357) and reads studio_install_ok from
that payload (:445); neither deeper command is invoked anywhere under
studio/src-tauri. A leg where capabilities regressed to ready while only those
standalone commands saw the damage would have passed green with the app stuck on
ManagedReady, which is the exact false negative this workflow exists to catch.
They are still run and recorded in verdict.json, just no longer repair evidence.

An interrupted install can leave the console script in place while its venv
interpreter is gone. The probes go through run(), which catches OSError, but the
backend spawn did not, so the probe aborted before writing verdict.json and both
workflows died on the json.load instead of reporting. That state is now recorded
as backend_spawn_error and lands on REPAIRABLE, which is what `-h` failing
already implies.

On win32 the CLI re-spawns the server as a child and waits on it
(unsloth_cli/commands/studio.py:1543), and CREATE_NEW_PROCESS_GROUP does not
make terminate() reach descendants, so the reap left a server holding the venv
open while the repair step reinstalled into files Windows had locked. Use
taskkill /F /T for the tree. The straggler sweep now falls back to the default
studio root, since under --tauri there is no UNSLOTH_STUDIO_HOME to match on.

* Judge the install the way preflight does, and reap the whole probe group

Read desktop-capabilities the way the desktop reads it. preflight/managed.rs
pipes stdout and sends stderr to /dev/null (managed.rs:358), then hands the
whole stdout buffer to serde_json (managed.rs:414). The probe concatenated both
streams and scanned to the first brace, so a single diagnostic line on stderr
made json.loads raise on the trailing text, studio_install_ok stayed "absent",
and a broken backend was reported FALSE_READY over an install the real app
parses, sees as incomplete, and offers to repair. That fails a valid recovery
change for a reason that exists only in the probe. stdout and stderr are now
captured separately and stdout is parsed strictly; a payload that does not parse
counts as repair evidence, matching the Stale the desktop reports when the
capability probe returns nothing (managed.rs:521).

A booting backend alone is not a finished install. The manifest is written last
(install_python_stack.py:3255), so a kill after "studio deps" but before it, the
data-designer leg, leaves a venv whose backend boots while desktop-capabilities
still reports studio_install_ok=false and preflight reports Stale
(managed.rs:445). Calling that HEALTHY skipped the re-run step, so the leg
asserted nothing beyond a marker appearing and never exercised the version fast
path that is supposed to clear an incomplete install, which is the half of the
bug that strands the user. HEALTHY now requires both.

Escalate to the process group after reaping the probe's backend. reap() returned
as soon as proc.wait() succeeded, and the leader exits promptly on SIGTERM while
a uvicorn worker does not, so the SIGKILL iteration was skipped and that worker
kept the port and the venv open while the repair step reinstalled underneath it.
It also read os.getpgid(proc.pid) after the reap, which raises. The pgid is now
captured up front and SIGKILL always goes to the group, the same escalation
interrupt-install.sh:94 makes. A heartbeat experiment left the group alive with
the old sequence and empty with the new one.

Trigger the workflow on pyproject.toml. Every leg installs the checkout with
--local, so that file decides the unsloth console script and the core
dependencies the probe leans on: -h and desktop-capabilities only survive a torn
install because typer/click/rich are declared there. No other install workflow
interrupts the installer, so such a change would otherwise merge without a
single leg running.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Judge an absent capability field and a dead -h the way preflight does

The probe left studio_install_ok=absent undecided and judged those installs on
whether the backend booted. preflight/managed.rs:445 tests studio_install_ok
!= Some(true), so an absent field is Stale exactly like a false one; a CLI too
old to carry it is already rejected one check earlier on
desktop_manageability_version. The gap mattered in both directions: a payload
that stopped carrying the field reported HEALTHY on every booting leg and
skipped the re-run assertion this workflow exists to make, and a torn venv with
a working -h was failed as FALSE_READY even though the app would have offered
repair. unsloth_cli/commands/studio.py is in this workflow's path filter
precisely to catch that class of change, so it must not be the thing that
silences it.

The verdict also consulted cli_h_ok only in the repairable arm, so a CLI that
cannot print help was called HEALTHY whenever the backend happened to boot.
probe_managed_bin runs -h first and returns Stale cli_unusable before it ever
reaches the capability probe (managed.rs:465-478), so that install goes to
repair in the real app and the leg must assert it here.

* Judge the probes on the desktop's deadline, and interrupt the host it uses

Preflight gives each managed probe ten seconds and nothing more: managed.rs:337
wraps `unsloth -h` and managed.rs:390 wraps `studio desktop-capabilities --json`
in a tokio timeout, kills the child on expiry, and returns Stale as
"cli_unusable" or "desktop_capability_probe_failed". The probe allowed three
minutes, so a venv torn badly enough that its CLI only answers after half a
minute of retries was recorded HEALTHY here while the real app shows it as
repairable. That skips the re-run assertion the leg exists to make, which is the
same false-HEALTHY hole the studio_install_ok and -h gating already closed. Both
calls now use the desktop's ten seconds, and the elapsed time is recorded so a
leg that flips for timing reasons says so in the artefact.

On Windows the installer child now runs where the desktop runs it. install.rs
325-339 spawns the bundled install.ps1 as powershell.exe with -NoLogo -NoProfile
-NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File, so Windows
PowerShell 5.1 is the only host a real desktop install ever uses. The interrupted
run and the repair re-run both used pwsh 7, and every other Windows job in
.github runs install.ps1 under pwsh too, so the installer's behaviour on 5.1 was
covered by nothing: .NET Framework instead of .NET, OEM console encoding instead
of UTF-8, and different native-command and OSArchitecture reporting are all real
sources of divergence. A workflow whose point is to reproduce what the app does
cannot run a different interpreter than the app does. The driver itself stays
under pwsh; only the installer child and the repair invocation change.

* Tighten the interrupted-install comments

* Tighten the probe docstrings

* Fail the leg when the installer completed inside the kill window

* Land the kill in the marked step, and reject non-boolean capabilities

Two holes found from the staging run's own logs.

The venv leg never interrupted the venv step. Creating the venv takes ~0.1s, so
by the time the 1s poll noticed its line the installer was already in
"Installing PyTorch", and the flat 3s beat sent the signal there: staging run
30419729244 shows both step lines in the tail and a kill 4s in. That made the
leg a duplicate of the torch leg while its label claimed otherwise. Both
drivers now poll in half-second slices, cut the beat short the moment a later
[TAURI:STEP] line appears, and print the step the signal actually landed in,
warning when it is not the marked one. Sub-step markers such as "studio deps"
print no step line, so they keep the whole beat and never warn.

studio_install_ok is Option<bool> (managed.rs:43), so serde rejects a
non-boolean and the whole payload fails to deserialize, which the desktop
reports as Stale. bool() read a JSON string "false" as True, so the probe
called a torn install ready. Only a literal JSON true counts now.

* Tighten the interrupt driver comments

* Fail the leg when the signal landed after the marked step

The cut-short added last round only helps when the marked step is still the
last [TAURI:STEP] line at the moment the poll notices it. Creating the venv
takes ~0.1s (staging run 30419729244: 03:31:07.371 -> 07.478), less than the
0.5s poll, so the next step's line is usually already in the log when the
marker matches, the step count never changes during the beat, and the full 3s
elapses inside "Installing PyTorch". Reproduced with a stub installer against
the driver at head: kill at 4.11s, step at kill "Installing PyTorch". The leg
then duplicates the torch leg while its matrix label claims the venv step, and
passed green on nothing but a ::warning::.

Both drivers now skip the beat entirely when the marked step is already over,
so the kill goes out at once instead of deeper into the next step, and both
record interrupt_step_mismatch in interrupt.env. The landing assertion fails on
it: a warning that cannot fail the leg proves nothing. Sub-step markers
("studio deps", "pip bootstrap") print no step line of their own and stay
exempt, as before.

The venv leg becomes experimental. Its step is shorter than any log poll can
resolve, so it must not block the PR on a race it cannot win, and it still
probes the earliest torn state whenever it does land.

* Tighten the interrupted-install workflow and driver comments

* Land the kill in the phase each leg is named for

Splitting the log on \r shows that 5 of the 12 legs of staging run 30419729244
interrupted a later phase than their label claims, and the run was fully green.
The venv leg's install.log is byte-identical to the torch leg's. So is
pip-bootstrap's to unsloth-extras'. Worse, both "studio deps" legs, the cells
that reproduce the reported bug, were killed at "7/10 data designer deps" and
"12/14 local plugin": their own probe artefacts report backend_ok=true, so
structlog was installed and the flagship cell was passing on the manifest gate
alone.

Two causes. The dependency pass rewrites ONE physical line with \r
(install_python_stack.py:2499), so its sub-steps are CR-separated segments and
a line-based check could not see one end; the drivers exempted them and warned
about nothing. And the flat 3s beat between the marker and the signal is longer
than several phases, while every phase label prints BEFORE its work starts, so
the beat pushed the signal past the phase instead of into it.

Both drivers now split on \r, track the running phase at both levels, and judge
a sub-step marker against the running sub-step and a step marker against the
running step, so a step is not "over" because the sub-steps beneath it
advanced. The beat defaults to 0 and is set per leg, 3s only for torch,
unsloth and setup, which run for minutes. The mismatch is recorded in
interrupt.env and the landing assertion fails on it, in both languages.

Both detectors were replayed against the 12 real logs from 30419729244 and
agree with the artefacts on every leg. venv and pip-bootstrap become
experimental: their phases are shorter than any log poll can resolve.

* Fail the Windows leg when the installer never exited

The driver writes installer_exit=running when the installer outlived Stop-Tree
and WaitForExit, and 'running' is not '0', so the landing assertion accepted it.
A live installer writing into the venv while the probe reads it is not an
interrupted install. Only a real integer exit code counts now, checked against
0, 143, 137, -1, running and the empty string.

* Drop the legs that cannot land, and prove the kill was delivered

Two cells never interrupted the phase they were named for. "Creating virtual
environment" runs 0.107s (staging 30419729244, 03:31:07.371 -> 07.478) and
"1/10 pip bootstrap" is over just as fast, both shorter than any poll that
watches the log, so in 30423181897 and 30424366953 the signal landed in
"Installing PyTorch" and "2/10 unsloth extras" every time. Each was another
leg wearing a false label, so they are gone rather than allowed to fail, and
continue-on-error goes with them: a leg permitted to fail asserts nothing.
The only coverage lost is a venv caught half-written, which interruption
cannot reach at this resolution; the torch leg's signal lands ~3s into a
multi-minute download, so it already leaves a complete venv with nothing
installed into it.

The landing check also accepted an installer that failed on its own. A
dependency error between the driver's last liveness check and the signal
exits non-zero, which the exit != 0 guard let through as a kill. POSIX now
requires 143 or 137, the only statuses a signal produces here and what all
ten POSIX legs of 30424366953 reported. Recording whether kill(2) returned 0
would not separate them, since the unreaped leader keeps its group alive.
Windows has no such status, so the driver records whether Stop-Process
actually terminated the installer: it throws on a process already gone, so
the flag is false exactly when there was nothing left to interrupt.

* Signal at the marker, with no beat to overshoot the phase

Staging run 30426111484 failed the macOS torch leg on the landing check: the
3s beat carried the signal from "Installing PyTorch" into "Installing
Unsloth", because the PyTorch step, which this workflow called minutes long,
finished in under three seconds. The beat only ever existed to land
mid-work, and it cannot do that safely: every label prints before its work
starts, so detection is already inside the phase, and any wait is a bet on
how long that phase runs. It lost in 30419729244 and again here.

So the beat is gone rather than retuned, and with it the matrix knob and the
driver parameter on both platforms. The landing check stays and can still
fail, since a phase shorter than one poll is seen only after it ends.

The Windows driver also polled every 500ms while its own comment claimed a
fifth of a second. That is 2.5 slices of overshoot the POSIX side does not
carry, and it is now 200ms like the POSIX loop.

* Kill the installer before its children, not after

The depth-first walk killed the child install.ps1 was waiting on and only
then the root, which races the leader's own reaction to that death. It is
not a theoretical race: in staging run 30424366953 install.ps1 had already
printed "unsloth studio setup failed (exit code -1)" by the time
Stop-Process reached it. A leader that wins the race makes Stop-Process
throw, and the new root-kill assertion would then fail a leg whose
interruption the driver really did deliver.

The tree is now snapshotted first, since a dead parent leaves nothing to
walk, then the root goes down ahead of its descendants. A dead leader cannot
react to a child and cannot respawn one either, which is what the
depth-first order was for.

* CI: give the probe the desktop's startup grace and fail a nonzero repair

The probe allowed the backend 120s to answer /api/health while the desktop
waits 5 minutes (BACKEND_STARTUP_GRACE_PERIOD, commands.rs:9), so a slow but
healthy install could be reported FALSE_READY. A broken backend exits at once
and the poll breaks on it, so the longer deadline only bounds a live backend.

The re-run step also accepted a HEALTHY probe over an installer that exited
nonzero. setup.sh does fallible sidecar and GPU setup after the manifest is
written, and the desktop returns the repair error without starting the backend
(commands.rs:615-630). The Windows leg ignored powershell.exe's status entirely.

* Tighten the interrupted-install comments

Comments only: shorter wording for the same rationale, no code touched.

* CI: raise the interrupted-install job timeout above its own deadlines

A leg configures up to 25 minutes to the marker plus two probe passes of up to
17 minutes each around a repair install, so the 60 minute limit could cancel a
slow runner mid-assertion. Legs land in 6 to 10 minutes in practice.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants