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: repair duplicate package metadata during updates (#8515)

oobabooga90644db9e861
diff --git a/install.ps1 b/install.ps1
index 44ff2fcb0af..fdb74e92c34 100644
--- a/install.ps1
+++ b/install.ps1
@@ -5886,8 +5886,27 @@ exit 0
}
}
- $installedPackageVersion = (& $VenvPython -c "from importlib.metadata import version; import sys; print(version(sys.argv[1]))" $PackageName 2>$null | Out-String).Trim()
- if ($LASTEXITCODE -eq 0 -and $installedPackageVersion) {
+ $installedPackageVersion = (& $VenvPython -c "
+import sys
+try:
+ from studio.install_manifest import installed_version_probe
+except Exception:
+ # --package installs something that does not ship studio/. Report what the
+ # old probe would have, rather than claiming the version is unknown.
+ from importlib.metadata import PackageNotFoundError, version
+ try:
+ print(version(sys.argv[1]))
+ except PackageNotFoundError:
+ sys.exit(1)
+ sys.exit(0)
+installed, conflict = installed_version_probe(sys.argv[1])
+print(installed)
+sys.exit(2 if conflict else (0 if installed else 1))
+" $PackageName 2>$null | Out-String).Trim()
+ $_installedPackageVersionExit = $LASTEXITCODE
+ if ($_installedPackageVersionExit -eq 2) {
+ substep "duplicate metadata found for $PackageName; the dependency pass will repair it" "Cyan"
+ } elseif ($_installedPackageVersionExit -eq 0 -and $installedPackageVersion) {
step $PackageName "$installedPackageVersion installed"
} else {
substep "[WARN] installed $PackageName version could not be determined" "Yellow"
diff --git a/install.sh b/install.sh
index f5bff7cd12e..68322c99737 100755
--- a/install.sh
+++ b/install.sh
@@ -5385,10 +5385,34 @@ else
fi
fi
-_installed_package_version=$("$_VENV_PY" -c \
- 'from importlib.metadata import version; import sys; print(version(sys.argv[1]))' \
- "$PACKAGE_NAME" 2>/dev/null || true)
-if [ -n "$_installed_package_version" ]; then
+# Same probe as install.ps1: version() answers from whichever record the finder
+# yields first, so a duplicate would be reported here as an ordinary version.
+_installed_package_version_exit=0
+if _installed_package_version=$("$_VENV_PY" -c '
+import sys
+try:
+ from studio.install_manifest import installed_version_probe
+except Exception:
+ # --package installs something that does not ship studio/. Report what the
+ # old probe would have, rather than claiming the version is unknown.
+ from importlib.metadata import PackageNotFoundError, version
+ try:
+ print(version(sys.argv[1]))
+ except PackageNotFoundError:
+ sys.exit(1)
+ sys.exit(0)
+installed, conflict = installed_version_probe(sys.argv[1])
+print(installed)
+sys.exit(2 if conflict else (0 if installed else 1))
+' "$PACKAGE_NAME" 2>/dev/null); then
+ :
+else
+ _installed_package_version_exit=$?
+ _installed_package_version=""
+fi
+if [ "$_installed_package_version_exit" -eq 2 ]; then
+ substep "duplicate metadata found for $PACKAGE_NAME; the dependency pass will repair it"
+elif [ -n "$_installed_package_version" ]; then
step "$PACKAGE_NAME" "$_installed_package_version installed"
else
substep "[WARN] installed $PACKAGE_NAME version could not be determined" "$C_WARN"
diff --git a/studio/install_manifest.py b/studio/install_manifest.py
index fec8a59591f..269b67386cf 100644
--- a/studio/install_manifest.py
+++ b/studio/install_manifest.py
@@ -25,7 +25,7 @@ import re
import sys
import time
from pathlib import Path
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional, Sequence, Tuple
MANIFEST_NAME = "unsloth_install_manifest.json"
MANIFEST_SCHEMA = 1
@@ -119,16 +119,137 @@ def _canonical(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()
+def _metadata_scan_paths() -> List[str]:
+ """This interpreter's site-packages roots, excluding inherited sys.path entries.
+
+ Deduplicated by real path, not by string: purelib hardcodes `lib` while
+ platlib follows sys.platlibdir, so a lib64 build (Fedora, SuSE) names one
+ directory twice through venv's lib64 -> lib symlink. Scanning both would
+ report every package twice and turn a healthy venv into a conflict.
+ """
+ import sysconfig
+
+ paths: List[str] = []
+ seen: set = set()
+ try:
+ configured = sysconfig.get_paths()
+ except Exception:
+ return paths
+ for key in ("purelib", "platlib"):
+ path = configured.get(key)
+ if not path or not os.path.isdir(path):
+ continue
+ try:
+ key_path = os.path.realpath(path)
+ except OSError:
+ key_path = path
+ if key_path in seen:
+ continue
+ seen.add(key_path)
+ paths.append(path)
+ return paths
+
+
+def _installed_metadata_records(dist_name: str) -> List[Tuple[str, Optional[Path]]]:
+ """Every matching metadata version and its directory, when available."""
+ from importlib.metadata import distributions
+
+ wanted = _canonical(dist_name)
+ paths = _metadata_scan_paths()
+ kwargs = {"path": paths} if paths else {}
+ found: List[Tuple[str, Optional[Path]]] = []
+ for dist in distributions(**kwargs):
+ path = getattr(dist, "_path", None)
+ try:
+ record_path = Path(os.fspath(path)) if path is not None else None
+ except (TypeError, ValueError):
+ record_path = None
+ try:
+ name = dist.metadata.get("Name")
+ if name:
+ if _canonical(name) == wanted:
+ found.append((dist.version or "", record_path))
+ continue
+ except Exception:
+ pass
+ # A nameless or unreadable matching record is itself a conflict. Wheel
+ # metadata directory names escape name separators as underscores, so
+ # splitting off the final version is unambiguous.
+ stem = record_path.name if record_path is not None else ""
+ path_name, separator, _version = stem.removesuffix(".dist-info").rpartition("-")
+ if stem.endswith(".dist-info") and separator and _canonical(path_name) == wanted:
+ found.append(("", record_path))
+ return sorted(found, key = lambda record: (record[0], os.fspath(record[1] or "")))
+
+
+def installed_versions(dist_name: str) -> List[str]:
+ """Every metadata version for one canonical distribution name.
+
+ More than one answer is an inconsistent environment, not a choice between
+ equivalent records: importlib.metadata.version() returns whichever record
+ the finder yields first, which can be a dist-info left by a failed uninstall.
+ """
+ return [version for version, _path in _installed_metadata_records(dist_name)]
+
+
+def invalid_metadata_paths(dist_name: str) -> List[Path]:
+ """Matching metadata directories that pip cannot safely identify."""
+ return [
+ path
+ for version, path in _installed_metadata_records(dist_name)
+ if not version and path is not None
+ ]
+
+
+def pip_backup_metadata_paths(dist_name: str) -> List[Path]:
+ """Matching records left behind by an interrupted pip upgrade.
+
+ pip renames the outgoing distribution to a `~` prefixed sibling while it
+ installs the replacement, so a kill mid-operation keeps both. The METADATA
+ still names the real project, so it counts as a duplicate here, but pip
+ calls the directory invalid: `pip uninstall <name>` can never consume it.
+ """
+ return [
+ path
+ for _version, path in _installed_metadata_records(dist_name)
+ if path is not None and path.name.startswith("~")
+ ]
+
+
+def metadata_conflict(versions: Sequence[str]) -> bool:
+ """Whether matching metadata records are duplicated or unreadable."""
+ return len(versions) > 1 or any(not version for version in versions)
+
+
+def _metadata_is_inconsistent(dist_name: str, versions: Optional[List[str]] = None) -> bool:
+ """Duplicated, unreadable, or standing on a record pip will not honour.
+
+ A sole `~` backup is the case a version count cannot see: one readable
+ version, so nothing looks wrong, while pip refuses the directory and the
+ package tree is usually renamed away with it. Left unflagged, the fast path
+ calls the package up to date and skips the pass that would reinstall it.
+ """
+ if versions is None:
+ versions = installed_versions(dist_name)
+ return bool(metadata_conflict(versions) or pip_backup_metadata_paths(dist_name))
+
+
+def installed_version_probe(
+ dist_name: str, companion_names: Sequence[str] = ()
+) -> Tuple[str, bool]:
+ """One unambiguous version and whether any requested metadata conflicts."""
+ versions = installed_versions(dist_name)
+ conflict = _metadata_is_inconsistent(dist_name, versions) or any(
+ _metadata_is_inconsistent(name) for name in companion_names
+ )
+ version = versions[0] if len(versions) == 1 and versions[0] else ""
+ return version, conflict
+
+
def _installed_version(dist_name: str, installed: Optional[Dict[str, str]] = None) -> Optional[str]:
if installed is not None:
return installed.get(_canonical(dist_name))
- from importlib.metadata import PackageNotFoundError, version
- try:
- return version(dist_name)
- except PackageNotFoundError:
- return None
- except Exception:
- return None
+ return installed_version_probe(dist_name)[0] or None
def remove_manifest(root: Optional[Path] = None) -> bool:
@@ -359,15 +480,17 @@ def verify_install(
req_root: Optional[Path] = None,
package_name: str = "unsloth",
installed: Optional[Dict[str, str]] = None,
+ installed_conflicts: Optional[Sequence[str]] = None,
) -> dict:
"""Report whether the managed install finished and can still boot.
Reason strings are surfaced verbatim by the desktop preflight as its
staleness reason, so keep them stable.
- Pass `installed` (and the matching `root` / `req_root`) to describe a venv
- other than this interpreter's; without it the version and dependency checks
- would answer for the venv the caller happens to be running in.
+ Pass `installed`, `installed_conflicts`, and the matching `root` / `req_root`
+ 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.
"""
reqs = req_root or requirements_root()
missing = missing_requirements(reqs / BOOT_REQUIREMENT_FILE, installed = installed)
@@ -384,9 +507,21 @@ def verify_install(
else:
# `update --package X` records X, so comparing against unsloth would
# report a permanent version change.
- current = _installed_version(manifest.get("package") or package_name, installed)
+ manifest_package = manifest.get("package") or package_name
+ if installed is None:
+ companions = () if _canonical(manifest_package) == "unsloth-zoo" else ("unsloth-zoo",)
+ current, local_conflict = installed_version_probe(manifest_package, companions)
+ else:
+ current = _installed_version(manifest_package, installed)
+ local_conflict = False
+ foreign_conflicts = {_canonical(name) for name in (installed_conflicts or ())}
+ core_conflict = _canonical(manifest_package) in foreign_conflicts or (
+ _canonical(manifest_package) != "unsloth-zoo" and "unsloth-zoo" in foreign_conflicts
+ )
recorded = manifest.get("package_version")
- if current and recorded and current != recorded:
+ if core_conflict or local_conflict:
+ reason = "studio_install_metadata_conflict"
+ elif current and recorded and current != recorded:
reason = "studio_install_version_changed"
elif manifest.get("requirement_files") != requirement_digests(reqs):
reason = "studio_install_requirements_changed"
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index e2f24f1466f..9863b5025e7 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -11,7 +11,10 @@ activated. Expects `pip` and `python` on PATH to point at the venv.
from __future__ import annotations
+import ast
+import functools
import glob
+import importlib
import importlib.util
import json
import os
@@ -3896,6 +3899,566 @@ def _shared_base_requirements() -> Path | None:
return None
+def _overlay_local_core_package(
+ name: str,
+ local_repo: str,
+ *,
+ strict: bool = True,
+) -> bool:
+ """Install one core package from the source selected by --local.
+
+ strict=False reports a failed install instead of exiting, which the metadata
+ repair needs: by the time it installs, it has already removed the records it
+ is replacing, so it has to say so rather than die mid-way.
+ """
+ canonical = re.sub(r"[-_.]+", "-", name).lower()
+ if canonical == "unsloth":
+ step_label = f"overlaying local repo (editable): {local_repo}"
+ install_label = "Overlaying local repo (editable)"
+ args = ("-e", local_repo)
+ elif canonical == "unsloth-zoo":
+ step_label = "overlaying unsloth-zoo from git main"
+ install_label = "Overlaying unsloth-zoo from git main"
+ args = ("--force-reinstall", "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo")
+ else:
+ return False
+ _step(_LABEL, step_label)
+ if not strict:
+ return pip_install_try(install_label, "--no-cache-dir", "--no-deps", *args, constrain = False)
+ pip_install(install_label, "--no-cache-dir", "--no-deps", *args, constrain = False)
+ return True
+
+
+def _overlay_local_core_packages(local_repo: str) -> None:
+ for name in ("unsloth", "unsloth-zoo"):
+ _overlay_local_core_package(name, local_repo)
+
+
+def _run_ok(label: str, cmd: list) -> bool:
+ """run() without the exit: the metadata repair has to unwind, not die."""
+ if VERBOSE:
+ _step(_LABEL, f"{label}...", _dim)
+ result = subprocess.run(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ env = _install_env_for_cmd(cmd),
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ if result.returncode != 0 and result.stdout:
+ _safe_print(_redact_install_output(result.stdout))
+ return result.returncode == 0
+
+
+def _is_overlayable_core_package(name: str) -> bool:
+ """Whether _overlay_local_core_package knows a source for this name."""
+ return re.sub(r"[-_.]+", "-", name).lower() in ("unsloth", "unsloth-zoo")
+
+
+def _overlay_source_spec(name: str, local_repo: str) -> str:
+ """What pip would be asked to build for this overlay.
+
+ unsloth-zoo comes from git, so an overlay is a network fetch just as much as
+ an index install is: it has to be staged before anything is uninstalled.
+ """
+ canonical = re.sub(r"[-_.]+", "-", name).lower()
+ if canonical == "unsloth":
+ return local_repo
+ if canonical == "unsloth-zoo":
+ return "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo"
+ return ""
+
+
+def _rewrite_minimal_metadata(path: str, name: str) -> bool:
+ """Replace an unparseable METADATA with the least pip needs to uninstall by RECORD.
+
+ Returns False when there is no RECORD to uninstall from, the one case that has
+ to fail closed: without it neither pip nor this installer knows which files
+ belong to the package, and laying a replacement over them would leave whatever
+ the new release no longer ships behind, still importable. The version is taken
+ from the directory name, where importlib's own fallback reads it from when
+ METADATA cannot be parsed.
+ """
+ # invalid_metadata_paths() hands back Path objects, so normalise before the
+ # string work below.
+ path = os.fspath(path)
+ if not os.path.isfile(os.path.join(path, "RECORD")):
+ return False
+ stem = os.path.basename(path.rstrip(os.sep)).removesuffix(".dist-info")
+ _package, separator, version = stem.rpartition("-")
+ if not separator or not version:
+ return False
+ try:
+ with open(os.path.join(path, "METADATA"), "w", encoding = "utf-8") as handle:
+ handle.write(f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n")
+ except OSError:
+ return False
+ return True
+
+
+class _QuarantinedMetadata:
+ """Invalid metadata directories moved aside, restorable until committed.
+
+ pip cannot parse an unreadable record: a non-UTF-8 METADATA makes pip list,
+ show and uninstall raise for the whole environment, so it has to be out of
+ the way before pip runs at all. Deleting it outright is not an option
+ either, because staging the replacement can still fail and a package whose
+ only record was deleted is left with files and no install at all.
+ """
+
+ def __init__(self) -> None:
+ self._holding = ""
+ self._moved: list = []
+ self._copied: list = []
+
+ def _holding_dir(self) -> str:
+ if not self._holding:
+ self._holding = tempfile.mkdtemp(prefix = "unsloth_metadata_quarantine_")
+ return self._holding
+
+ def back_up(self, path) -> bool:
+ """Keep a copy of a file that is about to be rewritten in place.
+
+ The rewrite has to happen before staging, and staging can still fail. Without
+ this the original is gone and what remains is a synthetic record that parses:
+ the next run would see one readable record, decide nothing is wrong, and never
+ attempt the payload repair that is still owed.
+
+ An absent METADATA is nothing to back up rather than a failure. Recording it
+ as absent still lets the rewrite proceed, so pip can uninstall that record by
+ its RECORD; restore() then deletes the synthetic file instead of reinstating
+ one that never existed.
+ """
+ path = os.fspath(path)
+ if not os.path.exists(path):
+ self._copied.append((path, None))
+ return True
+ target = os.path.join(self._holding_dir(), f"copy_{len(self._copied)}")
+ try:
+ shutil.copy2(path, target)
+ except OSError:
+ return False
+ self._copied.append((path, target))
+ return True
+
+ def take(self, paths) -> bool:
+ for path in paths:
+ target = os.path.join(
+ self._holding_dir(), f"{len(self._moved)}_{os.path.basename(path)}"
+ )
+ try:
+ shutil.move(os.fspath(path), target)
+ except OSError:
+ return False
+ self._moved.append((os.fspath(path), target))
+ return True
+
+ def forget_copies(self) -> None:
+ """Drop the backed-up METADATA copies, keeping the moved directories.
+
+ Called once a staged reinstall has put the package back: the wheel's own
+ metadata is authoritative, so copying the original over it would re-break the
+ package the rollback just repaired, and deleting it (where the original was
+ absent) would strip a record pip just wrote. The moved entries stay, because a
+ record pip cannot consume still has to go back as found.
+ """
+ self._copied.clear()
+
+ def restore(self) -> None:
+ while self._moved:
+ original, target = self._moved.pop()
+ try:
+ shutil.move(target, original)
+ except OSError:
+ pass
+ while self._copied:
+ original, target = self._copied.pop()
+ try:
+ if target is None:
+ os.remove(original)
+ else:
+ shutil.copy2(target, original)
+ except OSError:
+ pass
+ self.discard()
+
+ def discard(self) -> None:
+ if self._holding:
+ shutil.rmtree(self._holding, ignore_errors = True)
+ self._holding = ""
+ self._moved.clear()
+ self._copied.clear()
+
+
+def _restore_from_staged(
+ name: str,
+ staged: str,
+ removed_any: bool,
+ quarantine: "_QuarantinedMetadata | None" = None,
+) -> None:
+ """Put the payload back when the uninstall loop stops part way through.
+
+ An earlier successful uninstall has already deleted the package tree, so
+ returning here without this leaves a surviving dist-info claiming an
+ installed core package whose files are gone.
+ """
+ if not (removed_any and staged):
+ return
+ if pip_install_try(
+ f"Restoring {name} after an incomplete metadata repair",
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "--no-index",
+ "--find-links",
+ staged,
+ name,
+ # pip, not uv: the wheel is already built and sitting in staged, and uv would
+ # reject the unpinned name under UV_REQUIRE_HASHES with the package records
+ # already gone. Routing through pip also earns the PIP_REQUIRE_HASHES relaxation.
+ force_pip = True,
+ ):
+ # The wheel just wrote its own valid metadata at the same path the rewritten
+ # record occupied, so the unwinding below must not put the original back over
+ # it. See _QuarantinedMetadata.forget_copies.
+ if quarantine is not None:
+ quarantine.forget_copies()
+ _safe_print(_red(f" restored {name} from the staged replacement"), file = sys.stderr)
+ else:
+ _safe_print(
+ _red(f" {name} is no longer installed. Re-run the installer to restore it."),
+ file = sys.stderr,
+ )
+
+
+def _requirement_args(requirement: str, staging: str) -> "list[str]":
+ """How to hand pip the requirement, as a file when it carries hashes.
+
+ pip only accepts --hash entries from a requirements file, and the hashes are what
+ stop it accepting a different artifact of the same version from a source uv never
+ considered. The file lives in the staging directory, so it is removed with it.
+ """
+ if "--hash=" not in requirement:
+ return [requirement]
+ path = os.path.join(staging, "requirement.txt")
+ with open(path, "w", encoding = "utf-8") as handle:
+ handle.write(requirement + "\n")
+ return ["-r", path]
+
+
+def _stage_replacement(name: str):
+ """Build the wheel that will replace a package, before it is removed.
+
+ Returns a directory to install from, or None when the package cannot be
+ obtained, which must abort the repair while the existing install is still
+ intact.
+
+ pip wheel, not pip download: a source-only index leaves an sdist, and the
+ install that follows runs --no-index, so its isolated build could not fetch
+ setuptools and the package would stay uninstalled. Building here, while the
+ index is still reachable, keeps that install offline-safe. pip and not uv
+ because uv has no `wheel` subcommand, so uv's own index variables and upload
+ cutoff have to be handed across explicitly to keep the provenance and the
+ reproducibility policy the other installs run under.
+ """
+ requirement, overrides, build_options = name, {}, []
+ offline_local = USE_UV and _uv_is_offline() and _is_local_source(name)
+ if offline_local:
+ # The checkout needs no network, but pip's isolated build fetches the build
+ # backend, which UV_OFFLINE does not reach: measured, an isolated build with no
+ # index fails at "installing build dependencies", and this repo pins those
+ # exactly. Build against the interpreter's own backend and forbid the index, so
+ # no-network means no network. An unimportable backend fails the build and
+ # leaves the installation intact.
+ build_options = ["--no-build-isolation"]
+ overrides = {"PIP_NO_INDEX": "1"}
+ if USE_UV and _uv_is_offline() and not _is_local_source(name):
+ # A checkout on disk needs no network, so offline has nothing to say about it.
+ _safe_print(
+ _red(
+ " UV_OFFLINE is set and pip has no offline mode, so repairing "
+ f"{name} would have to reach the network; leaving the install alone."
+ ),
+ file = sys.stderr,
+ )
+ return None
+ if USE_UV and not _is_direct_reference(name):
+ # A direct reference is its own provenance, so it is staged as written.
+ plan = _uv_staging_plan(name)
+ if plan is None:
+ _safe_print(
+ _red(
+ f" uv could not resolve a replacement for {name}, so its source "
+ "cannot be preserved; leaving the install alone."
+ ),
+ file = sys.stderr,
+ )
+ return None
+ requirement, overrides, build_options = plan
+ cutoff_args = _uv_upload_cutoff_args()
+ if cutoff_args is None:
+ _safe_print(
+ _red(
+ " UV_EXCLUDE_NEWER is set but this pip is too old to honour it "
+ "(needs 25.3 for --uploaded-prior-to); leaving the install alone."
+ ),
+ file = sys.stderr,
+ )
+ return None
+ staging = tempfile.mkdtemp(prefix = "unsloth_metadata_repair_")
+ cmd = [
+ sys.executable,
+ "-m",
+ "pip",
+ "wheel",
+ "--no-deps",
+ *cutoff_args,
+ *build_options,
+ "--wheel-dir",
+ staging,
+ *_requirement_args(requirement, staging),
+ ]
+ env = _install_env_for_cmd(cmd)
+ if overrides:
+ env = dict(env if env is not None else os.environ)
+ env.update(overrides)
+ # Written into the staging directory, so it is removed with it.
+ env["PIP_CONFIG_FILE"] = _pip_config_without_sources(staging)
+ result = subprocess.run(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ env = env,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ if result.returncode == 0 and glob.glob(os.path.join(staging, "*.whl")):
+ return staging
+ if VERBOSE and result.stdout:
+ _safe_print(_redact_install_output(result.stdout))
+ shutil.rmtree(staging, ignore_errors = True)
+ return None
+
+
+def _repair_duplicate_core_metadata(
+ package_names: "tuple[str, ...]",
+ *,
+ local_repo: str = "",
+ ci_source_overlay: str = "",
+) -> bool:
+ """Reinstall managed core packages whose metadata has more than one record.
+
+ Remove invalid records directly because pip cannot parse them, then repeat a
+ dependency-free uninstall until no valid record remains, because pip's
+ force-reinstall only uninstalls the one record its finder selects. The
+ requested source can then be installed without asking a resolver to replace
+ the existing torch build. The normal dependency pass still follows.
+
+ The replacement is fetched BEFORE anything is removed: the uninstall loop
+ deletes every record it finds, so an index unreachable at that moment
+ (offline, a private package name, a mirror outage) would otherwise leave the
+ venv with no unsloth at all and no way back.
+ """
+ duplicates: list[tuple[str, int]] = []
+ seen: set[str] = set()
+ for name in package_names:
+ canonical = re.sub(r"[-_.]+", "-", name).lower()
+ if canonical in seen:
+ continue
+ seen.add(canonical)
+ versions = install_manifest.installed_versions(name)
+ record_count = len(versions)
+ # A sole `~` backup counts as one readable version, so metadata_conflict()
+ # cannot see it, yet pip and importlib both skip the directory and the real
+ # tree is usually renamed away with it. Repair it like any other duplicate.
+ if install_manifest.metadata_conflict(
+ versions
+ ) or install_manifest.pip_backup_metadata_paths(name):
+ duplicates.append((name, record_count))
+
+ repaired: list[str] = []
+ staging_dirs: list[str] = []
+ # One quarantine per package, discarded as soon as that package is back in place.
+ # Sharing one would, on a later package's failure, restore the first package's stale
+ # record over the install that replaced it: the conflict returns, and its old RECORD
+ # then describes a payload that is gone.
+ quarantine = _QuarantinedMetadata()
+ succeeded = False
+ try:
+ for name, record_count in duplicates:
+ quarantine = _QuarantinedMetadata()
+ _step(_LABEL, f"duplicate metadata for {name} detected; reinstalling it", _dim)
+ invalid_paths = install_manifest.invalid_metadata_paths(name)
+ # Give pip a parseable METADATA beside every intact RECORD so it can
+ # uninstall them normally, removing exactly the files they list.
+ # Quarantining one instead drops its RECORD, so the uninstall loop removes
+ # only what the readable records claim and a module existing solely in the
+ # older release stays on disk and importable while the repair reports success.
+ unrewritable = [
+ path
+ for path in invalid_paths
+ if not (
+ quarantine.back_up(os.path.join(path, "METADATA"))
+ and _rewrite_minimal_metadata(path, name)
+ )
+ ]
+ # Every record has to end up uninstallable by pip, or nothing is touched.
+ # Quarantining one instead only hides it: pip removes just the readable
+ # records, the quarantine is discarded once the reinstall succeeds, and
+ # whatever the quarantined release owned alone stays on disk and
+ # importable while the repair reports success and deletes the directory
+ # that was the evidence. Waiting for record_count to reach zero missed
+ # every case where another record survives. Refusing leaves the tree as
+ # found, so a later run can still see the conflict.
+ if unrewritable:
+ _safe_print(
+ _red(
+ f" the metadata for {name} at "
+ + ", ".join(os.path.basename(os.fspath(p)) for p in unrewritable)
+ + " cannot be read or rewritten, so the files that release owned "
+ "cannot be identified. Recreate the environment to repair it."
+ ),
+ file = sys.stderr,
+ )
+ return False
+ # pip skips its own abandoned backup ("Ignoring invalid distribution
+ # ~nsloth") while its METADATA still names the project, so the record
+ # counts here but no uninstall by name can consume it. Left in place the
+ # loop below cannot converge and the repair fails on every future run,
+ # which is the loop this whole path exists to end. Quarantined, not
+ # deleted: staging can still fail.
+ backups = install_manifest.pip_backup_metadata_paths(name)
+ if backups and not quarantine.take(backups):
+ _safe_print(
+ _red(f" could not move pip's leftover backup for {name} aside"),
+ file = sys.stderr,
+ )
+ return False
+ if invalid_paths or backups:
+ importlib.invalidate_caches()
+ record_count = len(install_manifest.installed_versions(name))
+ # A backup names a payload pip has already renamed away, so once it is
+ # aside there is nothing for a replacement to be laid over: a fresh
+ # install is exactly right, and refusing here would abort the installer
+ # on the one state it can trivially fix.
+ if invalid_paths and not record_count:
+ # Nothing is left for pip to uninstall, so the replacement would be
+ # laid over a payload no record describes.
+ _safe_print(
+ _red(
+ f" no usable metadata record is left for {name}, so its "
+ "files cannot be removed safely. Recreate the environment "
+ "to repair it."
+ ),
+ file = sys.stderr,
+ )
+ return False
+
+ canonical = re.sub(r"[-_.]+", "-", name).lower()
+ source_repo = local_repo or (ci_source_overlay if canonical == "unsloth" else "")
+ # A local or git source installs from a path or URL, so there is
+ # nothing to stage; anything else comes off an index, which has to
+ # be proven reachable while the current install is still intact.
+ overlaid = bool(source_repo) and _is_overlayable_core_package(name)
+ # Stage whichever source will be installed, overlay included: an
+ # overlay is a git fetch or a build, either of which can fail after
+ # the uninstall loop has already removed every record.
+ staged = _stage_replacement(
+ _overlay_source_spec(name, source_repo) if overlaid else name
+ )
+ if staged is None:
+ _safe_print(
+ _red(
+ f" could not fetch a replacement for {name}; leaving "
+ "the existing install in place"
+ ),
+ file = sys.stderr,
+ )
+ return False
+ staging_dirs.append(staged)
+
+ removed_any = False
+ while record_count:
+ if not _run_ok(
+ f"Removing an installed metadata record for {name}",
+ [sys.executable, "-m", "pip", "uninstall", "-y", name],
+ ):
+ _safe_print(
+ _red(f" could not uninstall a metadata record for {name}"),
+ file = sys.stderr,
+ )
+ _restore_from_staged(name, staged, removed_any, quarantine)
+ return False
+ importlib.invalidate_caches()
+ remaining = len(install_manifest.installed_versions(name))
+ if remaining >= record_count:
+ _safe_print(
+ _red(f" could not remove every metadata record for {name}"),
+ file = sys.stderr,
+ )
+ _restore_from_staged(name, staged, removed_any, quarantine)
+ return False
+ removed_any = True
+ record_count = remaining
+
+ # Installer handoffs may already have applied a local or CI source.
+ # Restore that provenance now that no ambiguous record remains.
+ restored = overlaid and _overlay_local_core_package(name, source_repo, strict = False)
+ if not restored:
+ # The overlay install is preferred because it keeps the editable
+ # or git provenance, but the staged wheel was built from that
+ # same source, so falling back to it never substitutes a release.
+ restored = pip_install_try(
+ f"Repairing duplicate metadata for {name}",
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "--no-index",
+ "--find-links",
+ staged,
+ name,
+ # As _restore_from_staged: pip, so a uv hash policy cannot reject the
+ # already-built wheel once every record has been removed.
+ force_pip = True,
+ )
+ if not restored:
+ _safe_print(
+ _red(
+ f" could not reinstall {name} after removing its duplicate "
+ "metadata; it is no longer installed. Re-run the installer "
+ "to restore it."
+ ),
+ file = sys.stderr,
+ )
+ return False
+ repaired.append(name)
+ # This package is back in place, so its old records must never return.
+ quarantine.discard()
+
+ importlib.invalidate_caches()
+ unresolved = [
+ name for name in repaired if not install_manifest.installed_version_probe(name)[0]
+ ]
+ if unresolved:
+ _safe_print(
+ _red(
+ " package metadata is inconsistent after reinstall: " + ", ".join(unresolved)
+ ),
+ file = sys.stderr,
+ )
+ return False
+ succeeded = True
+ return True
+ finally:
+ for staging in staging_dirs:
+ shutil.rmtree(staging, ignore_errors = True)
+ # Anything short of a completed repair puts the quarantined records back,
+ # so a failure leaves the environment as it was found.
+ if succeeded:
+ quarantine.discard()
+ else:
+ quarantine.restore()
+
+
def _translate_pip_args_for_uv(args: tuple[str, ...]) -> list[str]:
"""Translate pip flags to their uv equivalents."""
translated: list[str] = []
@@ -4008,20 +4571,308 @@ _PM_POLICY_ENV_VARS = (
def _relaxed_pip_policy_env(cmd: "list[str]") -> "dict[str, str]":
"""Overrides that stop a hardened user pip config failing the installer's own pip.
- Empty for anything that is not a `pip install` / `pip download` this module drives,
- every `uv` command included, so the "non-pinned installs inherit the caller env
- unchanged" contract holds on a machine with no hostile pip config.
+ Empty for anything that is not a `pip install` / `pip download` / `pip wheel` this
+ module drives, every `uv` command included, so the "non-pinned installs inherit the
+ caller env unchanged" contract holds on a machine with no hostile pip config.
+ `wheel` is in that set because the duplicate-metadata repair stages its replacement
+ with `pip wheel`, where require-hashes applies exactly as it does to install: an
+ unpinned name is rejected before anything is built, so the repair would abort on a
+ hardened machine and leave the conflict it exists to remove.
`require-hashes = true` makes pip reject any requirement without a --hash, which is
every requirements file we ship; that is what took the pip FALLBACK down in #8530
once uv had failed. pip applies env vars AFTER config files, so PIP_REQUIRE_HASHES=0
overrides it while pip.conf's index-url, trusted-host, cert and proxy stay in force.
"""
- if cmd[:1] == ["uv"] or not any(arg in ("install", "download") for arg in cmd):
+ if cmd[:1] == ["uv"] or not any(arg in ("install", "download", "wheel") for arg in cmd):
return {}
return {"PIP_REQUIRE_HASHES": "0"}
+def _uv_is_offline() -> bool:
+ """True when uv has been told not to touch the network."""
+ return os.environ.get("UV_OFFLINE", "").strip().lower() not in ("", "0", "false")
+
+
+def _uv_staging_plan(name: str) -> "tuple[str, dict[str, str]] | None":
+ """Ask uv which release and which index it would use, and reproduce that with pip.
+
+ Returns (requirement, pip env overrides), or None when uv could not resolve it.
+
+ Staging has to run pip, because uv has no `wheel` subcommand. Translating uv's index
+ configuration out of the environment cannot be made correct: uv also discovers
+ uv.toml, pyproject.toml [tool.uv] and a user config, honours UV_CONFIG_FILE, applies
+ an implicit PyPI default, and resolves under an index-strategy pip has no equivalent
+ for. Any of those missed means the repair can uninstall a private build and reinstall
+ the public package of the same name.
+
+ So uv is asked instead. `uv pip compile --emit-index-annotation` reports the exact
+ index each package resolved from, under uv's own discovery, priority, strategy and
+ upload cutoff, and pip is pointed at that one index with that one version. An
+ unreachable higher-priority index fails the compile rather than falling through to a
+ public fallback, which is the behaviour first-index exists to give.
+ """
+ cmd = [
+ "uv",
+ "pip",
+ "compile",
+ "--no-deps",
+ "--python",
+ sys.executable,
+ "--emit-index-url",
+ "--emit-find-links",
+ "--emit-index-annotation",
+ "--emit-build-options",
+ "--generate-hashes",
+ "-",
+ ]
+ try:
+ result = subprocess.run(
+ cmd,
+ input = name.encode(),
+ stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except OSError:
+ return None
+ if result.returncode != 0:
+ if VERBOSE and result.stderr:
+ _safe_print(_redact_install_output(result.stderr))
+ return None
+ requirement, origin = "", ""
+ hashes: list[str] = []
+ emitted: list[str] = []
+ find_links: list[str] = []
+ build_options: list[str] = []
+ canonical = _canonical_package_name(name)
+ for raw in (result.stdout or b"").decode("utf-8", "replace").splitlines():
+ line = raw.strip()
+ if line.startswith(("--index-url ", "--extra-index-url ")):
+ emitted.append(line.split(" ", 1)[1].strip())
+ elif line.startswith("--find-links "):
+ find_links.append(line.split(" ", 1)[1].strip())
+ elif line.startswith("--hash="):
+ hashes.append(line.rstrip("\\").strip())
+ elif line.startswith(("--no-binary ", "--only-binary ")):
+ # uv's artifact policy, which pip reads none of. Without it the repair can
+ # download a wheel under a no-binary rule or build an sdist under an
+ # only-binary one, changing the artifact type mid-repair.
+ option, _, value = line.partition(" ")
+ build_options.extend((option, value.strip()))
+ elif line.startswith("# from "):
+ # Names the index this package came from, the one to reproduce, but is not
+ # usable as written: measured on uv 0.10.7 the annotation drops userinfo
+ # while the emitted index lines keep it, so it is matched back to the
+ # emitted URL. A private index would answer 401 otherwise.
+ origin = line[len("# from ") :].strip() or origin
+ elif line and not line.startswith(("#", "-")):
+ # uv continues a hashed pin onto the following lines with a backslash.
+ pinned = line.split(";", 1)[0].rstrip("\\").strip()
+ if _canonical_package_name(_requirement_name(pinned)) == canonical:
+ requirement = pinned
+ if not requirement:
+ return None
+ # Replaying uv's answer means replacing pip's candidate sources, not adding to them.
+ # An inherited PIP_NO_INDEX would block the index uv picked, and an inherited
+ # extra index or find-links directory could satisfy the same version from a source
+ # uv never looked at, which is the provenance swap this whole path exists to stop.
+ # Empty rather than deleted: measured on pip 26.2, an empty value reads as unset.
+ overrides = {
+ "PIP_EXTRA_INDEX_URL": "",
+ "PIP_NO_INDEX": "",
+ "PIP_FIND_LINKS": " ".join(find_links),
+ }
+ index_url = _credentialed_index(origin, emitted)
+ if index_url:
+ overrides["PIP_INDEX_URL"] = index_url
+ elif find_links:
+ # uv resolved this from a flat source with no index in play, which is what a
+ # configured no-index looks like on the way out: it emits the find-links entry
+ # and no index line at all. Leaving PIP_NO_INDEX cleared would hand pip back
+ # the default PyPI and let it stage the same name and version from a source uv
+ # was told to exclude.
+ overrides["PIP_NO_INDEX"] = "1"
+ # Measured on uv 0.10.7: --emit-build-options surfaces the policy from uv.toml but
+ # NOT the environment-variable spelling of it, so that half is translated by hand.
+ # Only where pip has no setting of its own, which it reads natively.
+ # UV_KEYRING_PROVIDER is the same translation: uv reaches an authenticated index
+ # through the keyring CLI, and carrying only the URL leaves pip unable to fetch
+ # what uv just resolved. uv's two values (disabled, subprocess) are both valid pip
+ # values. Only the environment spelling is reachable here; a uv.toml
+ # keyring-provider is not emitted, so that half cannot be replayed.
+ for uv_name, pip_name in (
+ ("UV_NO_BINARY", "PIP_NO_BINARY"),
+ ("UV_ONLY_BINARY", "PIP_ONLY_BINARY"),
+ ("UV_KEYRING_PROVIDER", "PIP_KEYRING_PROVIDER"),
+ ):
+ value = os.environ.get(uv_name, "").strip()
+ if value and not os.environ.get(pip_name):
+ overrides[pip_name] = value
+ if hashes:
+ # The hashes are what make this safe rather than merely careful. Measured: pip
+ # verifies them even with PIP_REQUIRE_HASHES=0, and neither PIP_CONFIG_FILE nor
+ # --isolated suppresses a site pip.conf, so pip may still consult a source uv
+ # never considered. It can no longer accept a different artifact from one.
+ requirement = " \\\n ".join([requirement, *hashes])
+ return requirement, overrides, build_options
+
+
+_PIP_SOURCE_CONFIG_KEYS = ("index-url", "extra-index-url", "find-links", "no-index")
+
+
+def _pip_config_without_sources(directory: str) -> str:
+ """Write pip's own configuration back minus the candidate sources.
+
+ The environment overrides above cannot do this alone. Measured on pip 26.2: with
+ `extra-index-url` in pip.conf, an empty PIP_EXTRA_INDEX_URL does NOT suppress it,
+ so the config has to go for this one command, or uv's chosen index is only one
+ candidate among the user's.
+
+ Dropping it wholesale would take proxy, cert, client-cert and trusted-host with it,
+ and those are how a private index is reached, so uv would resolve and pip would then
+ fail to fetch. Everything except the four source keys is written back instead.
+ `pip config list` is asked rather than the files located, so global, user and site
+ are merged in pip's own order; `:env:` entries are skipped as they come from the
+ environment, handled above.
+ """
+ path = os.path.join(directory, "pip.conf")
+ try:
+ result = subprocess.run(
+ [sys.executable, "-m", "pip", "config", "list"],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.DEVNULL,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except OSError:
+ result = None
+ sections: dict[str, list[tuple[str, str]]] = {}
+ if result is not None and result.returncode == 0:
+ for line in (result.stdout or b"").decode("utf-8", "replace").splitlines():
+ name, separator, raw = line.partition("=")
+ if not separator or name.startswith(":env:"):
+ continue
+ section, _, option = name.strip().rpartition(".")
+ if not section or option in _PIP_SOURCE_CONFIG_KEYS:
+ continue
+ try:
+ value = ast.literal_eval(raw.strip())
+ except (ValueError, SyntaxError):
+ continue
+ # pip renders a multi-value setting as one newline separated string; an
+ # indented continuation is how it is spelled back into a config file.
+ sections.setdefault(section, []).append((option, str(value).replace("\n", "\n ")))
+ with open(path, "w", encoding = "utf-8") as handle:
+ for section, options in sections.items():
+ handle.write(f"[{section}]\n")
+ for option, value in options:
+ handle.write(
+ f"{option} ={value}\n" if value.startswith("\n") else f"{option} = {value}\n"
+ )
+ return path
+
+
+def _requirement_name(requirement: str) -> str:
+ """The distribution name from a pin or a PEP 508 direct reference.
+
+ An override can redirect a package to a path, a repository or a URL, and uv then
+ emits `name @ reference` rather than `name==version`. Treating the whole line as
+ the name left the requirement empty and aborted every repair under that policy.
+ """
+ head = requirement.split("==", 1)[0]
+ return head.split("@", 1)[0].strip()
+
+
+def _canonical_package_name(name: str) -> str:
+ return re.sub(r"[-_.]+", "-", name).strip().lower()
+
+
+def _strip_userinfo(url: str) -> str:
+ """The URL without any `user:password@`, which is how uv writes an annotation."""
+ scheme, separator, rest = url.partition("://")
+ if not separator:
+ return url
+ authority, slash, tail = rest.partition("/")
+ _credentials, at_sign, host = authority.rpartition("@")
+ return f"{scheme}://{host}{slash}{tail}" if at_sign else url
+
+
+def _credentialed_index(origin: str, emitted: "list[str]") -> str:
+ """The emitted index matching the annotated origin, credentials intact.
+
+ uv emits every index it was configured with, credentials and all, but strips
+ userinfo from the `# from` annotation that says which one answered. Taking the
+ annotation at face value hands pip an unauthenticated URL for a private index,
+ which answers 401 and aborts the repair. Matching is on the credential-free form
+ of each emitted URL, so an authenticated extra index is recovered too.
+ """
+ if origin:
+ target = _strip_userinfo(origin).rstrip("/")
+ matches = [url for url in emitted if _strip_userinfo(url).rstrip("/") == target]
+ # One index can be emitted both with and without credentials; the whole point
+ # here is the credentialed form, so it wins over a bare match on the same URL.
+ for url in matches:
+ if _strip_userinfo(url) != url:
+ return url
+ if matches:
+ return matches[0]
+ # The origin is not one of the emitted indexes, so it is a find-links source --
+ # uv annotates those with a file:// or directory URL. That belongs in
+ # PIP_FIND_LINKS, which is already set from the emitted find-links lines, and
+ # must not displace the real index: an sdist picked out of a flat directory still
+ # needs the index for its build backend.
+ return emitted[0] if emitted else ""
+
+
+def _is_local_source(requirement: str) -> bool:
+ """True when the replacement is already on disk, so no network is needed."""
+ return os.path.exists(requirement)
+
+
+def _is_direct_reference(requirement: str) -> bool:
+ """True when the requirement already names the source to build from.
+
+ The overlay paths hand staging a git URL or a local checkout rather than a bare
+ name, and such a requirement carries its own provenance: no index was consulted
+ to choose it, so there is nothing for uv to have decided and nothing to preserve.
+ Asking uv to resolve it would also compare a bare spec against uv's output, which
+ appends the resolved commit and so could never match.
+ """
+ return "://" in requirement or _is_local_source(requirement)
+
+
+def _uv_upload_cutoff_args() -> "list[str] | None":
+ """pip arguments carrying UV_EXCLUDE_NEWER, or None when it cannot be honoured.
+
+ uv's --exclude-newer limits candidates by upload time, and staging runs pip, which
+ ignores the variable and would stage a release the user's policy excludes. pip's
+ --uploaded-prior-to is the same filter and takes the same date spellings, but it only
+ exists from pip 25.3. Refusing to stage is the correct answer on an older pip: the
+ repair then aborts with the installation still intact, rather than quietly installing
+ a wheel the cutoff forbids.
+ """
+ cutoff = os.environ.get("UV_EXCLUDE_NEWER", "").strip()
+ if not cutoff:
+ return []
+ if not _pip_supports_upload_cutoff():
+ return None
+ return ["--uploaded-prior-to", cutoff]
+
+
[email protected]_cache(maxsize = 1)
+def _pip_supports_upload_cutoff() -> bool:
+ try:
+ result = subprocess.run(
+ [sys.executable, "-m", "pip", "wheel", "--help"],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except OSError:
+ return False
+ return b"--uploaded-prior-to" in (result.stdout or b"")
+
+
def _install_env_for_cmd(cmd: "list[str]") -> "dict[str, str] | None":
"""Return an env with the uv index vars stripped for a pinned-index install.
@@ -4280,6 +5131,8 @@ def install_python_stack() -> int:
package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")
# --local overlays a local repo checkout after updating deps.
local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")
+ # Clean-machine CI overlays only unsloth, not the full local source pair.
+ ci_source_overlay = os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY", "")
# +1 for the anyio repair check (step 8b), +1 for the diffusers pin (step 11b, every platform)
base_total = 12 if IS_WINDOWS else 13
if IS_MACOS:
@@ -4354,6 +5207,16 @@ def install_python_stack() -> int:
[sys.executable, "-m", "pip", "install", "--upgrade", "pip"],
)
+ # A superseded dist-info makes version() and every RECORD consumer choose
+ # an arbitrary package version. Repair it before any fast package operation,
+ # including installer handoffs that set skip_base after their own upgrade.
+ if not _repair_duplicate_core_metadata(
+ (package_name, "unsloth-zoo"),
+ local_repo = local_repo,
+ ci_source_overlay = ci_source_overlay,
+ ):
+ 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:
@@ -4415,24 +5278,7 @@ def install_python_stack() -> int:
req = REQ_ROOT / "no-torch-runtime.txt",
)
if local_repo:
- _step(_LABEL, f"overlaying local repo (editable): {local_repo}")
- pip_install(
- "Overlaying local repo (editable)",
- "--no-cache-dir",
- "--no-deps",
- "-e",
- local_repo,
- constrain = False,
- )
- _step(_LABEL, "overlaying unsloth-zoo from git main")
- pip_install(
- "Overlaying unsloth-zoo from git main",
- "--no-cache-dir",
- "--no-deps",
- "--force-reinstall",
- "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
- constrain = False,
- )
+ _overlay_local_core_packages(local_repo)
elif local_repo:
# Local dev install: update the released core packages, then overlay the
# checkout as an editable install (--no-deps so torch is not re-resolved).
@@ -4447,24 +5293,7 @@ def install_python_stack() -> int:
"unsloth",
"unsloth-zoo",
)
- _step(_LABEL, f"overlaying local repo (editable): {local_repo}")
- pip_install(
- "Overlaying local repo (editable)",
- "--no-cache-dir",
- "--no-deps",
- "-e",
- local_repo,
- constrain = False,
- )
- _step(_LABEL, "overlaying unsloth-zoo from git main")
- pip_install(
- "Overlaying unsloth-zoo from git main",
- "--no-cache-dir",
- "--no-deps",
- "--force-reinstall",
- "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
- constrain = False,
- )
+ _overlay_local_core_packages(local_repo)
elif package_name != "unsloth":
# Custom package name (for testing): install directly.
_progress("base packages")
@@ -4746,6 +5575,19 @@ def install_python_stack() -> int:
**_windows_hidden_subprocess_kwargs(),
)
+ # 14b. Repair again before the manifest is written. The pass above runs
+ # before the core packages are installed, so an upgrade that itself leaves a
+ # superseded record behind -- the exact state this repair exists for -- would
+ # otherwise survive it. write_manifest would then record a null version and
+ # the installer would report success while every later check rejects the
+ # environment. A no-op when nothing is ambiguous.
+ if not _repair_duplicate_core_metadata(
+ (package_name, "unsloth-zoo"),
+ local_repo = local_repo,
+ ci_source_overlay = ci_source_overlay,
+ ):
+ 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 c0db19431bd..f68e77f1a2f 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -4730,14 +4730,28 @@ $SkipPythonDeps = $false
if ($env:SKIP_STUDIO_BASE -ne "1" -and $env:STUDIO_LOCAL_INSTALL -ne "1") {
# Only check when NOT called from install.ps1 (which just installed the package)
- $InstalledVer = try { (& python -c "from importlib.metadata import version; print(version('$_PkgName'))" 2>$null | Out-String).Trim() } catch { "" }
+ $_InstalledVersionProbeExit = 1
+ $InstalledVer = try {
+ $_installedVersionOutput = & python -c "
+import sys
+sys.path.insert(0, sys.argv[2])
+import install_manifest
+version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
+print(version)
+sys.exit(2 if conflict else (0 if version else 1))
+" $_PkgName $PSScriptRoot 2>$null
+ $_InstalledVersionProbeExit = $LASTEXITCODE
+ ($_installedVersionOutput | Out-String).Trim()
+ } catch { "" }
$LatestVer = ""
try {
$pypiJson = Invoke-RestMethod -Uri "https://pypi.org/pypi/$_PkgName/json" -TimeoutSec 5 -ErrorAction Stop
$LatestVer = "$($pypiJson.info.version)".Trim()
} catch { }
- if ($InstalledVer -and $LatestVer -and ($InstalledVer -eq $LatestVer)) {
+ if ($_InstalledVersionProbeExit -eq 2) {
+ substep "duplicate metadata found for a core package -- forcing package repair..." "Cyan"
+ } elseif ($InstalledVer -and $LatestVer -and ($InstalledVer -eq $LatestVer)) {
step "python" "$_PkgName $InstalledVer is up to date"
$SkipPythonDeps = $true
# A pre-#6483-fix install can be stuck on anyio>=4.14 even though
@@ -5282,6 +5296,8 @@ if (-not $ROCmIndexUrl -and -not $XpuIndexUrl -and ($CuTag -eq "cpu" -or $ROCmCp
# install.ps1 sets SKIP_STUDIO_BASE=1 (base never reinstalled) and 'studio update'
# goes through uv (--upgrade-package), whose pip fallback no-ops on the
# already-satisfied bare unsloth/unsloth-zoo. Either way unsloth.exe stays.
+# Duplicate metadata repair is the one pass that DOES reinstall unsloth under
+# SKIP_STUDIO_BASE, so the CLI wraps this script in its launcher transaction.
# Ordered heavy dependency installation -- shared cross-platform script
substep "running ordered dependency installation..."
diff --git a/studio/setup.sh b/studio/setup.sh
index 209ac39d2a6..f6dfea89920 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -1795,16 +1795,28 @@ fi
_PKG_NAME="${STUDIO_PACKAGE_NAME:-unsloth}"
if [ "$_SKIP_VERSION_CHECK" != true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ] && [ "${STUDIO_LOCAL_INSTALL:-0}" != "1" ]; then
# Only check when NOT called from install.sh (which just installed the package)
- INSTALLED_VER=$("$VENV_DIR/bin/python" -c "
-import sys; from importlib.metadata import version
-print(version(sys.argv[1]))
-" "$_PKG_NAME" 2>/dev/null || echo "")
+ _INSTALLED_VERSION_PROBE_EXIT=0
+ if INSTALLED_VER=$("$VENV_DIR/bin/python" -c "
+import sys
+sys.path.insert(0, sys.argv[2])
+import install_manifest
+version, conflict = install_manifest.installed_version_probe(sys.argv[1], ('unsloth-zoo',))
+print(version)
+sys.exit(2 if conflict else (0 if version else 1))
+" "$_PKG_NAME" "$SCRIPT_DIR" 2>/dev/null); then
+ :
+ else
+ _INSTALLED_VERSION_PROBE_EXIT=$?
+ INSTALLED_VER=""
+ fi
LATEST_VER=$(_setup_http_get_timed "https://pypi.org/pypi/$_PKG_NAME/json" 2>/dev/null \
| "$VENV_DIR/bin/python" -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null \
|| echo "")
- if [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then
+ if [ "$_INSTALLED_VERSION_PROBE_EXIT" -eq 2 ]; then
+ substep "duplicate metadata found for a core package -- forcing package repair..."
+ elif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then
step "python" "$_PKG_NAME $INSTALLED_VER is up to date"
_SKIP_PYTHON_DEPS=true
# A pre-#6483-fix install can be stuck on anyio>=4.14 even though
diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.py
index 93cecee6f56..bf7eb4ff1bb 100644
--- a/tests/python/test_install_python_stack.py
+++ b/tests/python/test_install_python_stack.py
@@ -5,10 +5,13 @@ from __future__ import annotations
import ast
import contextlib
import importlib
+import inspect
import io
import os
import re
+import shutil
import sys
+import types
from pathlib import Path
from unittest import mock
@@ -769,6 +772,1453 @@ class TestBuildPipCmdUpgradeIntent:
assert cmd == [sys.executable, "-m", "pip", "install", "--no-cache-dir", "somepackage"]
+class TestDuplicateCoreMetadataRepair:
+ def test_an_unrewritable_record_stops_the_repair_before_pip_runs(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ """The invariant that replaced quarantine-and-proceed.
+
+ A record that cannot be made readable cannot be uninstalled by pip either.
+ Moving it aside only hid it: pip removed the readable records, the
+ quarantine was discarded once the reinstall succeeded, and whatever the
+ quarantined release owned alone stayed importable while the repair
+ reported success and deleted the directory that was the evidence.
+
+ So nothing may run: no staging, no pip, and the tree is left as found.
+ A non-UTF-8 METADATA also makes pip raise for the whole environment, so
+ refusing before pip is what that used to need quarantining for.
+ """
+ malformed = tmp_path / "unsloth-2026.8.12.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ (malformed / "RECORD").write_text("unsloth/gone.py,,\n")
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda _n: ["", "2026.8.15"]
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [malformed])
+ monkeypatch.setattr(ips.install_manifest, "pip_backup_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ # The rewrite is what normally saves this record; deny it to reach the branch.
+ monkeypatch.setattr(ips, "_rewrite_minimal_metadata", lambda *a, **k: False)
+
+ def refuse(*_a, **_k):
+ raise AssertionError("nothing may run once a record is unusable")
+
+ monkeypatch.setattr(ips, "_stage_replacement", refuse)
+ monkeypatch.setattr(ips, "_run_ok", refuse)
+ monkeypatch.setattr(ips, "pip_install_try", refuse)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert "cannot be read or rewritten" in capsys.readouterr().err
+ assert malformed.is_dir()
+ assert (malformed / "METADATA").read_bytes() == b"\xff\xfe"
+
+ def test_an_unrecorded_stale_record_fails_closed_even_beside_a_good_one(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ """No RECORD means nothing knows which files that release owned, which is
+ why _rewrite_minimal_metadata fails closed. Waiting for record_count to
+ reach zero missed the case where another record survives: pip uninstalls
+ only that one, the quarantine is discarded on success, and whatever the
+ older release owned alone stays importable while the directory that was
+ the evidence is deleted for good.
+ """
+ unreadable = tmp_path / "unsloth-2026.8.12.dist-info"
+ unreadable.mkdir()
+ (unreadable / "METADATA").write_bytes(b"\xff\xfe") # no RECORD beside it
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda _n: ["", "2026.8.15"]
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [unreadable])
+ monkeypatch.setattr(ips.install_manifest, "pip_backup_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+
+ def fake_stage(*_args, **_kwargs):
+ raise AssertionError("nothing may be staged once a record is unusable")
+
+ monkeypatch.setattr(ips, "_stage_replacement", fake_stage)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert "cannot be read or rewritten" in capsys.readouterr().err
+ # The evidence stays on disk so a later run can still see the conflict.
+ assert unreadable.is_dir()
+
+ def test_pips_tilde_backup_is_moved_aside_so_the_loop_can_converge(self, tmp_path, monkeypatch):
+ """The commonest real conflict: pip renamed the outgoing distribution to a
+ `~` sibling and was killed. Its METADATA still says Name: unsloth so it
+ counts as a duplicate, but `pip uninstall unsloth` logs "Ignoring invalid
+ distribution" and skips it, so the loop never converges and the repair
+ fails on every future run. Verified in a real venv before this fix.
+ """
+ backup = tmp_path / "~nsloth-2026.8.12.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.12\n", encoding = "utf-8"
+ )
+ # Two records; one once the backup is aside; none after the uninstall; then
+ # the reinstalled one for the final convergence probe.
+ probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"]))
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(
+ ips.install_manifest, "pip_backup_metadata_paths", lambda _name: [backup]
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+
+ def record_run(_label, _cmd):
+ # pip only ever sees a tree it can actually act on.
+ assert not backup.exists()
+ return True
+
+ monkeypatch.setattr(ips, "_run_ok", record_run)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is True
+ assert not backup.exists()
+
+ def test_a_sole_tilde_backup_is_repaired_by_a_fresh_install(self, tmp_path, monkeypatch):
+ """pip killed after the rename but before the replacement landed leaves the
+ backup alone: one readable version, so a version count sees nothing wrong
+ while the package is genuinely unimportable. Once the backup is aside there
+ is no payload left to lay a replacement over, so installing fresh is right
+ and refusing would abort the installer on a trivially fixable state.
+ """
+ backup = tmp_path / "~nsloth-2026.8.12.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.12\n", encoding = "utf-8"
+ )
+ # One record, none once the backup is aside, then the reinstalled one.
+ probes = iter((["2026.8.12"], [], ["2026.8.15"]))
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(
+ ips.install_manifest, "pip_backup_metadata_paths", lambda _name: [backup]
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ installs = []
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda label, *a, **k: installs.append(label) or True
+ )
+ monkeypatch.setattr(
+ ips, "_run_ok", lambda *_a: pytest.fail("nothing is left for pip to uninstall")
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is True
+ assert len(installs) == 1
+ assert not backup.exists()
+
+ def test_every_duplicate_record_is_uninstalled_before_reinstall(self, monkeypatch):
+ probes = {
+ "unsloth": iter(
+ (
+ ["2026.8.12", "2026.8.15"],
+ ["2026.8.15"],
+ [],
+ ["2026.8.15"],
+ )
+ ),
+ "unsloth-zoo": iter((["2026.8.10"],)),
+ }
+ installs = []
+ invalidations = []
+ commands = []
+
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "installed_versions",
+ lambda name: next(probes[name]),
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: invalidations.append(True))
+ monkeypatch.setattr(
+ ips,
+ "_run_ok",
+ lambda label, cmd: commands.append((label, cmd)) or True,
+ )
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(
+ ips,
+ "pip_install_try",
+ lambda label, *args, **kwargs: installs.append((label, args, kwargs)) or True,
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth", "unsloth-zoo")) is True
+ assert [command for _label, command in commands] == [
+ [sys.executable, "-m", "pip", "uninstall", "-y", "unsloth"],
+ [sys.executable, "-m", "pip", "uninstall", "-y", "unsloth"],
+ ]
+ assert len(installs) == 1
+ assert installs[0][1] == (
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "--no-index",
+ "--find-links",
+ "/staged",
+ "unsloth",
+ )
+ assert len(invalidations) == 3
+
+ def test_repair_fails_when_uninstall_does_not_remove_a_record(self, monkeypatch, capsys):
+ probes = iter(
+ (
+ ["2026.8.12", "2026.8.15"],
+ ["2026.8.12", "2026.8.15"],
+ )
+ )
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "installed_versions",
+ lambda _name: next(probes),
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ installs = []
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: installs.append((a, k)))
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert installs == []
+ assert "could not remove every metadata record" in capsys.readouterr().err
+
+ @pytest.mark.parametrize(
+ "duplicate, overlay_args",
+ [
+ ("unsloth", ("--no-cache-dir", "--no-deps", "-e", "/src/unsloth")),
+ (
+ "unsloth-zoo",
+ (
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
+ ),
+ ),
+ ],
+ )
+ def test_local_repair_restores_only_the_source_it_replaced(
+ self, monkeypatch, duplicate, overlay_args
+ ):
+ probes = {
+ name: iter((["old", "new"], ["new"], [], ["new"]) if name == duplicate else (["new"],))
+ for name in ("unsloth", "unsloth-zoo")
+ }
+ installs = []
+
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "installed_versions",
+ lambda name: next(probes[name]),
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(
+ ips,
+ "pip_install_try",
+ lambda label, *args, **kwargs: installs.append((label, args, kwargs)) or True,
+ )
+
+ assert ips._repair_duplicate_core_metadata(
+ ("unsloth", "unsloth-zoo"), local_repo = "/src/unsloth"
+ )
+ assert len(installs) == 1
+ assert installs[0][1] == overlay_args
+ assert installs[0][2]["constrain"] is False
+
+ def test_install_pass_hands_local_provenance_to_duplicate_repair(self):
+ source = inspect.getsource(ips.install_python_stack)
+ assert "local_repo=local_repo" in source.replace(" ", "")
+
+ def test_local_repair_reinstalls_a_custom_package_from_its_normal_source(self, monkeypatch):
+ probes = iter((["old", "new"], ["new"], [], ["new"]))
+ installs = []
+
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "installed_versions",
+ lambda _name: next(probes),
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(
+ ips,
+ "pip_install_try",
+ lambda label, *args, **kwargs: installs.append((label, args, kwargs)) or True,
+ )
+
+ assert ips._repair_duplicate_core_metadata(("custom-package",), local_repo = "/src/unsloth")
+ assert len(installs) == 1
+ assert installs[0][1] == (
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "--no-index",
+ "--find-links",
+ "/staged",
+ "custom-package",
+ )
+
+ def test_ci_repair_restores_only_the_candidate_unsloth_checkout(self, monkeypatch):
+ probes = {
+ "unsloth": iter((["old", "new"], ["new"], [], ["new"])),
+ "unsloth-zoo": iter((["new"],)),
+ }
+ installs = []
+
+ monkeypatch.setattr(
+ ips.install_manifest,
+ "installed_versions",
+ lambda name: next(probes[name]),
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(
+ ips,
+ "pip_install_try",
+ lambda label, *args, **kwargs: installs.append((label, args, kwargs)) or True,
+ )
+
+ assert ips._repair_duplicate_core_metadata(
+ ("unsloth", "unsloth-zoo"), ci_source_overlay = "/src/candidate"
+ )
+ assert len(installs) == 1
+ assert installs[0][1] == ("--no-cache-dir", "--no-deps", "-e", "/src/candidate")
+ assert installs[0][2]["constrain"] is False
+
+ def test_the_repair_runs_again_before_the_manifest_is_written(self):
+ """The first pass runs before the core packages are installed, so an
+ upgrade that leaves a superseded record behind would survive it and
+ write_manifest would record a null version under a successful exit."""
+ source = inspect.getsource(ips.install_python_stack)
+ first = source.index("_repair_duplicate_core_metadata")
+ second = source.index("_repair_duplicate_core_metadata", first + 1)
+ manifest = source.index("write_manifest(")
+ assert first < second < manifest, (
+ "the duplicate-metadata repair must run again after the core-package "
+ "install and before the manifest is written"
+ )
+
+ def test_staging_relaxes_pip_hash_enforcement(self):
+ """require-hashes applies to pip wheel exactly as it does to pip install
+ (measured on pip 26.2: an unpinned name is refused before anything is
+ built), so a hardened machine could never stage a replacement and the
+ repair would abort on the very conflict it exists to remove."""
+ env = ips._install_env_for_cmd(
+ [sys.executable, "-m", "pip", "wheel", "--no-deps", "--wheel-dir", "/staged", "unsloth"]
+ )
+ assert env is not None and env.get("PIP_REQUIRE_HASHES") == "0"
+
+ def _uv_only(self, monkeypatch):
+ monkeypatch.setattr(ips, "USE_UV", True)
+ for var in (
+ "PIP_INDEX_URL",
+ "PIP_EXTRA_INDEX_URL",
+ "PIP_FIND_LINKS",
+ "UV_INDEX",
+ "UV_EXTRA_INDEX_URL",
+ "UV_INDEX_URL",
+ "UV_DEFAULT_INDEX",
+ "UV_FIND_LINKS",
+ "UV_EXCLUDE_NEWER",
+ "UV_INDEX_STRATEGY",
+ "UV_NO_BINARY",
+ "UV_ONLY_BINARY",
+ "PIP_NO_BINARY",
+ "PIP_ONLY_BINARY",
+ "UV_KEYRING_PROVIDER",
+ "PIP_KEYRING_PROVIDER",
+ ):
+ monkeypatch.delenv(var, raising = False)
+
+ UV_COMPILE_OUT = (
+ b"# This file was autogenerated by uv via the following command:\n"
+ b"# uv pip compile --no-deps --emit-index-url -\n"
+ b"--index-url https://pypi.org/simple\n"
+ b"--extra-index-url https://mirror.corp/simple\n"
+ b"--find-links /opt/wheels\n"
+ b"\n"
+ b"unsloth-zoo==2026.8.15\n"
+ b" # from https://mirror.corp/simple\n"
+ )
+
+ def _uv_plan(
+ self,
+ monkeypatch,
+ stdout = None,
+ returncode = 0,
+ ):
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs))
+ if cmd[:3] == ["uv", "pip", "compile"]:
+ return types.SimpleNamespace(
+ returncode = returncode,
+ stdout = self.UV_COMPILE_OUT if stdout is None else stdout,
+ stderr = b"",
+ )
+ return types.SimpleNamespace(returncode = 1, stdout = b"")
+
+ monkeypatch.setattr(ips.subprocess, "run", fake_run)
+ return calls
+
+ def test_the_replacement_is_the_release_and_index_uv_resolved(self, monkeypatch):
+ """Staging must run pip, because uv has no wheel subcommand, and uv's index
+ configuration cannot be reconstructed from the environment: uv also reads
+ uv.toml, pyproject [tool.uv], a user config and UV_CONFIG_FILE, applies an
+ implicit PyPI default, and resolves under an index-strategy pip has no
+ equivalent for. So uv is asked, and its answer is reproduced verbatim."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ self._uv_plan(monkeypatch)
+ requirement, overrides, _options = ips._uv_staging_plan("unsloth_zoo")
+ assert requirement == "unsloth-zoo==2026.8.15"
+ # The annotation names the index the package actually came from, which is the
+ # one to reproduce -- not --index-url, which is only uv's default.
+ assert overrides["PIP_INDEX_URL"] == "https://mirror.corp/simple"
+ assert overrides["PIP_EXTRA_INDEX_URL"] == ""
+ assert overrides["PIP_FIND_LINKS"] == "/opt/wheels"
+
+ def test_the_plan_asks_uv_about_this_interpreter(self, monkeypatch):
+ """Markers and ABI tags come from the interpreter being repaired, not from
+ whichever one uv would discover on its own."""
+ self._uv_only(monkeypatch)
+ calls = self._uv_plan(monkeypatch)
+ ips._uv_staging_plan("unsloth-zoo")
+ cmd = calls[0][0]
+ assert cmd[cmd.index("--python") + 1] == sys.executable
+ assert calls[0][1]["input"] == b"unsloth-zoo"
+
+ def test_a_falling_index_aborts_the_repair_rather_than_substituting(self, monkeypatch, capsys):
+ """uv fails the compile outright when a higher-priority index is unreachable,
+ which is the behaviour first-index exists to give: a public release must not
+ stand in for a private one just because the private mirror was down."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ self._uv_plan(monkeypatch, returncode = 1)
+ assert ips._stage_replacement("unsloth-zoo") is None
+ assert "cannot be preserved" in capsys.readouterr().err
+
+ def test_offline_uv_leaves_the_install_alone(self, monkeypatch, capsys):
+ """UV_OFFLINE forbids network access and pip has no offline mode, so the
+ repair would have to break the policy to proceed."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+
+ def fake_run(*args, **kwargs):
+ raise AssertionError("nothing may run while uv is offline")
+
+ monkeypatch.setattr(ips.subprocess, "run", fake_run)
+ assert ips._stage_replacement("unsloth-zoo") is None
+ assert "UV_OFFLINE" in capsys.readouterr().err
+
+ @pytest.mark.parametrize("value", ("", "0", "false"))
+ def test_an_unset_or_disabled_offline_flag_is_not_offline(self, monkeypatch, value):
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_OFFLINE", value)
+ assert ips._uv_is_offline() is False
+
+ def test_the_plan_is_skipped_when_uv_is_not_the_package_manager(self, monkeypatch):
+ """Plain pip already reads its own configuration, so there is nothing to
+ translate and no uv to ask."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", False)
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement("unsloth-zoo") is None
+ assert all(cmd[:1] != ["uv"] for cmd, _ in calls)
+ assert calls[0][0][-1] == "unsloth-zoo"
+
+ @pytest.mark.parametrize(
+ "requirement",
+ (
+ "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
+ "https://example.invalid/unsloth_zoo-1.0-py3-none-any.whl",
+ ),
+ )
+ def test_a_direct_reference_is_staged_as_written(self, monkeypatch, requirement):
+ """The overlay paths hand staging a git URL or a checkout, not a bare name.
+ Such a requirement is its own provenance -- no index chose it -- and uv
+ appends the resolved commit to what it emits, so asking uv would compare a
+ bare spec against a pinned one and never match, aborting every local
+ duplicate-zoo repair before it started."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement(requirement) is None
+ assert all(cmd[:3] != ["uv", "pip", "compile"] for cmd, _ in calls)
+ assert calls[0][0][-1] == requirement
+
+ def test_a_local_checkout_is_a_direct_reference(self, tmp_path):
+ assert ips._is_direct_reference(str(tmp_path)) is True
+ assert ips._is_direct_reference("unsloth-zoo") is False
+
+ def test_replaying_uv_replaces_pips_candidate_sources(self, monkeypatch):
+ """Replaying uv's answer means replacing pip's sources, not adding to them.
+ An inherited PIP_NO_INDEX blocks the index uv picked, and an inherited extra
+ index or find-links directory can satisfy the same version from somewhere uv
+ never looked, which is the provenance swap this path exists to stop."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ for var, value in (
+ ("PIP_NO_INDEX", "1"),
+ ("PIP_EXTRA_INDEX_URL", "https://elsewhere/simple"),
+ ("PIP_FIND_LINKS", "/tmp/stale-wheels"),
+ ):
+ monkeypatch.setenv(var, value)
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement("unsloth-zoo") is None
+ env = calls[-1][1]["env"]
+ # Measured on pip 26.2: an empty value reads as unset.
+ assert env["PIP_NO_INDEX"] == ""
+ assert env["PIP_EXTRA_INDEX_URL"] == ""
+ assert env["PIP_FIND_LINKS"] == "/opt/wheels"
+ assert env["PIP_INDEX_URL"] == "https://mirror.corp/simple"
+ # pip.conf carries the same three settings, so it is replaced by a copy of
+ # itself with only those removed.
+ assert env["PIP_CONFIG_FILE"].endswith("pip.conf")
+ assert env["PIP_CONFIG_FILE"] != os.devnull
+
+ def test_no_find_links_survives_when_uv_emitted_none(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("PIP_FIND_LINKS", "/tmp/stale-wheels")
+ self._uv_plan(monkeypatch, stdout = b"unsloth-zoo==1.0\n # from https://m/s\n")
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_FIND_LINKS"] == ""
+
+ def test_pip_transport_settings_survive_the_source_replacement(self, tmp_path, monkeypatch):
+ """Dropping pip.conf wholesale would take proxy, cert, client-cert and
+ trusted-host with it, and those are how a private index is reached at all, so
+ uv would resolve and pip would then fail to fetch. The four source keys are
+ removed and everything else is written back."""
+ listing = (
+ b"global.cert='/etc/ssl/corp.pem'\n"
+ b"global.proxy='http://proxy.corp:8080'\n"
+ b"global.trusted-host='\\na.corp\\nb.corp'\n"
+ b"global.index-url='https://bogus/simple'\n"
+ b"global.extra-index-url='https://elsewhere/simple'\n"
+ b"global.find-links='/tmp/stale'\n"
+ b"global.no-index='true'\n"
+ b"install.no-binary='numpy'\n"
+ b":env:.config-file='/etc/pip.conf'\n"
+ )
+ monkeypatch.setattr(
+ ips.subprocess,
+ "run",
+ lambda *a, **k: types.SimpleNamespace(returncode = 0, stdout = listing),
+ )
+ written = Path(ips._pip_config_without_sources(str(tmp_path))).read_text()
+ assert "proxy = http://proxy.corp:8080" in written
+ assert "cert = /etc/ssl/corp.pem" in written
+ # A multi-value setting is spelled back as an indented continuation.
+ assert "trusted-host =\n a.corp\n b.corp" in written
+ assert "[install]" in written and "no-binary = numpy" in written
+ for dropped in ("index-url", "extra-index-url", "find-links", "no-index"):
+ assert dropped not in written, f"{dropped} must not survive"
+ # :env: entries come from the environment, which is overridden separately.
+ assert "config-file" not in written
+
+ def test_an_unreadable_pip_config_yields_an_empty_one(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ ips.subprocess,
+ "run",
+ lambda *a, **k: types.SimpleNamespace(returncode = 1, stdout = b""),
+ )
+ assert Path(ips._pip_config_without_sources(str(tmp_path))).read_text() == ""
+
+ def test_uv_artifact_policy_is_replayed_from_its_configuration(self, monkeypatch):
+ """A no-binary or only-binary rule would otherwise change the artifact type
+ during the repair: a wheel downloaded under a no-binary rule, or an sdist
+ built under an only-binary one."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = b"--only-binary :all:\nunsloth-zoo==1.0\n # from https://m/s\n",
+ )
+ _requirement, _overrides, options = ips._uv_staging_plan("unsloth-zoo")
+ assert options == ["--only-binary", ":all:"]
+
+ def test_the_env_spelling_of_the_artifact_policy_is_translated(self, monkeypatch):
+ """Measured on uv 0.10.7: --emit-build-options surfaces the policy from
+ uv.toml but not the environment-variable spelling, so that half is
+ translated by hand."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_ONLY_BINARY", ":all:")
+ monkeypatch.delenv("PIP_ONLY_BINARY", raising = False)
+ self._uv_plan(monkeypatch)
+ _requirement, overrides, options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_ONLY_BINARY"] == ":all:"
+ assert options == []
+
+ def test_an_explicit_pip_artifact_policy_is_left_alone(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_ONLY_BINARY", ":all:")
+ monkeypatch.setenv("PIP_ONLY_BINARY", "numpy")
+ self._uv_plan(monkeypatch)
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides.get("PIP_ONLY_BINARY") is None
+
+ def test_the_keyring_provider_is_translated(self, monkeypatch):
+ """uv reaches an authenticated index through the keyring CLI (uv 0.10.7:
+ `--keyring-provider subprocess` uses the `keyring` command). Carrying only
+ the URL leaves pip unable to fetch what uv just resolved, so every repair
+ on a private index aborts. pip accepts the same two values.
+ """
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_KEYRING_PROVIDER", "subprocess")
+ monkeypatch.delenv("PIP_KEYRING_PROVIDER", raising = False)
+ self._uv_plan(monkeypatch)
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_KEYRING_PROVIDER"] == "subprocess"
+
+ def test_an_explicit_pip_keyring_provider_is_left_alone(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_KEYRING_PROVIDER", "subprocess")
+ monkeypatch.setenv("PIP_KEYRING_PROVIDER", "import")
+ self._uv_plan(monkeypatch)
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides.get("PIP_KEYRING_PROVIDER") is None
+
+ def test_the_staging_command_carries_the_build_options(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ calls = self._uv_plan(
+ monkeypatch,
+ stdout = b"--only-binary :all:\nunsloth-zoo==1.0\n # from https://m/s\n",
+ )
+ assert ips._stage_replacement("unsloth-zoo") is None
+ cmd = calls[-1][0]
+ assert cmd[cmd.index("--only-binary") + 1] == ":all:"
+
+ def test_the_annotated_index_is_recovered_with_its_credentials(self, monkeypatch):
+ """Measured on uv 0.10.7: the emitted index lines carry userinfo and the
+ `# from` annotation has it stripped. Taking the annotation at face value
+ hands pip an unauthenticated URL for a private index, which answers 401 and
+ aborts the repair."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--index-url https://user:[email protected]/simple\n"
+ b"unsloth-zoo==1.0\n"
+ b" # from https://private.corp/simple\n"
+ ),
+ )
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_INDEX_URL"] == "https://user:[email protected]/simple"
+
+ def test_an_authenticated_extra_index_is_recovered_too(self, monkeypatch):
+ """uv puts a credentialed --index on the extra line and leaves --index-url as
+ the public default, so reading only --index-url would name the wrong index."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--index-url https://pypi.org/simple\n"
+ b"--extra-index-url https://user:[email protected]/simple\n"
+ b"unsloth-zoo==1.0\n"
+ b" # from https://private.corp/simple\n"
+ ),
+ )
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_INDEX_URL"] == "https://user:[email protected]/simple"
+
+ def test_the_credentialed_form_wins_over_a_bare_duplicate(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--index-url https://private.corp/simple\n"
+ b"--extra-index-url https://user:[email protected]/simple\n"
+ b"unsloth-zoo==1.0\n"
+ b" # from https://private.corp/simple\n"
+ ),
+ )
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_INDEX_URL"] == "https://user:[email protected]/simple"
+
+ @pytest.mark.parametrize(
+ "url, bare",
+ (
+ ("https://u:p@h/simple", "https://h/simple"),
+ ("https://h/simple", "https://h/simple"),
+ ("https://h/simple?a=b", "https://h/simple?a=b"),
+ ("/local/dir", "/local/dir"),
+ ),
+ )
+ def test_userinfo_is_stripped_without_disturbing_the_rest(self, url, bare):
+ assert ips._strip_userinfo(url) == bare
+
+ def test_offline_still_stages_a_local_checkout(self, tmp_path, monkeypatch):
+ """--local hands the repair a checkout on disk. It needs no network, so
+ UV_OFFLINE has nothing to say about it, and refusing left the conflict in
+ place and failed the update for no reason."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement(str(tmp_path)) is None
+ # It reached pip rather than refusing, and did not consult uv for a path.
+ assert calls and all(cmd[:3] != ["uv", "pip", "compile"] for cmd, _ in calls)
+ assert calls[-1][0][-1] == str(tmp_path)
+
+ def test_offline_local_staging_never_reaches_the_index(self, tmp_path, monkeypatch):
+ """The checkout needs no network, but pip builds it in an isolated
+ environment and fetches the build backend for that, which UV_OFFLINE does not
+ reach. Measured: an isolated build of a local project with no index reachable
+ fails at installing build dependencies, and this repository pins its build
+ requirements exactly, so they would be fetched unless already cached."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement(str(tmp_path)) is None
+ cmd, kwargs = calls[-1]
+ assert "--no-build-isolation" in cmd
+ assert kwargs["env"]["PIP_NO_INDEX"] == "1"
+
+ def test_online_local_staging_keeps_build_isolation(self, tmp_path, monkeypatch):
+ """Isolation is how the pinned build requirements are honoured, so it is only
+ given up when the alternative is breaking the no-network policy."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ calls = self._uv_plan(monkeypatch)
+ assert ips._stage_replacement(str(tmp_path)) is None
+ cmd, kwargs = calls[-1]
+ assert "--no-build-isolation" not in cmd
+ assert kwargs["env"] is None or kwargs["env"].get("PIP_NO_INDEX") != "1"
+
+ def test_offline_still_refuses_a_git_reference(self, monkeypatch, capsys):
+ """A git URL is a network fetch however direct the reference is."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ monkeypatch.setenv("UV_OFFLINE", "1")
+
+ def fake_run(*args, **kwargs):
+ raise AssertionError("nothing may run while uv is offline")
+
+ monkeypatch.setattr(ips.subprocess, "run", fake_run)
+ assert ips._stage_replacement("unsloth-zoo @ git+https://example/x") is None
+ assert "UV_OFFLINE" in capsys.readouterr().err
+
+ def test_a_find_links_origin_does_not_displace_the_real_index(self, monkeypatch):
+ """uv annotates a flat source with a file:// URL. That belongs in
+ PIP_FIND_LINKS, which is already set, and must not become PIP_INDEX_URL: an
+ sdist picked out of a flat directory still needs the index for its build
+ backend, so staging would abort."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--index-url https://pypi.org/simple\n"
+ b"--find-links /opt/wheels\n"
+ b"unsloth-zoo==1.0\n"
+ b" # from file:///opt/wheels\n"
+ ),
+ )
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_INDEX_URL"] == "https://pypi.org/simple"
+ assert overrides["PIP_FIND_LINKS"] == "/opt/wheels"
+
+ def test_a_sole_unreadable_record_is_made_uninstallable(self, tmp_path):
+ """Quarantining the only record leaves pip nothing to uninstall, so the
+ staged wheel is laid over the existing tree and any module the new release
+ dropped stays on disk, importable, while the repair reports success.
+
+ Verified against a real venv: with the METADATA corrupted pip show raises
+ UnicodeDecodeError for the whole environment; after this rewrite pip
+ uninstalls the package and removes its entire payload."""
+ record = tmp_path / "realpkg-1.2.3.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("realpkg/__init__.py,,\n")
+
+ assert ips._rewrite_minimal_metadata(str(record), "realpkg") is True
+
+ written = (record / "METADATA").read_text()
+ assert "Name: realpkg" in written
+ # The version comes from the directory name, which is where importlib's own
+ # fallback reads it when METADATA cannot be parsed.
+ assert "Version: 1.2.3" in written
+
+ def test_a_record_without_a_manifest_fails_closed(self, tmp_path):
+ """No RECORD means neither pip nor this installer knows which files belong
+ to the package, so a replacement laid over them would leave whatever the new
+ release no longer ships behind."""
+ record = tmp_path / "realpkg-1.2.3.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ assert ips._rewrite_minimal_metadata(str(record), "realpkg") is False
+
+ def test_an_unversioned_directory_fails_closed(self, tmp_path):
+ record = tmp_path / "realpkg.dist-info"
+ record.mkdir()
+ (record / "RECORD").write_text("realpkg/__init__.py,,\n")
+ assert ips._rewrite_minimal_metadata(str(record), "realpkg") is False
+
+ def test_a_path_object_is_accepted(self, tmp_path):
+ """install_manifest.invalid_metadata_paths() returns Path, and the repair
+ forwards it verbatim. Passing str here (as the tests around this one do)
+ hid an AttributeError on every real unreadable record.
+ """
+ record = tmp_path / "realpkg-1.2.3.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("realpkg/__init__.py,,\n")
+
+ assert ips._rewrite_minimal_metadata(record, "realpkg") is True
+ assert "Version: 1.2.3" in (record / "METADATA").read_text()
+
+ def test_an_absent_metadata_is_synthesized_not_quarantined(self, tmp_path):
+ """A record with an intact RECORD but no METADATA at all.
+
+ There is nothing to back up, which is not a failure: quarantining it
+ instead drops its RECORD, so the uninstall loop removes only what the
+ readable record claims and a module shipped solely by the older release
+ stays on disk and importable while the repair reports success.
+ """
+ record = tmp_path / "realpkg-1.2.3.dist-info"
+ record.mkdir()
+ (record / "RECORD").write_text("realpkg/__init__.py,,\n")
+
+ quarantine = ips._QuarantinedMetadata()
+ assert quarantine.back_up(record / "METADATA") is True
+ assert ips._rewrite_minimal_metadata(record, "realpkg") is True
+ assert "Name: realpkg" in (record / "METADATA").read_text()
+
+ # A failure after the rewrite must not leave the synthetic file behind: a
+ # readable record would tell the next run there is nothing left to repair.
+ quarantine.restore()
+ assert not (record / "METADATA").exists()
+
+ def test_the_repair_refuses_when_the_only_record_cannot_be_made_usable(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ record = tmp_path / "unsloth-2026.8.12.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ # Quarantining the only record leaves nothing behind for pip to uninstall.
+ probes = iter(([""], []))
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _n: next(probes))
+ monkeypatch.setattr(
+ ips.install_manifest, "invalid_metadata_paths", lambda _n: [str(record)]
+ )
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+
+ def fake_stage(*args, **kwargs):
+ raise AssertionError("nothing may be staged before the records are usable")
+
+ monkeypatch.setattr(ips, "_stage_replacement", fake_stage)
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert "Recreate the environment" in capsys.readouterr().err
+ # The record is left where it was, not quarantined into a temporary directory.
+ assert record.is_dir()
+
+ HASHED_OUT = (
+ b"--index-url https://mirror.corp/simple\n"
+ b"unsloth-zoo==2026.8.15 \\\n"
+ b" --hash=sha256:aaaa \\\n"
+ b" --hash=sha256:bbbb\n"
+ b" # from https://mirror.corp/simple\n"
+ )
+
+ def test_the_resolved_artifact_is_pinned_by_hash(self, monkeypatch):
+ """Neither PIP_CONFIG_FILE nor --isolated suppresses a site pip.conf --
+ measured: with both, a venv pip.conf's extra-index-url was still contacted.
+ So pip may consult a source uv never considered, and the hashes are what stop
+ it accepting a different artifact of the same version from one. pip verifies
+ them even with PIP_REQUIRE_HASHES=0, which is also measured."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(monkeypatch, stdout = self.HASHED_OUT)
+ requirement, _overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ # The pin line is continued with a backslash, which is not part of the pin.
+ assert requirement.startswith("unsloth-zoo==2026.8.15 \\\n")
+ assert "--hash=sha256:aaaa" in requirement
+ assert "--hash=sha256:bbbb" in requirement
+
+ def test_a_hashed_requirement_reaches_pip_as_a_file(self, tmp_path):
+ """pip only accepts --hash entries from a requirements file."""
+ requirement = "unsloth-zoo==1.0 \\\n --hash=sha256:aaaa"
+ args = ips._requirement_args(requirement, str(tmp_path))
+ assert args[0] == "-r"
+ assert Path(args[1]).read_text().strip() == requirement
+ # It lives in the staging directory, so it is removed with it.
+ assert Path(args[1]).parent == tmp_path
+
+ def test_an_unhashed_requirement_is_passed_directly(self, tmp_path):
+ assert ips._requirement_args("unsloth-zoo", str(tmp_path)) == ["unsloth-zoo"]
+ assert list(tmp_path.iterdir()) == []
+
+ def test_a_flat_source_with_no_index_forbids_the_index(self, monkeypatch):
+ """A configured no-index looks like this on the way out: uv emits the
+ find-links entry and no index line at all. Leaving PIP_NO_INDEX cleared would
+ hand pip back the default PyPI and let it stage the same name and version
+ from a source uv was told to exclude."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--find-links /opt/wheels\n"
+ b"unsloth-zoo==1.0\n"
+ b" # from file:///opt/wheels\n"
+ ),
+ )
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_NO_INDEX"] == "1"
+ assert overrides["PIP_FIND_LINKS"] == "/opt/wheels"
+ assert "PIP_INDEX_URL" not in overrides
+
+ def test_an_emitted_index_still_clears_no_index(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("PIP_NO_INDEX", "1")
+ self._uv_plan(monkeypatch)
+ _requirement, overrides, _options = ips._uv_staging_plan("unsloth-zoo")
+ assert overrides["PIP_NO_INDEX"] == ""
+
+ def test_every_unreadable_record_with_a_manifest_is_made_uninstallable(
+ self, tmp_path, monkeypatch
+ ):
+ """One unreadable record beside a readable one used to be quarantined and
+ discarded, so its RECORD was never applied: the uninstall loop removed only
+ what the readable record claimed, and a module existing solely in the older
+ release stayed on disk and importable while the repair reported success."""
+ stale = tmp_path / "unsloth-2026.8.12.dist-info"
+ stale.mkdir()
+ (stale / "METADATA").write_bytes(b"\xff\xfe")
+ (stale / "RECORD").write_text("unsloth/gone.py,,\n")
+ probes = iter(
+ (["", "2026.8.15"], ["2026.8.12", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"])
+ )
+ taken = []
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _n: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [str(stale)])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _n: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+ monkeypatch.setattr(
+ ips._QuarantinedMetadata, "take", lambda _self, paths: taken.append(paths) or True
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is True
+ # It was rewritten for pip rather than moved aside, so its RECORD is applied
+ # and nothing is quarantined at all.
+ assert taken == []
+ assert "Name: unsloth" in (stale / "METADATA").read_text()
+
+ def test_a_repaired_package_is_not_rolled_back_by_a_later_failure(self, monkeypatch):
+ """A single quarantine shared across both packages would, when the second
+ fails, restore the first package's stale record on top of the install that
+ has already replaced it: the conflict returns, and its old RECORD then
+ describes a payload that is gone."""
+ probes = {
+ "unsloth": iter((["", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"])),
+ "unsloth-zoo": iter((["", "2026.8.15"],)),
+ }
+ events = []
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda name: next(probes[name])
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+ # The second package cannot be staged, so the repair fails after the first
+ # one has already been reinstalled.
+ staged = iter(("/staged", None))
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _n: next(staged))
+ monkeypatch.setattr(
+ ips._QuarantinedMetadata, "discard", lambda _self: events.append("discard")
+ )
+ monkeypatch.setattr(
+ ips._QuarantinedMetadata, "restore", lambda _self: events.append("restore")
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth", "unsloth-zoo")) is False
+ # The first package was committed before the second was attempted, so the
+ # rollback at the end can only touch the one that failed.
+ assert events[0] == "discard"
+ assert events[-1] == "restore"
+
+ def test_a_direct_reference_pin_is_recognised(self, monkeypatch):
+ """An override can redirect a package to a path, repository or URL, and uv
+ then emits `name @ reference` rather than `name==version`. Treating the whole
+ line as the name left the requirement empty and aborted every repair under
+ that policy."""
+ self._uv_only(monkeypatch)
+ self._uv_plan(
+ monkeypatch,
+ stdout = (
+ b"--index-url https://pypi.org/simple\n"
+ b"unsloth-zoo @ file:///src/zoo\n"
+ b" # from https://pypi.org/simple\n"
+ ),
+ )
+ requirement, _overrides, _options = ips._uv_staging_plan("unsloth_zoo")
+ # The reference is kept as written; only the name is parsed out of it.
+ assert requirement == "unsloth-zoo @ file:///src/zoo"
+
+ @pytest.mark.parametrize(
+ "line, name",
+ (
+ ("six==1.17.0", "six"),
+ ("unsloth-zoo @ git+https://example/x", "unsloth-zoo"),
+ ("unsloth_zoo @ file:///src", "unsloth_zoo"),
+ ),
+ )
+ def test_the_name_is_taken_from_either_spelling(self, line, name):
+ assert ips._requirement_name(line) == name
+
+ def test_the_original_metadata_comes_back_when_the_repair_fails(self, tmp_path):
+ """The rewrite has to happen before staging, and staging can still fail.
+ Without a backup the original is gone and what remains parses, so the next
+ run would see one readable record, decide nothing is wrong, and never attempt
+ the payload repair that is still owed."""
+ record = tmp_path / "unsloth-2026.8.12.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("unsloth/gone.py,,\n")
+ quarantine = ips._QuarantinedMetadata()
+
+ assert quarantine.back_up(str(record / "METADATA")) is True
+ assert ips._rewrite_minimal_metadata(str(record), "unsloth") is True
+ assert "Name: unsloth" in (record / "METADATA").read_text()
+
+ quarantine.restore()
+
+ # Byte for byte what was there, so the conflict is still detected next time.
+ assert (record / "METADATA").read_bytes() == b"\xff\xfe"
+
+ def test_a_committed_rewrite_is_not_undone(self, tmp_path):
+ record = tmp_path / "unsloth-2026.8.12.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("unsloth/gone.py,,\n")
+ quarantine = ips._QuarantinedMetadata()
+ quarantine.back_up(str(record / "METADATA"))
+ ips._rewrite_minimal_metadata(str(record), "unsloth")
+
+ quarantine.discard()
+ quarantine.restore()
+
+ assert "Name: unsloth" in (record / "METADATA").read_text()
+
+ def test_an_unbackable_metadata_stops_the_repair(self, tmp_path, monkeypatch, capsys):
+ """The reachable route to an unrewritable record: a METADATA that exists but
+ cannot be read, as an elevated install leaves root-owned. back_up fails, so
+ the rewrite is skipped and the record can never be handed to pip.
+
+ Reproduced in a real venv with the file made unreadable: before this refused,
+ the repair returned True, the module only the stale release shipped stayed
+ importable, and its dist-info was deleted, so nothing could report it again.
+ """
+ record = tmp_path / "unsloth-2026.8.12.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("unsloth/gone.py,,\n")
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda _n: ["", "2026.8.15"]
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [record])
+ monkeypatch.setattr(ips.install_manifest, "pip_backup_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips._QuarantinedMetadata, "back_up", lambda _self, _p: False)
+
+ def refuse(*_a, **_k):
+ raise AssertionError("nothing may run once a record is unusable")
+
+ monkeypatch.setattr(ips, "_stage_replacement", refuse)
+ monkeypatch.setattr(ips, "_run_ok", refuse)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert "cannot be read or rewritten" in capsys.readouterr().err
+ # Untouched, so the next run still sees it.
+ assert (record / "METADATA").read_bytes() == b"\xff\xfe"
+
+ def test_an_unresolvable_name_stages_nothing(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ monkeypatch.setattr(ips, "USE_UV", True)
+ self._uv_plan(monkeypatch, stdout = b"--index-url https://pypi.org/simple\n")
+ assert ips._uv_staging_plan("unsloth-zoo") is None
+
+ def test_a_pin_for_another_package_is_not_mistaken_for_this_one(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ self._uv_plan(monkeypatch, stdout = b"unsloth==2026.8.15\n")
+ assert ips._uv_staging_plan("unsloth-zoo") is None
+
+ def test_the_uv_upload_cutoff_reaches_pip(self, monkeypatch):
+ """UV_EXCLUDE_NEWER limits candidates by upload time and pip ignores it, so
+ staging could install a release the user's policy excludes. pip's
+ --uploaded-prior-to is the same filter and takes the same date spellings
+ (checked on pip 26.2: a bare 2020-01-01 staged six 1.13.0, not 1.17.0)."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_EXCLUDE_NEWER", "2026-01-01")
+ monkeypatch.setattr(ips, "USE_UV", False)
+ monkeypatch.setattr(ips, "_pip_supports_upload_cutoff", lambda: True)
+ captured = {}
+
+ def fake_run(cmd, **kwargs):
+ captured["cmd"] = cmd
+ return types.SimpleNamespace(returncode = 1, stdout = b"")
+
+ monkeypatch.setattr(ips.subprocess, "run", fake_run)
+ assert ips._stage_replacement("unsloth") is None
+ assert "--uploaded-prior-to" in captured["cmd"]
+ assert captured["cmd"][captured["cmd"].index("--uploaded-prior-to") + 1] == "2026-01-01"
+
+ def test_an_unhonourable_cutoff_leaves_the_install_alone(self, monkeypatch, capsys):
+ """--uploaded-prior-to only exists from pip 25.3. Staging a newer wheel
+ anyway would silently break the policy, so the repair aborts instead, with
+ the duplicate still in place and the package still installed."""
+ self._uv_only(monkeypatch)
+ monkeypatch.setenv("UV_EXCLUDE_NEWER", "2026-01-01")
+ monkeypatch.setattr(ips, "USE_UV", False)
+ monkeypatch.setattr(ips, "_pip_supports_upload_cutoff", lambda: False)
+
+ def fake_run(*args, **kwargs):
+ raise AssertionError("pip must not run when the cutoff cannot be honoured")
+
+ monkeypatch.setattr(ips.subprocess, "run", fake_run)
+ assert ips._stage_replacement("unsloth") is None
+ assert "UV_EXCLUDE_NEWER" in capsys.readouterr().err
+
+ def test_no_cutoff_argument_without_the_variable(self, monkeypatch):
+ self._uv_only(monkeypatch)
+ assert ips._uv_upload_cutoff_args() == []
+
+ @pytest.mark.parametrize("label", ("_restore_from_staged", "the repair fallback"))
+ def test_the_staged_wheel_is_reinstalled_with_pip_not_uv(self, monkeypatch, label):
+ """UV_REQUIRE_HASHES would reject the unpinned name after the uninstall
+ loop has already removed every record, leaving the package uninstalled.
+ The wheel is already built, so pip is both safe and sufficient."""
+ installs = []
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(
+ ips,
+ "pip_install_try",
+ lambda _label, *args, **kwargs: installs.append(kwargs) or True,
+ )
+ if label == "_restore_from_staged":
+ ips._restore_from_staged("unsloth", "/staged", removed_any = True)
+ else:
+ probes = iter((["old", "new"], ["new"], [], ["new"]))
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda _name: next(probes)
+ )
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ assert ips._repair_duplicate_core_metadata(("custom-package",))
+ assert len(installs) == 1
+ assert installs[0].get("force_pip") is True
+
+ def test_ci_overlay_is_wired_into_duplicate_repair(self):
+ source = inspect.getsource(ips.install_python_stack).replace(" ", "")
+ assert 'os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY","")' in source
+ assert "ci_source_overlay=ci_source_overlay" in source
+
+ def test_the_replacement_is_staged_before_any_record_is_removed(self, monkeypatch):
+ """The uninstall loop deletes every record, so the replacement has to be
+ in hand first. Otherwise an index that is unreachable at that moment
+ leaves the venv with no unsloth and nothing to reinstall from."""
+ probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"]))
+ order = []
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(
+ ips, "_stage_replacement", lambda _name: order.append("stage") or "/staged"
+ )
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: order.append("uninstall") or True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: order.append("install") or True)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is True
+ # Two records, so two uninstalls: pip removes one per invocation.
+ assert order == ["stage", "uninstall", "uninstall", "install"]
+
+ def test_repair_leaves_the_install_alone_when_the_replacement_cannot_be_fetched(
+ self, monkeypatch, capsys
+ ):
+ probes = iter((["2026.8.12", "2026.8.15"],))
+ removals = []
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: None)
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: removals.append(a) or True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert removals == []
+ assert "could not fetch a replacement" in capsys.readouterr().err
+
+ def test_a_failed_reinstall_reports_instead_of_exiting(self, monkeypatch, capsys):
+ probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"], []))
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: False)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert "no longer installed" in capsys.readouterr().err
+
+ def test_a_failed_uninstall_reports_instead_of_exiting(self, monkeypatch, capsys):
+ probes = iter((["2026.8.12", "2026.8.15"],))
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: False)
+ installs = []
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: installs.append(a))
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert installs == []
+ assert "could not uninstall" in capsys.readouterr().err
+
+ def test_a_rollback_reinstall_keeps_its_own_metadata(self, monkeypatch, tmp_path, capsys):
+ """The rewritten record is uninstalled, a later uninstall fails, and
+ _restore_from_staged puts the package back from the staged wheel. The
+ finally block then ran quarantine.restore() over the top, either deleting
+ the wheel's valid METADATA (original absent) or overwriting it with the
+ original corrupt bytes, leaving the core package malformed after a
+ recovery that existed to make it whole.
+ """
+ record = tmp_path / "unsloth-2026.8.15.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_bytes(b"\xff\xfe")
+ (record / "RECORD").write_text("unsloth/__init__.py,,\n")
+
+ probes = iter((["2026.8.15", "2026.8.15"], ["2026.8.15", "2026.8.15"], ["2026.8.15"]))
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _n: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [record])
+ monkeypatch.setattr(ips.install_manifest, "pip_backup_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _n: str(tmp_path / "staged"))
+
+ runs = {"n": 0}
+
+ def uninstall(_label, _cmd):
+ runs["n"] += 1
+ if runs["n"] == 1:
+ # pip removed the rewritten record's whole directory.
+ shutil.rmtree(record)
+ return True
+ return False # the next one fails, triggering the rollback
+
+ monkeypatch.setattr(ips, "_run_ok", uninstall)
+
+ def reinstall(*_a, **_k):
+ # The staged wheel recreates the same path with its own valid metadata.
+ record.mkdir(exist_ok = True)
+ (record / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n", encoding = "utf-8"
+ )
+ return True
+
+ monkeypatch.setattr(ips, "pip_install_try", reinstall)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ # Whatever the rollback put back must survive the quarantine unwinding.
+ assert record.is_dir()
+ assert (record / "METADATA").read_text().startswith("Metadata-Version")
+ assert "Name: unsloth" in (record / "METADATA").read_text()
+
+ def test_a_quarantined_backup_is_restored_when_staging_fails(self, monkeypatch, tmp_path):
+ """Quarantine's remaining user is pip's ~ leftover, moved aside so the
+ uninstall loop can converge. Moving it and then failing to fetch the
+ replacement would leave the venv worse than it was found, so a failed
+ staging has to put it back.
+ """
+ backup = tmp_path / "~nsloth-2026.8.12.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.12\n", encoding = "utf-8"
+ )
+ probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"]))
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _n: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _n: [])
+ monkeypatch.setattr(ips.install_manifest, "pip_backup_metadata_paths", lambda _n: [backup])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _n: None)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert backup.is_dir()
+ assert "Name: unsloth" in (backup / "METADATA").read_text()
+
+ def test_staging_builds_a_wheel_so_the_offline_install_can_work(self):
+ """pip download leaves an sdist for a source-only index, and the install
+ that follows runs --no-index, so its isolated build cannot fetch
+ setuptools and the package stays uninstalled."""
+ source = inspect.getsource(ips._stage_replacement).replace(" ", "")
+ assert '"wheel",\n"--no-deps",' in source
+ assert '"--wheel-dir",\nstaging,' in source
+ assert '"download"' not in source
+ assert 'glob.glob(os.path.join(staging,"*.whl"))' in source
+
+ def test_a_git_overlay_is_staged_before_the_uninstall_loop(self, monkeypatch):
+ """--local pulls unsloth-zoo from git, so an overlay is a network fetch
+ too. Skipping staging for it meant an unreachable GitHub left the
+ package uninstalled."""
+ probes = {"unsloth-zoo": iter((["old", "new"], ["new"], [], ["new"]))}
+ order = []
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda name: next(probes[name])
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(
+ ips, "_stage_replacement", lambda spec: order.append(("stage", spec)) or "/staged"
+ )
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: order.append(("uninstall",)) or True)
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda label, *a, **k: order.append(("install",)) or True
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth-zoo",), local_repo = "/src/unsloth")
+ assert order[0] == ("stage", "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo")
+ assert order[1] == ("uninstall",)
+
+ def test_an_editable_overlay_stages_the_checkout(self, monkeypatch):
+ probes = {"unsloth": iter((["old", "new"], ["new"], [], ["new"]))}
+ staged_for = []
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda name: next(probes[name])
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(
+ ips, "_stage_replacement", lambda spec: staged_for.append(spec) or "/staged"
+ )
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",), local_repo = "/src/unsloth")
+ assert staged_for == ["/src/unsloth"]
+
+ def test_a_failed_overlay_falls_back_to_the_staged_source(self, monkeypatch):
+ probes = {"unsloth-zoo": iter((["old", "new"], ["new"], [], ["new"]))}
+ installs = []
+
+ monkeypatch.setattr(
+ ips.install_manifest, "installed_versions", lambda name: next(probes[name])
+ )
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _spec: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "_overlay_local_core_package", lambda *a, **k: False)
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda label, *a, **k: installs.append(a) or True
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth-zoo",), local_repo = "/src/unsloth")
+ assert installs and "--find-links" in installs[0]
+
+ def test_a_partial_uninstall_restores_the_payload(self, monkeypatch, capsys):
+ """The first uninstall deletes the package tree. Returning after a later
+ one fails would leave a dist-info claiming an install whose files are
+ gone."""
+ probes = iter((["a", "b", "c"], ["b", "c"]))
+ uninstalls = iter([True, False])
+ installs = []
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _spec: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: next(uninstalls))
+ monkeypatch.setattr(
+ ips, "pip_install_try", lambda label, *a, **k: installs.append(a) or True
+ )
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert installs and "--find-links" in installs[0]
+ assert "restored unsloth from the staged replacement" in capsys.readouterr().err
+
+ def test_nothing_is_restored_when_no_record_was_removed(self, monkeypatch):
+ probes = iter((["a", "b"],))
+ installs = []
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips.install_manifest, "invalid_metadata_paths", lambda _name: [])
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _spec: "/staged")
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: False)
+ monkeypatch.setattr(ips, "pip_install_try", lambda label, *a, **k: installs.append(a))
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is False
+ assert installs == []
+
+ def test_staging_directories_are_cleaned_up(self, monkeypatch, tmp_path):
+ staged = tmp_path / "staged"
+ staged.mkdir()
+ probes = iter((["2026.8.12", "2026.8.15"], ["2026.8.15"], [], ["2026.8.15"]))
+
+ monkeypatch.setattr(ips.install_manifest, "installed_versions", lambda _name: next(probes))
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(ips.importlib, "invalidate_caches", lambda: None)
+ monkeypatch.setattr(ips, "_stage_replacement", lambda _name: str(staged))
+ monkeypatch.setattr(ips, "_run_ok", lambda *a, **k: True)
+ monkeypatch.setattr(ips, "pip_install_try", lambda *a, **k: True)
+
+ assert ips._repair_duplicate_core_metadata(("unsloth",)) is True
+ assert not staged.exists()
+
+ def test_normal_local_overlay_still_applies_both_sources(self, monkeypatch):
+ installs = []
+ monkeypatch.setattr(ips, "_step", lambda *a, **k: None)
+ monkeypatch.setattr(
+ ips,
+ "pip_install",
+ lambda label, *args, **kwargs: installs.append((label, args, kwargs)),
+ )
+
+ ips._overlay_local_core_packages("/src/unsloth")
+
+ assert [call[1] for call in installs] == [
+ ("--no-cache-dir", "--no-deps", "-e", "/src/unsloth"),
+ (
+ "--no-cache-dir",
+ "--no-deps",
+ "--force-reinstall",
+ "unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
+ ),
+ ]
+ assert all(call[2]["constrain"] is False for call in installs)
+
+
class TestDesktopBackendVersionConstraint:
"""Verify that UNSLOTH_DESKTOP_BACKEND_VERSION adds the floor pin when upgrading unsloth."""
diff --git a/tests/python/test_studio_runtime_gate.py b/tests/python/test_studio_runtime_gate.py
index ded253bb6fb..8e25a6faa96 100644
--- a/tests/python/test_studio_runtime_gate.py
+++ b/tests/python/test_studio_runtime_gate.py
@@ -80,7 +80,7 @@ def test_terminal_update_holds_the_gate_through_environment_mutation():
# The launcher transaction wraps the mutation; it replaced the self-exe lock release.
launcher = body.index("_WindowsLauncherUpdateTransaction()", idle_scan)
setup = body.index("_run_setup_script(", launcher)
- verify = body.index("_fail_if_install_damaged()", setup)
+ verify = body.index("_fail_if_install_damaged(", setup)
assert consume < guard < idle_scan < launcher < setup < verify
@@ -90,8 +90,9 @@ def test_terminal_setup_holds_the_gate_through_environment_mutation():
consume = body.index("_studio_runtime_gate.consume_runtime_gate_handoff()")
guard = body.index("with _studio_runtime_launch_guard(", consume)
idle_scan = body.index("_studio_runtime_gate.ensure_managed_environment_is_idle", guard)
- setup = body.index("_run_setup_script(", idle_scan)
- assert consume < guard < idle_scan < setup
+ launcher = body.index("_WindowsLauncherUpdateTransaction()", idle_scan)
+ setup = body.index("_run_setup_script(", launcher)
+ assert consume < guard < idle_scan < launcher < setup
def test_interrupted_windows_setup_kills_tree_before_return(monkeypatch):
diff --git a/tests/python/test_windows_studio_update_launcher.py b/tests/python/test_windows_studio_update_launcher.py
index 535bf56bbac..6062bd42e17 100644
--- a/tests/python/test_windows_studio_update_launcher.py
+++ b/tests/python/test_windows_studio_update_launcher.py
@@ -88,7 +88,8 @@ def _configure_windows(
monkeypatch.setattr(studio, "_ensure_studio_env_exported", lambda: None)
monkeypatch.setattr(studio, "_windows_hidden_subprocess_kwargs", lambda: {})
monkeypatch.setattr(studio, "_refresh_desktop_shortcuts", lambda **_kwargs: None)
- monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda: None)
+ # *_args: the guard now takes the package name.
+ monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda *_args: None)
# The runtime gate's process scan is Windows-only, so off Windows it never runs and
# nothing here noticed it was unstubbed. On a real Windows host it shells out to
# powershell.exe through the same subprocess.run these tests replace, then reads
@@ -154,6 +155,26 @@ def test_a_recoverable_copy_exists_while_setup_runs(monkeypatch, studio, tmp_pat
_update(studio)
+def test_installer_setup_frees_the_running_launcher_for_metadata_repair(
+ monkeypatch, studio, tmp_path
+):
+ scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
+ replacement = b"MZ-reinstalled-launcher"
+
+ def setup(**_kwargs):
+ assert not launcher.exists()
+ assert (scripts / "unsloth.exe.update-backup").read_bytes() == ORIGINAL_LAUNCHER
+ launcher.write_bytes(replacement)
+
+ monkeypatch.setattr(studio, "_run_setup_script", setup)
+ monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())
+
+ studio.setup(verbose = False)
+
+ assert launcher.read_bytes() == replacement
+ assert not (scripts / "unsloth.exe.update-backup").exists()
+
+
def test_setup_failure_restores_original_and_propagates(monkeypatch, studio, tmp_path):
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
@@ -223,7 +244,9 @@ def test_no_verify_still_checks_launcher_but_skips_integrity_scan(monkeypatch, s
calls = []
monkeypatch.setattr(studio.subprocess, "run", _successful_version_run(calls))
integrity_calls = []
- monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda: integrity_calls.append(True))
+ monkeypatch.setattr(
+ studio, "_fail_if_install_damaged", lambda *_args: integrity_calls.append(True)
+ )
_update(studio, verify = False)
@@ -282,7 +305,7 @@ def test_non_windows_preserves_call_order_without_launcher_operations(
monkeypatch.setattr(studio, "_ensure_studio_env_exported", lambda: None)
calls = []
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: calls.append("setup"))
- monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda: calls.append("verify"))
+ monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda *_args: calls.append("verify"))
monkeypatch.setattr(
studio, "_refresh_desktop_shortcuts", lambda **_kwargs: calls.append("refresh")
)
diff --git a/tests/studio/install/test_install_manifest.py b/tests/studio/install/test_install_manifest.py
index 97741e9627a..29559d06c7b 100644
--- a/tests/studio/install/test_install_manifest.py
+++ b/tests/studio/install/test_install_manifest.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import importlib.util
import json
import pathlib
+import sysconfig
import pytest
@@ -50,6 +51,16 @@ def install_root(tmp_path: pathlib.Path) -> pathlib.Path:
return root
+def _write_dist_metadata(site: pathlib.Path, name: str, version: str) -> None:
+ stem = name.replace("-", "_")
+ info = site / f"{stem}-{version}.dist-info"
+ info.mkdir(parents = True)
+ (info / "METADATA").write_text(
+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n",
+ encoding = "utf-8",
+ )
+
+
def test_parse_requirement_line_handles_the_shapes_studio_txt_uses():
assert im._parse_requirement_line("structlog>=24.1.0") == ("structlog", "", ">=24.1.0")
assert im._parse_requirement_line("matplotlib==3.10.9") == ("matplotlib", "", "==3.10.9")
@@ -68,6 +79,168 @@ def test_parse_requirement_line_handles_the_shapes_studio_txt_uses():
assert specifier == ""
+def test_installed_versions_reports_every_canonical_metadata_record(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo_pkg", "1.0")
+ _write_dist_metadata(site, "demo-pkg", "2.0")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ assert im.installed_versions("demo.pkg") == ["1.0", "2.0"]
+ assert im._installed_version("demo-pkg") is None
+
+
+def test_installed_versions_ignores_malformed_unrelated_metadata(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ _write_dist_metadata(site, "demo", "2.0")
+ malformed = site / "unrelated-1.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ assert im.installed_versions("demo") == ["1.0", "2.0"]
+
+
+def test_installed_versions_marks_malformed_matching_metadata_as_a_conflict(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ malformed = site / "demo-2.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ versions = im.installed_versions("demo")
+ assert versions == ["", "1.0"]
+ assert im.invalid_metadata_paths("demo") == [malformed]
+ assert im.metadata_conflict(versions) is True
+ assert im._installed_version("demo") is None
+
+
+def test_a_pip_tilde_backup_is_named_as_a_backup(tmp_path, monkeypatch):
+ """pip's AdjacentTempDirectory leftover counts as a duplicate but pip will
+ not uninstall it, so the repair has to find it by directory name."""
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "2.0")
+ backup = site / "~emo-1.0.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: demo\nVersion: 1.0\n", encoding = "utf-8"
+ )
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ assert im.installed_versions("demo") == ["1.0", "2.0"]
+ assert im.pip_backup_metadata_paths("demo") == [backup]
+ # A healthy record must never be mistaken for one.
+ assert im.pip_backup_metadata_paths("demo") != [site / "demo-2.0.dist-info"]
+
+
+def test_a_sole_pip_backup_is_reported_as_a_conflict(tmp_path, monkeypatch):
+ """pip killed after moving the old record aside leaves one readable version,
+ so a version count sees nothing wrong while the package is really gone."""
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ backup = site / "~emo-1.0.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: demo\nVersion: 1.0\n", encoding = "utf-8"
+ )
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ assert im.metadata_conflict(im.installed_versions("demo")) is False
+ assert im.installed_version_probe("demo") == ("1.0", True)
+ assert im.installed_version_probe("other", ("demo",))[1] is True
+
+
+def test_a_healthy_install_has_no_pip_backups(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "2.0")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ assert im.pip_backup_metadata_paths("demo") == []
+
+
+def test_single_malformed_matching_metadata_is_a_conflict(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ malformed = site / "demo_pkg-2.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ versions = im.installed_versions("demo-pkg")
+ assert versions == [""]
+ assert im.invalid_metadata_paths("demo-pkg") == [malformed]
+ assert im.metadata_conflict(versions) is True
+
+
+def test_nameless_matching_metadata_is_a_conflict(tmp_path, monkeypatch):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ nameless = site / "demo-2.0.dist-info"
+ nameless.mkdir()
+ (nameless / "METADATA").write_text("Metadata-Version: 2.1\nVersion: 2.0\n", encoding = "utf-8")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ versions = im.installed_versions("demo")
+ assert versions == ["", "1.0"]
+ assert im.invalid_metadata_paths("demo") == [nameless]
+ assert im.metadata_conflict(versions) is True
+
+
+def test_malformed_matching_metadata_invalidates_the_manifest(
+ tmp_path, monkeypatch, install_root, req_root
+):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+ im.write_manifest(root = install_root, req_root = req_root, package_name = "demo")
+
+ malformed = site / "demo-2.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+
+ state = im.verify_install(root = install_root, req_root = req_root, package_name = "demo")
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_duplicate_package_metadata_invalidates_the_manifest(
+ tmp_path, monkeypatch, install_root, req_root
+):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ _write_dist_metadata(site, "demo", "2.0")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ im.write_manifest(root = install_root, req_root = req_root, package_name = "demo")
+ state = im.verify_install(root = install_root, req_root = req_root, package_name = "demo")
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_duplicate_zoo_metadata_invalidates_a_core_package_manifest(
+ tmp_path, monkeypatch, install_root, req_root
+):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ _write_dist_metadata(site, "demo", "1.0")
+ _write_dist_metadata(site, "unsloth-zoo", "1.0")
+ _write_dist_metadata(site, "unsloth-zoo", "2.0")
+ monkeypatch.setattr(im, "_metadata_scan_paths", lambda: [str(site)])
+
+ im.write_manifest(root = install_root, req_root = req_root, package_name = "demo")
+ state = im.verify_install(root = install_root, req_root = req_root, package_name = "demo")
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
def test_missing_requirements_rejects_an_incompatible_installed_version(tmp_path):
req = tmp_path / "studio.txt"
req.write_text(
@@ -187,6 +360,21 @@ def test_verify_follows_the_package_the_manifest_names(install_root, req_root):
assert state["manifest_ok"] is True
[email protected]("conflict", ["pytest", "unsloth-zoo"])
+def test_foreign_metadata_conflicts_invalidate_the_manifest(install_root, req_root, conflict):
+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")
+ state = im.verify_install(
+ root = install_root,
+ req_root = req_root,
+ package_name = "pytest",
+ installed = {"pytest": pytest.__version__},
+ installed_conflicts = {conflict},
+ )
+
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
def test_edited_requirements_invalidate_the_manifest(install_root, req_root):
# The --local dev path: an edited studio.txt must re-run the dependency
# pass, not sit behind setup.sh's "up to date" fast path.
@@ -280,6 +468,67 @@ def test_set_no_torch_marker_clears_itself_and_never_raises(install_root):
im.set_no_torch_marker(True, root = install_root / "does" / "not" / "exist")
+def test_scan_paths_dedupes_a_lib64_symlink(tmp_path, monkeypatch):
+ """purelib hardcodes `lib`, platlib follows sys.platlibdir.
+
+ On a lib64 build (Fedora, SuSE) venv creates lib64 as a symlink to lib, so
+ the two schemes name ONE directory by two paths. Scanning both reported
+ every installed package twice, which made metadata_conflict() true for a
+ perfectly healthy environment and sent the installer into a repair it could
+ never finish.
+ """
+ real = tmp_path / "lib" / "python3.13" / "site-packages"
+ real.mkdir(parents = True)
+ (tmp_path / "lib64").symlink_to("lib")
+ alias = tmp_path / "lib64" / "python3.13" / "site-packages"
+
+ # install_manifest imports sysconfig inside the function, so patch the module.
+ monkeypatch.setattr(
+ sysconfig, "get_paths", lambda *a, **k: {"purelib": str(real), "platlib": str(alias)}
+ )
+
+ assert im._metadata_scan_paths() == [str(real)]
+
+
+def test_scan_paths_keeps_genuinely_separate_roots(tmp_path, monkeypatch):
+ pure = tmp_path / "purelib"
+ plat = tmp_path / "platlib"
+ pure.mkdir()
+ plat.mkdir()
+
+ monkeypatch.setattr(
+ sysconfig, "get_paths", lambda *a, **k: {"purelib": str(pure), "platlib": str(plat)}
+ )
+
+ assert im._metadata_scan_paths() == [str(pure), str(plat)]
+
+
+def test_a_record_outside_this_interpreters_scheme_is_not_installed(tmp_path, monkeypatch):
+ """The scan is purelib/platlib only, so a user site or an inherited
+ PYTHONPATH entry is invisible. _installed_version used to answer from all of
+ sys.path, so this narrows it deliberately: every caller runs against the
+ managed venv, where those trees are either disabled or someone else's. A
+ duplicate the venv does not own must not make the venv look damaged.
+ """
+ scheme = tmp_path / "site-packages"
+ scheme.mkdir()
+ elsewhere = tmp_path / "user-site"
+ elsewhere.mkdir()
+ record = elsewhere / "demo-1.0.dist-info"
+ record.mkdir()
+ (record / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: demo\nVersion: 1.0\n", encoding = "utf-8"
+ )
+
+ monkeypatch.setattr(
+ sysconfig, "get_paths", lambda *a, **k: {"purelib": str(scheme), "platlib": str(scheme)}
+ )
+ monkeypatch.syspath_prepend(str(elsewhere))
+
+ assert im.installed_versions("demo") == []
+ assert im.installed_version_probe("demo") == ("", False)
+
+
def _fake_venv(root, files):
"""A venv-shaped tree whose installed package ships its own requirements."""
site = root / "lib" / "python3.12" / "site-packages"
diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.py
index da6f9aa7d84..377cf12661e 100644
--- a/tests/studio/install/test_setup_fast_path_guard.py
+++ b/tests/studio/install/test_setup_fast_path_guard.py
@@ -52,6 +52,24 @@ def test_guard_can_still_force_the_dependency_pass(script: pathlib.Path):
)
[email protected]("script", [SETUP_SH, SETUP_PS1], ids = ["setup.sh", "setup.ps1"])
+def test_duplicate_core_metadata_cannot_take_the_version_fast_path(script: pathlib.Path):
+ text = script.read_text(encoding = "utf-8")
+ probe = text.find("install_manifest.installed_version_probe")
+ zoo_probe = text.find("'unsloth-zoo'", probe)
+ repair = text.find("duplicate metadata found", probe)
+ if script.name.endswith(".ps1"):
+ skip = text.find("$SkipPythonDeps = $true", repair)
+ else:
+ skip = text.find("_SKIP_PYTHON_DEPS=true", repair)
+
+ assert probe != -1 and zoo_probe != -1 and repair != -1 and skip != -1
+ assert probe <= zoo_probe < repair < skip, (
+ f"{script.name} must detect duplicate metadata before an arbitrary "
+ "version can select the up-to-date fast path"
+ )
+
+
def test_ps1_drops_the_manifest_before_its_first_install():
"""Nothing may mutate the venv while the marker still says "install finished".
@@ -97,3 +115,26 @@ def test_sh_guard_runs_before_the_skip_decision():
"the incomplete-install guard must run before setup.sh acts on "
"_SKIP_PYTHON_DEPS, otherwise it can never change the outcome"
)
+
+
+INSTALL_SH = REPO_ROOT / "install.sh"
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+
+
[email protected]("script", [INSTALL_SH, INSTALL_PS1], ids = ["install.sh", "install.ps1"])
+def test_the_installer_reports_duplicate_metadata_on_every_platform(script: pathlib.Path):
+ """Both installers print the version they just installed.
+
+ importlib.metadata.version() answers from whichever record the finder
+ yields first, so on a duplicated install it prints an arbitrary one and the
+ run looks clean. Windows and POSIX have to agree here, or the same broken
+ venv is reported differently depending on the host.
+ """
+ text = script.read_text(encoding = "utf-8")
+ assert "installed_version_probe" in text, (
+ f"{script.name} still reports the installed version through "
+ "importlib.metadata.version(), which cannot see a duplicate record"
+ )
+ assert (
+ "duplicate metadata found" in text
+ ), f"{script.name} detects the conflict but never says so"
diff --git a/tests/studio/install/test_studio_deps_cli.py b/tests/studio/install/test_studio_deps_cli.py
index dabda162509..822bbe9ecd7 100644
--- a/tests/studio/install/test_studio_deps_cli.py
+++ b/tests/studio/install/test_studio_deps_cli.py
@@ -21,9 +21,11 @@ import importlib.util
import io
import json
import contextlib
+import os
import pathlib
import shutil
import sys
+import sysconfig
import pytest
import typer
@@ -74,6 +76,16 @@ def _studio_distribution_versions() -> dict:
return versions
+def _venv_executable(root: pathlib.Path) -> pathlib.Path:
+ """Where _venv_site_packages looks for this venv's interpreter.
+
+ Writing bin/python on Windows leaves the probe with nothing to run, so the
+ fixture falls through to the glob fallback and the case under test never
+ happens.
+ """
+ return root / "Scripts" / "python.exe" if os.name == "nt" else root / "bin" / "python"
+
+
def _make_venv(
root: pathlib.Path,
*,
@@ -134,6 +146,14 @@ def cross_venv(tmp_path, monkeypatch):
managed_distributions = None,
extra_requirement = "",
with_manifest = True,
+ duplicate_versions = (),
+ inactive_duplicate_version = "",
+ unresolved_active_paths = False,
+ malformed_unrelated_metadata = False,
+ malformed_core_metadata = False,
+ nameless_core_metadata = False,
+ versionless_core_metadata = False,
+ editable_requirements = False,
):
caller = tmp_path / "caller_venv"
caller_site = _make_venv(caller, unsloth_version = caller_version, distributions = [])
@@ -148,11 +168,75 @@ def cross_venv(tmp_path, monkeypatch):
)
if with_manifest:
_write_manifest(managed, managed_site, managed_version)
+ for index, version in enumerate(duplicate_versions):
+ dist_info = managed_site / f"unsloth_duplicate_{index}-{version}.dist-info"
+ dist_info.mkdir()
+ (dist_info / "METADATA").write_text(
+ f"Metadata-Version: 2.1\nName: unsloth\nVersion: {version}\n",
+ encoding = "utf-8",
+ )
+ if inactive_duplicate_version:
+ inactive_site = managed / "lib" / "python3.10" / "site-packages"
+ dist_info = inactive_site / f"unsloth-{inactive_duplicate_version}.dist-info"
+ dist_info.mkdir(parents = True)
+ (dist_info / "METADATA").write_text(
+ "Metadata-Version: 2.1\n"
+ "Name: unsloth\n"
+ f"Version: {inactive_duplicate_version}\n",
+ encoding = "utf-8",
+ )
+ if unresolved_active_paths:
+ (managed / "lib" / "python3.10" / "site-packages").mkdir(parents = True)
+ if malformed_unrelated_metadata:
+ malformed = managed_site / "unrelated-1.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ if malformed_core_metadata:
+ malformed = managed_site / "unsloth-2.0.dist-info"
+ malformed.mkdir()
+ (malformed / "METADATA").write_bytes(b"\xff\xfe")
+ if nameless_core_metadata:
+ nameless = managed_site / "unsloth-2.0.dist-info"
+ nameless.mkdir()
+ (nameless / "METADATA").write_text(
+ "Metadata-Version: 2.1\nVersion: 2.0\n", encoding = "utf-8"
+ )
+ if versionless_core_metadata:
+ versionless = managed_site / "unsloth-2.0.dist-info"
+ versionless.mkdir()
+ (versionless / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\n", encoding = "utf-8"
+ )
+ checkout_requirements = None
+ if editable_requirements:
+ checkout_studio = tmp_path / "checkout" / "studio"
+ shutil.move(str(managed_site / "studio"), checkout_studio)
+ checkout_requirements = checkout_studio / "backend" / "requirements"
+ executable = _venv_executable(managed)
+ executable.parent.mkdir(parents = True, exist_ok = True)
+ executable.write_text("probe placeholder", encoding = "utf-8")
(caller_site / "unsloth_cli").mkdir(parents = True)
shutil.copy(DEPS_PATH, caller_site / "unsloth_cli" / "_studio_deps.py")
monkeypatch.setattr(sys, "prefix", str(caller))
deps = _load(caller_site / "unsloth_cli" / "_studio_deps.py", "studio_deps_cross_venv")
+ if checkout_requirements is not None:
+
+ def editable_paths(args, **_kwargs):
+ if "sysconfig" in args[-1]:
+ return json.dumps([str(managed_site), str(managed_site)])
+ return json.dumps(str(checkout_requirements))
+
+ monkeypatch.setattr(deps.subprocess, "check_output", editable_paths)
+ if inactive_duplicate_version:
+ executable = _venv_executable(managed)
+ executable.parent.mkdir(parents = True, exist_ok = True)
+ executable.write_text("probe placeholder", encoding = "utf-8")
+
+ def active_paths(*_args, **_kwargs):
+ return json.dumps([str(managed_site), str(managed_site)])
+
+ monkeypatch.setattr(deps.subprocess, "check_output", active_paths)
return deps.install_state(extra_roots = (managed,))
return build
@@ -190,6 +274,71 @@ def test_an_unfinished_managed_install_is_still_reported_incomplete(cross_venv):
assert state["reason"] == "studio_install_incomplete"
[email protected]("duplicate_version", ["2026.6.1", "2026.5.9"])
+def test_duplicate_metadata_in_a_foreign_managed_venv_is_not_collapsed(
+ cross_venv, duplicate_version
+):
+ state = cross_venv(duplicate_versions = (duplicate_version,))
+
+ assert state["ok"] is False
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_inactive_python_site_packages_do_not_create_a_foreign_conflict(cross_venv):
+ state = cross_venv(inactive_duplicate_version = "2025.1.1")
+
+ assert state["ok"] is True, state
+ assert state["reason"] is None
+
+
+def test_unresolved_foreign_site_packages_fail_closed(cross_venv):
+ state = cross_venv(unresolved_active_paths = True)
+
+ assert state["ok"] is False
+ assert state["manifest_ok"] is False
+ assert state["deps_ok"] is False
+ assert state["reason"] == "studio_install_incomplete"
+
+
+def test_malformed_unrelated_foreign_metadata_does_not_hide_valid_records(cross_venv):
+ state = cross_venv(malformed_unrelated_metadata = True)
+
+ assert state["ok"] is True, state
+ assert state["reason"] is None
+
+
+def test_malformed_core_metadata_is_a_foreign_conflict(cross_venv):
+ state = cross_venv(malformed_core_metadata = True)
+
+ assert state["ok"] is False
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_nameless_core_metadata_is_a_foreign_conflict(cross_venv):
+ state = cross_venv(nameless_core_metadata = True)
+
+ assert state["ok"] is False
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_versionless_core_metadata_is_a_foreign_conflict(cross_venv):
+ state = cross_venv(versionless_core_metadata = True)
+
+ assert state["ok"] is False
+ assert state["manifest_ok"] is False
+ assert state["reason"] == "studio_install_metadata_conflict"
+
+
+def test_editable_foreign_install_follows_its_requirements_checkout(cross_venv):
+ state = cross_venv(editable_requirements = True)
+
+ assert state["ok"] is True, state
+ assert state["reason"] is None
+
+
# ── import name vs distribution name ─────────────────────────────────
@@ -314,3 +463,191 @@ def test_an_editable_checkout_is_not_owned_by_a_surrounding_venv(tmp_path, deps)
module = _load(module_path, "manifest_in_editable_checkout")
assert deps._venv_root_for_module(module) is None
+
+
+def test_scan_paths_dedupes_a_lib64_symlink(tmp_path, monkeypatch, deps):
+ """A lib64 build names one site-packages twice.
+
+ purelib hardcodes `lib` while platlib follows sys.platlibdir, and venv
+ creates lib64 as a symlink to lib, so Fedora and SuSE would otherwise scan
+ the same directory twice and report EVERY installed package as having
+ duplicate metadata -- failing `unsloth studio update` on a healthy venv.
+ """
+ real = tmp_path / "lib" / "python3.13" / "site-packages"
+ real.mkdir(parents = True)
+ (tmp_path / "lib64").symlink_to("lib")
+ alias = tmp_path / "lib64" / "python3.13" / "site-packages"
+
+ monkeypatch.setattr(
+ sysconfig, "get_paths", lambda *a, **k: {"purelib": str(real), "platlib": str(alias)}
+ )
+
+ assert deps._scan_paths() == {"path": [str(real)]}
+
+
+def test_a_foreign_lib64_venv_reports_no_duplicates(tmp_path, deps):
+ venv = tmp_path / "managed"
+ real = venv / "lib" / "python3.13" / "site-packages"
+ real.mkdir(parents = True)
+ (venv / "lib64").symlink_to("lib")
+ (venv / "pyvenv.cfg").write_text("home = /usr/bin\nversion = 3.13.0\n", encoding = "utf-8")
+ dist_info = real / "unsloth-2026.8.15.dist-info"
+ dist_info.mkdir()
+ (dist_info / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n", encoding = "utf-8"
+ )
+
+ found = deps._distributions_in(venv)
+
+ assert found is not None
+ installed, conflicts = found
+ assert installed["unsloth"] == "2026.8.15"
+ assert conflicts == set()
+
+
+def test_a_foreign_venvs_sole_tilde_backup_is_a_conflict(tmp_path, deps):
+ """The backup reads as one healthy version, so nothing else here can tell
+ the environment apart from a good one, yet pip calls it an invalid
+ distribution and the payload is renamed away with it. Reproduced in a real
+ venv: the scanner reported 1.0 while the package was unimportable.
+ """
+ venv = tmp_path / "managed"
+ site = venv / "lib" / "python3.13" / "site-packages"
+ site.mkdir(parents = True)
+ (venv / "pyvenv.cfg").write_text("home = /usr/bin\nversion = 3.13.0\n", encoding = "utf-8")
+ backup = site / "~nsloth_zoo-2026.8.12.dist-info"
+ backup.mkdir()
+ (backup / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth_zoo\nVersion: 2026.8.12\n", encoding = "utf-8"
+ )
+
+ found = deps._distributions_in(venv)
+
+ assert found is not None
+ installed, conflicts = found
+ assert installed["unsloth-zoo"] == "2026.8.12"
+ assert conflicts == {"unsloth-zoo"}
+
+
+def test_a_nameless_local_record_is_reported_as_a_conflict(tmp_path, monkeypatch, deps):
+ """install_manifest.installed_versions() calls this state a conflict, so the
+ CLI's own check has to agree: pip cannot parse the record either."""
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ for name, metadata in (
+ (
+ "unsloth-2026.8.15.dist-info",
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n",
+ ),
+ ("unsloth-2026.8.12.dist-info", "Metadata-Version: 2.1\nVersion: 2026.8.12\n"),
+ ):
+ entry = site / name
+ entry.mkdir()
+ (entry / "METADATA").write_text(metadata, encoding = "utf-8")
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+
+ conflicts = deps.installed_metadata_conflicts(names = ("unsloth",))
+
+ assert len(conflicts) == 1
+ assert "unsloth: multiple metadata records" in conflicts[0]
+
+
+def test_a_single_unreadable_record_is_reported_as_a_conflict(tmp_path, monkeypatch, deps):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ entry = site / "unsloth-2026.8.15.dist-info"
+ entry.mkdir()
+ (entry / "METADATA").write_bytes(b"Metadata-Version: 2.1\nName: un\xffsloth\n")
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+
+ assert deps.installed_metadata_conflicts(names = ("unsloth",))
+
+
+def test_one_readable_record_is_not_a_conflict(tmp_path, monkeypatch, deps):
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ entry = site / "unsloth-2026.8.15.dist-info"
+ entry.mkdir()
+ (entry / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n", encoding = "utf-8"
+ )
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+
+ assert deps.installed_metadata_conflicts(names = ("unsloth",)) == []
+
+
+def test_a_versionless_local_record_is_reported_as_a_conflict(tmp_path, monkeypatch, deps):
+ """install_manifest.metadata_conflict() counts an empty version as a
+ conflict, so trusting the same record here would leave the two checks
+ disagreeing about one directory, and would let the file-damage scan treat an
+ unparseable record as authoritative."""
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ entry = site / "unsloth-2026.8.15.dist-info"
+ entry.mkdir()
+ (entry / "METADATA").write_text("Metadata-Version: 2.1\nName: unsloth\n", encoding = "utf-8")
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+
+ conflicts = deps.installed_metadata_conflicts(names = ("unsloth",))
+
+ assert len(conflicts) == 1
+ assert "unreadable metadata" in conflicts[0]
+
+
+def test_an_interrupted_upgrades_tilde_orphan_is_a_conflict(tmp_path, monkeypatch, deps):
+ """pip renames the outgoing distribution to a `~` prefixed sibling during an
+ upgrade (AdjacentTempDirectory) and a kill mid-operation keeps both. pip has
+ no duplicate detection of its own, so nothing upstream clears it. The orphan
+ still parses and still says Name: unsloth, so it is a second record for the
+ same project: a conflict, not a file the newer release deleted.
+ """
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ for name, version in (
+ ("unsloth-2026.8.15.dist-info", "2026.8.15"),
+ ("~nsloth-2026.8.12.dist-info", "2026.8.12"),
+ ):
+ entry = site / name
+ entry.mkdir()
+ (entry / "METADATA").write_text(
+ f"Metadata-Version: 2.1\nName: unsloth\nVersion: {version}\n", encoding = "utf-8"
+ )
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+
+ conflicts = deps.installed_metadata_conflicts(names = ("unsloth",))
+
+ assert len(conflicts) == 1
+ assert "unsloth: multiple metadata records" in conflicts[0]
+
+
+def test_an_editable_checkouts_egg_info_is_not_a_second_record(tmp_path, monkeypatch, deps):
+ """A setuptools editable install legitimately resolves to two records, a
+ dist-info in site-packages and an egg-info in the source tree. Only the
+ first is in this interpreter's scheme, and scanning purelib/platlib rather
+ than all of sys.path is what keeps a developer checkout from failing the
+ update it is running.
+ """
+ site = tmp_path / "site-packages"
+ site.mkdir()
+ entry = site / "unsloth-2026.8.15.dist-info"
+ entry.mkdir()
+ (entry / "METADATA").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n", encoding = "utf-8"
+ )
+ checkout = tmp_path / "src"
+ egg = checkout / "unsloth.egg-info"
+ egg.mkdir(parents = True)
+ (egg / "PKG-INFO").write_text(
+ "Metadata-Version: 2.1\nName: unsloth\nVersion: 2026.8.15\n", encoding = "utf-8"
+ )
+ (site / "__editable__.unsloth.pth").write_text(str(checkout) + "\n", encoding = "utf-8")
+
+ monkeypatch.setattr(deps, "_scan_paths", lambda: {"path": [str(site)]})
+ monkeypatch.syspath_prepend(str(checkout))
+
+ assert deps.installed_metadata_conflicts(names = ("unsloth",)) == []
diff --git a/tests/test_installer_unsloth_version.py b/tests/test_installer_unsloth_version.py
index 660769a9f0f..6ab11662ad6 100644
--- a/tests/test_installer_unsloth_version.py
+++ b/tests/test_installer_unsloth_version.py
@@ -27,8 +27,10 @@ def _extract(pattern: str, source: str) -> str:
@pytest.mark.skipif(shutil.which("sh") is None, reason = "POSIX shell is unavailable")
def test_posix_installer_reports_installed_distribution_version():
source = INSTALL_SH.read_text(encoding = "utf-8")
+ # Two blocks now: the probe, whose exit code carries the conflict signal,
+ # and the report that acts on it.
reporter = _extract(
- r"_installed_package_version=\$\(.*?^fi",
+ r"^_installed_package_version_exit=0.*?^fi.*?^fi",
source,
)
result = subprocess.run(
diff --git a/unsloth_cli/_studio_deps.py b/unsloth_cli/_studio_deps.py
index 14e4af002a1..daff84733e6 100644
--- a/unsloth_cli/_studio_deps.py
+++ b/unsloth_cli/_studio_deps.py
@@ -16,9 +16,11 @@ from __future__ import annotations
import contextlib
import importlib.util
import inspect
+import json
import os
import re
import stat
+import subprocess
import sys
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence
@@ -107,11 +109,93 @@ def _resolved(path: Path) -> Path:
return path
+def _venv_executables(root: Path) -> tuple[Path, ...]:
+ return (
+ (root / "Scripts" / "python.exe",)
+ if os.name == "nt"
+ else (root / "bin" / "python", root / "bin" / "python3")
+ )
+
+
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
+ """The site-packages roots used by this venv's active interpreter.
+
+ A venv upgraded in place can retain lib/pythonX.Y directories from older
+ interpreters. Globbing all of them makes ordinary packages look duplicated,
+ even though only the active interpreter's directory is importable.
+ Deduplicated by real path: purelib hardcodes `lib` while platlib follows
+ sys.platlibdir, so a lib64 build (Fedora, SuSE) names one directory twice
+ through venv's lib64 -> lib symlink.
+ """
+
+ def existing_inside_root(values) -> List[Path]:
+ resolved_root = _resolved(root)
+ out: List[Path] = []
+ seen: set = set()
+ for value in values:
+ if not value:
+ continue
+ path = Path(value)
+ if not path.is_dir():
+ continue
+ resolved = _resolved(path)
+ if not resolved.is_relative_to(resolved_root) or resolved in seen:
+ continue
+ seen.add(resolved)
+ out.append(path)
+ return out
+
+ if _resolved(root) == _resolved(Path(sys.prefix)):
+ import sysconfig
+
+ try:
+ configured = sysconfig.get_paths()
+ except Exception:
+ configured = {}
+ current = existing_inside_root(configured.get(key) for key in ("purelib", "platlib"))
+ if current:
+ return current
+
+ probe = (
+ "import json, sysconfig; "
+ "p = sysconfig.get_paths(); "
+ "print(json.dumps([p.get('purelib'), p.get('platlib')]))"
+ )
+ for executable in _venv_executables(root):
+ if not executable.is_file():
+ continue
+ try:
+ output = subprocess.check_output(
+ [str(executable), "-I", "-c", probe],
+ stderr = subprocess.DEVNULL,
+ text = True,
+ timeout = 5,
+ )
+ values = json.loads(output)
+ except (OSError, subprocess.SubprocessError, TypeError, ValueError, json.JSONDecodeError):
+ continue
+ active = existing_inside_root(values if isinstance(values, list) else [])
+ if active:
+ return active
+
+ windows_site = root / "Lib" / "site-packages"
+ if windows_site.is_dir():
+ return [windows_site]
+
+ try:
+ config = (root / "pyvenv.cfg").read_text(encoding = "utf-8", errors = "replace")
+ except OSError:
+ config = ""
+ match = re.search(r"(?im)^\s*version\s*=\s*(\d+\.\d+)", config)
+ if match:
+ versioned = root / "lib" / f"python{match.group(1)}" / "site-packages"
+ if versioned.is_dir():
+ return [versioned]
+
+ # Test fixtures and incomplete venvs may not have a runnable interpreter or
+ # version entry yet. One directory is unambiguous; several are not.
+ candidates = sorted(root.glob("lib/python*/site-packages"))
+ return candidates if len(candidates) == 1 else []
def _managed_root(extra_roots: Sequence[Path]) -> Optional[Path]:
@@ -128,11 +212,13 @@ def _managed_root(extra_roots: Sequence[Path]) -> Optional[Path]:
return None
-def _distributions_in(root: Path) -> Optional[Dict[str, str]]:
- """Canonical distribution name -> version inside another venv.
+def _distributions_in(root: Path) -> Optional[tuple[Dict[str, str], set[str]]]:
+ """Installed versions and metadata conflicts inside another venv.
importlib.metadata reports the running interpreter only, so a foreign
- site-packages has to be handed to the finder explicitly.
+ site-packages has to be handed to the finder explicitly. Keep multiplicity
+ beside the single-version map: collapsing it here would let a foreign venv
+ with ambiguous core metadata pass manifest verification.
"""
paths = [str(path) for path in _venv_site_packages(root)]
if not paths:
@@ -140,14 +226,31 @@ def _distributions_in(root: Path) -> Optional[Dict[str, str]]:
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"]
+ conflicts: set[str] = set()
+ for dist in Distribution.discover(context = DistributionFinder.Context(path = paths)):
+ path = getattr(dist, "_path", None)
+ stem = os.path.basename(os.fspath(path)) if path is not None else ""
+ try:
+ name = dist.metadata.get("Name")
if name:
- found.setdefault(_canonical(name), dist.version or "")
- except Exception:
- return None
- return found
+ canonical = _canonical(name)
+ version = dist.version or ""
+ # pip renames the outgoing record to a `~` sibling while it lays
+ # the replacement down, so a kill there can leave the backup as
+ # the only record. It reads as one healthy version, but pip calls
+ # it an invalid distribution and the payload is renamed with it.
+ if not version or canonical in found or stem.startswith("~"):
+ conflicts.add(canonical)
+ if canonical not in found:
+ found[canonical] = version
+ continue
+ except Exception:
+ pass
+ # A nameless or unreadable record must not hide a foreign conflict.
+ path_name, separator, _version = stem.removesuffix(".dist-info").rpartition("-")
+ if stem.endswith(".dist-info") and separator:
+ conflicts.add(_canonical(path_name))
+ return found, conflicts
def _requirements_root_in(root: Path) -> Optional[Path]:
@@ -155,13 +258,38 @@ def _requirements_root_in(root: Path) -> Optional[Path]:
reqs = path / "studio" / "backend" / "requirements"
if reqs.is_dir():
return reqs
+ # An editable install can keep studio/ only in its source checkout. Ask the
+ # foreign interpreter to follow its .pth/finder instead of treating the
+ # absent site-packages copy as an incomplete environment.
+ probe = (
+ "import json, pathlib, studio; "
+ "print(json.dumps(str(pathlib.Path(studio.__file__).resolve().parent / "
+ "'backend' / 'requirements')))"
+ )
+ for executable in _venv_executables(root):
+ if not executable.is_file():
+ continue
+ try:
+ reqs = Path(
+ json.loads(
+ subprocess.check_output(
+ [str(executable), "-I", "-c", probe],
+ stderr = subprocess.DEVNULL,
+ text = True,
+ timeout = 5,
+ )
+ )
+ )
+ except (OSError, subprocess.SubprocessError, TypeError, ValueError, json.JSONDecodeError):
+ continue
+ 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."""
+def _verify_install_supports(module, parameter: str) -> bool:
try:
- return "installed" in inspect.signature(module.verify_install).parameters
+ return parameter in inspect.signature(module.verify_install).parameters
except (TypeError, ValueError):
return False
@@ -188,12 +316,32 @@ def install_state(extra_roots: Sequence[Path] = ()) -> dict:
# 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
+ foreign_distributions = _distributions_in(root) if foreign else None
+ installed = foreign_distributions[0] if foreign_distributions is not None else None
+ installed_conflicts = foreign_distributions[1] if foreign_distributions is not None else set()
req_root = _requirements_root_in(root) if foreign else None
+ if foreign and (foreign_distributions is None or req_root is None):
+ # Never answer for the caller when the requested environment cannot be
+ # inspected. That can turn a torn or ambiguous managed venv into a
+ # healthy result merely because the external CLI has matching packages.
+ return {
+ "ok": False,
+ "manifest_ok": False,
+ "deps_ok": False,
+ "missing": [],
+ "reason": "studio_install_incomplete",
+ }
try:
- if installed is not None and req_root is not None and _supports_foreign_root(module):
+ if (
+ installed is not None
+ and req_root is not None
+ and _verify_install_supports(module, "installed")
+ ):
# That venv's own metadata: unreadable through this interpreter.
- return module.verify_install(root = root, req_root = req_root, installed = installed)
+ kwargs = {"root": root, "req_root": req_root, "installed": installed}
+ if _verify_install_supports(module, "installed_conflicts"):
+ kwargs["installed_conflicts"] = installed_conflicts
+ return module.verify_install(**kwargs)
state = module.verify_install(root = root)
if foreign and not state["deps_ok"]:
# The manifest came from another venv but the dependency walk ran
@@ -217,18 +365,30 @@ def _scan_paths() -> Dict[str, list]:
Empty when the interpreter's site-packages cannot be resolved, which leaves
the scan at its default of the whole sys.path: over-scanning is the safe
- direction here, since the alternative is looking at nothing.
+ direction here, since the alternative is looking at nothing. Deduplicated
+ by real path, because purelib hardcodes `lib` while platlib follows
+ sys.platlibdir, so a lib64 build (Fedora, SuSE) names one directory twice
+ and scanning both reports every package as duplicated.
"""
import sysconfig
paths = []
+ seen: set = set()
for key in ("purelib", "platlib"):
try:
entry = sysconfig.get_paths().get(key)
except Exception:
continue
- if entry and entry not in paths and os.path.isdir(entry):
- paths.append(entry)
+ if not entry or not os.path.isdir(entry):
+ continue
+ try:
+ resolved = os.path.realpath(entry)
+ except OSError:
+ resolved = entry
+ if resolved in seen:
+ continue
+ seen.add(resolved)
+ paths.append(entry)
return {"path": paths} if paths else {}
@@ -287,86 +447,169 @@ def _installer_rewritten(rel: str) -> bool:
return rel.replace("\\", "/").rsplit("/", 1)[-1] in _INSTALLER_REWRITTEN_NAMES
+def _installed_distribution_groups():
+ """Canonical name -> installed metadata records in this interpreter's tree.
+
+ Each record is (distribution, display name, readable). A nameless or
+ unreadable METADATA still belongs to the distribution its directory is
+ named after, and still makes it ambiguous, which is what
+ install_manifest.installed_versions() reports for the same directory.
+ Readable means a name AND a version, since metadata_conflict() counts an
+ empty version as inconsistent: trusting such a record would leave the two
+ checks disagreeing about one directory.
+ """
+ from importlib.metadata import distributions
+
+ groups: Dict[str, list] = {}
+ for dist in distributions(**_scan_paths()):
+ try:
+ name = dist.metadata.get("Name")
+ except Exception:
+ name = None
+ if name:
+ try:
+ version = dist.version
+ except Exception:
+ version = None
+ groups.setdefault(_canonical(name), []).append((dist, name, bool(version)))
+ continue
+ # Wheel metadata directory names escape name separators as underscores,
+ # so splitting off the final version is unambiguous.
+ path = getattr(dist, "_path", None)
+ stem = os.path.basename(os.fspath(path)) if path is not None else ""
+ path_name, separator, _version = stem.removesuffix(".dist-info").rpartition("-")
+ if stem.endswith(".dist-info") and separator and path_name:
+ groups.setdefault(_canonical(path_name), []).append((dist, path_name, False))
+ return groups
+
+
+def installed_metadata_conflicts(
+ limit: int = 8,
+ *,
+ names: Optional[Sequence[str]] = None,
+ exclude_names: Sequence[str] = (),
+) -> List[str]:
+ """Distributions with multiple metadata records for one canonical name.
+
+ A duplicate is an ambiguous install, even when both records name the same
+ version: importlib.metadata.version() takes the first finder result rather
+ than identifying which RECORD owns the package tree, so none can drive the
+ file-damage check until the package is reinstalled. A single unreadable
+ record counts too, matching install_manifest.metadata_conflict(): pip
+ cannot parse it either, so it must be reported rather than skipped.
+ """
+ included = None if names is None else {_canonical(name) for name in names}
+ excluded = {_canonical(name) for name in exclude_names}
+ found: List[str] = []
+ groups = _installed_distribution_groups()
+ for canonical in sorted(groups):
+ if (included is not None and canonical not in included) or canonical in excluded:
+ continue
+ records = groups[canonical]
+ if len(records) < 2 and all(readable for _dist, _name, readable in records):
+ continue
+ details: List[str] = []
+ for dist, _name, _readable in records:
+ try:
+ version = dist.version or "unknown version"
+ except Exception:
+ version = "unknown version"
+ metadata_path = getattr(dist, "_path", None)
+ location = Path(str(metadata_path)).name if metadata_path else "unknown metadata path"
+ details.append(f"{version} at {location}")
+ detail = ", ".join(sorted(details))
+ problem = "multiple metadata records" if len(records) > 1 else "unreadable metadata"
+ found.append(f"{canonical}: {problem} ({detail})")
+ if len(found) >= limit:
+ break
+ return found
+
+
def damaged_installed_files(limit: int = 8) -> List[str]:
"""Installed files that are gone, or shorter than pip recorded.
- pip treats a distribution with intact metadata as already satisfied, so an
- update reinstalls nothing when a package's FILES are damaged: it reports
- success and the backend then dies on import at boot. A missing-package check
- cannot see this, because the damaged module still imports; the observed
- failure was `cannot import name 'Depends' from 'fastapi'`, not a missing
- fastapi. Comparing each RECORD entry against the filesystem does see it, and
- since nothing is imported it costs well under a second even with torch
- installed.
+ pip treats intact metadata as already satisfied, so an update reinstalls
+ nothing when a package's FILES are damaged: it reports success and the
+ backend dies on import at boot. A missing-package check cannot see this,
+ since the damaged module still imports; the observed failure was `cannot
+ import name 'Depends' from 'fastapi'`. Comparing RECORD against the
+ filesystem does see it, and imports nothing, so it costs under a second.
Only shrinkage and disappearance count, and only for paths a single
distribution claims. When two claim one path (descript-audio-codec ships a
top-level tests/__init__.py that another package overwrites) whichever copy
- landed is the one on disk, so its size says nothing about either RECORD --
- in EITHER direction. Sizes are therefore compared after the whole scan, once
- multiply-owned paths are known, rather than during it.
+ landed is the one on disk, so its size says nothing about either RECORD, in
+ EITHER direction. Sizes are therefore compared after the scan, once
+ multiply-owned paths are known.
Rows that cannot be import-time damage are dropped up front, and a file our
- own setup rewrites keeps its existence check but loses its size. The answer
+ own setup rewrites keeps its existence check but loses its size: the answer
to a finding is "reinstall over the top", so a file no reinstall would
change must not produce one. See _shared_non_runtime, _installer_rewritten.
- Scanned over the interpreter's own site-packages rather than all of
- sys.path. distributions() searches every sys.path entry, so a damaged
- distribution reachable only through an inherited PYTHONPATH would otherwise
- fail every update while sitting outside the installation, where neither
- printed repair command can reach it.
+ Multiple records for one canonical name are excluded entirely, none being
+ authoritative: an older RECORD can legitimately name files a newer wheel
+ removed, while picking the first or highest also fails after an interrupted
+ upgrade or a downgrade. Callers surface that through
+ installed_metadata_conflicts().
- RECORD is parsed here rather than read through Distribution.files, which
- drops entries whose file no longer exists and so can never report a deletion.
+ Scanned over this interpreter's own site-packages, not all of sys.path: a
+ damaged distribution reachable only through an inherited PYTHONPATH would
+ otherwise fail every update from outside the installation, where neither
+ printed repair command reaches. RECORD is parsed directly rather than read
+ through Distribution.files, which drops entries whose file is gone and so
+ can never report a deletion.
Describes this interpreter's environment. Callers that may be running
outside the managed venv should check first; see install_state().
"""
import csv
import io
- from importlib.metadata import distributions
entries: List[tuple] = []
owners: Dict[str, int] = {}
- for dist in distributions(**_scan_paths()):
- try:
- name = dist.metadata["Name"] or "?"
- record = dist.read_text("RECORD")
- except Exception:
- # An unreadable or absent RECORD says nothing about damage: editable
- # installs and system packages legitimately have none.
- continue
- if not record:
- continue
- for row in csv.reader(io.StringIO(record)):
- rel = row[0] if row else ""
- # A trailing slash is a directory entry, which has nothing to check.
- if not rel or rel.endswith("/"):
- continue
- # Installer-owned metadata is rewritten in place and drifts from the
- # size recorded inside itself; .pyc is regenerated from source.
- if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):
- continue
+ for records in _installed_distribution_groups().values():
+ # An unreadable record cannot be trusted to describe the package tree
+ # any more than a duplicated one can.
+ ambiguous = len(records) > 1 or not all(readable for _dist, _name, readable in records)
+ for dist, name, _readable in records:
try:
- target = dist.locate_file(rel)
+ record = dist.read_text("RECORD")
except Exception:
+ # An unreadable or absent RECORD says nothing about damage: editable
+ # installs and system packages legitimately have none.
continue
- key = os.path.normcase(str(target))
- # Before the filter: a dropped row still owns the path it claims.
- owners[key] = owners.get(key, 0) + 1
- if _shared_non_runtime(rel):
+ if not record:
continue
- # The size field is optional and real wheels do leave it blank. Keep
- # the row anyway with an unknown size: existence is still checkable,
- # and dropping the row meant a deletion went unreported.
- recorded: Optional[int] = None
- if len(row) >= 3 and row[2] and not _installer_rewritten(rel):
+ for row in csv.reader(io.StringIO(record)):
+ rel = row[0] if row else ""
+ # A trailing slash is a directory entry, which has nothing to check.
+ if not rel or rel.endswith("/"):
+ continue
+ # Installer-owned metadata is rewritten in place and drifts from the
+ # size recorded inside itself; .pyc is regenerated from source.
+ if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):
+ continue
try:
- recorded = int(row[2])
- except ValueError:
- recorded = None
- entries.append((name, rel, recorded, target, key))
+ target = dist.locate_file(rel)
+ except Exception:
+ continue
+ key = os.path.normcase(str(target))
+ # Before either filter: a row we cannot verify still owns the path
+ # it claims, so another distribution's size is ambiguous too.
+ owners[key] = owners.get(key, 0) + 1
+ if ambiguous or _shared_non_runtime(rel):
+ continue
+ # The size field is optional and real wheels do leave it blank. Keep
+ # the row anyway with an unknown size: existence is still checkable,
+ # and dropping the row meant a deletion went unreported.
+ recorded: Optional[int] = None
+ if len(row) >= 3 and row[2] and not _installer_rewritten(rel):
+ try:
+ recorded = int(row[2])
+ except ValueError:
+ recorded = None
+ entries.append((name, rel, recorded, target, key))
found: List[str] = []
for name, rel, recorded, target, key in entries:
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 82347b2399a..a4387482e2f 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -3883,10 +3883,15 @@ def setup(
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
_studio_runtime_gate.ensure_managed_environment_is_idle(STUDIO_HOME)
- _run_setup_script(verbose = verbose)
+ # Duplicate-metadata repair can reinstall unsloth even when the
+ # installer set SKIP_STUDIO_BASE. Free and preserve the running Windows
+ # launcher exactly as the direct update path does.
+ with _WindowsLauncherUpdateTransaction() as launcher_update:
+ _run_setup_script(verbose = verbose)
+ launcher_update.validate_launcher()
-def _fail_if_install_damaged() -> None:
+def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
"""Refuse to call an update successful when the tree it produced is damaged.
pip considers a distribution with intact metadata already satisfied, so an
@@ -3899,6 +3904,36 @@ def _fail_if_install_damaged() -> None:
# This CLI does not live in the venv the update just wrote, so its own
# file list describes the wrong tree. Silence beats a wrong answer.
return
+ managed_names = (package_name, "unsloth-zoo")
+ managed_conflicts = _studio_deps.installed_metadata_conflicts(names = managed_names)
+ if managed_conflicts:
+ typer.echo("", err = True)
+ typer.echo("Update finished, but Studio package metadata is inconsistent:", err = True)
+ for entry in managed_conflicts:
+ typer.echo(f" {entry}", err = True)
+ typer.echo("", err = True)
+ typer.echo("The file check cannot safely choose between these records.", err = True)
+ typer.echo("The installer could not repair its managed package metadata.", err = True)
+ typer.echo(
+ "Recreate the managed environment before running the Studio installer again.", err = True
+ )
+ typer.echo("", err = True)
+ typer.echo(
+ "To update anyway without this check: unsloth studio update --no-verify", err = True
+ )
+ raise typer.Exit(code = 1)
+ other_conflicts = _studio_deps.installed_metadata_conflicts(exclude_names = managed_names)
+ if other_conflicts:
+ typer.echo("", err = True)
+ typer.echo("Warning: some other packages have duplicate metadata:", err = True)
+ for entry in other_conflicts:
+ typer.echo(f" {entry}", err = True)
+ typer.echo("", err = True)
+ typer.echo("Studio skipped file verification for these packages.", err = True)
+ typer.echo(
+ "Reinstall the intended version from its original package source, or use a clean environment.",
+ err = True,
+ )
damaged = _studio_deps.damaged_installed_files()
if not damaged:
return
@@ -4065,7 +4100,7 @@ def update(
# is optional, but a successful update must leave its own launcher usable.
launcher_update.validate_launcher()
if verify:
- _fail_if_install_damaged()
+ _fail_if_install_damaged(package)
# Tauri desktop owns its own bundle entries; skip CLI launcher refresh
# so a Tauri-initiated update doesn't create duplicate shortcuts.
if os.environ.get("UNSLOTH_TAURI_UPDATE") == "1":
diff --git a/unsloth_cli/tests/test_studio_update_verify.py b/unsloth_cli/tests/test_studio_update_verify.py
index a6953c614b2..2f67019f961 100644
--- a/unsloth_cli/tests/test_studio_update_verify.py
+++ b/unsloth_cli/tests/test_studio_update_verify.py
@@ -46,17 +46,21 @@ def _make_dist(
name: str,
files: dict[str, bytes],
record_sizes = None,
+ version: str = "1.0",
):
"""Install `files` under `site` and write a dist-info RECORD describing them.
`record_sizes` overrides the size RECORD claims, which is how damage is
simulated without having to corrupt anything after the fact.
"""
- info = site / f"{name}-1.0.dist-info"
+ info = site / f"{name}-{version}.dist-info"
info.mkdir(parents = True, exist_ok = True)
- (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n")
+ (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n")
(info / "WHEEL").write_text("Wheel-Version: 1.0\n")
- rows = [f"{name}-1.0.dist-info/METADATA,,", f"{name}-1.0.dist-info/RECORD,,"]
+ rows = [
+ f"{name}-{version}.dist-info/METADATA,,",
+ f"{name}-{version}.dist-info/RECORD,,",
+ ]
for rel, body in files.items():
target = site / rel
target.parent.mkdir(parents = True, exist_ok = True)
@@ -90,6 +94,59 @@ def test_an_intact_install_reports_nothing(site):
assert _deps().damaged_installed_files() == []
+def test_superseded_metadata_is_not_treated_as_file_damage(site):
+ removed = "studio/frontend/dist/assets/removed-hash.js"
+ _make_dist(site, "unsloth", {removed: b"old\n"}, version = "1.0")
+ _make_dist(site, "unsloth", {"unsloth/__init__.py": b"new\n"}, version = "2.0")
+ (site / removed).unlink()
+
+ assert _deps().damaged_installed_files() == []
+ conflicts = _deps().installed_metadata_conflicts()
+ assert len(conflicts) == 1
+ assert "unsloth" in conflicts[0]
+ assert "1.0" in conflicts[0] and "2.0" in conflicts[0]
+
+
+def test_duplicate_metadata_names_are_canonicalized(site):
+ _make_dist(site, "foo_bar", {"foo_bar/old.py": b"old\n"}, version = "1.0")
+ info = site / "foo_bar-1.0.dist-info"
+ (info / "METADATA").write_text("Metadata-Version: 2.1\nName: foo.bar\nVersion: 1.0\n")
+ _make_dist(site, "foo_bar", {"foo_bar/new.py": b"new\n"}, version = "2.0")
+ info = site / "foo_bar-2.0.dist-info"
+ (info / "METADATA").write_text("Metadata-Version: 2.1\nName: foo-bar\nVersion: 2.0\n")
+
+ conflicts = _deps().installed_metadata_conflicts()
+ assert len(conflicts) == 1 and conflicts[0].startswith("foo-bar:")
+
+
+def test_duplicate_metadata_conflicts_can_be_scoped_by_canonical_name(site):
+ _make_dist(site, "unsloth", {"unsloth/old.py": b"old\n"}, version = "1.0")
+ _make_dist(site, "unsloth", {"unsloth/new.py": b"new\n"}, version = "2.0")
+ _make_dist(site, "foo_bar", {"foo_bar/old.py": b"old\n"}, version = "1.0")
+ _make_dist(site, "foo_bar", {"foo_bar/new.py": b"new\n"}, version = "2.0")
+
+ deps = _deps()
+ included = deps.installed_metadata_conflicts(names = ("foo.bar",))
+ excluded = deps.installed_metadata_conflicts(exclude_names = ("foo-bar",))
+
+ assert len(included) == 1 and included[0].startswith("foo-bar:")
+ assert len(excluded) == 1 and excluded[0].startswith("unsloth:")
+
+
+def test_duplicate_metadata_does_not_hide_another_packages_damage(site):
+ _make_dist(site, "unsloth", {"studio/old.py": b"old\n"}, version = "1.0")
+ _make_dist(site, "unsloth", {"unsloth/__init__.py": b"new\n"}, version = "2.0")
+ _make_dist(
+ site,
+ "fastapi",
+ {"fastapi/__init__.py": b""},
+ record_sizes = {"fastapi/__init__.py": 1081},
+ )
+
+ found = _deps().damaged_installed_files()
+ assert len(found) == 1 and "fastapi/__init__.py" in found[0]
+
+
def test_a_truncated_file_is_reported(site):
# The observed failure: fastapi/__init__.py emptied, metadata untouched.
_make_dist(
@@ -275,6 +332,69 @@ def test_a_clean_tree_passes_through(monkeypatch):
studio._fail_if_install_damaged() # must not raise
+def test_duplicate_metadata_gets_its_own_actionable_failure(monkeypatch, capsys):
+ import typer
+
+ studio = _studio()
+ monkeypatch.setattr(studio._studio_deps, "running_outside_managed_venv", lambda *a: False)
+ monkeypatch.setattr(
+ studio._studio_deps,
+ "installed_metadata_conflicts",
+ lambda *a, **k: [
+ "unsloth: multiple metadata records "
+ "(2026.8.12 at unsloth-2026.8.12.dist-info, "
+ "2026.8.15 at unsloth-2026.8.15.dist-info)"
+ ],
+ )
+
+ def _file_scan_must_not_run(*_args, **_kwargs):
+ raise AssertionError("ambiguous RECORDs reached the file-damage scan")
+
+ monkeypatch.setattr(studio._studio_deps, "damaged_installed_files", _file_scan_must_not_run)
+ with pytest.raises(typer.Exit) as excinfo:
+ studio._fail_if_install_damaged()
+
+ assert excinfo.value.exit_code == 1
+ err = capsys.readouterr().err
+ assert "Studio package metadata is inconsistent" in err
+ assert "cannot safely choose" in err
+ assert "Recreate the managed environment before" in err
+ assert "pip install" not in err
+ assert "installed files are damaged" not in err
+ assert "Studio will keep failing to start" not in err
+
+
[email protected]("package", ["typer", "torch"])
+def test_other_duplicate_metadata_warns_without_an_unsafe_command(monkeypatch, capsys, package):
+ studio = _studio()
+ monkeypatch.setattr(studio._studio_deps, "running_outside_managed_venv", lambda *a: False)
+
+ def conflicts(
+ *_args,
+ names = None,
+ exclude_names = (),
+ ):
+ if names is not None:
+ return []
+ assert "unsloth" in exclude_names and "unsloth-zoo" in exclude_names
+ return [
+ f"{package}: multiple metadata records "
+ f"(1.0 at {package}-1.0.dist-info, 2.0 at {package}-2.0.dist-info)"
+ ]
+
+ monkeypatch.setattr(studio._studio_deps, "installed_metadata_conflicts", conflicts)
+ monkeypatch.setattr(studio._studio_deps, "damaged_installed_files", lambda: [])
+
+ studio._fail_if_install_damaged()
+
+ err = capsys.readouterr().err
+ assert "Warning: some other packages have duplicate metadata" in err
+ assert f"{package}: multiple metadata records" in err
+ assert "skipped file verification" in err
+ assert "original package source" in err
+ assert "pip install" not in err
+
+
def test_a_damaged_tree_exits_nonzero_and_names_the_files(monkeypatch, capsys):
import typer
@@ -383,7 +503,9 @@ def _run_update(monkeypatch, argv, verified):
monkeypatch.setattr(studio, "_WindowsLauncherUpdateTransaction", _NoopLauncherUpdate)
monkeypatch.setattr(studio, "_run_setup_script", lambda *a, **k: None)
monkeypatch.setattr(studio, "_refresh_desktop_shortcuts", lambda *a, **k: None)
- monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda: verified.append(True))
+ monkeypatch.setattr(
+ studio, "_fail_if_install_damaged", lambda package: verified.append(package)
+ )
return CliRunner().invoke(studio.studio_app, ["update", *argv])
@@ -391,7 +513,7 @@ def test_update_verifies_by_default(monkeypatch):
verified = []
result = _run_update(monkeypatch, [], verified)
assert result.exit_code == 0, result.output
- assert verified == [True]
+ assert verified == ["unsloth"]
def test_no_verify_skips_the_check(monkeypatch):
@@ -409,7 +531,7 @@ def test_a_tauri_update_is_verified_too(monkeypatch):
monkeypatch.setenv("UNSLOTH_TAURI_UPDATE", "1")
result = _run_update(monkeypatch, [], verified)
assert result.exit_code == 0, result.output
- assert verified == [True]
+ assert verified == ["unsloth"]
@pytest.mark.parametrize(