π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
ci: reconcile the test venv with the torch each matrix leg installs (#4200)
Dmytro Mishkin1e322cb1531d
diff --git a/.github/scripts/check_torch_env.py b/.github/scripts/check_torch_env.pynew file mode 100644index 000000000..6574a3081--- /dev/null+++ b/.github/scripts/check_torch_env.py@@ -0,0 +1,284 @@+#!/usr/bin/env python3++# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Check the CI virtualenv against the torch build a matrix leg just installed.++``tests.yml`` builds its environment in two steps: ``uv sync`` installs the lockfile,+whose torch comes from PyPI, and the matrix leg then replaces *torch alone* with a build+from the CPU wheel index. Everything ``uv sync`` installed for the locked torch stays+behind, and the ``+cpu`` wheels declare a narrower dependency set than the PyPI ones --+no ``triton`` at all (checked for 2.5.1, 2.6.0, 2.9.1 and 2.14.0). The lockfile's triton+therefore survives the swap as an orphan belonging to a torch that is no longer+installed, and torch dispatches onto it: ``_is_triton_available()`` tests whether+``import triton`` succeeds, not whether that triton matches. torch 2.6 then runs+``from triton.backends.compiler import AttrsDescriptor``, a name triton 3.8 removed, and+32 dynamo and export tests die at import. See #4199.++This module is the single home of that explanation; the workflow comments point here.++Two modes:++``--list-undeclared-sidecars``+ Print the installed sidecar packages the installed torch does not declare, for the+ workflow to uninstall. These legs are CPU-only, so torch taking its non-triton path+ deliberately is the right outcome; an incompatible triton is worse than no triton.++``--channel CHANNEL --expected VERSION``+ Verify that the torch version satisfies the leg's channel, that every runtime+ requirement of *that* torch is installed and satisfied, and that no undeclared+ sidecar survived. A mis-provisioned venv fails here, at setup, instead of surfacing+ later as a wall of unrelated-looking test failures.++Machine-readable results go to stdout as ``key: value`` lines; diagnostics go to stderr.+A ``torch-version:`` line is printed only by a *passing* check, so the workflow can treat+its absence as failure rather than depending on the shell's pipefail setting.++Usage::++ python3 .github/scripts/check_torch_env.py --list-undeclared-sidecars+ python3 .github/scripts/check_torch_env.py --channel pinned --expected 2.6.0+"""++from __future__ import annotations++import argparse+import sys+from collections.abc import Iterable, Mapping, Sequence+from importlib.metadata import PackageNotFoundError, distribution, distributions++from packaging.requirements import Requirement+from packaging.utils import canonicalize_name+from packaging.version import InvalidVersion, Version++# Packages torch selects at runtime by import availability rather than by version, so an+# orphan left over from a different torch is silently picked up instead of ignored. Both+# names install the same ``triton`` import; ``pytorch-triton`` is the nightly channel's.+#+# Deliberately an allowlist rather than a general "installed but outside the installed+# torch's closure" diff: most of the venv is legitimately outside that closure -- kornia's+# own dependencies, the test tooling -- and installed metadata records no provenance, so a+# diff cannot tell an orphan from a root. The swap's other survivors, the lockfile's+# ``nvidia-*`` and ``cuda-*`` wheels, cost runner disk but are inert on these legs because+# a ``+cpu`` torch never loads them. Add a name here when a new sidecar turns out to be+# dispatched on availability.+SIDECAR_PACKAGES = ("triton", "pytorch-triton")++# The stdout contract the workflow greps. Renaming either of these without updating+# ``tests.yml`` silently turns its steps into no-ops, so ``tests/scripts`` pins both.+SIDECAR_PREFIX = "undeclared-sidecars:"+VERSION_PREFIX = "torch-version:"+++def runtime_requirements(+ requires: Iterable[str] | None, environment: Mapping[str, str] | None = None+) -> list[Requirement]:+ """Return the requirements of a distribution that apply to a plain, no-extra install.++ Args:+ requires: ``Requires-Dist`` entries, as ``importlib.metadata`` reports them.+ environment: Marker variables overriding the running interpreter's, for tests.++ Returns:+ The requirements whose markers hold, with the extras-only ones dropped.++ """+ markers = {"extra": ""}+ markers.update(environment or {})+ kept = []+ for entry in requires or ():+ requirement = Requirement(entry)+ if requirement.marker is not None and not requirement.marker.evaluate(markers):+ continue+ kept.append(requirement)+ return kept+++def scan_installed() -> tuple[dict[str, str], dict[str, list[str]]]:+ """Return every installed distribution's version, and the names that resolve ambiguously.++ ``distributions()`` walks ``sys.path`` in order and the first match wins, which is what+ ``importlib.metadata.version`` and a plain ``import`` resolve to, so first-wins is the+ honest answer across path entries. Two ``.dist-info`` directories for one name *inside a+ single* path entry have no such order -- that is a half-written venv, exactly what an+ interrupted ``uv pip install --reinstall-package torch`` leaves behind -- so those are+ reported rather than settled by whichever the filesystem happened to yield first.++ Returns:+ The canonical-name-to-version map, and the names seen with disagreeing versions.++ """+ found: dict[str, str] = {}+ seen: dict[str, set[str]] = {}+ for dist in distributions():+ name = dist.metadata["Name"]+ if not name:+ continue+ canonical = canonicalize_name(name)+ found.setdefault(canonical, dist.version)+ seen.setdefault(canonical, set()).add(dist.version)+ return found, {name: sorted(versions) for name, versions in seen.items() if len(versions) > 1}+++def installed_versions() -> dict[str, str]:+ """Map the canonical name of every installed distribution to its version."""+ return scan_installed()[0]+++def undeclared_sidecars(+ requires: Iterable[str] | None,+ installed: Mapping[str, str],+ environment: Mapping[str, str] | None = None,+) -> list[str]:+ """Return the installed sidecar packages that the installed torch does not declare."""+ declared = {canonicalize_name(item.name) for item in runtime_requirements(requires, environment)}+ return [name for name in map(canonicalize_name, SIDECAR_PACKAGES) if name in installed and name not in declared]+++def check_torch_version(version: str, channel: str, expected: str) -> str | None:+ """Return a problem description when ``version`` does not satisfy the leg's channel.++ ``pinned`` demands exactly ``expected`` (the local ``+cpu`` segment is ignored);+ ``stable`` treats ``expected`` as a floor, since the upstream probe installs whatever+ the stable index resolves to today.+ """+ release = Version(version.partition("+")[0])+ if channel == "pinned":+ if release != Version(expected):+ return f"torch {version} is not the pinned {expected}"+ elif channel == "stable":+ if release < Version(expected):+ return f"torch {version} is below the {expected} floor of the stable channel"+ else:+ raise ValueError(f"unknown torch channel: {channel!r}")+ return None+++def check_environment(+ torch_version: str,+ requires: Iterable[str] | None,+ installed: Mapping[str, str],+ channel: str,+ expected: str,+ environment: Mapping[str, str] | None = None,+ duplicates: Mapping[str, Sequence[str]] | None = None,+) -> list[str]:+ """Return every way the environment disagrees with the torch that is installed.++ Args:+ torch_version: Version of the imported torch, ``+cpu`` local segment included.+ requires: ``Requires-Dist`` entries of the installed torch distribution.+ installed: Canonical distribution name to version, as ``installed_versions``.+ channel: ``pinned`` or ``stable``.+ expected: The matrix version -- exact under ``pinned``, a floor under ``stable``.+ environment: Marker variables overriding the running interpreter's, for tests.+ duplicates: Names visible with disagreeing versions, as ``scan_installed``.++ Returns:+ Human-readable problem descriptions; empty when the environment is coherent.++ """+ problems = []+ version_problem = check_torch_version(torch_version, channel, expected)+ if version_problem is not None:+ problems.append(version_problem)++ for requirement in runtime_requirements(requires, environment):+ name = canonicalize_name(requirement.name)+ version = installed.get(name)+ if version is None:+ problems.append(f"torch {torch_version} requires {requirement}, which is not installed")+ elif not requirement.specifier.contains(version, prereleases=True):+ problems.append(f"torch {torch_version} requires {requirement}, but {requirement.name} {version} is here")++ for name in undeclared_sidecars(requires, installed, environment):+ problems.append(+ f"{name} {installed[name]} is installed, but torch {torch_version} declares no dependency on it: "+ "torch dispatches onto an importable sidecar without checking its version (#4199)"+ )++ for name, versions in sorted((duplicates or {}).items()):+ problems.append(+ f"{name} is installed more than once, as {' and '.join(versions)}: the venv is half-written, "+ "and which one importlib.metadata reports is filesystem order rather than a decision"+ )+ return problems+++def _torch_distribution() -> tuple[str, list[str] | None]:+ """Return the installed torch's runtime version and its ``Requires-Dist`` entries."""+ import torch++ dist = distribution("torch")+ try:+ recorded = Version(dist.version.partition("+")[0])+ running = Version(torch.__version__.partition("+")[0])+ except InvalidVersion: # A source or nightly build; the metadata check is best-effort.+ return torch.__version__, dist.requires+ if recorded != running:+ raise SystemExit(f"torch imports as {torch.__version__} but its distribution metadata says {dist.version}")+ return torch.__version__, dist.requires+++def main(argv: Sequence[str] | None = None) -> int:+ """Run the requested mode and return the process exit status."""+ parser = argparse.ArgumentParser(description="Check the CI venv against the installed torch.")+ parser.add_argument("--channel", choices=("pinned", "stable"), help="torch channel the leg installed with")+ parser.add_argument("--expected", help="matrix torch version: exact under pinned, a floor under stable")+ parser.add_argument(+ "--list-undeclared-sidecars",+ action="store_true",+ help="print the sidecar packages the installed torch does not declare, and exit",+ )+ args = parser.parse_args(argv)++ # Validated before any environment work: enumerating every distribution and importing+ # torch takes seconds and tells a caller who forgot a flag nothing they need.+ if not args.list_undeclared_sidecars and (args.channel is None or args.expected is None):+ parser.error("--channel and --expected are required unless --list-undeclared-sidecars is given")++ try:+ installed, duplicates = scan_installed()+ if args.list_undeclared_sidecars:+ stale = undeclared_sidecars(distribution("torch").requires, installed)+ print(f"{SIDECAR_PREFIX} {' '.join(stale)}".rstrip())+ return 0+ torch_version, requires = _torch_distribution()+ except PackageNotFoundError:+ print("torch is not installed in this environment", file=sys.stderr)+ return 1++ problems = check_environment(torch_version, requires, installed, args.channel, args.expected, duplicates=duplicates)+ if problems:+ # The requirement table is diagnostic, so it is printed where it diagnoses something+ # rather than as ~15 lines of noise on every healthy leg.+ for requirement in runtime_requirements(requires):+ name = canonicalize_name(requirement.name)+ print(f" {name} {installed.get(name, '(missing)')}", file=sys.stderr)+ for problem in problems:+ print(f"error: {problem}", file=sys.stderr)+ return 1++ # Only a passing check reports a version. Printing it on the failure path too would hand+ # the workflow a valid-looking answer from a mis-provisioned venv and leave its+ # "did the check report a version?" guard unable to ever fire.+ print(f"{VERSION_PREFIX} {torch_version.partition('+')[0]}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 0c935af85..3c96fc951 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -118,7 +118,7 @@ jobs:- name: Install dependenciesrun: pixi run -e ${{ steps.pixi-env.outputs.name }} install- - name: Install PyTorch matrix version+ - name: Install the matrix torch and reconcile the environmentshell: bashenv:PYTORCH_VERSION: ${{ matrix.pytorch-version }}@@ -139,6 +139,37 @@ jobs:;;esac+ # `uv sync` installed the lockfile's dependency set for the *locked* torch, and the swap+ # above replaced torch alone with a `+cpu` build that declares no `triton` at all, so the+ # lockfile's triton survives as an orphan of a torch that is no longer installed and torch+ # dispatches onto it by import availability rather than by version (#4199).+ # `.github/scripts/check_torch_env.py` carries the full mechanism. These legs are CPU-only+ # and never need triton, so dropping it lets torch take its non-triton path deliberately+ # instead of tripping over the wrong one.+ #+ # This runs inside the swap's own step rather than a step of its own so it cannot be+ # reordered ahead of it: against the *locked* torch -- which does declare triton -- the+ # check finds nothing stale, and #4199 would survive a green run.+ report=$(pixi run -e ${{ steps.pixi-env.outputs.name }} uv run --no-sync \+ python .github/scripts/check_torch_env.py --list-undeclared-sidecars | tr -d '\r')+ # An empty capture would mean the parse broke, not that the venv is clean, so the+ # result line has to be there before its content is believed.+ if ! printf '%s\n' "$report" | grep -q '^undeclared-sidecars:'; then+ echo "the sidecar check reported no result; refusing to assume the venv is clean" >&2+ printf '%s\n' "$report" >&2+ exit 1+ fi+ stale=$(printf '%s\n' "$report" | sed -n 's/^undeclared-sidecars:[[:space:]]*//p' | tail -n 1)+ if [[ -n "$stale" ]]; then+ echo "Removing packages the installed torch does not declare: $stale"+ pixi run -e ${{ steps.pixi-env.outputs.name }} uv run --no-sync uv pip uninstall $stale+ else+ echo "No stale torch sidecars to remove"+ fi++ # Assert the whole environment against the torch that was just installed, not only+ # torch.__version__: a silently mis-provisioned venv has to fail here, at setup, rather+ # than run the suite and report a wall of unrelated-looking test failures (#4199).- name: Verify PyTorch versionid: torch-versionshell: bash@@ -148,7 +179,17 @@ jobs:run: |# Under torch-channel: stable the matrix value is only a floor, so record what actually# got installed; the candidate-manifest artifact is named after it below.- resolved=$(pixi run -e ${{ steps.pixi-env.outputs.name }} uv run --no-sync python -c 'import os, torch; channel = os.environ["TORCH_CHANNEL"]; expected = os.environ["EXPECTED_PYTORCH_VERSION"]; version = torch.__version__; clean = version.partition("+")[0]; got = tuple(int(p) for p in clean.split(".")[:3]); floor = tuple(int(p) for p in expected.split(".")[:3]); ok = version.startswith(expected) if channel == "pinned" else got >= floor; assert ok, f"torch {version} does not satisfy channel={channel} expected={expected}"; print(clean)' | tr -d '\r' | tail -n 1)+ resolved=$(pixi run -e ${{ steps.pixi-env.outputs.name }} uv run --no-sync \+ python .github/scripts/check_torch_env.py \+ --channel "$TORCH_CHANNEL" --expected "$EXPECTED_PYTORCH_VERSION" \+ | tr -d '\r' | sed -n 's/^torch-version: //p' | tail -n 1)+ # The check prints `torch-version:` only when the environment is coherent, so an+ # empty capture is a real failure signal here and not merely a broken parse. It is+ # what makes this gate blocking regardless of the shell's pipefail setting.+ if [[ -z "$resolved" ]]; then+ echo "the environment check did not report a torch version" >&2+ exit 1+ fiecho "torch-channel=$TORCH_CHANNEL expected=$EXPECTED_PYTORCH_VERSION resolved=$resolved"echo "resolved=$resolved" >> "$GITHUB_OUTPUT"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87c768e1d..720d96eb2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -219,6 +219,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* The pinned-torch CI legs no longer run against the lockfile's `triton`. `uv sync` installs the locked torch's+ dependency set, and each matrix leg then swaps torch alone for a `+cpu` build -- whose wheels declare no `triton` at+ all -- so the lockfile's triton survived as an orphan of a torch that was no longer installed. torch guards its+ inductor triton path on import availability rather than on version, so it dispatched onto that orphan and the+ `2.6.0` leg died in `from triton.backends.compiler import AttrsDescriptor` on 32 dynamo and export tests, having+ never been green. The install step now drops sidecar packages the installed torch does not declare, and the+ verification step asserts the whole environment against that torch (`.github/scripts/check_torch_env.py`) so a+ mis-provisioned venv fails at setup instead of as a wall of unrelated-looking test failures. The five+ `tests/core/test_small_linalg.py` ONNX cases the import error was masking now export with `external_data=False`,+ which torch 2.6's dynamo exporter requires when the destination is a `BytesIO`. (#4199, #4200)+* `find_homography_dlt(..., solver="lu")` now solves the minimal four-point system with an adaptivehomogeneous gauge instead of applying LU to its singular normal matrix. This is the estimator`RANSAC(model_type="homography")` calls for every minimal sample, so homography RANSAC resultsdiff --git a/testing/known_failure_xfails/mps_float32.txt b/testing/known_failure_xfails/mps_float32.txtindex dd18bc254..28ea2daa3 100644--- a/testing/known_failure_xfails/mps_float32.txt+++ b/testing/known_failure_xfails/mps_float32.txt@@ -2,6 +2,8 @@# macos-26-arm64, Python 3.13, PyTorch 2.9.1, MPS float32, no CPU fallback,# one pytest process for the full suite (tests marked device_agnostic are deselected on an mps-only run).# Remove an entry when it becomes a strict XPASS; fix or explicitly add any new failure. Tracked in #4159.+# test_zero_weight_minimal_lu was added after recording and reaches the same unsupported+# aten::linalg_qr.out as nearby pins.# Format: <exact exception type>\t<pytest node ID>AssertionError tests/augmentation/_3d/test_random_affine_3d.py::TestRandomAffine3D::test_batch_random_affine_3d[mps-float32]NotImplementedError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[mps-float32-False-bilinear-circular-direction0-angle1]@@ -148,6 +150,7 @@ NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::teNotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape_noweights[mps-float32-2-5]NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_shape_noweights[mps-float32-3-6]NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_smoke[mps-float32]+NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLT::test_zero_weight_minimal_lu[mps-float32]NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_clean_points[mps-float32-1]NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_clean_points[mps-float32-2]NotImplementedError tests/geometry/test_homography.py::TestFindHomographyDLTIter::test_shape[mps-float32-1-4]diff --git a/tests/core/test_small_linalg.py b/tests/core/test_small_linalg.pyindex c270edb0f..390a6027c 100644--- a/tests/core/test_small_linalg.py+++ b/tests/core/test_small_linalg.py@@ -82,6 +82,22 @@ def _export_kwargs(use_dynamo_exporter: bool) -> dict:kwargs = {"opset_version": 18}if torch_version_ge(2, 5, 0):kwargs["dynamo"] = use_dynamo_exporter+ if use_dynamo_exporter and torch_version_ge(2, 6, 0):+ # These cases export into a ``BytesIO``, and the dynamo exporter's default+ # ``external_data=True`` hands that destination straight to onnxscript's+ # ``save_model_with_external_data``, which takes a filesystem path. On torch 2.6 that is+ # ``TypeError: expected str, bytes or os.PathLike object, not BytesIO`` after a successful+ # translation -- measured; 2.9.1 and 2.14.0 accept the buffer through a newer onnxscript+ # framework API. These graphs are a handful of nodes with no initializers, so there is no+ # external data to write out on any version.+ #+ # Gated because ``external_data=`` does not exist before 2.6, and this function promises+ # kwargs valid on every supported torch. Every call site happens to run+ # ``_require_exporter`` first, which skips below 2.6, but that is an ordering at three+ # call sites rather than a property of the function that claims the invariant -- and+ # ``test_cross_kernel_onnx_export_is_informational`` re-raises ``TypeError``, so getting+ # it wrong is a hard failure rather than a skip.+ kwargs["external_data"] = Falsereturn kwargsdiff --git a/tests/scripts/test_check_torch_env.py b/tests/scripts/test_check_torch_env.pynew file mode 100644index 000000000..9e81474f3--- /dev/null+++ b/tests/scripts/test_check_torch_env.py@@ -0,0 +1,312 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+import sys+from pathlib import Path++import pytest++# `.github/scripts/` is neither a package nor on the path. This deliberately stays a per-module+# insert rather than moving to a `tests/scripts/conftest.py`: `tests/` has no `__init__.py`, so a+# second bare `conftest` module shadows the repository-root one, and `tests/test_half_precision_ci.py`+# locates the repository through `Path(conftest.__file__).parent`. Measured: adding that conftest+# makes `import conftest` resolve here and sends five of its workflow assertions looking for+# `tests/scripts/.github/workflows/`.+sys.path.insert(0, str(Path(__file__).parent.parent.parent / ".github" / "scripts"))++import check_torch_env+from check_torch_env import (+ SIDECAR_PREFIX,+ VERSION_PREFIX,+ check_environment,+ check_torch_version,+ installed_versions,+ main,+ runtime_requirements,+ scan_installed,+ undeclared_sidecars,+)++INSTALL_STEP = "Install the matrix torch and reconcile the environment"++# Verbatim Requires-Dist of torch-2.6.0+cpu-cp311-cp311-linux_x86_64.whl, the leg that #4199+# broke. The CPU wheel index declares no triton; the PyPI wheel of the same version does.+CPU_WHEEL_REQUIRES = [+ "filelock",+ "typing-extensions (>=4.10.0)",+ "networkx",+ "jinja2",+ "fsspec",+ 'setuptools ; python_version >= "3.12"',+ 'sympy (==1.13.1) ; python_version >= "3.9"',+ "opt-einsum (>=3.3) ; extra == 'opt-einsum'",+ "optree (>=0.13.0) ; extra == 'optree'",+]+PYPI_WHEEL_REQUIRES = [+ *CPU_WHEEL_REQUIRES,+ 'triton (==3.2.0) ; platform_system == "Linux" and platform_machine == "x86_64" and python_version < "3.13"',+]++# A Linux x86_64 CPython 3.11 leg, so the markers above resolve the same way everywhere.+LINUX_PY311 = {"python_version": "3.11", "platform_system": "Linux", "platform_machine": "x86_64"}++# What `uv sync` leaves behind once the leg swaps in torch 2.6.0+cpu: the lockfile's triton,+# built for the locked torch 2.14.0, plus torch 2.6.0's own (correctly reinstalled) closure.+MIS_PROVISIONED = {+ "torch": "2.6.0+cpu",+ "triton": "3.8.0",+ "filelock": "3.20.0",+ "typing-extensions": "4.15.0",+ "networkx": "3.5",+ "jinja2": "3.1.6",+ "fsspec": "2025.9.0",+ "sympy": "1.13.1",+}+HEALTHY = {name: version for name, version in MIS_PROVISIONED.items() if name != "triton"}+++class TestRuntimeRequirements:+ def test_drops_extras_and_false_markers(self):+ requirements = runtime_requirements(CPU_WHEEL_REQUIRES, LINUX_PY311)++ names = [item.name for item in requirements]+ assert names == ["filelock", "typing-extensions", "networkx", "jinja2", "fsspec", "sympy"]+ # setuptools is python_version >= "3.12"; opt-einsum and optree are extras-only.+ assert "setuptools" not in names+ assert "optree" not in names++ def test_handles_a_distribution_without_requirements(self):+ assert runtime_requirements(None) == []+++class TestUndeclaredSidecars:+ def test_reports_the_lockfile_triton_the_cpu_wheel_does_not_declare(self):+ assert undeclared_sidecars(CPU_WHEEL_REQUIRES, MIS_PROVISIONED, LINUX_PY311) == ["triton"]++ def test_keeps_a_triton_the_installed_torch_declares(self):+ assert undeclared_sidecars(PYPI_WHEEL_REQUIRES, MIS_PROVISIONED, LINUX_PY311) == []++ def test_reports_nothing_when_no_sidecar_is_installed(self):+ assert undeclared_sidecars(CPU_WHEEL_REQUIRES, HEALTHY, LINUX_PY311) == []+++class TestCheckTorchVersion:+ @pytest.mark.parametrize("version", ["2.6.0", "2.6.0+cpu"])+ def test_pinned_accepts_the_matrix_version_with_or_without_a_local_segment(self, version):+ assert check_torch_version(version, "pinned", "2.6.0") is None++ def test_pinned_rejects_a_version_that_merely_shares_a_prefix(self):+ # `2.14.0`.startswith(`2.1`) is true, so a prefix test would have let this through.+ assert check_torch_version("2.14.0+cpu", "pinned", "2.1") is not None++ def test_pinned_rejects_another_version(self):+ assert "2.6.0" in check_torch_version("2.9.1+cpu", "pinned", "2.6.0")++ def test_stable_treats_the_matrix_version_as_a_floor(self):+ assert check_torch_version("2.14.0+cpu", "stable", "2.9.1") is None+ assert check_torch_version("2.5.1+cpu", "stable", "2.9.1") is not None++ def test_rejects_an_unknown_channel(self):+ with pytest.raises(ValueError, match="unknown torch channel"):+ check_torch_version("2.6.0", "nightly", "2.6.0")+++class TestCheckEnvironment:+ def test_flags_the_orphan_triton_that_broke_the_2_6_0_leg(self):+ problems = check_environment("2.6.0+cpu", CPU_WHEEL_REQUIRES, MIS_PROVISIONED, "pinned", "2.6.0", LINUX_PY311)++ assert len(problems) == 1+ assert "triton 3.8.0 is installed" in problems[0]+ assert "#4199" in problems[0]++ def test_accepts_the_reconciled_environment(self):+ assert check_environment("2.6.0+cpu", CPU_WHEEL_REQUIRES, HEALTHY, "pinned", "2.6.0", LINUX_PY311) == []++ def test_flags_a_missing_requirement(self):+ installed = {name: version for name, version in HEALTHY.items() if name != "sympy"}++ problems = check_environment("2.6.0+cpu", CPU_WHEEL_REQUIRES, installed, "pinned", "2.6.0", LINUX_PY311)++ assert len(problems) == 1+ assert "sympy" in problems[0] and "not installed" in problems[0]++ def test_flags_a_requirement_left_at_the_locked_version(self):+ # The failure mode option 1 of #4199 addresses: a dependency the pin step did not move.+ installed = {**HEALTHY, "sympy": "1.14.0"}++ problems = check_environment("2.6.0+cpu", CPU_WHEEL_REQUIRES, installed, "pinned", "2.6.0", LINUX_PY311)++ assert len(problems) == 1+ assert "sympy 1.14.0 is here" in problems[0]++ def test_reports_the_version_mismatch_alongside_the_environment(self):+ problems = check_environment("2.9.1+cpu", CPU_WHEEL_REQUIRES, MIS_PROVISIONED, "pinned", "2.6.0", LINUX_PY311)++ assert len(problems) == 2+ assert "is not the pinned 2.6.0" in problems[0]++ def test_flags_a_distribution_visible_twice(self):+ # What an interrupted `uv pip install --reinstall-package torch` leaves behind: two+ # dist-info directories in one path entry, where first-wins is filesystem order.+ problems = check_environment(+ "2.6.0+cpu",+ CPU_WHEEL_REQUIRES,+ HEALTHY,+ "pinned",+ "2.6.0",+ LINUX_PY311,+ duplicates={"sympy": ["1.13.1", "1.14.0"]},+ )++ assert len(problems) == 1+ assert "sympy is installed more than once" in problems[0]+++def test_installed_versions_reports_this_environment():+ installed = installed_versions()++ # Canonical names, so a `typing_extensions`/`typing-extensions` spelling cannot hide a dist.+ assert installed["torch"]+ assert "typing-extensions" in installed+++def test_scan_installed_finds_no_duplicates_in_a_coherent_venv():+ installed, duplicates = scan_installed()++ assert installed["torch"]+ assert duplicates == {}+++class TestMain:+ """`main` is the surface the workflow greps and gates on; the helpers above are not.++ Both contracts are load-bearing and neither is visible from the functions themselves:+ the stdout prefixes `tests.yml` parses, and the rule that only a *passing* check prints+ a version. Break either and the workflow steps degrade to no-ops that stay green.+ """++ def test_listing_mode_prints_the_prefix_the_workflow_greps(self, capsys):+ assert main(["--list-undeclared-sidecars"]) == 0++ printed = capsys.readouterr().out.splitlines()+ assert [line for line in printed if line.startswith(SIDECAR_PREFIX)]++ def test_a_passing_check_reports_the_version(self, monkeypatch, capsys):+ monkeypatch.setattr(check_torch_env, "check_environment", lambda *args, **kwargs: [])++ assert main(["--channel", "stable", "--expected", "0.0.1"]) == 0++ printed = capsys.readouterr().out+ assert printed.startswith(f"{VERSION_PREFIX} ")++ def test_a_failing_check_reports_no_version(self, monkeypatch, capsys):+ # The regression that made the workflow's own `-z "$resolved"` guard dead code: with+ # the version printed unconditionally, a mis-provisioned venv still handed the step a+ # valid-looking answer, and only the shell's pipefail default failed the leg.+ monkeypatch.setattr(check_torch_env, "check_environment", lambda *args, **kwargs: ["boom"])++ assert main(["--channel", "pinned", "--expected", "2.6.0"]) == 1++ captured = capsys.readouterr()+ assert VERSION_PREFIX not in captured.out+ assert "error: boom" in captured.err++ def test_a_real_version_mismatch_fails_without_a_version_line(self, capsys):+ # The same contract without a monkeypatch: no installed torch is ever 0.0.1.+ assert main(["--channel", "pinned", "--expected", "0.0.1"]) == 1++ assert VERSION_PREFIX not in capsys.readouterr().out++ def test_a_healthy_run_keeps_the_requirement_table_off_the_log(self, monkeypatch, capsys):+ monkeypatch.setattr(check_torch_env, "check_environment", lambda *args, **kwargs: [])++ main(["--channel", "stable", "--expected", "0.0.1"])++ # The table diagnoses nothing when there is nothing wrong, and every leg pays for it.+ # Matched by its indent rather than by an empty stderr, so an unrelated import warning+ # cannot make this pass or fail for the wrong reason.+ assert [line for line in capsys.readouterr().err.splitlines() if line.startswith(" ")] == []++ def test_missing_arguments_error_before_the_environment_is_scanned(self, monkeypatch):+ def fail(*args, **kwargs):+ raise AssertionError("the environment was scanned before the arguments were validated")++ monkeypatch.setattr(check_torch_env, "scan_installed", fail)++ with pytest.raises(SystemExit) as excinfo:+ main([])++ assert excinfo.value.code == 2+++class TestWorkflowWiring:+ """The reusable workflow has to actually run the check; a script nobody calls fixes nothing."""++ @staticmethod+ def _workflow():+ root = Path(__file__).parent.parent.parent+ return (root / ".github" / "workflows" / "tests.yml").read_text(encoding="utf-8")++ @staticmethod+ def _step(workflow, name):+ """Return one step's body, bounded at the next step rather than running to end of file.++ An unbounded slice is satisfied by any *later* step, so it would keep passing after the+ step it names had been gutted.+ """+ start = workflow.index(f"- name: {name}")+ end = workflow.find("\n - name:", start + 1)+ return workflow[start : end if end != -1 else len(workflow)]++ def test_the_reconcile_runs_inside_the_step_that_swaps_torch(self):+ # Ordering is the whole fix. Run the check against the *locked* torch -- which does+ # declare triton -- and it finds nothing stale, so the leg swaps in `+cpu` torch+ # afterwards and #4199 survives under a green run. Keeping the reconcile in the swap's+ # own step makes that ordering unreorderable rather than merely conventional.+ workflow = self._workflow()+ install = self._step(workflow, INSTALL_STEP)++ assert "--reinstall-package torch" in install+ assert "--list-undeclared-sidecars" in install+ assert "uv pip uninstall $stale" in install+ assert install.index("--reinstall-package torch") < install.index("--list-undeclared-sidecars")+ assert workflow.index(f"- name: {INSTALL_STEP}") < workflow.index("- name: Run tests")++ def test_the_reconcile_refuses_an_absent_result_line(self):+ # An empty capture means the parse broke, not that the venv is clean: the script always+ # prints the prefix. Without this guard the step reports success while doing nothing.+ install = self._step(self._workflow(), INSTALL_STEP)++ assert f"grep -q '^{SIDECAR_PREFIX}'" in install+ assert "refusing to assume the venv is clean" in install++ def test_verification_step_checks_the_whole_environment(self):+ # Guards the regression #4199 describes: a verify step that only reads torch.__version__+ # passes a venv whose remaining packages belong to a different torch.+ verify = self._step(self._workflow(), "Verify PyTorch version")++ assert "check_torch_env.py" in verify+ assert '--channel "$TORCH_CHANNEL" --expected "$EXPECTED_PYTORCH_VERSION"' in verify+ assert 'echo "resolved=$resolved" >> "$GITHUB_OUTPUT"' in verify+ assert 'if [[ -z "$resolved" ]]; then' in verify++ def test_the_workflow_parses_the_prefixes_the_script_prints(self):+ # The two ends of the stdout contract. Rename a prefix on one side only and both the+ # uninstall and the version gate degrade to silent no-ops.+ workflow = self._workflow()++ assert f"s/^{SIDECAR_PREFIX}" in workflow+ assert f"s/^{VERSION_PREFIX} //p" in workflow