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: apply base.txt on the install.sh and install.ps1 paths (#8195)
Daniel Han3a58fa5c41d7
diff --git a/studio/backend/requirements/base.txt b/studio/backend/requirements/base.txtindex dd8474ceda0..ae0acbf3e3f 100644--- a/studio/backend/requirements/base.txt+++ b/studio/backend/requirements/base.txt@@ -1,6 +1,7 @@-# Core unsloth packages-unsloth-zoo-unsloth-# diffusers is deliberately NOT here: install.sh skips this file entirely-# (SKIP_STUDIO_BASE=1), so a pin here never reaches a fresh install. It lives in-# diffusers-pin.txt, installed by its own step in install_python_stack.py.+# Shared torch-bound ML requirements, applied unchanged on fresh install.sh /+# install.ps1 installs and on `unsloth studio update`.+#+# Not unsloth or unsloth-zoo: those are the separately skippable core phase, which+# the shell installers install inline first.+# Not diffusers: its pin must run after every other requirements file so a later+# pass cannot replace it, so it lives in diffusers-pin.txt with its own late step.diff --git a/studio/backend/requirements/diffusers-pin.txt b/studio/backend/requirements/diffusers-pin.txtindex 02c195f754e..301788a2e47 100644--- a/studio/backend/requirements/diffusers-pin.txt+++ b/studio/backend/requirements/diffusers-pin.txt@@ -7,13 +7,9 @@# wheel yet, so a released version makes Studio refuse to load H3 at all. The archive# reports itself as 0.40.0.dev0.#-# Why it is installed from its own file, in its own step: install.sh installs unsloth-# itself and then hands off to install_python_stack.py with SKIP_STUDIO_BASE=1, which-# skips the base.txt step entirely. Anything pinned in base.txt is therefore applied on-# `unsloth studio update` but NOT on a fresh install.sh, where unsloth's own metadata had-# already pulled diffusers 0.39.0 from PyPI and nothing walked it forward. The step that-# installs this file runs on every path, and runs late, after every other requirements-# file, so nothing can re-resolve diffusers back to a release behind it.+# Why it is installed from its own file, in its own step: base.txt is applied near the+# start of the dependency pass. This step runs late, after every other requirements file,+# so nothing can re-resolve diffusers back to a release behind it.## python < 3.10 has no candidate: diffusers dropped 3.9 in 0.38, so pinning the archive# outright would leave the resolver nothing at all on a 3.9 host. Those hosts get thediff --git a/studio/backend/utils/uv_path_safety.py b/studio/backend/utils/uv_path_safety.pyindex 519014c71ce..04ebe90b3dc 100644--- a/studio/backend/utils/uv_path_safety.py+++ b/studio/backend/utils/uv_path_safety.py@@ -4,9 +4,9 @@"""Hand uv a space-free `-c`/`--override`/`-r` file path (issue #6503).uv splits `-c`/`--override` (and UV_OVERRIDE) on whitespace, so a path with a-space truncates. Windows uses the 8.3 short form; POSIX copies the file into a-space-free temp dir (removed at exit). Falls back to the original path on error.-Shared by install_python_stack and utils.mlx_repair.+space truncates. Windows uses the 8.3 short form; POSIX uses a space-free temp+path (removed at exit). Falls back to the original path on error. Shared by+install_python_stack and utils.mlx_repair."""from __future__ import annotations@@ -55,8 +55,21 @@ def uv_safe_path(path: object) -> str:if " " in tmp_dir: # e.g. TMPDIR itself has a spaceshutil.rmtree(tmp_dir, ignore_errors = True)return s- dst = os.path.join(tmp_dir, (os.path.basename(s) or "uv_args.txt").replace(" ", "_"))- shutil.copyfile(s, dst)+ source_name = os.path.basename(s) or "uv_args.txt"+ if " " in source_name:+ dst = os.path.join(tmp_dir, source_name.replace(" ", "_"))+ shutil.copyfile(s, dst)+ else:+ alias_dir = os.path.join(tmp_dir, "source")+ source_dir = os.path.abspath(os.path.dirname(s) or os.curdir)+ try:+ os.symlink(source_dir, alias_dir, target_is_directory = True)+ dst = os.path.join(alias_dir, source_name)+ except OSError:+ # No symlink permission: copy instead. That loses relative -r/-c+ # includes, but returning the spaced path loses the file entirely.+ dst = os.path.join(tmp_dir, source_name)+ shutil.copyfile(s, dst)_UV_SAFE_PATH_TMPDIRS.append(tmp_dir)tmp_dir = Nonereturn dstdiff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 695aa4a2486..ca4ab062267 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -3495,22 +3495,45 @@ def _bootstrap_uv() -> bool:def _filter_requirements(req: Path, skip: set[str]) -> Path:- """Return a temp copy of a requirements file with certain packages removed."""+ """Return a temp copy, adjacent when writable, with certain packages removed."""lines = req.read_text(encoding = "utf-8").splitlines(keepends = True)filtered = [line for line in lines if not any(line.strip().lower().startswith(pkg) for pkg in skip)]- tmp = tempfile.NamedTemporaryFile(+ # Beside the source so relative -r/-c includes resolve; a read-only tree+ # (root-owned install, non-root user) falls back rather than aborting.+ kwargs = dict(mode = "w",+ prefix = f".{req.stem}-filtered-",suffix = ".txt",delete = False,encoding = "utf-8",)+ try:+ tmp = tempfile.NamedTemporaryFile(dir = req.parent, **kwargs)+ except OSError:+ tmp = tempfile.NamedTemporaryFile(**kwargs)tmp.writelines(filtered)tmp.close()return Path(tmp.name)+def _shared_base_requirements() -> Path | None:+ """The shared torch-bound requirements file, or None when it has no work."""+ if NO_TORCH:+ return None+ req = REQ_ROOT / "base.txt"+ try:+ # utf-8-sig: a BOM would otherwise read as content, scheduling an empty step.+ text = req.read_text(encoding = "utf-8-sig")+ except OSError:+ return None # missing or unreadable: nothing to apply+ for line in text.splitlines():+ if line.split("#", 1)[0].strip():+ return req+ return None++def _translate_pip_args_for_uv(args: tuple[str, ...]) -> list[str]:"""Translate pip flags to their uv equivalents."""translated: list[str] = []@@ -3528,11 +3551,10 @@ def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:"""Build a standard pip install command.pip has no --upgrade-package, so uv's flag is translated rather than- dropped. Dropping it made this fallback a no-op on the update path:- `studio update` passes --upgrade-package unsloth with a base.txt that lists- a bare unsloth, so pip found the requirement already satisfied, installed- nothing, and the update still reported success. Any uv failure reached that,- not just the Windows in-use launcher.+ dropped. Dropping it made this fallback a no-op on the update path: pip saw+ the named distributions as already satisfied, installed nothing, and the+ update still reported success. Any uv failure reached that, not just the+ Windows in-use launcher.--upgrade-strategy is pinned to only-if-needed rather than left to pip'sdefault, because that default is the load-bearing part: it upgrades the@@ -3837,9 +3859,9 @@ def install_python_stack() -> int:# the first message would get a stray newline._PROGRESS_LINE_ACTIVE = False- # install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling base packages;+ # 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.+ # 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")@@ -3853,7 +3875,12 @@ def install_python_stack() -> int:base_total += 1 # ROCm torch check (step 2b), non-macOSif not IS_WINDOWS:base_total += 2 # flash-attn + torch final repair (step 13), Linux- _TOTAL = (base_total - 1) if skip_base else base_total+ if IS_MAC_ARM and not skip_base:+ 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)# 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@@ -3937,6 +3964,7 @@ def install_python_stack() -> int:# 3. Core packages: unsloth-zoo + unsloth (or custom package name)if skip_base:+ # install.sh / install.ps1 already installed both core distributions.passelif NO_TORCH:# No-torch update path: install unsloth + unsloth-zoo, then runtime deps,@@ -3987,17 +4015,18 @@ def install_python_stack() -> int:constrain = False,)elif local_repo:- # Local dev install: update deps from base.txt, then overlay the local+ # Local dev install: update the released core packages, then overlay the# checkout as an editable install (--no-deps so torch is not re-resolved)._progress("base packages")pip_install(- "Updating base packages",+ "Updating core packages","--no-cache-dir","--upgrade-package","unsloth","--upgrade-package","unsloth-zoo",- req = REQ_ROOT / "base.txt",+ "unsloth",+ "unsloth-zoo",)_step(_LABEL, f"overlaying local repo (editable): {local_repo}")pip_install(@@ -4031,13 +4060,30 @@ def install_python_stack() -> int:# --upgrade-package targets only base pkgs._progress("base packages")pip_install(- "Updating base packages",+ "Updating core packages","--no-cache-dir","--upgrade-package","unsloth","--upgrade-package","unsloth-zoo",- req = REQ_ROOT / "base.txt",+ "unsloth",+ "unsloth-zoo",+ )++ if not skip_base:+ base_requirements = _shared_base_requirements()++ # 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:+ if skip_base:+ _progress("base requirements")+ else:+ _step(_LABEL, "applying shared base requirements")+ pip_install(+ "Applying shared base requirements",+ "--no-cache-dir",+ req = base_requirements,)# 2b. AMD ROCm: reinstall torch with HIP wheels if the host has ROCm but the@@ -4229,15 +4275,11 @@ def install_python_stack() -> int:constrain = False,)- # 11b. The pinned Diffusers revision. Deliberately NOT in base.txt: install.sh installs- # unsloth itself and then runs this script with SKIP_STUDIO_BASE=1, so the whole- # base-packages step is skipped and anything pinned there reaches `unsloth studio- # update` but never a fresh install -- where unsloth's own metadata has already- # pulled a diffusers RELEASE from PyPI, and Studio then refuses to load MiniMax-H3.- # This step is outside every skip_base / NO_TORCH branch, and it runs after every- # other requirements file, so nothing left can re-resolve diffusers behind it.- # constrain stays on: constraints.txt says nothing about diffusers, and a future- # entry there should win rather than be silently bypassed here.+ # 11b. The pinned Diffusers revision. NOT in base.txt, which is applied early: this must+ # run after every other requirements file so nothing re-resolves Diffusers back to a+ # 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 revision",diff --git a/studio/setup.ps1 b/studio/setup.ps1index e9d88bd7a08..7407fb886af 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -4628,7 +4628,7 @@ if ($stackExit -eq 0 -and $XpuIndexUrl) {# triton-windows and torch's XPU triton BOTH own the top-level `triton` package (80 to 160 shared# paths, __init__.py and _C/libtriton.pyd among them), so a cu*-to-xpu pin repair leaves the CUDA# build shadowing the XPU one. AFTER the stack, since unsloth declares triton-windows a win32-# core dep and base.txt reinstalls anything removed earlier. Uninstall always paired with a+# core dependency install reinstalls anything removed earlier. Uninstall always paired with a# reinstall: removing one drops the shared paths the other overwrote. The spec is read from the# installed torch (renamed pytorch-triton-xpu -> triton-xpu in torch 2.10).if ($stackExit -eq 0 -and $XpuIndexUrl) {diff --git a/tests/python/test_e2e_no_torch_sandbox.py b/tests/python/test_e2e_no_torch_sandbox.pyindex 5cc1995eccb..309f70d5c7b 100644--- a/tests/python/test_e2e_no_torch_sandbox.py+++ b/tests/python/test_e2e_no_torch_sandbox.py@@ -864,8 +864,9 @@ class TestInstallPythonStackFiltering:if not extras.is_file():pytest.skip("extras.txt not found")- result_path = ips._filter_requirements(extras, ips.NO_TORCH_SKIP_PACKAGES)- filtered = Path(result_path).read_text(encoding = "utf-8").lower()+ result_path = Path(ips._filter_requirements(extras, ips.NO_TORCH_SKIP_PACKAGES))+ filtered = result_path.read_text(encoding = "utf-8").lower()+ result_path.unlink() # written beside extras.txt; do not leave it in the treelines = [l.strip() for l in filtered.splitlines() if l.strip() and not l.strip().startswith("#")]@@ -883,8 +884,9 @@ class TestInstallPythonStackFiltering:if not extras.is_file():pytest.skip("extras.txt not found")- result_path = ips._filter_requirements(extras, ips.NO_TORCH_SKIP_PACKAGES)- filtered_text = Path(result_path).read_text(encoding = "utf-8").lower()+ result_path = Path(ips._filter_requirements(extras, ips.NO_TORCH_SKIP_PACKAGES))+ filtered_text = result_path.read_text(encoding = "utf-8").lower()+ result_path.unlink()must_survive = ["scikit-learn", "loguru", "tiktoken", "einops"]original_text = extras.read_text(encoding = "utf-8").lower()diff --git a/tests/python/test_install_python_stack.py b/tests/python/test_install_python_stack.pyindex 3151067973f..c37ae8f04e9 100644--- a/tests/python/test_install_python_stack.py+++ b/tests/python/test_install_python_stack.py@@ -4,13 +4,11 @@ from __future__ import annotationsimport astimport contextlib-import globimport importlibimport ioimport osimport reimport sys-import tempfilefrom pathlib import Pathfrom unittest import mock@@ -86,16 +84,18 @@ class TestUvSafePath:assert ips._uv_safe_path(p) == p@pytest.mark.skipif(ips.IS_WINDOWS, reason = "POSIX temp-copy fallback")- def test_posix_space_path_returns_spacefree_copy(self, tmp_path):+ def test_posix_space_path_preserves_relative_requirements(self, tmp_path):src = tmp_path / "Open Source" / "constraints.txt"src.parent.mkdir(parents = True)- src.write_text("torch>=2.6\n")+ src.write_text("-r child.txt\n")+ (src.parent / "child.txt").write_text("torch>=2.6\n")out = ips._uv_safe_path(str(src))assert " " not in out, f"uv-safe path still has a space: {out!r}"assert out != str(src)- assert Path(out).read_text() == "torch>=2.6\n"+ assert Path(out).read_text() == "-r child.txt\n"+ assert (Path(out).parent / "child.txt").read_text() == "torch>=2.6\n"@pytest.mark.skipif(ips.IS_WINDOWS, reason = "POSIX temp-copy fallback")def test_posix_missing_file_falls_back_to_original(self):@@ -121,24 +121,23 @@ class TestUvSafePathHardening:assert uvps.uv_safe_path(str(src)) == str(src)@pytest.mark.skipif(ips.IS_WINDOWS, reason = "POSIX temp-copy fallback")- def test_no_temp_dir_leak_on_copy_failure(self, tmp_path, monkeypatch):- """A copyfile failure after mkdtemp must not orphan the temp dir."""+ def test_alias_failure_falls_back_to_a_copy(self, tmp_path, monkeypatch):+ """A symlink failure must still hand uv a space-free path, and not orphan the dir."""from backend.utils import uv_path_safety as uvpssrc = tmp_path / "Open Source" / "constraints.txt"src.parent.mkdir(parents = True)src.write_text("idna\n")- pattern = os.path.join(tempfile.gettempdir(), "unsloth_uv_*")- before = set(glob.glob(pattern))def boom(*a, **k):raise OSError("boom")- monkeypatch.setattr(uvps.shutil, "copyfile", boom)+ monkeypatch.setattr(uvps.os, "symlink", boom)out = uvps.uv_safe_path(str(src))- assert out == str(src)- assert set(glob.glob(pattern)) == before+ assert " " not in out+ assert Path(out).read_text() == "idna\n"+ assert str(Path(out).parent) in uvps._UV_SAFE_PATH_TMPDIRS@pytest.mark.skipif(ips.IS_WINDOWS, reason = "POSIX temp-copy fallback")def test_cleanup_removes_and_clears_registry(self, tmp_path):@@ -149,7 +148,7 @@ class TestUvSafePathHardening:src.parent.mkdir(parents = True)src.write_text("idna\n")out = uvps.uv_safe_path(str(src))- tmp_dir = Path(out).parent+ tmp_dir = Path(out).parents[1]assert tmp_dir.is_dir() and str(tmp_dir) in uvps._UV_SAFE_PATH_TMPDIRSuvps._cleanup_uv_safe_path_tmpdirs()@@ -516,9 +515,9 @@ class TestProgressLineNotes:class TestBuildPipCmdUpgradeIntent:"""pip has no --upgrade-package, so uv's flag must be translated, not dropped.- Dropping it made the fallback a no-op on the update path: `studio update`- passes --upgrade-package unsloth with a base.txt listing a bare unsloth, so- pip found it satisfied, installed nothing, and the update reported success.+ Dropping it made the fallback a no-op on the update path: pip saw the named+ distributions as already satisfied, installed nothing, and the update+ reported success."""def test_update_path_keeps_the_upgrade_intent(self):diff --git a/tests/python/test_no_torch_filtering.py b/tests/python/test_no_torch_filtering.pyindex f4e093c94a4..fa977c67e5d 100644--- a/tests/python/test_no_torch_filtering.py+++ b/tests/python/test_no_torch_filtering.py@@ -133,6 +133,21 @@ class TestFilterRequirements:# Blank lines must be preserved.assert "\n\n" in content or content.count("\n") >= 3+ @pytest.mark.skipif(+ os.geteuid() == 0 if hasattr(os, "geteuid") else True,+ reason = "root ignores directory permissions",+ )+ def test_read_only_requirements_dir_falls_back(self, tmp_path):+ """A root-owned install tree must not abort the install (torchcodec/Windows filters)."""+ req = self._write_req(tmp_path, "numpy\ntorchcodec>=0.1\n")+ tmp_path.chmod(0o555)+ try:+ result = Path(ips._filter_requirements(req, {"torchcodec"}))+ finally:+ tmp_path.chmod(0o755)+ assert result.read_text(encoding = "utf-8").split() == ["numpy"]+ result.unlink()+def test_stacked_windows_and_no_torch_filters(self, tmp_path):"""Both WINDOWS_SKIP_PACKAGES and NO_TORCH_SKIP_PACKAGES applied."""req = self._write_req(@@ -209,6 +224,10 @@ class TestRealRequirementsFiltering:pytest.skip("extras.txt not found in repo")if not EXTRAS_NO_DEPS_TXT.is_file():pytest.skip("extras-no-deps.txt not found in repo")+ existing_filtered = set(REQ_ROOT.glob(".*-filtered-*.txt"))+ yield+ for path in set(REQ_ROOT.glob(".*-filtered-*.txt")) - existing_filtered:+ path.unlink(missing_ok = True)def _non_blank_non_comment(self, path: Path) -> list[str]:"""Return non-blank, non-comment lines from a requirements file."""@@ -461,6 +480,11 @@ class TestInstallPythonStackSubprocessMock:"""Check if any captured command references the given filename."""return any(filename in cmd for cmd in cmds)+ def _cmds_contain_filtered_file(self, cmds: list[str], filename: str) -> bool:+ """Check for the adjacent temp name produced from a requirements file."""+ prefix = f".{Path(filename).stem}-filtered-"+ return any("-r" in cmd and prefix in cmd for cmd in cmds)+# -- NO_TORCH=True, IS_MACOS=True (Intel Mac scenario) --def test_no_torch_macos_skips_overrides(self):@@ -480,17 +504,17 @@ class TestInstallPythonStackSubprocessMock:def test_no_torch_macos_extras_called(self):"""With NO_TORCH=True, extras.txt is still called (but filtered)."""cmds = self._capture_install(no_torch = True, is_macos = True, is_windows = False)- has_extras = self._cmds_contain_file(cmds, "extras.txt") or any(- "-r" in cmd and "tmp" in cmd.lower() for cmd in cmds- )+ has_extras = self._cmds_contain_file(+ cmds, "extras.txt"+ ) or self._cmds_contain_filtered_file(cmds, "extras.txt")assert has_extras, "extras.txt (or its filtered temp) should be called"def test_no_torch_macos_extras_no_deps_called(self):"""With NO_TORCH=True, extras-no-deps.txt is still called (but filtered)."""cmds = self._capture_install(no_torch = True, is_macos = True, is_windows = False)- has_extras_nd = self._cmds_contain_file(cmds, "extras-no-deps.txt") or any(- "-r" in cmd and "tmp" in cmd.lower() for cmd in cmds- )+ has_extras_nd = self._cmds_contain_file(+ cmds, "extras-no-deps.txt"+ ) or self._cmds_contain_filtered_file(cmds, "extras-no-deps.txt")assert has_extras_nd, "extras-no-deps.txt (or its filtered temp) should be called"# -- IS_WINDOWS=True + NO_TORCH=True (stacked) --diff --git a/tests/studio/install/test_base_requirements_reach_install.py b/tests/studio/install/test_base_requirements_reach_install.pynew file mode 100644index 00000000000..9eadbf92f5b--- /dev/null+++ b/tests/studio/install/test_base_requirements_reach_install.py@@ -0,0 +1,220 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Core-package skipping must not skip shared base requirements."""++from __future__ import annotations++import ast+import textwrap+from pathlib import Path++import pytest+from packaging.requirements import Requirement+from packaging.utils import canonicalize_name++import install_manifest+import install_python_stack as ips++_REPO_ROOT = Path(__file__).resolve().parents[3]+_STACK = _REPO_ROOT / "studio" / "install_python_stack.py"+_REQ_ROOT = _REPO_ROOT / "studio" / "backend" / "requirements"+_EXTRA_PIN = "studio-extra @ https://example.invalid/studio-extra.zip " '; python_version >= "3.10"'+++def _install_function() -> ast.FunctionDef:+ tree = ast.parse(_STACK.read_text(encoding = "utf-8"))+ return next(+ node+ for node in tree.body+ if isinstance(node, ast.FunctionDef) and node.name == "install_python_stack"+ )+++def _core_branch() -> ast.If:+ return next(+ node+ for node in _install_function().body+ if isinstance(node, ast.If)+ and isinstance(node.test, ast.Name)+ and node.test.id == "skip_base"+ )+++def _shared_base_branch() -> ast.If:+ return next(+ node+ for node in _install_function().body+ if isinstance(node, ast.If)+ and isinstance(node.test, ast.Compare)+ and isinstance(node.test.left, ast.Name)+ and node.test.left.id == "base_requirements"+ )+++class TestSharedBaseSelection:+ def _select(+ self,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ body: str,+ *,+ no_torch: bool = False,+ ) -> Path | None:+ req = tmp_path / "base.txt"+ req.write_text(textwrap.dedent(body).lstrip(), encoding = "utf-8")+ monkeypatch.setattr(ips, "REQ_ROOT", tmp_path)+ monkeypatch.setattr(ips, "NO_TORCH", no_torch)+ return ips._shared_base_requirements()++ def test_comments_only_add_no_subprocess(self, tmp_path, monkeypatch):+ assert self._select(tmp_path, monkeypatch, "# reserved for shared requirements\n\n") is None++ @pytest.mark.parametrize(+ "entry",+ [+ _EXTRA_PIN,+ "-r child.txt",+ "--requirement=https://example.invalid/base.txt",+ "-c constraints.txt",+ ],+ )+ def test_any_pip_entry_uses_the_original_file_unchanged(self, tmp_path, monkeypatch, entry):+ selected = self._select(tmp_path, monkeypatch, f"# shared\n{entry}\n")+ assert selected == tmp_path / "base.txt"+ assert selected.read_text(encoding = "utf-8") == f"# shared\n{entry}\n"+ assert not list(tmp_path.glob(".*-filtered-*.txt"))++ def test_no_torch_keeps_its_own_runtime_list(self, tmp_path, monkeypatch):+ selected = self._select(tmp_path, monkeypatch, _EXTRA_PIN, no_torch = True)+ assert selected is None++ def test_current_base_file_adds_no_install_step(self):+ assert ips._shared_base_requirements() is None++ def test_a_bom_does_not_read_as_content(self, tmp_path, monkeypatch):+ """PowerShell 5.1 redirection and some Windows editors prepend a UTF-8 BOM."""+ req = tmp_path / "base.txt"+ req.write_text("# shared\n", encoding = "utf-8-sig")+ monkeypatch.setattr(ips, "REQ_ROOT", tmp_path)+ monkeypatch.setattr(ips, "NO_TORCH", False)+ assert ips._shared_base_requirements() is None++ def test_crlf_entry_is_still_seen(self, tmp_path, monkeypatch):+ (tmp_path / "base.txt").write_bytes(b"# shared\r\n" + _EXTRA_PIN.encode() + b"\r\n")+ monkeypatch.setattr(ips, "REQ_ROOT", tmp_path)+ monkeypatch.setattr(ips, "NO_TORCH", False)+ assert ips._shared_base_requirements() == tmp_path / "base.txt"++ @pytest.mark.parametrize("mode", ["missing", "unreadable"])+ def test_an_unusable_file_does_not_take_down_the_install(self, tmp_path, monkeypatch, mode):+ """This runs before the manifest is dropped, so raising here aborts with a traceback.++ The unreadable case raises from a patched read rather than chmod(0o000):+ root ignores the mode bits and Windows does not implement them at all.+ """+ if mode == "unreadable":+ (tmp_path / "base.txt").write_text(_EXTRA_PIN, encoding = "utf-8")++ def denied(*_args, **_kwargs):+ raise PermissionError(13, "Permission denied")++ monkeypatch.setattr(Path, "read_text", denied)+ monkeypatch.setattr(ips, "REQ_ROOT", tmp_path)+ monkeypatch.setattr(ips, "NO_TORCH", False)+ assert ips._shared_base_requirements() is None+++class TestSharedBasePhase:+ def _run(self, req: Path | None, *, skip_base: bool) -> tuple[list[Path], list[str]]:+ installs: list[Path] = []+ progress: list[str] = []++ def record_install(+ _label,+ *_args,+ req = None,+ **_kwargs,+ ):+ installs.append(req)++ module = ast.Module(body = [_shared_base_branch()], type_ignores = [])+ namespace = {+ "base_requirements": req,+ "skip_base": skip_base,+ "_progress": progress.append,+ "_step": lambda *_args, **_kwargs: None,+ "_LABEL": "python",+ "pip_install": record_install,+ }+ exec(compile(module, "<shared base phase>", "exec"), namespace)+ return installs, progress++ @pytest.mark.parametrize("skip_base", [False, True])+ def test_shared_file_is_applied_once_on_both_core_paths(self, tmp_path, skip_base):+ req = tmp_path / "base.txt"+ req.write_text(_EXTRA_PIN + "\n", encoding = "utf-8")+ installs, _progress = self._run(req, skip_base = skip_base)+ assert installs == [req]++ 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")+ _installs, progress = self._run(req, skip_base = True)+ assert progress == ["base requirements"]++ def test_no_selected_file_installs_nothing(self):+ assert self._run(None, skip_base = True) == ([], [])++ def test_shared_phase_is_after_and_outside_the_core_branch(self):+ core = _core_branch()+ shared = _shared_base_branch()+ between = _STACK.read_text(encoding = "utf-8").splitlines()[core.end_lineno : shared.lineno]+ assert " base_requirements = _shared_base_requirements()" in between+ assert all(isinstance(node, ast.Pass) for node in core.body)+++class TestCorePackageOwnership:+ def test_update_calls_name_both_core_distributions_directly(self):+ calls = [+ node+ for node in ast.walk(_install_function())+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "pip_install"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and node.args[0].value == "Updating core packages"+ ]+ assert len(calls) == 2+ for call in calls:+ values = [arg.value for arg in call.args if isinstance(arg, ast.Constant)]+ assert "unsloth" in values and "unsloth-zoo" in values+ assert not any(keyword.arg == "req" for keyword in call.keywords)++ def test_base_file_does_not_own_core_distributions(self):+ names = []+ for line in (_REQ_ROOT / "base.txt").read_text(encoding = "utf-8").splitlines():+ text = line.split("#", 1)[0].strip()+ if text and not text.startswith("-"):+ names.append(canonicalize_name(Requirement(text).name))+ assert {"unsloth", "unsloth-zoo"}.isdisjoint(names)+++class TestInstallerHandoff:+ @pytest.mark.parametrize(+ "path, needle",+ [+ ("install.sh", "_SKIP_BASE=1"),+ ("install.ps1", '$env:SKIP_STUDIO_BASE = "1"'),+ ],+ )+ def test_both_installers_delegate_the_core_skip(self, path, needle):+ assert needle in (_REPO_ROOT / path).read_text(encoding = "utf-8")++ @pytest.mark.parametrize("path", ["install.sh", "install.ps1"])+ def test_python_stack_owns_shared_base_requirements(self, path):+ assert "base.txt" not in (_REPO_ROOT / path).read_text(encoding = "utf-8")++ def test_base_changes_invalidate_the_install_manifest(self):+ assert "base.txt" in install_manifest.TRACKED_REQUIREMENT_FILESdiff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.pyindex a392f80cc56..ed54bfce209 100644--- a/tests/studio/install/test_diffusers_pin.py+++ b/tests/studio/install/test_diffusers_pin.py@@ -5,11 +5,9 @@MiniMax-H3 needs a Diffusers revision newer than any published release, and Studiorefuses to load it otherwise. The pin originally lived in-studio/backend/requirements/base.txt, which looks like the obvious home and is-completely dead on the install path that matters: install.sh installs unsloth itself-(which drags a diffusers RELEASE in from PyPI as a transitive dependency) and then runs-install_python_stack.py with SKIP_STUDIO_BASE=1, where the base-packages step is a bare-`pass`. A clean install therefore ended up on the release, every time, with no error.+studio/backend/requirements/base.txt, which did not reach fresh install.sh installs at+the time. base.txt now reaches those installs as an independent shared phase, but it+still runs too early to hold this pin safely.These tests pin the shape that fixes it: exactly one file names diffusers, and the stepthat installs it sits outside every skip.@@ -65,14 +63,12 @@ def test_only_the_pin_file_names_diffusers():offenders[str(path.relative_to(REPO_ROOT))] = namedassert not offenders, (f"diffusers is requirement-listed outside diffusers-pin.txt: {offenders}. "- f"Move it into the pin file; base.txt in particular is skipped entirely by install.sh."+ f"Move it into the pin file so the dedicated late step remains authoritative.")def test_the_pin_step_is_not_gated_by_skip_base_or_no_torch():- """The whole bug in one assertion. base.txt's step lives under `if skip_base: pass`,- so it never runs on install.sh; the pin's step has to sit at function top level,- outside every conditional, or it inherits the same hole."""+ """The pin must sit at function top level so it reaches every install path."""tree = ast.parse(STACK.read_text(encoding = "utf-8"))def _installs_pin(node: ast.AST) -> bool:@@ -95,8 +91,8 @@ def test_the_pin_step_is_not_gated_by_skip_base_or_no_torch():found = Trueassert found, ("no unconditional pip_install of diffusers-pin.txt found at the top level of any "- "function in install_python_stack.py. Nested under an `if`, the pin repeats the "- "base.txt bug: applied on `unsloth studio update`, skipped on a fresh install.sh."+ "function in install_python_stack.py. Nested under an `if`, the pin can miss an "+ "install path.")@@ -121,11 +117,7 @@ def test_the_pin_step_runs_after_every_other_requirements_install():assert not later, f"these requirements files are installed after the diffusers pin: {later}"-def test_install_sh_still_skips_the_base_step():- """Guards the premise. If install.sh ever stops setting SKIP_STUDIO_BASE=1 this test- fails loudly and the comments above (and the pin's separate file) can be revisited,- rather than quietly describing an installer that no longer behaves that way."""+def test_install_sh_still_delegates_the_core_package_skip():+ """The handoff flag skips core packages while allowing other base entries through."""assert 'SKIP_STUDIO_BASE="$_SKIP_BASE"' in INSTALL_SH.read_text(encoding = "utf-8")assert "_SKIP_BASE=1" in INSTALL_SH.read_text(encoding = "utf-8")- stack = STACK.read_text(encoding = "utf-8")- assert "if skip_base:\n pass" in stackdiff --git a/tests/studio/install/test_rocm_support.py b/tests/studio/install/test_rocm_support.pyindex 9c23af01d56..12cfb9ef87d 100644--- a/tests/studio/install/test_rocm_support.py+++ b/tests/studio/install/test_rocm_support.py@@ -4509,7 +4509,15 @@ class TestProgressStepCountMatchesTotal:base_total. Regression for a repair step added without incrementing base_total,which pushed _STEP past _TOTAL (Codex P2)."""- def _run_stack(self, tmp_path, *, is_windows, is_macos, is_mac_arm):+ def _run_stack(+ self,+ tmp_path,+ *,+ is_windows,+ is_macos,+ is_mac_arm,+ skip_base = True,+ ):unstructured_plugin = tmp_path / "unstructured"github_plugin = tmp_path / "github"unstructured_plugin.mkdir()@@ -4518,7 +4526,9 @@ class TestProgressStepCountMatchesTotal:sub.returncode = 0sub.stdout = ""with (- patch.dict(os.environ, {"SKIP_STUDIO_BASE": "1"}),+ patch.dict(os.environ, {"SKIP_STUDIO_BASE": "1" if skip_base else "0"}),+ patch.object(stack_mod, "_report_mlx_stack_health"),+ patch.object(stack_mod, "_bitsandbytes_installed", return_value = False),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),@@ -4546,6 +4556,29 @@ class TestProgressStepCountMatchesTotal:step, total = self._run_stack(tmp_path, is_windows = False, is_macos = False, is_mac_arm = False)assert step == total, f"Linux 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), (False, True, False)],+ ids = ["linux", "windows", "macos_arm", "macos_intel"],+ )+ def test_progress_reaches_total_on_both_core_paths(+ self, tmp_path, is_windows, is_macos, is_mac_arm, skip_base+ ):+ """Both the installer handoff and `studio update`, on every platform.++ The update path on Apple Silicon runs the MLX step, which the earlier+ SKIP_STUDIO_BASE=1-only cases never reached, so its slot went uncounted.+ """+ 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,+ )+ assert step == total, f"progress {step} != total {total}"+# TEST: worker.py -- Windows ROCm patches (source-level checks)