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.

71.8 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-Present the Unsloth team. See /studio/LICENSE.AGPL-3.0

"""Asserts on the os.execv command that reaches the real pip or uv, with UNSLOTH_NB_SHIM=1 set."""

from __future__ import annotations

import importlib.util
import os
import sys
from pathlib import Path

import pytest


def _shared_setup_1(monkeypatch, tmp_path):
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    here, there = tmp_path / "here", tmp_path / "there"
    here.mkdir()
    there.mkdir()
    _local_project(there, "unsloth")
    monkeypatch.chdir(here)
    return there


REPO_ROOT = Path(__file__).resolve().parents[2]
SHIM_PATH = REPO_ROOT / "docker" / "unsloth_pip_shim.py"

TORCH_WHEEL_URL = (
    "https://download.pytorch.org/whl/cu128/torch-2.11.0%2Bcu128-cp312-cp312-linux_x86_64.whl"
)


class _Exec(Exception):
    """Raised by the patched os.execv so main() stops here."""

    def __init__(self, path, argv):
        self.path = path
        self.argv = list(argv)


class _BakedImage:
    """Fake for `_installed_names()` that answers `in` by prefix, so nvidia-* wheels count as present."""

    def __init__(self, mod):
        self._mod = mod

    def __contains__(self, name):
        # transformers is out of _KEEP only because the sidecar replaces its version.
        if name == "transformers":
            return True
        return name in self._mod._KEEP or name.startswith(self._mod._KEEP_PREFIX)


@pytest.fixture()
def shim(tmp_path, monkeypatch):
    """Fresh shim copy, marker in tmp_path, os.execv patched to capture the exec."""
    marker = tmp_path / "requested_transformers"
    monkeypatch.setenv("UNSLOTH_NB_TF_MARKER", str(marker))
    monkeypatch.setenv("UNSLOTH_NB_SHIM", "1")

    assert SHIM_PATH.is_file(), f"missing shim: {SHIM_PATH}"
    spec = importlib.util.spec_from_file_location("unsloth_pip_shim_under_test", SHIM_PATH)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)

    def _fake_execv(path, argv):
        raise _Exec(path, argv)

    monkeypatch.setattr(mod.os, "execv", _fake_execv)
    # Pin the fully baked image so results do not depend on the CI venv.
    monkeypatch.setattr(mod, "_installed_names", lambda: _BakedImage(mod))
    mod._marker_path = marker
    return mod


def _run(shim, tool, args):
    """(args after `install` that reached the real tool or None, recorded transformers
    version or None). The injected trailing `--constraint <file>` pair is stripped."""
    if tool == "uv":
        argv = ["uv", "pip", "install", *args]
    else:
        argv = ["pip", "install", *args]
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        try:
            shim.main()
            execd = None
        except _Exec as exc:
            i = exc.argv.index("install")
            execd = exc.argv[i + 1 :]
            if (
                len(execd) >= 2
                and execd[-2] == "--constraint"
                and os.path.basename(execd[-1]).startswith("unsloth-nb-protected-")
            ):
                execd = execd[:-2]
    marker = shim._marker_path.read_text() if shim._marker_path.exists() else None
    return execd, marker


def test_host_owned_notebook_pip_restores_root(shim, monkeypatch):
    calls = []
    monkeypatch.setenv("UNSLOTH_NB_ROOT_INSTALL", "1")
    monkeypatch.setattr(shim.os, "setgid", lambda gid: calls.append(("gid", gid)))
    monkeypatch.setattr(shim.os, "setuid", lambda uid: calls.append(("uid", uid)))
    monkeypatch.setattr(shim.sys, "argv", ["pip", "--version"])

    with pytest.raises(_Exec):
        shim.main()

    assert calls == [("gid", 0), ("uid", 0)]


UNSLOTH_VCS = "git+https://github.com/unslothai/unsloth.git#egg=unsloth"

