Skip to content

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

Contain the installer tests' writes to the shared venv root (fixes the AMD fastpath probe flake) (#9587)

Daniel Han7cfe4811f0ab
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index b8ab24e1672..468b2778a34 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -80,6 +80,27 @@ def _studio_home_root(tmp_path_factory):
_studio_home_counter = itertools.count()
[email protected](autouse = True)
+def _contain_installer_venv_root(tmp_path_factory, monkeypatch):
+ """Mechanism: tests/_shared/installer_venv_root.py.
+
+ A separate pytest root, so it cannot poison the AMD fast-path probe (another job), but
+ it has the same defect: test_torchao_select.py drives install_python_stack() in process,
+ so it deletes and rewrites the manifest of the venv running the tests.
+ """
+ for _up in _iso.parents:
+ _shared = _up / "tests" / "_shared"
+ if (_shared / "installer_venv_root.py").is_file():
+ if str(_shared) not in sys.path:
+ sys.path.insert(0, str(_shared))
+ break
+ else:
+ return
+ from installer_venv_root import contain_installer_venv_root
+
+ contain_installer_venv_root(monkeypatch, tmp_path_factory)
+
+
@pytest.fixture(autouse = True)
def _isolate_studio_home(_studio_home_root, monkeypatch):
home = _studio_home_root / f"home-{next(_studio_home_counter)}"
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 0cd7a8b7de1..ad2ee35bb4d 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -335,6 +335,10 @@ _TORCH_RUNTIME_PROBE: "tuple[bool, bool, str | None, str, str] | None" = None
# line" is not reliably ours; "the last line starting with this" is.
_TORCH_PROBE_MARKER = "UNSLOTH_TORCH_PROBE|"
+# Prefix on the --amd-torch-needs-dependency-pass decision line: five states share exit 1,
+# so a caller (CI above all) needs to read WHICH input decided. setup.sh discards the stream.
+_AMD_FASTPATH_DECISION_MARKER = "UNSLOTH_AMD_FASTPATH|"
+
def _invalidate_torch_runtime_probe() -> None:
"""Forget the memoized torch classification after a pip operation."""
@@ -5688,7 +5692,18 @@ def install_python_stack() -> int:
if __name__ == "__main__":
if sys.argv[1:] == ["--amd-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
- sys.exit(0 if _amd_torch_needs_dependency_pass() else 1)
+ _needs_pass = _amd_torch_needs_dependency_pass()
+ # Exit 1 covers five states (no-torch venv, resolved non-ROCm backend, non-ROCm pin,
+ # absent or masked AMD host, unreadable torch), so a CI failure here would otherwise
+ # report a bare `assert 1 == 0` with both streams empty. setup.sh discards both
+ # streams, so this costs the installer nothing. _TORCH_RUNTIME_PROBE is read, not
+ # called, so no subprocess is added: None means an earlier gate answered first.
+ _safe_print(
+ f"{_AMD_FASTPATH_DECISION_MARKER}needs_pass={_needs_pass} no_torch={NO_TORCH} "
+ f"is_linux={IS_LINUX} machine={platform.machine()!r} backend={_TORCH_BACKEND!r} "
+ f"probe={_TORCH_RUNTIME_PROBE!r}"
+ )
+ sys.exit(0 if _needs_pass else 1)
if any(_arg.startswith("-") for _arg in sys.argv[1:]):
# Never let a malformed probe call fall through into a multi-gigabyte install.
_safe_print(f"Unknown argument: {' '.join(sys.argv[1:])}")
diff --git a/tests/_shared/installer_venv_root.py b/tests/_shared/installer_venv_root.py
new file mode 100644
index 00000000000..15580cff56d
--- /dev/null
+++ b/tests/_shared/installer_venv_root.py
@@ -0,0 +1,78 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep an in-process installer run from writing the venv root it is running in.
+
+``install_manifest.venv_root()`` is ``Path(sys.prefix)``: ONE directory, shared by every
+xdist worker and every subprocess they spawn. ``install_python_stack()`` removes the
+manifest there, writes ``.unsloth-no-torch`` there and writes the manifest back; several
+suites drive it in process with only ``subprocess.run`` mocked, so all three writes land in
+the real venv and outlive the test that made them.
+
+That is why ``test_amd_fastpath_probe.py`` failed its ``[2.9.0+cpu-None-0]`` case on 17
+"Repo tests (CPU)" runs across 7 branches in one day while passing in isolation, on
+branches touching no install file: the CLI resolves ``NO_TORCH`` at import through
+``install_manifest.recorded_no_torch()``, which reads exactly those two paths, so a leaked
+marker made every ``install_python_stack.py`` subprocess return False from
+``_amd_torch_needs_dependency_pass()`` at its first line and exit 1 with both streams empty.
+
+Redirecting the resolver beats patching each harness: the hazard is structural, any new
+harness calling ``install_python_stack()`` re-introduces it, and no pass count can show it
+because the damage is the difference between the tree before the run and the tree after.
+Every test that cares about a particular root already passes ``root=`` explicitly.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import pathlib
+import sys
+
+
+def _import_install_manifest():
+ """Register ``studio/install_manifest.py`` under the name the installer imports it by.
+
+ Imports it rather than skipping when it is absent, which is the whole of the containment
+ on one of the two roots. Keying on ``sys.modules`` alone made the fixture a no-op whenever
+ nothing had imported the installer yet, and the backend suites import it lazily inside the
+ test body (``test_torchao_select.py`` pops ``install_python_stack`` and re-imports it from
+ a ``_load_module`` helper). Measured with that early return in place: the one leaking
+ backend test run alone still rewrote the real manifest, while the whole file did not.
+ Order-dependent containment is the failure this fixture exists to remove.
+
+ ``install_manifest`` imports nothing heavier than ``json`` and ``pathlib``, so a suite that
+ never touches the installer pays one small module, not a torch import.
+ """
+ manifest = sys.modules.get("install_manifest")
+ if manifest is not None:
+ return manifest
+ for up in pathlib.Path(__file__).resolve().parents:
+ candidate = up / "studio" / "install_manifest.py"
+ if candidate.is_file():
+ spec = importlib.util.spec_from_file_location("install_manifest", candidate)
+ module = importlib.util.module_from_spec(spec)
+ # Registered BEFORE exec so the installer's own `import install_manifest` binds to
+ # this object rather than loading a second, unpatched copy.
+ sys.modules["install_manifest"] = module
+ spec.loader.exec_module(module)
+ return module
+ return None
+
+
+def contain_installer_venv_root(monkeypatch, tmp_path_factory) -> None:
+ """Point ``install_manifest.venv_root`` at a per-test directory.
+
+ Created lazily and one per test, so a run that removes the manifest and writes it back
+ sees its own writes.
+ """
+ manifest = _import_install_manifest()
+ if manifest is None:
+ return
+ resolved: list = []
+
+ def _contained_root():
+ if not resolved:
+ resolved.append(tmp_path_factory.mktemp("installer_venv_root"))
+ return resolved[0]
+
+ monkeypatch.setattr(manifest, "venv_root", _contained_root)
diff --git a/tests/conftest.py b/tests/conftest.py
index 865613679cc..d9bc923e142 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -47,6 +47,19 @@ import os
import sys
import types
+import pytest
+
+
[email protected](autouse = True)
+def _contain_installer_venv_root(tmp_path_factory, monkeypatch):
+ """Mechanism: tests/_shared/installer_venv_root.py.
+
+ Imported inside the body because tests/_shared reaches sys.path further down this file,
+ and an autouse fixture must not depend on where in the module it is defined.
+ """
+ from installer_venv_root import contain_installer_venv_root
+ contain_installer_venv_root(monkeypatch, tmp_path_factory)
+
def _has_real_accelerator() -> bool:
try:
diff --git a/tests/python/test_no_torch_filtering.py b/tests/python/test_no_torch_filtering.py
index e645eb2956b..591bd53e481 100644
--- a/tests/python/test_no_torch_filtering.py
+++ b/tests/python/test_no_torch_filtering.py
@@ -609,6 +609,42 @@ class TestInstallPythonStackSubprocessMock:
cmds, "triton-kernels.txt"
), "triton-kernels.txt should be skipped on macOS even via studio update"
+ # -- The harness above must not write the venv it is running in --
+
+ def test_the_harness_never_writes_the_running_venv_root(self):
+ """install_python_stack() drops, marks and rewrites the manifest for real here.
+
+ Only subprocess.run is mocked, so remove_manifest(), set_no_torch_marker() and
+ write_manifest() all execute against Path(sys.prefix), one directory shared by every
+ xdist worker and every subprocess they spawn. A leaked no-torch marker makes every
+ install_python_stack.py subprocess in the run resolve NO_TORCH True at import, which
+ is how the AMD fast-path CLI probe failed on 17 CI runs across 7 branches in one day
+ while passing in isolation. Driven through the real _capture_install, not a rebuilt
+ copy: the property has to hold for the harness that ships in this file.
+ """
+ real_root = Path(sys.prefix)
+ watched = (
+ real_root / ips.install_manifest.MANIFEST_NAME,
+ real_root / ips.install_manifest.NO_TORCH_MARKER,
+ )
+ before = [(p.exists(), p.read_bytes() if p.is_file() else None) for p in watched]
+
+ self._capture_install(no_torch = True, is_macos = False, is_windows = False)
+
+ after = [(p.exists(), p.read_bytes() if p.is_file() else None) for p in watched]
+ assert after == before, (
+ f"the installer harness wrote {real_root}, which every worker in this run "
+ "shares; give install_manifest.venv_root a contained root instead"
+ )
+ # Non-vacuous: the writes must have landed somewhere, or an install that returned
+ # early and wrote nothing at all would pass this too.
+ contained = ips.install_manifest.venv_root()
+ assert contained != real_root, "venv_root was never contained"
+ assert (contained / ips.install_manifest.MANIFEST_NAME).is_file(), (
+ "no manifest reached the contained root, so this run proves nothing about "
+ "where the installer writes"
+ )
+
# ── Overrides skip structural checks ─────────────────────────────────
diff --git a/tests/studio/install/test_amd_fastpath_probe.py b/tests/studio/install/test_amd_fastpath_probe.py
index ac641e81422..8c1504fcf1f 100644
--- a/tests/studio/install/test_amd_fastpath_probe.py
+++ b/tests/studio/install/test_amd_fastpath_probe.py
@@ -304,6 +304,26 @@ def _run_cli(
)
+def _decision(result):
+ """The CLI's own account of which input produced its exit code.
+
+ Exit 1 alone is five states (no-torch venv, resolved backend, non-ROCm pin, absent or
+ masked AMD host, unreadable torch), so the code cannot say which one it saw. Asserting
+ the line back against the code keeps the diagnostic from drifting off the decision.
+ """
+ stdout = result.stdout.decode(errors = "replace")
+ marked = [
+ line.strip()
+ for line in stdout.splitlines()
+ if line.strip().startswith(stack._AMD_FASTPATH_DECISION_MARKER)
+ ]
+ assert len(marked) == 1, f"expected one decision line, got {marked!r} in {stdout!r}"
+ line = marked[0]
+ expected = "needs_pass=True" if result.returncode == 0 else "needs_pass=False"
+ assert expected in line, f"decision line disagrees with exit {result.returncode}: {line}"
+ return line
+
+
@pytest.mark.parametrize("env_name", ["UNSLOTH_NO_TORCH", "UNSLOTH_TORCH_BACKEND"])
@pytest.mark.parametrize("safe_path", [False, True])
def test_the_cli_reports_keep_the_fast_path_as_a_non_zero_exit(env_name, safe_path):
@@ -316,7 +336,19 @@ def test_the_cli_reports_keep_the_fast_path_as_a_non_zero_exit(env_name, safe_pa
stderr = result.stderr.decode(errors = "replace")
# An import failure also exits 1, so exit 1 alone does not prove the gate ran.
assert not stderr, stderr
- assert result.returncode == 1, stderr
+ # Read as a STATEMENT, not in an assert message: a `_decision(result)` that appears only
+ # after the comma runs once the assertion has already failed, so it checks nothing on the
+ # passing path while reading exactly like it does.
+ decision = _decision(result)
+ assert result.returncode == 1, decision
+ # ...and the gate that answered must be the one this case names, not whichever other
+ # exit-1 state the host happened to be in, or the case passes on any host that keeps
+ # the fast path for an unrelated reason.
+ expected_field = {
+ "UNSLOTH_NO_TORCH": "no_torch=True",
+ "UNSLOTH_TORCH_BACKEND": "backend='cpu'",
+ }[env_name]
+ assert expected_field in decision
@pytest.mark.parametrize(
@@ -342,7 +374,14 @@ def test_the_cli_answers_end_to_end_over_a_stub_torch(tmp_path, version, hip, ex
)
stderr = result.stderr.decode(errors = "replace")
assert not stderr, stderr
- assert result.returncode == expected, stderr
+ # The decision line, not the bare code: exit 1 is five states here, and a bare
+ # `assert 1 == 0` with both streams empty is what this case used to report. A statement,
+ # so it is checked on the passing path too, not only when the next line fails.
+ decision = _decision(result)
+ assert result.returncode == expected, f"{decision}\n{stderr}"
+ # The wheel family must be the input that decided it, so the case cannot pass on a host
+ # that answered before the probe was reached.
+ assert f"'{version}'" in decision, decision
@pytest.mark.parametrize(