unsloth/unsloth_cli/_studio_deps.py
Daniel Han 1781770bee
Studio: detect an interrupted dependency install instead of launching a backend that cannot import (#7492)
* Studio: detect an interrupted dependency install instead of launching 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

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

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

* Match the trimmed comments merged on the pip branch

* Put the install manifest in the preflight fingerprint for PR #7492

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.

* Address the review findings on PR #7492

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.

* Declare click, which typer stopped providing, for PR #7492

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.

* Keep a running backend from the previous app version manageable

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.

* Answer for the managed venv, not the one the CLI happens to run in

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.

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

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

* A missing manifest helper is a torn install, not an old one

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.

* Tighten comments across the install-detection changes

* Validate Studio dependency readiness

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
Co-authored-by: Wasim Yousef Said <wasimysdev@gmail.com>
2026-07-28 10:57:20 +02:00

255 lines
9.4 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Studio dependency checks shared by the CLI commands.
The wheel ships studio/ and studio.backend*, so train / export / chat /
inference / studio all work after a plain `pip install unsloth` right up to the
point they import the backend. studio_backend_imports() turns the resulting
traceback into one sentence and the two commands that fix it.
Also loads studio/install_manifest.py for `unsloth studio verify-install`.
"""
from __future__ import annotations
import contextlib
import importlib.util
import inspect
import re
import sys
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence
import typer
# One parent up is the package root: site-packages, or the repo root if editable.
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent
_MANIFEST_MODULE = None
_MANIFEST_LOADED = False
def _manifest_candidates(extra_roots: Sequence[Path] = ()) -> Iterable[Path]:
yield _PACKAGE_ROOT / "studio" / "install_manifest.py"
roots: List[Path] = [Path(sys.prefix), *extra_roots]
for root in roots:
for pattern in (
"lib/python*/site-packages/studio/install_manifest.py",
"Lib/site-packages/studio/install_manifest.py",
):
yield from root.glob(pattern)
def load_install_manifest_module(extra_roots: Sequence[Path] = ()):
"""Load studio/install_manifest.py by file path, or None if unavailable.
By path for the same reason as studio.backend.run: a partial
site-packages/studio/ tree can shadow an editable install, which is exactly
what this check exists to detect.
"""
global _MANIFEST_MODULE, _MANIFEST_LOADED
if _MANIFEST_LOADED:
return _MANIFEST_MODULE
_MANIFEST_LOADED = True
for path in _manifest_candidates(extra_roots):
if not path.is_file():
continue
spec = importlib.util.spec_from_file_location("studio.install_manifest", path)
if spec is None or spec.loader is None:
continue
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except Exception:
continue
_MANIFEST_MODULE = module
return _MANIFEST_MODULE
return None
def _venv_root_for_module(module) -> Optional[Path]:
"""Prefix owning a manifest module, which may be a venv other than ours."""
path = Path(getattr(module, "__file__", "") or "")
for parent in path.parents:
if (parent / "pyvenv.cfg").is_file():
return parent
return None
def _canonical(name: str) -> str:
"""PEP 503 normalisation, so PyJWT / pyjwt / py_jwt compare equal."""
return re.sub(r"[-_.]+", "-", name).lower()
def _resolved(path: Path) -> Path:
try:
return path.resolve()
except OSError:
return path
def _venv_site_packages(root: Path) -> List[Path]:
out: List[Path] = []
for pattern in ("lib/python*/site-packages", "Lib/site-packages"):
out.extend(sorted(root.glob(pattern)))
return out
def _managed_root(extra_roots: Sequence[Path]) -> Optional[Path]:
"""A requested venv that is not the one this CLI runs in.
The wheel ships studio/, so a CLI installed outside the managed venv always
finds its own copy of the helper first; without this it would then verify
its own prefix instead of the venv it was asked about.
"""
running = _resolved(Path(sys.prefix))
for root in extra_roots:
if (root / "pyvenv.cfg").is_file() and _resolved(root) != running:
return root
return None
def _distributions_in(root: Path) -> Optional[Dict[str, str]]:
"""Canonical distribution name -> version inside another venv.
importlib.metadata reports the running interpreter only, so a foreign
site-packages has to be handed to the finder explicitly.
"""
paths = [str(path) for path in _venv_site_packages(root)]
if not paths:
return None
from importlib.metadata import Distribution, DistributionFinder
found: Dict[str, str] = {}
try:
for dist in Distribution.discover(context = DistributionFinder.Context(path = paths)):
name = getattr(dist, "name", None) or dist.metadata["Name"]
if name:
found.setdefault(_canonical(name), dist.version or "")
except Exception:
return None
return found
def _requirements_root_in(root: Path) -> Optional[Path]:
for path in _venv_site_packages(root):
reqs = path / "studio" / "backend" / "requirements"
if reqs.is_dir():
return reqs
return None
def _supports_foreign_root(module) -> bool:
"""A manifest helper predating the installed= parameter cannot describe another venv."""
try:
return "installed" in inspect.signature(module.verify_install).parameters
except (TypeError, ValueError):
return False
def install_state(extra_roots: Sequence[Path] = ()) -> dict:
"""verify_install() result, or incomplete when the helper cannot be loaded.
studio/install_manifest.py ships in the same wheel as this file, so a tree
that has one without the other is a torn install, not an old one: a CLI
predating both never reaches this code, and the desktop already calls it
stale on desktop_manageability_version. Answering yes here would launch a
backend whose own files may be just as absent.
"""
module = load_install_manifest_module(extra_roots)
if module is None:
return {
"ok": False,
"manifest_ok": False,
"deps_ok": False,
"missing": [],
"reason": "studio_install_manifest_missing",
}
# The requested managed venv is the subject, even though the helper above
# came from this CLI's own tree.
root = _managed_root(extra_roots) or _venv_root_for_module(module)
foreign = root is not None and _resolved(root) != _resolved(Path(sys.prefix))
installed = _distributions_in(root) if foreign else None
req_root = _requirements_root_in(root) if foreign else None
try:
if installed is not None and req_root is not None and _supports_foreign_root(module):
# That venv's own metadata: unreadable through this interpreter.
return module.verify_install(root = root, req_root = req_root, installed = installed)
state = module.verify_install(root = root)
if foreign and not state["deps_ok"]:
# The manifest came from another venv but the dependency walk ran
# here, so it says nothing about that venv.
state = dict(state, deps_ok = True, missing = [])
state["ok"] = state["manifest_ok"]
state["reason"] = None if state["ok"] else state["reason"]
return state
except Exception as exc:
return {
"ok": False,
"manifest_ok": False,
"deps_ok": False,
"missing": [],
"reason": f"studio_install_check_failed:{type(exc).__name__}",
}
def _missing_studio_packages() -> List[str]:
"""Studio packages studio.txt asks for and the venv does not have."""
module = load_install_manifest_module()
if module is None:
return []
try:
return list(module.missing_requirements())
except Exception:
return []
# studio.txt names distributions, ModuleNotFoundError names the import. Only
# pairs differing by more than PEP 503 normalisation need an entry, and each
# import name below is itself a real but unrelated PyPI project.
_IMPORT_TO_DISTRIBUTION = {
"jwt": "pyjwt",
"docx": "python-docx",
"fitz": "pymupdf",
}
@contextlib.contextmanager
def studio_backend_imports(feature: str = "This command", *, studio_only: bool = False):
"""Report a missing dependency as a message instead of a traceback.
Only ModuleNotFoundError is intercepted; any other ImportError from the
backend is a real bug and keeps its traceback.
"""
try:
yield
except ModuleNotFoundError as exc:
studio_missing = _missing_studio_packages()
# The failed import may not be a studio dependency at all: `train`
# reaches torch through the same wrapper, so only offer the extra when
# it helps.
trigger = exc.name or ""
# Match on the owning distribution, never the import: `pip install jwt`
# (or fastmcp.server) installs the wrong thing or nothing at all.
top = trigger.split(".", 1)[0]
needed = _IMPORT_TO_DISTRIBUTION.get(top, top)
wanted = _canonical(needed)
from_studio = not trigger or any(_canonical(name) == wanted for name in studio_missing)
if studio_only and not from_studio:
raise
typer.echo(
f"Error: {feature} needs {needed or 'a dependency'}, which is not installed.",
err = True,
)
others = [name for name in studio_missing if _canonical(name) != wanted]
if others:
typer.echo(f" also missing: {', '.join(others)}", err = True)
typer.echo("", err = True)
if not from_studio:
typer.echo(f" Install it: pip install {needed}", err = True)
if from_studio or others:
typer.echo(" Studio install: unsloth studio update", err = True)
typer.echo(' Plain pip: pip install "unsloth[studio]"', err = True)
raise typer.Exit(code = 1) from None