diff --git a/.github/dependency-floors-constraints.txt b/.github/dependency-floors-constraints.txt new file mode 100644 index 000000000..f57967c45 --- /dev/null +++ b/.github/dependency-floors-constraints.txt @@ -0,0 +1,124 @@ +# This file was autogenerated by uv via the following command: +# uv run python scripts/pin_dependency_floors.py +# pyproject.toml inputs sha256: 9c0622ae03c69f6d107eecec35bea0afba93c5e804f47454884cdc330308b34a +absl-py==2.4.0 +aiohappyeyeballs==2.6.1 +aiohttp==3.13.5 +aiosignal==1.4.0 +annotated-doc==0.0.4 +annotated-types==0.7.0 +anyio==4.13.0 +attrs==26.1.0 +av==17.1.0 +cachetools==6.2.6 +certifi==2026.2.25 +cffi==2.0.0 +charset-normalizer==3.4.7 +click==8.3.1 +cloudpickle==3.1.2 +cryptography==49.0.0 +cuda-bindings==13.5.0 +cuda-pathfinder==1.5.0 +cuda-toolkit==13.0.2 +databricks-sdk==0.103.0 +datasets==3.5.1 +dill==0.3.8 +docker-pycreds==0.4.0 +fastapi==0.139.2 +filelock==3.25.2 +frozenlist==1.8.0 +fsspec==2025.3.0 +gitdb==4.0.12 +gitpython==3.1.46 +google-auth==2.56.2 +grpcio==1.80.0 +h11==0.16.0 +hf-xet==1.4.3 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==1.8.0 +idna==3.11 +importlib-metadata==8.9.0 +iniconfig==2.3.0 +jinja2==3.1.6 +markdown==3.10.2 +markdown-it-py==4.0.0 +markupsafe==3.0.3 +mdurl==0.1.2 +mlflow-skinny==3.1.0 +mpmath==1.3.0 +multidict==6.7.1 +multiprocess==0.70.16 +networkx==3.6.1 +numpy==1.26.1 +nvidia-cublas==13.1.1.3 +nvidia-cuda-cupti==13.0.85 +nvidia-cuda-nvrtc==13.0.88 +nvidia-cuda-runtime==13.0.96 +nvidia-cudnn-cu13==9.20.0.48 +nvidia-cufft==12.0.0.61 +nvidia-cufile==1.15.1.6 +nvidia-curand==10.4.0.35 +nvidia-cusolver==12.0.4.66 +nvidia-cusparse==12.6.3.3 +nvidia-cusparselt-cu13==0.8.1 +nvidia-ml-py==11.470.66 +nvidia-nccl-cu13==2.29.7 +nvidia-nvjitlink==13.0.88 +nvidia-nvshmem-cu13==3.4.5 +nvidia-nvtx==13.0.85 +opentelemetry-api==1.44.0 +opentelemetry-sdk==1.44.0 +opentelemetry-semantic-conventions==0.65b0 +packaging==25.0 +pandas==2.1.2 +pillow==10.0.0 +platformdirs==4.9.4 +pluggy==1.6.0 +propcache==0.4.1 +protobuf==5.29.6 +psutil==5.9.4 +pyarrow==15.0.0 +pyasn1==0.6.4 +pyasn1-modules==0.4.2 +pycparser==3.0 +pydantic==2.12.5 +pydantic-core==2.41.5 +pygments==2.20.0 +pytest==9.0.2 +pytest-timeout==2.4.0 +python-dateutil==2.9.0.post0 +pytz==2026.6 +pyyaml==6.0.1 +regex==2026.3.32 +requests==2.33.1 +rich==14.3.3 +safetensors==0.7.0 +sentry-sdk==2.57.0 +setproctitle==1.3.8 +setuptools==81.0.0 +shellingham==1.5.4 +six==1.17.0 +smmap==5.0.3 +sqlparse==0.5.5 +starlette==1.0.0 +sympy==1.14.0 +tensorboard==2.17.1 +tensorboard-data-server==0.7.2 +tokenizers==0.22.1 +torch==2.12.0+cu130 +torchao==0.18.0 +tqdm==4.67.3 +transformers==5.4.0 +triton==3.7.0 +typer==0.24.1 +typing-extensions==4.15.0 +typing-inspection==0.4.2 +tzdata==2026.6 +urllib3==2.6.3 +uvicorn==0.44.0 +wandb==0.17.2 +werkzeug==3.1.8 +xxhash==3.6.0 +yarl==1.23.0 +zipp==4.1.0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 211c62f13..38075645b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -106,14 +106,13 @@ jobs: with: python-version: "3.12" - run: uv venv - # pytest and rich stay at the versions uv.lock holds (9.0.2 and 14.3.3): from pytest 9.1 a - # test that sets propagate=True captures each record twice, and from rich 14.3.4 importing - # httpx draws from Python's global random, which moves the RNG stream that - # test_streaming_resume.py checks. + - name: Check that the pins are current with pyproject.toml + run: uv run --no-sync python scripts/pin_dependency_floors.py --check - name: Install every runtime dependency at its lower bound run: >- uv pip install --resolution lowest-direct -e . --group video - "pytest>=9.0.2" "pytest-timeout>=2.4.0" --constraint <(echo "rich<14.3.4") + "pytest>=9.0.2" "pytest-timeout>=2.4.0" + --constraint .github/dependency-floors-constraints.txt - run: uv pip list # lowest-direct installs the lowest version the other requirements allow, not the declared # bound, so a bound set below what they allow would pass here without ever being installed. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab4d93c8b..caf62d644 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -210,7 +210,7 @@ CI runs on every push to `main` and every PR. Every job that runs must pass befo | Job | What it checks | Runs on | |-----|----------------|---------| | `lint` | `ruff check` + `ruff format --check` + `pyright` | Every push/PR | -| `unit-tests` | `pytest tests/unit/ -v --timeout=60` on Python 3.12 and 3.14 with `uv.lock`, and on Python 3.12 with every runtime dependency at its lower bound in `pyproject.toml` (the `unit-tests (dependency floors)` leg, which first checks that each one is installed at exactly that bound) | Manual dispatch, and pushes/PRs that change a file outside `docs/`, `examples/`, `plugins/`, `benchmarks/` and the repository files the workflow's `changes` job lists (such as `README.md`, `CONTRIBUTING.md` and `codebase-map.json`). When every changed file is in that set and one of them is `README.md` or a `.md` page under `docs/`, `examples/` or `plugins/`, the `unit-tests (doc pages)` job runs just the test that reads those pages | +| `unit-tests` | `pytest tests/unit/ -v --timeout=60` on Python 3.12 and 3.14 with `uv.lock`, and on Python 3.12 with every runtime dependency at its lower bound in `pyproject.toml` and every other package at the version `.github/dependency-floors-constraints.txt` pins (the `unit-tests (dependency floors)` leg, which first checks that those pins are current and then that each dependency is installed at exactly its bound) | Manual dispatch, and pushes/PRs that change a file outside `docs/`, `examples/`, `plugins/`, `benchmarks/` and the repository files the workflow's `changes` job lists (such as `README.md`, `CONTRIBUTING.md` and `codebase-map.json`). When every changed file is in that set and one of them is `README.md` or a `.md` page under `docs/`, `examples/` or `plugins/`, the `unit-tests (doc pages)` job runs just the test that reads those pages | | `gpu-tests` | `pytest tests/integration/` | Manual dispatch | | `-tests` | `examples//tests` in one pytest session, manual-only tiers excluded | Pushes/PRs touching `examples//`, `kempnerforge/`, `pyproject.toml`, `uv.lock` or the workflow | @@ -501,6 +501,8 @@ Always use `uv`, never pip, conda, or venv. PyTorch is pinned to the CUDA 13.0 i Every runtime dependency needs a lower bound (`uv add` writes one at the version it resolves), and every library `kempnerforge` imports must be declared, even one another dependency already installs; `tests/unit/test_check_dependency_floors.py` checks both. The `unit-tests (dependency floors)` CI leg installs each runtime dependency at its lower bound and runs the unit tests, so a bound must be a version the code works with. Its install takes the lowest version the other requirements allow, which is newer than a bound set below that, so the leg first runs `scripts/check_dependency_floors.py`: it fails, naming each one, when a dependency in `[project].dependencies` or the `video` group is installed at a version other than its lower bound, is missing, or declares no inclusive lower bound (`>=`, `~=` or `==`). Raise such a bound to the version the leg installed, and lower a bound only after that leg passes with it. +Every other package the leg installs is pinned in `.github/dependency-floors-constraints.txt`, so a new release cannot change what it tests. After changing `[project].dependencies`, the `video` group, `requires-python` or a `[tool.uv]` setting other than `default-groups` in `pyproject.toml`, run `uv run python scripts/pin_dependency_floors.py` and commit the file it rewrites: the leg checks the file before its install and fails with that command when the file is out of date, and so does `tests/unit/test_pin_dependency_floors.py`. The script resolves the leg's install with `uv pip compile`. A package keeps its pin while the new requirements allow it, and a package the file does not pin yet takes its `uv.lock` version when they allow that. To re-derive every pin from `uv.lock` where the floors allow it and `uv.lock` has a version for Linux, delete the file and run the script. + ## Quick Reference ```bash diff --git a/codebase-map.json b/codebase-map.json index 1a845ed44..cc9ef8190 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -1920,6 +1920,13 @@ "tested_by": [ "tests/unit/test_check_dependency_floors.py" ] + }, + "scripts/pin_dependency_floors.py": { + "purpose": "Writes .github/dependency-floors-constraints.txt, which pins every package the floor leg installs: uv pip compile of that install (--resolution lowest-direct, Python 3.12, x86_64 manylinux_2_28) preferring the file's own pins, then uv.lock's, and none for a declared dependency, plus a sha256 of the pyproject.toml inputs. --check compares that hash with the standard library only; the leg runs it before its install", + "entry": "main()", + "tested_by": [ + "tests/unit/test_pin_dependency_floors.py" + ] } }, "tests": { @@ -2550,6 +2557,18 @@ ], "count": 19 }, + "tests/unit/test_pin_dependency_floors.py": { + "classes": [ + "TestInputHash(5)", + "TestNames(2)", + "TestPreferences(2)", + "TestWrite(3)", + "TestRunUv(3)", + "TestCheck(3)", + "TestThisRepo(4)" + ], + "count": 22 + }, "tests/unit/test_checkpoint_numpy.py": { "classes": [ "TestTrainStateFromNumpy2(2)" diff --git a/docs/getting-started/install.md b/docs/getting-started/install.md index 2277bd249..a504b9d84 100644 --- a/docs/getting-started/install.md +++ b/docs/getting-started/install.md @@ -61,7 +61,10 @@ If all four pass, your environment is ready. not go through the lock, `pyproject.toml` gives every runtime dependency a lower bound, the oldest release KempnerForge supports. CI tests those bounds: its `unit-tests (dependency floors)` job installs every runtime dependency at -its lower bound on Python 3.12 and runs the unit tests. Before the tests, +its lower bound on Python 3.12 and runs the unit tests. Every other package it +installs is held at the version `.github/dependency-floors-constraints.txt` +pins, which `scripts/pin_dependency_floors.py` writes, so a new release +elsewhere cannot change what the job tests. Before the tests, `scripts/check_dependency_floors.py` fails the job if a dependency did not install at exactly its lower bound, which happens when the bound is lower than the other requirements allow. The commands are in `.github/workflows/ci.yml`. diff --git a/scripts/pin_dependency_floors.py b/scripts/pin_dependency_floors.py new file mode 100644 index 000000000..93982e74d --- /dev/null +++ b/scripts/pin_dependency_floors.py @@ -0,0 +1,244 @@ +"""Write, or check, the constraints that pin every package the dependency-floors CI job installs. + +The ``unit-tests (dependency floors)`` job installs with ``uv pip install +--resolution lowest-direct``, which holds each declared dependency at its lower +bound but takes every other package at its newest release, so a release of any +of them could change the job. The job therefore passes +``.github/dependency-floors-constraints.txt``, which pins every package it +installs, as ``--constraint``. + +Run without arguments, this script resolves the job's requirements as its +install does, with ``uv pip compile`` for Python 3.12 on x86_64 Linux, and +rewrites that file with a hash of the inputs it read from ``pyproject.toml``. +A package the file already pins keeps that version while the requirements allow +it, and a package it does not pin yet takes its ``uv.lock`` version when they +allow that. The declared dependencies get no such preference, so each resolves +to its lower bound. To re-derive every pin from ``uv.lock`` where the floors +allow it and ``uv.lock`` has a version for Linux, delete the file and run the +script. + +``--check`` only compares the recorded hash with ``pyproject.toml``, with no +uv or network. The job runs it before its install, which would otherwise fail +on a stale pin with a resolver error. + +Exit codes: + 0: the file was written, or is current. + 1: ``--check`` found the file missing or resolved for other inputs. + 2: pyproject.toml cannot be read or names no such group, or a uv command failed. + +Usage: + uv run python scripts/pin_dependency_floors.py + uv run --no-sync python scripts/pin_dependency_floors.py --check +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import tomllib +from collections.abc import Iterable, Mapping, Sequence +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +PYPROJECT = ROOT / "pyproject.toml" +CONSTRAINTS = ROOT / ".github" / "dependency-floors-constraints.txt" +GROUPS = ("video",) +JOB_REQUIREMENTS = ("pytest>=9.0.2", "pytest-timeout>=2.4.0") +PYTHON_VERSION = "3.12" +PYTHON_PLATFORM = "x86_64-manylinux_2_28" +COMMAND = "uv run python scripts/pin_dependency_floors.py" +HASH_PREFIX = "# pyproject.toml inputs sha256: " +NAME = re.compile(r"\s*([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)") + + +class UsageError(Exception): + """pyproject.toml names no such group, a group includes itself, or a uv command failed.""" + + +def canonical_name(name: str) -> str: + """The normalized form of a distribution or dependency group name.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def requirement_name(line: str) -> str | None: + """The normalized name a requirement or pin starts with; None for a comment or an option.""" + match = NAME.match(line) + return canonical_name(match.group(1)) if match else None + + +def group_requirements( + groups: Mapping[str, Any], name: str, seen: tuple[str, ...] = () +) -> list[str]: + """One dependency group's requirement strings, with its ``include-group`` entries expanded.""" + by_name = {canonical_name(key): key for key in groups} + key = by_name.get(canonical_name(name)) + if key is None: + raise UsageError(f"pyproject.toml has no dependency group {name!r}") + if key in seen: + raise UsageError(f"dependency group {key!r} includes itself") + found: list[str] = [] + for entry in groups[key]: + if isinstance(entry, str): + found.append(entry) + else: + found.extend(group_requirements(groups, entry["include-group"], (*seen, key))) + return found + + +def declared(pyproject: Mapping[str, Any]) -> list[str]: + """What the job asks for: the runtime dependencies, those of its groups, and its own.""" + found = list(pyproject.get("project", {}).get("dependencies", [])) + for group in GROUPS: + found.extend(group_requirements(pyproject.get("dependency-groups", {}), group)) + return [*found, *JOB_REQUIREMENTS] + + +def input_hash(pyproject: Mapping[str, Any]) -> str: + """A sha256 of what the pins are resolved from, independent of the order of dependencies. + + It covers ``requires-python``, ``[project].dependencies``, the job's dependency + groups, ``[tool.uv]`` (which holds torch's index) apart from ``default-groups``, + which only chooses the groups of project commands such as ``uv sync``, and this + script's own requirements and target. ``[build-system]`` is left out: the pins + cover what the job installs, not the isolated build of the project. + """ + project = pyproject.get("project", {}) + groups = pyproject.get("dependency-groups", {}) + uv = pyproject.get("tool", {}).get("uv", {}) + inputs = { + "requires-python": project.get("requires-python"), + "dependencies": sorted(project.get("dependencies", [])), + "groups": {group: sorted(group_requirements(groups, group)) for group in GROUPS}, + "tool.uv": {key: value for key, value in uv.items() if key != "default-groups"}, + "job": [*JOB_REQUIREMENTS, PYTHON_VERSION, PYTHON_PLATFORM], + } + return hashlib.sha256(json.dumps(inputs, sort_keys=True, default=str).encode()).hexdigest() + + +def pins(text: str) -> dict[str, str]: + """Each ``name==version`` line of a requirements file, marker included, by normalized name.""" + found: dict[str, str] = {} + for line in text.splitlines(): + name = requirement_name(line) + if name is not None and "==" in line: + found[name] = line.strip() + return found + + +def preferences(current: str, locked: str, direct: Iterable[str]) -> str: + """The pins for uv to prefer: the file's own, then ``uv.lock``'s, none for ``direct`` names.""" + skip = set(direct) + chosen = {**pins(locked), **pins(current)} + return "".join(f"{line}\n" for name, line in sorted(chosen.items()) if name not in skip) + + +def with_hash(resolved: str, digest: str) -> str: + """``uv pip compile`` output with the hash line after its header comments.""" + lines = resolved.splitlines(keepends=True) + header = 0 + while header < len(lines) and lines[header].startswith("#"): + header += 1 + return "".join([*lines[:header], f"{HASH_PREFIX}{digest}\n", *lines[header:]]) + + +def run_uv(args: Sequence[str], cwd: Path) -> str: + """Run uv in ``cwd`` and return what it prints; UsageError when it is missing or fails.""" + uv = os.environ.get("UV") or shutil.which("uv") + if uv is None: + raise UsageError("uv is not on PATH (https://docs.astral.sh/uv/)") + result = subprocess.run([uv, *args], cwd=cwd, capture_output=True, text=True, check=False) + if result.returncode != 0: + raise UsageError(f"`uv {' '.join(args)}` failed:\n{result.stderr}") + return result.stdout + + +def resolve(project: Path, preferred: str) -> str: + """``uv pip compile`` of the job's requirements in ``project``, preferring ``preferred``.""" + groups = [arg for group in GROUPS for arg in ("--group", group)] + with tempfile.TemporaryDirectory() as tmp: + requirements = Path(tmp, "requirements.in") + output = Path(tmp, "constraints.txt") + requirements.write_text("".join(f"{line}\n" for line in JOB_REQUIREMENTS)) + output.write_text(preferred) + command = ["pip", "compile", "pyproject.toml", str(requirements), *groups] + command += ["--resolution", "lowest-direct", "--python-version", PYTHON_VERSION] + command += ["--python-platform", PYTHON_PLATFORM, "--no-annotate"] + command += ["--custom-compile-command", COMMAND, "--output-file", str(output)] + run_uv(command, project) + return output.read_text() + + +def read_pyproject(path: Path) -> dict[str, Any]: + """The parsed ``pyproject.toml`` at ``path``.""" + with path.open("rb") as handle: + return tomllib.load(handle) + + +def write(pyproject_path: Path, constraints_path: Path) -> None: + """Resolve the job's pins in ``pyproject_path``'s project and write them with the hash.""" + pyproject = read_pyproject(pyproject_path) + project = pyproject_path.parent + direct = {name for name in map(requirement_name, declared(pyproject)) if name} + current = constraints_path.read_text() if constraints_path.exists() else "" + export = ["export", "--frozen", "--format", "requirements.txt", "--no-hashes"] + export += ["--no-header", "--no-annotate", "--no-emit-project", "--all-groups"] + locked = run_uv(export, project) + resolved = resolve(project, preferences(current, locked, direct)) + constraints_path.write_text(with_hash(resolved, input_hash(pyproject))) + + +def check(pyproject_path: Path, constraints_path: Path) -> str | None: + """None when the file records the hash of ``pyproject_path``'s inputs, else what is wrong.""" + if not constraints_path.exists(): + return f"{_shown(constraints_path)} does not exist" + recorded = [ + line.removeprefix(HASH_PREFIX).strip() + for line in constraints_path.read_text().splitlines() + if line.startswith(HASH_PREFIX) + ] + if recorded != [input_hash(read_pyproject(pyproject_path))]: + shown = _shown(constraints_path) + return f"{shown} is out of date: {_shown(pyproject_path)} changed since it was resolved" + return None + + +def _shown(path: Path) -> str: + """``path`` relative to the repository root when it lies inside it.""" + return str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path) + + +def main(argv: Sequence[str] | None = None) -> int: + """Write the pins, or with ``--check`` check them, and return the exit code.""" + parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0]) + parser.add_argument( + "--check", + action="store_true", + help="only check that the pins were resolved from the current pyproject.toml", + ) + args = parser.parse_args(argv) + try: + if args.check: + problem = check(PYPROJECT, CONSTRAINTS) + if problem is not None: + print(f"error: {problem}. Regenerate it with `{COMMAND}`.", file=sys.stderr) + return 1 + print(f"{_shown(CONSTRAINTS)} is current with {_shown(PYPROJECT)}.") + return 0 + write(PYPROJECT, CONSTRAINTS) + except (OSError, tomllib.TOMLDecodeError, UsageError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + print(f"Wrote {_shown(CONSTRAINTS)}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_pin_dependency_floors.py b/tests/unit/test_pin_dependency_floors.py new file mode 100644 index 000000000..9c1e2b58c --- /dev/null +++ b/tests/unit/test_pin_dependency_floors.py @@ -0,0 +1,331 @@ +"""``scripts/pin_dependency_floors.py``: the pins of every package the floor leg installs.""" + +from __future__ import annotations + +import copy +import importlib.util +import shlex +import subprocess +import sys +import tomllib +from pathlib import Path +from typing import Any + +import pytest +import yaml +from packaging.version import Version + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "pin_dependency_floors.py" +WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml" + + +def _load(name: str): + """A ``scripts/`` file as a module, registered in ``sys.modules`` as an import would be.""" + if name in sys.modules: + return sys.modules[name] + spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / f"{name}.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +pins_script = _load("pin_dependency_floors") + +PYPROJECT: dict[str, Any] = { + "project": {"requires-python": ">=3.12", "dependencies": ["torch>=2.12", "numpy>=1.26.1"]}, + "dependency-groups": {"video": ["av>=17.1.0"], "dev": ["pytest", {"include-group": "video"}]}, + "tool": {"uv": {"sources": {"torch": {"index": "pytorch-cu130"}}}}, +} + +RESOLVED = ( + "# This file was autogenerated by uv via the following command:\n" + "# uv run python scripts/pin_dependency_floors.py\n" + "av==17.1.0\n" + "certifi==2026.2.25\n" +) + + +def _changed(path: tuple[str, ...], value: Any) -> dict[str, Any]: + """A copy of ``PYPROJECT`` with the entry at ``path`` replaced by ``value``.""" + data = copy.deepcopy(PYPROJECT) + target = data + for key in path[:-1]: + target = target[key] + target[path[-1]] = value + return data + + +def _project(tmp_path: Path, av: str = "17.1.0") -> Path: + path = tmp_path / "pyproject.toml" + path.write_text( + f'[project]\nname = "example"\ndependencies = ["av>={av}"]\n\n' + "[dependency-groups]\nvideo = []\n" + ) + return path + + +class FakeUv: + """``run_uv`` stand-in: ``uv export`` prints ``locked``, ``uv pip compile`` writes RESOLVED.""" + + def __init__(self, locked: str = "av==17.2.0\ncertifi==2026.2.25\n"): + self.locked = locked + self.commands: list[list[str]] = [] + self.preferred: list[str] = [] + + def __call__(self, args, cwd): + self.commands.append(list(args)) + if args[0] == "export": + return self.locked + output = Path(args[args.index("--output-file") + 1]) + self.preferred.append(output.read_text()) + output.write_text(RESOLVED) + return "" + + +class TestInputHash: + def test_the_order_of_the_dependencies_leaves_it(self): + reordered = _changed(("project", "dependencies"), ["numpy>=1.26.1", "torch>=2.12"]) + assert pins_script.input_hash(reordered) == pins_script.input_hash(PYPROJECT) + + @pytest.mark.parametrize( + ("entry", "value"), + [ + (("project", "dependencies"), ["torch>=2.12", "numpy>=2.0.0"]), + (("project", "dependencies"), ["torch>=2.12", "numpy>=1.26.1", "einops>=0.8.0"]), + (("dependency-groups", "video"), ["av>=17.2.0"]), + (("project", "requires-python"), ">=3.13"), + (("tool", "uv", "sources"), {"torch": {"index": "pytorch-cu131"}}), + ("JOB_REQUIREMENTS", (*pins_script.JOB_REQUIREMENTS, "pytest-xdist>=3.6.1")), + ("PYTHON_VERSION", "3.13"), + ("PYTHON_PLATFORM", "aarch64-manylinux_2_28"), + ], + ) + def test_a_changed_input_changes_it(self, entry, value, monkeypatch): + """``entry`` is a path into ``pyproject.toml``, or a constant of the script's own.""" + before = pins_script.input_hash(PYPROJECT) + if isinstance(entry, str): + monkeypatch.setattr(pins_script, entry, value) + changed = PYPROJECT + else: + changed = _changed(entry, value) + assert pins_script.input_hash(changed) != before + + @pytest.mark.parametrize( + ("path", "value"), + [ + (("dependency-groups", "dev"), ["pytest", "ruff"]), + (("tool", "uv", "default-groups"), ["dev", "video"]), + (("build-system",), {"requires": ["hatchling>=1.27"]}), + ], + ) + def test_what_the_job_does_not_install_from_leaves_it(self, path, value): + """The job names its groups, and the pins do not cover the project's own build.""" + assert pins_script.input_hash(_changed(path, value)) == pins_script.input_hash(PYPROJECT) + + def test_a_group_the_job_installs_counts_the_groups_it_includes(self): + def including(av: str) -> dict[str, Any]: + groups = {"video": [{"include-group": "Codec"}], "codec": [f"av>={av}"]} + return _changed(("dependency-groups",), groups) + + assert pins_script.input_hash(including("17.1.0")) != pins_script.input_hash( + including("17.2.0") + ) + + @pytest.mark.parametrize( + ("groups", "match"), + [ + ({"dev": []}, "no dependency group 'video'"), + ({"video": [{"include-group": "video"}]}, "'video' includes itself"), + ], + ) + def test_a_missing_or_self_including_group_is_refused(self, groups, match): + with pytest.raises(pins_script.UsageError, match=match): + pins_script.input_hash(_changed(("dependency-groups",), groups)) + + +class TestNames: + def test_the_job_asks_for_the_runtime_dependencies_its_groups_and_its_own(self): + assert pins_script.declared(PYPROJECT) == [ + "torch>=2.12", + "numpy>=1.26.1", + "av>=17.1.0", + *pins_script.JOB_REQUIREMENTS, + ] + + @pytest.mark.parametrize( + ("line", "name"), + [ + ("Pillow==10.0.0", "pillow"), + ("pyright[nodejs]>=1.1.408", "pyright"), + ("nvidia-cublas==13.1.1.3 ; sys_platform == 'linux'", "nvidia-cublas"), + ("ruamel.yaml>=0.18", "ruamel-yaml"), + ("# via torch", None), + ("-e .", None), + ], + ) + def test_the_normalized_name_a_line_starts_with(self, line, name): + assert pins_script.requirement_name(line) == name + + +class TestPreferences: + LOCKED = "certifi==2026.2.25\nnumpy==2.4.4 ; python_version >= '3.12'\nrich==14.3.3\n" + + def test_the_file_pins_win_over_uv_lock_and_declared_dependencies_get_none(self): + """A preference outranks lowest-direct, so numpy, declared, must resolve to its floor.""" + current = "# header\ncertifi==2026.11.20\nnumpy==1.26.1\npytz==2026.6\n" + preferred = pins_script.preferences(current, self.LOCKED, {"numpy"}) + assert preferred == "certifi==2026.11.20\npytz==2026.6\nrich==14.3.3\n" + + def test_with_no_file_the_uv_lock_pins_keep_their_markers(self): + preferred = pins_script.preferences("", self.LOCKED, set()) + assert preferred.splitlines() == self.LOCKED.splitlines() + + +class TestWrite: + def test_writes_what_uv_resolves_with_the_input_hash_after_its_header( + self, tmp_path, monkeypatch + ): + uv = FakeUv() + monkeypatch.setattr(pins_script, "run_uv", uv) + pyproject, constraints = _project(tmp_path), tmp_path / "constraints.txt" + pins_script.write(pyproject, constraints) + digest = pins_script.input_hash(tomllib.loads(pyproject.read_text())) + resolved = RESOLVED.splitlines() + assert constraints.read_text().splitlines() == [ + *resolved[:2], + f"{pins_script.HASH_PREFIX}{digest}", + *resolved[2:], + ] + assert uv.preferred == ["certifi==2026.2.25\n"] + assert uv.commands[0][:2] == ["export", "--frozen"] and "--all-groups" in uv.commands[0] + compile_command = " ".join(uv.commands[1]) + for option in ( + "pip compile pyproject.toml", + "--group video", + "--resolution lowest-direct", + "--python-version 3.12", + "--python-platform x86_64-manylinux_2_28", + ): + assert option in compile_command + assert pins_script.check(pyproject, constraints) is None + + def test_a_second_run_prefers_what_the_file_pins(self, tmp_path, monkeypatch): + uv = FakeUv(locked="certifi==2025.1.1\nidna==3.11\n") + monkeypatch.setattr(pins_script, "run_uv", uv) + pyproject, constraints = _project(tmp_path), tmp_path / "constraints.txt" + pins_script.write(pyproject, constraints) + first = constraints.read_text() + pins_script.write(pyproject, constraints) + assert uv.preferred[1] == "certifi==2026.2.25\nidna==3.11\n" + assert constraints.read_text() == first + + def test_a_failed_uv_command_exits_2(self, tmp_path, monkeypatch, capsys): + def failing(args, cwd): + raise pins_script.UsageError("`uv export` failed") + + monkeypatch.setattr(pins_script, "run_uv", failing) + monkeypatch.setattr(pins_script, "PYPROJECT", _project(tmp_path)) + monkeypatch.setattr(pins_script, "CONSTRAINTS", tmp_path / "constraints.txt") + assert pins_script.main([]) == 2 + assert "`uv export` failed" in capsys.readouterr().err + assert not (tmp_path / "constraints.txt").exists() + + +class TestRunUv: + def test_returns_what_the_command_prints(self, tmp_path, monkeypatch): + monkeypatch.setenv("UV", sys.executable) + assert pins_script.run_uv(["-c", "print('resolved')"], tmp_path) == "resolved\n" + + def test_a_failing_command_raises_with_its_error(self, tmp_path, monkeypatch): + monkeypatch.setenv("UV", sys.executable) + with pytest.raises(pins_script.UsageError, match="no solution"): + pins_script.run_uv(["-c", "import sys; sys.exit('no solution')"], tmp_path) + + def test_no_uv_raises(self, tmp_path, monkeypatch): + monkeypatch.delenv("UV", raising=False) + monkeypatch.setattr(pins_script.shutil, "which", lambda name: None) + with pytest.raises(pins_script.UsageError, match="uv is not on PATH"): + pins_script.run_uv(["--version"], tmp_path) + + +class TestCheck: + @staticmethod + def _pinned(tmp_path: Path, pyproject: Path) -> Path: + constraints = tmp_path / "constraints.txt" + digest = pins_script.input_hash(tomllib.loads(pyproject.read_text())) + constraints.write_text(pins_script.with_hash(RESOLVED, digest)) + return constraints + + def test_a_raised_floor_asks_for_a_regeneration(self, tmp_path, monkeypatch, capsys): + constraints = self._pinned(tmp_path, _project(tmp_path)) + monkeypatch.setattr(pins_script, "PYPROJECT", _project(tmp_path, av="17.2.0")) + monkeypatch.setattr(pins_script, "CONSTRAINTS", constraints) + assert pins_script.main(["--check"]) == 1 + err = capsys.readouterr().err + assert "is out of date: " in err + assert f"Regenerate it with `{pins_script.COMMAND}`." in err + + def test_the_file_its_inputs_resolved_passes(self, tmp_path, monkeypatch, capsys): + pyproject = _project(tmp_path) + monkeypatch.setattr(pins_script, "PYPROJECT", pyproject) + monkeypatch.setattr(pins_script, "CONSTRAINTS", self._pinned(tmp_path, pyproject)) + assert pins_script.main(["--check"]) == 0 + assert "is current with" in capsys.readouterr().out + + def test_a_missing_file_or_hash_line_fails(self, tmp_path): + pyproject, constraints = _project(tmp_path), tmp_path / "constraints.txt" + assert pins_script.check(pyproject, constraints) == f"{constraints} does not exist" + constraints.write_text(RESOLVED) + assert "is out of date" in (pins_script.check(pyproject, constraints) or "") + + +class TestThisRepo: + """The committed pins: current, at every declared floor, and the ones the floor leg uses.""" + + @staticmethod + def _floor_leg_runs() -> list[str]: + """The ``run`` command of each step of the floor leg's job, ``""`` for an action.""" + workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + return [step.get("run", "") for step in workflow["jobs"]["unit-tests-floors"]["steps"]] + + def test_the_pins_are_current_as_the_floor_leg_checks_them(self): + command = [sys.executable, str(SCRIPT), "--check"] + result = subprocess.run(command, capture_output=True, text=True, timeout=60, check=False) + assert result.returncode == 0, result.stdout + result.stderr + + def test_every_declared_dependency_is_pinned_at_its_lower_bound(self): + floors_script = _load("check_dependency_floors") + pyproject = tomllib.loads(pins_script.PYPROJECT.read_text(encoding="utf-8")) + requirements = floors_script.declared_requirements(pyproject, list(pins_script.GROUPS)) + bounds = floors_script.floors(requirements) + pinned = { + name: Version(Version(line.split("==")[1].split(";")[0].strip()).public) + for name, line in pins_script.pins(pins_script.CONSTRAINTS.read_text()).items() + } + assert {name: pinned.get(name) for name in bounds} == bounds + + def test_the_floor_leg_checks_the_pins_before_its_install(self): + runs = self._floor_leg_runs() + checks = [i for i, run in enumerate(runs) if "pin_dependency_floors.py --check" in run] + installs = [i for i, run in enumerate(runs) if run.startswith("uv pip install ")] + assert len(checks) == len(installs) == 1 and checks[0] < installs[0], runs + + def test_the_floor_leg_installs_what_the_pins_were_resolved_for(self): + """Its requirements and groups are the script's, and its constraints are the pins.""" + (install,) = [run for run in self._floor_leg_runs() if run.startswith("uv pip install ")] + values: dict[str, list[str]] = { + option: [] for option in ("--resolution", "-e", "--group", "--constraint") + } + requirements: list[str] = [] + words = iter(shlex.split(install)[3:]) + for word in words: + if word in values: + values[word].append(next(words)) + else: + requirements.append(word) + assert requirements == list(pins_script.JOB_REQUIREMENTS) + assert values["--group"] == list(pins_script.GROUPS) + assert values["--constraint"] == [pins_script.CONSTRAINTS.relative_to(ROOT).as_posix()]