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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: skip dependency-pass steps whose evidence holds, and keep that evidence on Windows (#10649)
Daniel Hanc38bb137172b
diff --git a/studio/backend/tests/test_transformers_version_optional_tiktoken.py b/studio/backend/tests/test_transformers_version_optional_tiktoken.pynew file mode 100644index 00000000000..8eb56680c29--- /dev/null+++ b/studio/backend/tests/test_transformers_version_optional_tiktoken.py@@ -0,0 +1,586 @@+# Unsloth Zoo - Utilities for Unsloth+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published+# by the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""The runtime's idea of a complete sidecar matches setup's.++setup.sh and setup.ps1 install tiktoken best-effort and record a sidecar without it as+complete; the runtime validator used to require it, delete the sidecar and retry the+install that had just failed.+"""++import pathlib+import shutil+import sys+import types as _types+import os+from pathlib import Path++# The backend uses "from utils..." imports; ensure the backend dir is on sys.path.+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# Stub the custom logger before importing the module under test, as the sibling tests do.+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import utils.transformers_version as tv+++def _sidecar(+ root,+ *names,+ versions = None,+):+ versions = versions or {}+ for name in names:+ (root / name).mkdir(parents = True)+ version = versions.get(name)+ if version:+ info = root / f"{name}-{version}.dist-info"+ info.mkdir()+ (info / "METADATA").write_text(f"Name: {name}\nVersion: {version}\n", encoding = "utf-8")+ (root / tv._STUDIO_OWNED_MARKER).touch()+++def test_a_failed_optional_install_leaves_no_partial_payload(tmp_path, monkeypatch):+ """pip or uv exiting nonzero after copying part of tiktoken: the sidecar is still+ accepted (the package is optional), but nothing of the package may stay, or the+ half-copied tree ahead of site-packages shadows the ambient one at tokenization."""+ root = tmp_path / ".venv_t5_550"+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)+ optional = [p for p in tv._VENV_T5_550_PACKAGES if p.startswith("tiktoken")]+ assert optional and tv._sidecar_package_is_optional(optional[0])++ def fake_install(pkg, target):+ if pkg.startswith("tiktoken"):+ (Path(target) / "tiktoken").mkdir()+ (Path(target) / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ (Path(target) / "tiktoken_ext").mkdir()+ (Path(target) / "tiktoken_ext" / "openai_public.py").write_text("", encoding = "utf-8")+ (Path(target) / "tiktoken-0.9.0.dist-info").mkdir()+ (Path(target) / "tiktoken-0.9.0.dist-info" / "METADATA").write_text(+ "", encoding = "utf-8"+ )+ return False+ return True++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert not (root / "tiktoken").exists()+ # The plugin namespace too: a partial tiktoken_ext shadows the ambient openai_public module.+ assert not (root / "tiktoken_ext").exists()+ assert not list(root.glob("tiktoken-*.dist-info"))+ assert tv._optional_package_absent(str(root), "tiktoken") is True+++def test_a_staging_move_that_fails_part_way_rolls_the_moved_entries_back(tmp_path, monkeypatch):+ """os.replace failing on the second entry used to leave the first one in the sidecar+ with no dist-info for the whole retry backoff; the package must read as absent."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()++ def fake_install(pkg, target):+ (Path(target) / "tiktoken").mkdir()+ (Path(target) / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ (Path(target) / "tiktoken_ext").mkdir()+ (Path(target) / "tiktoken_ext" / "openai_public.py").write_text("", encoding = "utf-8")+ (Path(target) / "tiktoken-0.9.0.dist-info").mkdir()+ (Path(target) / "tiktoken-0.9.0.dist-info" / "RECORD").write_text("", encoding = "utf-8")+ return True++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ real_replace = tv.os.replace+ moved = []++ def flaky_replace(source, target):+ if ".top-up-staging" in str(source) and len(moved) == 1:+ raise OSError("disk full")+ moved.append(target)+ return real_replace(source, target)++ monkeypatch.setattr(tv.os, "replace", flaky_replace)+ assert tv._stage_optional_package("tiktoken", str(root)) is False+ assert len(moved) == 1+ assert not (root / "tiktoken").exists()+ assert not (root / "tiktoken_ext").exists()+ assert not list(root.glob("tiktoken-*.dist-info"))+ assert not (root / ".top-up-staging").exists()+ assert tv._optional_package_absent(str(root), "tiktoken") is True+++def test_a_sidecar_without_tiktoken_is_still_valid(tmp_path):+ root = tmp_path / ".venv_t5_550"+ _sidecar(+ root,+ "transformers",+ "huggingface_hub",+ "hf_xet",+ versions = {+ "transformers": tv.TRANSFORMERS_550_VERSION,+ "huggingface_hub": "1.8.0",+ "hf_xet": "1.4.2",+ },+ )+ assert tv._venv_dir_is_valid(str(root), tv._VENV_T5_550_PACKAGES) is True+ assert (+ tv._venv_dir_is_valid(str(root), tv._venv_t5_latest_packages(tv.TRANSFORMERS_550_VERSION))+ is True+ )+++def test_a_sidecar_without_a_required_package_is_still_invalid(tmp_path):+ root = tmp_path / ".venv_t5_550"+ _sidecar(+ root,+ "transformers",+ "huggingface_hub",+ "tiktoken",+ versions = {"transformers": tv.TRANSFORMERS_550_VERSION, "huggingface_hub": "1.8.0"},+ )+ assert tv._venv_dir_is_valid(str(root), tv._VENV_T5_550_PACKAGES) is False+++def test_a_runtime_repair_survives_a_tiktoken_that_will_not_install(tmp_path, monkeypatch):+ root = tmp_path / ".venv_t5_550"+ installed = []++ def fake_install(pkg, target_dir):+ installed.append(pkg)+ return not pkg.startswith("tiktoken")++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert installed == list(tv._VENV_T5_550_PACKAGES)++ def fake_install_failing_required(pkg, target_dir):+ return not pkg.startswith("hf_xet")++ monkeypatch.setattr(tv, "_install_to_dir", fake_install_failing_required)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False+++def test_a_rebuild_records_the_optional_install_it_could_not_do(tmp_path, monkeypatch):+ """The sidecar reads as valid from here on, so the next activation runs the top-up. Left+ unrecorded, the outage that just failed this install would be met again by that top-up and+ by every worker a job spawns, each sitting through the same doomed network retries."""+ root = tmp_path / ".venv_t5_550"+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: not pkg.startswith("tiktoken"))+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()++ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True++ optional = next(p for p in tv._VENV_T5_550_PACKAGES if p.startswith("tiktoken"))+ assert tv._top_up_failed_recently(str(root), optional) is True+ assert (os.path.normcase(os.path.abspath(str(root))), optional) in tv._OPTIONAL_TOP_UP_ATTEMPTED+ # A later attempt that succeeds clears it again.+ tv._record_top_up_outcome(str(root), optional, True)+ assert tv._top_up_failed_recently(str(root), optional) is False+++def test_a_remnant_that_will_not_go_fails_the_build_instead_of_shadowing(tmp_path, monkeypatch):+ """The optional install failed part-way and left tiktoken/ behind, and the cleanup+ cannot remove it (a file another process holds open on Windows, a permission). That+ directory sits ahead of site-packages, so the build is a failure to be redone, not a+ sidecar without the package."""+ root = tmp_path / ".venv_t5_550"++ def fake_install(pkg, target_dir):+ if pkg.startswith("tiktoken"):+ (Path(target_dir) / "tiktoken").mkdir(parents = True, exist_ok = True)+ (Path(target_dir) / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ return False+ return True++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: False)+ real_rmtree = tv.shutil.rmtree++ def stuck_rmtree(path, *a, **k):+ if Path(path).name == "tiktoken":+ return None+ return real_rmtree(path, *a, **k)++ monkeypatch.setattr(tv.shutil, "rmtree", stuck_rmtree)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False+ assert (root / "tiktoken").is_dir()+ monkeypatch.setattr(tv.shutil, "rmtree", real_rmtree)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert not (root / "tiktoken").exists()+ assert tv._remove_optional_remnants(str(root), "tiktoken==0.12.0") is True+++def test_a_present_tiktoken_is_held_to_its_record_like_any_other(tmp_path, monkeypatch):+ """Absence is what is optional. A tiktoken that is present but whose RECORD names a+ file that is not there (an interrupted install, a native extension left from an+ older interpreter) is a tokenizer that fails at import, and the scan says so."""+ root = tmp_path / ".venv_t5_550"+ _sidecar(+ root,+ "transformers",+ "huggingface_hub",+ "hf_xet",+ versions = {+ "transformers": tv.TRANSFORMERS_550_VERSION,+ "huggingface_hub": "1.8.0",+ "hf_xet": "1.4.2",+ },+ )+ (root / "transformers" / "__init__.py").write_text("", encoding = "utf-8")+ info = root / "tiktoken-0.9.0.dist-info"+ info.mkdir()+ (info / "METADATA").write_text("Name: tiktoken\nVersion: 0.9.0\n", encoding = "utf-8")+ (info / "RECORD").write_text("tiktoken/__init__.py,sha256=abc,1234\n", encoding = "utf-8")+ monkeypatch.delenv(tv._SIDECAR_FILE_CHECK_ENV, raising = False)+ assert tv._sidecar_damaged_files(str(root)) != []+ assert tv._venv_dir_is_valid_and_undamaged(str(root), tv._VENV_T5_550_PACKAGES) is False+ # With the payload the RECORD names in place, the sidecar is whole.+ (root / "tiktoken").mkdir()+ (root / "tiktoken" / "__init__.py").write_bytes(b"x" * 1234)+ assert tv._sidecar_damaged_files(str(root)) == []+ assert tv._venv_dir_is_valid_and_undamaged(str(root), tv._VENV_T5_550_PACKAGES) is True+ # A required package's RECORD is held to the disk too.+ hub = root / "huggingface_hub-1.8.0.dist-info"+ (hub / "RECORD").write_text("huggingface_hub/gone.py,sha256=abc,12\n", encoding = "utf-8")+ assert tv._sidecar_damaged_files(str(root)) != []+++def test_a_valid_sidecar_missing_tiktoken_is_topped_up_once(tmp_path, monkeypatch):+ """A transient failure while a sidecar was built (the latest sidecar in particular,+ which no setup top-up visits) left tiktoken out for good: every later check accepted+ the sidecar and returned before another install. The top-up adds it without touching+ the rest, and asks once per process when the wheel is unavailable."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: True)+ installed: list[tuple[str, str]] = []+ monkeypatch.setattr(+ tv, "_install_to_dir", lambda pkg, target: installed.append((pkg, target)) or False+ )+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert installed == [("tiktoken", str(root / ".top-up-staging"))]+ assert root.is_dir(), "the top-up must not wipe the sidecar"+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert len(installed) == 1, "an unavailable wheel is asked for once per process"+ # A tiktoken that is there is left alone.+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ (root / tv._OPTIONAL_TOP_UP_FAILED).unlink()+ (root / "tiktoken").mkdir()+ (root / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ (root / "tiktoken-0.9.0.dist-info").mkdir()+ (root / "tiktoken-0.9.0.dist-info" / "RECORD").write_text("", encoding = "utf-8")+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert len(installed) == 1+++def test_a_failed_top_up_is_remembered_across_processes_and_retried_later(tmp_path, monkeypatch):+ """Each job spawns its own workers, and every one of them used to run the same+ doomed install: the failure is written beside the sidecar, read by the next process,+ and forgotten after a while in case it was the network."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ packages = tv._VENV_T5_550_PACKAGES+ installed = []+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or False)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert installed == ["tiktoken"]+ # A fresh process: the in-memory set is empty, the file is not.+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert installed == ["tiktoken"]+ # Old enough to try again.+ failures = tv._read_top_up_failures(str(root))+ failures["tiktoken"] -= tv._OPTIONAL_TOP_UP_RETRY_SECONDS + 1+ tv._write_top_up_failures(str(root), failures)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert installed == ["tiktoken", "tiktoken"]+ # A success clears the record.+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)+ failures = tv._read_top_up_failures(str(root))+ failures["tiktoken"] -= tv._OPTIONAL_TOP_UP_RETRY_SECONDS + 1+ tv._write_top_up_failures(str(root), failures)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert not (root / tv._OPTIONAL_TOP_UP_FAILED).exists()+++def test_a_partial_live_tree_goes_when_the_top_up_install_itself_fails(tmp_path, monkeypatch):+ """An earlier top-up moved tiktoken/ in and was interrupted before its dist-info; the+ next one finds the package "absent", and its install fails (no network). The partial+ payload must not stay ahead of site-packages for the six-hour backoff."""+ root = tmp_path / ".venv_t5_550"+ (root / "tiktoken").mkdir(parents = True)+ (root / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ (root / "tiktoken_ext").mkdir()+ (root / "tiktoken_ext" / "openai_public.py").write_text("", encoding = "utf-8")+ assert tv._optional_package_absent(str(root), "tiktoken==0.12.0") is True+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target_dir: False)+ assert tv._stage_optional_package("tiktoken==0.12.0", str(root)) is False+ assert not (root / "tiktoken").exists()+ assert not (root / "tiktoken_ext").exists()+ assert not (root / ".top-up-staging").exists()+++def _partial_tiktoken(root):+ (root / "tiktoken").mkdir(parents = True, exist_ok = True)+ (root / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ (root / "tiktoken_ext").mkdir(exist_ok = True)+ (root / "tiktoken_ext" / "openai_public.py").write_text("", encoding = "utf-8")+++def test_offline_still_clears_a_partial_optional_payload(tmp_path, monkeypatch):+ """A worker killed after the payload moved in and before its dist-info left tiktoken/+ ahead of site-packages. Offline there is no install, but the partial tree still goes,+ or the otherwise valid sidecar would be activated with it shadowing the ambient copy."""+ root = tmp_path / ".venv_t5_550"+ _partial_tiktoken(root)+ monkeypatch.setenv("UV_OFFLINE", "1")+ installs = []+ monkeypatch.setattr(+ tv, "_install_to_dir", lambda pkg, target_dir: installs.append(pkg) or False+ )+ assert tv._top_up_optional_packages(str(root), tv._VENV_T5_550_PACKAGES) is True+ assert installs == []+ assert not (root / "tiktoken").exists() and not (root / "tiktoken_ext").exists()+ # And through the sidecar check that activation runs.+ _partial_tiktoken(root)+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: True)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert not (root / "tiktoken").exists()+++def test_a_partial_payload_behind_an_unobtainable_lock_withholds_the_sidecar(tmp_path, monkeypatch):+ """The lock could not be taken (held too long, or the file cannot be opened) and a+ payload without its RECORD is there: nothing is touched, and the sidecar is not+ activated with that payload shadowing the ambient copy. Nothing there: usable."""+ import contextlib++ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ _partial_tiktoken(root)+ monkeypatch.delenv("UV_OFFLINE", raising = False)+ monkeypatch.setattr(tv, "_env_offline", lambda: False)+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target_dir: False)++ @contextlib.contextmanager+ def not_held(venv_dir):+ yield False++ monkeypatch.setattr(tv, "_optional_top_up_lock", not_held)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ assert tv._top_up_optional_packages(str(root), tv._VENV_T5_550_PACKAGES) is False+ assert (root / "tiktoken").is_dir()+ import shutil as _shutil++ _shutil.rmtree(root / "tiktoken")+ _shutil.rmtree(root / "tiktoken_ext")+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ assert tv._top_up_optional_packages(str(root), tv._VENV_T5_550_PACKAGES) is True+++def test_a_sidecar_whose_top_up_remnants_will_not_go_is_not_activated(tmp_path, monkeypatch):+ """The top-up failed and the cleanup could not remove the partial tree (a locked+ file, a permission): the sidecar the cleanup itself calls unusable is not activated."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ _partial_tiktoken(root)+ monkeypatch.delenv("UV_OFFLINE", raising = False)+ monkeypatch.setattr(tv, "_env_offline", lambda: False)+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target_dir: False)+ monkeypatch.setattr(tv, "_venv_dir_is_valid_and_undamaged", lambda *a, **k: True)+ real_rmtree = tv.shutil.rmtree++ def stuck_rmtree(path, *a, **k):+ if Path(path).name in ("tiktoken", "tiktoken_ext"):+ return None+ return real_rmtree(path, *a, **k)++ monkeypatch.setattr(tv.shutil, "rmtree", stuck_rmtree)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is False+ assert (root / "tiktoken").is_dir()+ # Once the remnants can go, the same failed top-up leaves a usable sidecar.+ monkeypatch.setattr(tv.shutil, "rmtree", real_rmtree)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ (root / tv._OPTIONAL_TOP_UP_FAILED).unlink(missing_ok = True)+ assert tv._ensure_venv_dir(str(root), tv._VENV_T5_550_PACKAGES, "test sidecar") is True+ assert not (root / "tiktoken").exists()+++def test_an_interrupted_top_up_is_finished_by_the_next_one(tmp_path, monkeypatch):+ """A process killed between moving tiktoken/ in and its dist-info left a payload no+ scan could judge and no activation would complete: a package counts as present only+ once its dist-info has landed, and the next top-up replaces the partial entries."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ (root / "tiktoken").mkdir()+ (root / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ assert tv._optional_package_absent(str(root), "tiktoken") is True+ (root / "tiktoken-0.9.0.dist-info").mkdir()+ assert tv._optional_package_absent(str(root), "tiktoken") is True+ (root / "tiktoken-0.9.0.dist-info" / "RECORD").write_text("", encoding = "utf-8")+ assert tv._optional_package_absent(str(root), "tiktoken") is False+ shutil.rmtree(root / "tiktoken-0.9.0.dist-info")++ def fake_install(pkg, target):+ for d in ("tiktoken", "tiktoken_ext", "tiktoken-0.9.0.dist-info"):+ (pathlib.Path(target) / d).mkdir()+ (pathlib.Path(target) / d / "RECORD").write_text(d, encoding = "utf-8")+ (pathlib.Path(target) / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ return True++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), tv._VENV_T5_550_PACKAGES)+ assert tv._optional_package_absent(str(root), "tiktoken") is False+ assert (root / "tiktoken_ext" / "RECORD").is_file()+++def test_latest_sidecar_activation_tops_up_a_missing_tiktoken(tmp_path, monkeypatch):+ """Model activation goes through _ensure_venv_t5_latest_exists, not the provisioning+ path; a healthy latest sidecar without tiktoken has to get its top-up there too, or a+ latest-tier Qwen model keeps failing to tokenize after a transient install failure."""+ latest = tmp_path / ".venv_t5_latest"+ latest.mkdir()+ packages = ("transformers==9.9.9", "huggingface_hub==1.8.0", "hf_xet==1.4.2", "tiktoken")+ monkeypatch.setattr(tv, "_VENV_T5_LATEST_DIR", str(latest))+ monkeypatch.setattr(tv, "_latest_pin_data", lambda: {"version": "9.9.9", "packages": packages})+ monkeypatch.setattr(tv, "_venv_dir_health", lambda *a, **k: (True, True))+ installed = []+ monkeypatch.setattr(+ tv, "_install_to_dir", lambda pkg, target: installed.append((pkg, target)) or True+ )+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ assert tv._ensure_venv_t5_latest_exists() is True+ assert installed == [("tiktoken", str(latest / ".top-up-staging"))]+++def test_the_top_up_stays_home_offline_and_yields_to_another_process(tmp_path, monkeypatch):+ """Workers activate tiers on their own: offline, none of them should sit through+ network retries for a best-effort package, and two finding it absent at once must+ not both write into the shared sidecar."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ packages = tv._VENV_T5_550_PACKAGES+ installed = []+ monkeypatch.setattr(tv, "_install_to_dir", lambda pkg, target: installed.append(pkg) or True)+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ tv._top_up_optional_packages(str(root), packages)+ assert installed == []+ monkeypatch.delenv("HF_HUB_OFFLINE")+ monkeypatch.setenv("UV_OFFLINE", "1")+ tv._top_up_optional_packages(str(root), packages)+ assert installed == []+ monkeypatch.delenv("UV_OFFLINE")+ # Another process holds the top-up lock: wait up to the bound, then leave the package to it.+ monkeypatch.setattr(tv, "_OPTIONAL_TOP_UP_WAIT_SECONDS", 0.5)+ with tv._optional_top_up_lock(str(root)) as held:+ assert held is True+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert installed == []+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), packages)+ assert installed == ["tiktoken"]+++def test_the_top_up_is_staged_and_lands_dist_info_last(tmp_path, monkeypatch):+ """A scan by another worker must never meet a RECORD whose files have not landed:+ the package is built beside the sidecar and moved in, payload first, dist-info last."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ order = []++ def fake_install(pkg, target):+ assert target != str(root), "installed straight into the shared sidecar"+ for d in ("tiktoken", "tiktoken_ext", "tiktoken-0.9.0.dist-info"):+ (pathlib.Path(target) / d).mkdir()+ (pathlib.Path(target) / d / "marker").write_text(d, encoding = "utf-8")+ return True++ real_replace = tv.os.replace++ def replacing(src, dst):+ order.append(pathlib.Path(dst).name)+ return real_replace(src, dst)++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ monkeypatch.setattr(tv.os, "replace", replacing)+ assert tv._stage_optional_package("tiktoken", str(root)) is True+ assert order[-1] == "tiktoken-0.9.0.dist-info"+ assert set(order) == {"tiktoken", "tiktoken_ext", "tiktoken-0.9.0.dist-info"}+ assert (root / "tiktoken" / "marker").is_file() and not (root / ".top-up-staging").exists()+++def test_the_top_up_removes_the_recordless_dist_info_an_interrupted_install_left(+ tmp_path, monkeypatch+):+ """uv cannot uninstall a dist-info with no RECORD and lands the new version beside+ it; both validators skip the recordless one, but importlib.metadata would keep+ answering its version. Every other dist-info of the project goes before the new+ metadata lands, and a dist-info of another project stays."""+ root = tmp_path / ".venv_t5_550"+ root.mkdir()+ stale = root / "tiktoken-0.7.0.dist-info"+ stale.mkdir()+ (stale / "METADATA").write_text("Name: tiktoken\nVersion: 0.7.0\n", encoding = "utf-8")+ other = root / "regex-2024.11.6.dist-info"+ other.mkdir()+ (other / "RECORD").write_text("", encoding = "utf-8")++ def fake_install(pkg, target):+ for d in ("tiktoken", "tiktoken-0.9.0.dist-info"):+ (pathlib.Path(target) / d).mkdir()+ (pathlib.Path(target) / d / "marker").write_text(d, encoding = "utf-8")+ return True++ monkeypatch.setattr(tv, "_install_to_dir", fake_install)+ assert tv._stage_optional_package("tiktoken", str(root)) is True+ assert not stale.exists()+ assert (root / "tiktoken-0.9.0.dist-info" / "marker").is_file()+ assert (other / "RECORD").is_file()+++def test_a_recordless_record_beside_a_complete_install_is_removed_without_a_top_up(+ tmp_path, monkeypatch+):+ """A retry that succeeded after an interrupted install leaves both; the package is+ present, so no top-up runs, and the stale metadata must still go."""+ root = tmp_path / ".venv_t5_550"+ (root / "tiktoken").mkdir(parents = True)+ (root / "tiktoken" / "__init__.py").write_text("", encoding = "utf-8")+ good = root / "tiktoken-0.9.0.dist-info"+ good.mkdir()+ (good / "RECORD").write_text("", encoding = "utf-8")+ stale = root / "tiktoken-0.7.0.dist-info"+ stale.mkdir()+ (stale / "METADATA").write_text("Name: tiktoken\nVersion: 0.7.0\n", encoding = "utf-8")+ monkeypatch.setattr(tv, "_env_offline", lambda: False)+ monkeypatch.delenv("UV_OFFLINE", raising = False)+ monkeypatch.setattr(+ tv, "_install_to_dir", lambda *a, **k: pytest.fail("installed over a present package")+ )+ tv._OPTIONAL_TOP_UP_ATTEMPTED.clear()+ tv._top_up_optional_packages(str(root), ("tiktoken",))+ assert not stale.exists()+ assert (good / "RECORD").is_file()diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 1588e93a5f6..46e85014493 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -34,6 +34,7 @@ import importlib.utilimport jsonimport structlogfrom loggers import get_logger+import contextlibimport osimport reimport shutil@@ -2027,6 +2028,16 @@ _VENV_T5_550_PACKAGES = (# Backwards-compat alias_VENV_T5_PACKAGES = _VENV_T5_550_PACKAGES+# Setup installs tiktoken best-effort, so the runtime must agree or it deletes the sidecar and+# retries the same impossible install.+_OPTIONAL_SIDECAR_PACKAGES = frozenset({"tiktoken"})+++def _sidecar_package_is_optional(pkg_spec: str) -> bool:+ return (+ pkg_spec.split("==", 1)[0].strip().lower().replace("_", "-") in _OPTIONAL_SIDECAR_PACKAGES+ )+_SIDECAR_FILE_CHECK_ENV = "UNSLOTH_SKIP_SIDECAR_FILE_CHECK"@@ -2151,6 +2162,7 @@ def _sidecar_scan_impl(venv_dir: str, limit: int = 3) -> tuple[list[str], bool]:return [], Truefor di in dist_infos:name = di.name.split("-")[0]+ # Absent is fine; present, its RECORD is held to the same standard.try:record = (di / "RECORD").read_text(encoding = "utf-8", errors = "replace")except FileNotFoundError:@@ -2269,6 +2281,8 @@ def _venv_dir_is_valid(venv_dir: str, packages: tuple[str, ...]) -> bool:if not any((Path(venv_dir) / d).is_dir() for d in (pkg_name_norm, pkg_name_norm.replace("_", "-"))):+ if _sidecar_package_is_optional(pkg_spec):+ continuereturn False# Unpinned packages: existence is enough.if pkg_version is None:@@ -2412,10 +2426,335 @@ def _mark_studio_owned(venv_dir: str) -> None:pass+# An unavailable wheel is asked for once per session.+_OPTIONAL_TOP_UP_ATTEMPTED: set[tuple[str, str]] = set()+++def _optional_package_absent(venv_dir: str, pkg_spec: str) -> bool:+ """Whether *pkg_spec* is missing from the sidecar, or only partly there.++ The top-up moves a package in entry by entry with its dist-info last, so a package+ counts as present only when its dist-info has landed: a payload directory on its+ own is an interrupted top-up, which nothing else would ever finish.+ """+ name = pkg_spec.split("==")[0].replace("-", "_")+ root = Path(venv_dir)+ if not any((root / d / "__init__.py").is_file() for d in (name, name.replace("_", "-"))):+ return True+ return not any(+ (root / entry / "RECORD").is_file() for entry in _dist_info_entries(venv_dir, name)+ )+++def _optional_package_entries(venv_dir: str, pkg_spec: str) -> list[str]:+ """Every top-level entry of the sidecar the optional package's wheel owns."""+ stem = pkg_spec.split("==")[0].lower().replace("-", "_")+ try:+ entries = os.listdir(venv_dir)+ except OSError:+ return []+ return [+ entry+ for entry in entries+ if entry.lower().replace("-", "_") == stem+ or entry.lower().replace("-", "_").startswith((stem + "_", stem + "."))+ ]+++def _optional_package_partly_there(venv_dir: str, pkg_spec: str) -> bool:+ """A payload without the dist-info that would make it count: an interrupted top-up+ (or a failed install) left it, and it sits ahead of site-packages."""+ return _optional_package_absent(venv_dir, pkg_spec) and bool(+ _optional_package_entries(venv_dir, pkg_spec)+ )+++def _remove_optional_remnants(venv_dir: str, pkg_spec: str) -> bool:+ """Drop what a failed optional install left: the payload directory and every dist-info.++ An installer that exits nonzero part-way (a full disk, an interrupted copy) can leave+ the package directory without its native extension, or metadata without the package;+ with both gone, _optional_package_absent reads the package as absent and the next+ top-up tries again instead of the sidecar shadowing a working ambient copy.++ Answers whether nothing of the package is left. A remnant that would not go (a file+ another process holds open on Windows, a permission) still sits ahead of+ site-packages, and the caller has to treat the directory as not usable rather than+ report a sidecar that will fail at tokenization.+ """+ # Every top-level entry the wheel owns; the prefix is the project name then end, _, . or -.+ root = Path(venv_dir)++ def _owned() -> list[str]:+ return _optional_package_entries(venv_dir, pkg_spec)++ for entry in _owned():+ path = root / entry+ if path.is_dir() and not path.is_symlink():+ shutil.rmtree(path, ignore_errors = True)+ elif path.exists() or path.is_symlink():+ try:+ path.unlink()+ except OSError:+ pass+ left = _owned()+ if left:+ logger.warning(+ "%s could not be removed from %s after a failed install of %s; the directory is not usable",+ ", ".join(sorted(left)[:5]),+ venv_dir,+ pkg_spec,+ )+ return not left+++def _remove_recordless_dist_infos(venv_dir: str, pkg_spec: str) -> None:+ """Drop every `<pkg>-*.dist-info` with no RECORD: metadata uv cannot uninstall."""+ name = pkg_spec.split("==")[0]+ root = Path(venv_dir)+ for entry in _dist_info_entries(venv_dir, name):+ if not (root / entry / "RECORD").is_file():+ shutil.rmtree(root / entry, ignore_errors = True)+++def _dist_info_entries(venv_dir: str, name: str) -> list[str]:+ wanted = name.lower().replace("-", "_")+ try:+ entries = os.listdir(venv_dir)+ except OSError:+ return []+ return [+ entry+ for entry in entries+ if entry.endswith(".dist-info")+ and entry[: -len(".dist-info")].rsplit("-", 1)[0].lower().replace("-", "_") == wanted+ ]+++# Recorded beside the sidecar so every worker sees them; retried later in case it was the network.+_OPTIONAL_TOP_UP_FAILED = ".optional-top-up-failed.json"+_OPTIONAL_TOP_UP_RETRY_SECONDS = 6 * 60 * 60.0+++def _top_up_failure_path(venv_dir: str) -> str:+ return os.path.join(venv_dir, _OPTIONAL_TOP_UP_FAILED)+++def _read_top_up_failures(venv_dir: str) -> dict:+ try:+ with open(_top_up_failure_path(venv_dir), encoding = "utf-8") as fh:+ data = json.load(fh)+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}+++def _write_top_up_failures(venv_dir: str, failures: dict) -> None:+ path = _top_up_failure_path(venv_dir)+ try:+ if not failures:+ if os.path.exists(path):+ os.unlink(path)+ return+ tmp = path + ".tmp"+ with open(tmp, "w", encoding = "utf-8") as fh:+ json.dump(failures, fh)+ os.replace(tmp, path)+ except OSError:+ pass+++def _top_up_failed_recently(venv_dir: str, pkg: str) -> bool:+ when = _read_top_up_failures(venv_dir).get(pkg)+ if not isinstance(when, (int, float)):+ return False+ age = time.time() - when+ return 0 <= age < _OPTIONAL_TOP_UP_RETRY_SECONDS+++def _record_top_up_outcome(venv_dir: str, pkg: str, ok: bool) -> None:+ failures = _read_top_up_failures(venv_dir)+ if ok:+ if pkg not in failures:+ return+ failures.pop(pkg, None)+ else:+ failures[pkg] = time.time()+ _write_top_up_failures(venv_dir, failures)+++def _top_up_optional_packages(venv_dir: str, packages: tuple[str, ...]) -> bool:+ """Add an optional package a valid sidecar is missing, without touching the rest.++ _venv_dir_is_valid accepts a sidecar without tiktoken, so a transient failure while+ the sidecar was built (the latest sidecar in particular, which no setup top-up+ visits) left Qwen tokenizers broken until the user deleted the directory. Best+ effort and non-destructive: a failure is logged, recorded beside the sidecar and+ not retried by any worker process for a while (each job spawns its own workers,+ which would otherwise each sit through the same doomed install), and nothing is+ attempted while the session is offline (a worker would otherwise sit through+ network retries for a model that may not even need the package).++ Workers activate tiers independently and share the sidecar, so the add is staged:+ the package is installed into a scratch directory beside the sidecar and its+ entries are renamed in, payload first and dist-info last, so a scan by another+ worker never meets a RECORD whose files have not landed and reads the sidecar as+ damaged. One process at a time does this; another that finds the lock held waits+ for it, then finds the package there.+ """+ usable = True+ offline = (+ _env_offline() or os.environ.get("UV_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUES+ )+ for pkg in packages:+ if not _sidecar_package_is_optional(pkg):+ continue+ if offline:+ # A payload without its dist-info counts as absent yet would shadow the ambient copy.+ if _optional_package_partly_there(venv_dir, pkg):+ with _optional_top_up_lock(venv_dir) as held:+ if held and _optional_package_partly_there(venv_dir, pkg):+ logger.warning(+ "%s: removing the partial %s an interrupted add left", venv_dir, pkg+ )+ if not _remove_optional_remnants(venv_dir, pkg):+ usable = False+ elif not held:+ usable = False+ continue+ # The staging cleanup never reaches a recordless dist-info, and metadata still answers it.+ _remove_recordless_dist_infos(venv_dir, pkg)+ if not _optional_package_absent(venv_dir, pkg):+ continue+ key = (os.path.normcase(os.path.abspath(venv_dir)), pkg)+ if key in _OPTIONAL_TOP_UP_ATTEMPTED:+ continue+ _OPTIONAL_TOP_UP_ATTEMPTED.add(key)+ with _optional_top_up_lock(venv_dir) as held:+ if not held:+ logger.warning(+ "%s: another process held the top-up lock too long; left as is", venv_dir+ )+ if _optional_package_partly_there(venv_dir, pkg):+ usable = False+ continue+ if not _optional_package_absent(venv_dir, pkg):+ continue+ if _top_up_failed_recently(venv_dir, pkg):+ logger.info(+ "%s: a recent attempt to add %s failed; not retrying yet", venv_dir, pkg+ )+ continue+ logger.info("Adding %s to %s (optional package missing) ...", pkg, venv_dir)+ ok = _stage_optional_package(pkg, venv_dir)+ _record_top_up_outcome(venv_dir, pkg, ok)+ if not ok:+ logger.warning(+ "%s could not be added to %s; continuing without it (Qwen tokenizers may fail)",+ pkg,+ venv_dir,+ )+ if _optional_package_partly_there(venv_dir, pkg):+ usable = False+ return usable+++def _stage_optional_package(pkg: str, venv_dir: str) -> bool:+ """Install *pkg* beside the sidecar, then move its entries in, dist-info last."""+ staging = os.path.join(venv_dir, ".top-up-staging")+ shutil.rmtree(staging, ignore_errors = True)+ try:+ os.makedirs(staging, exist_ok = True)+ if not _install_to_dir(pkg, staging):+ # A partial payload would shadow the ambient copy for the whole backoff.+ _remove_optional_remnants(venv_dir, pkg)+ return False+ entries = sorted(os.listdir(staging), key = lambda name: name.endswith(".dist-info"))+ # uv cannot uninstall a recordless dist-info and metadata answers whichever it meets first.+ for name in entries:+ if not name.endswith(".dist-info"):+ continue+ project = name[: -len(".dist-info")].rsplit("-", 1)[0]+ for stale in _dist_info_entries(venv_dir, project):+ if stale != name:+ shutil.rmtree(os.path.join(venv_dir, stale), ignore_errors = True)+ for name in entries:+ source = os.path.join(staging, name)+ target = os.path.join(venv_dir, name)+ if os.path.isdir(target) and not os.path.islink(target):+ shutil.rmtree(target, ignore_errors = True)+ elif os.path.lexists(target):+ os.unlink(target)+ os.replace(source, target)+ return True+ except OSError as exc:+ logger.warning("staging %s into %s failed: %s", pkg, venv_dir, exc)+ _remove_optional_remnants(venv_dir, pkg)+ return False+ finally:+ shutil.rmtree(staging, ignore_errors = True)+++_OPTIONAL_TOP_UP_LOCK = ".optional-top-up.lock"+++_OPTIONAL_TOP_UP_WAIT_SECONDS = 120.0+++def _optional_top_up_lock(venv_dir: str):+ """A cross-process lock on a sidecar's optional top-up, waited for up to a bound.++ Workers activate tiers independently, so two can find the package absent at once;+ two installers writing one --target tree leave it half-written, and a worker that+ went on without waiting would activate with the package still absent. Yields True+ when this process holds the lock, False when another kept it past the bound (or+ the lock cannot be taken at all, read as "someone else's turn" rather than a+ reason to write unguarded).+ """+ handle = None+ try:+ handle = open(os.path.join(venv_dir, _OPTIONAL_TOP_UP_LOCK), "a+b")+ deadline = time.monotonic() + _OPTIONAL_TOP_UP_WAIT_SECONDS+ while True:+ try:+ if sys.platform == "win32":+ import msvcrt+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise+ time.sleep(0.25)+ except OSError:+ if handle is not None:+ handle.close()+ yield False+ return+ try:+ yield True+ finally:+ try:+ if sys.platform == "win32":+ import msvcrt+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ except OSError:+ pass+ handle.close()++def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bool:"""Ensure *venv_dir* exists with all *packages*. Install if missing."""if _venv_dir_is_valid_and_undamaged(venv_dir, packages):- return True+ return _top_up_optional_packages(venv_dir, packages)logger.warning("%s not found or incomplete at %s -- installing at runtime", label, venv_dir)# The Docker image links its sidecars into the Studio home (UNSLOTH_STUDIO_APP). rmtree refuses a@@ -2432,6 +2771,22 @@ def _ensure_venv_dir(venv_dir: str, packages: tuple[str, ...], label: str) -> bofor idx, pkg in enumerate(packages, start = 1):logger.info("Installing %s (%d/%d) into %s ...", pkg, idx, total, venv_dir)if not _install_to_dir(pkg, venv_dir):+ if _sidecar_package_is_optional(pkg):+ logger.warning(+ "%s could not be installed into %s; continuing without it (Qwen tokenizers may fail)",+ pkg,+ venv_dir,+ )+ # Only absent is safe: a half-copied payload fails at tokenization.+ if _remove_optional_remnants(venv_dir, pkg):+ # Recorded like the top-up path's failures: the sidecar reads as valid from+ # here on, so without it the next activation and every worker a job spawns+ # would sit through the same doomed install.+ _record_top_up_outcome(venv_dir, pkg, False)+ _OPTIONAL_TOP_UP_ATTEMPTED.add(+ (os.path.normcase(os.path.abspath(venv_dir)), pkg)+ )+ continuereturn Falselogger.info("Installed %s to %s", label, venv_dir)return True@@ -2853,7 +3208,8 @@ def _ensure_venv_t5_latest_exists() -> bool:# Only a scan that actually read the files may retire it; one that hit EIO has not.if conclusive:_clear_latest_repair_request()- return True+ # Activation is where a missing tiktoken gets topped up.+ return _top_up_optional_packages(_VENV_T5_LATEST_DIR, packages)# Broken, and every path below can still fail to fix it (offline, a child, a swap already# running, pip). Flag it here rather than per bailout, so the routing predicate withholds# the sidecar whichever we take: it cannot see sub-file damage itself, and a mapping@@ -2930,7 +3286,7 @@ def ensure_latest_transformers_venv(and tuple(pin["packages"]) == packagesand _venv_dir_is_valid_and_undamaged(_VENV_T5_LATEST_DIR, packages)):- return True+ return _top_up_optional_packages(_VENV_T5_LATEST_DIR, packages)return _stage_and_swap_latest_venv(version, packages, before_swap = before_swap)diff --git a/studio/install_manifest.py b/studio/install_manifest.pyindex 8dc619c0026..fe1c9dfe3aa 100644--- a/studio/install_manifest.py+++ b/studio/install_manifest.py@@ -17,6 +17,8 @@ Must import inside that half-installed venv: stdlib only, `packaging` optional.from __future__ import annotations+import contextlib+import errnoimport hashlibimport jsonimport os@@ -28,6 +30,21 @@ from pathlib import Pathfrom typing import Dict, List, Optional, Sequence, TupleMANIFEST_NAME = "unsloth_install_manifest.json"+# Where remove_manifest parks the completion manifest. Only the dependency pass reads it, as+# evidence of the LAST completed pass; verify_install, the setup fast path and the desktop preflight+# never do, so a venv without a live manifest still reads as half-built.+PREVIOUS_MANIFEST_NAME = "unsloth_install_manifest.previous.json"+# Serialises the three writers below ACROSS processes. The CLI guards two updates of one venv,+# but the shells and the installer can be driven directly, and the MLX probe rewrites the+# manifest minutes after the pass ends: unserialised, one writer's replace can land between+# another's remove and its mutations and recreate a completion marker over a half-built venv.+LOCK_NAME = "unsloth_install_manifest.lock"+# Held for a whole pass by the installer, and only ever tested, never waited on: see pass_lock.+PASS_LOCK_NAME = "unsloth_install_pass.lock"+# How long a writer waits for a peer before going ahead unserialised, matching msvcrt's+# LK_LOCK. These writers take milliseconds, and a peer killed holding the lock must not wedge+# every later update.+LOCK_WAIT_SECONDS = 10.0MANIFEST_SCHEMA = 1# Canonical truthy set for UNSLOTH_NO_TORCH, matching install.ps1 / install.sh.@@ -54,6 +71,22 @@ TRACKED_REQUIREMENT_FILES: Tuple[str, ...] = (# The import chain studio/backend/run.py walks on startup.BOOT_REQUIREMENT_FILE = "studio.txt"+# Every file the dependency pass reads, recorded under the additive `pass_inputs` key. NOT folded+# into TRACKED_REQUIREMENT_FILES: verify_install compares that whole dict, so one new name would+# report every install in the field as changed and buy each a repair pass.+PASS_INPUT_FILES: Tuple[str, ...] = TRACKED_REQUIREMENT_FILES + (+ "diffusers-pin.txt",+ "triton-kernels.txt",+ "overrides.txt",+ "single-env/constraints.txt",+ "single-env/overrides-darwin-arm64.txt",+)++# Written beside a sidecar directory by setup.sh / setup.ps1 and by the runtime self-heal in+# studio/backend/utils/transformers_version.py. Absent means not ours to delete, so not current+# either: a rebuild is the only repair, and it starts with rm.+SIDECAR_OWNED_MARKER = ".unsloth-studio-owned"+def venv_root() -> Path:"""Directory holding pyvenv.cfg for the interpreter running this code."""@@ -64,6 +97,10 @@ def manifest_path(root: Optional[Path] = None) -> Path:return (root or venv_root()) / MANIFEST_NAME+def previous_manifest_path(root: Optional[Path] = None) -> Path:+ return (root or venv_root()) / PREVIOUS_MANIFEST_NAME++def requirements_root(script_dir: Optional[Path] = None) -> Path:"""studio/backend/requirements/ next to this module (or a given studio/ dir)."""return (script_dir or Path(__file__).resolve().parent) / "backend" / "requirements"@@ -113,6 +150,29 @@ def requirement_digests(req_root: Optional[Path] = None) -> Dict[str, str]:return digests+def digest_file(path) -> Optional[str]:+ """sha256 of one file, or None when it is absent or unreadable.++ None is never equal to a recorded digest, so an input that cannot be read+ forces the step that consumes it to run. That is the safe direction.+ """+ try:+ return _sha256(Path(path))+ except (TypeError, ValueError):+ return None+++def pass_input_digests(req_root: Optional[Path] = None) -> Dict[str, str]:+ """sha256 of every PASS_INPUT_FILES entry that exists, relpath -> digest."""+ root = Path(req_root) if req_root is not None else requirements_root()+ digests: Dict[str, str] = {}+ for name in PASS_INPUT_FILES:+ digest = digest_file(root / name)+ if digest is not None:+ digests[name] = digest+ return digests++def _canonical(name: str) -> str:"""PEP 503 normalisation, so PyJWT / pyjwt / py_jwt compare equal."""return re.sub(r"[-_.]+", "-", name).lower()@@ -259,22 +319,302 @@ def _installed_version(dist_name: str, installed: Optional[Dict[str, str]] = Nonreturn installed_version_probe(dist_name)[0] or None+def _publish_json(+ path: Path,+ payload: dict,+ *,+ only_if_present: bool = False,+) -> bool:+ """Write *payload* to *path* through this writer's own temp file, then replace.++ A shared temp name is a second writer's file as much as this one's: either could clobber+ the other between the write and the replace and publish the wrong payload.+ *only_if_present* declines to recreate a manifest another updater removed meanwhile.+ Callers hold the lock; this raises nothing they do not already catch.+ """+ import tempfile # noqa: PLC0415 - stdlib, and not needed to read a manifest++ text = json.dumps(payload, indent = 2, sort_keys = True)+ descriptor, name = tempfile.mkstemp(dir = str(path.parent), prefix = path.name + ".", suffix = ".tmp")+ tmp = Path(name)+ try:+ with os.fdopen(descriptor, "w", encoding = "utf-8") as handle:+ handle.write(text)+ # mkstemp creates at 0600, where write_text gave the umask default (0644 on a stock+ # box). Narrowing it is a change nobody asked for, so keep the mode the manifest+ # already has, or the umask default: a tightening the user chose stays theirs.+ try:+ mode = path.stat().st_mode & 0o777+ except OSError:+ umask = os.umask(0)+ os.umask(umask)+ mode = 0o666 & ~umask+ try:+ os.chmod(tmp, mode)+ except OSError:+ pass # Windows, or a filesystem without modes: the content is what matters+ if only_if_present and not path.exists():+ return False+ os.replace(tmp, path)+ except BaseException:+ try:+ tmp.unlink()+ except OSError:+ pass+ raise+ finally:+ try:+ tmp.unlink()+ except OSError:+ pass+ return True+++def _manifest_lock(root: Optional[Path] = None):+ """Hold an exclusive lock on LOCK_NAME for the block. Never raises.++ Best effort: this module has to run inside a half-built venv, so a filesystem that cannot+ lock (a network mount, a read-only prefix, no fcntl or msvcrt) proceeds unserialised+ rather than failing an install, as it did before this existed. The deadline below bounds+ the retries, not one stalled syscall.+ """+ handle = None+ locked = False+ try:+ # O_NOFOLLOW where it exists, or a symlink on the reserved name would be followed and+ # open a file somewhere else. Never O_TRUNC: nothing is written, the lock is the fd.+ descriptor = os.open(+ (root or venv_root()) / LOCK_NAME,+ os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0),+ 0o644,+ )+ handle = os.fdopen(descriptor, "a+b")+ except OSError:+ handle = None+ if handle is not None:+ try:+ import fcntl # noqa: PLC0415 - POSIX only, and absent on Windows++ # Non-blocking with a deadline, never a bare LOCK_EX: that waits forever on a+ # peer suspended while holding it.+ deadline = time.monotonic() + LOCK_WAIT_SECONDS+ while True:+ try:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ locked = True+ break+ except OSError as exc:+ # Only contention is worth waiting out. A mount that does not implement+ # locking answers at once and would cost the deadline on every write.+ if exc.errno not in (+ errno.EWOULDBLOCK,+ errno.EAGAIN,+ errno.EACCES,+ errno.EINTR,+ ):+ break+ if time.monotonic() >= deadline:+ break+ time.sleep(0.02)+ except ImportError:+ try:+ import msvcrt # noqa: PLC0415 - the Windows half of the same thing++ handle.seek(0)+ # LK_LOCK retries for ~10 s and then raises; an update that waits longer than+ # that on a stale lock has to proceed, or a crashed peer strands every later run.+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)+ locked = True+ except (ImportError, OSError):+ locked = False+ except (OSError, ValueError):+ locked = False+ try:+ # The flag, not just the block: a writer that may only publish while it really holds the+ # lock has to be able to ask, and the two that must never fail an install can ignore it.+ yield locked+ finally:+ _release_lock(handle, locked)+++def _release_lock(handle, locked: bool) -> None:+ """Drop the lock and the handle. Never raises."""+ if handle is None:+ return+ if locked:+ try:+ try:+ import fcntl # noqa: PLC0415+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ except ImportError:+ import msvcrt # noqa: PLC0415+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ except (OSError, ValueError):+ pass+ try:+ handle.close()+ except OSError:+ pass+++def pass_lock(root: Optional[Path] = None):+ """Held for a whole dependency pass, and never waited on. Never raises.++ Yields False only when a peer is already inside a pass on this venv. Its packages are the+ ones the recorded evidence describes, so a second pass has to run every step rather than+ skip on an answer the peer is invalidating as it reads it. Not serialisation: the pass can+ take tens of minutes and a waiter would be worse than the concurrency.++ Best effort, as _manifest_lock: a filesystem that cannot lock reads as uncontended, which+ is what every release before this did.+ """+ handle = None+ locked = False+ contended = False+ try:+ descriptor = os.open(+ (root or venv_root()) / PASS_LOCK_NAME,+ os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0),+ 0o644,+ )+ handle = os.fdopen(descriptor, "a+b")+ except OSError:+ handle = None+ if handle is not None:+ try:+ import fcntl # noqa: PLC0415 - POSIX only, and absent on Windows+ try:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ locked = True+ except OSError as exc:+ # Only these mean a peer holds it. Anything else is a mount that does not+ # implement locking, which must not cost every step its evidence.+ contended = exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES)+ except ImportError:+ try:+ import msvcrt # noqa: PLC0415 - the Windows half of the same thing++ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ locked = True+ except ImportError:+ pass+ except OSError as exc:+ contended = exc.errno in (errno.EACCES, errno.EDEADLK)+ except (OSError, ValueError):+ pass+ try:+ yield not contended+ finally:+ _release_lock(handle, locked)++def remove_manifest(root: Optional[Path] = None) -> bool:"""Called before the dependency pass so an aborted run cannot leave a valid one.- True when no manifest remains. A surviving marker (Windows raises on a- read-only or locked file) still names this version and these digests, so a- pass killed afterwards would verify as complete.+ True when no manifest remains. A surviving marker still names this version and these+ digests, so a pass killed afterwards would verify as complete.++ Parked under PREVIOUS_MANIFEST_NAME rather than deleted: setup.ps1 calls this before pip,+ torch and triton are replaced, so without the parked copy every Windows update re-ran the+ whole pass. It is evidence only (see read_previous_manifest) and the next write_manifest+ drops it. Deleting it stays the fallback when the rename is refused."""+ path = manifest_path(root)+ parked = previous_manifest_path(root)+ with _manifest_lock(root):+ return _remove_manifest_locked(root, path, parked)+++def _remove_manifest_locked(root: Optional[Path], path: Path, parked: Path) -> bool:try:- manifest_path(root).unlink()+ os.replace(path, parked)except FileNotFoundError:- return True+ # No live manifest: an interrupted run took it. Nothing was parked by this call, so a+ # copy on the reserved name is that dead run's and must go the same way, or the pass+ # reads it as evidence and refuses behind one it cannot clear -- on Windows after+ # setup.ps1's mutations. Losing a dead run's evidence only costs a full pass.+ consume_previous_manifest(root)+ return not parked.exists()except OSError:- return False+ # The rename was refused. Clear the reserved name and retry before falling back to+ # the unlink: setup.ps1 reads True as permission to replace pip, torch and triton, and+ # the pass refuses behind a parked copy it cannot clear. Dropping the live manifest+ # first would put that refusal after the mutations, on a venv that cannot verify.+ consume_previous_manifest(root)+ if parked.exists():+ return False+ try:+ os.replace(path, parked)+ return True+ except FileNotFoundError:+ return True+ except OSError:+ pass+ try:+ path.unlink()+ except FileNotFoundError:+ return True+ except OSError:+ return Falsereturn True+def consume_previous_manifest(root: Optional[Path] = None) -> None:+ """Drop the parked copy once a pass has read it.++ The parked copy stands in for the live manifest remove_manifest took away, and it+ has to go the same way: a pass killed after reading it must not leave it for the+ next run to read as evidence of a completed pass. Best effort, as remove_manifest's+ own fallback is.+ """+ try:+ previous_manifest_path(root).unlink()+ except OSError:+ pass+++def read_previous_manifest(root: Optional[Path] = None) -> Optional[dict]:+ """The manifest remove_manifest parked, or None.++ Evidence of the last COMPLETED pass, for the dependency pass alone: every skip it+ permits is still re-verified on disk, and verify_install never reads it, so this+ can make an update faster but never make a half-built venv look finished.+ """+ try:+ raw = previous_manifest_path(root).read_text(encoding = "utf-8")+ except (OSError, ValueError):+ return None+ try:+ data = json.loads(raw)+ except ValueError:+ return None+ return data if isinstance(data, dict) else None+++# The keys write_manifest owns and the only ones verify_install, the setup fast path and+# desktop-capabilities decide on. Additive evidence (`extra`, update_manifest kwargs) may never+# shadow one: rewriting `package_version` would falsely validate an install, and absent means+# "unknown", which evidence must not invent. ONE constant, or the two writers would disagree.+PROTECTED_MANIFEST_KEYS: Tuple[str, ...] = (+ "schema",+ "completed_at_ms",+ "package",+ "package_version",+ "python",+ "platform",+ "prefix",+ "steps_total",+ "requirement_files",+ "no_torch",+ "expected_torch_tag",+ "expected_torch_tag_pinned",+)++def write_manifest(root: Optional[Path] = None,req_root: Optional[Path] = None,@@ -283,6 +623,7 @@ def write_manifest(no_torch: Optional[bool] = None,expected_torch_tag: Optional[str] = None,expected_torch_tag_pinned: Optional[bool] = None,+ extra: Optional[Dict[str, object]] = None,) -> Optional[Path]:"""Record a completed install. Never raises: no manifest reads as incomplete,which is the safe answer."""@@ -315,14 +656,73 @@ def write_manifest(# eGPU with no repair offered. Absent means unknown, as with every other additive key.if expected_torch_tag_pinned is not None:payload["expected_torch_tag_pinned"] = bool(expected_torch_tag_pinned)+ # The dependency pass's own evidence (`pass_inputs`, `step_results`, `pip_check_ok`, ...):+ # additive, never authoritative, every consumer re-verifies on disk. None is dropped so "absent+ # means unknown" holds, and nothing may shadow a field verify_install reads.+ for key, value in (extra or {}).items():+ if value is None or key in payload or key in PROTECTED_MANIFEST_KEYS:+ continue+ payload[key] = valuepath = manifest_path(root)try:- tmp = path.with_suffix(".json.tmp")- tmp.write_text(json.dumps(payload, indent = 2, sort_keys = True), encoding = "utf-8")- os.replace(tmp, path)- return path- except OSError:+ # The lock the other two writers take: this marker means the install finished and must+ # not interleave with another process dropping it. The temp copy is written under it+ # too, since that name belongs to whichever writer holds the lock.+ with _manifest_lock(root):+ _publish_json(path, payload)+ # TypeError/ValueError too: `extra` is caller-composed, and raising here would abort a pass+ # that has already installed everything, leaving a venv with no manifest at all.+ except (OSError, TypeError, ValueError):return None+ # The parked copy described the previous pass; the live file now does.+ try:+ previous_manifest_path(root).unlink()+ except OSError:+ pass+ return path+++def update_manifest(root: Optional[Path] = None, **extra: object) -> bool:+ """Merge additive keys into an existing manifest. Never raises.++ For evidence only available AFTER the manifest is written: the MLX probe runs there so a+ kill during its 180 s timeout cannot lose a finished install. False means "record+ nothing", never a failed install.++ PROTECTED_MANIFEST_KEYS are dropped as write_manifest drops them: this merges into a file+ that already claims the install finished, so rewriting the fields behind that claim could+ leave it valid-looking and wrong.+ """+ values = {+ key: value+ for key, value in extra.items()+ if value is not None and key not in PROTECTED_MANIFEST_KEYS+ }+ if not values:+ return False+ path = manifest_path(root)+ try:+ # Read, merge and replace inside the lock. The caller spends minutes gathering this+ # (the MLX probe waits up to 180 s), so a manifest read before that can be a different+ # one by now: another updater may have removed it and finished a new pass, and merging+ # into the old copy would put its fields back.+ with _manifest_lock(root) as locked:+ if not locked:+ # Advisory evidence only. A peer that timed out this lock is mid-pass, and+ # publishing beside it could put its removed marker back over a half-built+ # venv. Losing what this merges costs one probe.+ return False+ data = read_manifest(root)+ if data is None:+ return False+ data.update(values)+ # only_if_present: a peer on an older build of this module removes without taking+ # the lock, so the file is checked as late as it can be.+ if not _publish_json(path, data, only_if_present = True):+ return False+ except (OSError, TypeError, ValueError):+ return False+ return Truedef read_manifest(root: Optional[Path] = None) -> Optional[dict]:@@ -528,6 +928,210 @@ def missing_requirements(return missing+# A closure walk that never finishes (a wedged network mount) is a full pass on every update.+# Generous: 400 distributions cost well under a second in memory.+CLOSURE_SCAN_BUDGET_SECONDS = 10.0+# Belt to the deadline's braces: a cycle that never repeats a (name, extras) key still stops.+_CLOSURE_MAX_VISITS = 20000+++def _is_pip_backup(dist) -> bool:+ """True for the ~ame-1.0.dist-info an interrupted pip upgrade leaves behind."""+ return str(getattr(getattr(dist, "_path", None), "name", "")).startswith("~")+++def installed_dependency_index() -> Optional[Dict[str, Tuple[str, List[str]]]]:+ """canonical name -> (version, raw Requires-Dist lines) for this interpreter.++ One pass over the metadata, because every gated step asks the same question about+ the same site-packages and `distribution(name)` re-reads a dist-info per lookup.+ None when the metadata cannot be enumerated at all, which the caller reads as+ "cannot audit" rather than "satisfied".+ """+ from importlib.metadata import distributions+ try:+ index: Dict[str, Tuple[str, List[str]]] = {}+ for dist in distributions(path = _metadata_scan_paths()):+ # An interrupted pip upgrade leaves the old metadata renamed to ~ame-1.0.dist-info+ # with its payload gone. pip ignores those; so must this, or a closure reads an+ # unimportable package as installed and its step skips the reinstall that repairs it.+ if _is_pip_backup(dist):+ continue+ try:+ name = dist.metadata["Name"]+ version = dist.version+ except Exception:+ # Unreadable metadata is damage other checks report; it must not take the index+ # down.+ continue+ if not name or not version:+ continue+ key = _canonical(str(name))+ # First wins, as sys.path precedence does; a duplicate is metadata_conflict()'s to+ # report.+ if key in index:+ continue+ try:+ requires = list(dist.requires or [])+ except Exception:+ # Fails closed: unreadable Requires-Dist is not a leaf, or a step would skip a+ # closure it never walked.+ return None+ index[key] = (str(version), requires)+ return index+ except Exception:+ return None+++def unsatisfied_closure_requirement(+ req_file: Path,+ index: Optional[Dict[str, Tuple[str, List[str]]]] = None,+ budget_seconds: float = CLOSURE_SCAN_BUDGET_SECONDS,+) -> Optional[str]:+ """The first requirement in *req_file*'s INSTALLED closure that is not met, or None."""+ unmet = closure_unmet_requirements(req_file, index, budget_seconds)+ return unmet[0] if unmet else None+++def closure_unmet_requirements(+ req_file: Path,+ index: Optional[Dict[str, Tuple[str, List[str]]]] = None,+ budget_seconds: float = CLOSURE_SCAN_BUDGET_SECONDS,+) -> List[str]:+ """Every requirement in *req_file*'s INSTALLED closure that is not met; [] if none.++ A missing distribution is reported by name, a version outside its specifier as+ "name version", and a reason the audit could not run as one "<...>" entry that stops the+ walk, so a caller reads any "<" entry as "cannot audit".++ missing_requirements() reads the file's own lines, which stay true after a transitive+ dependency is uninstalled: `mammoth>=1.8.0` is satisfied by a mammoth whose `cobble` is+ gone, and importing it raises. Repairing that is the step being considered for a skip, so+ this follows Requires-Dist down from each line.++ Only for steps installed WITH dependencies: a `--no-deps` step leaves its requirements'+ own dependencies unresolved on purpose, and auditing one would run it forever.++ Fails CLOSED, unlike missing_requirements() and violated_constraints(). Absent+ `packaging`, a direct URL, an unreadable file or a budget overrun are not evidence that+ the closure holds, and being wrong costs one dependency pass rather than a broken import.+ """+ try:+ from packaging.requirements import Requirement+ except Exception:+ return ["<packaging unavailable>"]+ if index is None:+ index = installed_dependency_index()+ if index is None:+ return ["<metadata unreadable>"]+ try:+ lines = Path(req_file).read_text(encoding = "utf-8-sig").splitlines()+ except (OSError, ValueError):+ return ["<requirements unreadable>"]++ deadline = time.monotonic() + budget_seconds if budget_seconds > 0 else None+ # (raw requirement, the extras in scope for it); the top level has no extra.+ pending: List[Tuple[str, Tuple[str, ...]]] = []+ for line in lines:+ text = line.split("#", 1)[0].strip()+ if not text:+ continue+ if text.startswith("-"):+ # A pip flag; an `-r` include would hide requirements from this walk entirely.+ return [f"<flag line: {text}>"]+ pending.append((text, ("",)))++ unmet: List[str] = []+ seen: set = set()+ visits = 0+ while pending:+ visits += 1+ if visits > _CLOSURE_MAX_VISITS:+ return ["<closure too large>"]+ if deadline is not None and time.monotonic() > deadline:+ return ["<closure audit timed out>"]+ raw, contexts = pending.pop()+ try:+ requirement = Requirement(raw)+ except Exception:+ return [f"<unparseable: {raw}>"]+ marker = requirement.marker+ if marker is not None:+ try:+ applies = any(marker.evaluate({"extra": extra}) for extra in contexts)+ except Exception:+ return [f"<unevaluable marker: {raw}>"]+ if not applies:+ continue+ if requirement.url:+ # A direct reference is satisfied by whatever landed; _direct_reference_is_installed+ # answers for the one --no-deps step that has one.+ return [f"{requirement.name} (direct reference)"]+ key = _canonical(requirement.name)+ record = index.get(key)+ if record is None:+ if requirement.name not in unmet:+ unmet.append(requirement.name)+ continue+ version, requires = record+ if requirement.specifier and not requirement.specifier.contains(version, prereleases = True):+ # Recorded, and the walk goes on: what an installed distribution requires is still+ # closure.+ entry = f"{requirement.name} {version}"+ if entry not in unmet:+ unmet.append(entry)+ extras = tuple(sorted(_canonical(extra) for extra in requirement.extras))+ visit_key = (key, extras)+ if visit_key in seen:+ continue+ seen.add(visit_key)+ # foo[bar] puts "bar" in scope for foo's `extra == "bar"` markers. Both spellings: PEP 685+ # normalisation inside markers is newer than many wheels, and matching only "all-files"+ # would drop an `extra == "all_files"` subtree.+ child_contexts = ("", *extras, *requirement.extras)+ pending.extend((child, child_contexts) for child in requires)+ return unmet+++def violated_constraints(+ req_file: Optional[Path] = None, installed: Optional[Dict[str, str]] = None+) -> List[str]:+ """Constrained distributions whose INSTALLED version sits outside the pin.++ A constraints file never asks for an install, so only a resident distribution outside its+ window is a violation. `-c constraints.txt` reaches every constrained step, so a+ constraint that moved under an unchanged requirements file is the one input digest+ equality cannot see.++ Empty on an unreadable file, matching missing_requirements: the caller's other evidence+ still has to pass, and a violation nobody can name would force a full pass every run.+ """+ path = req_file or (requirements_root() / "single-env" / "constraints.txt")+ try:+ lines = path.read_text(encoding = "utf-8-sig").splitlines()+ except (OSError, ValueError):+ return []++ violated: List[str] = []+ for line in lines:+ parsed = _parse_requirement_line(line)+ if parsed is None:+ continue+ name, marker, specifier = parsed+ if not specifier or not _marker_applies(marker):+ continue+ if metadata_conflict(installed_versions(name)):+ # Two records, or an unreadable one: a record violating the pin can stand behind one+ # that meets it. Ambiguous is stale, not absent; the skipped step is what would fix it.+ violated.append(name)+ continue+ version = _installed_version(name, installed)+ # Absent is not a violation; unparseable metadata is, since the skipped step would fix it.+ if version and not _version_satisfies(version, specifier):+ violated.append(name)+ return violated++# Shared between wheels, so one uninstall deletes another's recorded files.# Mirrors _SHARED_NON_RUNTIME_ROOTS in unsloth_cli/_studio_deps.py._SHARED_NON_RUNTIME_ROOTS = frozenset(@@ -695,8 +1299,14 @@ def _scan_payload_files(record = dist.read_text("RECORD")except Exception:continue- # RECORD is optional per the spec, and unreadable says nothing.if not record:+ # uv and pip write RECORD last, so a .dist-info without one was interrupted; only+ # egg-info never had one. Unreadable still says nothing.+ dist_path = str(getattr(dist, "_path", "") or "")+ if dist_path.endswith(".dist-info"):+ found.append(f"{name}: RECORD is missing")+ if len(found) >= limit:+ return foundcontinuetry:anchor = _venv_anchor(Path(dist.locate_file("")))@@ -763,28 +1373,30 @@ def verify_install(installed_conflicts: Optional[Sequence[str]] = None,deep: bool = False,scan_paths: Optional[Sequence[str]] = None,+ manifest: Optional[dict] = 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.+ `manifest` verifies against a manifest the caller already holds (the dependency pass+ checking a parked one) instead of the live file; the verdict is otherwise unchanged.- 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.+ Reason strings are surfaced verbatim by the desktop preflight, so keep them stable.- `deep` adds the payload scan, off by default because an external CLI loads- this module out of the venv it drives: opt-out would spend the desktop- preflight's 10 second budget with no way for an old caller to decline.- `scan_paths` names that venv's site-packages, without which RECORD rows- resolve against the wrong tree.+ Pass `installed`, `installed_conflicts` and the matching `root` / `req_root` to describe+ a venv other than this interpreter's, or the version and dependency checks answer for+ whichever venv the caller runs in.++ `deep` adds the payload scan, off by default because an external CLI loads this module+ out of the venv it drives and opt-out would spend the preflight's 10 second budget with+ no way for an old caller to decline. `scan_paths` names that venv's site-packages,+ without which RECORD rows resolve against the wrong tree."""reqs = req_root or requirements_root()missing = missing_requirements(reqs / BOOT_REQUIREMENT_FILE, installed = installed)deps_ok = not missing- manifest = read_manifest(root)+ if manifest is None:+ manifest = read_manifest(root)manifest_ok = Falsereason: Optional[str] = Nonevanished = False@@ -858,3 +1470,291 @@ def verify_install("missing": missing,"reason": None if (manifest_ok and deps_ok) else (reason or "studio_deps_missing"),}+++# Sidecar directories: flat `pip --target` trees the training worker prepends to sys.path; nothing+# here may import from one. MIRRORED from `_venv_dir_is_valid` + `_sidecar_scan_impl` in+# studio/backend/utils/transformers_version.py, which the stdlib-only installer cannot import. Keep+# them in sync: the runtime self-heal rebuilds on every request otherwise.++# Version-tagged extension suffixes (.cpython-313-darwin.so, .cp313-win_amd64.pyd, .cpython-314t-*).+# Untagged and pypy/graalpy/debug spellings report nothing rather than guess.+_EXT_VERSION_TAG_RE = re.compile(r"\.(?:cpython-|cp)(\d{2,}t?)\b")+# Stable-ABI binaries: fine on a GIL build, a SIGSEGV on a free-threaded one.+_ABI3_EXT_RE = re.compile(r"\.abi3\.(?:so|pyd)$")++SIDECAR_SCAN_BUDGET_SECONDS = 5.0+++def _current_ext_tag() -> str:+ import sysconfig+ return "{}{}{}".format(+ sys.version_info.major,+ sys.version_info.minor,+ "t" if sysconfig.get_config_var("Py_GIL_DISABLED") else "",+ )+++def _sidecar_payload_present(root: Path, dist) -> bool:+ """Whether anything *dist* records as installed is on disk under *root*.++ The fallback for distributions a directory name cannot reach: one shipping top-level+ MODULES (`six.py`) has no directory, and an import name matching neither spelling of the+ project (pillow -> PIL) has one this cannot guess. Reported stale, they make+ `sidecar_is_current` rebuild a healthy several-hundred-MB tree on every update.++ Deliberately weaker than _sidecar_damaged_files, which reads every RECORD row: this only+ answers "did the payload arrive at all". Anything unreadable answers no.+ """+ try:+ recorded = list(dist.files or [])+ except Exception:+ return False+ for entry in recorded:+ parts = tuple(part for part in str(entry).replace("\\", "/").split("/") if part)+ # `..` escapes the tree (pip records ../../bin/hf) and metadata is not payload.+ if (+ not parts+ or ".." in parts+ or parts[0] in ("bin", "Scripts")+ or parts[0].endswith((".dist-info", ".egg-info"))+ ):+ continue+ try:+ if (root / parts[0]).exists():+ return True+ except OSError:+ continue+ return False+++def _sidecar_pin_ok(root: Path, spec: str) -> Optional[str]:+ """None when the pin is satisfied in *root*, else why it is not."""+ from importlib.metadata import distributions++ name, _, wanted = spec.partition("==")+ name = name.strip()+ wanted = wanted.strip()+ if not name:+ return None+ canonical = _canonical(name)+ module = canonical.replace("-", "_")+ # The package tree itself, as _venv_dir_is_valid checks it: a dist-info outlives its payload.+ # Two stats answer most pins; the RECORD fallback is for names that are not a directory.+ directory_present = any((root / candidate).is_dir() for candidate in (module, canonical))+ found: List[str] = []+ payload_present = False+ try:+ for dist in distributions(path = [str(root)]):+ try:+ dist_name = dist.metadata.get("Name") or ""+ except Exception:+ continue+ if _canonical(dist_name) != canonical:+ continue+ found.append(dist.version or "")+ # Only when the directory probe came up empty: reading a RECORD per pin per update is+ # what the stats avoid.+ if not directory_present and not payload_present:+ payload_present = _sidecar_payload_present(root, dist)+ except Exception:+ return f"{name} metadata unreadable"+ # An optional package absent, or a bare dist-info, is the top-up's business, not a rebuild.+ if canonical in OPTIONAL_SIDECAR_PACKAGES and (+ not found or (not directory_present and not payload_present)+ ):+ return None+ if not found:+ return f"{name} not installed"+ if not directory_present and not payload_present:+ return f"{name} directory missing"+ if len(found) > 1:+ return f"{name} has {len(found)} metadata records"+ if wanted and found[0] != wanted:+ return f"{name}=={found[0] or 'unknown'}, want {wanted}"+ return None+++def _sidecar_damaged_files(+ root: Path,+ limit: int = 3,+ budget_seconds: float = SIDECAR_SCAN_BUDGET_SECONDS,+ required: Sequence[str] = (),+) -> List[str]:+ """RECORD rows under a sidecar that are gone, truncated, or built for another CPython.++ Fails open everywhere: the caller's answer to a finding is to delete several hundred+ MB and refetch, so anything unreadable reports nothing rather than guessing. Bounded,+ because no installer wraps this in a timeout and a stalled mount would wedge setup.+ """+ import csv+ import io+ import stat++ deadline = time.monotonic() + budget_seconds if budget_seconds > 0 else None+ ext_tag = _current_ext_tag()+ entries: List[Tuple[str, str, Optional[int], Path, str]] = []+ owners: Dict[str, int] = {}+ required_names = {_canonical(name) for name in required if name}+ recordless: List[str] = []+ try:+ dist_infos = sorted(root.glob("*.dist-info"))+ except OSError:+ return []+ for dist_info in dist_infos:+ name = dist_info.name.split("-")[0]+ # Stricter than _sidecar_scan_impl on purpose: setup can rebuild to converge, the runtime cannot.+ try:+ record = (dist_info / "RECORD").read_text(encoding = "utf-8", errors = "replace")+ except FileNotFoundError:+ # No RECORD under a pinned dist-info is an interrupted install the size check cannot see.+ if _canonical(name) in required_names:+ recordless.append(f"{name}: RECORD is missing")+ continue+ except OSError:+ # Unreadable says nothing about damage.+ continue+ try:+ rows = list(csv.reader(io.StringIO(record)))+ except csv.Error:+ continue+ for row in rows:+ rel = row[0] if row else ""+ if not rel or rel.endswith("/"):+ continue+ if ".dist-info/" in rel or ".egg-info/" in rel or rel.endswith(".pyc"):+ continue+ parts = tuple(part for part in rel.replace("\\", "/").split("/") if part)+ # Console scripts (pip records ../../bin/hf, uv bin/hf) fail CLOSED on a healthy+ # sidecar; nothing here is ever on PATH.+ if (+ rel.startswith("/")+ or (len(rel) > 1 and rel[1] == ":")+ or ".." in parts+ or (parts and parts[0] in ("bin", "Scripts"))+ ):+ continue+ target = root / rel+ key = os.path.normcase(str(target))+ # Before the filter: a dropped row still owns its path.+ owners[key] = owners.get(key, 0) + 1+ if len(parts) > 1 and parts[0] in _SHARED_NON_RUNTIME_ROOTS:+ continue+ recorded: Optional[int] = None+ if len(row) >= 3 and row[2] and parts[-1] not in _INSTALLER_REWRITTEN_NAMES:+ try:+ recorded = int(row[2])+ except ValueError:+ recorded = None+ entries.append((name, rel, recorded, target, key))++ found: List[str] = list(recordless[:limit])+ if len(found) >= limit:+ return found+ for name, rel, recorded, target, key in entries:+ # Every row: a batched deadline let one slow mount overrun it by a minute.+ if deadline is not None and time.monotonic() > deadline:+ return found+ try:+ info = target.stat()+ except (FileNotFoundError, NotADirectoryError):+ found.append(f"{name}: {rel} is missing")+ except OSError:+ # Unreadable is not gone; a wrong answer costs a several-hundred-MB refetch.+ continue+ else:+ if not stat.S_ISREG(info.st_mode):+ found.append(f"{name}: {rel} is not a regular file")+ # A path two distributions claim makes the SIZES ambiguous: larger is a collision, not+ # damage.+ elif owners[key] == 1 and recorded is not None and info.st_size < recorded:+ found.append(f"{name}: {rel} is {info.st_size} bytes, expected {recorded}")+ elif rel.endswith((".so", ".pyd")):+ # The BASENAME alone: a tagged directory (pkg.cp312.libs/) says nothing about the+ # file.+ base = rel.replace("\\", "/").rsplit("/", 1)[-1]+ match = _EXT_VERSION_TAG_RE.search(base)+ if match and match.group(1) != ext_tag:+ found.append(+ f"{name}: {rel} targets cp{match.group(1)}, interpreter is cp{ext_tag}"+ )+ elif match is None and ext_tag.endswith("t") and _ABI3_EXT_RE.search(base):+ found.append(+ f"{name}: {rel} is a stable-ABI build, which free-threaded "+ f"cp{ext_tag} cannot load"+ )+ if len(found) >= limit:+ return found+ return found+++# Mirrors transformers_version: the escape hatch for a false positive must hold on the setup side too.+OPTIONAL_SIDECAR_PACKAGES = frozenset({"tiktoken"})+SIDECAR_FILE_CHECK_ENV = "UNSLOTH_SKIP_SIDECAR_FILE_CHECK"+++def _sidecar_file_check_disabled() -> bool:+ return os.environ.get(SIDECAR_FILE_CHECK_ENV, "").strip().lower() in ("1", "true", "yes", "on")+++def sidecar_is_current(+ venv_dir,+ pins: Sequence[str],+ budget_seconds: float = SIDECAR_SCAN_BUDGET_SECONDS,+) -> Tuple[bool, str]:+ """Whether a transformers sidecar directory already holds exactly *pins*, intact.++ `(True, "")` or `(False, reason)`. The reason is logged by the setup scripts, so+ a rebuild always says what it is repairing.++ *pins* are `name==version` or a bare `name` (present at any version). Every check+ is on-disk evidence: nothing here trusts a previous run's record, because the+ directory is what the next `import transformers` will read.+ """+ root = Path(venv_dir)+ try:+ if not root.is_dir():+ return False, "missing"+ if not os.listdir(root):+ return False, "empty"+ except OSError as exc:+ return False, f"unreadable ({exc.__class__.__name__})"+ # Rebuilding means `rm -rf`: an unowned directory must not be called current.+ if not (root / SIDECAR_OWNED_MARKER).is_file():+ return False, f"no {SIDECAR_OWNED_MARKER} marker"+ for spec in pins:+ problem = _sidecar_pin_ok(root, spec)+ if problem is not None:+ return False, problem+ if _sidecar_file_check_disabled():+ return True, ""+ damaged = _sidecar_damaged_files(+ root,+ budget_seconds = budget_seconds,+ required = [spec.split("==")[0] for spec in pins if "==" in spec],+ )+ if damaged:+ return False, "; ".join(damaged)+ return True, ""+++# CLI shim: one `sidecar_is_current` for both shells, whose reimplementations drifted last time.+# Exit 0 current, 1 not, 2 unimplemented. Both shells also require the marker line: an+# install_manifest.py without this block exits 0 with no output.+_SIDECAR_CLI_MARKER = "sidecar:"+++def _sidecar_cli(argv: Sequence[str]) -> int:+ if len(argv) < 2:+ print("usage: install_manifest.py sidecar <dir> <pin>...", file = sys.stderr)+ return 2+ current, reason = sidecar_is_current(argv[0], tuple(argv[1:]))+ print(f"{_SIDECAR_CLI_MARKER} {'current' if current else reason}")+ return 0 if current else 1+++if __name__ == "__main__":+ if sys.argv[1:2] == ["sidecar"]:+ sys.exit(_sidecar_cli(sys.argv[2:]))+ print(f"usage: {os.path.basename(__file__)} sidecar <dir> <pin>...", file = sys.stderr)+ sys.exit(2)diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 147bd8641d9..98a6a6232ff 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -731,6 +731,23 @@ def _torchcodec_spec_is_installable(spec: str) -> bool:return True+def _codec_spec_is_satisfied(spec: str, installed: str) -> bool:+ """Whether the resident torchcodec already sits inside the pin's window.++ The local tag is deliberately ignored here -- the caller has already decided the+ provenance question through _codec_rebuild, and a `+cu130` suffix makes the version+ fall outside a PyPI-shaped specifier that it in fact satisfies.+ """+ if not installed:+ return False+ base = installed.partition("+")[0]+ try:+ from packaging.requirements import Requirement+ return Requirement(spec).specifier.contains(base, prereleases = True)+ except Exception: # noqa: BLE001 - no packaging, or a version it cannot parse+ return False++def _select_torchcodec_spec(torch_version: "str | None") -> "str | None":"""Map an installed torch version (e.g. '2.11.0+cu128') to the torchcodec spec builtagainst it, or None below the oldest known torch minor. Falls back to@@ -1030,6 +1047,197 @@ def _bnb_rocm_prerelease_url() -> str | None:return _BNB_ROCM_PRERELEASE_URLS.get(arch)+# What this pass last installed bitsandbytes from. The second _ensure_rocm_torch() must not+# repeat the download yet must repair a bnb the steps between re-resolved, so this records WHAT+# landed, not merely THAT something did.+_BNB_ROCM_PASS_PROVENANCE: "str | None" = None+# What the release URL served when this pass last looked (_bnb_asset_identity): the URL alone cannot+# identify the build.+_BNB_ROCM_PASS_ASSET: "str | None" = None+++def _installed_direct_url(dist_name: str) -> "str | None":+ """The URL pip recorded for a distribution installed from one, or None.++ PEP 610: an install from a wheel URL writes direct_url.json beside the metadata,+ and it is the only durable record of WHERE a wheel came from -- the version cannot+ say, because the same version is published to PyPI and to a release page.+ """+ try:+ from importlib.metadata import distribution+ recorded = distribution(dist_name).read_text("direct_url.json")+ except Exception: # noqa: BLE001 - absent metadata is a reason to install+ return None+ if not recorded:+ return None+ try:+ payload = json.loads(recorded)+ except ValueError:+ return None+ if not isinstance(payload, dict):+ return None+ url = payload.get("url")+ return str(url) if isinstance(url, str) and url else None+++def _bnb_asset_identity(url: str) -> "str | None":+ """What is published at *url* right now, as an opaque string, or None if unreachable.++ The preferred ROCm wheel comes from bitsandbytes' continuous-release_main release, whose+ asset PATH never changes while its bytes do, so the URL pip recorded says where the wheel+ came from, not which one. One HEAD follows the redirect and reads the ETag and size of the+ current bytes; the pass records that beside the provenance and the next one compares.+ """+ import urllib.request++ try:+ request = urllib.request.Request(+ url, method = "HEAD", headers = {"User-Agent": "unsloth-studio-installer"}+ )+ with urllib.request.urlopen(request, timeout = 15) as response:+ etag = (response.headers.get("ETag") or "").strip()+ size = (response.headers.get("Content-Length") or "").strip()+ except Exception: # noqa: BLE001 - unreachable is "cannot say"; the caller decides+ return None+ if not etag and not size:+ return None+ return f"{etag}|{size}"+++def _bnb_wheel_version(url: str) -> "str | None":+ """The version in a bnb wheel filename, e.g. 1.33.7.preview.++ Compared textually against the installed version only as a fallback, and normalised+ the way PEP 440 does for this one wheel: its filename says 1.33.7.preview and its+ metadata says 1.33.7rc0, which is the same release spelled two ways.+ """+ name = url.rsplit("/", 1)[-1]+ parts = name.split("-")+ return parts[1] if len(parts) > 2 and parts[0] and parts[1] else None+++def _installed_bnb_provenance() -> "str | None":+ """What the resident bitsandbytes IS, or None when there is nothing to keep.++ An opaque string compared only against another produced the same way: the URL pip+ recorded, or the version when nothing did. It says nothing about whether that is the RIGHT+ build, which is the caller's question; keeping the two apart lets a recorded provenance be+ checked against both what is on disk and what this run would install.+ """+ installed = _installed_distribution_version("bitsandbytes")+ if not installed:+ return None+ # Metadata survives a quarantined payload; the skipped reinstall is what would restore it.+ try:+ if install_manifest.damaged_payload_files("bitsandbytes", limit = 1):+ return None+ except Exception: # noqa: BLE001 - an environment nobody can scan is not evidence+ return None+ recorded_url = _installed_direct_url("bitsandbytes")+ return f"url:{recorded_url}" if recorded_url else f"version:{installed}"+++def _bnb_provenance_matches_request(provenance: str, url: "str | None") -> bool:+ """Whether *provenance* describes a build one of the two install paths would land."""+ kind, _, value = provenance.partition(":")+ if kind == "url":+ # The pre-release wheel, proven by its URL; a bumped URL fetches the new wheel once.+ return url is not None and value == url+ # No direct_url.json: an older installer, or the PyPI fallback. The filename's version+ # identifies the first, the pin the second; reinstalling the fallback buys nothing.+ if url is not None:+ wheel_version = _bnb_wheel_version(url)+ if wheel_version is not None and _versions_are_same_release(value, wheel_version):+ return True+ return _spec_is_satisfied(_BNB_ROCM_PYPI_FALLBACK, value)+++def _refuse_bnb(reason: str) -> bool:+ """Say why the resident ROCm bitsandbytes is fetched again, then answer False."""+ if VERBOSE:+ _note(f"bitsandbytes (ROCm): {reason} -- reinstalling")+ return False+++def _bnb_rocm_install_is_current(url: "str | None") -> bool:+ """Whether this pass may leave bitsandbytes exactly as it found it.++ --force-reinstall from a release URL downloads the wheel before it can notice it+ already has it, and this decision is reached twice per dependency pass, so an AMD+ host paid the whole wheel twice on every no-op `studio update`.+ """+ global _BNB_ROCM_PASS_ASSET+ provenance = _installed_bnb_provenance()+ if provenance is None:+ return _refuse_bnb("no usable bitsandbytes on disk")+ if _BNB_ROCM_PASS_PROVENANCE is not None:+ # Already settled this pass: the second call skips only while the disk still holds what the+ # first left, since the steps between them can re-resolve it.+ return provenance == _BNB_ROCM_PASS_PROVENANCE+ if not _may_skip_on_evidence():+ return _refuse_bnb("no dependency pass evidence")+ # The last run must have recorded landing this build deliberately: a generic wheel another step+ # pulled in reads identically to the PyPI fallback.+ recorded = (_PASS_EVIDENCE or {}).get("bnb_rocm")+ if not isinstance(recorded, str) or recorded != provenance:+ return _refuse_bnb(f"last run recorded {recorded!r}, on disk {provenance!r}")+ if not _bnb_provenance_matches_request(provenance, url):+ return _refuse_bnb(f"{provenance!r} is not the build this run installs ({url})")+ if provenance.startswith("url:") and url is not None:+ # Same URL is not the same wheel: continuous-release_main republishes under a fixed path.+ recorded_asset = (_PASS_EVIDENCE or {}).get("bnb_rocm_asset")+ if not isinstance(recorded_asset, str) or not recorded_asset:+ return _refuse_bnb("the last run did not record which bytes the release URL served")+ published = _bnb_asset_identity(url)+ if published is None:+ # Offline: the reinstall could not fetch either, and the build on disk was deliberate.+ if VERBOSE:+ _note("bitsandbytes (ROCm): release page unreachable -- keeping the recorded build")+ _BNB_ROCM_PASS_ASSET = recorded_asset+ return True+ if published != recorded_asset:+ return _refuse_bnb(+ f"the wheel at {url} was republished ({recorded_asset} -> {published})"+ )+ _BNB_ROCM_PASS_ASSET = published+ return True+++def _record_bnb_rocm_provenance() -> None:+ """What this pass leaves installed, for its own second call and for the manifest."""+ global _BNB_ROCM_PASS_PROVENANCE, _BNB_ROCM_PASS_ASSET+ _BNB_ROCM_PASS_PROVENANCE = _installed_bnb_provenance()+ if _BNB_ROCM_PASS_ASSET is not None:+ # The keep decision already read the asset this pass.+ return+ url = _installed_direct_url("bitsandbytes")+ _BNB_ROCM_PASS_ASSET = _bnb_asset_identity(url) if url else None+++def _versions_are_same_release(installed: str, wheel: str) -> bool:+ """Whether two spellings of a version name the same release.++ bnb's continuous-release wheel is 1.33.7.preview in its filename and 1.33.7rc0 in+ its metadata, so a string compare says no and a PEP 440 parse says yes.+ """+ if installed == wheel:+ return True+ try:+ from packaging.version import Version+ return Version(installed) == Version(wheel)+ except Exception: # noqa: BLE001 - unparseable is not a match+ return False+++def _spec_is_satisfied(spec: str, installed: str) -> bool:+ """Whether *installed* satisfies a requirement string such as `name>=0.50.0`."""+ try:+ from packaging.requirements import Requirement+ return Requirement(spec).specifier.contains(installed, prereleases = True)+ except Exception: # noqa: BLE001 - no packaging, or a version it cannot parse+ return False++def _bnb_rocm_arch_has_binary() -> bool:"""False on aarch64: bitsandbytes ships no ROCm kernels there at any version.The PyPI 0.50.0 and continuous-release_main aarch64 wheels both carry only@@ -3044,33 +3252,45 @@ def _install_bnb_windows_rocm() -> bool:ROCm build; before 0.50.0 it was CUDA-only, which is why there was none."""_bnb_win_url = _BNB_ROCM_PRERELEASE_URLS.get("win_amd64")- _ok = False- if _bnb_win_url is not None:- _ok = pip_install_try(- "bitsandbytes (AMD Windows, pre-release main)",- "--force-reinstall",- "--no-cache-dir",- "--no-deps",- _bnb_win_url,- constrain = False,- force_pip = True,- )- if not _ok:- _safe_print(- _red(- " bnb pre-release install failed; falling back to PyPI "- f"{_BNB_ROCM_PYPI_FALLBACK}, which carries the ROCm 4-bit fix"+ # 39 MB per call on gfx1151 Windows: --force-reinstall downloads before it can notice the wheel+ # is already installed. The BNB_ROCM_VERSION work below reads the DLL and still runs.+ if _bnb_rocm_install_is_current(_bnb_win_url):+ _safe_print(_dim(" bitsandbytes (AMD Windows) is already this build -- keeping it"))+ # Recorded on the skip too, or the manifest would forget and the next update refetch.+ _record_bnb_rocm_provenance()+ _ok = True+ else:+ _ok = False+ if _bnb_win_url is not None:+ _ok = pip_install_try(+ "bitsandbytes (AMD Windows, pre-release main)",+ "--force-reinstall",+ "--no-cache-dir",+ "--no-deps",+ _bnb_win_url,+ constrain = False,+ force_pip = True,+ )+ if not _ok:+ _safe_print(+ _red(+ " bnb pre-release install failed; falling back to PyPI "+ f"{_BNB_ROCM_PYPI_FALLBACK}, which carries the ROCm 4-bit fix"+ ))+ if not _ok:+ _ok = pip_install_try(+ "bitsandbytes (AMD Windows)",+ "--force-reinstall",+ "--no-cache-dir",+ "--no-deps",+ _BNB_ROCM_PYPI_FALLBACK,+ constrain = False,)- if not _ok:- _ok = pip_install_try(- "bitsandbytes (AMD Windows)",- "--force-reinstall",- "--no-cache-dir",- "--no-deps",- _BNB_ROCM_PYPI_FALLBACK,- constrain = False,- )+ # Only after an install landed, or two failed installs would record the new asset identity+ # against the old wheel.+ if _ok:+ _record_bnb_rocm_provenance()if not _ok:return False# BNB_ROCM_VERSION from the DLL suffix (the wheel may ship "72" while torch reports 7.13).@@ -3835,6 +4055,7 @@ def _ensure_xpu_triton() -> None:))return+ _count_install_action()removed = subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "triton"],stdout = subprocess.DEVNULL,@@ -4364,6 +4585,7 @@ def _uninstall_distribution(name: str) -> bool:cmd.extend(["--python", sys.executable, name])else:cmd = [sys.executable, "-m", "pip", "uninstall", "-y", name]+ _count_install_action()removed = subprocess.run(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL)return removed.returncode == 0@@ -4404,8 +4626,18 @@ def _install_torchao_for_torch(torch_version: "str | None") -> None:# --no-deps skips nothing today (no torchao release declares a runtime torch dependency)# and guards the second caller, which runs right after the torch repair.args = ["--no-deps", "--no-cache-dir"]- if _pin_needs_reinstall(spec, _torch_index_tag(torch_version) if index else ""):+ needs_reinstall = _pin_needs_reinstall(spec, _torch_index_tag(torch_version) if index else "")+ if _may_skip_on_evidence() and not needs_reinstall:+ # This exact version from this exact index is what the pin asserts, and running it resolved+ # against the index on every update. Evidence first: a forced pass asks for the install.+ _note(f"torch {torch_version or 'unknown'} detected -- {spec} is already installed")+ _record_step("torchao", "skipped")+ return+ # Keyed off the pin alone, as before the skip existed: a matching build with no evidence+ # behind it (every install's first update here) would re-download a satisfied wheel.+ if needs_reinstall:args.insert(0, "--force-reinstall")+ _record_step("torchao", "ran")_note(f"torch {torch_version or 'unknown'} detected -- installing {spec}"# Redacted for display only; the installer below still gets the exact URL.@@ -5482,6 +5714,7 @@ def _ensure_rocm_torch() -> None:# (present before the base install) is left untouched.if _GFX906_BNB_ABSENT_BEFORE_BASE and _bitsandbytes_installed():_safe_print(_dim(" gfx906: removing generic bitsandbytes pulled in as a dependency"))+ _count_install_action()subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "bitsandbytes"],capture_output = True,@@ -5489,36 +5722,44 @@ def _ensure_rocm_torch() -> None:# bitsandbytes only when torch links ROCm; the pre-release wheel (bnb #1887) needs pip, not uv.elif rocm_torch_ready:_bnb_url = _bnb_rocm_prerelease_url()- _bnb_installed = False- if _bnb_url is not None:- _bnb_installed = pip_install_try(- "bitsandbytes (AMD, pre-release main)",- "--force-reinstall",- "--no-cache-dir",- "--no-deps",- _bnb_url,- constrain = False,- force_pip = True,- )- if not _bnb_installed:- _fallback_note = (- ", which carries the ROCm 4-bit fix" if _bnb_rocm_arch_has_binary() else ""+ # --force-reinstall from a URL fetches before it can decide: 43 MB per call, twice per pass,+ # on every no-op update (gfx1151).+ if _bnb_rocm_install_is_current(_bnb_url):+ _safe_print(_dim(" bitsandbytes (AMD) is already this build -- keeping it"))+ # Recorded on the skip too, or the manifest would forget and the next update refetch.+ _record_bnb_rocm_provenance()+ else:+ _bnb_installed = False+ if _bnb_url is not None:+ _bnb_installed = pip_install_try(+ "bitsandbytes (AMD, pre-release main)",+ "--force-reinstall",+ "--no-cache-dir",+ "--no-deps",+ _bnb_url,+ constrain = False,+ force_pip = True,)- _safe_print(- _red(- " bnb pre-release install failed; falling back to PyPI "- f"{_BNB_ROCM_PYPI_FALLBACK}{_fallback_note}"+ if not _bnb_installed:+ _fallback_note = (+ ", which carries the ROCm 4-bit fix" if _bnb_rocm_arch_has_binary() else ""+ )+ _safe_print(+ _red(+ " bnb pre-release install failed; falling back to PyPI "+ f"{_BNB_ROCM_PYPI_FALLBACK}{_fallback_note}"+ ))+ if not _bnb_installed:+ pip_install(+ "bitsandbytes (AMD)",+ "--force-reinstall",+ "--no-cache-dir",+ "--no-deps",+ _BNB_ROCM_PYPI_FALLBACK,+ constrain = False,)- if not _bnb_installed:- pip_install(- "bitsandbytes (AMD)",- "--force-reinstall",- "--no-cache-dir",- "--no-deps",- _BNB_ROCM_PYPI_FALLBACK,- constrain = False,- )+ _record_bnb_rocm_provenance()if not _bnb_rocm_arch_has_binary():_safe_print(_red(@@ -5949,6 +6190,9 @@ def _purge_recordless_distributions(output: "bytes | str | None") -> list[str]:shutil.rmtree(dist_info)except OSError:continue+ # What is installed just changed. Counted here, not at entry, so the usual no-purge case+ # keeps the cached constraint answer and the skipped `pip check`.+ _count_install_action()cleared.append(dist_info.name)return cleared@@ -6066,6 +6310,7 @@ def _remove_rejected_flash_attn() -> bool:cmd.extend(["--python", sys.executable, "flash-attn"])else:cmd = [sys.executable, "-m", "pip", "uninstall", "-y", "flash-attn"]+ _count_install_action()removed = subprocess.run(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL)return removed.returncode == 0@@ -6083,6 +6328,8 @@ def _ensure_flash_attn() -> None:env = probe_torch_wheel_env()wheel_url = _build_flash_attn_wheel_url(env) if env else Noneif wheel_url and url_exists(wheel_url):+ # Counted: it lands a distribution, so the caches keyed on the counter must be rebuilt.+ _count_install_action()for installer, wheel_result in install_wheel(wheel_url,python_executable = sys.executable,@@ -6132,23 +6379,30 @@ UV_NEEDS_SYSTEM = False # Set by _bootstrap_uv() via probedef _bootstrap_uv() -> bool:- """Check if uv is available and probe whether --system is needed."""+ """Check if uv is available and probe whether --system is needed.++ `pip freeze`, not `pip install --dry-run pip`: the question is only whether this uv can+ address this interpreter, and a dry-run answers it by RESOLVING pip against the index.+ That is a PyPI round-trip on every run, most of the 12 s the "pip bootstrap" step cost,+ and it fails offline where uv could have served from its cache. freeze reads the venv's+ own metadata: no resolution, no network, same answer.+ """global UV_NEEDS_SYSTEMif not shutil.which("uv"):return False# Explicit --python: uv can ignore the activated venv on some platforms.probe = subprocess.run(- ["uv", "pip", "install", "--dry-run", "--python", sys.executable, "pip"],- stdout = subprocess.PIPE,- stderr = subprocess.STDOUT,+ ["uv", "pip", "freeze", "--python", sys.executable],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,**_windows_hidden_subprocess_kwargs(),)if probe.returncode != 0:# Retry with --system (some envs need it when uv can't find a venv)probe_sys = subprocess.run(- ["uv", "pip", "install", "--dry-run", "--system", "pip"],- stdout = subprocess.PIPE,- stderr = subprocess.STDOUT,+ ["uv", "pip", "freeze", "--system"],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,**_windows_hidden_subprocess_kwargs(),)if probe_sys.returncode != 0:@@ -6157,6 +6411,42 @@ def _bootstrap_uv() -> bool:return True+def _venv_pip_is_usable() -> bool:+ """Whether this interpreter already has a pip new enough for the pass.++ Read from metadata rather than by spawning it: the bootstrap below reinstalls pip from the+ index on every run, a download and a resolve for a package nothing changed. 23.0 is the+ floor because the constraint and override handling the pass relies on predates it+ comfortably; a fresh uv venv has no pip at all and still bootstraps.+ """+ try:+ if importlib.util.find_spec("pip") is None:+ return False+ except (ImportError, ValueError):+ return False+ installed = _installed_distribution_version("pip")+ if not installed:+ return False+ try:+ major = int(re.match(r"\d+", installed).group(0))+ except (AttributeError, ValueError):+ return False+ if major < 23:+ return False+ # Metadata survives a truncated pip, and everything without uv is `python -m pip`: one bounded+ # launch settles it.+ try:+ probe = subprocess.run(+ [sys.executable, "-m", "pip", "--version"],+ capture_output = True,+ timeout = 60,+ **_windows_hidden_subprocess_kwargs(),+ )+ except (OSError, subprocess.SubprocessError):+ return False+ return probe.returncode == 0++def _filter_requirements(req: Path, skip: set[str]) -> Path:"""Return a temp copy, adjacent when writable, with certain packages removed."""lines = req.read_text(encoding = "utf-8").splitlines(keepends = True)@@ -6769,6 +7059,9 @@ def _repair_duplicate_core_metadata()return Falseif invalid_paths or backups:+ # Metadata changed outside _uninstall_distribution / pip_install*, so the constraint+ # cache is retired here at the mutation, not at entry where every no-op would pay.+ _count_install_action()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@@ -6813,6 +7106,9 @@ def _repair_duplicate_core_metadata(removed_any = Falsewhile record_count:+ # Counted BEFORE the command, as _uninstall_distribution: a failed uninstall can+ # still have removed files.+ _count_install_action()if not _run_ok(f"Removing an installed metadata record for {name}",[sys.executable, "-m", "pip", "uninstall", "-y", name],@@ -6944,9 +7240,20 @@ def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:cmd.append(arg)if upgrade:cmd += ["--upgrade", "--upgrade-strategy", "only-if-needed"]+# Every current caller also names these as positionals or via -r, but a# future one might not, and pip would then upgrade nothing.- cmd += [name for name in upgrade if name not in cmd]+ # By canonical project name: `--upgrade-package mlx` beside `mlx==0.32.1` is one project,+ # and pip refuses a double requirement where uv does not.+ def _project(requirement: str) -> str:+ # _requirement_name stops at "==" and "@"; a range (mlx-vlm>=0.4.4,<0.7.0) needs the+ # rest.+ return _canonical_package_name(+ re.split(r"[<>=!~;\[ ]", _requirement_name(requirement), maxsplit = 1)[0]+ )++ named = {_project(arg) for arg in cmd if arg and not arg.startswith("-")}+ cmd += [name for name in upgrade if _project(name) not in named]return cmd@@ -7350,6 +7657,8 @@ def pip_install_try(# Same reason as pip_install: this installs torch too (the Windows AMD ROCm trio),# so the memoized classification must not survive it._invalidate_torch_runtime_probe()+ # Counted before the command: a failed install can still have moved metadata.+ _count_install_action()constraint_args_pip: list[str] = []constraint_args_uv: list[str] = []if constrain and CONSTRAINTS.is_file():@@ -7390,29 +7699,20 @@ def pip_install(# Any pip operation can change which torch is installed, so the memoized# classification must not outlive it._invalidate_torch_runtime_probe()+ _count_install_action()constraint_args_pip: list[str] = []constraint_args_uv: list[str] = []if constrain and CONSTRAINTS.is_file():constraint_args_pip = ["-c", str(CONSTRAINTS)]constraint_args_uv = ["-c", _uv_safe_path(CONSTRAINTS)]+ # _effective_requirements also drops torchcodec where no wheel exists (Linux aarch64,+ # Windows ARM64, Intel Mac). The gate audits the file this installs from, or a filtered+ # package reads as missing on every such host.actual_req = reqtemp_reqs: list[Path] = []- if req is not None and IS_WINDOWS and WINDOWS_SKIP_PACKAGES:- actual_req = _filter_requirements(req, WINDOWS_SKIP_PACKAGES)- temp_reqs.append(actual_req)- if actual_req is not None and NO_TORCH and NO_TORCH_SKIP_PACKAGES:- actual_req = _filter_requirements(actual_req, NO_TORCH_SKIP_PACKAGES)- temp_reqs.append(actual_req)- if actual_req is not None and PLATFORM_LACKS_TORCHCODEC_WHEEL:- # Linux aarch64 / Windows ARM64 / Intel Mac have no torchcodec- # wheel. `unsloth studio update --local` does not pass- # --no-torch, so the NO_TORCH filter above does not fire; do- # the targeted skip independently so the audio extras step- # does not take down the whole update. Nothing feeds torchcodec- # now; this stays for any file that reintroduces it.- actual_req = _filter_requirements(actual_req, {"torchcodec"})- temp_reqs.append(actual_req)+ if req is not None:+ actual_req, temp_reqs = _effective_requirements(req)req_args_pip: list[str] = []req_args_uv: list[str] = []if actual_req is not None:@@ -7522,6 +7822,92 @@ def _has_working_git() -> bool:return False+# The MLX stack, one place; test_mlx_install.py compares it with utils/mlx_repair.py's+# _MLX_INSTALL_SPECS.+_MLX_PINS: tuple[str, ...] = ("mlx==0.32.1", "mlx-metal==0.32.1", "mlx-lm==0.31.3")+_MLX_VLM_SPEC = "mlx-vlm>=0.4.4,<0.7.0"+_MLX_NAMES: tuple[str, ...] = tuple(spec.partition("==")[0] for spec in _MLX_PINS) + ("mlx-vlm",)+++def _mlx_stack_is_current() -> bool:+ """Whether the three exact pins and mlx-vlm's range are all already satisfied.++ Without this the step ran `--upgrade` on every update and fetched ~60 MB of wheels+ it then discarded, because the pins were already exact and the upgrade only moved+ mlx-vlm inside a range it was already in.+ """+ if not all(_exact_distribution_spec_is_installed(spec) for spec in _MLX_PINS):+ return False+ installed = _installed_distribution_version("mlx-vlm")+ if not installed:+ return False+ try:+ from packaging.requirements import Requirement+ if not Requirement(_MLX_VLM_SPEC).specifier.contains(installed, prereleases = True):+ return False+ except Exception: # noqa: BLE001 - no packaging, or a version it cannot parse+ return False+ # The four pins are satisfied; their dependencies are a separate question. This step+ # installs WITH dependencies, so it repairs an mlx-vlm whose miniaudio is gone, and audits+ # its closure for the same reason the requirements steps audit theirs.+ return not _mlx_closure_unmet()+++def _overridden_project_names() -> "set[str]":+ """Canonical names the bundled macOS arm64 override file replaces every requirement on."""+ names: set[str] = set()+ try:+ text = _MLX_OVERRIDES.read_text(encoding = "utf-8-sig")+ except (OSError, ValueError, UnicodeDecodeError):+ return names+ for raw in text.splitlines():+ line = raw.split("#", 1)[0].strip()+ if not line or line.startswith("-"):+ continue+ head = re.split(r"[<>=!~;\[ ]", line, maxsplit = 1)[0].strip()+ if head:+ names.add(install_manifest._canonical(head))+ return names+++def _mlx_closure_unmet() -> bool:+ """Whether anything in the MLX pins' installed closure is missing or outside its pin."""+ handle = None+ try:+ import tempfile as _tempfile # noqa: PLC0415++ # mkstemp hands back an OPEN descriptor. Left open it leaks one per update, and on+ # Windows it also holds the file, so the unlink below cannot clear it.+ _fd, _name = _tempfile.mkstemp(prefix = "unsloth-mlx-", suffix = ".txt", text = True)+ os.close(_fd)+ handle = Path(_name)+ handle.write_text("\n".join([*_MLX_PINS, _MLX_VLM_SPEC]) + "\n", encoding = "utf-8")+ unmet = install_manifest.closure_unmet_requirements(handle, _installed_index())+ # An override REPLACES every requirement on the package it names, so the installed+ # version is the override's, not the one mlx-vlm's metadata asks for. Read raw, that+ # disagreement is permanent and this step runs on every update. An overridden package+ # that is ABSENT still counts: the step is what installs it.+ overridden = _overridden_project_names()+ if overridden:+ unmet = [+ entry+ for entry in unmet+ if " " not in entry+ or install_manifest._canonical(entry.split(" ", 1)[0]) not in overridden+ ]+ except Exception: # noqa: BLE001 - an audit that cannot run is a reason to run the step+ return True+ finally:+ if handle is not None:+ try:+ handle.unlink(missing_ok = True)+ except OSError:+ pass+ if unmet and VERBOSE:+ _note(f"MLX stack: {unmet[0]} is not satisfied -- running the step")+ return bool(unmet)++_MLX_HEALTH_PROBE = ("import json, sys;""sys.path.insert(0, sys.argv[1]);"@@ -7530,16 +7916,126 @@ _MLX_HEALTH_PROBE = ()-def _report_mlx_stack_health() -> None:+# What the probe imports through mlx_lm and mlx_vlm besides the MLX pins: ranged, so one can move+# with every step still satisfied, and a recorded verdict vouched for an import it never ran.+_MLX_IMPORTED_DEPENDENCIES = (+ "transformers",+ "tokenizers",+ "huggingface-hub",+ "safetensors",+ "numpy",+ "pillow",+ "protobuf",+ "sentencepiece",+)+++def _mlx_health_fingerprint() -> dict:+ """What a recorded MLX verdict is only valid for."""+ return {+ "pins": list(_MLX_PINS) + [_MLX_VLM_SPEC],+ "python": _installer_python_tag(),+ "mlx_vlm": _installed_distribution_version("mlx-vlm") or "",+ # Versions as installed; an older record without this key is probed once and rewritten.+ "imports": {+ name: _installed_distribution_version(name) or "" for name in _MLX_IMPORTED_DEPENDENCIES+ },+ }+++def _mlx_payload_present() -> bool:+ """The MLX stack's payload is on disk as its RECORDs describe it, without importing it.++ The recorded verdict below is keyed on pins and interpreter, which a payload deleted or+ truncated after the pass leaves unchanged, and find_spec sees only the top-level+ directory. So every file each RECORD names is checked for presence and size (bytecode+ excepted, it is regenerated): a few hundred stats, well under the import the probe pays.+ """+ try:+ import importlib.metadata+ import importlib.util++ for name in ("mlx", "mlx_lm", "mlx_vlm", "transformers"):+ if importlib.util.find_spec(name) is None:+ return False+ # mlx-metal too: its payload is the Metal library the probe would exercise.+ for dist_name in ("mlx", "mlx-metal", "mlx-lm", "mlx-vlm"):+ # No RECORD is not "present".+ if _recorded_payload_damaged(dist_name) is not False:+ return False+ # And what the probe imports through them: a truncated tokenizers keeps its version and+ # metadata, and only the import would notice. Not installed at all is the probe's to report.+ for dist_name in _MLX_IMPORTED_DEPENDENCIES:+ if not _installed_distribution_version(dist_name):+ continue+ if _recorded_payload_damaged(dist_name) is not False:+ return False+ return True+ except Exception: # noqa: BLE001 - not finding it is the probe's job to explain+ return False+++def _recorded_payload_damaged(dist_name: str) -> "bool | None":+ """Whether a file the distribution's RECORD names is gone or has another size.++ None when the distribution has no readable RECORD, which is not evidence of an intact+ payload. Read from RECORD rows, not Distribution.files: CPython 3.13 drops paths that no+ longer exist from `files`, so a deleted file is never found through it. Bytecode is left+ out (recompiled after install); rows without a size say nothing.+ """+ import csv+ import io++ dist = importlib.metadata.distribution(dist_name)+ record = dist.read_text("RECORD")+ if not record:+ return None+ for row in csv.reader(io.StringIO(record)):+ if len(row) < 3 or not row[0] or row[0].endswith(".pyc") or not row[2]:+ continue+ try:+ size = int(row[2])+ except ValueError:+ continue+ try:+ if os.stat(dist.locate_file(row[0])).st_size != size:+ return True+ except OSError:+ return True+ return False+++def _report_mlx_stack_health(skipped: bool = False) -> None:"""Name what would keep Train off on this Apple Silicon host, if anything.- Advisory only: the install has already succeeded, chat still works, and the- background self-heal gets another go at startup. It just must not be silent,- which is the whole of the reported "Train is blacked out after an update".+ Advisory only: the install has succeeded, chat still works and the self-heal gets another+ go at startup. It just must not be silent, which is the whole of "Train is blacked out+ after an update".- Run out of process: the probe imports mlx, mlx_lm and mlx_vlm, and a half- installed one of those can abort rather than raise.+ Run out of process, since a half-installed mlx can abort rather than raise. That costs a+ full torch and mlx import, so the recorded verdict stands when the MLX step was skipped,+ nothing else installed anything, and the last run recorded a healthy stack for these exact+ pins and this interpreter. Anything else runs the probe."""+ fingerprint = _mlx_health_fingerprint()+ recorded = (_PASS_EVIDENCE or {}).get("mlx_health")+ if (+ skipped+ # A later step that moved transformers or tokenizers can break the import with every pin+ # unchanged: only a pass that installed nothing keeps its recorded verdict.+ and _INSTALL_ACTIONS == 0+ and isinstance(recorded, dict)+ and recorded.get("ok") is True+ and recorded.get("pins") == fingerprint["pins"]+ and recorded.get("python") == fingerprint["python"]+ and recorded.get("mlx_vlm") == fingerprint["mlx_vlm"]+ and recorded.get("imports") == fingerprint["imports"]+ and _mlx_payload_present()+ ):+ _step("mlx", "training stack ready")+ # Written back so the record does not age out of the manifest.+ install_manifest.update_manifest(mlx_health = {**fingerprint, "ok": True})+ returnbackend = str(SCRIPT_DIR / "backend")try:probe = subprocess.run(@@ -7558,6 +8054,9 @@ def _report_mlx_stack_health() -> None:if blockers is None:_step("mlx", "could not verify the MLX stack", _dim)return+ # After the manifest is written, so a kill during the probe's 180 s timeout cannot lose a+ # finished install; update_manifest never raises and never creates one.+ install_manifest.update_manifest(mlx_health = {**fingerprint, "ok": not blockers})if not blockers:_step("mlx", "training stack ready")return@@ -7566,49 +8065,949 @@ def _report_mlx_stack_health() -> None:_step("", blocker, _cyan)-def install_python_stack() -> int:- global USE_UV, _STEP, _TOTAL, _PROGRESS_LINE_ACTIVE- _STEP = 0- # An aborted earlier run leaves it set, and every _safe_print() consumes it --- # the first message would get a stray newline.- _PROGRESS_LINE_ACTIVE = False+# The idempotent dependency pass. A skip is legal only when (a) the previous run recorded this+# exact work, (b) the inputs are byte-identical and (c) a cheap on-disk check of the OUTPUT+# passes. When in doubt, do the work: a wrong skip ships a venv that dies on `import structlog`.- # install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling the core packages;- # `studio update` does NOT, so unsloth + unsloth-zoo are reinstalled to pick- # up new versions. Shared base.txt requirements are handled independently.- skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"- # --package installs a different package name (for testing).- 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", "")- # read where the overlay runs, so UNSLOTH_ZOO_REF reaches the metadata-repair- # reinstall path too, not just the two calls below- # Clean-machine CI overlays only unsloth, not the full local source pair.- ci_source_overlay = os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY", "")- # Three lettered steps on top of the numbered ones: anyio repair (8b), diffusers pin- # (11b), torchcodec (13b, which reports progress on every branch including its skips).- base_total = 13 if IS_WINDOWS else 14- if IS_MACOS:- base_total -= 1 # triton step is skipped on macOS- if not IS_MACOS and not NO_TORCH:- base_total += 1 # ROCm torch check (step 2b), non-macOS- if not IS_WINDOWS:- base_total += 2 # flash-attn + torch final repair (step 13), Linux- else:- base_total += 1 # torch flavor invariant (step 13w), Windows- if IS_MAC_ARM and not NO_TORCH:- base_total += 1 # MLX stack, same gate as the step itself- base_requirements = _shared_base_requirements() if skip_base else None- # Core packages and shared base requirements occupy one progress slot. A- # shell-installer handoff skips that slot only while base.txt has no work.- _TOTAL = base_total - int(skip_base and base_requirements is None)+_FULL_DEPS_ENV = "UNSLOTH_STUDIO_FULL_DEPS"- # Drop it up front: a missing manifest is what tells the CLI, setup.sh and- # the preflight that an interrupted run left the venv half-built. Stop if it- # survives rather than mutate the venv behind a marker that still verifies.- if not install_manifest.remove_manifest():- _safe_print(- f"error: could not remove the stale {install_manifest.MANIFEST_NAME} in "+# Real install/uninstall commands this pass ran; `pip check` and the metadata patch are gated on it.+_INSTALL_ACTIONS = 0+# Last run's evidence, or None when this pass must do everything.+_PASS_EVIDENCE: "dict | None" = None+# False when a peer is already inside a pass on this venv, which refuses the evidence below.+_PASS_UNCONTENDED = True+# What this pass did per step. Only "ran" and "skipped" let the NEXT run skip.+_STEP_RESULTS: "dict[str, str]" = {}+# The with-deps requirements steps this pass audited, for the closure record below.+_AUDITED_STEPS: "dict[str, Path]" = {}+_CONSTRAINTS_CACHE: "tuple[int, list[str]] | None" = None+++def _count_install_action() -> None:+ """Called by every command that can change what is installed."""+ global _INSTALL_ACTIONS+ _INSTALL_ACTIONS += 1+++def _full_deps_requested() -> bool:+ """The escape hatch. A skip nobody can turn off is a bug nobody can work around."""+ return os.environ.get(_FULL_DEPS_ENV, "").strip().lower() in ("1", "true", "yes", "on")+++def _record_step(key: str, result: str) -> None:+ _STEP_RESULTS[key] = result+++def _closure_record() -> "dict[str, list[str]]":+ """What each audited with-deps step leaves unmet in its closure, after the pass.++ Recorded for the next run's gate: a requirement still unmet once its step has run is one+ the step cannot satisfy (sqlfluff 3.x pins click<=8.3.0 while huggingface-hub 1.23+ needs+ >=8.4.2), and re-running the step for it resolved nothing and needed the index. A skipped+ step carries the record it was skipped on. Audit failures are not recorded, or an+ unreadable environment would skip the step next time.+ """+ record: dict[str, list[str]] = {}+ # Under a caller's PIP_NO_DEPS the unmet dependencies are deliberate, not known conflicts.+ # UV_OVERRIDE is the same case (_plan_pass already refuses evidence for it): it forces+ # versions past the pins that asked for them, so what it leaves unmet is its own doing.+ if _foreign_resolver_inputs() or _foreign_uv_override_in_effect():+ return record+ # A hand-edited manifest can carry anything under this key; it reaches here outside the+ # per-step try below, and this runs while write_manifest's arguments are being built.+ previous = (_PASS_EVIDENCE or {}).get("known_unmet")+ if not isinstance(previous, dict):+ previous = {}+ for key, req in _AUDITED_STEPS.items():+ # An argument to write_manifest, so every install has already landed and nothing here may+ # raise: the core step can have replaced the tree these paths came from.+ temps: list[Path] = []+ try:+ effective, temps = _effective_requirements(req)+ unmet = install_manifest.closure_unmet_requirements(effective, _installed_index())+ except Exception: # noqa: BLE001 - nothing recorded means nothing ignored next time+ unmet = ["<audit failed>"]+ finally:+ for temp in temps:+ # An unlink that raises here would end the pass between the last install and+ # the manifest write. A temp file left behind is the cheaper outcome.+ try:+ temp.unlink(missing_ok = True)+ except OSError:+ pass+ audited = not any(entry.startswith("<") for entry in unmet)+ # Only a version CONFLICT can be a known conflict: closure_unmet_requirements names an+ # absent distribution by itself and one outside its specifier as "name version". An+ # absent one is work this step does, and recording it would excuse the install that+ # repairs it. Reachable through a pip.conf with no-deps, which the guard above cannot+ # see.+ unmet = [entry for entry in unmet if entry.startswith("<") or " " in entry]+ if _STEP_RESULTS.get(key) == "skipped":+ # Narrowed to what is still unmet, or a later loss of a since-satisfied package+ # hides behind the record. An audit that could not run keeps it as it was, and a+ # step that did not run adopts nothing it never stood behind.+ carried = list(previous.get(key) or []) if isinstance(previous.get(key), list) else []+ # Same rule for a record written by an earlier build of this code.+ carried = [entry for entry in carried if " " in entry]+ if audited:+ carried = [entry for entry in carried if entry in unmet]+ if carried:+ record[key] = carried+ continue+ unmet = [entry for entry in unmet if not entry.startswith("<")]+ if unmet:+ record[key] = unmet+ return record+++def _may_skip_on_evidence() -> bool:+ """Whether a step is allowed to answer from what is already on disk.++ The requirements steps ask through _requirements_satisfied. The three pin-shaped steps+ (torchao, MLX, torchcodec) compare against the installed distribution rather than a+ recorded digest, so they ask for themselves: otherwise a satisfied pin outranks every+ reason _plan_pass had for refusing evidence, including UNSLOTH_STUDIO_FULL_DEPS, a failed+ deep verify, and a moved interpreter, platform or torch flavour.++ _full_deps_requested is asked again rather than left to _plan_pass: these steps are also+ reachable from _ensure_expected_torch_flavor and the post-repair torchao re-selection, and+ the one switch a user is told to set has to hold on every path.+ """+ return _PASS_EVIDENCE is not None and not _full_deps_requested()+++_FOREIGN_RESOLVER_ENV = (+ "UV_CONSTRAINT",+ "UV_BUILD_CONSTRAINT",+ "PIP_CONSTRAINT",+ "PIP_NO_DEPS",+ "UV_NO_DEPS",+)+++def _foreign_resolver_inputs() -> list:+ """Environment inputs that change what a step installs and that no digest covers."""+ return [name for name in _FOREIGN_RESOLVER_ENV if (os.environ.get(name) or "").strip()]+++def _foreign_uv_override_in_effect() -> bool:+ """Whether UV_OVERRIDE names a file other than the bundled macOS arm64 overrides."""+ value = (os.environ.get("UV_OVERRIDE") or "").strip()+ if not value:+ return False++ def _canonical(path: str) -> str:+ try:+ return os.path.normcase(os.path.realpath(path))+ except (OSError, ValueError):+ return path++ bundled = {_canonical(str(_MLX_OVERRIDES))}+ try:+ bundled.add(_canonical(_uv_safe_path(_MLX_OVERRIDES)))+ except Exception: # noqa: BLE001 - the short-path form is an optimisation, not evidence+ pass+ return _canonical(value) not in bundled+++def _refuse_evidence(reason: str) -> None:+ """Say why last run's evidence is not usable, then answer "none".++ Named under UNSLOTH_VERBOSE for the same reason as the closure audit's note: a+ refusal here turns every update into a full dependency pass, which is correct, slow,+ and otherwise indistinguishable from a pass that had no evidence to begin with.+ """+ if VERBOSE:+ _note(f"dependency pass evidence not used: {reason}")+ return None+++def _plan_pass(package_name: str, local_repo: str, ci_source_overlay: str) -> "dict | None":+ """Last run's evidence, or None when nothing may be skipped.++ Must run BEFORE remove_manifest: the manifest is the only copy, and it is dropped+ up front precisely so a run killed mid-pass cannot leave a valid one behind.+ """+ # The parked copy is consumed before the refusals below: a forced pass mutates the venv too, and+ # one killed part-way must not leave it as evidence of a completed pass.+ manifest, manifest_error = None, False+ try:+ manifest = install_manifest.read_manifest()+ # setup.ps1 drops the live manifest before this runs; the parked copy is the last completed+ # pass's record. Evidence only: every skip is re-verified on disk.+ if not manifest:+ manifest = install_manifest.read_previous_manifest()+ # Read once: like the live manifest, the parked copy must not survive a pass killed+ # part-way as evidence over a half-modified venv.+ if manifest:+ install_manifest.consume_previous_manifest()+ except Exception: # noqa: BLE001 - an unreadable manifest is a full pass, never a crash+ manifest_error = True+ if _full_deps_requested():+ return _refuse_evidence("UNSLOTH_STUDIO_FULL_DEPS requested")+ # A peer inside its own pass is replacing the packages this evidence describes, so every+ # step runs. The parked copy is consumed above either way.+ if not _PASS_UNCONTENDED:+ return _refuse_evidence("another install is already running in this venv")+ # Dev shapes: an editable overlay or another package name is not the tree the manifest+ # describes.+ if local_repo or ci_source_overlay or package_name != "unsloth":+ return _refuse_evidence("development install shape")+ # UV_OVERRIDE replaces requirements outright. The bundled macOS arm64 file is digested by the+ # gate; a caller's own file is an input no digest covers.+ if _foreign_uv_override_in_effect():+ return _refuse_evidence("a caller-supplied UV_OVERRIDE is in effect")+ # UV_CONSTRAINT / PIP_CONSTRAINT change what a step installs without touching a digested file,+ # and PIP_NO_DEPS would leave the closure record carrying deliberate gaps as known.+ foreign = _foreign_resolver_inputs()+ if foreign:+ return _refuse_evidence(f"caller-supplied resolver input in effect: {', '.join(foreign)}")+ if manifest_error:+ return _refuse_evidence("manifest unreadable")+ if not manifest or manifest.get("schema") != install_manifest.MANIFEST_SCHEMA:+ return _refuse_evidence("no manifest, or a schema this build does not read")+ inputs = manifest.get("pass_inputs")+ results = manifest.get("step_results")+ # Written by a build that predates this, so it can answer for nothing.+ if not isinstance(inputs, dict) or not isinstance(results, dict):+ return _refuse_evidence("manifest written by a build that recorded no pass inputs")+ if manifest.get("python") != platform.python_version():+ return _refuse_evidence(+ f"python moved ({manifest.get('python')} -> {platform.python_version()})"+ )+ if manifest.get("platform") != f"{sys.platform}-{platform.machine()}":+ return _refuse_evidence(+ f"platform moved ({manifest.get('platform')} -> {sys.platform}-{platform.machine()})"+ )+ # The version cannot tell a GIL 3.14 from a free-threaded one; the tag can.+ if manifest.get("installer_python_tag") != _installer_python_tag():+ return _refuse_evidence(+ f"interpreter ABI moved ({manifest.get('installer_python_tag')} -> "+ f"{_installer_python_tag()})"+ )+ # Absent is unknown, not False.+ if manifest.get("no_torch") is not bool(NO_TORCH):+ return _refuse_evidence(+ f"no-torch mode moved ({manifest.get('no_torch')} -> {bool(NO_TORCH)})"+ )+ if not NO_TORCH:+ # The flavour tag, not the index URL: only the tag is safe to keep on disk.+ try:+ expected = _recordable_torch_flavor_tag(_expected_torch_flavor_tag())+ except Exception: # noqa: BLE001 - a probe that did not answer buys a full pass+ return _refuse_evidence("torch flavour probe did not answer")+ if (manifest.get("expected_torch_tag") or "") != expected:+ return _refuse_evidence(+ f"torch flavour moved ({manifest.get('expected_torch_tag')!r} -> {expected!r})"+ )+ # Last, being the only check that walks the filesystem.+ try:+ verified = install_manifest.verify_install(deep = True, manifest = manifest)+ except Exception as exc: # noqa: BLE001+ return _refuse_evidence(f"deep verify raised {exc!r}")+ if not verified.get("ok"):+ return _refuse_evidence(+ f"deep verify failed ({verified.get('reason')}; missing {verified.get('missing')})"+ )+ return {+ "pass_inputs": inputs,+ "step_results": results,+ "pip_check_ok": manifest.get("pip_check_ok"),+ "mlx_health": manifest.get("mlx_health"),+ "known_unmet": manifest.get("known_unmet"),+ "known_unmet_index": manifest.get("known_unmet_index"),+ "bnb_rocm": manifest.get("bnb_rocm"),+ "bnb_rocm_asset": manifest.get("bnb_rocm_asset"),+ }+++def _effective_requirements(req: Path) -> "tuple[Path, list[Path]]":+ """The file pip_install will really install from, plus temp copies to unlink.++ Shared with pip_install so the skip gate audits exactly what the install would do.+ extras.txt names torchcodec and three platforms filter it out; auditing the raw file+ would report it missing on every one of them and never skip anything again.+ """+ temps: list[Path] = []+ actual = req+ if IS_WINDOWS and WINDOWS_SKIP_PACKAGES:+ actual = _filter_requirements(actual, WINDOWS_SKIP_PACKAGES)+ temps.append(actual)+ if NO_TORCH and NO_TORCH_SKIP_PACKAGES:+ actual = _filter_requirements(actual, NO_TORCH_SKIP_PACKAGES)+ temps.append(actual)+ if PLATFORM_LACKS_TORCHCODEC_WHEEL:+ # Linux aarch64 / Windows ARM64 / Intel Mac have no torchcodec wheel.+ actual = _filter_requirements(actual, {"torchcodec"})+ temps.append(actual)+ return actual, temps+++def _pass_input_key(path: Path) -> "str | None":+ """A requirements file as the manifest names it: relative to REQ_ROOT, posix."""+ try:+ return Path(path).resolve().relative_to(REQ_ROOT.resolve()).as_posix()+ except (OSError, ValueError):+ return None+++def _violated_constraints() -> "list[str]":+ """Constrained distributions currently outside their pin.++ Recomputed whenever something was installed: a constraint the last step satisfied+ must not keep the next one running, and one it broke must not be missed. Cached+ otherwise, because every gated step asks.+ """+ global _CONSTRAINTS_CACHE+ if _CONSTRAINTS_CACHE is None or _CONSTRAINTS_CACHE[0] != _INSTALL_ACTIONS:+ try:+ found = install_manifest.violated_constraints(CONSTRAINTS)+ except Exception: # noqa: BLE001 - unreadable is a reason to install, not to crash+ found = ["<unreadable>"]+ _CONSTRAINTS_CACHE = (_INSTALL_ACTIONS, found)+ return _CONSTRAINTS_CACHE[1]+++_CLOSURE_INDEX_CACHE: "tuple[int, dict | None] | None" = None+++def _installed_index_digest() -> "str | None":+ """One sha256 over (name, version) of everything installed: what a recorded conflict+ is evidence about. None when the index cannot be read, which matches no record."""+ import hashlib++ index = _installed_index()+ if index is None:+ return None+ digest = hashlib.sha256()+ for name in sorted(index):+ digest.update(f"{name}=={index[name][0]}\n".encode("utf-8"))+ return digest.hexdigest()+++def _installed_index() -> "dict | None":+ """This venv's installed distributions, read once per install action.++ Every with-deps step walks the same site-packages, and building the index costs one+ pass over every dist-info; `distribution(name)` inside the walk would re-read one per+ node. Invalidated the moment something is installed, like _violated_constraints.+ """+ global _CLOSURE_INDEX_CACHE+ if _CLOSURE_INDEX_CACHE is None or _CLOSURE_INDEX_CACHE[0] != _INSTALL_ACTIONS:+ # importlib.metadata revalidates its listing cache on mtime, one-second granular on+ # some filesystems, so a rebuild in the same tick as its install reads the old one.+ importlib.invalidate_caches()+ try:+ index = install_manifest.installed_dependency_index()+ except Exception: # noqa: BLE001 - None is "cannot audit", which installs+ index = None+ _CLOSURE_INDEX_CACHE = (_INSTALL_ACTIONS, index)+ return _CLOSURE_INDEX_CACHE[1]+++def _inputs_unchanged(keys: "list[str]") -> bool:+ recorded = (_PASS_EVIDENCE or {}).get("pass_inputs") or {}+ for key in keys:+ # Membership first: an unreadable input is left out of both sides, and a missing key+ # compared against None would read as unchanged.+ if key not in recorded:+ return False+ current = install_manifest.digest_file(REQ_ROOT / key)+ if current is None or recorded[key] != current:+ return False+ return True+++def _local_plugin_payload_is_damaged(dist_name: str) -> bool:+ """Whether the installed seed plugin has files RECORD names and disk does not.++ Errors read as damaged, unlike install_manifest's own convention: this decides+ whether to skip a pip install that takes well under a second from a local path, so+ the conservative answer is cheap here and is not on the fast path for anything else.+ """+ try:+ return bool(install_manifest.damaged_payload_files(dist_name, limit = 1))+ except Exception: # noqa: BLE001+ return True+++def _refuse_step(key: str, reason: str) -> bool:+ """Say why one requirements step cannot be skipped, then answer False."""+ if VERBOSE:+ _note(f"{key}: {reason} -- running the step")+ return False+++_INCLUDE_FLAGS = ("-r", "--requirement", "-c", "--constraint")+++def _includes_another_requirements_file(req: Path) -> bool:+ """Whether *req* pulls in a second file the pass_inputs digests do not cover.++ Unreadable counts as "yes": a file this cannot read is one whose contents the gate cannot+ stand behind either, and the step running is the safe answer.+ """+ try:+ text = req.read_text(encoding = "utf-8-sig")+ except (OSError, ValueError, UnicodeDecodeError):+ return True+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ head = line.split()[0].split("=", 1)[0]+ if head in _INCLUDE_FLAGS or any(+ line.startswith(flag) for flag in ("-r", "-c", "--requirement", "--constraint")+ ):+ return True+ return False+++def _requirements_satisfied(+ req: Path,+ *,+ no_deps: bool,+ label: str = "",+ constrain: bool = True,+) -> bool:+ """Whether one requirements step can be skipped, on this run's evidence.++ *label* is the caller's bookkeeping only; the manifest key is the file's path under+ REQ_ROOT, so two steps cannot collide and a renamed file cannot inherit another's record.++ *no_deps* decides whether the dependency closure is audited, and is keyword-only and+ required on purpose: a new step that forgot to answer would get the weaker check.+ """+ if _PASS_EVIDENCE is None:+ return False+ key = _pass_input_key(req)+ if key is None:+ return _refuse_step(str(req), "not under the requirements root")+ # (a) the previous run recorded that it did this exact work+ if (_PASS_EVIDENCE.get("step_results") or {}).get(key) not in ("ran", "skipped"):+ return _refuse_step(key, "last run did not record this step")+ # (b) the inputs are byte-identical, the constraints file and the macOS arm64 overrides+ # included: they move under an unchanged requirements file.+ keys = [key]+ if constrain:+ keys.append("single-env/constraints.txt")+ if IS_MAC_ARM:+ keys.append("single-env/overrides-darwin-arm64.txt")+ if not _inputs_unchanged(keys):+ return _refuse_step(key, "an input file changed")+ # (c) the output is still on disk.+ importlib.invalidate_caches()+ # Inside the try: on a filtering host this reads the file, and a tree the core step replaced+ # mid-pass is a reason to run the step, not to end the update.+ temps: list[Path] = []+ try:+ effective, temps = _effective_requirements(req)+ if _includes_another_requirements_file(effective):+ # The digest covers this file; an -r target is a second file pass_inputs does not+ # name, and missing_requirements skips flag lines, so a pin behind the include can+ # move unseen. No shipped file uses one, so the refusal costs nothing today.+ return _refuse_step(key, "the file includes another requirements file")+ missing = install_manifest.missing_requirements(effective)+ if missing:+ return _refuse_step(key, f"not installed or outside the pin: {missing[:5]}")+ # ...and the output's own dependencies: `mammoth>=1.8.0` stays satisfied with its `cobble`+ # gone, and this step is what repaired that. Not asked of --no-deps steps.+ if not no_deps:+ unmet = install_manifest.closure_unmet_requirements(effective, _installed_index())+ # What the last pass left unmet right after this step (disjoint pins) is not+ # missing work; anything new is. Honoured only against the installed set it was+ # recorded on, since a requirer that moved may have dropped the bound.+ known: set = set()+ if _PASS_EVIDENCE.get("known_unmet_index") == _installed_index_digest():+ known = set((_PASS_EVIDENCE.get("known_unmet") or {}).get(key) or [])+ unmet = [entry for entry in unmet if entry not in known]+ if unmet:+ # Named under UNSLOTH_VERBOSE: an audit that can never pass makes every update a+ # full pass, and nothing else says why.+ if VERBOSE:+ _note(f"{key}: {unmet[0]} is not satisfied -- running the step")+ return False+ except Exception as exc: # noqa: BLE001+ return _refuse_step(key, f"audit raised {exc!r}")+ finally:+ for temp in temps:+ try:+ temp.unlink(missing_ok = True)+ except OSError:+ pass+ if constrain and _violated_constraints():+ return _refuse_step(key, f"constraints violated: {_violated_constraints()[:5]}")+ return True+++def _skip_step(+ req: Path,+ progress_label: str,+ *,+ no_deps: bool,+ constrain: bool = True,+ extra_check = None,+) -> bool:+ """Announce one requirements step and say whether it is already satisfied.++ The progress slot is spent either way, so the denominator does not depend on how much of+ the install was already there.++ *extra_check* is an on-disk predicate for a file importlib.metadata cannot fully answer:+ today only triton-kernels.txt, whose git ref no version reflects.+ """+ key = _pass_input_key(req) or str(req)+ if not no_deps and _pass_input_key(req) is not None:+ # Registered whether or not skipped, so the first pass records what its closure cannot+ # satisfy.+ _AUDITED_STEPS[key] = req+ satisfied = _requirements_satisfied(req, no_deps = no_deps, constrain = constrain)+ if satisfied and extra_check is not None:+ satisfied = bool(extra_check())+ _progress(f"{progress_label} (satisfied, skipped)" if satisfied else progress_label)+ _record_step(key, "skipped" if satisfied else "ran")+ return satisfied+++def _direct_reference_in_requirements(req: Path) -> "tuple[str, str, str] | None":+ """``(url, requested revision, subdirectory)`` for a git requirement, or None.++ The fragment is NOT an inline comment here: ``#subdirectory=`` is part of the URL,+ and a different subdirectory is a different package.+ """+ # ValueError too: a requirements file that is not UTF-8 raises UnicodeDecodeError here.+ try:+ lines = req.read_text(encoding = "utf-8-sig").splitlines()+ except (OSError, ValueError):+ return None+ for line in lines:+ stripped = line.strip()+ if not stripped or stripped.startswith("#") or "git+" not in stripped:+ continue+ rest = stripped.partition("git+")[2]+ base, _, fragment = rest.partition("#")+ # The last "@" IN THE PATH: the whole URL's last "@" may be git+ssh userinfo, and the last+ # "@" before the last "/" misses a branch with a slash (release/3.6.x).+ scheme, separator, remainder = base.partition("://")+ netloc, slash, path = remainder.partition("/") if separator else ("", "", base)+ cut = path.rfind("@")+ if cut == -1:+ revision = ""+ else:+ revision = path[cut + 1 :]+ path = path[:cut]+ url = f"{scheme}://{netloc}{slash}{path}" if separator else path+ subdirectory = ""+ for part in fragment.split("&"):+ key, sep, value = part.partition("=")+ if sep and key.strip() == "subdirectory":+ subdirectory = value.strip()+ return url, revision, subdirectory+ return None+++_COMMIT_REVISION_RE = re.compile(r"[0-9a-fA-F]{7,40}")+++def _direct_reference_is_installed(req: Path, dist_name: str) -> bool:+ """Whether the resident *dist_name* came from the ref *req* names.++ A version says nothing about a git requirement: the same one is published from every+ branch, so a release/3.6.x pin is satisfied on paper by a build from main. direct_url.json+ is the only place the ref pip and uv actually installed survives.+ """+ wanted = _direct_reference_in_requirements(req)+ if wanted is None:+ return False+ url, revision, subdirectory = wanted+ payload = _recorded_direct_url(dist_name)+ if payload is None:+ return False+ vcs = payload.get("vcs_info")+ if not isinstance(vcs, dict):+ return False+ if not (+ str(payload.get("url") or "").rstrip("/") == url.rstrip("/")+ and str(vcs.get("requested_revision") or "") == revision+ and str(payload.get("subdirectory") or "") == subdirectory+ ):+ return False+ if _COMMIT_REVISION_RE.fullmatch(revision):+ return True+ # A branch ref (release/3.6.x) moves without the requirements text changing, so one+ # `git ls-remote` says where it is now. Same commit skips, a moved ref runs the step, an+ # unreachable remote keeps the resident build (the pass used to die here offline).+ commit_id = str(vcs.get("commit_id") or "").strip().lower()+ if not _COMMIT_REVISION_RE.fullmatch(commit_id or "x"):+ return False+ remote = _git_remote_commit(url, revision)+ if remote is None:+ _note(+ f"{dist_name}: {url} ({revision}) is unreachable -- keeping the installed build "+ f"{commit_id[:12]}",+ _dim,+ )+ return True+ return remote == commit_id or remote.startswith(commit_id) or commit_id.startswith(remote)+++def _payload_recorded_intact(dist_name: str) -> bool:+ """True only when the distribution has a RECORD and every file it names is there+ at its recorded size; a missing distribution or RECORD is not intact."""+ try:+ return _recorded_payload_damaged(dist_name) is False+ except Exception: # noqa: BLE001 - not installed, or unreadable, is not intact+ return False+++def _triton_kernels_step() -> None:+ """Install triton kernels, or keep the build that is there.++ The requirement is a git branch, so the evidence is asked of the remote now (one+ ls-remote in `_direct_reference_is_installed`) rather than read from a record, and holds+ even on a pass with no recorded evidence: a full pass has no reason to rebuild a checkout+ the branch still points at, and an unreachable git host must not fail an update over a+ speedup that is already installed. It did, since the step ran every pass.+ """+ req = REQ_ROOT / "triton-kernels.txt"+ if not _has_working_git():+ _progress("triton kernels (skipped, no git)")+ _note("no working git -- skipping triton kernels (training speedup only)")+ return+ asked: dict = {}++ def _ref_current() -> bool:+ asked["current"] = _direct_reference_is_installed(req, "triton_kernels")+ return asked["current"]++ if _skip_step(req, "triton kernels", no_deps = True, constrain = False, extra_check = _ref_current):+ return+ if "current" not in asked:+ _ref_current()+ # Provenance alone is not a build: triton_kernels/ can be gone under its dist-info, and a forced+ # pass asked for every step.+ if (+ asked["current"]+ and not _full_deps_requested()+ and _payload_recorded_intact("triton_kernels")+ ):+ _note("triton kernels: the installed build is what the requirement's ref points at -- kept")+ _record_step(_pass_input_key(req) or str(req), "skipped")+ return+ pip_install(+ "Installing triton kernels",+ "--no-deps",+ "--no-cache-dir",+ req = req,+ constrain = False,+ )+++def _recorded_direct_url(dist_name: str) -> "dict | None":+ """The direct_url.json pip and uv wrote for *dist_name*, or None when there is none+ that parses. This is the only place a git install's ref and commit survive."""+ try:+ from importlib.metadata import distribution+ recorded = distribution(dist_name).read_text("direct_url.json")+ except Exception: # noqa: BLE001 - absent metadata is a reason to install+ return None+ if not recorded:+ return None+ try:+ payload = json.loads(recorded)+ except ValueError:+ return None+ return payload if isinstance(payload, dict) else None+++def _git_remote_commit(+ url: str,+ revision: str,+ timeout: int = 45,+) -> "str | None":+ """The commit *revision* names on the remote right now (lower-case hex), or None+ when the remote cannot be asked: no git, no network, no such ref, a timeout.++ A peeled tag (`refs/tags/x^{}`) wins over the tag object and a branch over a tag of the+ same name: pip and uv record the commit the checkout landed on, peeled for annotated tags.+ """+ exe = shutil.which("git")+ if exe is None or not revision:+ return None+ env = dict(os.environ)+ env["GIT_TERMINAL_PROMPT"] = "0"+ env.setdefault("GIT_ASKPASS", "echo")+ try:+ probe = subprocess.run(+ [exe, "ls-remote", "--", url, revision],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = timeout,+ env = env,+ **_windows_hidden_subprocess_kwargs(),+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if probe.returncode != 0:+ return None+ rows: dict[str, str] = {}+ for line in probe.stdout.splitlines():+ sha, _, ref = line.strip().partition("\t")+ if ref and _COMMIT_REVISION_RE.fullmatch(sha):+ rows[ref] = sha.lower()+ for ref in (+ f"refs/tags/{revision}^{{}}",+ f"refs/heads/{revision}",+ f"refs/tags/{revision}",+ revision,+ ):+ if ref in rows:+ return rows[ref]+ return next(iter(rows.values()), None) if len(rows) == 1 else None+++def _uv_version() -> "str | None":+ """The uv this pass used, for the record. None when pip did the work."""+ if not USE_UV:+ return None+ try:+ probe = subprocess.run(+ ["uv", "--version"],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 30,+ **_windows_hidden_subprocess_kwargs(),+ )+ except Exception: # noqa: BLE001 - advisory+ return None+ return probe.stdout.strip() or None if probe.returncode == 0 else None+++def _installer_python_tag() -> str:+ """The interpreter's ABI tag, free-threaded builds included.++ Recorded beside `python`, which carries only the version: a GIL and a free-threaded+ 3.14 install the same version string and cannot load each other's extensions.+ """+ return "{}{}{}".format(+ sys.version_info.major,+ sys.version_info.minor,+ "t" if sysconfig.get_config_var("Py_GIL_DISABLED") else "",+ )+++def _patch_metadata_is_pending() -> bool:+ """Whether any METADATA the single-env patch owns still matches a pattern it rewrites.++ The patch is idempotent, so re-running it on a settled install rewrites nothing and costs+ a subprocess plus a metadata walk. Asking first is the same walk without the interpreter+ start; on a fresh venv, where the data-designer steps just ran, the caller does not ask.+ """+ try:+ sys.path.insert(0, str(SINGLE_ENV))+ try:+ import patch_metadata # noqa: PLC0415+ finally:+ if sys.path and sys.path[0] == str(SINGLE_ENV):+ sys.path.pop(0)+ for name in patch_metadata.TARGETS:+ path = patch_metadata.metadata_path(name)+ if path is None:+ continue+ text = path.read_text(encoding = "utf-8")+ if any(pattern.search(text) for pattern, _replacement in patch_metadata.PATCHES):+ return True+ except Exception: # noqa: BLE001 - unknown means run it, which is what it did before+ return True+ return False+++def _run_patch_metadata() -> None:+ """Apply the single-env metadata patch, in process where that works.++ A subprocess is a whole interpreter start for a stdlib script that edits at most three+ files. It stays the fallback: the script is also a standalone entry point, and an import+ failure must not fail the install. Its tally, which run() captured, is captured here too+ and kept for UNSLOTH_VERBOSE, or it lands in the middle of the progress line.+ """+ import contextlib # noqa: PLC0415+ import io # noqa: PLC0415++ try:+ sys.path.insert(0, str(SINGLE_ENV))+ try:+ import patch_metadata # noqa: PLC0415+ finally:+ if sys.path and sys.path[0] == str(SINGLE_ENV):+ sys.path.pop(0)+ captured = io.StringIO()+ with contextlib.redirect_stdout(captured):+ patch_metadata.main()+ if VERBOSE:+ for line in captured.getvalue().splitlines():+ if line.strip():+ _note(line.strip())+ return+ except Exception: # noqa: BLE001+ pass+ run(+ "Patching single-env metadata",+ [sys.executable, str(SINGLE_ENV / "patch_metadata.py")],+ )+++# What building the plugin writes back into its directory (build/lib, src/<name>.egg-info).+# Digesting those rebuilt the plugin on the first pass after an install, which failed offline.+_PLUGIN_BUILD_ARTIFACT_DIRS = frozenset({"__pycache__", "build", "dist", ".eggs"})+++def _is_plugin_build_artifact(relative: Path) -> bool:+ parts = relative.parts+ if any(part in _PLUGIN_BUILD_ARTIFACT_DIRS for part in parts[:-1]):+ return True+ if any(part.endswith((".egg-info", ".dist-info")) for part in parts[:-1]):+ return True+ return parts[-1].endswith((".pyc", ".pyo"))+++def _local_plugin_digest(plugin_dir: Path) -> "str | None":+ """One sha256 over a local plugin tree, so an edited seed plugin reinstalls.++ Sorted (relpath, bytes): a directory listing has no order, and a digest that+ depended on one would differ between two byte-identical trees.+ """+ import hashlib++ if not plugin_dir.is_dir():+ # None never equals a recorded digest: an unreadable plugin reinstalls.+ return None+ digest = hashlib.sha256()+ try:+ paths = sorted(+ path+ for path in plugin_dir.rglob("*")+ if path.is_file() and not _is_plugin_build_artifact(path.relative_to(plugin_dir))+ )+ for path in paths:+ # surrogateescape, not strict: POSIX allows filenames that are not UTF-8, and+ # a stray one beside the sources would otherwise end the update here.+ digest.update(+ path.relative_to(plugin_dir).as_posix().encode("utf-8", "surrogateescape")+ )+ digest.update(b"\x00")+ digest.update(path.read_bytes())+ digest.update(b"\x00")+ except OSError:+ return None+ return digest.hexdigest()+++def _under_pass_lock(func):+ """Run the pass holding the pass lock, and record whether a peer already had it."""++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ global _PASS_UNCONTENDED+ with install_manifest.pass_lock() as uncontended:+ _PASS_UNCONTENDED = uncontended+ return func(*args, **kwargs)++ return wrapper+++@_under_pass_lock+def install_python_stack() -> int:+ global USE_UV, _STEP, _TOTAL, _PROGRESS_LINE_ACTIVE+ global _INSTALL_ACTIONS, _PASS_EVIDENCE, _CONSTRAINTS_CACHE, _CLOSURE_INDEX_CACHE+ global _BNB_ROCM_PASS_PROVENANCE, _BNB_ROCM_PASS_ASSET+ _STEP = 0+ # Module state reset, so a second call in one process (the tests) starts fresh.+ _INSTALL_ACTIONS = 0+ _PASS_EVIDENCE = None+ _CONSTRAINTS_CACHE = None+ _CLOSURE_INDEX_CACHE = None+ _BNB_ROCM_PASS_PROVENANCE = None+ _BNB_ROCM_PASS_ASSET = None+ _STEP_RESULTS.clear()+ # Registered by the steps as they run: a stale entry would be audited for a step never reached.+ _AUDITED_STEPS.clear()+ # An aborted earlier run leaves it set, and every _safe_print() consumes it --+ # the first message would get a stray newline.+ _PROGRESS_LINE_ACTIVE = False++ # install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling the core packages;+ # `studio update` does NOT, so unsloth + unsloth-zoo are reinstalled to pick+ # up new versions. Shared base.txt requirements are handled independently.+ skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"+ # --package installs a different package name (for testing).+ 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", "")+ # read where the overlay runs, so UNSLOTH_ZOO_REF reaches the metadata-repair+ # reinstall path too, not just the two calls below+ # Clean-machine CI overlays only unsloth, not the full local source pair.+ ci_source_overlay = os.environ.get("UNSLOTH_CI_SOURCE_OVERLAY", "")+ # Three lettered steps beside the numbered ones: anyio repair (8b), diffusers pin (11b),+ # torchcodec (13b).+ base_total = 13 if IS_WINDOWS else 14+ if IS_MACOS:+ base_total -= 1 # triton step is skipped on macOS+ if not IS_MACOS and not NO_TORCH:+ base_total += 1 # ROCm torch check (step 2b), non-macOS+ if not IS_WINDOWS:+ base_total += 2 # flash-attn + torch final repair (step 13), Linux+ else:+ base_total += 1 # torch flavor invariant (step 13w), Windows+ if IS_MAC_ARM and not NO_TORCH:+ base_total += 1 # MLX stack, same gate as the step itself+ if NO_TORCH and not skip_base:+ # no-torch runtime deps, which this build announces on its own slot inside the core+ # step rather than folding into it. Same gate as the step itself.+ base_total += 1+ base_requirements = _shared_base_requirements() if skip_base else None+ # Core packages and shared base requirements occupy one progress slot. A+ # shell-installer handoff skips that slot only while base.txt has no work.+ _TOTAL = base_total - int(skip_base and base_requirements is None)++ # Before the manifest goes: it is the only copy of what the last run did. None means every step+ # runs.+ _PASS_EVIDENCE = _plan_pass(package_name, local_repo, ci_source_overlay)++ # Drop it up front: a missing manifest is what tells the CLI, setup.sh and the preflight+ # that an interrupted run left the venv half-built, so stop if it survives rather than+ # mutate behind a marker that still verifies.+ # A stale parked copy goes FIRST, while the live manifest is still there: _plan_pass+ # consumes the one it reads, so anything left is from a run that died. One that cannot be+ # cleared has to refuse here, or the venv can neither verify nor finish and every later+ # update stops at the same point.+ _parked = install_manifest.previous_manifest_path()+ install_manifest.consume_previous_manifest()+ if _parked.exists():+ _safe_print(+ f"error: could not remove the parked {install_manifest.PREVIOUS_MANIFEST_NAME} "+ f"in {install_manifest.venv_root()}; refusing to install behind evidence the "+ "next run would read as a completed pass",+ file = sys.stderr,+ )+ return 1+ if install_manifest.remove_manifest():+ install_manifest.consume_previous_manifest()+ if _parked.exists():+ _safe_print(+ f"error: could not remove the parked {install_manifest.PREVIOUS_MANIFEST_NAME} "+ f"in {install_manifest.venv_root()}; refusing to install behind evidence the "+ "next run would read as a completed pass",+ file = sys.stderr,+ )+ return 1+ else:+ _safe_print(+ f"error: could not remove the stale {install_manifest.MANIFEST_NAME} in "f"{install_manifest.venv_root()}; refusing to install behind a marker ""that would still report this venv as complete",file = sys.stderr,@@ -7623,8 +9022,14 @@ def install_python_stack() -> int:USE_UV = _bootstrap_uv()# 2. Ensure pip is available (uv venvs from install.sh omit pip).- _progress("pip bootstrap")- if USE_UV:+ # The escape hatch (UNSLOTH_STUDIO_FULL_DEPS) reaches this skip too.+ if not _full_deps_requested() and _venv_pip_is_usable():+ # This step used to reinstall pip from the index on every update.+ _progress("pip bootstrap (satisfied, skipped)")+ _record_step("pip", "skipped")+ elif USE_UV:+ _progress("pip bootstrap")+ _record_step("pip", "ran")run("Bootstrapping pip via uv",[@@ -7637,6 +9042,8 @@ def install_python_stack() -> int:],)else:+ _progress("pip bootstrap")+ _record_step("pip", "ran")# uv-created venvs omit pip: ensurepip, else direct upgrade._has_pip = (subprocess.run(@@ -7681,16 +9088,27 @@ def install_python_stack() -> int:if IS_MAC_ARM and not NO_TORCH:# Both branches spend the slot, so the denominator does not depend on the host.if _mlx_pins_are_installable():- _progress("MLX stack (Apple Silicon)")- pip_install(- "Installing MLX stack (mlx + mlx-lm + mlx-vlm)",- "--no-cache-dir",- "--upgrade",- "mlx==0.32.1",- "mlx-metal==0.32.1",- "mlx-lm==0.31.3",- "mlx-vlm>=0.4.4,<0.7.0",- )+ # _may_skip_on_evidence too: exact pins read as satisfied on the very run a forced pass+ # was asked for. And the arm64 overrides digest: UV_OVERRIDE shapes MLX's graph.+ if (+ _may_skip_on_evidence()+ and _mlx_stack_is_current()+ and _inputs_unchanged(["single-env/overrides-darwin-arm64.txt"])+ ):+ _progress("MLX stack (satisfied, skipped)")+ _record_step("mlx", "skipped")+ else:+ _progress("MLX stack (Apple Silicon)")+ _record_step("mlx", "ran")+ pip_install(+ "Installing MLX stack (mlx + mlx-lm + mlx-vlm)",+ "--no-cache-dir",+ # --upgrade-package per name, never a bare --upgrade, which re-resolves every+ # transitive dependency; _build_pip_cmd translates back for pip.+ *[arg for name in _MLX_NAMES for arg in ("--upgrade-package", name)],+ *_MLX_PINS,+ _MLX_VLM_SPEC,+ )else:_progress("MLX stack (skipped, no wheel for this macOS or Python)")_note(@@ -7738,12 +9156,13 @@ def install_python_stack() -> int:"--no-cache-dir","pydantic",)- pip_install(- "Installing no-torch runtime deps",- "--no-cache-dir",- "--no-deps",- req = REQ_ROOT / "no-torch-runtime.txt",- )+ if not _skip_step(REQ_ROOT / "no-torch-runtime.txt", "no-torch runtime deps", no_deps = True):+ pip_install(+ "Installing no-torch runtime deps",+ "--no-cache-dir",+ "--no-deps",+ req = REQ_ROOT / "no-torch-runtime.txt",+ )if local_repo:_overlay_local_core_packages(local_repo)elif local_repo:@@ -7794,15 +9213,22 @@ def install_python_stack() -> int:# Independent of the core phase: the shell installers skip that after# installing the two distributions inline, but still apply this file.if base_requirements is not None:+ satisfied = _requirements_satisfied(base_requirements, no_deps = False)+ _record_step("base.txt", "skipped" if satisfied else "ran")if skip_base:- _progress("base requirements")+ _progress(+ "base requirements (satisfied, skipped)" if satisfied else "base requirements"+ )+ elif satisfied:+ _step(_LABEL, "shared base requirements are current")else:_step(_LABEL, "applying shared base requirements")- pip_install(- "Applying shared base requirements",- "--no-cache-dir",- req = base_requirements,- )+ if not satisfied:+ pip_install(+ "Applying shared base requirements",+ "--no-cache-dir",+ req = base_requirements,+ )# 2b. Torch repair (wrong-family / CPU-only); must follow base packages so torch is present.if not IS_MACOS and not NO_TORCH:@@ -7857,24 +9283,24 @@ def install_python_stack() -> int:)# 3. Extra dependencies- _progress("unsloth extras")- pip_install(- "Installing additional unsloth dependencies",- "--no-cache-dir",- # extras.txt is where the wheel-less requirements live, so a user-level- # no-build/only-binary policy fails this step first (#8530).- *_sdist_only_build_args(*_extras_sdist_only_packages()),- req = REQ_ROOT / "extras.txt",- )+ if not _skip_step(REQ_ROOT / "extras.txt", "unsloth extras", no_deps = False):+ pip_install(+ "Installing additional unsloth dependencies",+ "--no-cache-dir",+ # extras.txt is where the wheel-less requirements live, so a user-level+ # no-build/only-binary policy fails this step first (#8530).+ *_sdist_only_build_args(*_extras_sdist_only_packages()),+ req = REQ_ROOT / "extras.txt",+ )# 3b. Extra dependencies (no-deps) -- audio model support etc.- _progress("extra codecs")- pip_install(- "Installing extras (no-deps)",- "--no-deps",- "--no-cache-dir",- req = REQ_ROOT / "extras-no-deps.txt",- )+ if not _skip_step(REQ_ROOT / "extras-no-deps.txt", "extra codecs", no_deps = True):+ pip_install(+ "Installing extras (no-deps)",+ "--no-deps",+ "--no-cache-dir",+ req = REQ_ROOT / "extras-no-deps.txt",+ )# 4. Install the torch-matched torchao override. Reinstall only when the pin# changes, since Windows can remove shared files during replacement.@@ -7893,18 +9319,7 @@ def install_python_stack() -> int:# and without git (the requirement is a git+https URL); a training speedup# only, so warn rather than fail the install.if not IS_WINDOWS and not IS_MACOS:- if not _has_working_git():- _progress("triton kernels (skipped, no git)")- _note("no working git -- skipping triton kernels (training speedup only)")- else:- _progress("triton kernels")- pip_install(- "Installing triton kernels",- "--no-deps",- "--no-cache-dir",- req = REQ_ROOT / "triton-kernels.txt",- constrain = False,- )+ _triton_kernels_step()if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:_progress("flash-attn")@@ -7932,33 +9347,37 @@ def install_python_stack() -> int:# )# 8. Unsloth dependencies- _progress("studio deps")- pip_install(- "Installing studio dependencies",- "--no-cache-dir",- req = REQ_ROOT / "studio.txt",- )+ if not _skip_step(REQ_ROOT / "studio.txt", "studio deps", no_deps = False):+ pip_install(+ "Installing studio dependencies",+ "--no-cache-dir",+ req = REQ_ROOT / "studio.txt",+ )# 8b. anyio repair (#6483)_progress("anyio check")_repair_bad_anyio()# 9. Data-designer dependencies- _progress("data designer deps")- pip_install(- "Installing data-designer base dependencies",- "--no-cache-dir",- req = SINGLE_ENV / "data-designer-deps.txt",+ _dd_deps_ran = not _skip_step(+ SINGLE_ENV / "data-designer-deps.txt", "data designer deps", no_deps = False)+ if _dd_deps_ran:+ pip_install(+ "Installing data-designer base dependencies",+ "--no-cache-dir",+ req = SINGLE_ENV / "data-designer-deps.txt",+ )# 10. Data-designer packages (no-deps to avoid conflicts)- _progress("data designer")- pip_install(- "Installing data-designer",- "--no-cache-dir",- "--no-deps",- req = SINGLE_ENV / "data-designer.txt",- )+ _dd_ran = not _skip_step(SINGLE_ENV / "data-designer.txt", "data designer", no_deps = True)+ if _dd_ran:+ pip_install(+ "Installing data-designer",+ "--no-cache-dir",+ "--no-deps",+ req = SINGLE_ENV / "data-designer.txt",+ )# 11. Local Data Designer seed pluginslocal_dd_plugins = [@@ -7969,8 +9388,30 @@ def install_python_stack() -> int:if not plugin_dir.is_dir():_note(f"❌ Missing local plugin directory: {plugin_dir}", _red)return 1- _progress("local plugin")- for plugin_name, plugin_dir in local_dd_plugins:+ # Digested, not version-compared: a path-installed plugin's version never moves.+ _plugin_digests: dict[str, str] = {}+ _plugin_work: list[tuple[str, Path]] = []+ _recorded_plugins = (_PASS_EVIDENCE or {}).get("pass_inputs") or {}+ for _plugin_name, plugin_dir in local_dd_plugins:+ _plugin_key = f"plugins/{plugin_dir.name}"+ _plugin_digest = _local_plugin_digest(plugin_dir)+ if _plugin_digest is not None:+ _plugin_digests[_plugin_key] = _plugin_digest+ _plugin_current = (+ _PASS_EVIDENCE is not None+ and _plugin_digest is not None+ and _recorded_plugins.get(_plugin_key) == _plugin_digest+ # The directory name IS the distribution name (each plugin's pyproject.toml).+ and bool(_installed_distribution_version(plugin_dir.name))+ # ...and the payload: deleting the installed module left version and source digest+ # unchanged and the step skipped forever. limit = 1: one missing file is the answer.+ and not _local_plugin_payload_is_damaged(plugin_dir.name)+ )+ if not _plugin_current:+ _plugin_work.append((_plugin_name, plugin_dir))+ _progress("local plugin" if _plugin_work else "local plugin (satisfied, skipped)")+ _record_step("plugins", "ran" if _plugin_work else "skipped")+ for plugin_name, plugin_dir in _plugin_work:pip_install(f"Installing local data-designer {plugin_name} plugin","--no-cache-dir",@@ -7984,19 +9425,19 @@ def install_python_stack() -> int:# release, and outside every skip_base / NO_TORCH branch so it reaches every path.# constrain stays on: constraints.txt says nothing about diffusers today, and a# future entry there should win rather than be silently bypassed here.- _progress("diffusers pin")- pip_install(- "Installing the pinned Diffusers release",- "--no-cache-dir",- req = REQ_ROOT / "diffusers-pin.txt",- )+ if not _skip_step(REQ_ROOT / "diffusers-pin.txt", "diffusers pin", no_deps = False):+ pip_install(+ "Installing the pinned Diffusers release",+ "--no-cache-dir",+ req = REQ_ROOT / "diffusers-pin.txt",+ )# 12. Patch metadata for single-env compatibility- _progress("finalizing")- run(- "Patching single-env metadata",- [sys.executable, str(SINGLE_ENV / "patch_metadata.py")],- )+ _finalize_ran = _dd_deps_ran or _dd_ran or _patch_metadata_is_pending()+ _progress("finalizing" if _finalize_ran else "finalizing (satisfied, skipped)")+ _record_step("patch-metadata", "ran" if _finalize_ran else "skipped")+ if _finalize_ran:+ _run_patch_metadata()# 13. Final torch repair. Steps above can pull CUDA torch from PyPI, so repair last.torch_flavor_tag = ""@@ -8079,6 +9520,8 @@ def install_python_stack() -> int:_codec_index = _torchcodec_index_url(_codec_torch_ver, _codec_spec)_codec_args = ("--no-deps", "--no-cache-dir")_codec_rebuild = False+ _codec_have = _installed_distribution_version("torchcodec") or ""+ _codec_want = Noneif _codec_index:_codec_args += ("--index-url", _codec_index)# A codec already inside the window satisfies the requirement, so pip and uv@@ -8086,7 +9529,6 @@ def install_python_stack() -> int:# wrong-accelerator wheel this pin exists to replace. Provenance is readable# from the version: the torch indexes carry a +cuNNN / +cpu local tag and PyPI# forbids one, so a local tag that is missing or different means another build.- _codec_have = _installed_distribution_version("torchcodec") or ""# The tag the PIN will fetch, not the resident torch's: an xpu torch is served# the cpu wheel, so comparing against "xpu" would force-reinstall every run._codec_want = _torchcodec_index_tag(_codec_torch_ver)@@ -8095,8 +9537,20 @@ def install_python_stack() -> int:):_codec_args += ("--force-reinstall",)_codec_rebuild = True+ # One decision, read twice (the line below names it). _may_skip_on_evidence is part of+ # it: a forced pass or failed deep verify is a claim metadata cannot answer.+ _codec_skip = (+ _may_skip_on_evidence()+ and not _codec_rebuild+ and _codec_spec_is_satisfied(_codec_spec, _codec_have)+ )_safe_print(- f" torch {_codec_torch_ver} detected -- installing {_codec_spec}"+ f" torch {_codec_torch_ver} detected -- "+ + (+ f"{_codec_spec} is already installed"+ if _codec_skip+ else f"installing {_codec_spec}"+ )# Redacted for display only; the installer below still gets the exact URL.# An authenticated mirror puts its credentials in the userinfo or a query# token, and this line is printed straight to the terminal and CI log rather@@ -8109,9 +9563,17 @@ def install_python_stack() -> int:# install inverts the rule the extras-no-deps filter above exists to enforce, and# the index can refuse for reasons no local table predicts -- a yanked release, an# offline mirror, a platform tag added or dropped upstream after this shipped.- _codec_ok = pip_install_try("Installing torchcodec", *_codec_args, _codec_spec)- _codec_fellback = False- if not _codec_ok and _codec_index:+ if _codec_skip:+ # Right version, right index: pip and uv would resolve against the accelerator index to+ # decide the same thing.+ _record_step("torchcodec", "skipped")+ _codec_ok = True+ _codec_fellback = False+ else:+ _record_step("torchcodec", "ran")+ _codec_ok = pip_install_try("Installing torchcodec", *_codec_args, _codec_spec)+ _codec_fellback = False+ if not _codec_ok and _codec_index and _STEP_RESULTS.get("torchcodec") == "ran":# The leaf may not carry this window at all: cu129 serves torch 2.8-2.13 but# publishes no 0.8 or 0.9. Retry unpinned rather than table what each index# holds, which is what goes stale. _torchcodec_provenance_hint explains at@@ -8137,6 +9599,8 @@ def install_python_stack() -> int:"the rest of the install is unaffected")elif _codec_index:+ # NOT gated on the codec step having run: NPP fails on its own, and gating it meant a+ # skipped codec left NPP never looked at again. Still free when already installed.# torchcodec's CUDA build dlopens libnppicc and libnppc, and NPP is not in torch's# dependency set, so an older cuNNN wheel installs fine under --no-deps and then# fails to import. 0.12+ no longer links NPP, so this only guards the older pins.@@ -8155,7 +9619,14 @@ def install_python_stack() -> int:)_npp_major = _npp_probed_npp_spec = _npp_requirement(_npp_major) if _npp_major else ""- if _npp_spec and not pip_install_try(+ # The distribution the spec names (nvidia-npp-cuNN through CUDA 12, nvidia-npp above);+ # _spec_is_satisfied answers the range.+ _npp_name = re.split(r"[<>=!~]", _npp_spec, maxsplit = 1)[0].strip() if _npp_spec else ""+ _npp_have = _installed_distribution_version(_npp_name) if _npp_name else None+ if _npp_have and _spec_is_satisfied(_npp_spec, _npp_have):+ # Already resident; asking pip resolved against PyPI on every update.+ pass+ elif _npp_spec and not pip_install_try("Installing torchcodec CUDA runtime (NPP)","--no-cache-dir",_npp_spec,@@ -8165,13 +9636,19 @@ def install_python_stack() -> int:"import on a host without the CUDA toolkit, leaving audio disabled")- # 14. Final check (silent; third-party conflicts are expected)- subprocess.run(- [sys.executable, "-m", "pip", "check"],- stdout = subprocess.DEVNULL,- stderr = subprocess.DEVNULL,- **_windows_hidden_subprocess_kwargs(),- )+ # 14. Final check (silent; third-party conflicts are expected). Paid when this pass installed+ # something, or the last recorded run had no clean answer.+ _pip_check_ok = (_PASS_EVIDENCE or {}).get("pip_check_ok")+ if _INSTALL_ACTIONS > 0 or _pip_check_ok is not True:+ _pip_check_ok = (+ subprocess.run(+ [sys.executable, "-m", "pip", "check"],+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ **_windows_hidden_subprocess_kwargs(),+ ).returncode+ == 0+ )# 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@@ -8210,6 +9687,25 @@ def install_python_stack() -> int:expected_torch_tag = _recordable_torch_flavor_tag(torch_flavor_tag),expected_torch_tag_pinned = bool(_recordable_torch_flavor_tag(torch_flavor_tag))and _expected_torch_flavor_was_pinned(_recordable_torch_flavor_tag(torch_flavor_tag)),+ # What the NEXT run may skip. Digested from the CURRENT REQ_ROOT, which the core step+ # may have replaced: a file that moved during this pass must not read as unchanged.+ extra = {+ "pass_inputs": {+ **install_manifest.pass_input_digests(REQ_ROOT),+ **_plugin_digests,+ },+ "step_results": dict(_STEP_RESULTS),+ "known_unmet": _closure_record(),+ # The installed set that record describes; honoured only against the same set.+ "known_unmet_index": _installed_index_digest(),+ # What the AMD bitsandbytes repair left, so the next pass can tell it from a+ # pulled-in wheel.+ "bnb_rocm": _BNB_ROCM_PASS_PROVENANCE,+ "bnb_rocm_asset": _BNB_ROCM_PASS_ASSET,+ "pip_check_ok": _pip_check_ok,+ "uv_version": _uv_version(),+ "installer_python_tag": _installer_python_tag(),+ },)is None):@@ -8233,7 +9729,7 @@ def install_python_stack() -> int:# step done and no record of it, and verify-install, the desktop preflight and the# setup fast path all then call a complete install incomplete.if IS_MAC_ARM and not NO_TORCH:- _report_mlx_stack_health()+ _report_mlx_stack_health(skipped = _STEP_RESULTS.get("mlx") == "skipped")_step(_LABEL, "installed")return 0diff --git a/studio/setup.ps1 b/studio/setup.ps1index f439fab17ef..2a337dd59fe 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -911,6 +911,16 @@ function Redact-InstallOutput {return $Text -replace '(https?://[^\s`#]+)#[^\s`]+', '$1#<redacted>'}+# A credential-free identity for an index URL (no userinfo, query, fragment or trailing slash),+# recorded beside the venv and compared across runs.+function Get-IndexIdentity {+ param([string]$Url)+ if (-not $Url) { return "" }+ $Url = $Url -replace '(https?://)[^/@\s`]+@', '$1'+ $Url = ($Url -split '[?#]', 2)[0]+ return $Url.TrimEnd('/')+}+# _grouped_mm bug: these leaves need the torch 2.11 floor. Must match the other installers.function Test-RocmGfx211Leaf {param([string]$Leaf)@@ -5157,6 +5167,7 @@ if (-not $SkipPythonDeps) {# install_python_stack.py drops the manifest before its own dependency pass, but# pip, torch and triton are replaced first here. Drop it now so a run killed in# those leaves the venv marked half-built, not behind a marker that verifies.+# remove_manifest parks the file, so the dependency pass can still read the last completed pass.$_ManifestDropped = $truetry {& python -c "@@ -5331,16 +5342,60 @@ if ($ROCmIndexUrl) {$_rocmKeptActive = $true}}+ # As the XPU and CPU arms: force only when the resident torch is not this family, the pin moved+ # or the import failed. Unconditional --force-reinstall re-resolved the trio every update.+ $rocmForce = @()+ # The same escape hatch the Python pass honours, in the same spellings: a skip nobody can turn+ # off is a bug nobody can work around, and this arm is reached before the pass runs.+ if (@("1", "true", "yes", "on") -contains "$($env:UNSLOTH_STUDIO_FULL_DEPS)".Trim().ToLowerInvariant()) { $rocmForce = @("--force-reinstall") }+ if ($installedTorchTag -ne "rocm") { $rocmForce = @("--force-reinstall") }+ if ($script:PinChangedForceReinstall) { $rocmForce = @("--force-reinstall") }+ if ($script:TorchImportDefinitivelyFailed) { $rocmForce = @("--force-reinstall") }+ # +rocm names the family, not the architecture: a changed UNSLOTH_ROCM_GFX_ARCH or replaced+ # card moves $ROCmIndexUrl while the trio still satisfies its pins, so the index it came from+ # is recorded. Another index, or no record, takes the reinstall.+ $script:RocmIndexRecord = Join-Path $VenvDir ".unsloth-rocm-index"+ $_rocmIndexIdentity = Get-IndexIdentity $ROCmIndexUrl+ $_recordedRocmIndex = ""+ if (Test-Path -LiteralPath $script:RocmIndexRecord -PathType Leaf) {+ try { $_recordedRocmIndex = Get-IndexIdentity ((Get-Content -LiteralPath $script:RocmIndexRecord -Raw -ErrorAction Stop).Trim()) } catch { $_recordedRocmIndex = "" }+ }+ if ($installedTorchTag -eq "rocm" -and $rocmForce.Count -eq 0 -and $_recordedRocmIndex -ne $_rocmIndexIdentity) {+ if ($_recordedRocmIndex) {+ substep "the ROCm trio was installed from $_recordedRocmIndex, this run selects $_rocmIndexIdentity; reinstalling the trio" "Yellow"+ } else {+ substep "no record of the index the ROCm trio came from; reinstalling the trio once to record it" "Yellow"+ }+ $rocmForce = @("--force-reinstall")+ }+ if ($installedTorchTag -eq "rocm" -and $rocmForce.Count -eq 0 -and $VenvPyExe -and (Test-Path -LiteralPath $VenvPyExe)) {+ # torch alone names the family: a companion re-resolved from PyPI (+cpu, +cuNNN or no+ # tag) satisfies its pin without linking ROCm, and the pinned install leaves it. AMD tags+ # all three +rocm. Payload too, since a dist-info without its package or a RECORD row gone+ # or resized is damage the pinned install would not repair; rows, not Distribution.files+ # (3.13 filters to existing files), bytecode left out. No answer forces the trio. Only the+ # companions the trio installs: Windows on ARM has no torchaudio to repair.+ # The ROCm release is compared too: +rocm6.2 beside a +rocm6.4 torch still satisfies its+ # pin. Numeric versions only, so the community wheels tagged with a bare git hash keep the+ # fast path rather than reinstalling on every update.+ $_companionNames = if ($WinArm64NoAudio) { "('torchvision',)" } else { "('torchvision', 'torchaudio')" }+ $_companionProbe = Invoke-BoundedPythonProbe -PythonExe $VenvPyExe -Code "import csv, io, re, importlib.util as u, importlib.metadata as m, os`ndef rocmver(s):`n hit = re.search(r'rocm(\d+(?:\.\d+)*)', s.lower())`n return hit.group(1) if hit else ''`ntry:`n torchrocm = rocmver(m.distribution('torch').version)`nexcept m.PackageNotFoundError:`n torchrocm = ''`nout = []`nfor n in $($_companionNames):`n try:`n d = m.distribution(n)`n except m.PackageNotFoundError:`n continue`n v = d.version`n if u.find_spec(n) is None:`n out.append(n + '==' + v + ' (payload missing)')`n continue`n rec = d.read_text('RECORD')`n damaged = not rec`n for row in csv.reader(io.StringIO(rec or '')):`n if damaged or len(row) < 3 or not row[0] or row[0].endswith('.pyc') or not row[2]:`n continue`n try:`n damaged = os.stat(d.locate_file(row[0])).st_size != int(row[2])`n except (OSError, ValueError):`n damaged = True`n if damaged:`n out.append(n + '==' + v + ' (payload damaged)')`n continue`n t = (v.split('+', 1) + [''])[1].lower()`n if not t or t.startswith('cpu') or t.startswith('cu') or t.startswith('xpu'):`n out.append(n + '==' + v)`n elif torchrocm and rocmver(t) and rocmver(t) != torchrocm:`n out.append(n + '==' + v + ' (rocm' + rocmver(t) + ' beside torch rocm' + torchrocm + ')')`nprint(' '.join(out))"+ $_companionMismatch = if ($_companionProbe.Ok) { $_companionProbe.Output.Trim() } else { "probe did not answer" }+ if ($_companionMismatch) {+ substep "torchvision/torchaudio do not match the ROCm torch ($_companionMismatch); reinstalling the trio" "Yellow"+ $rocmForce = @("--force-reinstall")+ }+ }while ($true) {# Built here, not in the verbose branch (a splat assigned there is unset on the other path).$_rocmTrio = @($ROCmTorchSpec, $ROCmVisionSpec, $ROCmAudioSpec)if ($WinArm64NoAudio) { $_rocmTrio = @($ROCmTorchSpec, $ROCmVisionSpec) }if ($script:UnslothVerbose) {- Fast-Install @_rocmTrio --force-reinstall --index-url $ROCmIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host+ Fast-Install @_rocmTrio @rocmForce --index-url $ROCmIndexUrl | ForEach-Object { Redact-InstallOutput "$_" } | Out-Host$torchInstallExit = $LASTEXITCODE$output = ""} else {- $output = Fast-Install @_rocmTrio --force-reinstall --index-url $ROCmIndexUrl | Out-String+ $output = Fast-Install @_rocmTrio @rocmForce --index-url $ROCmIndexUrl | Out-String$torchInstallExit = $LASTEXITCODE}if ($torchInstallExit -eq 0 -or -not $_rocmKeptActive) { break }@@ -5357,6 +5412,10 @@ if ($ROCmIndexUrl) {} else {# Tell install_python_stack.py to skip the probe and the manual-install warning.$env:UNSLOTH_ROCM_TORCH_INSTALLED = "1"+ # Recorded after the trio landed (see $rocmForce).+ try {+ if ($script:RocmIndexRecord) { Set-Content -LiteralPath $script:RocmIndexRecord -Value (Get-IndexIdentity $ROCmIndexUrl) -Encoding ascii -NoNewline }+ } catch { }substep "GPU ROCm PyTorch installed ($ROCmGfxArch) -- training and GPU inference will use the GPU" "Cyan"}}@@ -5798,139 +5857,217 @@ function Test-TargetPackageVersion {return $false}-$_NeedT5Install = $false-if (Test-Path -LiteralPath $VenvT5Legacy) {- # Legacy layout -- migrate. The tiered venvs a staged run builds land under the- # stage root and may never be activated, so removing the live legacy one here- # would strip the running install of its only sidecar. The live update does it.- if (-not $StageRoot) {- Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"- Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force+# Audited AND installed from here; mirrors _SIDECAR_COMMON_PINS in setup.sh. A name the audit+# cannot reach on disk reads stale forever.+$SidecarCommonPins = @("huggingface_hub==1.8.0", "hf_xet==1.4.2")++# Mirrors fast_install_sidecar: an inherited UV_OVERRIDE would replace the pin and force rebuilds.+function Fast-Install-Sidecar {+ param([Parameter(ValueFromRemainingArguments=$true)]$Args_)+ $savedOverride = $env:UV_OVERRIDE+ try {+ Remove-Item Env:UV_OVERRIDE -ErrorAction SilentlyContinue+ Fast-Install @Args_+ } finally {+ if ($null -ne $savedOverride) { $env:UV_OVERRIDE = $savedOverride }}- $_NeedT5Install = $true}-if (-not (Test-Path -LiteralPath $VenvT5_530Dir)) { $_NeedT5Install = $true }-if (-not (Test-Path -LiteralPath $VenvT5_550Dir)) { $_NeedT5Install = $true }-if (-not (Test-Path -LiteralPath $VenvT5_510Dir)) { $_NeedT5Install = $true }-if (-not (Test-TargetPackageVersion -TargetDir $VenvT5_530Dir -PackageName "transformers" -ExpectedVersion "5.3.0")) { $_NeedT5Install = $true }-if (-not (Test-TargetPackageVersion -TargetDir $VenvT5_550Dir -PackageName "transformers" -ExpectedVersion "5.5.0")) { $_NeedT5Install = $true }-if (-not (Test-TargetPackageVersion -TargetDir $VenvT5_510Dir -PackageName "transformers" -ExpectedVersion "5.10.2")) { $_NeedT5Install = $true }-# Also reinstall when python deps were updated-if (-not $SkipPythonDeps) { $_NeedT5Install = $true }-if ($_NeedT5Install) {-Write-StudioLine ""--$prevEAP_t5 = $ErrorActionPreference-$ErrorActionPreference = "Continue"--# --- .venv_t5_530 (transformers 5.3.0) ----substep "pre-installing transformers 5.3.0 for newer model support..."-Assert-StudioOwnedOrAbsent -Path $VenvT5_530Dir -Label "transformers 5.3 sidecar venv"-if (Test-Path -LiteralPath $VenvT5_530Dir) { Remove-Item -LiteralPath $VenvT5_530Dir -Recurse -Force }-[System.IO.Directory]::CreateDirectory($VenvT5_530Dir) | Out-Null-Mark-StudioOwned -Path $VenvT5_530Dir-foreach ($pkg in @("transformers==5.3.0", "huggingface_hub==1.8.0", "hf_xet==1.4.2")) {- if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_530Dir --no-deps $pkg- $t5PkgExit = $LASTEXITCODE- $output = ""- } else {- $output = Fast-Install --target $VenvT5_530Dir --no-deps $pkg | Out-String- $t5PkgExit = $LASTEXITCODE+function Remove-SidecarTiktoken {+ # Remnants of a failed tiktoken install shadow the ambient copy and nothing else clears them.+ param([Parameter(Mandatory = $true)][string]$TargetDir)+ foreach ($name in @("tiktoken", "tiktoken_ext", "tiktoken.libs")) {+ $entry = Join-Path $TargetDir $name+ if (Test-Path -LiteralPath $entry) { Remove-Item -LiteralPath $entry -Recurse -Force -ErrorAction SilentlyContinue }}- if ($t5PkgExit -ne 0) {- Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_530/" -ForegroundColor Red- Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red- $ErrorActionPreference = $prevEAP_t5- Exit-SetupFailure "Could not install $pkg into .venv_t5_530"+ Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |+ ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }+ foreach ($name in @("tiktoken", "tiktoken_ext", "tiktoken.libs")) {+ if (Test-Path -LiteralPath (Join-Path $TargetDir $name)) { return $false }}+ $left = @(Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue)+ return ($left.Count -eq 0)}-if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_530Dir --no-deps tiktoken- $tiktokenInstallExit = $LASTEXITCODE- $output = ""-} else {- $output = Fast-Install --target $VenvT5_530Dir --no-deps tiktoken | Out-String- $tiktokenInstallExit = $LASTEXITCODE++function Retire-SidecarAfterFailedTiktoken {+ param(+ [Parameter(Mandatory = $true)][string]$TargetDir,+ [Parameter(Mandatory = $true)][string]$DirName+ )+ Remove-Item -LiteralPath $TargetDir -Recurse -Force -ErrorAction SilentlyContinue+ substep "$DirName/ kept part of a failed tiktoken install; retired, rebuilt on the next update" "Yellow"}-if ($tiktokenInstallExit -ne 0) {- substep "Could not install tiktoken into .venv_t5_530/ -- Qwen tokenizers may fail" "Yellow"++function Repair-SidecarTiktoken {+ param(+ [Parameter(Mandatory = $true)][string]$TargetDir,+ [Parameter(Mandatory = $true)][string]$DirName+ )+ # Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the+ # other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.+ Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |+ Where-Object { -not (Test-Path -LiteralPath (Join-Path $_.FullName "RECORD") -PathType Leaf) } |+ ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }+ $present = @(Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |+ Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "RECORD") -PathType Leaf })+ $payload = Join-Path $TargetDir "tiktoken"+ if ($present.Count -gt 0 -and (Test-Path -LiteralPath (Join-Path $payload "__init__.py") -PathType Leaf)) { return }+ # Dropping the metadata is what makes uv reinstall instead of calling the pin satisfied.+ Get-ChildItem -LiteralPath $TargetDir -Directory -Filter "tiktoken-*.dist-info" -ErrorAction SilentlyContinue |+ ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }+ # Cleared first: an install that runs no native command would retire the sidecar on a stale+ # nonzero (unresolvable uv is non-terminating under "Continue").+ $global:LASTEXITCODE = 0+ $output = Fast-Install-Sidecar --target $TargetDir --no-deps --upgrade tiktoken 2>&1 | Out-String+ if ($LASTEXITCODE -ne 0) {+ if (Remove-SidecarTiktoken -TargetDir $TargetDir) {+ substep "Could not install tiktoken into $DirName/ -- Qwen tokenizers may fail" "Yellow"+ } else {+ Retire-SidecarAfterFailedTiktoken -TargetDir $TargetDir -DirName $DirName+ }+ }}-step "transformers" "5.3.0 pre-installed"-# --- .venv_t5_550 (transformers 5.5.0) ----substep "pre-installing transformers 5.5.0 for Gemma 4 support..."-Assert-StudioOwnedOrAbsent -Path $VenvT5_550Dir -Label "transformers 5.5 sidecar venv"-if (Test-Path -LiteralPath $VenvT5_550Dir) { Remove-Item -LiteralPath $VenvT5_550Dir -Recurse -Force }-[System.IO.Directory]::CreateDirectory($VenvT5_550Dir) | Out-Null-Mark-StudioOwned -Path $VenvT5_550Dir-foreach ($pkg in @("transformers==5.5.0", "huggingface_hub==1.8.0", "hf_xet==1.4.2")) {- if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_550Dir --no-deps $pkg- $t5PkgExit = $LASTEXITCODE- $output = ""+function Test-SidecarCurrent {+ # One predicate for both shells: the shell reimplementation called a half-written sidecar current.+ param(+ [Parameter(Mandatory = $true)][string]$TargetDir,+ [Parameter(Mandatory = $true)][string]$Version+ )+ if (-not (Test-Path -LiteralPath $TargetDir -PathType Container)) { return $false }+ $shim = Join-Path $PSScriptRoot "install_manifest.py"+ if (-not (Test-Path -LiteralPath $shim -PathType Leaf)) {+ return (Test-TargetPackageVersion -TargetDir $TargetDir -PackageName "transformers" -ExpectedVersion $Version)+ }+ $pins = @("transformers==$Version") + $SidecarCommonPins+ $out = ""+ # A bounded process, not a native command: a native nonzero exit terminates under+ # $PSNativeCommandUseErrorActionPreference. argv is base64 so quoting cannot break -c, and the+ # venv interpreter comes first, as in setup.sh: a PATH `python` can be the Store alias stub.+ $pythonExe = $null+ $probe = $null+ if ($VenvPyExe -and (Test-Path -LiteralPath $VenvPyExe -PathType Leaf)) {+ $pythonExe = $VenvPyExe} else {- $output = Fast-Install --target $VenvT5_550Dir --no-deps $pkg | Out-String- $t5PkgExit = $LASTEXITCODE+ try { $pythonExe = (Get-Command python -ErrorAction Stop).Source } catch { $pythonExe = $null }+ }+ if ($pythonExe) {+ $argv = (@($shim, "sidecar", $TargetDir) + $pins) -join [char]0+ $encoded = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($argv))+ $code = "import sys, runpy, base64; sys.argv = base64.b64decode('$encoded').decode('utf-8').split(chr(0)); runpy.run_path(sys.argv[0], run_name='__main__')"+ $probe = Invoke-BoundedPythonProbe -PythonExe $pythonExe -Code $code -TimeoutSec 60+ if ($probe.TimedOut) {+ $out = "sidecar: audit did not answer within 60 seconds"+ } else {+ $out = ([string]$probe.Output).Trim()+ }}- if ($t5PkgExit -ne 0) {- Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_550/" -ForegroundColor Red- Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red- $ErrorActionPreference = $prevEAP_t5- Exit-SetupFailure "Could not install $pkg into .venv_t5_550"+ if ($out -eq "sidecar: current") { return $true }+ if ($out -like "sidecar:*") {+ # A regex, not Substring: `-like` matches the bare marker too and Substring would throw.+ if ($script:UnslothVerbose) { substep "sidecar $TargetDir`: $($out -replace '^sidecar:\s*', '')" }+ return $false}+ # A failure with no marker is a dead audit, not the legacy silent exit 0.+ if ($null -ne $probe -and -not $probe.Ok) {+ if ($script:UnslothVerbose) { substep "sidecar $TargetDir`: audit failed" }+ return $false+ }+ # An old shim exits 0 silently: fall back to the grep this replaced.+ return (Test-TargetPackageVersion -TargetDir $TargetDir -PackageName "transformers" -ExpectedVersion $Version)}-if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_550Dir --no-deps tiktoken- $tiktokenInstallExit = $LASTEXITCODE- $output = ""-} else {- $output = Fast-Install --target $VenvT5_550Dir --no-deps tiktoken | Out-String- $tiktokenInstallExit = $LASTEXITCODE-}-if ($tiktokenInstallExit -ne 0) {- substep "Could not install tiktoken into .venv_t5_550/ -- Qwen tokenizers may fail" "Yellow"-}-step "transformers" "5.5.0 pre-installed"-# --- .venv_t5_510 (transformers 5.10.2) ----substep "pre-installing transformers 5.10.2 for Gemma 4 Unified support..."-Assert-StudioOwnedOrAbsent -Path $VenvT5_510Dir -Label "transformers 5.10 sidecar venv"-if (Test-Path -LiteralPath $VenvT5_510Dir) { Remove-Item -LiteralPath $VenvT5_510Dir -Recurse -Force }-[System.IO.Directory]::CreateDirectory($VenvT5_510Dir) | Out-Null-Mark-StudioOwned -Path $VenvT5_510Dir-foreach ($pkg in @("transformers==5.10.2", "huggingface_hub==1.8.0", "hf_xet==1.4.2")) {+function Install-T5Sidecar {+ param(+ [Parameter(Mandatory = $true)][string]$TargetDir,+ [Parameter(Mandatory = $true)][string]$Version,+ [Parameter(Mandatory = $true)][string]$Label,+ [Parameter(Mandatory = $true)][string]$DirName,+ [Parameter(Mandatory = $true)][string]$Reason+ )+ substep "pre-installing transformers $Version $Reason..."+ Assert-StudioOwnedOrAbsent -Path $TargetDir -Label "transformers $Label sidecar venv"+ if (Test-Path -LiteralPath $TargetDir) { Remove-Item -LiteralPath $TargetDir -Recurse -Force }+ [System.IO.Directory]::CreateDirectory($TargetDir) | Out-Null+ Mark-StudioOwned -Path $TargetDir+ # From $SidecarCommonPins, not a copy: a pin demanded but never installed reads stale forever.+ foreach ($pkg in @("transformers==$Version") + $SidecarCommonPins) {+ if ($script:UnslothVerbose) {+ Fast-Install-Sidecar --target $TargetDir --no-deps $pkg+ $t5PkgExit = $LASTEXITCODE+ $output = ""+ } else {+ $output = Fast-Install-Sidecar --target $TargetDir --no-deps $pkg | Out-String+ $t5PkgExit = $LASTEXITCODE+ }+ if ($t5PkgExit -ne 0) {+ Write-StudioLine "[FAIL] Could not install $pkg into $DirName/" -ForegroundColor Red+ Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red+ $ErrorActionPreference = $script:PrevEAP_T5+ Exit-SetupFailure "Could not install $pkg into $DirName"+ }+ }if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_510Dir --no-deps $pkg- $t5PkgExit = $LASTEXITCODE+ Fast-Install-Sidecar --target $TargetDir --no-deps tiktoken+ $tiktokenInstallExit = $LASTEXITCODE$output = ""} else {- $output = Fast-Install --target $VenvT5_510Dir --no-deps $pkg | Out-String- $t5PkgExit = $LASTEXITCODE+ $output = Fast-Install-Sidecar --target $TargetDir --no-deps tiktoken | Out-String+ $tiktokenInstallExit = $LASTEXITCODE}- if ($t5PkgExit -ne 0) {- Write-StudioLine "[FAIL] Could not install $pkg into .venv_t5_510/" -ForegroundColor Red- Write-StudioLine (Redact-InstallOutput $output) -ForegroundColor Red- $ErrorActionPreference = $prevEAP_t5- Exit-SetupFailure "Could not install $pkg into .venv_t5_510"+ if ($tiktokenInstallExit -ne 0) {+ if (Remove-SidecarTiktoken -TargetDir $TargetDir) {+ substep "Could not install tiktoken into $DirName/ -- Qwen tokenizers may fail" "Yellow"+ } else {+ Retire-SidecarAfterFailedTiktoken -TargetDir $TargetDir -DirName $DirName+ }}+ step "transformers" "$Version pre-installed"}-if ($script:UnslothVerbose) {- Fast-Install --target $VenvT5_510Dir --no-deps tiktoken- $tiktokenInstallExit = $LASTEXITCODE- $output = ""-} else {- $output = Fast-Install --target $VenvT5_510Dir --no-deps tiktoken | Out-String- $tiktokenInstallExit = $LASTEXITCODE++$_NeedT5_530 = $false+$_NeedT5_550 = $false+$_NeedT5_510 = $false+if (Test-Path -LiteralPath $VenvT5Legacy) {+ # Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.+ if (-not $StageRoot) {+ Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"+ Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force+ }+ $_NeedT5_530 = $true+ $_NeedT5_550 = $true+ $_NeedT5_510 = $true}-if ($tiktokenInstallExit -ne 0) {- substep "Could not install tiktoken into .venv_t5_510/ -- Qwen tokenizers may fail" "Yellow"+if (-not (Test-SidecarCurrent -TargetDir $VenvT5_530Dir -Version "5.3.0")) { $_NeedT5_530 = $true }+if (-not (Test-SidecarCurrent -TargetDir $VenvT5_550Dir -Version "5.5.0")) { $_NeedT5_550 = $true }+if (-not (Test-SidecarCurrent -TargetDir $VenvT5_510Dir -Version "5.10.2")) { $_NeedT5_510 = $true }++if ($_NeedT5_530 -or $_NeedT5_550 -or $_NeedT5_510) {+Write-StudioLine ""}-$ErrorActionPreference = $prevEAP_t5-step "transformers" "5.10.2 pre-installed"-} # end $_NeedT5Install+$script:PrevEAP_T5 = $ErrorActionPreference+$ErrorActionPreference = "Continue"++if ($_NeedT5_530) {+ Install-T5Sidecar -TargetDir $VenvT5_530Dir -Version "5.3.0" -Label "5.3" -DirName ".venv_t5_530" -Reason "for newer model support"+} else {+ step "transformers" "5.3.0 sidecar current"+ Repair-SidecarTiktoken -TargetDir $VenvT5_530Dir -DirName ".venv_t5_530"+}+if ($_NeedT5_550) {+ Install-T5Sidecar -TargetDir $VenvT5_550Dir -Version "5.5.0" -Label "5.5" -DirName ".venv_t5_550" -Reason "for Gemma 4 support"+} else {+ step "transformers" "5.5.0 sidecar current"+ Repair-SidecarTiktoken -TargetDir $VenvT5_550Dir -DirName ".venv_t5_550"+}+if ($_NeedT5_510) {+ Install-T5Sidecar -TargetDir $VenvT5_510Dir -Version "5.10.2" -Label "5.10" -DirName ".venv_t5_510" -Reason "for Gemma 4 Unified support"+} else {+ step "transformers" "5.10.2 sidecar current"+ Repair-SidecarTiktoken -TargetDir $VenvT5_510Dir -DirName ".venv_t5_510"+}+$ErrorActionPreference = $script:PrevEAP_T5# ==========================================================================# PHASE 3.4: Prefer prebuilt llama.cpp bundles before source builddiff --git a/studio/setup.sh b/studio/setup.shindex a196dc2ce6a..a493fd389f9 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -2040,6 +2040,30 @@ sys.exit(0 if installed is not None and required is not None and installed >= resubstep "$_setup_pin_leaf pinned over an XPU wheel -- forcing dependency pass to migrate..."_SKIP_PYTHON_DEPS=falsefi+ # As setup.ps1's "Torch-index pin changed" branch: an explicit cu*/rocm*/cpu pin over+ # ANOTHER family's torch is a request only the dependency pass acts on, and the version+ # compare calls it up to date. Labelled wheels only; custom leaves left alone.+ _setup_pin_have_family=""+ case "${_setup_pin_ver:-}" in+ *+cu[0-9]*) _setup_pin_have_family=cu ;;+ *+rocm*) _setup_pin_have_family=rocm ;;+ *+cpu) _setup_pin_have_family=cpu ;;+ *+xpu) _setup_pin_have_family=xpu ;;+ esac+ _setup_pin_want_family=""+ if [ "$_setup_pin_known_nonxpu" = true ]; then+ case "$_setup_pin_leaf" in+ cu[0-9]*) _setup_pin_want_family=cu ;;+ rocm[0-9]* | gfx[0-9]*) _setup_pin_want_family=rocm ;;+ cpu) _setup_pin_want_family=cpu ;;+ esac+ fi+ if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -n "$_setup_pin_want_family" ] \+ && [ -n "$_setup_pin_have_family" ] && [ "$_setup_pin_have_family" != xpu ] \+ && [ "$_setup_pin_have_family" != "$_setup_pin_want_family" ]; then+ substep "$_setup_pin_leaf pinned over a +$_setup_pin_have_family torch wheel -- forcing dependency pass to reinstall torch from the pin..."+ _SKIP_PYTHON_DEPS=false+ fielif [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ]; thensubstep "$_PKG_NAME $INSTALLED_VER -> $LATEST_VER available, updating..."elif [ -z "$LATEST_VER" ]; then@@ -2093,56 +2117,184 @@ _target_has_pkg_version() {donereturn 1}-_NEED_T5_INSTALL=false+# Audited AND installed from here: a name the audit cannot reach on disk reads stale forever.+_SIDECAR_COMMON_PINS="huggingface_hub==1.8.0 hf_xet==1.4.2"++# Remnants of a failed tiktoken install shadow the ambient copy and nothing else clears them.+_sidecar_drop_tiktoken() {+ for _sdt_entry in "$1"/tiktoken "$1"/tiktoken_ext "$1"/tiktoken.libs "$1"/tiktoken-*.dist-info; do+ [ -e "$_sdt_entry" ] && rm -rf "$_sdt_entry" 2>/dev/null+ done+ _sdt_left=0+ for _sdt_entry in "$1"/tiktoken "$1"/tiktoken_ext "$1"/tiktoken.libs "$1"/tiktoken-*.dist-info; do+ [ -e "$_sdt_entry" ] && _sdt_left=1+ done+ unset _sdt_entry+ if [ "$_sdt_left" = 1 ]; then+ unset _sdt_left+ return 1+ fi+ unset _sdt_left+ return 0+}++_sidecar_retire_after_failed_tiktoken() {+ # `|| true`: best effort under `set -e`, or an undeletable file fails an otherwise fine update.+ rm -rf "$1" 2>/dev/null || true+ substep "the $2 sidecar kept part of a failed tiktoken install; retired, rebuilt on the next update"+}++_sidecar_top_up_tiktoken() {+ _stt_dir="$1"+ _stt_label="$2"+ # Payload AND dist-info (RECORD is written last): an interrupted install leaves one without the+ # other. A recordless dist-info goes first; uv cannot uninstall it, metadata still reads it.+ for _stt_info in "$_stt_dir"/tiktoken-*.dist-info; do+ if [ -d "$_stt_info" ] && [ ! -f "$_stt_info/RECORD" ]; then+ rm -rf "$_stt_info" || true # `|| true`: set -e; the reinstall below handles a leftover+ fi+ done+ unset _stt_info+ for _stt_meta in "$_stt_dir"/tiktoken-*.dist-info/METADATA; do+ if [ -f "$_stt_meta" ] && [ -f "${_stt_meta%METADATA}RECORD" ] && [ -f "$_stt_dir/tiktoken/__init__.py" ]; then+ unset _stt_meta+ return 0+ fi+ done+ unset _stt_meta+ # Dropping the metadata is what makes uv reinstall instead of calling the pin satisfied.+ for _stt_info in "$_stt_dir"/tiktoken-*.dist-info; do+ [ -d "$_stt_info" ] && { rm -rf "$_stt_info" || true; }+ done+ unset _stt_info+ if ! fast_install_sidecar --target "$_stt_dir" --no-deps --upgrade "tiktoken" >/dev/null 2>&1; then+ if _sidecar_drop_tiktoken "$_stt_dir"; then+ substep "could not install tiktoken into the $_stt_label sidecar -- Qwen tokenizers may fail"+ else+ _sidecar_retire_after_failed_tiktoken "$_stt_dir" "$_stt_label"+ fi+ fi+ return 0+}++_sidecar_current() {+ # One predicate for both shells: the version grep called a half-written sidecar current.+ _sc_dir="$1"+ _sc_ver="$2"+ [ -d "$_sc_dir" ] || return 1+ # No shim: answer from the grep, as setup.ps1 does, or every tier reads stale.+ if [ ! -f "$SCRIPT_DIR/install_manifest.py" ]; then+ _target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"+ return $?+ fi+ # Colab has no venv interpreter but the stdlib-only shim runs under its own python.+ _sc_python="$VENV_DIR/bin/python"+ if [ ! -x "$_sc_python" ]; then+ _sc_python=$(command -v python 2>/dev/null || command -v python3 2>/dev/null || true)+ fi+ if [ -z "$_sc_python" ]; then+ unset _sc_python+ _target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"+ return $?+ fi+ # Bounded where timeout exists: the shim cannot interrupt a stalled read. A timeout is stale.+ # shellcheck disable=SC2086 # the pins are a deliberate word-split list+ if command -v timeout >/dev/null 2>&1; then+ _sc_out=$(timeout -k 5 60 "$_sc_python" "$SCRIPT_DIR/install_manifest.py" sidecar "$_sc_dir" \+ "transformers==$_sc_ver" $_SIDECAR_COMMON_PINS 2>/dev/null)+ _sc_rc=$?+ else+ _sc_out=$("$_sc_python" "$SCRIPT_DIR/install_manifest.py" sidecar "$_sc_dir" \+ "transformers==$_sc_ver" $_SIDECAR_COMMON_PINS 2>/dev/null)+ _sc_rc=$?+ fi+ # 124 is timeout's TERM, 137 its KILL.+ if [ "$_sc_rc" -eq 124 ] || [ "$_sc_rc" -eq 137 ]; then+ _sc_out="sidecar: audit did not answer within 60 seconds"+ fi+ unset _sc_python+ case "$_sc_out" in+ "sidecar: current")+ unset _sc_out _sc_rc+ return 0+ ;;+ sidecar:*)+ verbose_substep "sidecar $_sc_dir: ${_sc_out#sidecar: }"+ unset _sc_out _sc_rc+ return 1+ ;;+ esac+ unset _sc_out+ # A failure with no marker is a dead audit, not the legacy silent exit 0.+ if [ "$_sc_rc" -ne 0 ]; then+ verbose_substep "sidecar $_sc_dir: audit failed (exit $_sc_rc)"+ unset _sc_rc+ return 1+ fi+ unset _sc_rc+ # An old shim exits 0 silently: fall back to the grep this replaced.+ _target_has_pkg_version "$_sc_dir" "transformers" "$_sc_ver"+}++_install_sidecar() {+ _is_dir="$1"+ _is_ver="$2"+ _is_label="$3"+ _assert_studio_owned_or_absent "$_is_dir" "transformers $_is_label sidecar venv"+ [ -d "$_is_dir" ] && rm -rf "$_is_dir"+ mkdir -p "$_is_dir"+ : > "$_is_dir/$_STUDIO_OWNED_MARKER" 2>/dev/null || true+ run_quiet "install transformers $_is_ver" fast_install_sidecar --target "$_is_dir" --no-deps "transformers==$_is_ver"+ # From $_SIDECAR_COMMON_PINS, not a copy: a pin demanded but never installed reads stale forever.+ for _is_pin in $_SIDECAR_COMMON_PINS; do+ run_quiet "install ${_is_pin%%==*} for $_is_label" fast_install_sidecar --target "$_is_dir" --no-deps "$_is_pin"+ done+ unset _is_pin+ # Optional, as in setup.ps1; _sidecar_top_up_tiktoken retries it later.+ if ! run_quiet_no_exit "install tiktoken for $_is_label" fast_install_sidecar --target "$_is_dir" --no-deps "tiktoken"; then+ if _sidecar_drop_tiktoken "$_is_dir"; then+ substep "could not install tiktoken into the $_is_label sidecar -- Qwen tokenizers may fail"+ else+ _sidecar_retire_after_failed_tiktoken "$_is_dir" "$_is_label"+ fi+ fi+ step "transformers" "$_is_ver pre-installed"+}++_NEED_T5_530=false+_NEED_T5_550=false+_NEED_T5_510=falseif [ -d "$STUDIO_HOME/.venv_t5" ]; then- # Legacy layout — migrate. The tiered venvs a staged run builds land under the- # stage root and may never be activated, so removing the live legacy one here- # would strip the running install of its only sidecar. The live update does it.+ # Legacy layout. A staged run's venvs may never be activated, so only the live update migrates.if [ -z "$STAGE_ROOT" ]; then_assert_studio_owned_or_absent "$STUDIO_HOME/.venv_t5" "legacy transformers sidecar venv"rm -rf "$STUDIO_HOME/.venv_t5"fi- _NEED_T5_INSTALL=true+ _NEED_T5_530=true+ _NEED_T5_550=true+ _NEED_T5_510=truefi-[ ! -d "$VENV_T5_530_DIR" ] && _NEED_T5_INSTALL=true-[ ! -d "$VENV_T5_550_DIR" ] && _NEED_T5_INSTALL=true-[ ! -d "$VENV_T5_510_DIR" ] && _NEED_T5_INSTALL=true-_target_has_pkg_version "$VENV_T5_530_DIR" "transformers" "5.3.0" || _NEED_T5_INSTALL=true-_target_has_pkg_version "$VENV_T5_550_DIR" "transformers" "5.5.0" || _NEED_T5_INSTALL=true-_target_has_pkg_version "$VENV_T5_510_DIR" "transformers" "5.10.2" || _NEED_T5_INSTALL=true-# Also reinstall when python deps were updated (packages may need rebuild)-[ "$_SKIP_PYTHON_DEPS" = false ] && _NEED_T5_INSTALL=true--if [ "$_NEED_T5_INSTALL" = true ]; then- _assert_studio_owned_or_absent "$VENV_T5_530_DIR" "transformers 5.3 sidecar venv"- [ -d "$VENV_T5_530_DIR" ] && rm -rf "$VENV_T5_530_DIR"- mkdir -p "$VENV_T5_530_DIR"- : > "$VENV_T5_530_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true- run_quiet "install transformers 5.3.0" fast_install_sidecar --target "$VENV_T5_530_DIR" --no-deps "transformers==5.3.0"- run_quiet "install huggingface_hub for t5_530" fast_install_sidecar --target "$VENV_T5_530_DIR" --no-deps "huggingface_hub==1.8.0"- run_quiet "install hf_xet for t5_530" fast_install_sidecar --target "$VENV_T5_530_DIR" --no-deps "hf_xet==1.4.2"- run_quiet "install tiktoken for t5_530" fast_install_sidecar --target "$VENV_T5_530_DIR" --no-deps "tiktoken"- step "transformers" "5.3.0 pre-installed"-- _assert_studio_owned_or_absent "$VENV_T5_550_DIR" "transformers 5.5 sidecar venv"- [ -d "$VENV_T5_550_DIR" ] && rm -rf "$VENV_T5_550_DIR"- mkdir -p "$VENV_T5_550_DIR"- : > "$VENV_T5_550_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true- run_quiet "install transformers 5.5.0" fast_install_sidecar --target "$VENV_T5_550_DIR" --no-deps "transformers==5.5.0"- run_quiet "install huggingface_hub for t5_550" fast_install_sidecar --target "$VENV_T5_550_DIR" --no-deps "huggingface_hub==1.8.0"- run_quiet "install hf_xet for t5_550" fast_install_sidecar --target "$VENV_T5_550_DIR" --no-deps "hf_xet==1.4.2"- run_quiet "install tiktoken for t5_550" fast_install_sidecar --target "$VENV_T5_550_DIR" --no-deps "tiktoken"- step "transformers" "5.5.0 pre-installed"-- _assert_studio_owned_or_absent "$VENV_T5_510_DIR" "transformers 5.10 sidecar venv"- [ -d "$VENV_T5_510_DIR" ] && rm -rf "$VENV_T5_510_DIR"- mkdir -p "$VENV_T5_510_DIR"- : > "$VENV_T5_510_DIR/$_STUDIO_OWNED_MARKER" 2>/dev/null || true- run_quiet "install transformers 5.10.2" fast_install_sidecar --target "$VENV_T5_510_DIR" --no-deps "transformers==5.10.2"- run_quiet "install huggingface_hub for t5_510" fast_install_sidecar --target "$VENV_T5_510_DIR" --no-deps "huggingface_hub==1.8.0"- run_quiet "install hf_xet for t5_510" fast_install_sidecar --target "$VENV_T5_510_DIR" --no-deps "hf_xet==1.4.2"- run_quiet "install tiktoken for t5_510" fast_install_sidecar --target "$VENV_T5_510_DIR" --no-deps "tiktoken"- step "transformers" "5.10.2 pre-installed"+_sidecar_current "$VENV_T5_530_DIR" "5.3.0" || _NEED_T5_530=true+_sidecar_current "$VENV_T5_550_DIR" "5.5.0" || _NEED_T5_550=true+_sidecar_current "$VENV_T5_510_DIR" "5.10.2" || _NEED_T5_510=true++if [ "$_NEED_T5_530" = true ]; then+ _install_sidecar "$VENV_T5_530_DIR" "5.3.0" "5.3"+else+ step "transformers" "5.3.0 sidecar current"+ _sidecar_top_up_tiktoken "$VENV_T5_530_DIR" "5.3"+fi+if [ "$_NEED_T5_550" = true ]; then+ _install_sidecar "$VENV_T5_550_DIR" "5.5.0" "5.5"+else+ step "transformers" "5.5.0 sidecar current"+ _sidecar_top_up_tiktoken "$VENV_T5_550_DIR" "5.5"+fi+if [ "$_NEED_T5_510" = true ]; then+ _install_sidecar "$VENV_T5_510_DIR" "5.10.2" "5.10"+else+ step "transformers" "5.10.2 sidecar current"+ _sidecar_top_up_tiktoken "$VENV_T5_510_DIR" "5.10"fifidiff --git a/tests/python/test_cross_platform_parity.py b/tests/python/test_cross_platform_parity.pyindex 87b67e62fec..cc0248eab4f 100644--- a/tests/python/test_cross_platform_parity.py+++ b/tests/python/test_cross_platform_parity.py@@ -998,8 +998,13 @@ class TestNoTorchPersistenceParity:# Written after the manifest is dropped and before the dependency pass, so# a pass killed part-way still leaves the mode recorded somewhere.assert text.index("install_manifest.set_no_torch_marker(NO_TORCH)") > text.index(- "if not install_manifest.remove_manifest():"+ "if install_manifest.remove_manifest():")+ # And the parked copy goes with it before the pass starts, so a pass killed part-way leaves+ # no evidence of a finished one.+ removed_at = text.index("if install_manifest.remove_manifest():")+ consumed_at = text.index("install_manifest.consume_previous_manifest()", removed_at)+ assert consumed_at < text.index("install_manifest.set_no_torch_marker(NO_TORCH)")def test_both_sides_use_the_same_marker_filename(self):manifest = (REPO_ROOT / "studio" / "install_manifest.py").read_text(encoding = "utf-8")diff --git a/tests/python/test_tokenizers_and_torch_constraint.py b/tests/python/test_tokenizers_and_torch_constraint.pyindex 175998cf8b5..21d4ead4935 100644--- a/tests/python/test_tokenizers_and_torch_constraint.py+++ b/tests/python/test_tokenizers_and_torch_constraint.py@@ -180,7 +180,12 @@ def test_setup_sh_sidecar_installs_isolate_uv_override():result = subprocess.run(["bash", "-c", script], capture_output = True, text = True)assert result.returncode == 0 and result.stdout.splitlines() == ["child=unset", "parent=base"]sidecars = source.split("# ── 6b.", 1)[1].split("# ── GPU detection", 1)[0]- assert sidecars.count("fast_install_sidecar --target") == 12+ # Four call sites in ONE helper per tier plus the tiktoken top-up (it used to be twelve,+ # written out three times): transformers, the $_SIDECAR_COMMON_PINS loop, tiktoken, and the+ # top-up's reinstall. Every sidecar install must go through the UV_OVERRIDE-clearing wrapper.+ assert sidecars.count("fast_install_sidecar --target") == 4+ assert sidecars.count('_install_sidecar "$VENV_T5_') == 3+ assert sidecars.count('_sidecar_top_up_tiktoken "$VENV_T5_') == 3assert " fast_install --target" not in sidecarsdiff --git a/tests/sh/test_setup_xpu_fastpath_escape.sh b/tests/sh/test_setup_xpu_fastpath_escape.shindex fe0cd330771..bcaf14f178d 100755--- a/tests/sh/test_setup_xpu_fastpath_escape.sh+++ b/tests/sh/test_setup_xpu_fastpath_escape.sh@@ -31,7 +31,7 @@ awk '/_setup_pin="\$\{UNSLOTH_TORCH_INDEX_URL/{on=1} on && /^ elif \[ -n "\$I[ -s "$WORK/blk.sh" ] || { echo "FATAL: escape block not found in $SETUP_SH" >&2; exit 1; }# An extraction that lost any of the three moving parts would make cases below pass vacuously._arms=$(grep -c '_SKIP_PYTHON_DEPS=false' "$WORK/blk.sh")-[ "$_arms" = "3" ] || { echo "FATAL: expected 3 escape arms, extracted $_arms" >&2; exit 1; }+[ "$_arms" = "4" ] || { echo "FATAL: expected 4 escape arms, extracted $_arms" >&2; exit 1; }for _need in _setup_pin_leaf _setup_pin_is_xpu _setup_generic_triton _setup_pin_known_nonxpu \_setup_known_nonxpu_leaf; dogrep -q "$_need" "$WORK/blk.sh" || { echo "FATAL: extraction lost $_need" >&2; exit 1; }@@ -101,6 +101,17 @@ check "no pin, untagged wheel" "$(escape "$(make_venv '2.9.1' yes f)" "")" truecheck "no pin, no torch at all" "$(escape "$(make_venv '' yes g)" "")" truecheck "no pin, no venv at all" "$(escape "$WORK/nope" "")" true+echo "an explicit pin of another curated family over a labelled wheel forces the pass (setup.ps1 parity)"+check "cu128 pin, +cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no h)" "" cu128)" false+check "cu128 pin, +cu130 wheel" "$(escape "$(make_venv '2.9.1+cu130' no i)" "" cu128)" true+check "rocm7.1 pin, +cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no j)" "" rocm7.1)" false+check "gfx1201 pin, +cu128 wheel" "$(escape "$(make_venv '2.9.1+cu128' no k)" "" gfx1201)" false+check "cpu pin, +cu130 wheel" "$(escape "$(make_venv '2.9.1+cu130' no l)" "" cpu)" false+check "cu128 pin, untagged wheel" "$(escape "$(make_venv '2.9.1' no m)" "" cu128)" true+check "cu128 pin, no torch at all" "$(escape "$(make_venv '' no n)" "" cu128)" true+check "cu128-private pin, +cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no o)" "" cu128-private)" true+check "cu128 URL pin, +cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no p)" "https://download.pytorch.org/whl/cu128")" false+echo "an explicit xpu pin still repairs a mismatched wheel"check "pin + cpu wheel" "$(escape "$(make_venv '2.9.1+cpu' no h)" "$XPU")" falsecheck "pin + no torch" "$(escape "$(make_venv '' no i)" "$XPU")" falsediff --git a/tests/studio/install/conftest.py b/tests/studio/install/conftest.pyindex 86104231f33..de2369fd6bc 100644--- a/tests/studio/install/conftest.py+++ b/tests/studio/install/conftest.py@@ -5,10 +5,82 @@from __future__ import annotations+import osimport sysfrom pathlib import Path+from types import ModuleType++import pytest# <repo-root>/studio → makes `backend` importable as a package_STUDIO_DIR = Path(__file__).resolve().parents[3] / "studio"if str(_STUDIO_DIR) not in sys.path:sys.path.insert(0, str(_STUDIO_DIR))+++_STACK_FILE = _STUDIO_DIR / "install_python_stack.py"++# What install_python_stack() resets at the top of every pass: the module is loaded once per test+# FILE, so without this each test measures the previous one.+_PASS_STATE_DEFAULTS = {+ "_INSTALL_ACTIONS": 0,+ "_PASS_EVIDENCE": None,+ "_CONSTRAINTS_CACHE": None,+ "_CLOSURE_INDEX_CACHE": None,+ "_BNB_ROCM_PASS_PROVENANCE": None,+ "_BNB_ROCM_PASS_ASSET": None,+}+++def _loaded_stacks(test_module):+ """Every live copy of install_python_stack, sys.modules or not.++ Three test files load it into sys.modules under the same name+ ("studio_install_python_stack"), so the last one imported owns that key and the+ others keep a module object nothing in sys.modules points at any more. Resetting+ only sys.modules leaves those copies carrying the previous test's pass state, which+ is invisible when the file runs alone and decides the answer when the directory+ runs together. So the module under test is looked up through the test file that+ holds it as well.+ """+ target = os.path.realpath(_STACK_FILE)+ found = {}+ candidates = list(sys.modules.values())+ if test_module is not None:+ candidates.extend(vars(test_module).values())+ for module in candidates:+ if not isinstance(module, ModuleType):+ continue+ path = getattr(module, "__file__", None)+ if not path:+ continue+ try:+ if os.path.realpath(path) != target:+ continue+ except OSError:+ continue+ found[id(module)] = module+ return found.values()+++def _reset_pass_state(test_module) -> None:+ for module in _loaded_stacks(test_module):+ for name, value in _PASS_STATE_DEFAULTS.items():+ if hasattr(module, name):+ setattr(module, name, value)+ results = getattr(module, "_STEP_RESULTS", None)+ if isinstance(results, dict):+ results.clear()++[email protected](autouse = True)+def reset_install_pass_state(request):+ """Start and end every test with the state a fresh dependency pass would have.++ Here rather than in each file because the state belongs to install_python_stack, not+ to any one suite, and a file that forgets it fails in a way that only shows up when+ the whole directory runs in one process.+ """+ _reset_pass_state(request.module)+ yield+ _reset_pass_state(request.module)diff --git a/tests/studio/install/test_base_requirements_reach_install.py b/tests/studio/install/test_base_requirements_reach_install.pyindex 9eadbf92f5b..e61f91fcf29 100644--- a/tests/studio/install/test_base_requirements_reach_install.py+++ b/tests/studio/install/test_base_requirements_reach_install.py@@ -126,7 +126,13 @@ class TestSharedBaseSelection:class TestSharedBasePhase:- def _run(self, req: Path | None, *, skip_base: bool) -> tuple[list[Path], list[str]]:+ def _run(+ self,+ req: Path | None,+ *,+ skip_base: bool,+ satisfied: bool = False,+ ) -> tuple[list[Path], list[str]]:installs: list[Path] = []progress: list[str] = []@@ -146,6 +152,9 @@ class TestSharedBasePhase:"_step": lambda *_args, **_kwargs: None,"_LABEL": "python","pip_install": record_install,+ # The skip gate, stubbed: this class pins that the shared file reaches BOTH core paths.+ "_requirements_satisfied": lambda *_args, **_kwargs: satisfied,+ "_record_step": lambda *_args, **_kwargs: None,}exec(compile(module, "<shared base phase>", "exec"), namespace)return installs, progress@@ -157,6 +166,16 @@ class TestSharedBasePhase:installs, _progress = self._run(req, skip_base = skip_base)assert installs == [req]+ @pytest.mark.parametrize("skip_base", [False, True])+ def test_an_already_satisfied_file_still_spends_the_slot(self, tmp_path, skip_base):+ """A skipped step must cost nothing but its progress slot: the denominator+ cannot depend on how much of the install was already there."""+ req = tmp_path / "base.txt"+ req.write_text(_EXTRA_PIN + "\n", encoding = "utf-8")+ installs, progress = self._run(req, skip_base = skip_base, satisfied = True)+ assert installs == []+ assert progress == (["base requirements (satisfied, skipped)"] if skip_base else [])+def test_shell_handoff_owns_the_progress_slot_when_shared_work_exists(self, tmp_path):req = tmp_path / "base.txt"req.write_text(_EXTRA_PIN + "\n", encoding = "utf-8")diff --git a/tests/studio/install/test_dependency_pass_skips.py b/tests/studio/install/test_dependency_pass_skips.pynew file mode 100644index 00000000000..65b8b4280dd--- /dev/null+++ b/tests/studio/install/test_dependency_pass_skips.py@@ -0,0 +1,2293 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The dependency pass must be idempotent: a second `unsloth studio update` does no+network work and leaves the install byte-identical.++Every skip is legal only when (a) the previous run recorded that it did this exact work,+(b) the inputs are byte-identical, and (c) a cheap on-disk check of the output passes.+This file is the unit half of that; the end-to-end half is+tests/studio/install/test_update_idempotency.py, which runs a real install.++The direction that matters is asymmetric. A needless install costs seconds. A wrong skip+ships a venv that answers `-h` and dies on `import structlog`, which is exactly the+failure the manifest was added to catch -- so every case below that cannot prove the+work was done asserts that the work runs.+"""++from __future__ import annotations++import ast+import importlib.util+import json+import os+import pathlib+import platform+import re+import sys+import tempfile+import types++import pytest++REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]+STACK_PATH = REPO_ROOT / "studio" / "install_python_stack.py"+++def _load():+ sys.path.insert(0, str(REPO_ROOT / "studio"))+ try:+ spec = importlib.util.spec_from_file_location("studio_stack_pass_skips", STACK_PATH)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ finally:+ if sys.path and sys.path[0] == str(REPO_ROOT / "studio"):+ sys.path.pop(0)+ return module+++stack = _load()+++# -- the plan ------------------------------------------------------------------+++def manifest(monkeypatch, tmp_path):+ """A manifest and requirements tree that _plan_pass would accept."""+ req_root = tmp_path / "requirements"+ (req_root / "single-env").mkdir(parents = True)+ for name in stack.install_manifest.PASS_INPUT_FILES:+ (req_root / name).write_text(f"# {name}\n", encoding = "utf-8")+ monkeypatch.setattr(stack, "REQ_ROOT", req_root)+ monkeypatch.setattr(stack, "CONSTRAINTS", req_root / "single-env" / "constraints.txt")+ monkeypatch.setattr(stack, "NO_TORCH", False)+ monkeypatch.setattr(stack, "IS_MAC_ARM", False)+ monkeypatch.setattr(stack, "IS_WINDOWS", False)+ monkeypatch.setattr(stack, "PLATFORM_LACKS_TORCHCODEC_WHEEL", False)+ monkeypatch.setattr(stack, "_expected_torch_flavor_tag", lambda: "cpu")+ monkeypatch.setattr(stack, "_recordable_torch_flavor_tag", lambda tag: tag)+ payload = {+ "schema": stack.install_manifest.MANIFEST_SCHEMA,+ "python": platform.python_version(),+ "platform": f"{sys.platform}-{platform.machine()}",+ "no_torch": False,+ "expected_torch_tag": "cpu",+ "installer_python_tag": stack._installer_python_tag(),+ "pass_inputs": stack.install_manifest.pass_input_digests(req_root),+ "step_results": {name: "ran" for name in stack.install_manifest.PASS_INPUT_FILES},+ }+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: dict(payload))+ monkeypatch.setattr(+ stack.install_manifest, "verify_install", lambda *a, **k: {"ok": True, "reason": None}+ )+ return payload, req_root+++def _plan(**kwargs):+ return stack._plan_pass(+ kwargs.pop("package_name", "unsloth"), kwargs.pop("local_repo", ""), kwargs.pop("ci", "")+ )+++def test_a_clean_manifest_plans_a_skippable_pass(manifest) -> None:+ plan = _plan()+ assert plan is not None+ assert plan["pass_inputs"] == manifest[0]["pass_inputs"]++[email protected]("value", ["1", "true", "YES", "on"])+def test_full_deps_forces_everything(monkeypatch, manifest, value) -> None:+ """The escape hatch. A skip nobody can turn off is a bug nobody can work around."""+ monkeypatch.setenv(stack._FULL_DEPS_ENV, value)+ assert _plan() is None++[email protected]("value", ["0", "false", "", "maybe"])+def test_a_non_true_full_deps_value_changes_nothing(monkeypatch, manifest, value) -> None:+ monkeypatch.setenv(stack._FULL_DEPS_ENV, value)+ assert _plan() is not None+++def test_a_peer_already_in_a_pass_forces_everything(monkeypatch, manifest) -> None:+ """Its packages are the ones this evidence describes, so nothing may be skipped on it."""+ monkeypatch.setattr(stack, "_PASS_UNCONTENDED", False)+ assert _plan() is None+++def test_the_pass_runs_inside_the_pass_lock() -> None:+ """The flag has to cover the whole pass: a lock dropped early proves nothing."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ assert "@_under_pass_lock\ndef install_python_stack() -> int:" in source+ wrapper = source[source.index("def _under_pass_lock(") : source.index("@_under_pass_lock")]+ assert "with install_manifest.pass_lock() as uncontended:" in wrapper+ assert "return func(*args, **kwargs)" in wrapper+++ "kwargs",+ [+ {"local_repo": "/checkout"},+ {"ci": "1"},+ {"package_name": "unsloth-nightly"},+ ],+)+def test_dev_shapes_never_skip(manifest, kwargs) -> None:+ """An editable overlay or another package name means the tree on disk is not the+ tree the manifest describes, and its digests describe neither."""+ assert _plan(**kwargs) is None+++ "mutation",+ [+ {"schema": 2},+ {"pass_inputs": None},+ {"step_results": None},+ {"pass_inputs": "not a dict"},+ {"python": "3.0.0"},+ # A GIL and a free-threaded build share the version string; only the tag differs.+ {"installer_python_tag": "999t"},+ {"installer_python_tag": None},+ {"platform": "sunos-vax"},+ {"no_torch": True},+ {"no_torch": None},+ {"expected_torch_tag": "cu128"},+ {"expected_torch_tag": None},+ ],+)+def test_a_moved_input_forces_a_full_pass(monkeypatch, manifest, mutation) -> None:+ payload, _req_root = manifest+ payload.update(mutation)+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: dict(payload))+ assert _plan() is None+++def test_no_manifest_at_all_forces_a_full_pass(monkeypatch, manifest) -> None:+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: None)+ monkeypatch.setattr(stack.install_manifest, "read_previous_manifest", lambda *a, **k: None)+ assert _plan() is None+++def test_a_parked_manifest_is_evidence_when_the_live_one_is_gone(monkeypatch, manifest) -> None:+ """setup.ps1 parks the manifest before the installer starts; the pass still has to+ find last run's evidence there, and verify the tree against that same copy."""+ payload, _ = manifest+ seen = {}+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: None)+ monkeypatch.setattr(+ stack.install_manifest, "read_previous_manifest", lambda *a, **k: dict(payload)+ )++ def _verify(*a, **k):+ seen["manifest"] = k.get("manifest")+ return {"ok": True, "reason": None}++ monkeypatch.setattr(stack.install_manifest, "verify_install", _verify)+ plan = _plan()+ assert plan is not None+ assert plan["pass_inputs"] == payload["pass_inputs"]+ assert seen["manifest"] == payload+++def test_a_damaged_install_forces_a_full_pass(monkeypatch, manifest) -> None:+ """verify_install(deep=True) is the only check that walks the filesystem, and it is+ the one that catches a payload quarantined after the manifest was written."""+ monkeypatch.setattr(+ stack.install_manifest,+ "verify_install",+ lambda *a, **k: {"ok": False, "reason": "studio_install_damaged"},+ )+ assert _plan() is None+++def test_a_probe_that_raises_forces_a_full_pass(monkeypatch, manifest) -> None:+ def boom(*_a, **_k):+ raise RuntimeError("the venv is unreadable")++ monkeypatch.setattr(stack.install_manifest, "verify_install", boom)+ assert _plan() is None+ monkeypatch.setattr(stack, "_expected_torch_flavor_tag", boom)+ assert _plan() is None+++# -- one step's evidence -------------------------------------------------------+++def gated(monkeypatch, manifest):+ payload, req_root = manifest+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", _plan())+ monkeypatch.setattr(stack, "_CONSTRAINTS_CACHE", None)+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 0)+ monkeypatch.setattr(stack.install_manifest, "missing_requirements", lambda *a, **k: [])+ monkeypatch.setattr(stack.install_manifest, "violated_constraints", lambda *a, **k: [])+ return payload, req_root+++def test_a_step_with_unchanged_inputs_is_skipped(gated) -> None:+ _payload, req_root = gated+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is True+++def test_nothing_is_skipped_without_evidence(monkeypatch, gated) -> None:+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", None)+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_a_step_the_last_run_never_reached_is_not_skipped(monkeypatch, gated) -> None:+ """The manifest is written at the end, so a pass killed after step 8 records+ nothing for step 9. Absent must never read as done."""+ evidence = dict(stack._PASS_EVIDENCE)+ evidence["step_results"] = {+ key: value for key, value in evidence["step_results"].items() if key != "studio.txt"+ }+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", evidence)+ assert stack._requirements_satisfied(gated[1] / "studio.txt", no_deps = False) is False+++def test_a_one_byte_edit_to_the_file_runs_the_step(gated) -> None:+ _payload, req_root = gated+ (req_root / "studio.txt").write_text("# studio.txt \n", encoding = "utf-8")+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_a_moved_constraint_runs_every_constrained_step(gated) -> None:+ """A constraint that moved under an unchanged requirements file is exactly what+ digest equality on the file alone cannot see."""+ _payload, req_root = gated+ (req_root / "single-env" / "constraints.txt").write_text("numpy<2\n", encoding = "utf-8")+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+ # ...but not the unconstrained one, which never reads that file.+ assert (+ stack._requirements_satisfied(+ req_root / "triton-kernels.txt", no_deps = True, constrain = False+ )+ is True+ )+++def test_the_mac_overrides_file_counts_on_mac_arm(monkeypatch, gated) -> None:+ """It reaches uv through UV_OVERRIDE rather than the command line, so nothing else+ in the recorded inputs would notice it moving."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "IS_MAC_ARM", True)+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is True+ (req_root / "single-env" / "overrides-darwin-arm64.txt").write_text("x\n", encoding = "utf-8")+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_an_uninstalled_requirement_runs_the_step(monkeypatch, gated) -> None:+ """(c): the output has to still be on disk. A venv edited after the install is the+ case a recorded digest cannot see."""+ _payload, req_root = gated+ monkeypatch.setattr(stack.install_manifest, "missing_requirements", lambda *a, **k: ["rich"])+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_a_violated_constraint_runs_the_step(monkeypatch, gated) -> None:+ _payload, req_root = gated+ monkeypatch.setattr(stack.install_manifest, "violated_constraints", lambda *a, **k: ["numpy"])+ monkeypatch.setattr(stack, "_CONSTRAINTS_CACHE", None)+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_a_file_outside_the_requirements_tree_is_never_skipped(gated) -> None:+ """--local points base.txt somewhere else; there is no manifest key for it."""+ _payload, req_root = gated+ assert stack._requirements_satisfied(req_root.parent / "elsewhere.txt", no_deps = False) is False+++def test_the_constraint_scan_is_redone_after_an_install(monkeypatch, gated) -> None:+ """Cached per pass, because every gated step asks -- but a step that installed+ something can have satisfied or broken a constraint the next step reads."""+ answers = iter([["numpy"], []])+ monkeypatch.setattr(+ stack.install_manifest, "violated_constraints", lambda *a, **k: next(answers)+ )+ monkeypatch.setattr(stack, "_CONSTRAINTS_CACHE", None)+ assert stack._violated_constraints() == ["numpy"]+ assert stack._violated_constraints() == ["numpy"] # cached+ stack._count_install_action()+ assert stack._violated_constraints() == []+++def test_the_progress_slot_is_spent_either_way(monkeypatch, gated) -> None:+ """The denominator cannot depend on how much of the install was already there."""+ _payload, req_root = gated+ seen: list[str] = []+ monkeypatch.setattr(stack, "_progress", seen.append)+ assert stack._skip_step(req_root / "studio.txt", "studio deps", no_deps = False) is True+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", None)+ assert stack._skip_step(req_root / "studio.txt", "studio deps", no_deps = False) is False+ assert seen == ["studio deps (satisfied, skipped)", "studio deps"]+++def test_an_extra_check_can_veto_a_skip(monkeypatch, gated) -> None:+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_progress", lambda *_a: None)+ assert (+ stack._skip_step(+ req_root / "studio.txt", "studio deps", no_deps = False, extra_check = lambda: False+ )+ is False+ )+ assert (+ stack._skip_step(+ req_root / "studio.txt", "studio deps", no_deps = False, extra_check = lambda: True+ )+ is True+ )+++# -- the effective requirements file -------------------------------------------+++def test_the_gate_audits_the_file_the_install_would_use(monkeypatch, tmp_path) -> None:+ """extras.txt names torchcodec and three platforms filter it out. Auditing the raw+ file would report it missing on every one of them and never skip anything again."""+ req = tmp_path / "extras.txt"+ req.write_text("rich\ntorchcodec\n", encoding = "utf-8")+ monkeypatch.setattr(stack, "IS_WINDOWS", False)+ monkeypatch.setattr(stack, "NO_TORCH", False)+ monkeypatch.setattr(stack, "PLATFORM_LACKS_TORCHCODEC_WHEEL", True)+ effective, temps = stack._effective_requirements(req)+ try:+ assert effective != req+ assert effective.read_text(encoding = "utf-8") == "rich\n"+ finally:+ for temp in temps:+ temp.unlink(missing_ok = True)+++def test_an_unfiltered_file_is_used_as_is(monkeypatch, tmp_path) -> None:+ req = tmp_path / "extras.txt"+ req.write_text("rich\n", encoding = "utf-8")+ monkeypatch.setattr(stack, "IS_WINDOWS", False)+ monkeypatch.setattr(stack, "NO_TORCH", False)+ monkeypatch.setattr(stack, "PLATFORM_LACKS_TORCHCODEC_WHEEL", False)+ effective, temps = stack._effective_requirements(req)+ assert effective == req and temps == []+++def test_pip_install_and_the_gate_share_one_filter() -> None:+ """Two copies of the filter list is how the two would disagree, and a disagreement+ here reads as "already installed" for a package the install never had."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ body = source[source.index("def pip_install(") : source.index("def download_file(")]+ assert "_effective_requirements(req)" in body+ assert "_filter_requirements(" not in body+++# -- the git requirement -------------------------------------------------------+++def test_a_git_requirement_is_matched_by_ref_not_version(monkeypatch, tmp_path) -> None:+ """The same version is published from every branch, so a release/3.6.x pin is+ satisfied on paper by a build from main. direct_url.json is the only place the ref+ survives the install."""+ req = tmp_path / "triton-kernels.txt"+ req.write_text(+ "# comment\n"+ "triton_kernels @ git+https://example.invalid/triton.git@release/3.6.x"+ "#subdirectory=python/triton_kernels\n",+ encoding = "utf-8",+ )+ assert stack._direct_reference_in_requirements(req) == (+ "https://example.invalid/triton.git",+ "release/3.6.x",+ "python/triton_kernels",+ )++ # A commit, the only ref that cannot move under the requirements text.+ commit = "0123456789abcdef0123456789abcdef01234567"+ req.write_text(+ f"triton_kernels @ git+https://example.invalid/triton.git@{commit}"+ "#subdirectory=python/triton_kernels\n",+ encoding = "utf-8",+ )+ recorded = {+ "url": "https://example.invalid/triton.git",+ "subdirectory": "python/triton_kernels",+ "vcs_info": {"vcs": "git", "requested_revision": commit},+ }++ class _Dist:+ def __init__(self, payload):+ self._payload = payload++ def read_text(self, _name):+ return json.dumps(self._payload) if self._payload is not None else None++ import importlib.metadata++ def _distribution(payload):+ return lambda _name: _Dist(payload)++ monkeypatch.setattr(importlib.metadata, "distribution", _distribution(recorded))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is True++ for broken in (+ {**recorded, "vcs_info": {"vcs": "git", "requested_revision": "main"}},+ {**recorded, "url": "https://example.invalid/other.git"},+ {**recorded, "subdirectory": "python/other"},+ {"url": recorded["url"]},+ None,+ ):+ monkeypatch.setattr(importlib.metadata, "distribution", _distribution(broken))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is False+++def test_a_mutable_git_ref_is_evidence_only_while_the_remote_still_points_at_it(+ tmp_path, monkeypatch, capsys+) -> None:+ """release/3.6.x advances without the requirements text changing, and+ direct_url.json records the commit that landed, not whether the branch still points+ at it. So the remote is asked (one ls-remote): the same commit is evidence, a moved+ branch runs the step, and a remote that cannot be reached keeps the installed build+ rather than failing the whole update over a training speedup."""+ req = tmp_path / "t.txt"+ req.write_text(+ "triton_kernels @ git+https://example.invalid/triton.git@release/3.6.x"+ "#subdirectory=python/triton_kernels\n",+ encoding = "utf-8",+ )+ commit = "0123456789abcdef0123456789abcdef01234567"+ recorded = {+ "url": "https://example.invalid/triton.git",+ "subdirectory": "python/triton_kernels",+ "vcs_info": {"vcs": "git", "requested_revision": "release/3.6.x", "commit_id": commit},+ }++ class _Dist:+ def __init__(self, payload):+ self._payload = payload++ def read_text(self, _name):+ return json.dumps(self._payload)++ import importlib.metadata++ monkeypatch.setattr(importlib.metadata, "distribution", lambda _name: _Dist(recorded))+ asked: list = []++ def _remote(answer):+ def _ask(+ url,+ revision,+ timeout = 45,+ ):+ asked.append((url, revision))+ return answer++ return _ask++ # The branch still points at the installed commit: evidence, no reinstall.+ monkeypatch.setattr(stack, "_git_remote_commit", _remote(commit))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is True+ assert asked == [("https://example.invalid/triton.git", "release/3.6.x")]++ # The branch moved: the step runs.+ monkeypatch.setattr(stack, "_git_remote_commit", _remote("f" * 40))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is False++ # The remote cannot be reached: the installed build is kept, and the log says so.+ monkeypatch.setattr(stack, "_git_remote_commit", _remote(None))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is True+ # Whitespace-normalised: _note wraps to the terminal width, so on an 80-column+ # terminal -- every xdist worker, and CI runs this suite with -n 4 -- the sentence+ # breaks mid-phrase and a literal substring match fails for no reason of substance.+ assert "keeping the installed build 0123456789ab" in " ".join(capsys.readouterr().out.split())++ # Without a recorded commit there is nothing to compare: the step runs, offline or not.+ without_commit = {**recorded, "vcs_info": {"vcs": "git", "requested_revision": "release/3.6.x"}}+ monkeypatch.setattr(importlib.metadata, "distribution", lambda _name: _Dist(without_commit))+ monkeypatch.setattr(stack, "_git_remote_commit", _remote(commit))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is False++ # A different branch recorded: not this requirement's build, whatever the remote says.+ other_branch = {**recorded, "vcs_info": {**recorded["vcs_info"], "requested_revision": "main"}}+ monkeypatch.setattr(importlib.metadata, "distribution", lambda _name: _Dist(other_branch))+ assert stack._direct_reference_is_installed(req, "triton_kernels") is False+++def test_the_triton_step_keeps_a_current_build_even_on_a_full_pass(monkeypatch, capsys) -> None:+ """With no usable recorded evidence `_skip_step` says "run"; the step still asks the+ remote and keeps the resident build when the branch has not moved (or cannot be+ asked), and installs only when it has. Nothing is asked twice."""+ installs: list = []+ recorded: list = []+ asked: list = []+ monkeypatch.setattr(stack, "_has_working_git", lambda: True)+ monkeypatch.setattr(stack, "pip_install", lambda *a, **k: installs.append((a, k)))+ monkeypatch.setattr(stack, "_record_step", lambda key, outcome: recorded.append((key, outcome)))+ monkeypatch.setattr(stack, "_progress", lambda *_a, **_k: None)+ # The keep also wants the payload intact and no forced pass; both at the end of this test.+ payload_intact = {"value": True}+ monkeypatch.setattr(stack, "_payload_recorded_intact", lambda dist: payload_intact["value"])+ monkeypatch.setattr(stack, "_full_deps_requested", lambda: False)++ def _skip(+ req,+ label,+ *,+ no_deps,+ constrain,+ extra_check = None,+ ):+ # A full pass: the requirement is not counted as satisfied, extra_check unasked.+ return False++ monkeypatch.setattr(stack, "_skip_step", _skip)++ def _current(answer):+ def _ask(req, dist):+ asked.append((req.name, dist))+ return answer++ return _ask++ monkeypatch.setattr(stack, "_direct_reference_is_installed", _current(True))+ stack._triton_kernels_step()+ assert installs == []+ assert asked == [("triton-kernels.txt", "triton_kernels")]+ assert recorded and recorded[-1][1] == "skipped"+ assert "kept" in capsys.readouterr().out++ asked.clear()+ monkeypatch.setattr(stack, "_direct_reference_is_installed", _current(False))+ stack._triton_kernels_step()+ assert len(installs) == 1 and installs[0][0][0] == "Installing triton kernels"+ assert (+ installs[0][1]["req"].name == "triton-kernels.txt" and installs[0][1]["constrain"] is False+ )+ assert asked == [("triton-kernels.txt", "triton_kernels")]++ # Evidence available and the extra check consulted by _skip_step: one question, no install.+ installs.clear()+ asked.clear()++ def _skip_asking(+ req,+ label,+ *,+ no_deps,+ constrain,+ extra_check = None,+ ):+ return bool(extra_check())++ monkeypatch.setattr(stack, "_skip_step", _skip_asking)+ monkeypatch.setattr(stack, "_direct_reference_is_installed", _current(True))+ stack._triton_kernels_step()+ assert installs == [] and len(asked) == 1++ # No git at all: nothing asked, nothing installed.+ asked.clear()+ monkeypatch.setattr(stack, "_has_working_git", lambda: False)+ stack._triton_kernels_step()+ assert installs == [] and asked == []++ # A current commit keeps neither a damaged build (`pip show` still answers) nor one under+ # UNSLOTH_FULL_DEPS.+ monkeypatch.setattr(stack, "_has_working_git", lambda: True)+ monkeypatch.setattr(stack, "_skip_step", _skip)+ monkeypatch.setattr(stack, "_direct_reference_is_installed", _current(True))+ payload_intact["value"] = False+ stack._triton_kernels_step()+ assert len(installs) == 1 and installs[0][0][0] == "Installing triton kernels"+ installs.clear()+ payload_intact["value"] = True+ monkeypatch.setattr(stack, "_full_deps_requested", lambda: True)+ stack._triton_kernels_step()+ assert len(installs) == 1+++def test_the_remote_commit_probe_reads_ls_remote_and_fails_closed(monkeypatch) -> None:+ """`git ls-remote -- URL REF` answers `sha<TAB>ref` rows; a peeled tag wins over the tag+ object and a branch over a tag, and any failure (no git, non-zero exit, timeout, no+ rows) answers None so the caller keeps the resident build."""+ import subprocess as _sp++ calls: list = []++ class _Done:+ def __init__(self, rc, out):+ self.returncode = rc+ self.stdout = out++ def _fake_run(argv, **kwargs):+ calls.append((list(argv), kwargs))+ return _fake_run.answer++ monkeypatch.setattr(stack.shutil, "which", lambda _name: "/usr/bin/git")+ monkeypatch.setattr(stack.subprocess, "run", _fake_run)++ _fake_run.answer = _Done(+ 0, "aaaa000000000000000000000000000000000001\trefs/heads/release/3.6.x\n"+ )+ assert stack._git_remote_commit("https://example.invalid/t.git", "release/3.6.x") == (+ "aaaa000000000000000000000000000000000001"+ )+ argv, kwargs = calls[-1]+ assert argv[:3] == ["/usr/bin/git", "ls-remote", "--"]+ assert argv[3:] == ["https://example.invalid/t.git", "release/3.6.x"]+ assert kwargs["env"]["GIT_TERMINAL_PROMPT"] == "0"++ _fake_run.answer = _Done(+ 0,+ "bbbb000000000000000000000000000000000002\trefs/tags/v1\n"+ "cccc000000000000000000000000000000000003\trefs/tags/v1^{}\n",+ )+ assert stack._git_remote_commit("https://example.invalid/t.git", "v1") == (+ "cccc000000000000000000000000000000000003"+ )++ _fake_run.answer = _Done(128, "")+ assert stack._git_remote_commit("https://example.invalid/t.git", "release/3.6.x") is None+ _fake_run.answer = _Done(0, "")+ assert stack._git_remote_commit("https://example.invalid/t.git", "release/3.6.x") is None++ def _timeout(argv, **kwargs):+ raise _sp.TimeoutExpired(argv, 1)++ monkeypatch.setattr(stack.subprocess, "run", _timeout)+ assert stack._git_remote_commit("https://example.invalid/t.git", "release/3.6.x") is None+ monkeypatch.setattr(stack.shutil, "which", lambda _name: None)+ assert stack._git_remote_commit("https://example.invalid/t.git", "release/3.6.x") is None++[email protected]("name", ["UV_CONSTRAINT", "PIP_CONSTRAINT", "PIP_NO_DEPS", "UV_NO_DEPS"])+def test_a_caller_supplied_resolver_input_forces_a_full_pass(monkeypatch, manifest, name) -> None:+ """Additive constraints change which versions a step installs, and PIP_NO_DEPS makes+ a with-deps step leave dependencies out; no digest the gate keeps sees either."""+ payload, _req_root = manifest+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: dict(payload))+ for other in stack._FOREIGN_RESOLVER_ENV:+ monkeypatch.delenv(other, raising = False)+ assert _plan() is not None+ monkeypatch.setenv(name, "1" if "NO_DEPS" in name else "/tmp/constraints.txt")+ assert _plan() is None+ monkeypatch.setenv(name, " ")+ assert _plan() is not None+++def test_no_closure_record_is_kept_under_a_callers_no_deps(monkeypatch) -> None:+ """A dependency PIP_NO_DEPS left out is not a known conflict; carrying it forward+ would skip the step that installs it on the next run."""+ monkeypatch.setenv("PIP_NO_DEPS", "1")+ assert stack._closure_record() == {}+++def test_no_closure_record_is_kept_under_a_callers_uv_override(monkeypatch, gated) -> None:+ """uv applies an override past the pin that asked for the package, so what the pass+ leaves unmet under one is the override's doing. _plan_pass already refuses evidence+ for a caller's UV_OVERRIDE, but the pass still writes the manifest at the end: a+ record kept here would excuse the step that repairs it on every later update, long+ after the override is gone."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "ran"})+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["click 8.5.0"]+ )+ assert stack._closure_record() == {"studio.txt": ["click 8.5.0"]}+ foreign = req_root / "my-overrides.txt"+ foreign.write_text("click==8.5.0\n", encoding = "utf-8")+ monkeypatch.setenv("UV_OVERRIDE", str(foreign))+ assert stack._closure_record() == {}+ # The module's own macOS arm64 file is a tracked input, not a caller's.+ monkeypatch.setenv("UV_OVERRIDE", str(stack._MLX_OVERRIDES))+ assert stack._closure_record() == {"studio.txt": ["click 8.5.0"]}+++def test_a_caller_supplied_uv_override_forces_a_full_pass(monkeypatch, manifest) -> None:+ """uv applies UV_OVERRIDE to every step and its versions replace requirements+ outright; the gate digests only the bundled macOS file, so a caller's own file is+ an input the evidence cannot see."""+ payload, req_root = manifest+ monkeypatch.setattr(stack.install_manifest, "read_manifest", lambda *a, **k: dict(payload))+ foreign = req_root / "my-overrides.txt"+ foreign.write_text("numpy==1.0\n", encoding = "utf-8")+ monkeypatch.setenv("UV_OVERRIDE", str(foreign))+ assert _plan() is None+ # The module's own setting, in either spelling, is the tracked input and not foreign.+ monkeypatch.setenv("UV_OVERRIDE", str(stack._MLX_OVERRIDES))+ assert _plan() is not None+ monkeypatch.setenv("UV_OVERRIDE", stack._uv_safe_path(stack._MLX_OVERRIDES))+ assert _plan() is not None+ monkeypatch.delenv("UV_OVERRIDE")+ assert _plan() is not None+++def test_userinfo_in_a_git_url_is_not_mistaken_for_a_ref(tmp_path) -> None:+ req = tmp_path / "t.txt"+ req.write_text("pkg @ git+ssh://[email protected]/repo.git\n", encoding = "utf-8")+ assert stack._direct_reference_in_requirements(req) == (+ "ssh://[email protected]/repo.git",+ "",+ "",+ )+++def test_the_shipped_triton_requirement_still_parses() -> None:+ parsed = stack._direct_reference_in_requirements(+ REPO_ROOT / "studio" / "backend" / "requirements" / "triton-kernels.txt"+ )+ assert parsed is not None+ url, revision, subdirectory = parsed+ assert url.startswith("https://") and revision and subdirectory+++# -- local plugins -------------------------------------------------------------+++def test_a_plugin_digest_is_stable_and_content_addressed(tmp_path) -> None:+ """A directory listing has no order, so a digest that depended on one would differ+ between two byte-identical trees and reinstall both seed plugins every update."""+ first = tmp_path / "a"+ (first / "src").mkdir(parents = True)+ (first / "pyproject.toml").write_text("name = 'x'\n", encoding = "utf-8")+ (first / "src" / "mod.py").write_text("VALUE = 1\n", encoding = "utf-8")+ second = tmp_path / "b"+ (second / "src").mkdir(parents = True)+ (second / "src" / "mod.py").write_text("VALUE = 1\n", encoding = "utf-8")+ (second / "pyproject.toml").write_text("name = 'x'\n", encoding = "utf-8")++ assert stack._local_plugin_digest(first) == stack._local_plugin_digest(second)+ (second / "src" / "mod.py").write_text("VALUE = 2\n", encoding = "utf-8")+ assert stack._local_plugin_digest(first) != stack._local_plugin_digest(second)++[email protected](os.name == "nt", reason = "Windows filenames are UTF-16, not bytes")+def test_a_filename_that_is_not_utf_8_still_digests(tmp_path) -> None:+ """POSIX filenames are bytes. A stray one beside the sources -- a download, an editor+ backup -- used to raise UnicodeEncodeError out of the digest and end the update."""+ plugin = tmp_path / "p"+ plugin.mkdir()+ (plugin / "ok.py").write_text("x\n", encoding = "utf-8")+ odd = os.path.join(str(plugin), b"\xff.txt".decode("utf-8", "surrogateescape"))+ try:+ with open(odd, "wb") as handle:+ handle.write(b"x")+ except OSError:+ # APFS and other filesystems enforce UTF-8 names, so there is nothing to test here.+ pytest.skip("this filesystem refuses filenames that are not UTF-8")+ digest = stack._local_plugin_digest(plugin)+ assert digest and stack._local_plugin_digest(plugin) == digest+++def test_a_renamed_file_changes_the_plugin_digest(tmp_path) -> None:+ """Path and bytes both, so moving a file between two names is not a no-op."""+ plugin = tmp_path / "p"+ plugin.mkdir()+ (plugin / "one.py").write_text("x\n", encoding = "utf-8")+ before = stack._local_plugin_digest(plugin)+ (plugin / "one.py").rename(plugin / "two.py")+ assert stack._local_plugin_digest(plugin) != before+++def test_what_a_build_writes_into_the_plugin_tree_does_not_move_its_digest(tmp_path) -> None:+ """Installing the plugin from its directory leaves build/lib/... and+ src/<name>.egg-info/ beside the sources (setuptools, observed with uv and pip). The+ first pass after an install saw a tree the install had changed and rebuilt the+ plugin; offline, that build asked the cache for setuptools and the pass exited 1+ on a fresh install. Only the sources decide."""+ plugin = tmp_path / "data-designer-unstructured-seed"+ (plugin / "src" / "pkg").mkdir(parents = True)+ (plugin / "pyproject.toml").write_text("name = 'x'\n", encoding = "utf-8")+ (plugin / "src" / "pkg" / "__init__.py").write_text("VALUE = 1\n", encoding = "utf-8")+ clean = stack._local_plugin_digest(plugin)++ (plugin / "build" / "lib" / "pkg").mkdir(parents = True)+ (plugin / "build" / "lib" / "pkg" / "__init__.py").write_text("VALUE = 1\n", encoding = "utf-8")+ (plugin / "src" / "pkg.egg-info").mkdir()+ (plugin / "src" / "pkg.egg-info" / "SOURCES.txt").write_text(+ "pyproject.toml\n", encoding = "utf-8"+ )+ (plugin / "src" / "pkg.egg-info" / "PKG-INFO").write_text("Name: x\n", encoding = "utf-8")+ (plugin / "src" / "pkg" / "__pycache__").mkdir()+ (plugin / "src" / "pkg" / "__pycache__" / "__init__.cpython-313.pyc").write_bytes(b"\x00")+ (plugin / "dist").mkdir()+ (plugin / "dist" / "x-0.1-py3-none-any.whl").write_bytes(b"PK")+ assert stack._local_plugin_digest(plugin) == clean++ # The sources still count, wherever they sit.+ (plugin / "src" / "pkg" / "__init__.py").write_text("VALUE = 2\n", encoding = "utf-8")+ assert stack._local_plugin_digest(plugin) != clean+++def test_the_shipped_plugins_digest(tmp_path) -> None:+ for plugin in (stack.LOCAL_DD_UNSTRUCTURED_PLUGIN, stack.LOCAL_DD_GITHUB_PLUGIN):+ assert stack._local_plugin_digest(plugin)+++def test_an_unreadable_plugin_has_no_digest(tmp_path) -> None:+ assert stack._local_plugin_digest(tmp_path / "gone") is None+++# -- the pip bootstrap ---------------------------------------------------------+++def test_the_uv_probe_resolves_nothing(monkeypatch) -> None:+ """`uv pip install --dry-run pip` answered "can this uv address this interpreter"+ by resolving pip against the index -- one PyPI round trip on every installer run,+ and a hard failure on an offline host uv could have served from its cache."""+ seen: list[list[str]] = []++ class _Result:+ returncode = 0++ monkeypatch.setattr(stack.shutil, "which", lambda _name: "/usr/bin/uv")+ monkeypatch.setattr(stack.subprocess, "run", lambda cmd, **_k: (seen.append(cmd), _Result())[1])+ assert stack._bootstrap_uv() is True+ assert seen == [["uv", "pip", "freeze", "--python", sys.executable]]+ assert not any("--dry-run" in cmd for cmd in seen)+ assert not any("install" in cmd for cmd in seen)+++def test_the_uv_probe_still_retries_with_system(monkeypatch) -> None:+ seen: list[list[str]] = []+ codes = iter([1, 0])++ class _Result:+ def __init__(self, code):+ self.returncode = code++ monkeypatch.setattr(stack.shutil, "which", lambda _name: "/usr/bin/uv")+ monkeypatch.setattr(+ stack.subprocess, "run", lambda cmd, **_k: (seen.append(cmd), _Result(next(codes)))[1]+ )+ monkeypatch.setattr(stack, "UV_NEEDS_SYSTEM", False)+ assert stack._bootstrap_uv() is True+ assert stack.UV_NEEDS_SYSTEM is True+ assert seen[1] == ["uv", "pip", "freeze", "--system"]+++def test_a_broken_uv_still_falls_back_to_pip(monkeypatch) -> None:+ class _Result:+ returncode = 2++ monkeypatch.setattr(stack.shutil, "which", lambda _name: "/usr/bin/uv")+ monkeypatch.setattr(stack.subprocess, "run", lambda cmd, **_k: _Result())+ assert stack._bootstrap_uv() is False+++def test_a_venv_that_already_has_pip_does_not_reinstall_it(monkeypatch) -> None:+ monkeypatch.setattr(+ stack.subprocess, "run", lambda cmd, **_k: types.SimpleNamespace(returncode = 0)+ )+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "24.2")+ assert stack._venv_pip_is_usable() is True+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "22.0.4")+ assert stack._venv_pip_is_usable() is False+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: None)+ assert stack._venv_pip_is_usable() is False+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "not-a-version")+ assert stack._venv_pip_is_usable() is False+++def test_a_fresh_uv_venv_still_bootstraps(monkeypatch) -> None:+ """uv venvs omit pip entirely, and that is the case this step exists for."""+ monkeypatch.setattr(stack.importlib.util, "find_spec", lambda _n: None)+ assert stack._venv_pip_is_usable() is False+++def test_a_pip_that_cannot_run_is_bootstrapped_again(monkeypatch) -> None:+ """Metadata survives a pip whose __main__.py is gone; `python -m pip` does not."""+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "24.2")+ seen: list[list[str]] = []++ def broken(cmd, **_k):+ seen.append(list(cmd))+ return types.SimpleNamespace(returncode = 1)++ monkeypatch.setattr(stack.subprocess, "run", broken)+ assert stack._venv_pip_is_usable() is False+ assert seen and seen[0][1:] == ["-m", "pip", "--version"]++ def hangs(cmd, **kw):+ raise stack.subprocess.TimeoutExpired(cmd, kw.get("timeout", 60))++ monkeypatch.setattr(stack.subprocess, "run", hangs)+ assert stack._venv_pip_is_usable() is False+++# -- MLX and torchcodec --------------------------------------------------------+++def test_the_mlx_stack_is_current_only_when_all_four_hold(monkeypatch) -> None:+ versions = {"mlx": "0.32.1", "mlx-metal": "0.32.1", "mlx-lm": "0.31.3", "mlx-vlm": "0.5.0"}+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda name: versions.get(name))+ # The closure of a stack that is not installed on this host is its own test below.+ monkeypatch.setattr(stack, "_mlx_closure_unmet", lambda: False)+ assert stack._mlx_stack_is_current() is True+ for name, wrong in (+ ("mlx", "0.32.0"),+ ("mlx-metal", None),+ ("mlx-lm", "0.31.2"),+ ("mlx-vlm", "0.8.0"),+ ("mlx-vlm", None),+ ):+ broken = dict(versions)+ broken[name] = wrong+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda n, b = broken: b.get(n))+ assert stack._mlx_stack_is_current() is False, name+++def test_a_satisfied_mlx_pin_with_a_broken_closure_is_not_current(monkeypatch, tmp_path) -> None:+ """This step installs WITH dependencies, so it is what repairs an mlx-vlm whose own+ miniaudio or mlx-audio is gone. Versions alone would skip that repair."""+ versions = {"mlx": "0.32.1", "mlx-metal": "0.32.1", "mlx-lm": "0.31.3", "mlx-vlm": "0.5.0"}+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda name: versions.get(name))+ monkeypatch.setattr(stack, "_mlx_closure_unmet", lambda: True)+ assert stack._mlx_stack_is_current() is False+++def test_the_mlx_audit_does_not_fight_the_bundled_override(monkeypatch) -> None:+ """An override REPLACES every requirement on the package it names, so the version the+ installer leaves behind is the override's, not the one mlx-vlm's metadata asks for. Read+ raw, that disagreement is permanent and the MLX step would run on every update forever."""+ monkeypatch.setattr(stack, "_installed_index", lambda: {})+ names = stack._overridden_project_names()+ # The bundled file is the source of truth; these three are what it currently replaces.+ assert {"transformers", "anyio", "huggingface-hub"} <= names++ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["transformers 5.5.0", "anyio 4.13.0"],+ )+ assert stack._mlx_closure_unmet() is False+ # An override-named package that is ABSENT is still this step's work.+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["transformers"]+ )+ assert stack._mlx_closure_unmet() is True+ # ...as is anything the override does not name.+ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["transformers 5.5.0", "miniaudio 1.0"],+ )+ assert stack._mlx_closure_unmet() is True+++def test_the_mlx_closure_audit_reads_the_pins_and_cleans_up(monkeypatch, tmp_path) -> None:+ seen: list[str] = []++ def _closure(+ req,+ _index = None,+ **_kwargs,+ ):+ seen.append(req.read_text(encoding = "utf-8"))+ assert req.exists()+ return ["miniaudio"]++ monkeypatch.setattr(stack.install_manifest, "closure_unmet_requirements", _closure)+ monkeypatch.setattr(stack, "_installed_index", lambda: {})+ assert stack._mlx_closure_unmet() is True+ assert seen and all(spec in seen[0] for spec in [*stack._MLX_PINS, stack._MLX_VLM_SPEC])+ # A temp file per update, on a path the step is not allowed to leave behind.+ assert not list(pathlib.Path(tempfile.gettempdir()).glob("unsloth-mlx-*.txt"))++ def _raises(*_a, **_k):+ raise RuntimeError("metadata unreadable")++ monkeypatch.setattr(stack.install_manifest, "closure_unmet_requirements", _raises)+ # An audit that cannot run is a reason to run the step, never to skip it.+ assert stack._mlx_closure_unmet() is True+++def test_the_mlx_pins_match_the_runtime_repair() -> None:+ """One stack, two callers. The self-heal at startup reinstalls whatever this+ installed, so a pin that drifts here is a repair loop there."""+ names = {spec.partition("==")[0] for spec in stack._MLX_PINS} | {"mlx-vlm"}+ assert set(stack._MLX_NAMES) == names+ assert stack._MLX_VLM_SPEC.startswith("mlx-vlm")+++ "spec,installed,expected",+ [+ ("torchcodec==0.8.0", "0.8.0", True),+ ("torchcodec==0.8.0", "0.8.0+cu130", True),+ ("torchcodec==0.8.0", "0.7.0", False),+ ("torchcodec>=0.7,<0.9", "0.8.0+cpu", True),+ ("torchcodec>=0.7,<0.9", "0.9.1", False),+ ("torchcodec==0.8.0", "", False),+ ],+)+def test_a_resident_codec_inside_the_window_needs_no_install(spec, installed, expected) -> None:+ """The local tag is ignored here on purpose: provenance is the caller's separate+ question, and a +cu130 suffix puts the version outside a PyPI-shaped specifier it+ in fact satisfies."""+ assert stack._codec_spec_is_satisfied(spec, installed) is expected+++# -- the pip fallback ----------------------------------------------------------+++def test_the_pip_fallback_never_names_one_project_twice() -> None:+ """pip refuses `mlx==0.32.1 mlx` outright with "Double requirement given", which+ would fail the very step the fallback exists to rescue."""+ cmd = stack._build_pip_cmd(+ (+ "--upgrade-package",+ "mlx",+ "--upgrade-package",+ "mlx-vlm",+ "mlx==0.32.1",+ "mlx-vlm>=0.4.4,<0.7.0",+ )+ )+ assert "--upgrade" in cmd and "--upgrade-package" not in cmd+ assert cmd.count("mlx") == 0 and cmd.count("mlx-vlm") == 0+ assert "mlx==0.32.1" in cmd and "mlx-vlm>=0.4.4,<0.7.0" in cmd+++def test_a_package_named_only_by_the_flag_is_still_passed() -> None:+ """pip would otherwise upgrade nothing at all."""+ cmd = stack._build_pip_cmd(("--upgrade-package", "future-pkg", "other"))+ assert "future-pkg" in cmd and "other" in cmd+++# -- accounting ----------------------------------------------------------------+++def test_every_install_entry_point_is_counted() -> None:+ """`pip check` and the metadata patch are gated on this counter, so an install site that+ does not increment it makes both skip a venv that just changed. The two repairs were the+ ones missed: neither goes through pip_install*, and both change the environment.+ """+ source = STACK_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(source)+ counted = {+ "pip_install",+ "pip_install_try",+ "_uninstall_distribution",+ "_purge_recordless_distributions",+ "_repair_duplicate_core_metadata",+ }+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name in counted:+ body = ast.dump(node)+ assert "_count_install_action" in body, node.name+ counted.discard(node.name)+ assert not counted, f"install entry points are gone: {counted}"+++def counting(monkeypatch):+ """A zeroed counter and a constraint answer that is already cached against it."""+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 0)+ monkeypatch.setattr(stack, "_CONSTRAINTS_CACHE", None)+ answers = iter([["numpy"], [], [], []])+ monkeypatch.setattr(+ stack.install_manifest, "violated_constraints", lambda *a, **k: next(answers)+ )+ monkeypatch.setattr(stack, "_safe_print", lambda *a, **k: None)+ monkeypatch.setattr(stack, "_step", lambda *a, **k: None)+ assert stack._violated_constraints() == ["numpy"]+ return monkeypatch+++def _site_with_recordless_dist(monkeypatch, tmp_path):+ site = tmp_path / "site-packages"+ (site / "ghost-1.0.dist-info").mkdir(parents = True)+ monkeypatch.setattr(stack.sysconfig, "get_path", lambda name: str(site))+ return site+++_PIP_REFUSED = "Cannot uninstall ghost 1.0, RECORD file not found: no RECORD file was found"+++def test_purging_a_half_written_record_counts_as_an_install_action(counting, tmp_path) -> None:+ """It rmtree's a dist-info pip was reading a moment ago. Nothing else on that path+ touches the counter, so a constraint answer cached before it would survive it and+ let a gated step skip on evidence about an environment that no longer exists."""+ _site_with_recordless_dist(counting, tmp_path)+ assert stack._purge_recordless_distributions(_PIP_REFUSED) == ["ghost-1.0.dist-info"]+ assert stack._INSTALL_ACTIONS == 1+ assert stack._violated_constraints() == []+++def test_a_purge_that_deletes_nothing_leaves_the_cache_alone(counting, tmp_path) -> None:+ """The other direction, and the reason this is counted at the rmtree rather than at+ the top of the function: `pip check` is gated on the same counter, so a spurious+ increment buys a full metadata resolve of the venv on every no-op update."""+ site = _site_with_recordless_dist(counting, tmp_path)+ assert stack._purge_recordless_distributions("") == []+ assert stack._purge_recordless_distributions("some unrelated pip failure") == []+ # Named, but complete: whatever failed, it was not this.+ (site / "ghost-1.0.dist-info" / "RECORD").write_text("", encoding = "utf-8")+ assert stack._purge_recordless_distributions(_PIP_REFUSED) == []+ assert stack._INSTALL_ACTIONS == 0+ assert stack._violated_constraints() == ["numpy"], "the cached answer was discarded"+++class _ScriptedVersions:+ """installed_versions(), draining a scripted sequence of record counts."""++ def __init__(self, counts) -> None:+ self.counts = list(counts)++ def __call__(self, name, *args, **kwargs):+ count = self.counts.pop(0) if len(self.counts) > 1 else self.counts[0]+ return ["1.0"] * count+++def _metadata_repair_stubs(+ monkeypatch,+ counts,+ *,+ invalid = (),+):+ monkeypatch.setattr(stack.install_manifest, "installed_versions", _ScriptedVersions(counts))+ monkeypatch.setattr(stack.install_manifest, "pip_backup_metadata_paths", lambda *a, **k: [])+ monkeypatch.setattr(+ stack.install_manifest, "invalid_metadata_paths", lambda *a, **k: list(invalid)+ )+ monkeypatch.setattr(+ stack.install_manifest, "installed_version_probe", lambda *a, **k: ("1.0", False)+ )+ monkeypatch.setattr(stack, "_rewrite_minimal_metadata", lambda path, name: True)+ monkeypatch.setattr(stack, "_stage_replacement", lambda name: "/staged")+ monkeypatch.setattr(stack, "_run_ok", lambda label, cmd: True)+ monkeypatch.setattr(stack, "pip_install_try", lambda *a, **k: True)+++def test_removing_a_duplicate_metadata_record_counts_as_an_install_action(counting) -> None:+ """The uninstall loop goes through _run_ok, not _uninstall_distribution, so it was+ the one removal path the counter never saw."""+ _metadata_repair_stubs(counting, [2, 1, 0])+ assert stack._repair_duplicate_core_metadata(("unsloth",)) is True+ assert stack._INSTALL_ACTIONS == 2, "one per pip uninstall, as _uninstall_distribution"+ assert stack._violated_constraints() == []+++def test_rewriting_unreadable_metadata_counts_even_if_the_repair_then_aborts(+ counting, tmp_path+) -> None:+ """The rewrite happens before anything is staged and is not undone by returning+ False: what importlib.metadata reports has already changed."""+ _metadata_repair_stubs(counting, [2, 0], invalid = [str(tmp_path)])+ assert stack._repair_duplicate_core_metadata(("unsloth",)) is False+ assert stack._INSTALL_ACTIONS == 1+ assert stack._violated_constraints() == []+++def test_a_repair_with_nothing_to_repair_leaves_the_cache_alone(counting) -> None:+ """One readable record each and no damage: both repairs are pure inspection, and+ an update that does nothing must not pay for a `pip check` because they ran."""+ _metadata_repair_stubs(counting, [1])+ monkeypatch = counting+ monkeypatch.setattr(stack.install_manifest, "damaged_payload_files", lambda *a, **k: [])+ assert stack._repair_duplicate_core_metadata(("unsloth", "unsloth-zoo")) is True+ assert stack._repair_damaged_core_payload(("unsloth", "unsloth-zoo")) is True+ assert stack._INSTALL_ACTIONS == 0+ assert stack._violated_constraints() == ["numpy"], "the cached answer was discarded"+++def test_the_pass_state_is_reset_per_call() -> None:+ """The suites call install_python_stack() several times in one interpreter, and a+ counter that survived would make the second call skip what the first installed."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ entry = source[source.index("def install_python_stack() -> int:") :]+ head = entry[: entry.index("# --package installs")]+ for name in ("_INSTALL_ACTIONS = 0", "_PASS_EVIDENCE = None", "_STEP_RESULTS.clear()"):+ assert name in head, name+++def test_the_plan_is_read_before_the_manifest_is_dropped() -> None:+ """remove_manifest deletes the only copy of what the last run did."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ plan = source.index("_PASS_EVIDENCE = _plan_pass(")+ drop = source.index("install_manifest.remove_manifest()")+ assert plan < drop+++# The finalizing tail: three fixed costs a settled install has no reason to pay (the METADATA+# rewrite, a discarded `pip check`, an out-of-process MLX import probe).+++class _FakePatchModule:+ """Stands in for requirements/single-env/patch_metadata.py."""++ TARGETS = ("data-designer",)+ PATCHES = ((re.compile(r"^Requires-Dist: huggingface-hub<2,>=1\.0\.1$", re.MULTILINE), "x"),)++ def __init__(+ self,+ path,+ *,+ raise_on_lookup = False,+ raise_on_main = False,+ ):+ self._path = path+ self._raise_on_lookup = raise_on_lookup+ self._raise_on_main = raise_on_main+ self.main_calls = 0++ def metadata_path(self, _name):+ if self._raise_on_lookup:+ raise RuntimeError("distribution metadata is unreadable")+ return self._path++ def main(self):+ self.main_calls += 1+ print("single-env metadata patch: checked=1, changed=1")+ if self._raise_on_main:+ raise RuntimeError("cannot patch in process")+ return 0+++PATCHED = "Requires-Dist: huggingface-hub<2,>=0.34.0\n"+UNPATCHED = "Requires-Dist: huggingface-hub<2,>=1.0.1\n"+++def _patch_module(+ monkeypatch,+ tmp_path,+ text = PATCHED,+ **kwargs,+):+ metadata = tmp_path / "METADATA"+ if text is not None:+ metadata.write_text(text, encoding = "utf-8")+ fake = _FakePatchModule(metadata if text is not None else None, **kwargs)+ monkeypatch.setattr(stack, "SINGLE_ENV", tmp_path)+ # Cached in sys.modules after the first pass, so the second call in one interpreter sees it too.+ monkeypatch.setitem(sys.modules, "patch_metadata", fake)+ return fake+++def test_a_settled_install_does_not_re_run_the_metadata_patch(monkeypatch, tmp_path) -> None:+ _patch_module(monkeypatch, tmp_path, PATCHED)+ assert stack._patch_metadata_is_pending() is False+++def test_an_unpatched_metadata_file_is_still_pending(monkeypatch, tmp_path) -> None:+ _patch_module(monkeypatch, tmp_path, UNPATCHED)+ assert stack._patch_metadata_is_pending() is True+++def test_a_distribution_that_is_not_installed_needs_no_patch(monkeypatch, tmp_path) -> None:+ _patch_module(monkeypatch, tmp_path, None)+ assert stack._patch_metadata_is_pending() is False++[email protected]("kwargs", [{"raise_on_lookup": True}])+def test_anything_it_cannot_answer_runs_the_patch(monkeypatch, tmp_path, kwargs) -> None:+ """Unknown means do the work: this replaces an unconditional run, so the failure+ mode of the question must be the old behaviour, not a skip."""+ _patch_module(monkeypatch, tmp_path, PATCHED, **kwargs)+ assert stack._patch_metadata_is_pending() is True+++def test_an_unimportable_patch_module_runs_the_patch(monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(stack, "SINGLE_ENV", tmp_path / "gone")+ monkeypatch.delitem(sys.modules, "patch_metadata", raising = False)+ assert stack._patch_metadata_is_pending() is True+++def test_the_patch_applies_in_process(monkeypatch, tmp_path) -> None:+ fake = _patch_module(monkeypatch, tmp_path, UNPATCHED)+ ran = []+ monkeypatch.setattr(stack, "run", lambda *a, **k: ran.append(a))+ stack._run_patch_metadata()+ assert fake.main_calls == 1+ assert ran == []+++def test_the_in_process_patch_does_not_print_into_the_progress_line(+ monkeypatch, tmp_path, capsys+) -> None:+ """The script prints its tally, and the subprocess path it replaces captured that.+ In process it would land in the middle of the progress bar."""+ _patch_module(monkeypatch, tmp_path, UNPATCHED)+ monkeypatch.setattr(stack, "run", lambda *a, **k: None)+ monkeypatch.setattr(stack, "VERBOSE", False)+ stack._run_patch_metadata()+ assert capsys.readouterr().out == ""+ # ...and it is not lost: UNSLOTH_VERBOSE prints no progress line for it to break.+ monkeypatch.setattr(stack, "VERBOSE", True)+ stack._run_patch_metadata()+ assert "checked=1, changed=1" in capsys.readouterr().out+++def test_the_patch_still_falls_back_to_the_subprocess(monkeypatch, tmp_path) -> None:+ """It is a supported standalone entry point, and an import failure inside the+ installer must not turn into a failed install."""+ fake = _patch_module(monkeypatch, tmp_path, UNPATCHED, raise_on_main = True)+ ran = []+ monkeypatch.setattr(stack, "run", lambda *a, **k: ran.append(a))+ stack._run_patch_metadata()+ assert fake.main_calls == 1+ assert len(ran) == 1 and str(tmp_path / "patch_metadata.py") in [str(x) for x in ran[0][1]]++[email protected]("fn", ["_patch_metadata_is_pending", "_run_patch_metadata"])+def test_neither_helper_leaves_single_env_on_sys_path(monkeypatch, tmp_path, fn) -> None:+ """sys.path.insert(0, SINGLE_ENV) that outlives the call shadows stdlib names for+ the rest of the install."""+ _patch_module(monkeypatch, tmp_path, UNPATCHED)+ monkeypatch.setattr(stack, "run", lambda *a, **k: None)+ before = list(sys.path)+ getattr(stack, fn)()+ assert sys.path == before+++def test_the_metadata_patch_still_runs_whenever_data_designer_did() -> None:+ """The pending scan reads the METADATA of packages the data-designer steps just+ wrote, so a fresh install must not be gated on it at all."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ assert "_finalize_ran = _dd_deps_ran or _dd_ran or _patch_metadata_is_pending()" in source+++def test_pip_check_is_gated_on_this_pass_having_changed_something() -> None:+ source = STACK_PATH.read_text(encoding = "utf-8")+ gate = source.index('_pip_check_ok = (_PASS_EVIDENCE or {}).get("pip_check_ok")')+ tail = source[gate : gate + 400]+ # Both halves: anything installed re-checks, and so does a last answer that was not a clean+ # True.+ assert "if _INSTALL_ACTIONS > 0 or _pip_check_ok is not True:" in tail+ assert '"pip_check_ok": _pip_check_ok,' in source+++# -- the MLX verdict -----------------------------------------------------------+++class _FakeSubprocess:+ def __init__(self, stdout = "[]"):+ self.calls = 0+ self._stdout = stdout++ def run(self, *args, **kwargs):+ self.calls += 1+ return type("R", (), {"stdout": self._stdout, "stderr": "", "returncode": 0})()+++def mlx(monkeypatch):+ fake = _FakeSubprocess()+ monkeypatch.setattr(stack, "subprocess", fake)+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "0.4.5")+ steps: list[tuple[str, str]] = []+ monkeypatch.setattr(stack, "_step", lambda label, value, *a: steps.append((label, value)))+ written: list[dict] = []+ monkeypatch.setattr(+ stack.install_manifest,+ "update_manifest",+ lambda **kw: written.append(kw.get("mlx_health")) or True,+ )+ healthy = {**stack._mlx_health_fingerprint(), "ok": True}+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"mlx_health": healthy})+ monkeypatch.setattr(stack, "_mlx_payload_present", lambda: True)+ return fake, steps, written, healthy+++def test_a_recorded_healthy_stack_is_not_re_probed(mlx) -> None:+ fake, steps, written, _ = mlx+ stack._report_mlx_stack_health(skipped = True)+ assert fake.calls == 0+ assert steps == [("mlx", "training stack ready")]+ # Rewritten so the record does not age out of the manifest this pass just wrote.+ assert written and written[0]["ok"] is True+++def test_a_recorded_verdict_needs_the_payload_on_disk(mlx, monkeypatch) -> None:+ """Pins and interpreter survive a payload deleted after the pass; the recorded verdict+ does not describe a package whose files are gone, so the probe runs."""+ fake, steps, _written, _ = mlx+ monkeypatch.setattr(stack, "_mlx_payload_present", lambda: False)+ stack._report_mlx_stack_health(skipped = True)+ # The probe ran; what it reported is the probe's business (the fake answers healthy).+ assert fake.calls == 1+++def test_a_rebuilt_mlx_stack_is_always_probed(mlx) -> None:+ fake, steps, _written, _ = mlx+ stack._report_mlx_stack_health(skipped = False)+ assert fake.calls == 1+++ "mutation",+ [+ {"ok": False},+ {"ok": None},+ {"pins": ["mlx==0.0.1"]},+ {"python": "39"},+ {"mlx_vlm": "0.4.4"},+ # An imported dependency moved within its range between passes, and a record from before the+ # imports were fingerprinted.+ {+ "imports": {+ **{n: "0.4.5" for n in stack._MLX_IMPORTED_DEPENDENCIES},+ "transformers": "4.0.0",+ }+ },+ {"imports": None},+ ],+)+def test_a_verdict_that_no_longer_describes_this_install_is_re_probed(mlx, mutation) -> None:+ fake, _steps, _written, healthy = mlx+ stack._PASS_EVIDENCE = {"mlx_health": {**healthy, **mutation}}+ stack._report_mlx_stack_health(skipped = True)+ assert fake.calls == 1+++def test_a_pass_that_installed_anything_re_probes(mlx, monkeypatch) -> None:+ """The probe imports transformers and tokenizers through mlx_lm; a later step of the+ same pass can move those with every MLX pin unchanged, so a recorded verdict only+ stands for a pass that installed nothing at all."""+ fake, _steps, _written, _ = mlx+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 1)+ stack._report_mlx_stack_health(skipped = True)+ assert fake.calls == 1+++def test_no_evidence_at_all_is_probed(mlx, monkeypatch) -> None:+ fake, _steps, _written, _ = mlx+ for evidence in (None, {}, {"mlx_health": "yes"}, {"mlx_health": {}}):+ fake.calls = 0+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", evidence)+ stack._report_mlx_stack_health(skipped = True)+ assert fake.calls == 1, evidence+++def test_the_fingerprint_names_everything_a_verdict_depends_on(monkeypatch) -> None:+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: "0.4.5")+ fingerprint = stack._mlx_health_fingerprint()+ assert fingerprint["pins"] == list(stack._MLX_PINS) + [stack._MLX_VLM_SPEC]+ assert fingerprint["python"] == stack._installer_python_tag()+ assert fingerprint["imports"] == {n: "0.4.5" for n in stack._MLX_IMPORTED_DEPENDENCIES}+ assert {"transformers", "tokenizers", "numpy", "huggingface-hub"} <= set(fingerprint["imports"])+ # mlx-vlm floats inside a range: the pin string alone does not identify what is installed.+ assert fingerprint["mlx_vlm"] == "0.4.5"+ monkeypatch.setattr(stack, "_installed_distribution_version", lambda _n: None)+ assert stack._mlx_health_fingerprint()["mlx_vlm"] == ""+++def test_a_probe_verdict_is_recorded_for_next_time(mlx) -> None:+ fake, steps, written, _ = mlx+ stack._report_mlx_stack_health(skipped = False)+ assert written and written[0]["ok"] is True+ fake._stdout = '["mlx-lm is not importable"]'+ written.clear()+ stack._report_mlx_stack_health(skipped = False)+ assert written and written[0]["ok"] is False+ assert ("", "mlx-lm is not importable") in steps+++def test_a_probe_that_cannot_answer_records_nothing(mlx) -> None:+ fake, _steps, written, _ = mlx+ fake._stdout = "null"+ stack._report_mlx_stack_health(skipped = False)+ assert written == []+++def test_the_verdict_is_recorded_after_the_manifest_is_written() -> None:+ """The probe has a 180 s timeout. Writing through write_manifest would make a kill+ during it lose a finished install; update_manifest never creates one."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ # rindex: the definition comes first in the file, the call site is what is ordered.+ assert source.index("install_manifest.write_manifest(") < source.rindex(+ "_report_mlx_stack_health("+ )+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.FunctionDef) and node.name == "_report_mlx_stack_health":+ called = {+ child.func.attr+ for child in ast.walk(node)+ if isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)+ }+ assert "write_manifest" not in called+ assert "update_manifest" in called+ break+ else: # pragma: no cover - the function is the subject of this file+ raise AssertionError("_report_mlx_stack_health is gone")+++def test_the_escape_hatch_reaches_the_pip_bootstrap_skip() -> None:+ """UNSLOTH_STUDIO_FULL_DEPS is what a user is told to set when the install is+ behaving oddly. A step it cannot turn off is a step they cannot work around, and the+ pip bootstrap skip is not gated on the manifest, so nothing else would reach it."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ assert "if not _full_deps_requested() and _venv_pip_is_usable():" in source+++# -- the dependency closure ----------------------------------------------------+++def _closure_index(**dists):+ """canonical name -> (version, Requires-Dist lines), as install_manifest builds it."""+ return {name.replace("_", "-").lower(): value for name, value in dists.items()}+++def test_a_missing_transitive_dependency_is_not_satisfied(tmp_path) -> None:+ """The file's own lines stay true after a dependency of a dependency is removed.+ mammoth>=1.8.0 is satisfied by a mammoth whose cobble is gone, and importing it+ raises; the step that would have repaired that is the one being skipped."""+ req = tmp_path / "studio.txt"+ req.write_text("mammoth>=1.8.0\n", encoding = "utf-8")+ healthy = _closure_index(mammoth = ("1.12.1", ["cobble>=0.1.3"]), cobble = ("0.1.4", []))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, healthy) is None+ damaged = _closure_index(mammoth = ("1.12.1", ["cobble>=0.1.3"]))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, damaged) == "cobble"+++def test_a_transitive_dependency_outside_its_window_is_not_satisfied(tmp_path) -> None:+ req = tmp_path / "studio.txt"+ req.write_text("cryptography\n", encoding = "utf-8")+ index = _closure_index(cryptography = ("46.0.3", ["cffi>=1.14"]), cffi = ("1.9.0", []))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, index) == "cffi 1.9.0"+++def test_every_unmet_closure_requirement_is_collected(tmp_path) -> None:+ """The gate needs the whole list, not the first hit: a step is skipped only when+ everything left unmet is on the record the last pass wrote."""+ req = tmp_path / "studio.txt"+ req.write_text("mammoth>=1.8.0\ncryptography\n", encoding = "utf-8")+ index = _closure_index(+ mammoth = ("1.12.1", ["cobble>=0.1.3"]),+ cryptography = ("46.0.3", ["cffi>=1.14"]),+ cffi = ("1.9.0", []),+ )+ unmet = stack.install_manifest.closure_unmet_requirements(req, index)+ assert sorted(unmet) == ["cffi 1.9.0", "cobble"]+ assert stack.install_manifest.unsatisfied_closure_requirement(req, index) in unmet+++def test_a_conflict_the_last_pass_left_behind_does_not_run_the_step(monkeypatch, gated) -> None:+ """sqlfluff 3.x pins click<=8.3.0 and huggingface-hub 1.23+ needs click>=8.4.2, so+ the data-designer step's closure is unmet after every pass. The record the last+ pass wrote of exactly that lets the gate skip; a new unmet requirement still runs."""+ _payload, req_root = gated+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["click 8.5.0"]+ )+ monkeypatch.setattr(stack.install_manifest, "missing_requirements", lambda *a, **k: [])+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+ stack._PASS_EVIDENCE["known_unmet"] = {"studio.txt": ["click 8.5.0"]}+ # The record is evidence about its own installed set only: a requirer moved since can have+ # dropped the bound that made the conflict. No recorded set and a different one both run.+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+ stack._PASS_EVIDENCE["known_unmet_index"] = "not-the-installed-set"+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+ stack._PASS_EVIDENCE["known_unmet_index"] = stack._installed_index_digest()+ assert stack._PASS_EVIDENCE["known_unmet_index"]+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is True+ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["click 8.5.0", "cobble"],+ )+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+++def test_the_closure_record_never_carries_an_audit_failure(monkeypatch, gated) -> None:+ """A "<...>" entry means the audit could not run; recording it would let an+ unreadable environment skip the step next time."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "ran"})+ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["<metadata unreadable>", "click 8.5.0"],+ )+ assert stack._closure_record() == {"studio.txt": ["click 8.5.0"]}+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "skipped"})+ stack._PASS_EVIDENCE["known_unmet"] = {"studio.txt": ["click 8.3.0"]}+ assert stack._closure_record() == {"studio.txt": ["click 8.3.0"]}+++def test_a_known_unmet_field_that_is_not_a_mapping_is_ignored(monkeypatch, gated) -> None:+ """Read from the manifest on disk and reached while write_manifest's arguments are+ being built, so a hand-edited value here used to abort a pass whose installs had all+ landed -- leaving the venv with no manifest at all."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "skipped"})+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["click 8.3.0"]+ )+ for value in (["click 8.3.0"], "click", 7):+ stack._PASS_EVIDENCE["known_unmet"] = value+ # The step ran for nothing it can prove was known, so nothing is carried.+ assert stack._closure_record() == {}+++def test_a_requirement_that_is_simply_absent_is_never_a_known_conflict(monkeypatch, gated) -> None:+ """closure_unmet_requirements names an absent distribution by itself and one outside its+ specifier as "name version". Only the second can be a conflict nothing can resolve: an+ absent one is work this step does, and recording it would excuse the install that repairs+ it on every later update. Reachable whenever the resolver was told to skip dependencies by+ something no digest covers -- a pip.conf with no-deps, not only the environment."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "ran"})+ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["cobble", "click 8.3.0"],+ )+ assert stack._closure_record() == {"studio.txt": ["click 8.3.0"]}++ # ...and a record an earlier build wrote with bare names does not excuse one either.+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "skipped"})+ stack._PASS_EVIDENCE["known_unmet"] = {"studio.txt": ["cobble", "click 8.3.0"]}+ assert stack._closure_record() == {"studio.txt": ["click 8.3.0"]}+++def test_a_file_that_includes_another_one_is_never_skipped(monkeypatch, gated, tmp_path) -> None:+ """pass_inputs digests this file; an -r line's target is a second file it does not name,+ and missing_requirements skips flag lines, so a pin behind the include could move with+ nothing in the gate able to see it."""+ _payload, req_root = gated+ outer = req_root / "studio.txt"+ outer.write_text("-r nested.txt\n", encoding = "utf-8")+ (req_root / "nested.txt").write_text("cobble==0.1.3\n", encoding = "utf-8")+ monkeypatch.setattr(stack, "_inputs_unchanged", lambda keys: True)+ monkeypatch.setattr(stack, "_effective_requirements", lambda r: (r, []))+ assert stack._requirements_satisfied(outer, no_deps = True) is False+ # Every shipped requirements file must stay skippable, or the gate does nothing. The repo's+ # own tree, not the fixture's: REQ_ROOT points at the temporary copy here.+ root = REPO_ROOT / "studio" / "backend" / "requirements"+ shipped = [+ name+ for name in stack.install_manifest.PASS_INPUT_FILES+ if (root / name).is_file() and stack._includes_another_requirements_file(root / name)+ ]+ assert shipped == []+++def test_an_unreadable_requirements_file_is_never_skipped(tmp_path) -> None:+ """A file the gate cannot read is one whose contents it cannot stand behind."""+ odd = tmp_path / "req.txt"+ odd.write_bytes(b"\xff\xfe not utf-8\n")+ assert stack._includes_another_requirements_file(odd) is True+ assert stack._includes_another_requirements_file(tmp_path / "absent.txt") is True+++def test_a_carried_known_unmet_record_drops_what_is_met_again(monkeypatch, gated) -> None:+ """A skipped step carries its record, narrowed to what the closure still lacks: an+ entry satisfied since it was recorded was no conflict, and keeping it would let a+ later loss of that package pass as intentional."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "_AUDITED_STEPS", {"studio.txt": req_root / "studio.txt"})+ monkeypatch.setattr(stack, "_STEP_RESULTS", {"studio.txt": "skipped"})+ stack._PASS_EVIDENCE["known_unmet"] = {"studio.txt": ["click 8.3.0", "mammoth"]}+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["click 8.3.0"]+ )+ assert stack._closure_record() == {"studio.txt": ["click 8.3.0"]}+ monkeypatch.setattr(stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: [])+ assert stack._closure_record() == {}+ # A new unmet entry is not adopted by a skipped step: the step never ran for it.+ monkeypatch.setattr(+ stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: ["numpy 1.0"]+ )+ assert stack._closure_record() == {}+++def test_the_closure_walk_follows_extras_and_survives_cycles(tmp_path) -> None:+ req = tmp_path / "studio.txt"+ req.write_text("alpha[fancy]\n", encoding = "utf-8")+ # beta is only pulled in by the extra; gamma cycles back to alpha.+ index = _closure_index(+ alpha = ("1.0", ['beta ; extra == "fancy"', 'zeta ; extra == "other"', "gamma"]),+ beta = ("2.0", []),+ gamma = ("3.0", ["alpha"]),+ )+ assert stack.install_manifest.unsatisfied_closure_requirement(req, index) is None+ # ...and the extra's own dependency is really required, not merely walked.+ without_beta = dict(index)+ without_beta.pop("beta")+ assert stack.install_manifest.unsatisfied_closure_requirement(req, without_beta) == "beta"+++def test_an_extra_named_before_pep_685_is_still_followed(tmp_path) -> None:+ """A wheel built before extras were normalised in the marker still says+ extra == "all_files", and matching only the canonical spelling would drop that+ extra's whole subtree without a word."""+ req = tmp_path / "studio.txt"+ req.write_text("alpha[all_files]\n", encoding = "utf-8")+ index = _closure_index(alpha = ("1.0", ['beta ; extra == "all_files"']))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, index) == "beta"+ both = dict(index, beta = ("2.0", []))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, both) is None+++def test_an_inapplicable_marker_is_not_a_missing_dependency(tmp_path) -> None:+ req = tmp_path / "studio.txt"+ req.write_text("alpha\n", encoding = "utf-8")+ index = _closure_index(alpha = ("1.0", ['pywin32 ; sys_platform == "never-a-platform"']))+ assert stack.install_manifest.unsatisfied_closure_requirement(req, index) is None+++ "line,reason",+ [+ ("-r other.txt", "<flag line: -r other.txt>"),+ ("--index-url https://example.invalid", "<flag line: --index-url https://example.invalid>"),+ ],+)+def test_the_closure_audit_fails_closed(tmp_path, line, reason) -> None:+ """Every answer that is not a proven-complete closure has to install. A flag line+ can hide requirements from the walk entirely, and guessing the other way would let+ a step skip on evidence nobody gathered."""+ req = tmp_path / "studio.txt"+ req.write_text(f"{line}\n", encoding = "utf-8")+ assert stack.install_manifest.unsatisfied_closure_requirement(req, {}) == reason+++def test_a_direct_url_requirement_fails_closed(tmp_path) -> None:+ """A version says nothing about which ref landed, and the one step that has such a+ requirement is --no-deps and never reaches this audit."""+ req = tmp_path / "studio.txt"+ req.write_text("alpha @ https://example.invalid/alpha.whl\n", encoding = "utf-8")+ index = _closure_index(alpha = ("1.0", []))+ got = stack.install_manifest.unsatisfied_closure_requirement(req, index)+ assert got == "alpha (direct reference)"+++def test_an_unreadable_requirements_file_fails_closed(tmp_path) -> None:+ assert (+ stack.install_manifest.unsatisfied_closure_requirement(tmp_path / "gone.txt", {})+ == "<requirements unreadable>"+ )+++def test_a_budget_overrun_fails_closed(monkeypatch, tmp_path) -> None:+ """A site-packages on a wedged mount must cost one dependency pass, not a hang."""+ req = tmp_path / "studio.txt"+ req.write_text("alpha\n", encoding = "utf-8")+ index = _closure_index(alpha = ("1.0", []))+ clock = iter([0.0, 100.0, 200.0])+ monkeypatch.setattr(stack.install_manifest.time, "monotonic", lambda: next(clock))+ assert (+ stack.install_manifest.unsatisfied_closure_requirement(req, index, budget_seconds = 1.0)+ == "<closure audit timed out>"+ )+++def test_a_broken_closure_runs_a_with_deps_step_but_not_a_no_deps_one(monkeypatch, gated) -> None:+ """--no-deps steps leave their requirements' own dependencies unresolved on purpose,+ so auditing one would report a conflict the installer created and force it forever."""+ _payload, req_root = gated+ monkeypatch.setattr(+ stack.install_manifest,+ "closure_unmet_requirements",+ lambda *a, **k: ["botocore"],+ )+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is False+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = True) is True+++def test_the_closure_audit_reads_the_filtered_file(monkeypatch, gated) -> None:+ """The temp copy _effective_requirements builds is unlinked on the way out, so an+ audit placed after that cleanup would read nothing and never skip again."""+ _payload, req_root = gated+ monkeypatch.setattr(stack, "PLATFORM_LACKS_TORCHCODEC_WHEEL", True)+ seen: list[bool] = []++ def audit(path, *_a, **_k):+ seen.append(pathlib.Path(path).is_file())+ return []++ monkeypatch.setattr(stack.install_manifest, "closure_unmet_requirements", audit)+ assert stack._requirements_satisfied(req_root / "studio.txt", no_deps = False) is True+ assert seen == [True]+++def test_every_gated_step_states_whether_it_installs_with_deps() -> None:+ """no_deps is keyword-only and required so a new step cannot inherit the weaker+ check by forgetting to answer. Pinned on the source, since the failure is silent."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(source)+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef) or node.name not in (+ "_skip_step",+ "_requirements_satisfied",+ ):+ continue+ names = [arg.arg for arg in node.args.kwonlyargs]+ assert "no_deps" in names, node.name+ defaults = dict(zip(names, node.args.kw_defaults))+ assert defaults["no_deps"] is None, f"{node.name}: no_deps must have no default"+++# -- the pin-shaped steps ask for the same evidence ----------------------------++[email protected]("value", ["1", "true", "YES", " on "])+def test_the_escape_hatch_reaches_the_pin_shaped_steps(monkeypatch, value) -> None:+ """torchao, MLX and torchcodec compare against the installed distribution rather+ than a recorded digest, so a satisfied pin read as "nothing to do" even on the pass+ that was asked to do everything."""+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"pass_inputs": {}, "step_results": {}})+ assert stack._may_skip_on_evidence() is True+ monkeypatch.setenv(stack._FULL_DEPS_ENV, value)+ assert stack._may_skip_on_evidence() is False+++def test_a_rejected_manifest_reaches_the_pin_shaped_steps(monkeypatch) -> None:+ monkeypatch.delenv(stack._FULL_DEPS_ENV, raising = False)+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", None)+ assert stack._may_skip_on_evidence() is False+++def test_a_satisfied_torchao_pin_is_still_reinstalled_on_a_forced_pass(monkeypatch) -> None:+ calls: list[tuple] = []+ monkeypatch.setattr(stack, "_select_torchao_spec", lambda _v: "torchao==0.18.0")+ monkeypatch.setattr(stack, "_torch_accelerator_index_url", lambda _v: "")+ monkeypatch.setattr(stack, "_pin_needs_reinstall", lambda *_a: False)+ monkeypatch.setattr(stack, "_note", lambda *_a, **_k: None)+ monkeypatch.setattr(stack, "pip_install", lambda *a, **k: calls.append(a))++ monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"pass_inputs": {}, "step_results": {}})+ monkeypatch.delenv(stack._FULL_DEPS_ENV, raising = False)+ stack._install_torchao_for_torch("2.10.0")+ assert calls == []+ assert stack._STEP_RESULTS.get("torchao") == "skipped"++ monkeypatch.setattr(stack, "_PASS_EVIDENCE", None)+ stack._install_torchao_for_torch("2.10.0")+ assert len(calls) == 1+ assert stack._STEP_RESULTS.get("torchao") == "ran"+ # ...with the flags the step had before the skip existed. Every install's first update on+ # this build has no evidence, and forcing there would re-download a wheel pip was about to+ # report as already satisfied.+ assert "--force-reinstall" not in calls[0]++ monkeypatch.setattr(stack, "_pin_needs_reinstall", lambda *_a: True)+ stack._install_torchao_for_torch("2.10.0")+ assert "--force-reinstall" in calls[1]+++def test_the_mlx_and_codec_skips_ask_for_the_evidence_too() -> None:+ """Both skips live inside install_python_stack's body, so the guard is pinned on the+ source: a satisfied pin must not outrank a forced or repair pass."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ mlx_guard = (+ " _may_skip_on_evidence()\n"+ " and _mlx_stack_is_current()\n"+ ' and _inputs_unchanged(["single-env/overrides-darwin-arm64.txt"])\n'+ )+ # Moved arm64 overrides (UV_OVERRIDE) run the resolver even with the four pins satisfied.+ assert mlx_guard in source+ assert "_may_skip_on_evidence()\n and not _codec_rebuild\n" in source+++def test_the_npp_repair_is_not_conditional_on_reinstalling_the_codec() -> None:+ """NPP is a separate distribution with its own failure modes. While the repair was+ gated on the codec step having run, a codec the skip accepted meant a missing NPP+ was never looked at again, and torchcodec's CUDA build cannot import without it."""+ source = STACK_PATH.read_text(encoding = "utf-8")+ assert " elif _codec_index:\n" in source+ # One occurrence left: the unpinned retry, which really does depend on an attempt.+ assert source.count('_STEP_RESULTS.get("torchcodec") == "ran"') == 1+ # A resident NPP short-circuits the install. The name comes from the spec: nvidia-npp-cu12+ # through CUDA 12, plain nvidia-npp above.+ assert '_npp_name = re.split(r"[<>=!~]", _npp_spec, maxsplit = 1)[0].strip()' in source+ assert "if _npp_have and _spec_is_satisfied(_npp_spec, _npp_have):" in source+++# -- local seed plugins --------------------------------------------------------+++def test_a_damaged_plugin_payload_is_reinstalled(monkeypatch, tmp_path) -> None:+ """A seed plugin is installed from a path, so its version never moves: deleting the+ installed module leaves both the version and the source digest unchanged."""+ monkeypatch.setattr(+ stack.install_manifest, "damaged_payload_files", lambda *a, **k: ["plugin.py"]+ )+ assert stack._local_plugin_payload_is_damaged("data-designer-github-repo-seed") is True+ monkeypatch.setattr(stack.install_manifest, "damaged_payload_files", lambda *a, **k: [])+ assert stack._local_plugin_payload_is_damaged("data-designer-github-repo-seed") is False+++def test_an_unscannable_plugin_is_reinstalled(monkeypatch) -> None:+ """Unlike install_manifest's own convention: this decides whether to skip a local+ path install that costs well under a second, so the conservative answer is cheap."""++ def boom(*_a, **_k):+ raise OSError("no")++ monkeypatch.setattr(stack.install_manifest, "damaged_payload_files", boom)+ assert stack._local_plugin_payload_is_damaged("anything") is True+++def test_the_plugin_skip_consults_the_installed_payload() -> None:+ source = STACK_PATH.read_text(encoding = "utf-8")+ assert "and not _local_plugin_payload_is_damaged(plugin_dir.name)" in source+++def test_an_unreadable_requires_dist_makes_the_whole_index_unreadable(monkeypatch) -> None:+ """A distribution whose Requires-Dist cannot be read is not a leaf; calling it one+ would let a step skip over a closure the audit never walked."""+ import importlib.metadata++ class _Dist:+ metadata = {"Name": "broken"}+ version = "1.0"++ @property+ def requires(self):+ raise ValueError("unreadable METADATA")++ monkeypatch.setattr(stack.install_manifest, "_metadata_scan_paths", lambda: [])+ monkeypatch.setattr(importlib.metadata, "distributions", lambda **kw: [_Dist()])+ assert stack.install_manifest.installed_dependency_index() is None+++def test_pip_backup_metadata_is_not_read_as_installed(tmp_path, monkeypatch) -> None:+ """An interrupted pip upgrade leaves ~ame-1.0.dist-info with the payload gone. pip+ ignores it, so the closure must too, or the step that would reinstall it skips."""+ site = tmp_path / "site-packages"+ backup = site / "~obble-0.1.dist-info"+ backup.mkdir(parents = True)+ (backup / "METADATA").write_text(+ "Metadata-Version: 2.1\nName: cobble\nVersion: 0.1\n", encoding = "utf-8"+ )+ live = site / "mammoth-1.0.dist-info"+ live.mkdir()+ (live / "METADATA").write_text(+ "Metadata-Version: 2.1\nName: mammoth\nVersion: 1.0\n", encoding = "utf-8"+ )+ monkeypatch.setattr(stack.install_manifest, "_metadata_scan_paths", lambda: [str(site)])+ index = stack.install_manifest.installed_dependency_index()+ assert index is not None+ assert "mammoth" in index+ assert "cobble" not in index, "the backup metadata was read as an installed package"+++def test_a_second_pass_in_one_process_starts_with_no_audited_steps() -> None:+ """The reset block clears what the previous pass registered, so a step this pass+ never reaches is not audited and recorded as known-unmet on its behalf."""+ source = (stack.__file__ and open(stack.__file__, encoding = "utf-8").read()) or ""+ reset = source.index("_STEP_RESULTS.clear()")+ assert "_AUDITED_STEPS.clear()" in source[reset : reset + 400]+++def test_the_mlx_payload_check_walks_each_records_files(monkeypatch, tmp_path) -> None:+ """find_spec sees only the top-level directory; a module the RECORD names that is+ gone or truncated is what makes the recorded verdict false, so it is what is checked."""+ import importlib.metadata+ import importlib.util+ from types import SimpleNamespace++ payload = tmp_path / "mlx_lm" / "sample_utils.py"+ payload.parent.mkdir()+ payload.write_bytes(b"x" * 10)++ # RECORD rows, not Distribution.files: CPython 3.13 drops missing paths from `files`.+ record = {"text": "mlx_lm/sample_utils.py,sha256=x,10\nmlx_lm/__pycache__/x.pyc,,\n"}+ dist = SimpleNamespace(+ read_text = lambda name: record["text"] if name == "RECORD" else None,+ locate_file = lambda f: tmp_path / str(f),+ )+ asked: list[str] = []++ def distribution(name):+ asked.append(name)+ return dist++ monkeypatch.setattr(importlib.util, "find_spec", lambda name: object())+ monkeypatch.setattr(importlib.metadata, "distribution", distribution)+ # The imported dependencies are walked too, except one not installed at all (the probe's).+ monkeypatch.setattr(+ stack,+ "_installed_distribution_version",+ lambda name: None if name == "sentencepiece" else "1.0",+ )+ assert stack._mlx_payload_present() is True+ # Every pinned MLX distribution, the Metal library included.+ assert set(asked) >= {"mlx", "mlx-metal", "mlx-lm", "mlx-vlm"}+ assert set(asked) >= set(stack._MLX_IMPORTED_DEPENDENCIES) - {"sentencepiece"}+ assert "sentencepiece" not in asked+ payload.write_bytes(b"x" * 3)+ assert stack._mlx_payload_present() is False+ payload.write_bytes(b"x" * 10)+ assert stack._mlx_payload_present() is True+ payload.unlink()+ assert stack._mlx_payload_present() is False+ # No RECORD is not "present" either: nothing then vouches for the payload.+ payload.write_bytes(b"x" * 10)+ record["text"] = None+ assert stack._mlx_payload_present() is False+++def test_the_parked_manifest_goes_right_after_the_live_one_is_removed(monkeypatch, tmp_path):+ """remove_manifest parks the live copy for setup.ps1's ordering. On the path that+ read the live manifest itself, the parked copy would otherwise outlive a pass killed+ part-way and be read by the next run as evidence of a completed pass."""+ manifest = stack.install_manifest+ live = tmp_path / manifest.MANIFEST_NAME+ parked = tmp_path / manifest.PREVIOUS_MANIFEST_NAME+ live.write_text("{}", encoding = "utf-8")+ monkeypatch.setattr(manifest, "manifest_path", lambda root = None: live)+ monkeypatch.setattr(manifest, "previous_manifest_path", lambda root = None: parked)+ assert manifest.remove_manifest() is True+ assert not live.exists() and parked.exists()+ manifest.consume_previous_manifest()+ assert not parked.exists()+ source = open(stack.__file__, encoding = "utf-8").read()+ at = source.index("if install_manifest.remove_manifest():")+ assert "install_manifest.consume_previous_manifest()" in source[at : at + 200]+ # The path is bound above the removal so the same check can run BEFORE it as well; the+ # invariant here is that the parked copy is read for and gone within this window.+ assert "_parked.exists()" in source[at : at + 400]+++def test_an_input_missing_from_the_record_or_unreadable_now_is_changed(monkeypatch, tmp_path):+ """pass_input_digests leaves out a file it could not read and digest_file answers None+ for one it cannot read now; compared with .get, the two Nones were equal and an+ unreadable requirements file counted as unchanged."""+ monkeypatch.setattr(stack, "REQ_ROOT", tmp_path)+ monkeypatch.setattr(stack, "_PASS_EVIDENCE", {"pass_inputs": {"studio.txt": "abc"}})+ digests = {"studio.txt": "abc"}+ monkeypatch.setattr(stack.install_manifest, "digest_file", lambda p: digests.get(p.name))+ assert stack._inputs_unchanged(["studio.txt"]) is True+ assert stack._inputs_unchanged(["extras.txt"]) is False, "not recorded, not readable: unchanged"+ digests["studio.txt"] = None+ assert stack._inputs_unchanged(["studio.txt"]) is False, "recorded, unreadable now"+ digests["studio.txt"] = "def"+ assert stack._inputs_unchanged(["studio.txt"]) is False+++def test_the_parked_manifest_is_consumed_when_it_is_read_as_evidence(monkeypatch, tmp_path):+ """The live manifest is removed before a pass so a killed pass leaves nothing that+ verifies as complete; the parked copy follows the same rule once read."""+ parked = tmp_path / "unsloth_install_manifest.previous.json"+ parked.write_text("{}", encoding = "utf-8")+ monkeypatch.setattr(stack.install_manifest, "previous_manifest_path", lambda root = None: parked)+ stack.install_manifest.consume_previous_manifest()+ assert not parked.exists()+ stack.install_manifest.consume_previous_manifest() # gone already: not an error+ source = open(stack.__file__, encoding = "utf-8").read()+ at = source.index("manifest = install_manifest.read_previous_manifest()")+ assert "install_manifest.consume_previous_manifest()" in source[at : at + 700]+ # And before every refusal: a forced pass killed part-way must not leave the parked copy behind.+ planner = source[source.index("def _plan_pass(") :]+ assert planner.index("consume_previous_manifest()") < planner.index("_full_deps_requested()")+ assert planner.index("consume_previous_manifest()") < planner.index(+ "_foreign_resolver_inputs()"+ )+++def test_duplicate_constrained_metadata_is_a_violation_not_an_absence(monkeypatch, tmp_path):+ """Two pyarrow records: importlib.metadata answers from whichever it meets first, so+ the pinned one can hide the other; the step that puts one record back must run."""+ manifest = stack.install_manifest+ req = tmp_path / "constraints.txt"+ req.write_text("pyarrow==15.0.0\nnumpy>=1.0\n", encoding = "utf-8")+ versions = {"pyarrow": ["15.0.0", "16.0.0"], "numpy": ["2.0.0"]}+ monkeypatch.setattr(manifest, "installed_versions", lambda name: versions.get(name, []))+ assert manifest.violated_constraints(req_file = req) == ["pyarrow"]+ versions["pyarrow"] = ["15.0.0"]+ assert manifest.violated_constraints(req_file = req) == []+ versions["pyarrow"] = [""]+ assert manifest.violated_constraints(req_file = req) == ["pyarrow"]+++# -- nothing the gate reads may end a pass that already installed everything ----+++def audited(monkeypatch, tmp_path):+ """One audited with-deps step, on a host where _effective_requirements really copies.++ Windows and --no-torch hosts filter the file, so the gate and the record read it from+ disk. The record is an argument to write_manifest, after every install has landed and+ after the core step may have replaced REQ_ROOT, so the file can be gone or not UTF-8.+ """+ req_root = tmp_path / "requirements"+ (req_root / "single-env").mkdir(parents = True)+ for name in stack.install_manifest.PASS_INPUT_FILES:+ (req_root / name).write_text(f"# {name}\n", encoding = "utf-8")+ monkeypatch.setattr(stack, "REQ_ROOT", req_root)+ monkeypatch.setattr(stack, "CONSTRAINTS", req_root / "single-env" / "constraints.txt")+ monkeypatch.setattr(stack, "IS_WINDOWS", True)+ monkeypatch.setattr(stack, "NO_TORCH", False)+ monkeypatch.setattr(stack, "IS_MAC_ARM", False)+ monkeypatch.setattr(stack, "PLATFORM_LACKS_TORCHCODEC_WHEEL", False)+ monkeypatch.setattr(stack.install_manifest, "missing_requirements", lambda *a, **k: [])+ monkeypatch.setattr(stack.install_manifest, "violated_constraints", lambda *a, **k: [])+ monkeypatch.setattr(stack.install_manifest, "closure_unmet_requirements", lambda *a, **k: [])+ monkeypatch.setattr(stack.install_manifest, "installed_dependency_index", lambda *a, **k: {})+ stack._AUDITED_STEPS["studio.txt"] = req_root / "studio.txt"+ return req_root+++def test_a_requirements_file_the_update_replaced_still_lets_the_manifest_be_written(+ audited,+) -> None:+ """The failure this guards is the worst shape available: every package installed, the+ pass then dies with a traceback, and the venv is left with no manifest at all -- which+ every reader takes for a half-built install."""+ (audited / "studio.txt").unlink()+ assert isinstance(stack._closure_record(), dict)+++def test_a_requirements_file_that_is_not_utf8_still_lets_the_manifest_be_written(audited) -> None:+ (audited / "studio.txt").write_bytes(b"\xff\xfe studio\n")+ assert isinstance(stack._closure_record(), dict)+++def test_a_temp_copy_that_cannot_be_written_still_lets_the_manifest_be_written(+ audited, monkeypatch+) -> None:+ """_filter_requirements already falls back from the requirements tree to the system+ temp dir; a host that refuses both is a reason to record nothing, not to fail."""++ def _refuse(*a, **k):+ raise OSError("read-only file system")++ monkeypatch.setattr(stack.tempfile, "NamedTemporaryFile", _refuse)+ assert isinstance(stack._closure_record(), dict)+++def test_a_step_whose_file_moved_mid_pass_runs_rather_than_raising(audited) -> None:+ """The same read, one line earlier, inside the gate."""+ target = audited / "studio.txt"+ stack._PASS_EVIDENCE = {+ "pass_inputs": {"studio.txt": stack.install_manifest.digest_file(target)},+ "step_results": {"studio.txt": "ran"},+ }+ target.unlink()+ assert stack._requirements_satisfied(target, no_deps = False) is False+++def test_a_triton_requirements_file_that_is_not_utf8_does_not_end_the_step(tmp_path) -> None:+ """triton-kernels.txt is read for its git direct reference. utf-8-sig raises a+ UnicodeDecodeError, not an OSError, and this step could not fail before."""+ target = tmp_path / "triton-kernels.txt"+ target.write_bytes(b"\xff\xfe git+https://example.invalid/x@abcdef1\n")+ assert stack._direct_reference_in_requirements(target) is None+++def test_every_uninstall_is_counted() -> None:+ """A mutation the counter does not see leaves the constraint and closure caches+ describing a venv that no longer exists, and lets the final `pip check` be skipped+ right after something was removed. Three sites removed distributions without saying+ so: the XPU generic-triton swap, the gfx906 bitsandbytes drop and the flash-attn+ rejection."""+ tree = ast.parse(STACK_PATH.read_text(encoding = "utf-8"))+ offenders = []+ for node in ast.walk(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ body = ast.dump(node)+ if "'uninstall'" not in body and '"uninstall"' not in body:+ continue+ if "_count_install_action" not in body:+ offenders.append(node.name)+ assert not offenders, f"uninstalls that do not move the counter: {offenders}"+++def test_rejecting_a_flash_attn_wheel_counts_as_an_install_action(monkeypatch) -> None:+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 0)+ monkeypatch.setattr(stack, "USE_UV", False)+ monkeypatch.setattr(+ stack.subprocess, "run", lambda *a, **k: types.SimpleNamespace(returncode = 0)+ )+ assert stack._remove_rejected_flash_attn() is True+ assert stack._INSTALL_ACTIONS == 1+++def test_installing_a_flash_attn_wheel_counts_as_an_install_action(monkeypatch) -> None:+ """install_wheel lands a distribution without going through pip_install, so nothing+ else on that path moves the counter."""+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 0)+ monkeypatch.setattr(stack, "NO_TORCH", False)+ monkeypatch.setattr(stack, "IS_WINDOWS", False)+ monkeypatch.setattr(stack, "IS_MACOS", False)+ monkeypatch.setattr(stack, "_flash_attn_install_disabled", lambda: False)+ monkeypatch.setattr(stack, "_flash_attn_importable", lambda: False)+ monkeypatch.setattr(stack, "probe_torch_wheel_env", lambda: {"torch": "2.8.0"})+ monkeypatch.setattr(stack, "_build_flash_attn_wheel_url", lambda env: "https://x.invalid/w")+ monkeypatch.setattr(stack, "url_exists", lambda url, **k: True)+ monkeypatch.setattr(+ stack,+ "install_wheel",+ lambda *a, **k: iter([("uv", types.SimpleNamespace(returncode = 1, stdout = "", stderr = ""))]),+ )+ monkeypatch.setattr(stack, "_print_optional_install_failure", lambda *a, **k: None)+ monkeypatch.setattr(stack, "_step", lambda *a, **k: None)+ stack._ensure_flash_attn()+ assert stack._INSTALL_ACTIONS == 1+++def test_the_installed_index_is_rebuilt_against_a_fresh_metadata_listing(monkeypatch) -> None:+ """importlib.metadata memoises directory listings and revalidates them on mtime, which+ is one-second granular on some filesystems, so a rebuild in the same tick as the+ install that triggered it can read the listing from before. The gate invalidates+ before its own on-disk check; _closure_record reaches the index without one."""+ calls = []+ monkeypatch.setattr(stack, "_CLOSURE_INDEX_CACHE", None)+ monkeypatch.setattr(stack, "_INSTALL_ACTIONS", 0)+ monkeypatch.setattr(stack.importlib, "invalidate_caches", lambda: calls.append(1))+ monkeypatch.setattr(+ stack.install_manifest, "installed_dependency_index", lambda: {"a": ("1", [])}+ )+ assert stack._installed_index() == {"a": ("1", [])}+ assert calls == [1]+ # Cached while nothing moves: the invalidation is not paid per gated step.+ stack._installed_index()+ assert calls == [1]+ # ...and paid again the moment something is installed.+ stack._count_install_action()+ stack._installed_index()+ assert calls == [1, 1]+++def test_an_unclearable_parked_copy_refuses_before_the_live_manifest_is_dropped(+ monkeypatch, tmp_path+) -> None:+ """A parked path that cannot be removed (a directory on the name, a held handle) used to+ be found only AFTER remove_manifest took the live manifest away: the pass exited 1, the+ venv read as half-built and every later update refused at the same point, on an install+ complete a moment earlier. The refusal now happens while the manifest is still there.+ """+ live = tmp_path / stack.install_manifest.MANIFEST_NAME+ live.write_text("{}", encoding = "utf-8")+ parked = tmp_path / stack.install_manifest.PREVIOUS_MANIFEST_NAME+ parked.mkdir() # cannot be unlinked, and os.replace onto it raises++ monkeypatch.setattr(stack.install_manifest, "venv_root", lambda *a, **k: tmp_path)+ monkeypatch.setattr(stack.install_manifest, "manifest_path", lambda *a, **k: live)+ monkeypatch.setattr(stack.install_manifest, "previous_manifest_path", lambda *a, **k: parked)+ monkeypatch.setattr(stack, "_plan_pass", lambda *a, **k: None)+ monkeypatch.setattr(stack, "_safe_print", lambda *a, **k: None)+ monkeypatch.setattr(stack, "_step", lambda *a, **k: None)+ monkeypatch.setattr(stack, "_progress", lambda *a, **k: None)++ assert stack.install_python_stack() == 1+ assert live.exists(), "the live manifest was dropped before the refusal"+ assert stack.install_manifest.read_manifest(tmp_path) is not None+++def test_a_temp_copy_that_cannot_be_unlinked_does_not_end_the_pass(audited, monkeypatch) -> None:+ """The audit's own cleanup runs after the last install and before the manifest write.+ A Windows sharing violation on its temp copy -- an indexer or scanner holding the file+ -- used to escape from the `finally` and end the update there, with everything+ installed and no manifest written."""+ real = stack.Path.unlink++ def _locked(self, *a, **k):+ if "-filtered-" in self.name:+ raise PermissionError(32, "The process cannot access the file")+ return real(self, *a, **k)++ monkeypatch.setattr(stack.Path, "unlink", _locked)+ assert isinstance(stack._closure_record(), dict)+ # The gate's own cleanup is the same shape, one step earlier: it must answer, not raise.+ stack._PASS_EVIDENCE = {"pass_inputs": {}, "step_results": {}}+ assert stack._requirements_satisfied(audited / "studio.txt", no_deps = False) is Falsediff --git a/tests/studio/install/test_install_manifest.py b/tests/studio/install/test_install_manifest.pyindex a493a03c239..3c6d302788a 100644--- a/tests/studio/install/test_install_manifest.py+++ b/tests/studio/install/test_install_manifest.py@@ -402,6 +402,7 @@ def test_remove_manifest_reports_whether_the_marker_is_really_gone(def _refuse(*_args, **_kwargs):raise PermissionError(13, "Access is denied")+ monkeypatch.setattr(im.os, "replace", _refuse)monkeypatch.setattr(pathlib.Path, "unlink", _refuse)assert im.remove_manifest(install_root) is Falsemonkeypatch.undo()@@ -672,3 +673,52 @@ def test_the_venv_resolver_finds_both_layouts(tmp_path):reqs = root / layout / "studio" / "backend" / "requirements"reqs.mkdir(parents = True)assert im.installed_requirements_root(root) == reqs+++def test_remove_manifest_parks_the_file_as_evidence_only(install_root, req_root):+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")+ live = json.loads(im.manifest_path(install_root).read_text(encoding = "utf-8"))+ assert im.remove_manifest(install_root) is True+ assert not im.manifest_path(install_root).is_file()+ # The parked copy is byte-for-byte the last completed pass...+ assert im.read_previous_manifest(install_root) == live+ # ...and nothing that decides whether the venv is finished can see it.+ state = im.verify_install(root = install_root, req_root = req_root, package_name = "pytest")+ assert state["reason"] == "studio_install_incomplete"+ assert im.read_manifest(install_root) is None+ # A pass that verifies against the parked copy gets the same verdict the live file gave.+ parked = im.read_previous_manifest(install_root)+ state = im.verify_install(+ root = install_root, req_root = req_root, package_name = "pytest", manifest = parked+ )+ assert state["manifest_ok"] is True+++def test_remove_manifest_falls_back_to_deleting_when_the_rename_is_refused(+ install_root, req_root, monkeypatch+):+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")++ def _refuse(*_args, **_kwargs):+ raise PermissionError(13, "Access is denied")++ monkeypatch.setattr(im.os, "replace", _refuse)+ assert im.remove_manifest(install_root) is True+ assert not im.manifest_path(install_root).is_file()+ assert im.read_previous_manifest(install_root) is None+++def test_write_manifest_drops_the_parked_copy(install_root, req_root):+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")+ im.remove_manifest(install_root)+ assert im.previous_manifest_path(install_root).is_file()+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")+ assert im.manifest_path(install_root).is_file()+ assert not im.previous_manifest_path(install_root).is_file()+++def test_a_parked_manifest_is_never_read_as_the_live_one(install_root, req_root):+ im.write_manifest(root = install_root, req_root = req_root, package_name = "pytest")+ im.remove_manifest(install_root)+ assert im.recorded_no_torch(root = install_root) is None+ assert im.read_manifest(install_root) is Nonediff --git a/tests/studio/install/test_install_manifest_damage.py b/tests/studio/install/test_install_manifest_damage.pyindex 0fdba19d38b..f685eb13449 100644--- a/tests/studio/install/test_install_manifest_damage.py+++ b/tests/studio/install/test_install_manifest_damage.py@@ -187,11 +187,12 @@ def test_a_larger_file_is_not_damage(site_packages):assert install_manifest.damaged_payload_files(PKG) == []-def test_an_absent_record_is_not_damage(site_packages):- """RECORD is optional per the installed-projects spec."""+def test_an_absent_record_in_a_dist_info_is_damage(site_packages):+ """uv and pip write RECORD last, so a managed wheel install without one was+ interrupted, and every truncation of its payload is invisible to the size check."""_dist(site_packages)_write(site_packages / PKG / "__init__.py", "x = 1\n")- assert install_manifest.damaged_payload_files(PKG) == []+ assert install_manifest.damaged_payload_files(PKG) == [f"{PKG}: RECORD is missing"]def test_an_unreadable_file_is_not_damage(site_packages):diff --git a/tests/studio/install/test_install_manifest_pass_evidence.py b/tests/studio/install/test_install_manifest_pass_evidence.pynew file mode 100644index 00000000000..3197b8a0396--- /dev/null+++ b/tests/studio/install/test_install_manifest_pass_evidence.py@@ -0,0 +1,1046 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The evidence the idempotent dependency pass records and reads back.++Every skip in install_python_stack.py is gated on three things: the previous run+recorded that it did this exact work, the inputs are byte-identical, and a cheap+on-disk check of the OUTPUT still passes. This file covers the pieces of that in+install_manifest.py -- the additive manifest keys, the digests, the constraint+check and the sidecar predicate -- because a false "already done" here is an+install nobody can tell apart from a finished one.+"""++from __future__ import annotations++import ast+import contextlib+import errno+import importlib.util+import json+import os+import pathlib+import stat+import subprocess+import sys+import sysconfig+import tempfile+import textwrap+import time+import unittest.mock++import pytest++REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]+MODULE_PATH = REPO_ROOT / "studio" / "install_manifest.py"+++def _load_module():+ spec = importlib.util.spec_from_file_location("studio_install_manifest_evidence", MODULE_PATH)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++im = _load_module()+++# -- digests -------------------------------------------------------------------+++def test_pass_inputs_are_a_superset_of_the_tracked_requirements() -> None:+ """The pass reads more files than verify_install fingerprints, and they stay two lists:+ verify_install compares the whole `requirement_files` dict, so widening THAT one reports+ every install in the field as `studio_install_requirements_changed`.+ """+ assert im.PASS_INPUT_FILES[: len(im.TRACKED_REQUIREMENT_FILES)] == (+ im.TRACKED_REQUIREMENT_FILES+ )+ for extra in (+ "diffusers-pin.txt",+ "triton-kernels.txt",+ "single-env/constraints.txt",+ ):+ assert extra in im.PASS_INPUT_FILES+ assert extra not in im.TRACKED_REQUIREMENT_FILES+++def test_the_shipped_requirements_tree_supplies_every_pass_input() -> None:+ """A name nothing on disk answers is evidence that can never match."""+ digests = im.pass_input_digests(REPO_ROOT / "studio" / "backend" / "requirements")+ assert set(digests) == set(im.PASS_INPUT_FILES)+++def test_an_absent_or_unreadable_input_has_no_digest(tmp_path: pathlib.Path) -> None:+ """None never equals a recorded digest, so the step that reads it runs."""+ assert im.digest_file(tmp_path / "nope.txt") is None+ assert im.digest_file(tmp_path) is None+ target = tmp_path / "there.txt"+ target.write_bytes(b"payload")+ assert im.digest_file(target) == im.digest_file(str(target))+ assert (tmp_path / "nope.txt").name not in im.pass_input_digests(tmp_path)+++def test_a_one_byte_edit_changes_the_digest(tmp_path: pathlib.Path) -> None:+ target = tmp_path / "studio.txt"+ target.write_text("structlog\n", encoding = "utf-8")+ before = im.digest_file(target)+ target.write_text("structlog \n", encoding = "utf-8")+ assert im.digest_file(target) != before+++# -- additive manifest keys ----------------------------------------------------+++def _payload(root: pathlib.Path) -> dict:+ return json.loads((root / im.MANIFEST_NAME).read_text(encoding = "utf-8"))+++def test_extra_keys_are_written_and_schema_stays_1(tmp_path: pathlib.Path) -> None:+ im.write_manifest(+ root = tmp_path,+ req_root = tmp_path,+ package_name = "pytest",+ extra = {"pass_inputs": {"studio.txt": "abc"}, "pip_check_ok": True},+ )+ payload = _payload(tmp_path)+ assert payload["schema"] == im.MANIFEST_SCHEMA == 1+ assert payload["pass_inputs"] == {"studio.txt": "abc"}+ assert payload["pip_check_ok"] is True+++def test_a_none_extra_is_left_out_entirely(tmp_path: pathlib.Path) -> None:+ """Absent means unknown for these keys too, exactly as for no_torch."""+ im.write_manifest(+ root = tmp_path, req_root = tmp_path, package_name = "pytest", extra = {"mlx_health": None}+ )+ assert "mlx_health" not in _payload(tmp_path)+++def test_extras_cannot_shadow_a_field_verify_install_reads(tmp_path: pathlib.Path) -> None:+ """`extra` is evidence, never authority: package_version and requirement_files+ are what decides whether this install is complete."""+ im.write_manifest(+ root = tmp_path,+ req_root = tmp_path,+ package_name = "pytest",+ extra = {"package_version": "9.9.9", "requirement_files": {"studio.txt": "no"}, "schema": 7},+ )+ payload = _payload(tmp_path)+ assert payload["schema"] == 1+ assert payload["requirement_files"] == im.requirement_digests(tmp_path)+ assert payload["package_version"] != "9.9.9"+++def test_update_manifest_merges_without_touching_the_rest(tmp_path: pathlib.Path) -> None:+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ before = _payload(tmp_path)+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is True+ after = _payload(tmp_path)+ assert after["mlx_health"] == {"ok": True}+ assert after["completed_at_ms"] == before["completed_at_ms"]+ assert after["requirement_files"] == before["requirement_files"]+++def test_update_manifest_never_creates_one(tmp_path: pathlib.Path) -> None:+ """The manifest's presence means the install finished; a post-manifest probe+ must not be able to claim that on its own."""+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is False+ assert not (tmp_path / im.MANIFEST_NAME).exists()+++def test_update_manifest_merges_into_the_manifest_it_replaces(+ tmp_path: pathlib.Path, monkeypatch+) -> None:+ """The caller spends minutes gathering this evidence (the MLX probe waits up to 180 s).+ If a second updater removed the manifest and finished a new pass in that time, merging+ into a copy read before the probe would put the old pass's fields back -- including+ no_torch and the torch flavour, which a later update acts on."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest", no_torch = True)+ assert _payload(tmp_path)["no_torch"] is True+ real_lock = im._manifest_lock+ done: list[int] = []++ @contextlib.contextmanager+ def _lock_with_a_peer_ahead_of_us(root = None):+ # The second updater got there first: it removed the manifest, ran its pass and wrote+ # a new one. Everything it did is complete before this call takes the lock.+ if not done:+ done.append(1)+ assert im.remove_manifest(root = tmp_path) is True+ im.write_manifest(+ root = tmp_path, req_root = tmp_path, package_name = "pytest", no_torch = False+ )+ with real_lock(root) as locked:+ yield locked++ monkeypatch.setattr(im, "_manifest_lock", _lock_with_a_peer_ahead_of_us)+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is True+ after = _payload(tmp_path)+ assert after["mlx_health"] == {"ok": True}+ assert after["no_torch"] is False, "the newer pass's fields were overwritten"+++def test_the_manifest_lock_is_exclusive_across_processes(tmp_path: pathlib.Path) -> None:+ """The writers serialise against another PROCESS, not just another thread: setup.sh,+ setup.ps1, the installer and the CLI are separate processes on one venv."""+ order = tmp_path / "order.txt"+ child_code = "\n".join(+ [+ f"import sys, time, pathlib",+ f"sys.path.insert(0, {str(pathlib.Path(im.__file__).resolve().parent)!r})",+ f"import install_manifest as im",+ f"with im._manifest_lock(pathlib.Path({str(tmp_path)!r})):",+ f" pathlib.Path({str(tmp_path / 'held')!r}).write_text('1', encoding='utf-8')",+ f" time.sleep(1.5)",+ f" fh = open({str(order)!r}, 'a', encoding='utf-8')",+ f" fh.write('child-released\\n')",+ f" fh.close()",+ ]+ )+ child = subprocess.Popen([sys.executable, "-c", child_code])+ try:+ held = tmp_path / "held"+ deadline = time.time() + 20+ while not held.exists() and time.time() < deadline:+ time.sleep(0.02)+ assert held.exists(), "the child never took the lock"+ with im._manifest_lock(tmp_path):+ with order.open("a", encoding = "utf-8") as fh:+ fh.write("parent-acquired\n")+ finally:+ child.wait(timeout = 30)+ # Ordering, not duration: the parent's acquire cannot land inside the child's hold.+ assert order.read_text(encoding = "utf-8").split() == ["child-released", "parent-acquired"]+++def test_the_advisory_write_declines_rather_than_publish_unserialised(+ tmp_path: pathlib.Path, monkeypatch+) -> None:+ """A peer holding the lock past the timeout is mid-pass. write_manifest and+ remove_manifest must still go ahead there (failing an install is worse), but this one+ merges evidence a probe gathered minutes ago: publishing beside that peer risks putting+ its removed completion marker back over a half-built venv, and losing the evidence costs+ one probe."""+ monkeypatch.setattr(im, "LOCK_WAIT_SECONDS", 0.3)+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ before = _payload(tmp_path)+ holder = "\n".join(+ [+ "import sys, time, pathlib",+ f"sys.path.insert(0, {str(pathlib.Path(im.__file__).resolve().parent)!r})",+ "import install_manifest as im",+ f"with im._manifest_lock(pathlib.Path({str(tmp_path)!r})):",+ f" pathlib.Path({str(tmp_path / 'held')!r}).write_text('1', encoding='utf-8')",+ " time.sleep(30)",+ ]+ )+ child = subprocess.Popen([sys.executable, "-c", holder])+ try:+ deadline = time.time() + 20+ while not (tmp_path / "held").exists() and time.time() < deadline:+ time.sleep(0.02)+ assert (tmp_path / "held").exists(), "the child never took the lock"+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is False+ assert _payload(tmp_path) == before+ # The two that must never fail an install still do their work.+ assert im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.remove_manifest(root = tmp_path) is True+ finally:+ child.kill()+ child.wait(timeout = 30)++[email protected](not hasattr(os, "O_NOFOLLOW"), reason = "needs O_NOFOLLOW")+def test_a_symlink_on_the_lock_name_is_not_followed(tmp_path: pathlib.Path) -> None:+ """Followed, it would open or create a file somewhere else entirely, and a replacement+ of the target behind it would let two holders think they had the same lock."""+ elsewhere = tmp_path / "elsewhere.txt"+ os.symlink(elsewhere, tmp_path / im.LOCK_NAME)+ with im._manifest_lock(tmp_path) as locked:+ assert locked is False+ assert not elsewhere.exists(), "the symlink's target was created"+ # ...and the writers still work, unserialised, as they did before the lock existed.+ assert im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+++def test_a_filesystem_without_locking_is_not_waited_out(+ tmp_path: pathlib.Path, monkeypatch+) -> None:+ """Some NFS and SMB mounts answer immediately that they do not implement locking. Only+ contention is worth waiting out; retrying that answer would cost the whole deadline on+ every manifest write."""+ fcntl = pytest.importorskip("fcntl")+ monkeypatch.setattr(im, "LOCK_WAIT_SECONDS", 5.0)++ def _unsupported(*_args, **_kwargs):+ raise OSError(errno.ENOTSUP, "locking not supported")++ monkeypatch.setattr(fcntl, "flock", _unsupported)+ started = time.monotonic()+ with im._manifest_lock(tmp_path) as locked:+ assert locked is False+ assert time.monotonic() - started < 1.0+++def test_a_stuck_peer_does_not_wedge_the_lock(tmp_path: pathlib.Path, monkeypatch) -> None:+ """A process suspended or stopped while holding the lock must not stop every later+ update: after the wait the writer goes ahead unserialised, which is what shipped before+ the lock existed. Windows does this on its own (msvcrt's LK_LOCK gives up); POSIX flock+ waits forever unless asked not to."""+ monkeypatch.setattr(im, "LOCK_WAIT_SECONDS", 0.3)+ holder = "\n".join(+ [+ "import sys, time, pathlib",+ f"sys.path.insert(0, {str(pathlib.Path(im.__file__).resolve().parent)!r})",+ "import install_manifest as im",+ f"with im._manifest_lock(pathlib.Path({str(tmp_path)!r})):",+ f" pathlib.Path({str(tmp_path / 'held')!r}).write_text('1', encoding='utf-8')",+ " time.sleep(30)",+ ]+ )+ child = subprocess.Popen([sys.executable, "-c", holder])+ try:+ held = tmp_path / "held"+ deadline = time.time() + 20+ while not held.exists() and time.time() < deadline:+ time.sleep(0.02)+ assert held.exists(), "the child never took the lock"+ started = time.monotonic()+ with im._manifest_lock(tmp_path):+ pass+ waited = time.monotonic() - started+ assert waited < 10, f"waited {waited:.1f}s on a peer that never lets go"+ # ...and the writers still answer while that peer holds it.+ assert im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ finally:+ child.kill()+ child.wait(timeout = 30)+++def test_every_manifest_writer_takes_the_lock() -> None:+ """A writer outside it reintroduces the race the lock exists for, and nothing in the+ payloads themselves would show it."""+ source = pathlib.Path(im.__file__).read_text(encoding = "utf-8")+ tree = ast.parse(source)+ writers = {+ node.name: node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef)+ and node.name in ("write_manifest", "update_manifest", "remove_manifest")+ }+ assert set(writers) == {"write_manifest", "update_manifest", "remove_manifest"}+ for name, node in writers.items():+ body = ast.unparse(node)+ assert "_manifest_lock(" in body, f"{name} replaces the manifest outside the lock"+ assert "os.replace" not in body or "_manifest_lock(" in body+++def test_a_root_that_cannot_hold_a_lock_still_writes(tmp_path: pathlib.Path, monkeypatch) -> None:+ """This module has to run inside a half-built venv and on filesystems that cannot lock.+ Unserialised is the behaviour that shipped before; failing the install is not."""++ def _no_open(*_args, **_kwargs):+ raise OSError("no lock file here")++ monkeypatch.setattr(pathlib.Path, "open", _no_open)+ with im._manifest_lock(tmp_path):+ pass+ monkeypatch.undo()+ assert im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is True+ assert im.remove_manifest(root = tmp_path) is True+++def test_remove_manifest_keeps_the_live_one_when_the_parked_name_cannot_be_cleared(+ tmp_path: pathlib.Path,+) -> None:+ """setup.ps1 reads True here as permission to replace pip, torch and triton, and the+ dependency pass refuses to run behind a parked copy it cannot clear. Dropping the live+ manifest first would put that refusal after the mutations, on a venv that can no longer+ verify, and every later update would stop at the same place."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ live = tmp_path / im.MANIFEST_NAME+ # A directory on the reserved name refuses both the rename and the unlink, on every OS.+ blocked = tmp_path / im.PREVIOUS_MANIFEST_NAME+ blocked.mkdir()+ (blocked / "keep.txt").write_text("x", encoding = "utf-8")++ assert im.remove_manifest(root = tmp_path) is False+ assert live.exists(), "the venv must still verify when the pass cannot be entered"++ # Cleared, the same call parks as usual.+ (blocked / "keep.txt").unlink()+ blocked.rmdir()+ assert im.remove_manifest(root = tmp_path) is True+ assert not live.exists() and (tmp_path / im.PREVIOUS_MANIFEST_NAME).exists()+++def test_remove_manifest_refuses_an_unclearable_parked_copy_with_no_live_manifest(+ tmp_path: pathlib.Path,+) -> None:+ """An interrupted run already took the live manifest. Nothing is parked by this call, so+ a surviving copy is that dead run's, and answering True would send setup.ps1 into its+ pip/torch mutations ahead of the refusal the pass makes on exactly that path."""+ blocked = tmp_path / im.PREVIOUS_MANIFEST_NAME+ blocked.mkdir()+ (blocked / "keep.txt").write_text("x", encoding = "utf-8")+ assert im.remove_manifest(root = tmp_path) is False++ (blocked / "keep.txt").unlink()+ blocked.rmdir()+ assert im.remove_manifest(root = tmp_path) is True+++def test_a_dead_runs_parked_copy_does_not_outlive_the_next_invalidation(+ tmp_path: pathlib.Path,+) -> None:+ """It would otherwise be read as this pass's evidence."""+ (tmp_path / im.PREVIOUS_MANIFEST_NAME).write_text("{}", encoding = "utf-8")+ assert im.remove_manifest(root = tmp_path) is True+ assert not (tmp_path / im.PREVIOUS_MANIFEST_NAME).exists()+++def test_remove_manifest_parks_over_a_stale_copy_it_can_clear(tmp_path: pathlib.Path) -> None:+ """The ordinary case the fallback must not punish: a leftover file from a run that died+ is replaced, not treated as an obstruction."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ (tmp_path / im.PREVIOUS_MANIFEST_NAME).write_text("{}", encoding = "utf-8")+ assert im.remove_manifest(root = tmp_path) is True+ assert not (tmp_path / im.MANIFEST_NAME).exists()+ assert im.read_previous_manifest(root = tmp_path)["schema"] == im.MANIFEST_SCHEMA++[email protected](os.name == "nt", reason = "POSIX file modes")+def test_the_manifest_keeps_the_mode_it_had(tmp_path: pathlib.Path) -> None:+ """It used to be written through Path.write_text, so it carried the umask default and+ anything else on the machine could read it. mkstemp creates at 0600, and silently+ narrowing a file other tooling may read is a change nobody asked for."""+ previous = os.umask(0o022)+ try:+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ live = tmp_path / im.MANIFEST_NAME+ assert stat.S_IMODE(live.stat().st_mode) == 0o644+ # ...and a mode the user tightened stays tightened.+ os.chmod(live, 0o600)+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is True+ assert stat.S_IMODE(live.stat().st_mode) == 0o600+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert stat.S_IMODE(live.stat().st_mode) == 0o600+ finally:+ os.umask(previous)+++def test_two_writers_do_not_share_a_temp_file(tmp_path: pathlib.Path) -> None:+ """A temp name shared between writers is a second writer's file as much as this one's:+ one could remove or overwrite the other's copy between the write and the replace, and+ publish the wrong payload into the manifest that says the install finished."""+ seen: list[str] = []+ real_mkstemp = tempfile.mkstemp++ def _record(*args, **kwargs):+ descriptor, name = real_mkstemp(*args, **kwargs)+ seen.append(pathlib.Path(name).name)+ return descriptor, name++ with unittest.mock.patch.object(tempfile, "mkstemp", _record):+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is True+ assert len(seen) == 2 and seen[0] != seen[1], seen+ assert all(name.startswith(im.MANIFEST_NAME + ".") for name in seen)+ # Neither copy outlives its writer.+ assert not list(tmp_path.glob("*.tmp"))+ assert _payload(tmp_path)["mlx_health"] == {"ok": True}+++def test_update_manifest_does_not_recreate_one_removed_while_it_worked(+ tmp_path: pathlib.Path, monkeypatch+) -> None:+ """A peer running an older build of this module removes the manifest without taking the+ lock. Writing it back would put a completion marker over the venv that peer is part-way+ through rebuilding."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ live = tmp_path / im.MANIFEST_NAME+ real_read = im.read_manifest++ def _read_then_the_peer_removes_it(root = None):+ data = real_read(root)+ live.unlink(missing_ok = True)+ return data++ monkeypatch.setattr(im, "read_manifest", _read_then_the_peer_removes_it)+ assert im.update_manifest(root = tmp_path, mlx_health = {"ok": True}) is False+ monkeypatch.undo()+ assert not live.exists()+ assert not list(tmp_path.glob("*.tmp")), "the temp copy outlived the call"+++def test_update_manifest_with_nothing_to_say_is_a_no_op(tmp_path: pathlib.Path) -> None:+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.update_manifest(root = tmp_path) is False+ assert im.update_manifest(root = tmp_path, mlx_health = None) is False+++def test_update_manifest_survives_a_corrupt_manifest(tmp_path: pathlib.Path) -> None:+ (tmp_path / im.MANIFEST_NAME).write_text("{not json", encoding = "utf-8")+ assert im.update_manifest(root = tmp_path, pip_check_ok = True) is False+ assert (tmp_path / im.MANIFEST_NAME).read_text(encoding = "utf-8") == "{not json"+++def test_update_manifest_cannot_shadow_a_field_verify_install_reads(tmp_path: pathlib.Path) -> None:+ """The same guard write_manifest applies to `extra`, on the merge path. This one merges+ into a manifest that already means "the install finished", so a caller able to rewrite+ `package_version` or `prefix` leaves a file that validates and describes nobody's install.+ """+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ before = _payload(tmp_path)+ assert (+ im.update_manifest(+ root = tmp_path,+ schema = 7,+ package_version = "9.9.9",+ requirement_files = {"studio.txt": "no"},+ prefix = "/somewhere/else",+ steps_total = 999,+ mlx_health = {"ok": True},+ )+ is True+ )+ after = _payload(tmp_path)+ for key in ("schema", "package_version", "requirement_files", "prefix", "steps_total"):+ assert after[key] == before[key], key+ # The additive key it was actually called for still lands.+ assert after["mlx_health"] == {"ok": True}+++def test_update_manifest_with_only_protected_keys_writes_nothing(tmp_path: pathlib.Path) -> None:+ """Nothing left to merge is "record nothing", the same answer as no arguments at+ all -- and, in particular, not a rewrite of the file with the keys dropped."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ raw = (tmp_path / im.MANIFEST_NAME).read_bytes()+ assert im.update_manifest(root = tmp_path, package_version = "9.9.9") is False+ assert (tmp_path / im.MANIFEST_NAME).read_bytes() == raw+++def test_both_writers_refuse_the_same_keys() -> None:+ """One constant, because two copies of this list is how the two writers would drift. Every+ key write_manifest sets from its own arguments is in it, the optional three included:+ absent means "unknown", and only a build that knew the answer may write one.+ """+ for key in (+ "schema",+ "completed_at_ms",+ "package",+ "package_version",+ "python",+ "platform",+ "prefix",+ "steps_total",+ "requirement_files",+ "no_torch",+ "expected_torch_tag",+ "expected_torch_tag_pinned",+ ):+ assert key in im.PROTECTED_MANIFEST_KEYS, key+ source = MODULE_PATH.read_text(encoding = "utf-8")+ assert source.count("PROTECTED_MANIFEST_KEYS: Tuple[str, ...] = (") == 1+ # Both writers, and no third spelling of the rule.+ assert source.count("key not in PROTECTED_MANIFEST_KEYS") == 1+ assert source.count("or key in PROTECTED_MANIFEST_KEYS") == 1+++def test_an_optional_field_cannot_be_invented_by_evidence(tmp_path: pathlib.Path) -> None:+ """no_torch absent means "unknown", and a GGUF-only venv is what the wrong answer+ costs: the next update reinstalls torch into it."""+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.update_manifest(root = tmp_path, no_torch = True) is False+ assert "no_torch" not in _payload(tmp_path)+ im.write_manifest(+ root = tmp_path, req_root = tmp_path, package_name = "pytest", extra = {"no_torch": True}+ )+ assert "no_torch" not in _payload(tmp_path)+++# -- constraints ---------------------------------------------------------------+++def test_an_absent_distribution_does_not_violate_a_constraint(tmp_path: pathlib.Path) -> None:+ """A constraints file never asks for an install, so nothing to install is+ nothing to repair -- otherwise every pass would run forever."""+ constraints = tmp_path / "constraints.txt"+ constraints.write_text("nonexistent-dist-xyz<2\n", encoding = "utf-8")+ assert im.violated_constraints(constraints, installed = {}) == []+++def test_a_resident_version_outside_the_window_is_reported(tmp_path: pathlib.Path) -> None:+ constraints = tmp_path / "constraints.txt"+ constraints.write_text(+ "# a comment\n\npytest>=99\nanyio<1 # inline\n-r other.txt\n", encoding = "utf-8"+ )+ violated = im.violated_constraints(constraints, installed = {"pytest": "8.0.0", "anyio": "0.1"})+ assert violated == ["pytest"]+++def test_an_unpinned_or_unreadable_constraints_file_reports_nothing(tmp_path: pathlib.Path) -> None:+ bare = tmp_path / "bare.txt"+ bare.write_text("pytest\n", encoding = "utf-8")+ assert im.violated_constraints(bare, installed = {"pytest": "8.0.0"}) == []+ assert im.violated_constraints(tmp_path / "gone.txt", installed = {}) == []+++def test_the_shipped_constraints_file_parses() -> None:+ """Not an assertion about this machine's venv, only that the real file is+ readable by the parser the skip gate relies on."""+ real = REPO_ROOT / "studio" / "backend" / "requirements" / "single-env" / "constraints.txt"+ assert isinstance(im.violated_constraints(real, installed = {}), list)+++# -- sidecar predicate ---------------------------------------------------------+++def _sidecar(+ root: pathlib.Path,+ name: str,+ version: str,+ *,+ files = ("__init__.py",),+) -> None:+ """A flat `pip --target` tree: package dir, dist-info, RECORD with sizes."""+ package = root / name.replace("-", "_")+ package.mkdir(parents = True, exist_ok = True)+ rows = []+ for relative in files:+ target = package / relative+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 32)+ rows.append(f"{package.name}/{relative},sha256=deadbeef,32")+ dist_info = root / f"{name.replace('-', '_')}-{version}.dist-info"+ dist_info.mkdir(parents = True, exist_ok = True)+ (dist_info / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding = "utf-8"+ )+ (dist_info / "RECORD").write_text("\n".join(rows) + "\n", encoding = "utf-8")+++def sidecar(tmp_path: pathlib.Path) -> pathlib.Path:+ root = tmp_path / ".venv_t5_530"+ root.mkdir()+ (root / im.SIDECAR_OWNED_MARKER).write_text("", encoding = "utf-8")+ _sidecar(root, "transformers", "5.3.0")+ _sidecar(root, "huggingface_hub", "1.8.0")+ _sidecar(root, "hf_xet", "1.4.2")+ _sidecar(root, "tiktoken", "0.9.0")+ return root+++PINS = ("transformers==5.3.0", "huggingface_hub==1.8.0", "hf_xet==1.4.2", "tiktoken")+++def test_a_complete_sidecar_is_current(sidecar: pathlib.Path) -> None:+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+++def test_a_missing_or_empty_directory_is_not_current(tmp_path: pathlib.Path) -> None:+ assert im.sidecar_is_current(tmp_path / "gone", PINS)[0] is False+ empty = tmp_path / "empty"+ empty.mkdir()+ assert im.sidecar_is_current(empty, PINS) == (False, "empty")+++def test_an_unowned_directory_is_never_current(sidecar: pathlib.Path) -> None:+ """Rebuilding starts with rm -rf, so "current" has to mean "and ours"."""+ (sidecar / im.SIDECAR_OWNED_MARKER).unlink()+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and im.SIDECAR_OWNED_MARKER in reason+++def test_a_wrong_version_names_itself(sidecar: pathlib.Path) -> None:+ current, reason = im.sidecar_is_current(sidecar, ("transformers==5.5.0",) + PINS[1:])+ assert current is False+ assert "transformers==5.3.0" in reason and "5.5.0" in reason+++def test_an_unpinned_name_only_has_to_be_present(sidecar: pathlib.Path) -> None:+ assert im.sidecar_is_current(sidecar, ("tiktoken",)) == (True, "")+ current, reason = im.sidecar_is_current(sidecar, ("regex",))+ assert current is False and "regex" in reason+++def test_metadata_without_its_package_tree_is_not_current(sidecar: pathlib.Path) -> None:+ """The failure mode the version check alone cannot see: an interrupted pip+ leaves METADATA behind and takes the module with it."""+ import shutil++ shutil.rmtree(sidecar / "transformers")+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and "directory missing" in reason+++def test_a_truncated_recorded_file_forces_a_rebuild(sidecar: pathlib.Path) -> None:+ (sidecar / "transformers" / "__init__.py").write_bytes(b"")+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False+ assert "0 bytes, expected 32" in reason++[email protected]("value", ["1", "true", "YES", "on"])+def test_the_file_check_kill_switch_reaches_the_setup_predicate(+ sidecar: pathlib.Path, monkeypatch, value+) -> None:+ """The runtime honours UNSLOTH_SKIP_SIDECAR_FILE_CHECK so a false positive can be+ turned off without a release; a setup-side scan that ignored it would be the one+ path left that still wipes the sidecar. Package and version checks still apply."""+ (sidecar / "transformers" / "__init__.py").write_bytes(b"")+ monkeypatch.setenv(im.SIDECAR_FILE_CHECK_ENV, value)+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+ current, reason = im.sidecar_is_current(sidecar, ("transformers==5.5.0",) + PINS[1:])+ assert current is False and "5.5.0" in reason++[email protected]("value", ["0", "false", "", "maybe"])+def test_a_non_true_kill_switch_value_changes_nothing(+ sidecar: pathlib.Path, monkeypatch, value+) -> None:+ (sidecar / "transformers" / "__init__.py").write_bytes(b"")+ monkeypatch.setenv(im.SIDECAR_FILE_CHECK_ENV, value)+ assert im.sidecar_is_current(sidecar, PINS)[0] is False+++def test_a_pinned_package_without_a_record_forces_a_rebuild(sidecar: pathlib.Path) -> None:+ """pip and uv write RECORD last: a pinned dist-info without one is an interrupted+ install whose payload the size check cannot see. The optional package is not held+ to it, since its own top-up clears a recordless dist-info."""+ (sidecar / "hf_xet-1.4.2.dist-info" / "RECORD").unlink()+ (sidecar / "hf_xet" / "__init__.py").write_bytes(b"")+ ok, reason = im.sidecar_is_current(sidecar, PINS)+ assert ok is False+ assert "hf_xet: RECORD is missing" in reason+ (sidecar / "hf_xet-1.4.2.dist-info" / "RECORD").write_text(+ "hf_xet/__init__.py,sha256=deadbeef,0\n", encoding = "utf-8"+ )+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+ (sidecar / "tiktoken-0.9.0.dist-info" / "RECORD").unlink()+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+++def test_a_deleted_recorded_file_forces_a_rebuild(sidecar: pathlib.Path) -> None:+ (sidecar / "transformers" / "__init__.py").unlink()+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and "is missing" in reason+++def test_a_larger_file_is_a_collision_not_damage(sidecar: pathlib.Path) -> None:+ (sidecar / "transformers" / "__init__.py").write_bytes(b"x" * 64)+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+++def test_an_extension_built_for_another_interpreter_is_rejected(+ tmp_path: pathlib.Path, sidecar: pathlib.Path+) -> None:+ """A sidecar survives a Python upgrade intact and stops importing."""+ tag = "{}{}{}".format(+ sys.version_info.major,+ sys.version_info.minor,+ "t" if sysconfig.get_config_var("Py_GIL_DISABLED") else "",+ )+ foreign = "990" if not tag.startswith("99") else "980"+ _sidecar(+ sidecar,+ "regex",+ "2024.1.1",+ files = ("__init__.py", f"_regex.cpython-{foreign}-x86_64-linux-gnu.so"),+ )+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False+ assert f"targets cp{foreign}" in reason and f"interpreter is cp{tag}" in reason+++def test_a_tag_in_a_directory_name_says_nothing_about_the_binary(sidecar: pathlib.Path) -> None:+ """Wiping several hundred MB over a directory name is the false positive this+ check must not have."""+ _sidecar(sidecar, "regex", "2024.1.1", files = ("__init__.py", "regex.cp312.libs/libhelper.so"))+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+++def test_every_distribution_is_scanned_not_only_the_pinned_ones(sidecar: pathlib.Path) -> None:+ """The whole directory goes on sys.path, so a truncated regex/ shadows the+ base install and breaks `import transformers` just as a truncated+ transformers/ does."""+ _sidecar(sidecar, "regex", "2024.1.1")+ (sidecar / "regex" / "__init__.py").write_bytes(b"")+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and "regex" in reason+++def _module_dist(+ root: pathlib.Path,+ name: str,+ version: str,+ *,+ modules = ("six.py",),+) -> None:+ """A distribution that installs top-level MODULES, with no package directory."""+ rows = []+ for relative in modules:+ target = root / relative+ target.parent.mkdir(parents = True, exist_ok = True)+ target.write_bytes(b"x" * 32)+ rows.append(f"{relative},sha256=deadbeef,32")+ dist_info = root / f"{name.replace('-', '_')}-{version}.dist-info"+ dist_info.mkdir(parents = True, exist_ok = True)+ (dist_info / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding = "utf-8"+ )+ rows.append(f"{dist_info.name}/METADATA,,")+ (dist_info / "RECORD").write_text("\n".join(rows) + "\n", encoding = "utf-8")+++def test_a_module_only_distribution_is_current(sidecar: pathlib.Path) -> None:+ """six installs six.py and nothing else, so there is no directory named after it.++ Called stale, `sidecar_is_current` deletes and refetches a healthy several-hundred-MB+ tree on every single update -- for a pin that is satisfied.+ """+ _module_dist(sidecar, "six", "1.17.0")+ assert im.sidecar_is_current(sidecar, ("six==1.17.0",)) == (True, "")+ assert im.sidecar_is_current(sidecar, ("six",)) == (True, "")+++def test_a_module_only_distribution_still_answers_on_its_version(sidecar: pathlib.Path) -> None:+ """The payload fallback decides whether the files arrived, never which release."""+ _module_dist(sidecar, "six", "1.17.0")+ current, reason = im.sidecar_is_current(sidecar, ("six==1.16.0",))+ assert current is False+ assert "six==1.17.0" in reason and "1.16.0" in reason+++def test_a_module_only_distribution_whose_module_is_gone_is_not_current(+ sidecar: pathlib.Path,+) -> None:+ """The case the directory probe was there for, on the path that replaces it: an+ interrupted pip leaves the METADATA and takes the module with it."""+ _module_dist(sidecar, "six", "1.17.0")+ (sidecar / "six.py").unlink()+ current, reason = im.sidecar_is_current(sidecar, ("six==1.17.0",))+ assert current is False and "directory missing" in reason+++def test_an_import_name_that_matches_neither_spelling_is_current(sidecar: pathlib.Path) -> None:+ """pillow -> PIL. Neither `pillow` nor `pillow` with dashes swapped is on disk, and+ guessing the mapping is not something an installer can do."""+ _module_dist(sidecar, "pillow", "11.0.0", modules = ("PIL/__init__.py", "PIL/Image.py"))+ assert im.sidecar_is_current(sidecar, ("pillow==11.0.0",)) == (True, "")+++def test_a_console_script_alone_does_not_prove_the_payload_arrived(sidecar: pathlib.Path) -> None:+ """pip records ../../bin/hf and uv records bin/hf, and neither is inside the tree the+ training worker puts on sys.path. Believing them fails CLOSED on a real sidecar."""+ _module_dist(sidecar, "toolonly", "1.0", modules = ("bin/toolonly",))+ current, reason = im.sidecar_is_current(sidecar, ("toolonly==1.0",))+ assert current is False and "directory missing" in reason+++def test_a_distribution_with_no_record_at_all_is_not_current(sidecar: pathlib.Path) -> None:+ """No directory and no RECORD to fall back to leaves nothing that says the files+ landed, and the answer has to be the one that repairs rather than the one that+ ships a sidecar the worker cannot import."""+ dist_info = sidecar / "ghost-1.0.dist-info"+ dist_info.mkdir()+ (dist_info / "METADATA").write_text(+ "Metadata-Version: 2.1\nName: ghost\nVersion: 1.0\n", encoding = "utf-8"+ )+ current, reason = im.sidecar_is_current(sidecar, ("ghost==1.0",))+ assert current is False and "directory missing" in reason+++def test_a_pinned_sidecar_package_with_no_record_is_rebuilt(sidecar: pathlib.Path) -> None:+ """An absent RECORD used to say nothing about damage, since the answer costs a+ several-hundred-MB refetch; but pip and uv write RECORD last, so a pinned package+ without one is an interrupted install whose payload the size check cannot see."""+ (sidecar / "transformers-5.3.0.dist-info" / "RECORD").unlink()+ ok, reason = im.sidecar_is_current(sidecar, PINS)+ assert ok is False+ assert reason == "transformers: RECORD is missing"+++def test_the_scan_is_bounded(sidecar: pathlib.Path) -> None:+ """No installer wraps this in a timeout, so a stalled mount must not wedge setup."""+ assert im.sidecar_is_current(sidecar, PINS, budget_seconds = 0.0)[0] is True+++# -- the CLI shim both shells call ---------------------------------------------+++def _shim(*args: str):+ import subprocess+ return subprocess.run(+ [sys.executable, str(MODULE_PATH), *args],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ )+++def test_the_shim_reports_current(sidecar: pathlib.Path) -> None:+ result = _shim("sidecar", str(sidecar), *PINS)+ assert result.returncode == 0+ assert result.stdout.strip() == "sidecar: current"+++def test_the_shim_reports_the_reason_and_exits_1(sidecar: pathlib.Path) -> None:+ result = _shim("sidecar", str(sidecar), "transformers==5.5.0")+ assert result.returncode == 1+ assert result.stdout.startswith("sidecar: ")+ assert "5.5.0" in result.stdout+++def test_the_shim_marks_its_own_output(sidecar: pathlib.Path) -> None:+ """An install_manifest.py predating the shim has no __main__ block at all, so+ running it exits 0 with no output. Both shells require the marker line before+ believing exit 0, or that silence reads as "current" and no sidecar is ever+ rebuilt again."""+ assert im._SIDECAR_CLI_MARKER == "sidecar:"+ for args in ((), ("sidecar",), ("nonsense",), ("sidecar", str(sidecar))):+ result = _shim(*args)+ if result.returncode == 2:+ assert not result.stdout.strip().startswith(im._SIDECAR_CLI_MARKER)+++def test_the_shim_refuses_what_it_does_not_implement() -> None:+ for args in ((), ("nonsense",), ("sidecar",)):+ assert _shim(*args).returncode == 2+++def test_an_absent_tiktoken_is_optional_but_a_present_one_is_held_to_its_record(+ sidecar: pathlib.Path,+) -> None:+ """Absence is what is optional: a sidecar without tiktoken is current, and setup's+ top-up adds it. Present, tiktoken's RECORD is held to the disk like every other+ package's, since a file it names that is not there is a tokenizer that fails at+ import. A required package's RECORD is held to the disk too."""+ import shutil++ (sidecar / "tiktoken" / "__init__.py").unlink()+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and "tiktoken" in reason+ shutil.rmtree(sidecar / "tiktoken")+ shutil.rmtree(next(sidecar.glob("tiktoken-*.dist-info")))+ assert im.sidecar_is_current(sidecar, PINS) == (True, "")+ (sidecar / "hf_xet" / "__init__.py").unlink()+ current, reason = im.sidecar_is_current(sidecar, PINS)+ assert current is False and "hf_xet" in reason+++def test_write_manifest_never_raises_on_a_payload_json_cannot_encode(+ tmp_path: pathlib.Path,+) -> None:+ """`extra` is caller-composed and the docstring promises this never raises. It is the last+ act of a pass that has already installed everything, so a TypeError out of json.dumps+ would end the update with no manifest, which every reader takes for a half-built install.+ """+ assert (+ im.write_manifest(+ root = tmp_path,+ req_root = tmp_path,+ package_name = "pytest",+ extra = {"known_unmet": {"studio.txt"}},+ )+ is None+ )+ assert not (tmp_path / im.MANIFEST_NAME).exists()+++def test_an_unencodable_extra_leaves_an_existing_manifest_alone(tmp_path: pathlib.Path) -> None:+ """Refusing is the safe direction: the previous record is still true of this venv."""+ im.write_manifest(+ root = tmp_path, req_root = tmp_path, package_name = "pytest", extra = {"pip_check_ok": True}+ )+ before = _payload(tmp_path)+ assert (+ im.write_manifest(+ root = tmp_path,+ req_root = tmp_path,+ package_name = "pytest",+ extra = {"bad": object()},+ )+ is None+ )+ assert _payload(tmp_path) == before+++def test_both_writers_refuse_the_same_unencodable_payload(tmp_path: pathlib.Path) -> None:+ im.write_manifest(root = tmp_path, req_root = tmp_path, package_name = "pytest")+ assert im.update_manifest(root = tmp_path, mlx_health = {1, 2}) is False+ assert (+ im.write_manifest(+ root = tmp_path, req_root = tmp_path, package_name = "pytest", extra = {"x": {1, 2}}+ )+ is None+ )+++def test_the_pass_lock_reads_as_contended_only_while_a_peer_holds_it(+ tmp_path: pathlib.Path,+) -> None:+ """A second pass on one venv must see the first one, across processes."""+ child_code = "\n".join(+ [+ "import sys, time, pathlib",+ f"sys.path.insert(0, {str(pathlib.Path(im.__file__).resolve().parent)!r})",+ "import install_manifest as im",+ f"with im.pass_lock(pathlib.Path({str(tmp_path)!r})) as owned:",+ " assert owned",+ f" pathlib.Path({str(tmp_path / 'held')!r}).write_text('1', encoding='utf-8')",+ " time.sleep(2.0)",+ ]+ )+ child = subprocess.Popen([sys.executable, "-c", child_code])+ try:+ held = tmp_path / "held"+ deadline = time.time() + 20+ while not held.exists() and time.time() < deadline:+ time.sleep(0.02)+ assert held.exists(), "the child never took the pass lock"+ with im.pass_lock(tmp_path) as uncontended:+ assert uncontended is False+ finally:+ child.wait(timeout = 30)+ # And the moment it lets go, the next pass is free to trust its evidence again.+ with im.pass_lock(tmp_path) as uncontended:+ assert uncontended is True+++def test_the_pass_lock_never_waits_for_the_peer(tmp_path: pathlib.Path) -> None:+ """It is tested, not waited on: a pass runs for minutes, so a waiter would be worse."""+ with im.pass_lock(tmp_path):+ started = time.monotonic()+ code = "\n".join(+ [+ "import sys, pathlib",+ f"sys.path.insert(0, {str(pathlib.Path(im.__file__).resolve().parent)!r})",+ "import install_manifest as im",+ f"with im.pass_lock(pathlib.Path({str(tmp_path)!r})) as owned:",+ " print(owned)",+ ]+ )+ peer = subprocess.run(+ [sys.executable, "-c", code], capture_output = True, text = True, timeout = 60+ )+ assert peer.stdout.strip() == "False", peer.stderr+ assert time.monotonic() - started < 5.0+++def test_a_root_that_cannot_hold_a_pass_lock_reads_as_uncontended(tmp_path: pathlib.Path) -> None:+ """Best effort, as the manifest lock: an unlockable filesystem keeps the fast path."""+ with im.pass_lock(tmp_path / "does" / "not" / "exist") as uncontended:+ assert uncontended is True+++def test_a_symlink_on_the_pass_lock_name_is_not_followed(tmp_path: pathlib.Path) -> None:+ target = tmp_path / "elsewhere"+ target.write_text("untouched", encoding = "utf-8")+ (tmp_path / im.PASS_LOCK_NAME).symlink_to(target)+ with im.pass_lock(tmp_path) as uncontended:+ assert uncontended is True+ assert target.read_text(encoding = "utf-8") == "untouched"diff --git a/tests/studio/install/test_installed_family_hermeticity.py b/tests/studio/install/test_installed_family_hermeticity.pyindex de454ea3b16..a5c8f198e7a 100644--- a/tests/studio/install/test_installed_family_hermeticity.py+++ b/tests/studio/install/test_installed_family_hermeticity.py@@ -5,9 +5,10 @@the machine running pytest, so it passes on a bare laptop and fails on any host thatalready has AMD per-arch torch. Three cases in TestEnsureRocmTorch did.-_installed_rocm_wheel_family and _torch_requires_rocm_sdk go to importlib.metadata for the-RUNNING interpreter, which is the venv being repaired at install time and the test runner-here. This file fakes the metadata layer, never the functions, so their parsing still runs.+_installed_rocm_wheel_family, _torch_requires_rocm_sdk and _installed_bnb_provenance go to+importlib.metadata for the RUNNING interpreter, which is the venv being repaired at install+time and the test runner here. This file fakes the metadata layer, never the functions, so+their parsing still runs."""from __future__ import annotations@@ -104,14 +105,19 @@ def _route(env: "dict | None" = None,family: "str | None" = None,torch_owns_rocm: bool = False,+ bnb_provenance: "str | None" = None,) -> str:"""Every pip argument _ensure_rocm_torch() produced, as one string. ``family`` /- ``torch_owns_rocm`` pin the installed-wheel pair; the defaults are "no ROCm installed"."""+ ``torch_owns_rocm`` / ``bnb_provenance`` pin what is installed; the defaults are+ "no ROCm and no keepable bitsandbytes installed"."""pip, pip_try = MagicMock(), MagicMock(return_value = True)probe = MagicMock(returncode = 0, stdout = _MARK + torch_line + "\n")buf = io.StringIO()stack_mod._invalidate_torch_runtime_probe()+ # Pass state: the second _ensure_rocm_torch of a pass answers from the first; each call here is+ # its own pass.+ stack_mod._BNB_ROCM_PASS_PROVENANCE = Nonewith (patch.dict(os.environ, env or {}, clear = False),patch.object(stack_mod, "IS_WINDOWS", False),@@ -128,6 +134,9 @@ def _route(patch.object(stack_mod, "_kfd_gfx_targets", return_value = []),patch.object(stack_mod, "_installed_rocm_wheel_family", return_value = family),patch.object(stack_mod, "_torch_requires_rocm_sdk", return_value = torch_owns_rocm),+ # The third door into the running interpreter, pinned like the other two, or the verdict+ # depends on whether the pytest machine has bitsandbytes.+ patch.object(stack_mod, "_installed_bnb_provenance", return_value = bnb_provenance),patch.object(stack_mod.os.path, "isdir", return_value = True),patch.object(stack_mod.subprocess, "run", return_value = probe),):@@ -161,8 +170,8 @@ HOSTS = {@pytest.mark.parametrize("host", sorted(HOSTS))def test_pinning_the_pair_makes_this_machine_irrelevant(host):- """Pinning the pair is SUFFICIENT isolation. Not "routing ignores what is installed" --- at install time it must not; the claim is that these two functions are the only door."""+ """Pinning them is SUFFICIENT isolation. Not "routing ignores what is installed" --+ at install time it must not; the claim is that these functions are the only door."""gfx, torch_line = HOSTS[host]with ambient("bare"):expected = _route(gfx, torch_line)@@ -171,9 +180,9 @@ def test_pinning_the_pair_makes_this_machine_irrelevant(host):got = _route(gfx, torch_line)assert got == expected, (f"{host} routes differently when the interpreter running the tests is in the "- f"{state!r} state, even though the installed-wheel pair is pinned. Something in "- f"_ensure_rocm_torch now reads this venv by a path those two functions do not "- f"cover, so the suite's verdict depends on who runs it.\n"+ f"{state!r} state, even though what is installed is pinned. Something in "+ f"_ensure_rocm_torch now reads this venv by a path those three functions do "+ f"not cover, so the suite's verdict depends on who runs it.\n"f" bare: {expected}\n {state}: {got}")diff --git a/tests/studio/install/test_mlx_install.py b/tests/studio/install/test_mlx_install.pyindex f4f716f62cb..877bbaebe37 100644--- a/tests/studio/install/test_mlx_install.py+++ b/tests/studio/install/test_mlx_install.py@@ -118,9 +118,21 @@ def test_mlx_install_respects_platform_mode_and_pins(enabled = platform == "macos_arm" and not no_torchassert len(calls) == int(enabled)if platform.startswith("macos"):- assert stack._TOTAL == (12 if skip_base and not shared_base else 13) + int(enabled)+ # An update without torch announces the no-torch runtime deps on their own slot.+ assert stack._TOTAL == (+ (12 if skip_base and not shared_base else 13)+ + int(enabled)+ + int(no_torch and not skip_base)+ )if enabled:- requirements = [Requirement(arg) for arg in calls[0].args[1:] if not arg.startswith("-")]+ # --upgrade-package takes a bare NAME, not a pin: skip its argument.+ args = list(calls[0].args[1:])+ pins = [+ arg+ for index, arg in enumerate(args)+ if not arg.startswith("-") and (index == 0 or args[index - 1] != "--upgrade-package")+ ]+ requirements = [Requirement(arg) for arg in pins]actual = {req.name: str(req.specifier) for req in requirements}expected = _repair_specs()expected["mlx-metal"] = expected["mlx"]@@ -171,10 +183,32 @@ def test_mlx_command_preserves_pins_and_interpreter_on_fallback(monkeypatch, retassert commands[0][:5] == ["uv", "pip", "install", "--python", sys.executable]if len(commands) > 1:assert commands[1][:4] == [sys.executable, "-m", "pip", "install"]+ args = list(call.args[1:])+ upgraded = {+ arg for index, arg in enumerate(args) if index and args[index - 1] == "--upgrade-package"+ }+ pins = {+ arg for index, arg in enumerate(args) if not arg.startswith("-") and arg not in upgraded+ }+ assert upgraded == {"mlx", "mlx-metal", "mlx-lm", "mlx-vlm"}for command in commands:- assert {arg for arg in call.args[1:] if not arg.startswith("-")} <= set(command)- assert "--upgrade" in command+ assert pins <= set(command)assert "-c" in command+ # The upgrade INTENT must survive both spellings: a dropped pip translation made the fallback a+ # silent no-op, and a bare uv --upgrade refetches ~60 MB per update.+ assert "--upgrade" not in commands[0]+ for name in upgraded:+ assert commands[0][commands[0].index("--upgrade-package") :].count(name) == 1+ if len(commands) > 1:+ assert "--upgrade" in commands[1]+ assert "--upgrade-package" not in commands[1]+ # ...and no project twice: pip refuses "mlx==0.32.1 mlx" with "Double requirement given".+ projects = [+ arg.split(";")[0].split("[")[0].split("=")[0].split("<")[0].split(">")[0].strip()+ for arg in commands[1]+ if arg and not arg.startswith("-") and arg != sys.executable+ ]+ assert len(projects) == len(set(projects)), projects@pytest.mark.parametrize(diff --git a/tests/studio/install/test_rocm_companion_probe.py b/tests/studio/install/test_rocm_companion_probe.pynew file mode 100644index 00000000000..bd44a5a5603--- /dev/null+++ b/tests/studio/install/test_rocm_companion_probe.py@@ -0,0 +1,146 @@+"""The setup.ps1 Windows ROCm companion probe, extracted and executed on real trees.++The probe decides whether torchvision/torchaudio beside a ROCm torch are trustworthy+enough to skip the trio reinstall, so it is run here rather than regex-matched.+"""++import csv+import re+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest++SETUP_PS1 = Path(__file__).resolve().parents[3] / "studio" / "setup.ps1"+++def _probe_source(names = "('torchvision', 'torchaudio')"):+ """The -Code string of the companion probe, as Python."""+ for line in SETUP_PS1.read_text(encoding = "utf-8").splitlines():+ if line.lstrip().startswith("$_companionProbe = Invoke-BoundedPythonProbe"):+ code = line.split("-Code ", 1)[1].strip()+ assert code.startswith('"') and code.endswith('"'), code[:40]+ return code[1:-1].replace("`n", "\n").replace("$($_companionNames)", names)+ raise AssertionError("companion probe not found in setup.ps1")+++def _install(+ root,+ name,+ version,+ *,+ payload = True,+ record = True,+ resize = False,+):+ """A dist-info and package good enough for importlib.metadata and find_spec."""+ pkg = root / name+ if payload:+ pkg.mkdir()+ (pkg / "__init__.py").write_text("x = 1\n", encoding = "utf-8")+ dist = root / f"{name}-{version}.dist-info"+ dist.mkdir()+ (dist / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding = "utf-8"+ )+ if record:+ rows = []+ if payload:+ size = (pkg / "__init__.py").stat().st_size + (1 if resize else 0)+ rows.append([f"{name}/__init__.py", "sha256=x", str(size)])+ with (dist / "RECORD").open("w", newline = "", encoding = "utf-8") as handle:+ csv.writer(handle).writerows(rows)+++def _run(root, names = "('torchvision', 'torchaudio')"):+ # This interpreter has a real torch stack; only the fabricated one may answer.+ prelude = (+ "import sys\n"+ "sys.path[:] = [p for p in sys.path if 'packages' not in p]\n"+ f"sys.path.insert(0, {str(root)!r})\n"+ )+ proc = subprocess.run(+ [sys.executable, "-I", "-c", prelude + _probe_source(names)],+ cwd = str(root),+ capture_output = True,+ text = True,+ timeout = 120,+ )+ assert proc.returncode == 0, proc.stderr+ return proc.stdout.strip()+++def venv(tmp_path):+ root = tmp_path / "site-packages"+ root.mkdir()+ return root+++class TestCompanionProbe:+ def test_matching_rocm_trio_keeps_the_fast_path(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2")+ _install(venv, "torchaudio", "2.8.0+rocm6.4.2")+ assert _run(venv) == ""++ def test_pypi_companion_forces_the_trio(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0")+ _install(venv, "torchaudio", "2.8.0+rocm6.4.2")+ assert _run(venv) == "torchvision==0.23.0"++ def test_companion_from_another_rocm_release_forces_the_trio(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.2.4")+ _install(venv, "torchaudio", "2.8.0+rocm6.4.2")+ out = _run(venv)+ assert out.startswith("torchvision==0.23.0+rocm6.2.4 (rocm6.2.4 beside torch rocm6.4.2)")++ def test_git_tagged_community_wheels_keep_the_fast_path(self, venv):+ """No numeric ROCm version on either side is not evidence of a mismatch."""+ _install(venv, "torch", "2.7.0a0+rocm.gitabc1234")+ _install(venv, "torchvision", "0.22.0a0+rocm.gitdef5678")+ _install(venv, "torchaudio", "2.7.0a0+rocm.git99aabb0")+ assert _run(venv) == ""++ def test_missing_payload_forces_the_trio(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2", payload = False)+ _install(venv, "torchaudio", "2.8.0+rocm6.4.2")+ assert _run(venv) == "torchvision==0.23.0+rocm6.4.2 (payload missing)"++ def test_resized_record_row_forces_the_trio(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2", resize = True)+ _install(venv, "torchaudio", "2.8.0+rocm6.4.2")+ assert _run(venv) == "torchvision==0.23.0+rocm6.4.2 (payload damaged)"++ def test_absent_companion_is_not_a_mismatch(self, venv):+ """The pinned install brings it in; nothing to repair."""+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2")+ assert _run(venv) == ""++ def test_windows_arm64_never_asks_about_torchaudio(self, venv):+ _install(venv, "torch", "2.8.0+rocm6.4.2")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2")+ _install(venv, "torchaudio", "2.8.0")+ assert _run(venv, "('torchvision',)") == ""++ def test_a_torch_without_a_rocm_version_does_not_force_on_release(self, venv):+ """Only the +cpu/+cu/untagged rule may fire when torch names no release."""+ _install(venv, "torch", "2.8.0+rocm")+ _install(venv, "torchvision", "0.23.0+rocm6.4.2")+ assert _run(venv) == ""+++class TestProbeSource:+ def test_the_extracted_source_compiles(self):+ compile(_probe_source(), "companion_probe", "exec")++ def test_the_release_comparison_is_numeric_only(self):+ source = _probe_source()+ assert re.search(r"rocm\(\\d\+\(\?:\\\.\\d\+\)\*\)", source), textwrap.shorten(source, 200)diff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex 1787611ca3a..9b48abc90e0 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -5081,6 +5081,7 @@ class TestProgressStepCountMatchesTotal:is_macos,is_mac_arm,skip_base = True,+ no_torch = False,):unstructured_plugin = tmp_path / "unstructured"github_plugin = tmp_path / "github"@@ -5096,7 +5097,7 @@ class TestProgressStepCountMatchesTotal:patch.object(stack_mod, "IS_WINDOWS", is_windows),patch.object(stack_mod, "IS_MACOS", is_macos),patch.object(stack_mod, "IS_MAC_ARM", is_mac_arm),- patch.object(stack_mod, "NO_TORCH", False),+ patch.object(stack_mod, "NO_TORCH", no_torch),patch.object(stack_mod, "_rocm_windows_torch_installed", False),patch.object(stack_mod, "_bootstrap_uv", return_value = False),patch.object(stack_mod, "_installed_torch_is_windows_rocm", return_value = False),@@ -5141,6 +5142,27 @@ class TestProgressStepCountMatchesTotal:)assert step == total, f"progress {step} != total {total}"+ @pytest.mark.parametrize("skip_base", [True, False])+ @pytest.mark.parametrize(+ "is_windows, is_macos, is_mac_arm",+ [(False, False, False), (True, False, False), (False, True, True)],+ ids = ["linux", "windows", "macos_arm"],+ )+ def test_progress_reaches_total_without_torch(+ self, tmp_path, is_windows, is_macos, is_mac_arm, skip_base+ ):+ """--no-torch, on both core paths. The no-torch runtime deps step announces its own+ progress slot, which the denominator has to count: an update printed 15/14 without it."""+ step, total = self._run_stack(+ tmp_path,+ is_windows = is_windows,+ is_macos = is_macos,+ is_mac_arm = is_mac_arm,+ skip_base = skip_base,+ no_torch = True,+ )+ assert step == total, f"progress {step} != total {total}"+# TEST: worker.py -- Windows ROCm patches (source-level checks)@@ -7257,3 +7279,192 @@ class TestRocmMiscomputingArchDemotion:if __name__ == "__main__":pytest.main([__file__, "-v"])+++# ─────────────────────────────────────────────────────────────────────────────+# TEST: install_python_stack.py -- the AMD bitsandbytes reinstall is evidence-gated+++class TestBnbRocmProvenance:+ """A no-op `studio update` on an AMD host must not refetch the bnb wheel.++ Measured on gfx1151: two 43 MB downloads from release-assets.githubusercontent.com+ per Linux update (39 MB twice on Windows), because --force-reinstall from a release+ URL fetches the wheel before it can decide it already has it, and _ensure_rocm_torch+ is called twice by one dependency pass.+ """++ URL = "https://example.invalid/bitsandbytes-1.33.7.preview-py3-none-manylinux.whl"+ # What the release URL served when the last run looked: an ETag and a size.+ ASSET = '"3f2a"|43000000'++ @pytest.fixture(autouse = True)+ def _healthy_payload(self, monkeypatch):+ monkeypatch.setattr(stack_mod.install_manifest, "damaged_payload_files", lambda *a, **k: [])+ monkeypatch.setattr(stack_mod, "_bnb_asset_identity", lambda _url: self.ASSET)+ monkeypatch.setattr(stack_mod, "_BNB_ROCM_PASS_ASSET", None)++ def _evidence(self, monkeypatch, **extra):+ monkeypatch.setattr(+ stack_mod,+ "_PASS_EVIDENCE",+ {"bnb_rocm": f"url:{self.URL}", "bnb_rocm_asset": self.ASSET, **extra},+ )++ def test_a_republished_wheel_at_the_same_url_is_fetched_again(self, monkeypatch):+ """continuous-release_main replaces the bytes under a fixed asset path, so the URL+ pip recorded says where the wheel came from, not which one it is."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ monkeypatch.setattr(stack_mod, "_bnb_asset_identity", lambda _url: '"9c1d"|43100000')+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_an_unreachable_release_page_keeps_the_recorded_build(self, monkeypatch):+ """Offline, the reinstall could not fetch anything either; the build on disk is one+ the last run recorded landing deliberately."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ monkeypatch.setattr(stack_mod, "_bnb_asset_identity", lambda _url: None)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is True+ assert stack_mod._BNB_ROCM_PASS_ASSET == self.ASSET++ def test_a_run_that_recorded_no_asset_identity_reinstalls_once(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", {"bnb_rocm": f"url:{self.URL}"})+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_the_kept_asset_identity_is_what_the_pass_records(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is True+ assert stack_mod._BNB_ROCM_PASS_ASSET == self.ASSET+ # A second HEAD would only repeat the first.+ monkeypatch.setattr(+ stack_mod,+ "_bnb_asset_identity",+ lambda _url: (_ for _ in ()).throw(AssertionError("second HEAD")),+ )+ stack_mod._record_bnb_rocm_provenance()+ assert stack_mod._BNB_ROCM_PASS_ASSET == self.ASSET++ def _installed(self, monkeypatch, version, direct_url):+ monkeypatch.setattr(stack_mod, "_installed_distribution_version", lambda _n: version)+ monkeypatch.setattr(stack_mod, "_installed_direct_url", lambda _n: direct_url)++ def test_a_matching_direct_url_recorded_last_run_is_kept(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is True++ def test_a_forced_pass_reinstalls(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", None)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_the_escape_hatch_reinstalls(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ monkeypatch.setenv(stack_mod._FULL_DEPS_ENV, "1")+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_a_damaged_payload_reinstalls(self, monkeypatch):+ """Metadata survives a quarantined payload, and the reinstall this would skip is+ the only thing that puts the shared objects back."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(+ stack_mod.install_manifest,+ "damaged_payload_files",+ lambda *a, **k: ["bitsandbytes/libbitsandbytes_rocm.so"],+ )+ self._evidence(monkeypatch)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_an_absent_bitsandbytes_reinstalls(self, monkeypatch):+ self._installed(monkeypatch, None, None)+ self._evidence(monkeypatch)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_a_wheel_url_that_moved_reinstalls(self, monkeypatch):+ """A new installer release naming a newer wheel must fetch it exactly once."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ self._evidence(monkeypatch)+ assert stack_mod._bnb_rocm_install_is_current(self.URL + ".new") is False++ def test_a_wheel_nobody_recorded_reinstalls(self, monkeypatch):+ """The PyPI wheel another step pulled in reads identically on disk to the one+ this path installs on purpose, so only the manifest can tell them apart."""+ self._installed(monkeypatch, "0.50.0", None)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", {"bnb_rocm": None})+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_a_recorded_pypi_fallback_is_kept(self, monkeypatch):+ """The fallback this path takes when the release page is unreachable. Recorded+ deliberately last run, so reinstalling it every update buys nothing."""+ self._installed(monkeypatch, "0.50.0", None)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", {"bnb_rocm": "version:0.50.0"})+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is True++ def test_a_filename_version_match_stands_in_for_a_missing_direct_url(self, monkeypatch):+ """1.33.7.preview in the filename is 1.33.7rc0 in the metadata."""+ assert stack_mod._bnb_wheel_version(self.URL) == "1.33.7.preview"+ assert stack_mod._versions_are_same_release("1.33.7rc0", "1.33.7.preview") is True+ assert stack_mod._bnb_provenance_matches_request("version:1.33.7rc0", self.URL) is True++ def test_the_second_call_of_one_pass_does_not_repeat_the_install(self, monkeypatch):+ """_ensure_rocm_torch runs twice per dependency pass. The first call settles it."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", None)+ monkeypatch.setattr(stack_mod, "_BNB_ROCM_PASS_PROVENANCE", None)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False+ stack_mod._record_bnb_rocm_provenance()+ assert stack_mod._BNB_ROCM_PASS_PROVENANCE == f"url:{self.URL}"+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is True++ def test_a_clobber_between_the_two_calls_is_still_repaired(self, monkeypatch):+ """The with-deps steps run BETWEEN the two calls and can re-resolve bnb to a+ generic wheel, which is the whole reason the torch repair runs twice."""+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(stack_mod, "_PASS_EVIDENCE", None)+ monkeypatch.setattr(stack_mod, "_BNB_ROCM_PASS_PROVENANCE", None)+ stack_mod._record_bnb_rocm_provenance()+ self._installed(monkeypatch, "0.50.0", None)+ assert stack_mod._bnb_rocm_install_is_current(self.URL) is False++ def test_a_kept_wheel_is_still_recorded_for_the_next_update(self, monkeypatch):+ """Without this the manifest this pass writes forgets what is installed and the+ next update fetches the wheel again."""+ import ast++ source = _STACK_PATH.read_text(encoding = "utf-8")+ calls = [+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_record_bnb_rocm_provenance"+ ]+ # Two per platform path: the install arm and the keep arm.+ assert len(calls) == 4+ assert '"bnb_rocm": _BNB_ROCM_PASS_PROVENANCE,' in source++ def test_a_current_wheel_makes_the_linux_path_install_nothing(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setattr(stack_mod, "_bnb_rocm_prerelease_url", lambda: self.URL)+ self._evidence(monkeypatch)+ pip, pip_try = run_ensure_rocm_torch(+ probe = json.dumps({"version": "2.10.0+rocm7.1", "hip": "7.1", "cuda": None}),+ _has_rocm_gpu = True,+ _detect_rocm_version = (7, 1),+ )+ assert pip.call_count == 0+ assert pip_try.call_count == 0++ def test_a_current_wheel_makes_the_windows_path_install_nothing(self, monkeypatch):+ self._installed(monkeypatch, "1.33.7rc0", self.URL)+ monkeypatch.setitem(stack_mod._BNB_ROCM_PRERELEASE_URLS, "win_amd64", self.URL)+ self._evidence(monkeypatch)+ monkeypatch.setattr(stack_mod, "_persist_bnb_rocm_version", lambda _v: True)+ monkeypatch.setattr(stack_mod, "_detect_bnb_rocm_dll_ver", lambda: "72")+ with patch.object(stack_mod, "pip_install_try", return_value = True) as mock_pip:+ assert stack_mod._install_bnb_windows_rocm() is True+ assert mock_pip.call_count == 0diff --git a/tests/studio/install/test_setup_fast_path_guard.py b/tests/studio/install/test_setup_fast_path_guard.pyindex 377cf12661e..813027674e4 100644--- a/tests/studio/install/test_setup_fast_path_guard.py+++ b/tests/studio/install/test_setup_fast_path_guard.py@@ -138,3 +138,179 @@ def test_the_installer_reports_duplicate_metadata_on_every_platform(script: pathassert ("duplicate metadata found" in text), f"{script.name} detects the conflict but never says so"+++def test_the_sidecar_predicate_asks_the_shim_on_colab_too():+ """No venv interpreter on Colab; the shim is stdlib-only and the installer's own+ `python` asks it. The version grep alone read a sidecar interrupted after+ transformers landed as current on every later run."""+ text = SETUP_SH.read_text(encoding = "utf-8")+ start = text.index("_sidecar_current() {")+ body = text[start : text.index("\n}\n", start)]+ assert "command -v python" in body+ assert '"$_sc_python" "$SCRIPT_DIR/install_manifest.py" sidecar' in body+ # Exactly one grep may precede the interpreter search: the guard for a tree that ships no+ # shim at all. Every other fall back to the grep is a last resort behind `command -v python`,+ # or Colab (venv-less but with an ambient python) would never reach the shim.+ shim_guard = body.index('[ ! -f "$SCRIPT_DIR/install_manifest.py" ]')+ assert shim_guard < body.index("command -v python")+ assert body.index("command -v python") < body.rindex("_target_has_pkg_version")+++def test_the_ps1_sidecar_predicate_runs_the_shim_as_a_bounded_process():+ """Two reasons, one mechanism. The shim answers "stale" with exit 1, which a native+ command turns into a terminating error under $PSNativeCommandUseErrorActionPreference,+ and the shim's scan budget cannot interrupt a stalled read on a wedged mount. A bounded+ process has neither problem; a timeout reads as stale."""+ text = SETUP_PS1.read_text(encoding = "utf-8")+ start = text.index("function Test-SidecarCurrent {")+ body = text[start : text.index("\nfunction ", start + 1)]+ assert "& python $shim" not in body+ assert "Invoke-BoundedPythonProbe -PythonExe $pythonExe -Code $code -TimeoutSec 60" in body+ # The argv travels base64-encoded: a path with quotes or backslashes cannot break -c.+ assert "[Convert]::ToBase64String" in body and "base64.b64decode" in body+ assert "runpy.run_path(sys.argv[0], run_name='__main__')" in body+ assert body.index("$probe.TimedOut") < body.index('$out = "sidecar: audit did not answer')+ # The shell mirror: the shim call is bounded where a timeout exists and a timeout is stale.+ sh = SETUP_SH.read_text(encoding = "utf-8")+ call = sh.index('install_manifest.py" sidecar "$_sc_dir"')+ window = sh[call - 400 : call + 900]+ assert "timeout -k 5 60" in window+ assert '[ "$_sc_rc" -eq 124 ] || [ "$_sc_rc" -eq 137 ]' in window+ assert "sidecar: audit did not answer" in window+++def test_the_ps1_sidecar_installs_are_isolated_from_uv_override():+ """setup.sh routes every sidecar install through fast_install_sidecar, which unsets+ UV_OVERRIDE; an override naming huggingface_hub or hf_xet would otherwise install+ another version than the exact pin and the audit would rebuild the sidecar to the+ same wrong answer on every run. The PowerShell helper mirrors it."""+ text = SETUP_PS1.read_text(encoding = "utf-8")+ start = text.index("function Fast-Install-Sidecar {")+ body = text[start : text.index("\nfunction ", start + 1)]+ assert "Remove-Item Env:UV_OVERRIDE" in body and "Fast-Install @Args_" in body+ assert "finally" in body and "$env:UV_OVERRIDE = $savedOverride" in body+ for name in ("function Repair-SidecarTiktoken {", "function Install-T5Sidecar {"):+ start = text.index(name)+ body = text[start : text.index("\nfunction ", start + 1)]+ assert "Fast-Install --target" not in body, name+ assert "Fast-Install-Sidecar --target" in body, name+++def test_the_tiktoken_top_up_checks_the_payload_not_the_dist_info_alone():+ """An interrupted install leaves tiktoken-*.dist-info with no package beside it; the+ sidecar predicate accepts that sidecar (tiktoken is optional), so the top-up is the+ only repair left, and a dist-info-only check would skip it forever."""+ sh = SETUP_SH.read_text(encoding = "utf-8")+ start = sh.index("_sidecar_top_up_tiktoken() {")+ assert '"$_stt_dir/tiktoken/__init__.py"' in sh[start : sh.index("\n}\n", start)]+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Repair-SidecarTiktoken {")+ body = ps1[start : ps1.index("\nfunction ", start + 1)]+ assert 'Join-Path $payload "__init__.py"' in body+ # ...and the repair replaces what is there (--target without --upgrade keeps damaged files).+ assert "--no-deps --upgrade tiktoken" in body+ sh_body = sh[sh.index("_sidecar_top_up_tiktoken() {") :]+ assert '--no-deps --upgrade "tiktoken"' in sh_body[: sh_body.index("\n}\n")]+++def test_the_ps1_sidecar_predicate_reads_no_version_gated_variable():+ """$PSNativeCommandUseErrorActionPreference exists from PowerShell 7.3 and reading an+ absent variable under Set-StrictMode is a terminating error; the predicate no longer+ touches it at all, and must not grow a version check in its place."""+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Test-SidecarCurrent {")+ body = ps1[start : ps1.index("\nfunction ", start + 1)]+ assert "$PSNativeCommandUseErrorActionPreference =" not in body+ assert "PSVersion.Major -ge 7" not in body+++def test_the_installer_pins_come_from_the_audited_pin_list():+ """The list the audit demands and the list the install performs must be one variable: a+ pin `sidecar_is_current` requires but `_install_sidecar` never installs reads stale every+ run, silently wiping and refetching all three tiers on every update.+ """+ sh = SETUP_SH.read_text(encoding = "utf-8")+ start = sh.index("_install_sidecar() {")+ body = sh[start : sh.index("\n}\n", start)]+ assert "$_SIDECAR_COMMON_PINS" in body, (+ "_install_sidecar hardcodes the common pins instead of reading "+ "$_SIDECAR_COMMON_PINS; the audit and the install can now drift apart."+ )+ assert "huggingface_hub==" not in body, "a second copy of the pins crept back in"++ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Install-T5Sidecar {")+ body = (+ ps1[start : ps1.index("\nfunction ", start + 1)]+ if "\nfunction " in ps1[start + 1 :]+ else ps1[start:]+ )+ assert (+ "$SidecarCommonPins" in body+ ), "Install-T5Sidecar hardcodes the common pins instead of reading $SidecarCommonPins."+ assert "huggingface_hub==" not in body, "a second copy of the pins crept back in"+++def test_a_tree_without_the_shim_falls_back_to_the_version_grep():+ """Both shells must answer from `_target_has_pkg_version` when install_manifest.py is+ absent. Treating the missing file as a failed audit reports every tier stale and rebuilds+ all three, and the two shells would disagree about the same tree."""+ sh = SETUP_SH.read_text(encoding = "utf-8")+ start = sh.index("_sidecar_current() {")+ body = sh[start : sh.index("\n}\n", start)]+ assert '[ ! -f "$SCRIPT_DIR/install_manifest.py" ]' in body, (+ "_sidecar_current no longer checks that the shim exists before running it; a tree "+ "without install_manifest.py now rebuilds all three sidecars."+ )++ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Test-SidecarCurrent {")+ body = ps1[start : ps1.index("\nfunction ", start + 1)]+ assert "Test-Path -LiteralPath $shim -PathType Leaf" in body+++def test_the_sidecar_cleanups_cannot_abort_the_installer():+ """setup.sh runs under `set -euo pipefail` and these functions are called bare. Every `rm`+ here is best effort by construction, since the paths that reach them are already+ undeletable, and an unguarded one turns a skipped rebuild into a silent exit 1.+ """+ sh = SETUP_SH.read_text(encoding = "utf-8")+ for fn in ("_sidecar_retire_after_failed_tiktoken() {", "_sidecar_top_up_tiktoken() {"):+ start = sh.index(fn)+ body = sh[start : sh.index("\n}\n", start)]+ for line in body.splitlines():+ stripped = line.strip()+ if not stripped.startswith("rm -rf") and "&& rm -rf" not in stripped:+ continue+ assert "|| true" in stripped, (+ f"unguarded `rm` in {fn.rstrip('( {')}: {stripped!r}. Under `set -e` this "+ "aborts the whole installer when the entry cannot be removed."+ )+++def test_the_ps1_marker_reason_is_parsed_without_substring():+ """`-like 'sidecar:*'` also matches the bare marker, and Substring past the end throws.++ The sh side uses `${_sc_out#sidecar: }`, which degrades to the empty string; the two must+ not differ on a malformed answer."""+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Test-SidecarCurrent {")+ body = ps1[start : ps1.index("\nfunction ", start + 1)]+ assert ".Substring(" not in body, (+ "Test-SidecarCurrent parses the audit's reason with Substring again; a bare "+ "'sidecar:' answer makes that throw."+ )+ assert "-replace '^sidecar:" in body+++def test_the_ps1_predicate_prefers_the_venv_interpreter():+ """As setup.sh does. A PATH `python` on Windows can be the Store App Execution Alias+ stub, whose failure reads as "audit died" and rebuilds all three tiers every run."""+ ps1 = SETUP_PS1.read_text(encoding = "utf-8")+ start = ps1.index("function Test-SidecarCurrent {")+ body = ps1[start : ps1.index("\nfunction ", start + 1)]+ assert "$VenvPyExe" in body, (+ "Test-SidecarCurrent goes straight to a PATH python; setup.sh prefers "+ "$VENV_DIR/bin/python and the two shells must pick the same interpreter."+ )diff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 438f1ca1b6a..f1b1e8d3374 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -329,13 +329,14 @@ def _base_total(**flags) -> int:class TestStepTotals:def test_windows_totals_include_torchcodec(self):assert _base_total(IS_WINDOWS = True) == 15- assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 13+ # 14, not 13: an update installs the no-torch runtime deps on their own slot.+ assert _base_total(IS_WINDOWS = True, NO_TORCH = True) == 14@pytest.mark.parametrize("flags,total",[({}, 17), # Linux, torch- ({"NO_TORCH": True}, 14), # Linux, GGUF-only+ ({"NO_TORCH": True}, 15), # Linux, GGUF-only (incl. the no-torch runtime step)({"IS_MACOS": True, "IS_MAC_ARM": True}, 14), # Apple Silicon({"IS_MACOS": True}, 13), # Intel Mac],@@ -415,7 +416,7 @@ class TestManifestRecordsTheFlavor:read = _line_of(_STACK_SRC, "_RECORDED_TORCH_TAG = install_manifest.recorded_torch_flavor()")- drop = _line_of(_STACK_SRC, "if not install_manifest.remove_manifest():")+ drop = _line_of(_STACK_SRC, "if install_manifest.remove_manifest():")assert read < dropassert ("def install_python_stack"@@ -497,9 +498,8 @@ class TestABrokenTorchForcesItsOwnReinstall:f"other order leaves the reinstall announced but unreachable")- @pytest.mark.parametrize("force_var", ["$xpuForce", "$cpuForce"])+ @pytest.mark.parametrize("force_var", ["$rocmForce", "$xpuForce", "$cpuForce"])def test_every_conditional_force_gate_reads_the_flag(self, force_var):- # The ROCm arm forces unconditionally, so only these two have a gate to miss.assignments = [linefor line in _SETUP_SRC.splitlines()@@ -516,13 +516,6 @@ class TestABrokenTorchForcesItsOwnReinstall:f"resolver keeps it: its on-disk tag is unchanged and the range is satisfied")- def test_the_rocm_arm_needs_no_gate(self):- rocm = _SETUP_SRC[_SETUP_SRC.index("if ($ROCmIndexUrl) {") :]- rocm = rocm[: rocm.index("if ($XpuIndexUrl) {")]- assert (- "--force-reinstall" in rocm and "$rocmForce" not in rocm- ), "the ROCm arm forces every time, so a broken wheel is already replaced there"-def test_the_flag_is_still_raised_where_the_import_definitively_failed(self):assert "$script:TorchImportDefinitivelyFailed = $true" in _SETUP_SRC@@ -607,3 +600,63 @@ class TestPinProvenanceMustBeABoolean:encoding = "utf-8",)assert install_manifest.recorded_torch_flavor_was_pinned(tmp_path) is True+++def test_the_rocm_arm_forces_a_reinstall_only_when_the_other_arms_would():+ """The ROCm arm used to pass --force-reinstall unconditionally, so every update on a+ Windows ROCm venv re-resolved torch, torchvision and torchaudio against the ROCm index+ and moved their resolved dependencies. It now keys the flag on the same three facts+ the XPU and CPU arms read."""+ text = _SETUP_PS1.read_text(encoding = "utf-8")+ start = text.index('substep "installing PyTorch (AMD ROCm, $ROCmGfxArch)..."')+ end = text.index('substep "GPU ROCm PyTorch installed', start)+ arm = text[start:end]+ assert "--force-reinstall --index-url $ROCmIndexUrl" not in arm+ assert arm.count("@rocmForce --index-url $ROCmIndexUrl") == 2+ assert 'if ($installedTorchTag -ne "rocm") { $rocmForce = @("--force-reinstall") }' in arm+ assert "if ($script:PinChangedForceReinstall) { $rocmForce" in arm+ assert "if ($script:TorchImportDefinitivelyFailed) { $rocmForce" in arm+ # ...and the escape hatch the Python pass honours reaches this arm too, in the same+ # spellings: this runs before the pass, so UNSLOTH_STUDIO_FULL_DEPS would not otherwise+ # reach the one install that used to be forced every time.+ assert '@("1", "true", "yes", "on") -contains' in arm+ assert '"$($env:UNSLOTH_STUDIO_FULL_DEPS)".Trim().ToLowerInvariant()' in arm+ # torch alone names the family: a companion re-resolved from PyPI satisfies its pin+ # without linking ROCm, and only a forced reinstall replaces a satisfied package.+ companion = arm[arm.index("$_companionNames = ") :]+ companion = companion[: companion.index("while ($true)")]+ # Both spellings: Windows on ARM installs no torchaudio, so it is not probed there.+ assert "('torchvision', 'torchaudio')" in companion+ assert "('torchvision',)" in companion+ assert "$WinArm64NoAudio" in companion+ # +cpu, +cuNNN and +xpu companions beside a ROCm torch all force the trio.+ assert "t.startswith('cpu') or t.startswith('cu') or t.startswith('xpu')" in companion+ assert '$rocmForce = @("--force-reinstall")' in companion+ assert '"' not in companion[companion.index("-Code ") + 7 : companion.index("print(")]+++def test_the_rocm_trio_is_reinstalled_when_the_architecture_index_moves():+ """The +rocm tag names the family, not the GPU architecture: AMD publishes one index+ per architecture family, so a changed UNSLOTH_ROCM_GFX_ARCH or a replaced card moves+ the index while the resident trio still satisfies its pins. The index a trio came+ from is recorded after each successful install and compared before the fast path."""+ text = _SETUP_PS1.read_text(encoding = "utf-8")+ force = text.index("$_recordedRocmIndex -ne $_rocmIndexIdentity")+ record = text.index("Set-Content -LiteralPath $script:RocmIndexRecord")+ installed = text.index('$env:UNSLOTH_ROCM_TORCH_INSTALLED = "1"')+ assert force < installed < record+ # Recorded, compared and logged as a credential-free identity: a mirror URL can carry+ # userinfo or a token, and the record and the reinstall message must carry neither.+ record_line = text[record : text.index("\n", record)]+ assert "Get-IndexIdentity $ROCmIndexUrl" in record_line+ assert "$ROCmIndexUrl.TrimEnd" not in record_line+ message = text.index("the ROCm trio was installed from $_recordedRocmIndex")+ message_line = text[message : text.index("\n", message)]+ assert "$ROCmIndexUrl" not in message_line+ identity = text[+ text.index("function Get-IndexIdentity") : text.index("function Test-RocmGfx211Leaf")+ ]+ assert "]+@', '$1'" in identity and "-split '[?#]'" in identity+ # The record follows the install, never precedes it: a failed trio must not be recorded.+ failed = text.index("AMD ROCm PyTorch install failed -- falling back to CPU")+ assert failed < recorddiff --git a/tests/studio/test_amd_venv_repair_loop.ps1 b/tests/studio/test_amd_venv_repair_loop.ps1index a51bcdc29df..5135a828586 100644--- a/tests/studio/test_amd_venv_repair_loop.ps1+++ b/tests/studio/test_amd_venv_repair_loop.ps1@@ -703,10 +703,13 @@ $_cuTag = if ($setupText -match $_cuTagPat) { $Matches[1] } else { "" }Check "the index selection was found" ($_cuTag -ne "")Check "CRLF is normalised, not tolerated" (-not (($setupText -replace "`n", "`r`n") -match $_cuTagPat))# The two install arms that force torch back on their own. Their CONDITIONS are extracted and-# evaluated below, so "the kept wheel survives" is answered by the shipped gates. The AMD arm's-# --force-reinstall is unconditional inside its block; the XPU arm's is keyed off the installed tag.-Check "the AMD arm still force-reinstalls unconditionally" (- $setupText -match 'Fast-Install @_rocmTrio --force-reinstall --index-url \$ROCmIndexUrl')+# evaluated below, so "the kept wheel survives" is answered by the shipped gates. Both arms key+# --force-reinstall off the installed tag; the AMD arm used to force unconditionally, which made+# every update re-resolve the trio against the ROCm index.+Check "the AMD arm forces on any non-rocm tag" (+ $setupText -match 'if \(\$installedTorchTag -ne "rocm"\) \{ \$rocmForce = @\("--force-reinstall"\) \}')+Check "the AMD arm no longer forces unconditionally" (+ -not ($setupText -match 'Fast-Install @_rocmTrio --force-reinstall'))Check "the XPU arm forces on any non-xpu tag" ($setupText -match 'if \(\$installedTorchTag -ne "xpu"\) \{ \$xpuForce = @\("--force-reinstall"\) \}')$_amdGate = if ($setupText -match '(?m)^if \((-not \$TorchIndexPinned -and \(\$HasROCm -or \$ROCmGfxArch\) -and \$CuTag -eq "cpu")\) \{$') { $Matches[1] } else { "" }diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.pyindex 47df5028b2c..30c48213b52 100644--- a/tests/studio/test_xpu_triton_swap.py+++ b/tests/studio/test_xpu_triton_swap.py@@ -80,6 +80,7 @@ def _load():"""Import the module with the world stubbed, and return (module, action log)."""log: list[str] = []+ counted: list[int] = []mod = types.ModuleType("_stack_under_test")src = STACK.read_text(encoding = "utf-8")@@ -192,6 +193,9 @@ def _load(),"pip_install_try": fake_pip_install_try,"pip_install": fake_pip_install,+ # The slice removes the generic triton itself, outside pip_install, and the final+ # pip check only runs when something said it changed the environment.+ "_count_install_action": lambda: counted.append(1),"_red": lambda s: s,# _safe_print, not print: the slice calls it by name, so stubbing "print" would leave _safe_print undefined at# exec time.@@ -201,6 +205,7 @@ def _load(}exec(compile(body, str(STACK), "exec"), ns)mod.__dict__.update(ns)+ mod.__dict__["_test_counted"] = countedmod.__dict__["_test_index_urls"] = index_urlsmod.__dict__["_test_download_envs"] = download_envsreturn mod, log@@ -218,6 +223,14 @@ class TestXpuTritonSwap:log = _run(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")assert log == ["DOWNLOAD", "UNINSTALL", "INSTALL"]+ def test_the_uninstall_counts_as_an_environment_change(self, monkeypatch, tmp_path):+ """It removes a distribution outside pip_install, and the pass's final pip check only+ runs when something said the environment moved. Uncounted, dropping generic triton on+ an XPU host would leave torch's dependency unmet with nothing left to report it."""+ mod, _log = _load(monkeypatch, tmp_path, spec = "pytorch-triton-xpu==3.5.0", generic = "3.7.1")+ mod.__dict__["_ensure_xpu_triton"]()+ assert mod.__dict__["_test_counted"], "the uninstall did not count as a change"+def test_handles_the_triton_xpu_rename(self, monkeypatch, tmp_path):# torch 2.10 renamed the distribution; the spec is read from torch, never hardcoded.log = _run(monkeypatch, tmp_path, spec = "triton-xpu==3.6.0", generic = "3.7.1")diff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.pyindex b5e4567f697..107bdf0500b 100644--- a/tests/test_installer_interactive_prompts.py+++ b/tests/test_installer_interactive_prompts.py@@ -523,6 +523,10 @@ def test_helpers_the_installers_invoke_are_scanned():# resolves to the local copy. What resolves nowhere is a filename in a message, not an invocation.reference = match.group(1).replace("\\", "/")name = reference.rsplit("/", 1)[-1]+ if name == "__init__.py":+ # A presence marker (tiktoken/__init__.py), not a helper they run; by name alone it+ # would resolve to studio/__init__.py.+ continuefor candidate in (path.parent / reference,REPO_ROOT / reference,