KEPT = object()


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param(["-e", UNSLOTH_VCS, "snac"], ["snac"], id = "sep-protected"),
        pytest.param(["-e", UNSLOTH_VCS], None, id = "sep-only-protected-noop"),
        pytest.param(["-e", "./localpkg"], KEPT, id = "sep-unprotected-kept"),
        pytest.param(["--editable=" + UNSLOTH_VCS, "snac"], ["snac"], id = "inline-protected"),
        pytest.param(["--editable=./localpkg"], KEPT, id = "inline-unprotected-kept"),
        pytest.param(["-e" + UNSLOTH_VCS, "snac"], ["snac"], id = "attached-protected"),
    ],
)
def test_editable_forms(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == (args if expected is KEPT else expected), execd


@pytest.mark.parametrize(
    "args, expected, expected_marker",
    [
        pytest.param(["-P", "torch", "snac"], ["snac"], None, id = "protected-dropped"),
        pytest.param(["--upgrade-package=transformers", "snac"], ["snac"], None, id = "inline"),
        pytest.param(["-P", "transformers==4.55.0", "snac"], ["snac"], "4.55.0", id = "tf-pin"),
        pytest.param(["-P", "requests", "requests"], KEPT, None, id = "unprotected-kept"),
        pytest.param(["-P", "torch"], None, None, id = "only-protected-noop"),
    ],
)
def test_upgrade_package_forms(shim, args, expected, expected_marker):
    execd, marker = _run(shim, "uv", args)
    assert execd == (args if expected is KEPT else expected), execd
    assert marker == expected_marker, marker


NUMPY_WHEEL_URL = "https://example.com/wheels/numpy-2.1.0-cp312-cp312-linux_x86_64.whl"


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param([TORCH_WHEEL_URL], None, id = "direct-url"),
        pytest.param(
            ["/tmp/torch-2.11.0+cu128-cp312-cp312-linux_x86_64.whl"], None, id = "local-path"
        ),
        pytest.param(
            ["https://example.com/unsloth_zoo-1.0-py3-none-any.whl"], None, id = "normalised"
        ),
        pytest.param([NUMPY_WHEEL_URL], KEPT, id = "unprotected-kept"),
    ],
)
def test_wheel_url_and_path_forms(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == (args if expected is KEPT else expected), execd


def test_protected_wheel_in_requirements_file_dropped(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text(
        TORCH_WHEEL_URL + "\n" + "snac==1.2.0\n",
        encoding = "utf-8",
    )
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r"
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert "torch" not in filtered


def test_plain_package_passes_through(shim):
    execd, _ = _run(shim, "pip", ["omegaconf==2.3.1"])
    assert execd == ["omegaconf==2.3.1"], execd


def test_bare_transformers_recorded_and_dropped(shim):
    execd, marker = _run(shim, "pip", ["transformers==4.55.0"])
    assert execd is None
    assert marker == "4.55.0"


def test_index_url_value_flag_kept_verbatim(shim):
    execd, _ = _run(shim, "pip", ["--extra-index-url", "https://example.com/simple", "snac"])
    assert execd == ["--extra-index-url", "https://example.com/simple", "snac"], execd


@pytest.mark.parametrize(
    "requirements, tool, flag, expected_program, absent",
    [
        pytest.param(
            "-e git+https://github.com/unslothai/unsloth.git#egg=unsloth\nsnac==1.2.0\n",
            "pip",
            "-r",
            "-r",
            "unsloth",
            id = "editable_protected_in_requirements_file_dropped",
        ),
        pytest.param(
            "-egit+https://github.com/unslothai/unsloth.git#egg=unsloth\nsnac==1.2.0\n",
            "pip",
            "-r",
            "-r",
            "unsloth",
            id = "editable_attached_protected_in_requirements_file_dropped",
        ),
        pytest.param(
            "torch==2.11.0\nsnac==1.2.0\n",
            "uv",
            "--requirements",
            "--requirements",
            "torch",
            id = "uv_plural_requirements_filtered",
        ),
    ],
)
def test_requirements_file_drops_the_protected_package(
    shim, tmp_path, requirements, tool, flag, expected_program, absent
):
    req = tmp_path / "reqs.txt"
    req.write_text(requirements, encoding = "utf-8")
    execd, _ = _run(shim, tool, [flag, str(req)])
    assert execd is not None and execd[0] == expected_program, execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert absent not in filtered


def test_editable_unprotected_in_requirements_file_kept(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text(
        "-e ./localpkg\ntorch==2.11.0\nsnac==1.2.0\n",
        encoding = "utf-8",
    )
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "./localpkg" in filtered
    assert "snac==1.2.0" in filtered
    assert "torch" not in filtered


def test_nested_constraint_transformers_pin_not_recorded(shim, tmp_path):
    constraints = tmp_path / "constraints.txt"
    constraints.write_text("transformers==4.55.0\n", encoding = "utf-8")
    req = tmp_path / "reqs.txt"
    req.write_text("-c constraints.txt\nsnac==1.2.0\n", encoding = "utf-8")
    execd, marker = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    assert marker is None, marker


def test_nested_requirement_transformers_pin_recorded(shim, tmp_path):
    nested = tmp_path / "nested.txt"
    nested.write_text("transformers==4.55.0\n", encoding = "utf-8")
    req = tmp_path / "reqs.txt"
    req.write_text("-r nested.txt\nsnac==1.2.0\n", encoding = "utf-8")
    execd, marker = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    assert marker == "4.55.0", marker


def test_attached_short_requirement_file_filtered(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text("torch==2.11.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r" + str(req)])
    assert execd is not None and execd[0] == "-r", execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert "torch" not in filtered


def test_attached_short_constraint_file_filtered(shim, tmp_path):
    constraints = tmp_path / "constraints.txt"
    constraints.write_text("torch==2.11.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-c" + str(constraints), "snac"])
    assert execd is not None and execd[0] == "-c", execd
    assert "snac" in execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "torch" not in filtered


def test_attached_short_upgrade_package_protected_dropped(shim):
    execd, _ = _run(shim, "uv", ["-Ptorch", "snac"])
    assert execd == ["snac"], execd
    assert "torch" not in execd and "-P" not in execd


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param(["torch-2.11.0+cu128-cp312-cp312-linux_x86_64.whl"], None, id = "bare-torch"),
        pytest.param(["dist/torch-2.11.0-cp312-cp312-linux_x86_64.whl"], None, id = "subdir-torch"),
        pytest.param(["numpy-2.1.0-cp312-cp312-linux_x86_64.whl"], KEPT, id = "unprotected-kept"),
    ],
)
def test_bare_wheel_filename_forms(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == (args if expected is KEPT else expected), execd


@pytest.mark.parametrize(
    "tool, argument",
    [
        pytest.param(
            "pip",
            "git+https://github.com/huggingface/transformers.git",
            id = "vcs_url_without_egg_protected_dropped",
        ),
        pytest.param(
            "pip",
            "git+https://github.com/unslothai/unsloth-zoo.git@main",
            id = "vcs_url_without_egg_with_ref_dropped",
        ),
        pytest.param("pip", "--force-reinstall", id = "force_reinstall_flag_stripped"),
        pytest.param("pip", "-I", id = "ignore_installed_short_flag_stripped"),
        pytest.param("uv", "--reinstall", id = "uv_reinstall_flag_stripped"),
        pytest.param("uv", "--exact", id = "uv_exact_flag_stripped"),
    ],
)
def test_protected_arguments_are_stripped_before_exec(shim, tool, argument):
    execd, _ = _run(shim, tool, [argument, "snac"])
    assert execd == ["snac"], execd


def test_vcs_url_without_egg_unprotected_kept(shim):
    url = "git+https://github.com/someone/coolpkg.git"
    execd, _ = _run(shim, "pip", [url])
    assert execd == [url], execd


R_URL = "https://example.com/reqs.txt"


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param(["-r", R_URL], None, id = "sep-r-only-noop"),
        pytest.param(["-r", R_URL, "snac"], ["snac"], id = "sep-r-target-kept"),
        pytest.param(["--requirement=" + R_URL, "snac"], ["snac"], id = "inline-r"),
        pytest.param(["-r" + R_URL, "snac"], ["snac"], id = "attached-r"),
        pytest.param(["-c", "https://example.com/constraints.txt", "snac"], ["snac"], id = "sep-c"),
    ],
)
def test_remote_requirement_and_constraint_urls_refused(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == expected, execd


def test_nested_remote_include_dropped(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text("-r https://example.com/evil.txt\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert "example.com" not in filtered and "://" not in filtered


@pytest.mark.parametrize(
    "args, expected, expected_marker",
    [
        pytest.param(["--reinstall-package", "torch", "snac"], ["snac"], None, id = "sep-protected"),
        pytest.param(["--reinstall-package=torch", "snac"], ["snac"], None, id = "inline-protected"),
        pytest.param(["--reinstall-package", "requests", "requests"], KEPT, None, id = "unprotected"),
        pytest.param(
            ["--reinstall-package", "transformers==4.55.0", "snac"], ["snac"], "4.55.0", id = "tf-pin"
        ),
    ],
)
def test_reinstall_package_forms(shim, args, expected, expected_marker):
    execd, marker = _run(shim, "uv", args)
    assert execd == (args if expected is KEPT else expected), execd
    assert marker == expected_marker, marker


SDIST_URL = "https://files.pythonhosted.org/packages/aa/unsloth-2026.7.1.tar.gz"


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param([SDIST_URL, "snac"], ["snac"], id = "url-protected"),
        pytest.param(["torch-2.11.0.tar.gz"], None, id = "bare-protected"),
        pytest.param(["./transformers-4.55.0.zip", "snac"], ["snac"], id = "zip-protected"),
        pytest.param(["flashinfer-python-0.5.0.tar.gz"], None, id = "hyphenated-name"),
        pytest.param(["numpy-2.1.0.tar.gz"], KEPT, id = "unprotected-kept"),
    ],
)
def test_source_archive_forms(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == (args if expected is KEPT else expected), execd


def test_uv_plural_constraints_filtered(shim, tmp_path):
    constraints = tmp_path / "constraints.txt"
    constraints.write_text("torch==2.11.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "uv", ["--constraints", str(constraints), "snac"])
    assert execd is not None and execd[0] == "--constraints", execd
    assert "snac" in execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "torch" not in filtered


@pytest.mark.parametrize(
    "args, expected",
    [
        pytest.param(["-U", "--upgrade-strategy", "eager", "snac"], ["-U", "snac"], id = "eager"),
        pytest.param(["--upgrade-strategy=eager", "snac"], ["snac"], id = "inline-eager"),
        pytest.param(
            ["--upgrade-strategy", "only-if-needed", "snac"], ["snac"], id = "only-if-needed"
        ),
    ],
)
def test_upgrade_strategy_forms(shim, args, expected):
    execd, _ = _run(shim, "pip", args)
    assert execd == expected, execd


# Every forwarded install carries a constraints file.
def _raw_execd(shim, tool, args):
    argv = ["uv", "pip", "install", *args] if tool == "uv" else ["pip", "install", *args]
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        try:
            shim.main()
            return None
        except _Exec as exc:
            return exc.argv[exc.argv.index("install") + 1 :]


class _FakeDist:
    def __init__(self, name, version):
        self.metadata = {"Name": name}
        self.version = version


def _fake_distributions(monkeypatch, *pairs):
    """Pin what _protected_constraints_file sees as installed, else assertions depend on the ambient
    venv; the shim imports it inside the function, so patch at its source."""
    monkeypatch.setattr(
        "importlib.metadata.distributions",
        lambda **kw: [_FakeDist(n, v) for n, v in pairs],
    )


def test_forwarded_install_carries_protected_constraints(shim, monkeypatch):
    _fake_distributions(monkeypatch, ("transformers", "5.14.1"), ("trl", "0.24.0"))
    execd = _raw_execd(shim, "pip", ["snac"])
    assert execd is not None, "an unprotected target must still be forwarded"
    assert len(execd) >= 2 and execd[-2] == "--constraint", execd
    pins = Path(execd[-1]).read_text(encoding = "utf-8").strip().splitlines()
    assert pins, "constraints file must pin the installed protected packages"
    assert all("==" in pin for pin in pins), pins
    names = {pin.split("==", 1)[0].lower().replace("_", "-") for pin in pins}
    protected = {"transformers"} | shim._KEEP | {"nvidia-"}
    assert all(
        n in shim._KEEP or n == "transformers" or n.startswith("nvidia-") for n in names
    ), names


def test_forwarded_install_without_protected_packages_has_no_constraints(shim, monkeypatch):
    _fake_distributions(monkeypatch, ("snac", "1.2.1"))
    execd = _raw_execd(shim, "pip", ["snac"])
    assert execd is not None, "the install must still be forwarded"
    assert "--constraint" not in execd, execd


def test_noop_install_gets_no_constraints(shim):
    execd = _raw_execd(shim, "pip", ["torch"])
    assert execd is None


# pip expands ${VAR} in requirements files, so classification must too.
def test_env_expanded_protected_requirement_dropped(shim, tmp_path, monkeypatch):
    monkeypatch.setenv("PKG", "torch")
    req = tmp_path / "reqs.txt"
    req.write_text("${PKG}==2.11.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert "${PKG}" not in filtered and "torch" not in filtered


def test_env_expanded_transformers_pin_recorded(shim, tmp_path, monkeypatch):
    monkeypatch.setenv("TF_PKG", "transformers")
    req = tmp_path / "reqs.txt"
    req.write_text("${TF_PKG}==4.56.2\nsnac==1.2.0\n", encoding = "utf-8")
    _, marker = _run(shim, "pip", ["-r", str(req)])
    assert marker == "4.56.2"


def test_unset_env_reference_left_verbatim(shim, tmp_path, monkeypatch):
    monkeypatch.delenv("NOT_SET_ANYWHERE", raising = False)
    req = tmp_path / "reqs.txt"
    req.write_text("${NOT_SET_ANYWHERE}==1.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    assert execd == ["-r", str(req)], execd


# Must fail closed: forwarding the original passes unfiltered pins to pip.
def test_filter_write_failure_refuses_original_file(shim, tmp_path, monkeypatch):
    req = tmp_path / "reqs.txt"
    req.write_text("torch==2.11.0\nsnac==1.2.0\n", encoding = "utf-8")

    def denied(*args, **kwargs):
        raise OSError(30, "Read-only file system")

    monkeypatch.setattr(shim.tempfile, "mkstemp", denied)
    with pytest.raises(SystemExit, match = "refusing to forward"):
        shim._filter_requirements_file(str(req))


# Must warn, not abort or stay silent: transformers is already dropped from the args.
def test_marker_write_failure_warns_and_does_not_claim_success(shim, monkeypatch, capsys):
    def denied(*args, **kwargs):
        raise OSError(30, "Read-only file system")

    monkeypatch.setattr(shim.os, "makedirs", denied)
    monkeypatch.setattr(shim.sys, "argv", ["pip", "install", "transformers==4.99.0"])
    shim.main()
    err = capsys.readouterr()
    assert "WARNING" in err.err and "will NOT" in err.err
    assert "will activate its sidecar" not in err.out


# makedirs("") raises for a bare relative MARKER.
def test_bare_relative_marker_still_records(shim, tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    monkeypatch.setattr(shim, "MARKER", "requested_transformers")
    monkeypatch.setattr(shim.sys, "argv", ["pip", "install", "transformers==4.99.0"])
    shim.main()
    assert (tmp_path / "requested_transformers").read_text() == "4.99.0"


def test_filter_write_failure_clean_file_passes_through(shim, tmp_path, monkeypatch):
    req = tmp_path / "reqs.txt"
    req.write_text("snac==1.2.0\n", encoding = "utf-8")

    def denied(*args, **kwargs):
        raise OSError(30, "Read-only file system")

    monkeypatch.setattr(shim.tempfile, "mkstemp", denied)
    path, recorded, dropped = shim._filter_requirements_file(str(req))
    assert path == str(req) and recorded is None and dropped == []


# The constraints file is the only guard on transitive pins, so its write must fail closed.
def test_protected_constraints_write_failure_refuses_install(shim, monkeypatch):
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))

    def denied(*args, **kwargs):
        raise OSError(28, "No space left on device")

    monkeypatch.setattr(shim.tempfile, "mkstemp", denied)
    with pytest.raises(SystemExit, match = "refusing to install"):
        _raw_execd(shim, "pip", ["snac"])


def test_protected_metadata_enumeration_failure_refuses_install(shim, monkeypatch):
    def denied(**kw):
        raise OSError(5, "Input/output error")

    monkeypatch.setattr("importlib.metadata.distributions", denied)
    with pytest.raises(SystemExit, match = "refusing to install"):
        _raw_execd(shim, "pip", ["snac"])


# An interrupted install's .dist-info without METADATA must not drop the other pins.
def test_one_unreadable_dist_does_not_drop_the_other_pins(shim, monkeypatch):
    class _BrokenDist:
        @property
        def metadata(self):
            raise KeyError("Name")

        @property
        def version(self):
            raise KeyError("Version")

    monkeypatch.setattr(
        "importlib.metadata.distributions",
        lambda **kw: [_BrokenDist(), _FakeDist("torch", "2.11.0"), _FakeDist("snac", "1.2.1")],
    )
    execd = _raw_execd(shim, "pip", ["snac"])
    assert execd is not None and execd[-2] == "--constraint", execd
    pins = Path(execd[-1]).read_text(encoding = "utf-8").split()
    assert pins == ["torch==2.11.0"], pins


# uv --exact removes packages outside the kept target's closure.


# A local project's name comes from its metadata; a same-version dev build slips past constraints.
def _make_local_project(tmp_path, dirname, project_name):
    proj = tmp_path / dirname
    proj.mkdir()
    (proj / "pyproject.toml").write_text(f'[project]\nname = "{project_name}"\nversion = "1.0"\n')
    return str(proj)


def test_local_dir_protected_by_metadata_dropped(shim, tmp_path):
    path = _make_local_project(tmp_path, "my-checkout", "transformers")
    execd, _ = _run(shim, "pip", [path, "snac"])
    assert execd == ["snac"], execd


def test_local_dir_protected_editable_dropped(shim, tmp_path):
    path = _make_local_project(tmp_path, "unsloth", "unsloth")
    execd, _ = _run(shim, "pip", ["-e", path, "snac"])
    assert execd == ["snac"], execd
    assert "-e" not in execd


def test_local_dir_basename_fallback_setup_py(shim, tmp_path):
    proj = tmp_path / "torch"
    proj.mkdir()
    (proj / "setup.py").write_text("from setuptools import setup\nsetup()\n")
    execd, _ = _run(shim, "pip", [str(proj), "snac"])
    assert execd == ["snac"], execd


def test_local_dir_unprotected_kept(shim, tmp_path):
    path = _make_local_project(tmp_path, "my-torch-utils", "my-torch-utils")
    execd, _ = _run(shim, "pip", [path])
    assert execd == [path], execd


def test_local_dir_without_metadata_passes_through(shim, tmp_path):
    plain = tmp_path / "datadir"
    plain.mkdir()
    execd, _ = _run(shim, "pip", [str(plain)])
    assert execd == [str(plain)], execd


# Unknown value-taking flags make their value read as an install target.
@pytest.mark.parametrize(
    "tool, flag, value",
    [
        pytest.param("uv", "--torch-backend", "cu128", id = "uv-torch-backend"),
        pytest.param("uv", "--resolution", "lowest", id = "uv-resolution"),
        pytest.param("uv", "--default-index", "https://mirror/simple", id = "uv-default-index"),
        pytest.param("uv", "--exclude-newer", "2026-01-01", id = "uv-exclude-newer"),
        pytest.param("uv", "-b", "build-constraints.txt", id = "uv-build-constraints-short"),
        pytest.param("uv", "--prerelease-package", "snac", id = "uv-prerelease-package"),
        # Added in uv 0.12.
        pytest.param("uv", "--output-format", "json", id = "uv-output-format"),
        pytest.param("pip", "--proxy", "http://proxy:3128", id = "pip-proxy"),
        pytest.param("pip", "--retries", "3", id = "pip-retries"),
        pytest.param("pip", "--trusted-host", "mirror.internal", id = "pip-trusted-host"),
    ],
)
def test_value_flag_protected_only_noops(shim, tool, flag, value):
    execd, _ = _run(shim, tool, [flag, value, "torch"])
    assert execd is None, execd


@pytest.mark.parametrize(
    "tool, flag, value",
    [
        pytest.param("uv", "--torch-backend", "cu128", id = "uv-torch-backend"),
        pytest.param("uv", "--resolution", "lowest", id = "uv-resolution"),
        pytest.param("uv", "--output-format", "json", id = "uv-output-format"),
        pytest.param("pip", "--proxy", "http://proxy:3128", id = "pip-proxy"),
    ],
)
def test_value_flag_pair_forwarded_with_kept_target(shim, tool, flag, value):
    execd, _ = _run(shim, tool, [flag, value, "torch", "snac"])
    assert execd == [flag, value, "snac"], execd


def test_extra_value_is_not_a_protected_target(shim):
    execd, _ = _run(shim, "uv", ["--extra", "torch", "snac"])
    assert execd == ["--extra", "torch", "snac"], execd


def test_uv_per_package_value_flags_classified(shim):
    known = shim._VALUE_FLAGS | shim._DROP_VALUE_FLAGS
    family = {
        "--config-settings-package",
        "--exclude-newer-package",
        "--no-build-isolation-package",
        "--no-editable-package",
        "--no-sources-package",
        "--prerelease-package",
        "--refresh-package",
        "--reinstall-package",
        "--upgrade-package",
    }
    assert family <= known, sorted(family - known)


def _value_flags_from_help(cmd):
    import re
    import subprocess

    out = subprocess.run(cmd, capture_output = True, text = True).stdout
    flags = set()
    for m in re.finditer(r"^\s+(-\w)?,?\s*(--[\w-]+)[= ]<", out, re.M):
        if m.group(1):
            flags.add(m.group(1))
        flags.add(m.group(2))
    for m in re.finditer(r"^\s+(-\w) <", out, re.M):
        flags.add(m.group(1))
    return flags


# Opt-in: CI runs current pip/uv; the image build's selfcheck is authoritative.
_DRIFT_OPT_IN = os.environ.get("UNSLOTH_SHIM_FLAG_DRIFT_CHECK") == "1"


@pytest.mark.skipif(not _DRIFT_OPT_IN, reason = "opt-in: UNSLOTH_SHIM_FLAG_DRIFT_CHECK=1")
def test_pip_help_value_flags_all_classified(shim):
    known = shim._VALUE_FLAGS | shim._DROP_VALUE_FLAGS
    missing = _value_flags_from_help([sys.executable, "-m", "pip", "install", "--help"]) - known
    assert not missing, f"value flags missing from _VALUE_FLAGS: {sorted(missing)}"


@pytest.mark.skipif(
    not _DRIFT_OPT_IN or not __import__("shutil").which("uv"),
    reason = "opt-in: UNSLOTH_SHIM_FLAG_DRIFT_CHECK=1 (and uv installed)",
)
def test_uv_help_value_flags_all_classified(shim):
    known = shim._VALUE_FLAGS | shim._DROP_VALUE_FLAGS
    missing = _value_flags_from_help(["uv", "pip", "install", "--help"]) - known
    assert not missing, f"value flags missing from _VALUE_FLAGS: {sorted(missing)}"


# A VCS @ref may contain a slash; strip it before taking the last segment.
@pytest.mark.parametrize(
    "url",
    [
        pytest.param(
            "git+https://github.com/unslothai/unsloth.git@feature/foo", id = "https-slash-ref"
        ),
        pytest.param(
            "git+ssh://[email protected]/unslothai/unsloth.git@feature/foo",
            id = "ssh-userinfo-and-slash-ref",
        ),
        pytest.param("git+https://github.com/unslothai/[email protected]", id = "plain-tag-ref"),
        pytest.param("git+https://github.com/unslothai/unsloth.git", id = "no-ref"),
    ],
)
def test_vcs_slash_ref_still_protected(shim, url):
    execd, _ = _run(shim, "pip", [url, "snac"])
    assert execd == ["snac"], execd


def test_vcs_slash_ref_unprotected_kept(shim):
    url = "git+https://github.com/someorg/sometool.git@feature/foo"
    execd, _ = _run(shim, "pip", [url])
    assert execd == [url], execd


# Constraints must go before `--`, which pip and uv treat as the start of requirements.
def _execd_full(shim, tool, args):
    argv = ["uv", "pip", "install", *args] if tool == "uv" else ["pip", "install", *args]
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        with pytest.raises(_Exec) as exc:
            shim.main()
    tail = exc.value.argv[exc.value.argv.index("install") + 1 :]
    return tail


@pytest.mark.parametrize("tool", ["pip", "uv"])
def test_constraints_precede_the_end_of_options_marker(shim, tool):
    execd = _execd_full(shim, tool, ["--", "snac"])
    assert "--constraint" in execd, execd
    assert execd.index("--constraint") < execd.index("--"), (
        f"the constraints pair lands after `--`, so the real tool parses "
        f"--constraint as a requirement and the cell fails: {execd}"
    )
    assert execd[execd.index("--") :] == ["--", "snac"], execd


@pytest.mark.parametrize("tool", ["pip", "uv"])
def test_end_of_options_marker_still_protects_the_baked_stack(shim, tool):
    execd = _execd_full(shim, tool, ["--", "torch", "snac"])
    assert "torch" not in execd, execd
    assert execd[execd.index("--") :] == ["--", "snac"], execd


@pytest.mark.parametrize("tool", ["pip", "uv"])
def test_without_a_terminator_the_pair_is_still_appended_last(shim, tool):
    execd = _execd_full(shim, tool, ["snac"])
    assert execd[0] == "snac", execd
    assert execd[-2] == "--constraint", execd


# PEP 503: names compare equal under any run of -, _ or .
@pytest.mark.parametrize(
    "token",
    [
        "unsloth.zoo @ git+https://github.com/unslothai/unsloth_zoo",
        "git+https://github.com/unslothai/unsloth_zoo#egg=unsloth.zoo",
        "https://example.invalid/unsloth.zoo-1.0-py3-none-any.whl",
        "unsloth.zoo-1.0.tar.gz",
        "git+https://github.com/unslothai/unsloth.zoo",
        "unsloth.zoo==2026.9.1",
        "unsloth__zoo==2026.9.1",
        "UNSLOTH.ZOO==2026.9.1",
    ],
)
def test_dotted_spellings_of_a_protected_package_are_still_protected(shim, token):
    assert shim._canon(token) == "unsloth-zoo", token
    assert shim._canon(token) in shim._KEEP, token


@pytest.mark.parametrize(
    "token, expected",
    [
        ("nvidia.cublas-cu12==1.0", "nvidia-cublas-cu12"),
        ("huggingface.hub==1.0", "huggingface-hub"),
    ],
)
def test_prefix_and_plain_matches_normalize_too(shim, token, expected):
    name = shim._canon(token)
    assert name == expected, token
    assert name in shim._KEEP or name.startswith(shim._KEEP_PREFIX), token


def test_normalization_does_not_merge_distinct_distributions(shim):
    for token in ("torch-directml==0.2", "torch_tensorrt==2.0", "torchsde==0.2"):
        assert shim._canon(token) not in shim._KEEP, token


# --group and --requirements-from-script are the install target themselves.
@pytest.mark.parametrize(
    "args",
    [
        ["--group", "test"],
        ["--group=test"],
        ["--group", "sub/pyproject.toml:dev"],
        ["--requirements-from-script", "demo.py"],
        ["--requirements-from-script=demo.py"],
    ],
)
def test_dependency_group_flags_are_never_a_silent_no_op(shim, args):
    """Dependency-group flags are refused, so the shim never reports success while installing nothing."""
    argv = ["pip", "install", *args]
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        with pytest.raises(SystemExit) as exc:
            shim.main()
    assert "refusing" in str(exc.value), (args, exc.value)


@pytest.mark.parametrize("args", [["--no-deps"], ["--quiet"], ["torch"]])
def test_flag_only_or_fully_protected_cells_still_no_op(shim, args):
    """The guard must keep no-op'ing where there really is nothing to install."""
    argv = ["pip", "install", *args]
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        shim.main()


# Hashed lock files continue a requirement across lines with `\` and --hash rows.
HASHED_LOCK = (
    "colorama==0.4.6 \\\n"
    "    --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \\\n"
    "    --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6\n"
    "    # via -r in.txt\n"
    "torch==2.11.0 \\\n"
    "    --hash=sha256:1111111111111111111111111111111111111111111111111111111111111111 \\\n"
    "    --hash=sha256:2222222222222222222222222222222222222222222222222222222222222222\n"
    "idna==3.18 \\\n"
    "    --hash=sha256:7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2\n"
)


def test_hashed_requirement_drops_its_continuation_lines(shim, tmp_path):
    req = tmp_path / "locked.txt"
    req.write_text(HASHED_LOCK, encoding = "utf-8")
    execd, _ = _run(shim, "uv", ["-r", str(req)])
    assert execd is not None and execd[0] == "-r", execd
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    prev = ""
    for line in filtered.splitlines():
        if line.strip().startswith("--hash"):
            assert prev.rstrip().endswith("\\"), filtered
        prev = line
    assert "torch" not in filtered, filtered
    assert "1111111111111111" not in filtered and "2222222222222222" not in filtered, filtered
    assert "colorama==0.4.6 \\" in filtered, filtered
    assert "08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44" in filtered
    assert "4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6" in filtered
    assert "idna==3.18 \\" in filtered, filtered
    assert "7f952cbe720b688055e3f87de14f5c3e5fdaa8bc3928985c4077ca689de849a2" in filtered


def test_hashed_transformers_still_records_its_version(shim, tmp_path):
    req = tmp_path / "locked.txt"
    req.write_text(
        "transformers==4.55.0 \\\n"
        "    --hash=sha256:3333333333333333333333333333333333333333333333333333333333333333\n"
        "snac==1.2.0\n",
        encoding = "utf-8",
    )
    execd, marker = _run(shim, "pip", ["-r", str(req)])
    assert marker == "4.55.0", marker
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "snac==1.2.0" in filtered
    assert "transformers" not in filtered and "3333333333333333" not in filtered, filtered


def test_continued_protected_requirement_leaves_no_orphan_specifier(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text("torch \\\n    ==2.11.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "==2.11.0" not in filtered, filtered
    assert "snac==1.2.0" in filtered, filtered


# Installing extras of a baked package adds deps; --constraint pins the baked version.
@pytest.mark.parametrize(
    "arg, expected",
    [
        pytest.param("datasets[audio]", "datasets[audio]", id = "bare"),
        pytest.param("unsloth[studio]", "unsloth[studio]", id = "unsloth-studio"),
        pytest.param("datasets[audio]==4.3.0", "datasets[audio]", id = "pinned"),
        pytest.param("datasets[audio, vision]", "datasets[audio, vision]", id = "multi"),
        pytest.param(
            'datasets[audio]; python_version >= "3.10"',
            'datasets[audio] ; python_version >= "3.10"',
            id = "marker",
        ),
    ],
)
def test_extras_of_baked_package_are_forwarded(shim, arg, expected):
    execd, _ = _run(shim, "pip", [arg])
    assert execd == [expected], execd


@pytest.mark.parametrize(
    "arg",
    [
        "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git",
        "torch[opt] @ https://example.com/torch-2.11.0-py3-none-any.whl",
    ],
)
def test_extras_with_direct_reference_still_dropped(shim, arg):
    execd, _ = _run(shim, "pip", [arg])
    assert execd is None, execd


def test_extras_of_baked_package_in_requirements_file(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text("datasets[audio]==4.3.0\ntorch==2.11.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, _ = _run(shim, "pip", ["-r", str(req)])
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "datasets[audio]" in filtered, filtered
    assert "datasets[audio]==4.3.0" not in filtered, filtered
    assert "torch" not in filtered, filtered
    assert "snac==1.2.0" in filtered, filtered


# transformers extras must be forwarded like _KEEP packages.
@pytest.mark.parametrize(
    "arg, expected, expected_marker",
    [
        pytest.param(
            "transformers[deepspeed]==5.5.0", "transformers[deepspeed]", "5.5.0", id = "pinned"
        ),
        pytest.param("transformers[torch]", "transformers[torch]", None, id = "bare"),
        pytest.param(
            "transformers[torch, sentencepiece]",
            "transformers[torch, sentencepiece]",
            None,
            id = "multi",
        ),
    ],
)
def test_transformers_extras_are_forwarded_and_the_pin_is_still_recorded(
    shim, arg, expected, expected_marker
):
    execd, marker = _run(shim, "pip", [arg])
    assert execd == [expected], execd
    assert marker == expected_marker, marker


def test_transformers_extras_direct_reference_still_dropped(shim):
    execd, marker = _run(
        shim, "pip", ["transformers[torch] @ git+https://github.com/huggingface/transformers"]
    )
    assert execd is None, execd
    assert marker is None, marker


def test_transformers_extras_in_requirements_file(shim, tmp_path):
    req = tmp_path / "reqs.txt"
    req.write_text("transformers[deepspeed]==5.5.0\nsnac==1.2.0\n", encoding = "utf-8")
    execd, marker = _run(shim, "pip", ["-r", str(req)])
    filtered = Path(execd[1]).read_text(encoding = "utf-8")
    assert "transformers[deepspeed]\n" in filtered, filtered
    assert "5.5.0" not in filtered, filtered
    assert "snac==1.2.0" in filtered, filtered
    assert marker == "5.5.0", marker


def test_transformers_extras_are_dropped_when_transformers_is_not_installed(shim, monkeypatch):
    """No baked transformers means no version to hold in place: forwarding the extras
    would install whatever transformers pip resolves, so keep the sidecar route."""
    monkeypatch.setattr(shim, "_installed_names", lambda: set())
    execd, marker = _run(shim, "pip", ["transformers[deepspeed]==5.5.0"])
    assert execd is None, execd
    assert marker == "5.5.0", marker


# A sidecar's transformers dist-info comes first on PYTHONPATH and must not set the pin.
def _sidecar_dir(tmp_path, version):
    d = tmp_path / f"t_{version.replace('.', '_')}"
    info = d / f"transformers-{version}.dist-info"
    info.mkdir(parents = True)
    (info / "METADATA").write_text(
        f"Metadata-Version: 2.1\nName: transformers\nVersion: {version}\n",
        encoding = "utf-8",
    )
    (info / "RECORD").write_text("", encoding = "utf-8")
    return d


def test_protected_pins_ignore_a_sidecar_on_pythonpath(shim, tmp_path, monkeypatch):
    """The pin must name the BAKED transformers, not the activated sidecar."""
    baked = _sidecar_dir(tmp_path / "base", "4.57.6")
    sidecar = _sidecar_dir(tmp_path / "sc", "5.5.0")
    monkeypatch.setattr(shim, "_base_site_packages", lambda: [str(baked)])
    monkeypatch.syspath_prepend(str(sidecar))

    path = shim._protected_constraints_file()
    assert path is not None
    pins = Path(path).read_text(encoding = "utf-8").split()
    tf = [p for p in pins if p.lower().startswith("transformers==")]
    assert tf == ["transformers==4.57.6"], f"sidecar version leaked into the pins: {tf}"


def test_base_site_packages_never_returns_a_pythonpath_entry(shim, tmp_path, monkeypatch):
    """PYTHONPATH cannot change sys.prefix, which pin scoping needs; sidecars must not appear."""
    sidecar = _sidecar_dir(tmp_path / "sc", "5.5.0")
    monkeypatch.syspath_prepend(str(sidecar))
    scope = shim._base_site_packages()
    assert scope, "the base site-packages must be locatable"
    assert str(sidecar) not in scope, scope


# Only `uv pip install` is guarded, not `uv tool install` or `uv python install`.
def _full_argv(shim, argv):
    """The whole command line the shim would run, or None when it ran nothing."""
    with pytest.MonkeyPatch.context() as mp:
        mp.setattr(shim.sys, "argv", argv)
        try:
            shim.main()
            return None
        except _Exec as exc:
            return list(exc.argv)


@pytest.mark.parametrize(
    "argv",
    [
        ["uv", "python", "install", "3.13"],
        ["uv", "tool", "install", "ruff"],
        ["uv", "tool", "install", "transformers"],
    ],
    ids = ["python-install", "tool-install", "tool-install-protected-name"],
)
def test_non_pip_uv_subcommands_pass_through_untouched(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"), ("torch", "2.11.0"))
    ran = _full_argv(shim, argv)
    assert ran is not None, f"{' '.join(argv)} installed NOTHING"
    assert ran[1:] == argv[1:], ran
    assert "--constraint" not in ran, "this uv subcommand takes no --constraint"


@pytest.mark.parametrize(
    "argv",
    [
        ["uv", "pip", "install", "snac"],
        ["uv", "pip", "--quiet", "install", "snac"],
        ["uv", "--directory", "/x", "pip", "install", "snac"],
    ],
    ids = ["plain", "opt-before-install", "global-opt-before-pip"],
)
def test_real_uv_pip_installs_are_still_intercepted(shim, monkeypatch, argv):
    """Narrowing the match must not stop protecting the command that matters."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"), ("torch", "2.11.0"))
    ran = _full_argv(shim, argv)
    assert ran is not None
    assert "--constraint" in ran, ran


def test_a_protected_target_under_uv_tool_install_is_not_swallowed(shim, monkeypatch):
    """The silent shape: filtering left nothing to run and reported success."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    ran = _full_argv(shim, ["uv", "tool", "install", "transformers"])
    assert ran is not None, "the tool install was swallowed and reported ok"
    assert ran[-1] == "transformers", ran


# uv globals with values may sit between `pip` and `install`.
@pytest.mark.parametrize(
    "argv",
    [
        ["uv", "pip", "--directory", "/tmp", "install", "snac"],
        # Targets the guarded venv; other interpreters are bypassed on purpose.
        ["uv", "pip", "--python", "/opt/unsloth-venv/bin/python", "install", "snac"],
        ["uv", "pip", "--cache-dir", "/c", "--color", "never", "install", "snac"],
        ["uv", "pip", "--directory=/tmp", "install", "snac"],
    ],
    ids = ["directory", "python", "two-value-opts", "equals-form"],
)
def test_value_taking_options_before_install_do_not_lose_the_command(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"), ("torch", "2.11.0"))
    ran = _full_argv(shim, argv)
    assert ran is not None, f"{' '.join(argv)} was not recognised as an install"
    assert "--constraint" in ran, "the baked stack was left unprotected for a real uv pip install"


def test_a_protected_pin_behind_a_value_option_is_still_held(shim, monkeypatch):
    """Protected pins behind a value option must still be held: `torch==9.9` must never reach uv."""
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    ran = _full_argv(shim, ["uv", "pip", "--directory", "/tmp", "install", "torch==9.9"])
    assert ran is None or "torch==9.9" not in ran, f"the baked torch was replaceable: {ran}"


# Short-option clusters like -qr must be parsed.
@pytest.mark.parametrize(
    "cluster",
    ["-qr", "-Ur", "-vr", "-nr", "-Ir", "-qqr"],
)
def test_short_option_clusters_still_filter_the_requirements_file(
    shim, monkeypatch, tmp_path, cluster
):
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"), ("torch", "2.11.0"))
    reqs = tmp_path / "reqs.txt"
    reqs.write_text("transformers==5.5.0\nsnac==1.2.1\n", encoding = "utf-8")
    ran = _full_argv(shim, ["pip", "install", cluster, str(reqs)])
    assert ran is not None
    assert str(reqs) not in ran, (
        f"{cluster} forwarded the ORIGINAL requirements file; the protected pin in it "
        f"was never filtered and never recorded"
    )


def test_an_attached_short_value_is_left_alone(shim, monkeypatch, tmp_path):
    """`-rfoo.txt` already worked; splitting clusters must not break it."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    reqs = tmp_path / "reqs.txt"
    # Needs a protected pin, else forwarding the original is correct.
    reqs.write_text("transformers==5.5.0\nsnac==1.2.1\n", encoding = "utf-8")
    ran = _full_argv(shim, ["pip", "install", f"-r{reqs}"])
    assert ran is not None and str(reqs) not in ran, ran


def test_reinstall_flags_inside_a_cluster_are_still_handled(shim, monkeypatch, tmp_path):
    """-I hid inside a cluster and escaped _REINSTALL_FLAGS."""
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    ran = _full_argv(shim, ["pip", "install", "-qI", "snac"])
    assert ran is not None
    assert "-I" not in ran and "-qI" not in ran, ran


# `uv pip sync` uninstalls anything absent from the file, so it cannot be filtered.
@pytest.mark.parametrize(
    "argv",
    [
        ["uv", "pip", "sync", "reqs.txt"],
        ["uv", "pip", "--directory", "/tmp", "sync", "reqs.txt"],
    ],
    ids = ["plain", "behind-a-value-option"],
)
def test_uv_pip_sync_is_refused_rather_than_forwarded(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    with pytest.raises(SystemExit) as exc:
        _full_argv(shim, argv)
    assert "refusing" in str(exc.value), exc.value
    assert "uv pip install" in str(exc.value), "say what to use instead"


def test_uv_pip_install_is_not_caught_by_the_sync_refusal(shim, monkeypatch):
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    ran = _full_argv(shim, ["uv", "pip", "install", "snac"])
    assert ran is not None and "--constraint" in ran, ran


def test_a_byte_order_mark_does_not_hide_the_first_pin(shim, monkeypatch, tmp_path):
    """Both real tools strip a BOM and honour the line. Reading as utf-8 left
    '\\ufefftransformers==X' matching nothing, so a file whose ONLY protected pin was
    on line 1 was forwarded unchanged."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    reqs = tmp_path / "bom.txt"
    reqs.write_bytes("transformers==5.5.0\n".encode("utf-8"))
    ran = _full_argv(shim, ["pip", "install", "-r", str(reqs)])
    assert ran is None or str(reqs) not in ran, (
        "the BOM'd requirements file was forwarded verbatim, so its transformers pin "
        "reached the resolver instead of being recorded for the sidecar"
    )


# The Dockerfile lets the torchcodec / non-amd64 vLLM bakes fail; the fixture assumes none did.
def test_a_baked_name_that_is_not_installed_is_still_forwarded(shim, monkeypatch):
    assert "vllm" in shim._KEEP, "this test is meaningless if vllm is not protected"
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    monkeypatch.setattr(shim, "_installed_names", lambda: {"torch"})
    ran = _full_argv(shim, ["pip", "install", "vllm"])
    assert ran is not None, "the install was swallowed as 'already baked' on an image with no vLLM"
    assert "vllm" in ran, ran


def test_a_baked_name_that_IS_installed_is_still_dropped(shim, monkeypatch):
    """The other half, so the test above cannot be satisfied by never protecting."""
    _fake_distributions(monkeypatch, ("torch", "2.11.0"), ("vllm", "0.11.0"))
    monkeypatch.setattr(shim, "_installed_names", lambda: {"torch", "vllm"})
    ran = _full_argv(shim, ["pip", "install", "vllm"])
    assert ran is None or "vllm" not in ran, ran


# Unknown value flags hide the real target; pip help lists one alias per option.
@pytest.mark.parametrize(
    "argv",
    [
        ["pip", "--default-timeout", "100", "install", "torch"],
        ["pip", "--log-file", "/tmp/x.log", "install", "torch"],
        ["pip", "--source-dir", "/tmp/s", "install", "torch"],
        ["uv", "--python-preference", "system", "pip", "install", "torch"],
    ],
    ids = ["default-timeout", "log-file", "source-dir", "uv-python-preference"],
)
def test_a_separated_alias_value_is_not_read_as_a_target(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    ran = _full_argv(shim, argv)
    assert (
        ran is None or "torch" not in ran
    ), f"the baked torch was forwarded for replacement: {ran}"


def test_an_alias_value_does_not_hide_uv_pip_sync(shim, monkeypatch):
    """The sync refusal uses the same positional walk, so a mis-parsed global hid it too."""
    _fake_distributions(monkeypatch, ("torch", "2.11.0"))
    with pytest.raises(SystemExit) as exc:
        _full_argv(shim, ["uv", "--python-preference", "system", "pip", "sync", "r.txt"])
    assert "refusing" in str(exc.value), exc.value


def test_the_value_flag_selfcheck_cannot_certify_what_it_cannot_inspect(shim):
    """It used to scrape `--help` only, which structurally cannot see an alias, and
    still printed OK. A selfcheck that can pass while blind is worse than none."""
    src = SHIM_PATH.read_text(encoding = "utf-8")
    body = src[src.index("def _selfcheck_value_flags():") :]
    body = body[: body.index("\ndef ", 10)]
    assert "option_list_all" in body, "pip must be introspected, not scraped"
    assert (
        "refusing to" in body and "sys.exit(1)" in body
    ), "failing to introspect pip must be a FAILURE, never a silent pass"
    assert '[REAL["uv"], "--help"]' in body, "uv globals must be checked too"


# uv chdirs before resolving relative -r/-c, so the shim must read from there.


def _working_dir_case(tmp_path):
    """A cwd with NO requirements.txt, beside a directory that has one."""
    here = tmp_path / "here"
    there = tmp_path / "there"
    here.mkdir()
    there.mkdir()
    (there / "requirements.txt").write_text("transformers==4.55.0\nsnac\n", encoding = "utf-8")
    return here, there


@pytest.mark.parametrize(
    "build",
    [
        lambda d: ["uv", "pip", "--directory", d, "install", "-r", "requirements.txt"],
        lambda d: ["uv", "--directory", d, "pip", "install", "-r", "requirements.txt"],
        lambda d: ["uv", "pip", "install", "--directory", d, "-r", "requirements.txt"],
        lambda d: ["uv", "pip", "--directory=" + d, "install", "-r", "requirements.txt"],
    ],
    ids = ["between-pip-and-install", "before-pip", "after-install", "equals-form"],
)
def test_a_relative_requirements_file_is_read_from_uvs_working_directory(
    shim, monkeypatch, tmp_path, build
):
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    here, there = _working_dir_case(tmp_path)
    monkeypatch.chdir(here)
    ran = _full_argv(shim, build(str(there)))
    assert ran is not None, "the shim ran nothing"
    assert "requirements.txt" not in ran, f"forwarded the file unfiltered: {ran}"
    assert shim._marker_path.exists(), "no transformers pin was recorded"
    assert shim._marker_path.read_text() == "4.55.0"


def test_the_uv_working_dir_env_moves_the_file_too(shim, monkeypatch, tmp_path):
    """uv documents --directory as `[env: UV_WORKING_DIR=]`, so the variable alone
    relocates the file with no flag on the command line at all."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    here, there = _working_dir_case(tmp_path)
    monkeypatch.chdir(here)
    monkeypatch.setenv("UV_WORKING_DIR", str(there))
    ran = _full_argv(shim, ["uv", "pip", "install", "-r", "requirements.txt"])
    assert ran is not None, "the shim ran nothing"
    assert "requirements.txt" not in ran, f"forwarded the file unfiltered: {ran}"
    assert shim._marker_path.read_text() == "4.55.0"


def test_the_directory_flag_wins_over_the_working_dir_env(shim, monkeypatch, tmp_path):
    """uv gives the flag precedence, so honouring the variable would filter the wrong file."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    here, there = _working_dir_case(tmp_path)
    other = tmp_path / "other"
    other.mkdir()
    (other / "requirements.txt").write_text("transformers==1.0.0\n", encoding = "utf-8")
    monkeypatch.chdir(here)
    monkeypatch.setenv("UV_WORKING_DIR", str(other))
    ran = _full_argv(
        shim, ["uv", "pip", "--directory", str(there), "install", "-r", "requirements.txt"]
    )
    assert ran is not None, "the shim ran nothing"
    assert shim._marker_path.read_text() == "4.55.0", "read the env's file, not the flag's"


def test_a_nested_include_follows_uvs_working_directory(shim, monkeypatch, tmp_path):
    """Nested `-r` paths resolve against the naming file, which now sits in uv's directory."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    here, there = _working_dir_case(tmp_path)
    (there / "requirements.txt").write_text("-r nested.txt\nsnac\n", encoding = "utf-8")
    (there / "nested.txt").write_text("transformers==4.55.0\n", encoding = "utf-8")
    monkeypatch.chdir(here)
    ran = _full_argv(
        shim, ["uv", "pip", "--directory", str(there), "install", "-r", "requirements.txt"]
    )
    assert ran is not None, "the shim ran nothing"
    assert shim._marker_path.read_text() == "4.55.0"


def test_pip_keeps_resolving_a_relative_requirements_file_from_the_cwd(shim, monkeypatch, tmp_path):
    """pip has no --directory and never chdirs, so none of this may change for it."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    here, _there = _working_dir_case(tmp_path)
    (here / "requirements.txt").write_text("transformers==4.99.0\nsnac\n", encoding = "utf-8")
    monkeypatch.chdir(here)
    ran = _full_argv(shim, ["pip", "install", "-r", "requirements.txt"])
    assert ran is not None, "the shim ran nothing"
    assert shim._marker_path.read_text() == "4.99.0"


# Local project names are resolved from uv's working directory too.


def _local_project(
    root,
    name,
    version = "2026.6.9",
):
    proj = root / name
    proj.mkdir(parents = True)
    (proj / "pyproject.toml").write_text(
        f'[project]\nname = "{name}"\nversion = "{version}"\n', encoding = "utf-8"
    )
    return proj


@pytest.mark.parametrize(
    "build",
    [
        lambda d: ["uv", "pip", "--directory", d, "install", "-e", "./unsloth"],
        lambda d: ["uv", "pip", "--directory", d, "install", "./unsloth"],
        lambda d: ["uv", "--directory", d, "pip", "install", "-e", "./unsloth"],
        lambda d: ["uv", "pip", "install", "--directory", d, "-e", "./unsloth"],
    ],
    ids = ["editable", "positional", "before-pip", "after-install"],
)
def test_a_local_protected_project_is_found_in_uvs_working_directory(
    shim, monkeypatch, tmp_path, build
):
    there = _shared_setup_1(monkeypatch, tmp_path)

    ran = _full_argv(shim, build(str(there)))
    assert ran is None or not any(
        "unsloth" in a for a in ran
    ), f"the baked unsloth was forwarded for replacement: {ran}"


def test_the_working_dir_env_also_finds_a_local_protected_project(shim, monkeypatch, tmp_path):
    there = _shared_setup_1(monkeypatch, tmp_path)
    monkeypatch.setenv("UV_WORKING_DIR", str(there))

    ran = _full_argv(shim, ["uv", "pip", "install", "-e", "./unsloth"])
    assert ran is None or not any(
        "unsloth" in a for a in ran
    ), f"the baked unsloth was forwarded for replacement: {ran}"


def test_a_local_project_relative_to_the_cwd_is_still_classified(shim, monkeypatch, tmp_path):
    """Without --directory, uv resolves from the cwd as we do; local projects still classify."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    here = tmp_path / "here"
    here.mkdir()
    _local_project(here, "unsloth")
    monkeypatch.chdir(here)

    ran = _full_argv(shim, ["pip", "install", "-e", "./unsloth"])
    assert ran is None or not any(
        "unsloth" in a for a in ran
    ), f"the baked unsloth was forwarded for replacement: {ran}"


def test_an_unrelated_local_project_still_reaches_the_real_tool(shim, monkeypatch, tmp_path):
    """Unprotected local projects must still install when resolving from uv's directory."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    here, there = tmp_path / "here", tmp_path / "there"
    here.mkdir()
    there.mkdir()
    _local_project(there, "mytool", version = "0.1.0")
    monkeypatch.chdir(here)

    ran = _full_argv(shim, ["uv", "pip", "--directory", str(there), "install", "-e", "./mytool"])
    assert ran is not None and any(
        "mytool" in a for a in ran
    ), f"an unprotected local project was dropped: {ran}"


@pytest.mark.parametrize(
    "spec",
    ["./unsloth#subdirectory=sub", "./unsloth#foo=1"],
    ids = ["subdirectory", "unknown-fragment"],
)
def test_a_fragment_does_not_hide_a_local_protected_project(shim, monkeypatch, tmp_path, spec):
    """Stat the bare path: the egg fragment is stripped earlier, but other fragments stay attached
    and make the stat miss, forwarding a protected project for replacement"""
    there = _shared_setup_1(monkeypatch, tmp_path)

    ran = _full_argv(shim, ["uv", "pip", "--directory", str(there), "install", "-e", spec])
    assert ran is None or not any(
        "unsloth" in a for a in ran
    ), f"the baked unsloth was forwarded for replacement: {ran}"


# --target/--prefix/--root/--python install elsewhere, so they are not filtered.

BAKED_VENV = "/opt/unsloth-venv"


@pytest.mark.parametrize(
    "argv",
    [
        ["pip", "--python", "/tmp/venv/bin/python", "install", "torch==2.5.0"],
        ["pip", "install", "--target", "/tmp/lib", "torch==2.5.0"],
        ["pip", "install", "--target=/tmp/lib", "torch==2.5.0"],
        ["pip", "install", "-t", "/tmp/lib", "torch==2.5.0"],
        ["pip", "install", "-t/tmp/lib", "torch==2.5.0"],
        ["pip", "install", "--prefix", "/tmp/pfx", "torch==2.5.0"],
        ["pip", "install", "--root", "/tmp/root", "torch==2.5.0"],
        ["uv", "pip", "install", "--python", "/tmp/venv/bin/python", "torch==2.5.0"],
        ["uv", "pip", "install", "-p", "/tmp/venv/bin/python", "torch==2.5.0"],
        ["uv", "pip", "install", "--target", "/tmp/lib", "torch==2.5.0"],
        ["uv", "pip", "install", "--prefix", "/tmp/pfx", "torch==2.5.0"],
    ],
    ids = [
        "pip-python",
        "pip-target",
        "pip-target-eq",
        "pip-t",
        "pip-t-attached",
        "pip-prefix",
        "pip-root",
        "uv-python",
        "uv-p",
        "uv-target",
        "uv-prefix",
    ],
)
def test_an_install_aimed_elsewhere_keeps_the_packages_it_asked_for(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    ran = _full_argv(shim, argv)
    assert ran is not None, "the shim installed nothing and reported success"
    assert "torch==2.5.0" in ran, f"torch was dropped from another environment: {ran}"


@pytest.mark.parametrize(
    "var, value",
    [
        ("PIP_TARGET", "/tmp/lib"),
        ("PIP_PREFIX", "/tmp/pfx"),
        ("PIP_ROOT", "/tmp/root"),
        ("UV_PYTHON", "/tmp/venv/bin/python"),
    ],
)
def test_a_destination_environment_variable_redirects_too(shim, monkeypatch, var, value):
    """pip reads PIP_<OPTION> and uv reads UV_PYTHON, so the destination moves without a flag."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    monkeypatch.setenv(var, value)
    tool = "uv" if var.startswith("UV_") else "pip"
    argv = (
        ["uv", "pip", "install", "torch==2.5.0"]
        if tool == "uv"
        else ["pip", "install", "torch==2.5.0"]
    )
    ran = _full_argv(shim, argv)
    assert ran is not None, "the shim installed nothing and reported success"
    assert "torch==2.5.0" in ran, f"torch was dropped from another environment: {ran}"


def test_a_sync_aimed_elsewhere_is_not_refused(shim, monkeypatch):
    """The sync refusal exists because sync uninstalls everything missing from the file, stripping
    the baked stack; aimed elsewhere there is no stack to strip."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    ran = _full_argv(shim, ["uv", "pip", "sync", "--python", "/tmp/venv/bin/python", "r.txt"])
    assert ran is not None and "r.txt" in ran, f"a sync aimed elsewhere was refused: {ran}"


@pytest.mark.parametrize(
    "argv",
    [
        ["pip", "install", "torch==2.5.0"],
        ["uv", "pip", "install", "torch==2.5.0"],
        # A bare name or version may be the baked interpreter, so it buys no bypass.
        ["uv", "pip", "install", "--python", "python3", "torch==2.5.0"],
        ["uv", "pip", "install", "--python", "3.12", "torch==2.5.0"],
        [
            "pip",
            "install",
            "--target",
            BAKED_VENV + "/lib/python3.12/site-packages",
            "torch==2.5.0",
        ],
        ["uv", "pip", "install", "--python", BAKED_VENV + "/bin/python", "torch==2.5.0"],
    ],
    ids = ["pip-plain", "uv-plain", "bare-name", "bare-version", "target-in-venv", "python-in-venv"],
)
def test_the_baked_venv_is_still_protected(shim, monkeypatch, argv):
    """Guard on already-correct behaviour: the bypass must fire only for a destination
    positively resolved OUTSIDE the venv."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    ran = _full_argv(shim, argv)
    assert (
        ran is None or "torch==2.5.0" not in ran
    ), f"the baked torch was forwarded for replacement: {ran}"


# pip and uv each honour only their own env vars, so a bypass must match the tool.
@pytest.mark.parametrize(
    "tool, var",
    [
        ("pip", "UV_PYTHON"),
        ("uv", "PIP_PYTHON"),
        ("uv", "PIP_TARGET"),
        ("uv", "PIP_PREFIX"),
        ("uv", "PIP_ROOT"),
    ],
    ids = [
        "pip-ignores-uv-python",
        "uv-ignores-pip-python",
        "uv-ignores-pip-target",
        "uv-ignores-pip-prefix",
        "uv-ignores-pip-root",
    ],
)
def test_the_other_tools_destination_variable_buys_no_bypass(shim, monkeypatch, tool, var):
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    monkeypatch.setenv(var, "/tmp/elsewhere")
    argv = (
        ["uv", "pip", "install", "torch==2.5.0"]
        if tool == "uv"
        else ["pip", "install", "torch==2.5.0"]
    )
    ran = _full_argv(shim, argv)
    assert ran is None or "torch==2.5.0" not in ran, (
        f"{var} is ignored by {tool}, so the install went to the BAKED venv with no "
        f"filtering: {ran}"
    )


# pip reads PIP_<OPTION> for every option, so targets can come from env.


def _full_argv_env(shim, monkeypatch, argv):
    """(whole command line, child environment or None) for a run that execs."""
    seen = {}

    def _fake_execve(path, a, env):
        seen["env"] = env
        raise _Exec(path, a)

    monkeypatch.setattr(shim.os, "execve", _fake_execve)
    return _full_argv(shim, argv), seen.get("env")


def test_a_requirements_file_hidden_in_the_environment_is_filtered(shim, monkeypatch, tmp_path):
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    hidden = tmp_path / "hidden.txt"
    hidden.write_text("torch==9.9.9\nidna==3.6\n", encoding = "utf-8")
    monkeypatch.setenv("PIP_REQUIREMENT", str(hidden))

    ran, env = _full_argv_env(shim, monkeypatch, ["pip", "install", "packaging"])
    assert ran is not None, "the shim ran nothing"
    assert "torch==9.9.9" not in ran, f"the baked torch was forwarded: {ran}"
    assert str(hidden) not in ran, f"the uninspected file was forwarded verbatim: {ran}"
    assert any(
        os.path.basename(a).startswith("unsloth-nb-req-") for a in ran
    ), f"no filtered requirements file reached the real tool: {ran}"
    assert env is not None and "PIP_REQUIREMENT" not in env, (
        "the variable survived into the child, so the real pip reads the file again "
        "unfiltered alongside our filtered copy"
    )


def test_an_editable_hidden_in_the_environment_is_classified(shim, monkeypatch, tmp_path):
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    _local_project(tmp_path, "unsloth")
    monkeypatch.setenv("PIP_EDITABLE", str(tmp_path / "unsloth"))

    proj = str(tmp_path / "unsloth")
    ran, env = _full_argv_env(shim, monkeypatch, ["pip", "install", "packaging"])
    # Not a substring test: our constraints file is named unsloth-nb-protected-*.
    assert ran is not None, "the shim ran nothing"
    assert (
        proj not in ran and "-e" not in ran
    ), f"the baked unsloth was forwarded for replacement: {ran}"
    assert env is not None and "PIP_EDITABLE" not in env


def test_several_hidden_requirements_files_are_all_filtered(shim, monkeypatch, tmp_path):
    """pip splits these on whitespace, so one variable can carry several files."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    one, two = tmp_path / "one.txt", tmp_path / "two.txt"
    one.write_text("torch==9.9.9\n", encoding = "utf-8")
    two.write_text("torch==8.8.8\nidna==3.6\n", encoding = "utf-8")
    monkeypatch.setenv("PIP_REQUIREMENT", f"{one} {two}")

    ran, _env = _full_argv_env(shim, monkeypatch, ["pip", "install", "packaging"])
    assert ran is not None, "the shim ran nothing"
    assert not any("9.9.9" in a or "8.8.8" in a for a in ran), f"a baked torch survived: {ran}"
    assert (
        sum(1 for a in ran if os.path.basename(a).startswith("unsloth-nb-req-")) == 2
    ), f"both files should have been filtered: {ran}"


def test_uv_is_not_given_a_requirements_file_pip_alone_reads(shim, monkeypatch, tmp_path):
    """Guard: uv has no environment form for --requirements, so folding PIP_REQUIREMENT
    into a uv command would install a file uv was never asked for."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    hidden = tmp_path / "hidden.txt"
    hidden.write_text("idna==3.6\n", encoding = "utf-8")
    monkeypatch.setenv("PIP_REQUIREMENT", str(hidden))

    ran = _full_argv(shim, ["uv", "pip", "install", "snac"])
    assert ran is not None, "the shim ran nothing"
    assert (
        "-r" not in ran and str(hidden) not in ran
    ), f"a pip-only requirements file was handed to uv: {ran}"


def test_nothing_is_added_when_no_hidden_target_is_set(shim, monkeypatch):
    """Guard: the ordinary case must be byte-identical, and must not switch to execve."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    monkeypatch.delenv("PIP_REQUIREMENT", raising = False)
    monkeypatch.delenv("PIP_EDITABLE", raising = False)
    ran, env = _full_argv_env(shim, monkeypatch, ["pip", "install", "snac"])
    assert ran is not None and "snac" in ran, ran
    assert "-r" not in ran and "-e" not in ran, f"a phantom target was added: {ran}"
    assert env is None, "the environment was rebuilt when nothing needed clearing"


# pip --root / is the identity relocation and still writes the venv.
IDENTITY_ROOT = "/" + ""


@pytest.mark.parametrize(
    "argv",
    [
        ["pip", "install", "--root", IDENTITY_ROOT, "torch==2.5.0"],
        ["pip", "install", "--root=" + IDENTITY_ROOT, "torch==2.5.0"],
        ["pip", "install", "--root", IDENTITY_ROOT + IDENTITY_ROOT, "torch==2.5.0"],
    ],
    ids = ["separated", "equals-form", "double-slash"],
)
def test_an_identity_root_still_protects_the_baked_venv(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    ran = _full_argv(shim, argv)
    assert ran is None or "torch==2.5.0" not in ran, (
        f"--root {IDENTITY_ROOT!r} relocates nothing, so this still replaces the baked "
        f"CUDA stack: {ran}"
    )


def test_an_identity_root_from_the_environment_still_protects(shim, monkeypatch):
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    monkeypatch.setenv("PIP_ROOT", IDENTITY_ROOT)
    ran = _full_argv(shim, ["pip", "install", "torch==2.5.0"])
    assert (
        ran is None or "torch==2.5.0" not in ran
    ), f"PIP_ROOT={IDENTITY_ROOT!r} relocates nothing: {ran}"


def test_a_real_root_relocation_is_still_a_bypass(shim, monkeypatch):
    """Guard: a root that genuinely moves the install must keep bypassing, or we are
    back to emptying the environment the caller actually named."""
    _fake_distributions(monkeypatch, ("torch", "2.9.1+cu128"))
    ran = _full_argv(shim, ["pip", "install", "--root", "/tmp/reloc", "torch==2.5.0"])
    assert (
        ran is not None and "torch==2.5.0" in ran
    ), f"a genuine --root relocation was filtered: {ran}"


@pytest.mark.parametrize(
    "spec",
    [
        "unsloth@GIT+HTTPS://github.com/unslothai/unsloth.git",
        "unsloth@Git+Https://github.com/unslothai/unsloth.git",
        "unsloth@HTTPS://example.com/unsloth-2026.6.9-py3-none-any.whl",
        "unsloth[all]@GIT+HTTPS://github.com/unslothai/unsloth.git",
    ],
    ids = ["upper-vcs", "mixed-vcs", "upper-url-wheel", "extras"],
)
def test_an_uppercase_direct_reference_scheme_is_still_classified(shim, monkeypatch, spec):
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    ran = _full_argv(shim, ["pip", "install", spec, "snac"])
    assert (
        ran is None or spec not in ran
    ), f"a protected direct reference was forwarded because of scheme casing: {ran}"


def test_an_unprotected_direct_reference_still_reaches_the_real_tool(shim, monkeypatch):
    """Guard: matching schemes case insensitively must not start dropping things that
    were never protected."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    spec = "snac@GIT+HTTPS://github.com/example/snac.git"
    ran = _full_argv(shim, ["pip", "install", spec])
    assert ran is not None and spec in ran, f"an unprotected direct reference was dropped: {ran}"


def test_an_uppercase_scheme_without_a_double_slash_is_still_classified(shim, monkeypatch):
    """Direct references like `GIT+FILE:` lack `://`, so the scheme match must ignore case."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    spec = "GIT+FILE:/tmp/checkout#egg=unsloth"
    ran = _full_argv(shim, ["pip", "install", spec, "snac"])
    assert (
        ran is None or spec not in ran
    ), f"a protected direct reference was forwarded because of scheme casing: {ran}"


# --group/--requirements-from-script targets cannot be scanned or constrained.
@pytest.mark.parametrize(
    "argv",
    [
        ["pip", "install", "--group", "dev"],
        ["pip", "install", "--group=dev"],
        ["uv", "pip", "install", "--group", "dev"],
        ["pip", "install", "--requirements-from-script", "demo.py"],
        ["pip", "install", "--group", "dev", "snac"],
    ],
    ids = ["pip-group", "pip-group-eq", "uv-group", "pip-script", "group-with-target"],
)
def test_an_uninspectable_target_source_is_refused(shim, monkeypatch, argv):
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    with pytest.raises(SystemExit) as exc:
        _full_argv(shim, argv)
    assert "refusing" in str(exc.value), exc.value


def test_a_group_install_aimed_elsewhere_is_not_refused(shim, monkeypatch):
    """The destination bypass runs first on purpose: a group installed into another environment
    cannot touch the baked stack, so refusing it would block a harmless command."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    ran = _full_argv(shim, ["pip", "install", "--target", "/tmp/lib", "--group", "dev"])
    assert ran is not None and "--group" in ran, f"a harmless group install was refused: {ran}"


def test_an_ordinary_install_is_not_refused(shim, monkeypatch):
    """Guard: the refusal must key on those flags alone."""
    _fake_distributions(monkeypatch, ("unsloth", "2026.6.9"))
    ran = _full_argv(shim, ["pip", "install", "snac"])
    assert ran is not None and "snac" in ran, ran


@pytest.mark.parametrize(
    "spec, expected",
    [
        ("transformers==4.57.6", "4.57.6"),
        ("transformers==4.57.6; python_version < '3.0'", None),
        ("transformers==4.57.6; sys_platform == 'win32'", None),
        ("transformers==5.5.0; python_version >= '3.0'", "5.5.0"),
    ],
    ids = ["no-marker", "false-marker", "false-marker-platform", "true-marker"],
)
def test_a_false_marker_does_not_record_a_transformers_pin(shim, monkeypatch, spec, expected):
    """Both real tools skip a requirement whose marker is false ("Ignoring
    transformers: markers ... don't match your environment"), so it installs nothing
    and must not write the sidecar marker file that every later cell reads."""
    _fake_distributions(monkeypatch, ("transformers", "4.57.6"))
    _execd, marker = _run(shim, "pip", [spec])
    assert marker == expected, f"recorded {marker!r} for {spec!r}"