Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: notice a quarantined payload before trusting the update fast path (#10053)

Daniel Hanfa57a7986f3a
diff --git a/studio/install_manifest.py b/studio/install_manifest.py
index 2bb57253569..3a341ae6b09 100644
--- a/studio/install_manifest.py
+++ b/studio/install_manifest.py
@@ -504,12 +504,242 @@ def missing_requirements(
return missing
+# Shared between wheels, so one uninstall deletes another's recorded files.
+# Mirrors _SHARED_NON_RUNTIME_ROOTS in unsloth_cli/_studio_deps.py.
+_SHARED_NON_RUNTIME_ROOTS = frozenset(
+ (
+ "test",
+ "tests",
+ "doc",
+ "docs",
+ "example",
+ "examples",
+ "benchmark",
+ "benchmarks",
+ "sample",
+ "samples",
+ "scripts",
+ )
+)
+
+# `_move_launcher_aside` renames this before setup, so setup.ps1's deep check
+# sees it missing on every healthy Windows update. Nothing else is staged, so
+# nothing else is excused, or a stray sibling could hide any quarantine.
+_STAGED_LAUNCHER_NAME = "unsloth.exe"
+_STAGED_LAUNCHER_SUFFIXES = (".update-stale", ".update-backup", ".deleteme")
+
+# Rewritten in place by our own setup: the size claim is waived, absence is not.
+_INSTALLER_REWRITTEN_NAMES = frozenset(("package-lock.json",))
+
+# `npm run build` in the installed tree rehashes every asset, so RECORD names
+# files our own setup deleted. Skipped whole: they are gone, not shorter.
+_INSTALLER_REGENERATED_TREES = (("studio", "frontend", "dist"),)
+
+
+def _staged_beside(target) -> bool:
+ """Whether an absent launcher is one an update moved aside a moment ago.
+
+ Usable, not merely present: `_recover_missing_launcher` reads these through
+ `_is_valid_pe`, so a copy it would reject is no excuse. Same two-byte test.
+ """
+ try:
+ path = Path(target)
+ if path.name != _STAGED_LAUNCHER_NAME:
+ return False
+ for suffix in _STAGED_LAUNCHER_SUFFIXES:
+ staged = path.with_name(path.name + suffix)
+ try:
+ if staged.stat().st_size < 2:
+ continue
+ with staged.open("rb") as handle:
+ if handle.read(2) == b"MZ":
+ return True
+ except OSError:
+ continue
+ return False
+ except (OSError, ValueError):
+ return False
+
+
+def _within(target: Path, anchor: Path) -> bool:
+ """Whether a parent-relative row lands inside the environment.
+
+ One outside it belongs to something else, which reinstalling ours cannot fix.
+ """
+ try:
+ resolved = target.resolve()
+ except OSError:
+ return False
+ try:
+ resolved.relative_to(anchor)
+ except ValueError:
+ return False
+ return True
+
+
+def _venv_anchor(site_packages: Path) -> Optional[Path]:
+ """The venv a site-packages belongs to, or None and the caller skips them."""
+ try:
+ current = site_packages.resolve()
+ except OSError:
+ return None
+ # site-packages is 2 (Windows) or 3 (posix) below the prefix.
+ for _ in range(4):
+ if (current / "pyvenv.cfg").is_file():
+ return current
+ if current == current.parent:
+ break
+ current = current.parent
+ return None
+
+
+# Neither installer wraps the scan in a timeout, so a stalled mount would wedge
+# setup. Warm cost of the largest real case is ~65ms.
+PAYLOAD_SCAN_BUDGET_SECONDS = 5.0
+
+
+def damaged_payload_files(
+ package_name: str = "unsloth",
+ limit: int = 3,
+ budget_seconds: float = PAYLOAD_SCAN_BUDGET_SECONDS,
+ companion_names: Sequence[str] = (),
+ scan_paths: Optional[Sequence[str]] = None,
+) -> List[str]:
+ """Recorded files of the managed distribution that are gone or truncated.
+
+ Every check above reads metadata, which a quarantine of the payload leaves
+ intact. Only the named package and companions, unlike `damaged_installed_files`:
+ this runs on the fast path to decide whether to repair ours. `scan_paths`
+ aims it at another venv. Never raises, and an environment it cannot read or
+ finish reading is reported undamaged, since guessing the other way would
+ repair a healthy venv on every run.
+
+ The walk's own deadline bounds many slow stats but not one that never
+ returns, which a wedged mount produces and no installer wraps in a timeout.
+ So it runs on a daemon thread and is abandoned; the interpreter does not
+ wait for one at exit (1.04s measured, thread parked in a syscall).
+ `budget_seconds = 0` is unbounded, for the installer already committed to a
+ full pass.
+ """
+ if budget_seconds <= 0:
+ return _scan_payload_files(package_name, limit, 0.0, companion_names, scan_paths)
+
+ import threading
+
+ done: List[List[str]] = []
+
+ def scan() -> None:
+ done.append(
+ _scan_payload_files(package_name, limit, budget_seconds, companion_names, scan_paths)
+ )
+
+ worker = threading.Thread(target = scan, daemon = True)
+ worker.start()
+ # The walk's deadline is the ordinary way out and reports what it found;
+ # this margin only bounds the wait for a call that is not coming back.
+ worker.join(budget_seconds + 1.0)
+ return done[0] if done else []
+
+
+def _scan_payload_files(
+ package_name: str,
+ limit: int,
+ budget_seconds: float,
+ companion_names: Sequence[str],
+ scan_paths: Optional[Sequence[str]],
+) -> List[str]:
+ """The walk itself. Bounded between calls only; see `damaged_payload_files`."""
+ import csv
+ import io
+ import stat
+ from importlib.metadata import distributions
+
+ found: List[str] = []
+ deadline = time.monotonic() + budget_seconds if budget_seconds > 0 else None
+ try:
+ wanted = {_canonical(name) for name in (package_name, *companion_names) if name}
+ paths = list(scan_paths) if scan_paths is not None else _metadata_scan_paths()
+ if not paths:
+ return found
+ seen: set = set()
+ for dist in distributions(path = paths):
+ try:
+ name = _canonical(dist.metadata["Name"] or "")
+ if name not in wanted or name in seen:
+ continue
+ seen.add(name)
+ record = dist.read_text("RECORD")
+ except Exception:
+ continue
+ # RECORD is optional per the spec, and unreadable says nothing.
+ if not record:
+ continue
+ try:
+ anchor = _venv_anchor(Path(dist.locate_file("")))
+ except Exception:
+ anchor = None
+ # csv, not splitlines: a quoted field may hold a newline, and
+ # splitlines also breaks on \v, \f and the Unicode separators.
+ for row in csv.reader(io.StringIO(record, newline = "")):
+ # Every row: batching this let one slow mount overrun 5s by a minute.
+ if deadline is not None and time.monotonic() > deadline:
+ return found
+ rel = row[0] if row else ""
+ if not rel or rel.endswith("/"):
+ continue
+ norm = rel.replace("\\", "/")
+ if ".dist-info/" in norm or ".egg-info/" in norm or norm.endswith(".pyc"):
+ continue
+ parts = tuple(p for p in norm.split("/") if p and p != ".")
+ if not parts or norm.startswith("/") or ":" in parts[0]:
+ continue
+ if len(parts) > 1 and parts[0] in _SHARED_NON_RUNTIME_ROOTS:
+ continue
+ if any(parts[: len(tree)] == tree for tree in _INSTALLER_REGENERATED_TREES):
+ continue
+ try:
+ target = dist.locate_file(rel)
+ # `..` is ordinary for console scripts and data files.
+ # Bounded rather than skipped: a quarantined `bin/unsloth`
+ # leaves the tree intact and the command gone.
+ if ".." in parts and (anchor is None or not _within(Path(target), anchor)):
+ continue
+ info = target.stat()
+ except FileNotFoundError:
+ if not _staged_beside(target):
+ found.append(f"{rel} is missing")
+ except NotADirectoryError:
+ # Not a FileNotFoundError: a parent replaced by a file.
+ found.append(f"{rel} is not reachable")
+ except OSError:
+ # Unreadable is not missing, and a reinstall cannot fix it.
+ continue
+ else:
+ if not stat.S_ISREG(info.st_mode):
+ found.append(f"{rel} is not a regular file")
+ elif (
+ len(row) >= 3
+ and row[2]
+ and row[2].isdigit()
+ and parts[-1] not in _INSTALLER_REWRITTEN_NAMES
+ and info.st_size < int(row[2])
+ ):
+ found.append(f"{rel} is {info.st_size} bytes, expected {row[2]}")
+ if len(found) >= limit:
+ return found
+ except Exception:
+ return found[:limit]
+ return found
+
+
def verify_install(
root: Optional[Path] = None,
req_root: Optional[Path] = None,
package_name: str = "unsloth",
installed: Optional[Dict[str, str]] = None,
installed_conflicts: Optional[Sequence[str]] = None,
+ deep: bool = False,
+ scan_paths: Optional[Sequence[str]] = None,
) -> dict:
"""Report whether the managed install finished and can still boot.
@@ -520,6 +750,12 @@ def verify_install(
to describe a venv other than this interpreter's; without them the version
and dependency checks would answer for the venv the caller happens to be
running in.
+
+ `deep` adds the payload scan, off by default because an external CLI loads
+ this module out of the venv it drives: opt-out would spend the desktop
+ preflight's 10 second budget with no way for an old caller to decline.
+ `scan_paths` names that venv's site-packages, without which RECORD rows
+ resolve against the wrong tree.
"""
reqs = req_root or requirements_root()
missing = missing_requirements(reqs / BOOT_REQUIREMENT_FILE, installed = installed)
@@ -528,6 +764,7 @@ def verify_install(
manifest = read_manifest(root)
manifest_ok = False
reason: Optional[str] = None
+ vanished = False
if manifest is None:
reason = "studio_install_incomplete"
@@ -548,6 +785,10 @@ def verify_install(
_canonical(manifest_package) != "unsloth-zoo" and "unsloth-zoo" in foreign_conflicts
)
recorded = manifest.get("package_version")
+ # Every check below compares against `current`, which an absent
+ # distribution passes -- as does a manifest written with no version at
+ # all, which is what write_manifest records for one already gone.
+ vanished = not current
if core_conflict or local_conflict:
reason = "studio_install_metadata_conflict"
elif current and recorded and current != recorded:
@@ -561,6 +802,33 @@ def verify_install(
# Install finished but the boot deps are gone: venv edited afterwards.
reason = "studio_deps_missing"
+ # Last: the only check that touches the filesystem, so it must not divert a
+ # reason above. `installed` without `scan_paths` is a venv we cannot stat.
+ if manifest_ok and deps_ok and deep and (installed is None or scan_paths):
+ # Reused, not re-read: a manifest rewritten mid-run would make the scan
+ # disagree with the checks that already passed.
+ scan_package = (manifest or {}).get("package") or package_name
+ # unsloth-zoo only for the default install: `--package X` installs X
+ # alone, so its neighbours are not ours to repair.
+ companions = ("unsloth-zoo",) if _canonical(scan_package) == "unsloth" else ()
+ # No dist-info leaves the scan nothing to walk, and no check above ever
+ # looked at the companion's version.
+ if not vanished:
+ for companion in companions:
+ present = (
+ _installed_version(companion, installed)
+ if installed is not None
+ else installed_version_probe(companion)[0]
+ )
+ if not present:
+ vanished = True
+ break
+ if vanished or damaged_payload_files(
+ scan_package, companion_names = companions, scan_paths = scan_paths
+ ):
+ manifest_ok = False
+ reason = "studio_install_damaged"
+
return {
"ok": manifest_ok and deps_ok,
"manifest_ok": manifest_ok,
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 1c61531b374..cf5368851eb 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -5706,6 +5706,118 @@ def _stage_replacement(name: str):
return None
+def _core_package_names(package_name: str) -> "tuple[str, ...]":
+ """The distributions a run is responsible for.
+
+ unsloth-zoo only for the default install: `--package X` installs X alone, so
+ demanding the companion would force-reinstall an unrelated distribution and
+ fail the update on an unreachable zoo index. Canonically, because
+ verify_install reads `--package Unsloth` that way and the two disagreeing
+ had the deep check scan zoo and force a pass no repair gate would act on.
+ """
+ default = re.sub(r"[-_.]+", "-", package_name).lower() == "unsloth"
+ return (package_name, "unsloth-zoo") if default else (package_name,)
+
+
+def _repair_damaged_core_payload(
+ package_names: "tuple[str, ...]",
+ *,
+ local_repo: str = "",
+ require_present: bool = False,
+) -> bool:
+ """Reinstall managed core packages whose recorded files are gone or truncated.
+
+ An upgrade of a distribution already at the wanted version installs nothing:
+ uv audits it, pip calls it satisfied, and both read metadata a quarantine of
+ the payload leaves intact, so it has to be named for reinstall. Skipped for
+ a local checkout, whose core packages are an editable overlay.
+
+ False when the files are still missing afterwards and the caller aborts, or
+ the pass that follows audits the intact metadata as satisfied and
+ write_manifest records a success nothing rechecks. Judged on the tree, not
+ pip's exit code, so a reinstall that restored the files while exiting
+ non-zero still counts.
+
+ `require_present` also refuses a distribution not installed at all, which
+ has no RECORD and so reads as undamaged. Off before the core phase, where a
+ fresh run has nothing yet; on after it, where absence means the phase was
+ skipped (SKIP_STUDIO_BASE=1) or silently did nothing.
+ """
+ if local_repo:
+ return True
+ if require_present:
+ for name in package_names:
+ try:
+ present = any(install_manifest.installed_versions(name))
+ except Exception:
+ continue
+ if not present:
+ _safe_print(
+ _red(
+ f" {name} is not installed, so this environment cannot run. "
+ "Rerun the installer with the package index available."
+ ),
+ file = sys.stderr,
+ )
+ return False
+ damaged: list[str] = []
+ seen: set[str] = set()
+ for name in package_names:
+ canonical = re.sub(r"[-_.]+", "-", name).lower()
+ if canonical in seen:
+ continue
+ seen.add(canonical)
+ try:
+ if install_manifest.damaged_payload_files(name, limit = 1, budget_seconds = 0.0):
+ damaged.append(name)
+ except Exception:
+ continue
+ still_damaged: list[str] = []
+ for name in damaged:
+ _step(_LABEL, f"{name} is missing installed files; reinstalling it", _dim)
+ # --no-deps: resolving the graph would drag the torch build along. Both
+ # flags: pip has no per-package form, uv's --reinstall is environment-wide.
+ pip_install_try(
+ f"Reinstalling {name}",
+ "--no-cache-dir",
+ "--no-deps",
+ "--reinstall-package",
+ name,
+ "--force-reinstall",
+ name,
+ )
+ importlib.invalidate_caches()
+ # Presence first: --force-reinstall uninstalls before it installs, and
+ # what it leaves behind has no RECORD for the scan below to call
+ # damaged. Unconditional, unlike require_present: we only reinstall what
+ # the scan already found, so it was installed a moment ago.
+ try:
+ remaining = (
+ []
+ if any(install_manifest.installed_versions(name))
+ else [f"{name} is no longer installed"]
+ )
+ except Exception:
+ remaining = []
+ try:
+ remaining = remaining or install_manifest.damaged_payload_files(
+ name, budget_seconds = 0.0
+ )
+ except Exception:
+ pass
+ if remaining:
+ still_damaged.append(name)
+ _safe_print(
+ _red(
+ f" {name} is still missing installed files after a reinstall "
+ f"({remaining[0]}). An unreachable or offline index cannot "
+ "replace them; rerun with the index available."
+ ),
+ file = sys.stderr,
+ )
+ return not still_damaged
+
+
def _repair_duplicate_core_metadata(
package_names: "tuple[str, ...]",
*,
@@ -5932,6 +6044,9 @@ def _translate_pip_args_for_uv(args: tuple[str, ...]) -> list[str]:
for arg in args:
if arg == "--no-cache-dir":
continue # uv cache is fast; drop this flag
+ elif arg == "--force-reinstall" and "--reinstall-package" in args:
+ # Already targeted by name; uv's --reinstall would rebuild torch.
+ continue
elif arg == "--force-reinstall":
translated.append("--reinstall")
else:
@@ -5954,14 +6069,21 @@ def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:
"""
cmd = [sys.executable, "-m", "pip", "install"]
upgrade: list[str] = []
- skip_next = False
+ drop_next = ""
for arg in args:
- if skip_next:
- skip_next = False
- upgrade.append(arg)
+ if drop_next:
+ # The previous flag's value: never a bare positional of its own.
+ if drop_next == "--upgrade-package":
+ upgrade.append(arg)
+ drop_next = ""
continue
if arg == "--upgrade-package":
- skip_next = True # the flag; its value is the package to upgrade
+ drop_next = arg # the flag; its value is the package to upgrade
+ continue
+ if arg == "--reinstall-package":
+ # uv-only. Its caller's --force-reinstall is environment-wide for
+ # pip, safe only because that call also passes --no-deps.
+ drop_next = arg
continue
cmd.append(arg)
if upgrade:
@@ -6695,6 +6817,11 @@ def install_python_stack() -> int:
):
return 1
+ # Intact metadata over a missing payload: the core phase would audit it as
+ # satisfied. Unbudgeted, since this run is already doing a full install.
+ if not _repair_damaged_core_payload(_core_package_names(package_name), local_repo = local_repo):
+ return 1
+
# macOS arm64: install MLX stack at latest (UV_OVERRIDE relaxes the
# mlx-vlm / mlx-lm transformers pin -- set at module load).
if IS_MAC_ARM and not skip_base:
@@ -7073,6 +7200,16 @@ def install_python_stack() -> int:
):
return 1
+ # 14c. write_manifest reads the installed version, so a core package absent
+ # or quarantined now is recorded as a finished install. The skip_base
+ # handoff never reaches the core phase, so nothing else would see it.
+ if not _repair_damaged_core_payload(
+ _core_package_names(package_name),
+ local_repo = local_repo,
+ require_present = True,
+ ):
+ return 1
+
# 15. Record success. Written last so an earlier kill leaves none. Exiting 0
# without it reports a finished install every later check calls unfinished.
if (
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 39ef29ca706..afdf91cf13d 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -4867,13 +4867,21 @@ sys.exit(0 if (major, minor) >= (4, 14) else 1)
$_studioInstallIncomplete = $false
try {
& python -c "
-import sys
+import os, sys
sys.path.insert(0, sys.argv[1])
try:
import install_manifest
except Exception:
- sys.exit(0) # older tree without the manifest helper: leave the fast path alone
-sys.exit(0 if install_manifest.verify_install()['ok'] else 1)
+ # Present but unimportable is damage, not an old release, and this is the
+ # one file whose damage silences every check below. Absent keeps the old
+ # escape: separating it from an old tree needs a RECORD walk here, and the
+ # CLI already reports studio_install_manifest_missing.
+ sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
+try:
+ ok = install_manifest.verify_install(deep = True)['ok']
+except TypeError:
+ ok = install_manifest.verify_install()['ok'] # older tree, no payload scan
+sys.exit(0 if ok else 1)
" "$PSScriptRoot" 2>$null
if ($LASTEXITCODE -ne 0) { $_studioInstallIncomplete = $true }
} catch {}
diff --git a/studio/setup.sh b/studio/setup.sh
index ad7326d8c06..a9056d995ef 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -1852,13 +1852,21 @@ sys.exit(0 if (major, minor) >= (4, 14) else 1)
# never finished, so the compare above says "up to date" and update --
# plus the desktop Repair button -- no-ops on a venv that cannot boot.
if ! "$VENV_DIR/bin/python" -c "
-import sys
+import os, sys
sys.path.insert(0, sys.argv[1])
try:
import install_manifest
except Exception:
- sys.exit(0) # older tree without the manifest helper: leave the fast path alone
-sys.exit(0 if install_manifest.verify_install()['ok'] else 1)
+ # Present but unimportable is damage, not an old release, and this is the
+ # one file whose damage silences every check below. Absent keeps the old
+ # escape: separating it from an old tree needs a RECORD walk here, and the
+ # CLI already reports studio_install_manifest_missing.
+ sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)
+try:
+ ok = install_manifest.verify_install(deep = True)['ok']
+except TypeError:
+ ok = install_manifest.verify_install()['ok'] # older tree, no payload scan
+sys.exit(0 if ok else 1)
" "$SCRIPT_DIR" 2>/dev/null; then
substep "studio install incomplete -- forcing dependency pass to repair..."
_SKIP_PYTHON_DEPS=false
diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.py
index bad566bd30f..69bad6b9f1f 100644
--- a/tests/python/test_install_python_stack.py
+++ b/tests/python/test_install_python_stack.py
@@ -773,6 +773,177 @@ class TestBuildPipCmdUpgradeIntent:
assert cmd == [sys.executable, "-m", "pip", "install", "--no-cache-dir", "somepackage"]
+class TestDamagedCorePayloadRepair:
+ """An upgrade of a distribution already at the wanted version installs
+ nothing: uv audits it, pip calls it satisfied, and both read metadata a
+ quarantine of the payload leaves intact."""
+
+ def test_the_uv_command_targets_only_the_named_package(self):
+ cmd = ips._build_uv_cmd(
+ ("--no-cache-dir", "--no-deps", "--reinstall-package", "x", "--force-reinstall", "x")
+ )
+ assert "--reinstall-package" in cmd
+ # Not --reinstall: that is the whole environment, torch included.
+ assert "--reinstall" not in cmd
+ assert "--no-deps" in cmd
+
+ def test_a_plain_force_reinstall_still_becomes_uv_reinstall(self):
+ assert "--reinstall" in ips._build_uv_cmd(("--force-reinstall", "x"))
+
+ def test_the_pip_fallback_drops_the_uv_only_flag(self):
+ cmd = ips._build_pip_cmd(
+ ("--no-cache-dir", "--no-deps", "--reinstall-package", "x", "--force-reinstall", "x")
+ )
+ assert "--reinstall-package" not in cmd
+ assert "--force-reinstall" in cmd and "--no-deps" in cmd
+ assert cmd.count("x") == 1
+ # It is not an upgrade request, so it must not acquire pip's upgrade flags.
+ assert "--upgrade" not in cmd
+
+ def test_a_damaged_package_is_reinstalled(self, monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "damaged_payload_files",
+ lambda name, **kwargs: ["gone"] if name == "unsloth-zoo" else [],
+ )
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda name: ["1.0"])
+ monkeypatch.setattr(ips, "pip_install_try", lambda label, *args: calls.append(args))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ ips._repair_damaged_core_payload(("unsloth", "unsloth-zoo"))
+ assert len(calls) == 1
+ assert "--reinstall-package" in calls[0] and calls[0][-1] == "unsloth-zoo"
+
+ def test_a_healthy_tree_runs_nothing(self, monkeypatch):
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", lambda *a, **k: [])
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda *a, **k: pytest.fail("nothing to repair")
+ )
+ ips._repair_damaged_core_payload(("unsloth", "unsloth-zoo"))
+
+ def test_a_local_checkout_is_left_alone(self, monkeypatch):
+ """Its core packages are an editable overlay, not an index install."""
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "damaged_payload_files",
+ lambda *a, **k: pytest.fail("a local checkout must not even be scanned"),
+ )
+ ips._repair_damaged_core_payload(("unsloth",), local_repo = "/src/unsloth")
+
+ def test_a_scan_that_raises_does_not_stop_the_install(self, monkeypatch):
+ def boom(*args, **kwargs):
+ raise OSError("unreadable")
+
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", boom)
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda *a, **k: pytest.fail("nothing was proven damaged")
+ )
+ ips._repair_damaged_core_payload(("unsloth",))
+
+ def test_a_repair_that_leaves_the_files_missing_fails(self, monkeypatch, capsys):
+ """Otherwise the pass that follows audits the intact metadata as
+ satisfied and write_manifest records a success nothing rechecks."""
+ monkeypatch.setattr(
+ ips.install_manifest, "damaged_payload_files", lambda name, **kwargs: ["gone"]
+ )
+ monkeypatch.setattr(ips, "pip_install_try", lambda label, *args: False)
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ assert ips._repair_damaged_core_payload(("unsloth",)) is False
+
+ def test_a_reinstall_that_restored_the_files_is_a_success(self, monkeypatch):
+ """Judged on the tree, not pip's exit code: uv and pip both exit non-zero
+ for reasons that have nothing to do with the payload."""
+ seen = {"n": 0}
+
+ def scan(name, **kwargs):
+ seen["n"] += 1
+ return ["gone"] if seen["n"] == 1 else []
+
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", scan)
+ # Stubbed, or the presence check added beside the scan answers for the
+ # host: a source checkout with no unsloth distribution installed would
+ # fail this on the environment rather than on the code.
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda name: ["1.0"])
+ monkeypatch.setattr(ips, "pip_install_try", lambda label, *args: False)
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ assert ips._repair_damaged_core_payload(("unsloth",)) is True
+
+ def test_an_absent_distribution_is_refused_after_the_core_phase(self, monkeypatch):
+ """It has no RECORD to walk, so the scan alone reads it as undamaged.
+
+ The install.sh handoff sets SKIP_STUDIO_BASE=1 and the core phase never
+ runs, so this is the only place that would see unsloth-zoo gone before
+ write_manifest records the environment as a finished install.
+ """
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", lambda *a, **k: [])
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda name: [])
+ monkeypatch.setattr(ips, "_safe_print", lambda *a, **k: None)
+ assert ips._repair_damaged_core_payload(("unsloth",), require_present = True) is False
+ # Off before the core phase: a fresh run has nothing installed yet.
+ assert ips._repair_damaged_core_payload(("unsloth",)) is True
+
+ def test_a_present_distribution_passes_the_presence_check(self, monkeypatch):
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", lambda *a, **k: [])
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda name: ["1.0"])
+ assert ips._repair_damaged_core_payload(("unsloth",), require_present = True) is True
+
+ def test_the_companion_is_only_for_the_default_install(self):
+ assert ips._core_package_names("unsloth") == ("unsloth", "unsloth-zoo")
+ assert ips._core_package_names("unsloth-nightly") == ("unsloth-nightly",)
+
+ def test_the_default_is_recognised_however_it_is_spelled(self):
+ """verify_install canonicalizes, and the two disagreeing meant the deep
+ check scanned zoo, forced a pass, and no repair gate would touch it."""
+ for spelling in ("Unsloth", "UNSLOTH", "UnSloth"):
+ assert ips._core_package_names(spelling)[1:] == ("unsloth-zoo",), spelling
+ # PEP 503 folds runs of -_. to -, it does not delete them, so this is a
+ # different project and keeps its neighbours to itself.
+ assert ips._core_package_names("uns_loth") == ("uns_loth",)
+
+ def test_both_repair_sites_use_that_list(self):
+ source = inspect.getsource(ips)
+ assert (
+ source.count("_repair_damaged_core_payload(\n _core_package_names")
+ + source.count("_repair_damaged_core_payload(_core_package_names")
+ == 2
+ )
+ assert "_repair_damaged_core_payload((package_name" not in source
+
+ def test_the_second_site_runs_before_the_manifest_is_written(self):
+ source = inspect.getsource(ips)
+ gate = source.rindex("_repair_damaged_core_payload(")
+ assert gate < source.index("install_manifest.write_manifest(")
+
+ def test_a_reinstall_that_removed_the_distribution_fails(self, monkeypatch):
+ """--force-reinstall uninstalls before it installs, and a failure in
+ between leaves nothing: an absent distribution has no RECORD, so the
+ payload scan alone would call the repair a success."""
+ scans = {"n": 0}
+
+ def scan(name, **kwargs):
+ scans["n"] += 1
+ # Damaged on the way in, and afterwards nothing left to call damaged.
+ return ["gone"] if scans["n"] == 1 else []
+
+ monkeypatch.setattr(ips.install_manifest, "damaged_payload_files", scan)
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda name: [])
+ monkeypatch.setattr(ips, "pip_install_try", lambda label, *args: True)
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips, "_safe_print", lambda *a, **k: None)
+ assert ips._repair_damaged_core_payload(("unsloth",)) is False
+
+ def test_the_caller_aborts_the_install(self):
+ source = inspect.getsource(ips)
+ assert "if not _repair_damaged_core_payload(" in source
+
+ def test_the_repair_runs_before_the_core_phase(self):
+ """After it, the upgrade would already have audited the damage as fine."""
+ source = inspect.getsource(ips)
+ repair = source.index("_repair_damaged_core_payload(_core_package_names")
+ core = source.index("# 3. Core packages")
+ assert repair < core
+
+
class TestDuplicateCoreMetadataRepair:
def test_an_unrewritable_record_stops_the_repair_before_pip_runs(
self, tmp_path, monkeypatch, capsys
diff --git a/tests/sh/test_setup_desktop_backend_version_fastpath.sh b/tests/sh/test_setup_desktop_backend_version_fastpath.sh
index b5b04210a99..72b36cda325 100644
--- a/tests/sh/test_setup_desktop_backend_version_fastpath.sh
+++ b/tests/sh/test_setup_desktop_backend_version_fastpath.sh
@@ -107,7 +107,7 @@ EOF
chmod +x "$VENV_DIR/bin/python"
# Mock install_manifest to return ok: True so manifest check passes
-printf 'def verify_install():\n return {"ok": True}\n' > "$WORK/install_manifest.py"
+printf 'def verify_install(**kwargs):\n return {"ok": True}\n' > "$WORK/install_manifest.py"
eval_fastpath() {
local installed_ver="$1"
diff --git a/tests/studio/install/test_install_manifest_damage.py b/tests/studio/install/test_install_manifest_damage.py
new file mode 100644
index 00000000000..a8a44cb3537
--- /dev/null
+++ b/tests/studio/install/test_install_manifest_damage.py
@@ -0,0 +1,700 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The payload scan behind `studio_install_damaged`.
+
+Both directions: real damage has to be seen, and the trees our own setup
+rewrites must not be mistaken for it, since a false positive repairs a healthy
+venv on every run.
+"""
+
+import csv
+import io
+import json
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "studio"))
+
+import install_manifest # noqa: E402
+
+
+PKG = "demo"
+VER = "1.0"
+
+
+def site_packages(tmp_path, monkeypatch):
+ """A throwaway site-packages that the scan treats as the venv's own."""
+ root = tmp_path / "site-packages"
+ root.mkdir()
+ monkeypatch.setattr(install_manifest, "_metadata_scan_paths", lambda: [str(root)])
+ return root
+
+
+def _dist(
+ site_packages: Path,
+ name = PKG,
+ version = VER,
+) -> Path:
+ dist_info = site_packages / f"{name}-{version}.dist-info"
+ dist_info.mkdir(parents = True, exist_ok = True)
+ (dist_info / "METADATA").write_text(
+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding = "utf-8"
+ )
+ return dist_info
+
+
+def _record(dist_info: Path, rows) -> None:
+ buf = io.StringIO(newline = "")
+ writer = csv.writer(buf, lineterminator = "\n")
+ for row in rows:
+ writer.writerow(row)
+ (dist_info / "RECORD").write_text(buf.getvalue(), encoding = "utf-8", newline = "")
+
+
+def _write(path: Path, text: str) -> int:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(text, encoding = "utf-8")
+ return len(text.encode())
+
+
+def _healthy(site_packages: Path):
+ dist_info = _dist(site_packages)
+ size = _write(site_packages / PKG / "__init__.py", "x = 1\n")
+ return dist_info, [
+ [f"{PKG}/__init__.py", "sha256=x", size],
+ [f"{dist_info.name}/RECORD", "", ""],
+ ]
+
+
+# ----------------------------------------------------------------- true positives
+
+
+def test_a_healthy_install_reports_nothing(site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_quarantined_file_is_damage(site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ (site_packages / PKG / "__init__.py").unlink()
+ assert install_manifest.damaged_payload_files(PKG) == [f"{PKG}/__init__.py is missing"]
+
+
+def test_a_truncated_file_is_damage(site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ (site_packages / PKG / "__init__.py").write_text("", encoding = "utf-8")
+ assert install_manifest.damaged_payload_files(PKG) == [
+ f"{PKG}/__init__.py is 0 bytes, expected 6"
+ ]
+
+
+def test_a_directory_where_a_file_was_recorded_is_damage(site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ target = site_packages / PKG / "__init__.py"
+ target.unlink()
+ target.mkdir()
+ assert install_manifest.damaged_payload_files(PKG) == [
+ f"{PKG}/__init__.py is not a regular file"
+ ]
+
+
+def test_the_findings_respect_the_limit(site_packages):
+ dist_info = _dist(site_packages)
+ _record(dist_info, [[f"{PKG}/m{i}.py", "sha256=x", 10] for i in range(9)])
+ assert len(install_manifest.damaged_payload_files(PKG, limit = 3)) == 3
+
+
+# ---------------------------------------------------------------- false positives
+
+
+def test_a_regenerated_frontend_dist_is_not_damage(site_packages):
+ """The wheel ships the bundle, so its files are in RECORD, and setup's own
+ `npm run build` rehashes every one of them."""
+ dist_info, rows = _healthy(site_packages)
+ old = _write(site_packages / "studio/frontend/dist/assets/index-OLDHASH1.js", "x\n")
+ index = _write(site_packages / "studio/frontend/dist/index.html", "<html>old</html>\n")
+ _record(
+ dist_info,
+ rows
+ + [
+ ["studio/frontend/dist/assets/index-OLDHASH1.js", "sha256=x", old],
+ ["studio/frontend/dist/index.html", "sha256=x", index],
+ ],
+ )
+ (site_packages / "studio/frontend/dist/assets/index-OLDHASH1.js").unlink()
+ _write(site_packages / "studio/frontend/dist/assets/index-NEWHASH2.js", "y\n")
+ _write(site_packages / "studio/frontend/dist/index.html", "<html>\n")
+
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_damage_outside_the_regenerated_tree_still_counts(site_packages):
+ """The carve-out is a subtree, not an amnesty."""
+ dist_info, rows = _healthy(site_packages)
+ old = _write(site_packages / "studio/frontend/dist/assets/index-OLDHASH1.js", "x\n")
+ _record(dist_info, rows + [["studio/frontend/dist/assets/index-OLDHASH1.js", "sha256=x", old]])
+ (site_packages / "studio/frontend/dist/assets/index-OLDHASH1.js").unlink()
+ (site_packages / PKG / "__init__.py").unlink()
+
+ assert install_manifest.damaged_payload_files(PKG) == [f"{PKG}/__init__.py is missing"]
+
+
+def test_a_shrunk_package_lock_is_not_damage(site_packages):
+ """npm dedupes hoisted entries, shrinking the lockfile below its recorded size."""
+ dist_info, rows = _healthy(site_packages)
+ lock = _write(site_packages / "studio/frontend/package-lock.json", '{"a": 1, "b": 2}\n')
+ _record(dist_info, rows + [["studio/frontend/package-lock.json", "sha256=x", lock]])
+ _write(site_packages / "studio/frontend/package-lock.json", "{}\n")
+
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_deleted_package_lock_is_still_damage(site_packages):
+ """Only the size claim is waived for a rewritten file, not its existence."""
+ dist_info, rows = _healthy(site_packages)
+ lock = _write(site_packages / "studio/frontend/package-lock.json", "{}\n")
+ _record(dist_info, rows + [["studio/frontend/package-lock.json", "sha256=x", lock]])
+ (site_packages / "studio/frontend/package-lock.json").unlink()
+
+ assert install_manifest.damaged_payload_files(PKG) == [
+ "studio/frontend/package-lock.json is missing"
+ ]
+
+
+def test_a_shared_non_runtime_root_is_not_damage(site_packages):
+ """unsloth_zoo <= 2026.8.5 shipped tests/ into a squatted namespace."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows + [["tests/conftest.py", "sha256=x", 9999]])
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_larger_file_is_not_damage(site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ _write(site_packages / PKG / "__init__.py", "x = 1\n" * 50)
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_an_absent_record_is_not_damage(site_packages):
+ """RECORD is optional per the installed-projects spec."""
+ _dist(site_packages)
+ _write(site_packages / PKG / "__init__.py", "x = 1\n")
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_an_unreadable_file_is_not_damage(site_packages):
+ """A reinstall cannot fix EACCES, and unreadable is not missing."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ target = site_packages / PKG / "__init__.py"
+ os.chmod(target, 0o000)
+ try:
+ if os.access(target, os.R_OK):
+ pytest.skip("running as a user that ignores the mode")
+ assert install_manifest.damaged_payload_files(PKG) == []
+ finally:
+ os.chmod(target, 0o644)
+
+
+def test_a_quoted_line_break_in_a_recorded_name_is_not_damage(site_packages):
+ """RECORD is CSV: a quoted field may hold a newline that splitlines breaks."""
+ dist_info = _dist(site_packages)
+ size = _write(site_packages / PKG / "we\nird.py", "x = 1\n")
+ _record(
+ dist_info, [[f"{PKG}/we\nird.py", "sha256=x", size], [f"{dist_info.name}/RECORD", "", ""]]
+ )
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_an_unrelated_distribution_is_not_scanned(site_packages):
+ """It answers for the managed package alone."""
+ other = _dist(site_packages, name = "other")
+ _record(other, [["other/__init__.py", "sha256=x", 10]])
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_an_unreadable_environment_reports_undamaged(monkeypatch):
+ """A scan that cannot answer leaves the fast path as it found it."""
+ monkeypatch.setattr(install_manifest, "_metadata_scan_paths", lambda: [])
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+# ------------------------------------------------------------- verify_install wiring
+
+
+def _complete_install(tmp_path, monkeypatch, site_packages):
+ """A manifest and requirements that make every metadata check pass."""
+ req_root = tmp_path / "requirements"
+ req_root.mkdir()
+ (req_root / install_manifest.BOOT_REQUIREMENT_FILE).write_text("", encoding = "utf-8")
+ install_manifest.write_manifest(root = tmp_path, req_root = req_root, package_name = PKG)
+ return req_root
+
+
+def test_a_damaged_payload_invalidates_an_otherwise_complete_install(
+ tmp_path, monkeypatch, site_packages
+):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+
+ ok_state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert ok_state["ok"] is True and ok_state["reason"] is None
+
+ (site_packages / PKG / "__init__.py").unlink()
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["ok"] is False
+ assert state["reason"] == "studio_install_damaged"
+ # The deps walk still succeeded; only the payload is at fault.
+ assert state["deps_ok"] is True
+
+
+def test_the_scan_is_off_unless_asked_for(tmp_path, monkeypatch, site_packages):
+ """Default off: an external CLI can load a newer copy of this module out of
+ the venv it drives, and cannot decline a scan it does not expect."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ (site_packages / PKG / "__init__.py").unlink()
+
+ for kwargs in ({}, {"deep": False}):
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, **kwargs)
+ assert state["ok"] is True and state["reason"] is None, kwargs
+
+
+def test_describing_a_foreign_venv_never_scans_this_one(tmp_path, monkeypatch, site_packages):
+ """`installed` means another venv, whose tree this interpreter cannot stat."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ (site_packages / PKG / "__init__.py").unlink()
+
+ state = install_manifest.verify_install(
+ root = tmp_path, req_root = req_root, installed = {PKG: VER}, deep = True
+ )
+ assert state["reason"] != "studio_install_damaged"
+
+
+def test_the_scan_runs_last_and_diverts_no_existing_reason(tmp_path, monkeypatch, site_packages):
+ """A missing manifest still reports incomplete, not damaged."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ (site_packages / PKG / "__init__.py").unlink()
+
+ state = install_manifest.verify_install(root = tmp_path, deep = True)
+ assert state["reason"] == "studio_install_incomplete"
+
+
+# ------------------------------------------------------- who asks for the scan
+
+
+def test_the_installers_ask_for_the_scan():
+ """They import this module from their own directory, so unlike an external
+ CLI they can never be skewed against it."""
+ repo = Path(__file__).resolve().parents[3]
+ for name in ("studio/setup.sh", "studio/setup.ps1"):
+ text = (repo / name).read_text(encoding = "utf-8")
+ assert "verify_install(deep = True)" in text, f"{name} stopped asking for the scan"
+ # and it must survive an older module that has no such keyword
+ assert "except TypeError:" in text, f"{name} lost its older-tree fallback"
+
+
+def test_the_desktop_boot_path_does_not_ask_for_the_scan():
+ """`desktop-capabilities` feeds the Tauri preflight under a 10 second
+ timeout, and a probe that overruns it repairs a healthy install."""
+ repo = Path(__file__).resolve().parents[3]
+ deps = (repo / "unsloth_cli" / "_studio_deps.py").read_text(encoding = "utf-8")
+ assert "def install_state(extra_roots: Sequence[Path] = (), deep: bool = False)" in deps
+
+ cli = (repo / "unsloth_cli" / "commands" / "studio.py").read_text(encoding = "utf-8")
+ assert "def _install_state(deep: bool = False)" in cli
+ # verify-install is the one command that opts in.
+ assert "_install_state(deep = True)" in cli
+
+
+# ------------------------------------------------- damage the first pass missed
+
+
+def test_a_package_directory_replaced_by_a_file_is_damage(site_packages):
+ """NotADirectoryError is an OSError but not a FileNotFoundError, so the
+ generic arm read a payload replaced by a quarantine stub as healthy."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ import shutil
+
+ shutil.rmtree(site_packages / PKG)
+ (site_packages / PKG).write_text("quarantined", encoding = "utf-8")
+ assert install_manifest.damaged_payload_files(PKG) == [f"{PKG}/__init__.py is not reachable"]
+
+
+def test_the_companion_distribution_is_scanned_too(site_packages):
+ """unsloth-zoo is not in studio.txt, so nothing else would notice it gone."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ zoo_info = _dist(site_packages, name = "unsloth-zoo", version = "2.0")
+ size = _write(site_packages / "unsloth_zoo" / "__init__.py", "y = 2\n")
+ _record(zoo_info, [["unsloth_zoo/__init__.py", "sha256=y", size]])
+
+ assert install_manifest.damaged_payload_files(PKG, companion_names = ("unsloth-zoo",)) == []
+ (site_packages / "unsloth_zoo" / "__init__.py").unlink()
+ assert install_manifest.damaged_payload_files(PKG) == []
+ assert install_manifest.damaged_payload_files(PKG, companion_names = ("unsloth-zoo",)) == [
+ "unsloth_zoo/__init__.py is missing"
+ ]
+
+
+def test_scan_paths_points_the_scan_at_another_venv(tmp_path, site_packages):
+ """Without it a caller holding a foreign venv could only check metadata."""
+ other = tmp_path / "other-site-packages"
+ other.mkdir()
+ dist_info = _dist(other)
+ size = _write(other / PKG / "__init__.py", "x = 1\n")
+ _record(dist_info, [[f"{PKG}/__init__.py", "sha256=x", size]])
+
+ assert install_manifest.damaged_payload_files(PKG, scan_paths = [str(other)]) == []
+ (other / PKG / "__init__.py").unlink()
+ # This interpreter's own tree is healthy and must not be the one answered for.
+ healthy_info, rows = _healthy(site_packages)
+ _record(healthy_info, rows)
+ assert install_manifest.damaged_payload_files(PKG) == []
+ assert install_manifest.damaged_payload_files(PKG, scan_paths = [str(other)]) == [
+ f"{PKG}/__init__.py is missing"
+ ]
+
+
+def test_a_foreign_venv_is_scanned_when_its_paths_are_given(tmp_path, monkeypatch, site_packages):
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ (site_packages / PKG / "__init__.py").unlink()
+
+ state = install_manifest.verify_install(
+ root = tmp_path,
+ req_root = req_root,
+ package_name = PKG,
+ installed = {PKG: VER},
+ deep = True,
+ scan_paths = [str(site_packages)],
+ )
+ assert state["reason"] == "studio_install_damaged"
+
+
+def test_an_uninstalled_managed_distribution_is_damage(tmp_path, monkeypatch, site_packages):
+ """No dist-info at all: every version check compares against it and passes."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+
+ import shutil
+
+ shutil.rmtree(dist_info)
+ shutil.rmtree(site_packages / PKG)
+ shallow = install_manifest.verify_install(root = tmp_path, req_root = req_root)
+ assert shallow["ok"] is True, "the metadata-only checks cannot see this"
+
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["ok"] is False
+ assert state["reason"] == "studio_install_damaged"
+
+
+def test_the_budget_is_checked_before_every_stat(site_packages, monkeypatch):
+ """Batched every 64 rows, one slow stat per row overran the budget."""
+ dist_info = _dist(site_packages)
+ rows = []
+ for index in range(500):
+ rel = f"{PKG}/mod{index}.py"
+ _write(site_packages / PKG / f"mod{index}.py", "x = 1\n")
+ rows.append([rel, "sha256=x", 6])
+ _record(dist_info, rows)
+
+ clock = {"now": 0.0}
+ monkeypatch.setattr(install_manifest.time, "monotonic", lambda: clock["now"])
+ real_stat = Path.stat
+
+ def slow_stat(self, *args, **kwargs):
+ clock["now"] += 1.0 # a second per stat, as a stalled mount would
+ return real_stat(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", slow_stat)
+ install_manifest.damaged_payload_files(PKG, budget_seconds = 5.0)
+ # The lower bound keeps the patched stat honest: unpatched the clock never
+ # moves, and the upper bound alone passes a scan that ignored the budget.
+ assert 5.0 <= clock["now"] <= 6.0
+
+
+def test_the_cli_hands_over_the_managed_venvs_own_paths():
+ """RECORD rows resolve against the distribution that declared them, so
+ without this the foreign branch scans the CLI's own tree, or nothing."""
+ repo = Path(__file__).resolve().parents[3]
+ deps = (repo / "unsloth_cli" / "_studio_deps.py").read_text(encoding = "utf-8")
+ assert 'kwargs["scan_paths"] = paths' in deps
+ # Guarded on its own: a module new enough for `deep` may still predate it.
+ assert '_verify_install_supports(module, "scan_paths")' in deps
+
+
+def test_a_quarantined_console_script_is_damage(tmp_path, site_packages):
+ """Skipping every parent-relative row meant the `unsloth` command could be
+ gone, tree intact, while the deep check called the install healthy."""
+ venv = site_packages.parent
+ (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding = "utf-8")
+ dist_info = _dist(site_packages)
+ size = _write(site_packages / PKG / "__init__.py", "x = 1\n")
+ launcher = _write(venv / "bin" / PKG, "#!/usr/bin/env python\n")
+ _record(
+ dist_info,
+ [[f"{PKG}/__init__.py", "sha256=x", size], [f"../bin/{PKG}", "sha256=b", launcher]],
+ )
+ assert install_manifest.damaged_payload_files(PKG) == []
+ (venv / "bin" / PKG).unlink()
+ assert install_manifest.damaged_payload_files(PKG) == [f"../bin/{PKG} is missing"]
+
+
+def test_a_recorded_path_outside_the_venv_is_not_damage(tmp_path, site_packages):
+ """It belongs to something else, and reinstalling ours would not restore it."""
+ venv = site_packages.parent
+ (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding = "utf-8")
+ dist_info = _dist(site_packages)
+ _record(dist_info, [["../../elsewhere/thing", "sha256=z", 4]])
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_parent_relative_row_outside_a_venv_is_skipped(site_packages):
+ """No pyvenv.cfg, so nothing bounds the row and it stays out of scope."""
+ dist_info = _dist(site_packages)
+ _record(dist_info, [[f"../bin/{PKG}", "sha256=b", 4]])
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_vanished_companion_is_damage(tmp_path, monkeypatch, site_packages):
+ """No dist-info leaves the RECORD scan nothing to walk, and no check above
+ ever looked at the companion's version."""
+ dist_info = _dist(site_packages, name = "unsloth", version = VER)
+ size = _write(site_packages / "unsloth" / "__init__.py", "x = 1\n")
+ _record(dist_info, [["unsloth/__init__.py", "sha256=x", size]])
+ req_root = tmp_path / "requirements"
+ req_root.mkdir()
+ (req_root / install_manifest.BOOT_REQUIREMENT_FILE).write_text("", encoding = "utf-8")
+ monkeypatch.setattr(install_manifest, "installed_versions", lambda name: [VER])
+ install_manifest.write_manifest(root = tmp_path, req_root = req_root, package_name = "unsloth")
+
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["ok"] is True
+
+ monkeypatch.setattr(
+ install_manifest,
+ "installed_versions",
+ lambda name: [] if _canonical_name(name) == "unsloth-zoo" else [VER],
+ )
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["reason"] == "studio_install_damaged"
+
+
+def test_a_custom_package_does_not_have_to_ship_unsloth_zoo(tmp_path, monkeypatch, site_packages):
+ """`--package X` installs X alone, so its neighbours are not ours to fix."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ zoo_info = _dist(site_packages, name = "unsloth-zoo", version = "2.0")
+ _write(site_packages / "unsloth_zoo" / "__init__.py", "y = 2\n")
+ _record(zoo_info, [["unsloth_zoo/__init__.py", "sha256=y", 999999]])
+
+ state = install_manifest.verify_install(
+ root = tmp_path, req_root = req_root, package_name = PKG, deep = True
+ )
+ assert state["ok"] is True
+
+
+def _canonical_name(name):
+ return install_manifest._canonical(name)
+
+
+def test_a_custom_package_installs_no_companion(monkeypatch):
+ """The installer's own view has to agree with the scan's."""
+ import install_python_stack as ips
+
+ assert ips._core_package_names("unsloth") == ("unsloth", "unsloth-zoo")
+ assert ips._core_package_names("unsloth-nightly") == ("unsloth-nightly",)
+
+
+def test_a_manifest_with_no_recorded_version_is_damage(tmp_path, monkeypatch, site_packages):
+ """write_manifest stores whatever version it could read, so a package gone
+ when it ran is recorded as a finished install with none. Absence is the only
+ way to get here empty: ambiguity sets `local_conflict` first."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ manifest_path = install_manifest.manifest_path(tmp_path)
+ manifest = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ manifest["package_version"] = ""
+ manifest_path.write_text(json.dumps(manifest), encoding = "utf-8")
+
+ monkeypatch.setattr(install_manifest, "installed_versions", lambda name: [])
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["reason"] == "studio_install_damaged"
+
+
+def test_ambiguous_metadata_still_reports_its_own_reason(tmp_path, monkeypatch, site_packages):
+ """Also empty, but a conflict: these strings are a contract the desktop reads."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ req_root = _complete_install(tmp_path, monkeypatch, site_packages)
+ monkeypatch.setattr(install_manifest, "installed_versions", lambda name: [VER, "2.0"])
+ state = install_manifest.verify_install(root = tmp_path, req_root = req_root, deep = True)
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_a_stat_that_never_returns_does_not_wedge_setup(site_packages, monkeypatch):
+ """Nothing in-process bounds a syscall that never returns, and no installer
+ wraps its `verify_install(deep = True)` call in a timeout."""
+ import threading
+
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ released = threading.Event()
+ monkeypatch.setattr(Path, "stat", lambda self, *a, **k: released.wait())
+ try:
+ started = time.monotonic()
+ assert install_manifest.damaged_payload_files(PKG, budget_seconds = 0.5) == []
+ assert time.monotonic() - started < 5.0
+ finally:
+ # The worker is a daemon, but this keeps it from outliving the test.
+ released.set()
+
+
+def test_an_unbounded_scan_stays_on_this_thread(site_packages, monkeypatch):
+ """`budget_seconds = 0` is the installer: it needs the real answer."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ (site_packages / PKG / "__init__.py").unlink()
+ caller = threading.get_ident()
+ seen = {}
+ real = install_manifest._scan_payload_files
+
+ def record(*args, **kwargs):
+ seen["thread"] = threading.get_ident()
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(install_manifest, "_scan_payload_files", record)
+ assert install_manifest.damaged_payload_files(PKG, budget_seconds = 0.0) == [
+ f"{PKG}/__init__.py is missing"
+ ]
+ assert seen["thread"] == caller
+
+
+def _launcher_case(site_packages: Path):
+ """A recorded console script, the way a wheel records one."""
+ venv = site_packages.parent
+ (venv / "pyvenv.cfg").write_text("home = /usr\n", encoding = "utf-8")
+ dist_info = _dist(site_packages)
+ size = _write(venv / "Scripts" / "unsloth.exe", "MZ binary\n")
+ _record(dist_info, [["../Scripts/unsloth.exe", "sha256=b", size]])
+ return venv / "Scripts" / "unsloth.exe"
+
+
[email protected]("suffix", [".update-stale", ".update-backup", ".deleteme"])
+def test_a_launcher_an_update_moved_aside_is_not_damage(site_packages, suffix):
+ """setup.ps1's deep check runs inside the window `_move_launcher_aside`
+ opens, so without this every healthy Windows update loses its fast path and
+ force-reinstalls the core package over the network."""
+ launcher = _launcher_case(site_packages)
+ launcher.rename(launcher.with_name(launcher.name + suffix))
+ assert install_manifest.damaged_payload_files(PKG) == []
+
+
+def test_a_launcher_with_nothing_staged_beside_it_is_still_damage(site_packages):
+ """The quarantine this exists to catch, with no update in flight."""
+ launcher = _launcher_case(site_packages)
+ launcher.unlink()
+ assert install_manifest.damaged_payload_files(PKG) == ["../Scripts/unsloth.exe is missing"]
+
+
+def test_an_unrelated_sibling_does_not_excuse_a_missing_file(site_packages):
+ """Only the three names `_recover_missing_launcher` reads count."""
+ launcher = _launcher_case(site_packages)
+ launcher.rename(launcher.with_name(launcher.name + ".bak"))
+ assert install_manifest.damaged_payload_files(PKG) == ["../Scripts/unsloth.exe is missing"]
+
+
+def test_a_truncated_staged_copy_is_no_excuse(site_packages):
+ """`_recover_missing_launcher` reads these through `_is_valid_pe`."""
+ launcher = _launcher_case(site_packages)
+ launcher.unlink()
+ (launcher.parent / "unsloth.exe.update-stale").write_text("", encoding = "utf-8")
+ assert install_manifest.damaged_payload_files(PKG) == ["../Scripts/unsloth.exe is missing"]
+
+
+def test_a_staged_copy_that_is_not_a_pe_is_no_excuse(site_packages):
+ launcher = _launcher_case(site_packages)
+ launcher.unlink()
+ (launcher.parent / "unsloth.exe.deleteme").write_text("not a binary", encoding = "utf-8")
+ assert install_manifest.damaged_payload_files(PKG) == ["../Scripts/unsloth.exe is missing"]
+
+
+def test_only_the_launcher_is_ever_excused(site_packages):
+ """Only the launcher is staged, so a stray sibling elsewhere is no excuse."""
+ dist_info, rows = _healthy(site_packages)
+ _record(dist_info, rows)
+ module = site_packages / PKG / "__init__.py"
+ module.rename(module.with_name(module.name + ".update-stale"))
+ assert install_manifest.damaged_payload_files(PKG) == [f"{PKG}/__init__.py is missing"]
+
+
+def _installer_helper_probe() -> str:
+ """The manifest-helper probe exactly as setup.sh runs it."""
+ import re
+
+ repo = Path(__file__).resolve().parents[3]
+ setup = (repo / "studio" / "setup.sh").read_text(encoding = "utf-8")
+ match = re.search(
+ r'if ! "\$VENV_DIR/bin/python" -c "\n(import os, sys\n.*?)" "\$SCRIPT_DIR"', setup, re.S
+ )
+ assert match, "the manifest-helper probe moved; this test is reading the wrong block"
+ return match.group(1)
+
+
+ "contents,expected",
+ [
+ (None, 0),
+ ("def broken(:\n", 1),
+ ("raise RuntimeError('quarantined')\n", 1),
+ ],
+ ids = ["absent-keeps-the-fast-path", "truncated-forces-repair", "raises-forces-repair"],
+)
+def test_an_unimportable_helper_forces_the_dependency_pass(tmp_path, contents, expected):
+ """The one file whose damage silences every check that follows it.
+
+ Absent keeps the old escape: telling it from an old tree needs a RECORD walk
+ here, and the CLI reports it as studio_install_manifest_missing anyway.
+ """
+ import subprocess
+
+ script_dir = tmp_path / "studio"
+ script_dir.mkdir()
+ if contents is not None:
+ (script_dir / "install_manifest.py").write_text(contents, encoding = "utf-8")
+ result = subprocess.run(
+ [sys.executable, "-c", _installer_helper_probe(), str(script_dir)],
+ capture_output = True,
+ )
+ assert result.returncode == expected
+
+
+def test_both_installers_run_the_same_helper_probe():
+ repo = Path(__file__).resolve().parents[3]
+ guard = "sys.exit(1 if os.path.isfile(os.path.join(sys.argv[1], 'install_manifest.py')) else 0)"
+ for name in ("studio/setup.sh", "studio/setup.ps1"):
+ assert guard in (repo / name).read_text(encoding = "utf-8"), name
diff --git a/unsloth_cli/_studio_deps.py b/unsloth_cli/_studio_deps.py
index 60fa3364b98..4438f77fb49 100644
--- a/unsloth_cli/_studio_deps.py
+++ b/unsloth_cli/_studio_deps.py
@@ -294,7 +294,7 @@ def _verify_install_supports(module, parameter: str) -> bool:
return False
-def install_state(extra_roots: Sequence[Path] = ()) -> dict:
+def install_state(extra_roots: Sequence[Path] = (), deep: bool = False) -> 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
@@ -341,8 +341,21 @@ def install_state(extra_roots: Sequence[Path] = ()) -> dict:
kwargs = {"root": root, "req_root": req_root, "installed": installed}
if _verify_install_supports(module, "installed_conflicts"):
kwargs["installed_conflicts"] = installed_conflicts
+ if deep and _verify_install_supports(module, "deep"):
+ kwargs["deep"] = True
+ # Without that venv's site-packages the scan answers for this
+ # interpreter's tree. Guarded separately: a module new enough
+ # for `deep` may predate `scan_paths`.
+ if _verify_install_supports(module, "scan_paths"):
+ paths = [str(path) for path in _venv_site_packages(root)]
+ if paths:
+ kwargs["scan_paths"] = paths
return module.verify_install(**kwargs)
- state = module.verify_install(root = root)
+ # Off for `desktop-capabilities`: the Tauri preflight times it out at
+ # 10s, and a probe that overruns repairs a healthy venv. `verify-install`
+ # is untimed, so it opts in.
+ deep_kwargs = {"deep": True} if (deep and _verify_install_supports(module, "deep")) else {}
+ state = module.verify_install(root = root, **deep_kwargs)
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.
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 2e9f60becce..884807e0a48 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -671,13 +671,16 @@ def _find_run_py() -> Optional[Path]:
return None
-def _install_state() -> dict:
+def _install_state(deep: bool = False) -> dict:
"""verify_install() result for this install root.
STUDIO_HOME is an extra search root so a CLI installed outside the managed
venv still inspects the venv the desktop app launches.
"""
- return _studio_deps.install_state(extra_roots = (STUDIO_HOME / "unsloth_studio",))
+ return _studio_deps.install_state(
+ extra_roots = (STUDIO_HOME / "unsloth_studio",),
+ deep = deep,
+ )
_RUN_MODULE = None
@@ -4787,8 +4790,11 @@ def verify_install(
Exits 0 when complete, 1 otherwise. setup.sh / setup.ps1 use the exit code
to decide whether the "already up to date" fast path may be taken.
+
+ Scans the installed files too, unlike `desktop-capabilities`: nothing times
+ this one out.
"""
- state = _install_state()
+ state = _install_state(deep = True)
if json_output:
typer.echo(json.dumps(state, sort_keys = True))