Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
ci: pull-request runs install a pinned upstream stack; CodSpeed starts only by hand (#1787)
Alpamys Makazhan1fc0aa870eb2
diff --git a/.github/constraints/pinned-upstream.txt b/.github/constraints/pinned-upstream.txtnew file mode 100644index 00000000..77e468a2--- /dev/null+++ b/.github/constraints/pinned-upstream.txt@@ -0,0 +1,34 @@+# The upstream stack that pull-request CI installs: exact pins, nothing else.+#+# WHAT. On a pull request and on a push to `main`, every workflow job that+# installs torch or transformers passes this file to pip with `-c`, so a new+# release of a package below cannot fail every open pull request at once. A+# constraint installs nothing: a job takes only the lines for what it installs+# (mlx-smoke, which has no torch: transformers, tokenizers, huggingface-hub and+# safetensors). `transformers-floor` uses its own file, transformers-floor.txt.+#+# WHERE A NEW RELEASE STILL SHOWS. The nightly full run of ci.yml, a manual+# dispatch, a push to `release/**` and the weekly `dependency drift` job install+# without this file. Packages that are not listed here float on every run.+#+# WHEN TO BUMP. The nightly run is green on newer versions; or it is red on a+# new release, and the pull request that fixes `main` bumps the pin so that its+# own cells run the fix; or a bound in pyproject.toml moves past a pin.+#+# HOW. Run this on Windows or macOS (on Linux it downloads the CUDA wheels):+# python -m pip install --dry-run --ignore-installed -e ".[dev]"+# Copy the versions it prints after `Would install` for the packages below, run+# `pytest --no-cov -q tests/test_ci_pinned_upstream.py`, and open a pull request+# with the `ci:full` label: its own cells then install under the new pins.+#+# FORMAT. One `name==version` per line and each package once: no range, marker,+# pip option or trailing comment. The test refuses them.+torch==2.14.1+transformers==5.19.0+tokenizers==0.23.3+huggingface-hub==2.2.0+safetensors==0.8.0+trl==0.29.1+peft==0.21.2+accelerate==1.15.0+datasets==5.1.0diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex fa326192..d1b24825 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -204,6 +204,17 @@ jobs:# status function (`always()`, `failure()`, ...) in its `if:`, or it runs on# drafts.#+ # 2026-10-12: `plan` also picks the upstream stack. QUICK and APPROVAL (every+ # pull-request run, every push to main) install under+ # .github/constraints/pinned-upstream.txt; FULL and RELEASE install with no+ # constraints and resolve the newest release of everything. So one release+ # upstream no longer fails every open pull request at once: it turns the+ # nightly run red, on `main`, once. The jobs that install the project end+ # every `pip install` with `plan`'s `constraints` output, `-c <that file>` or+ # nothing. Do not write the `-c` into a step: that pins the nightly run too,+ # and a pinned nightly run stays green and says nothing. When and how to bump+ # the pins is in the header of that file.+ ## `timeout-minutes: 5` is not a measurement: one shell step, no checkout, no# install.plan:@@ -234,9 +245,13 @@ jobs:"exclude": [{"os": "windows-latest", "python-version": "3.10"},{"os": "macos-latest", "python-version": "3.10"}]}QUICK_MATRIX: '{"os": ["ubuntu-latest"], "python-version": ["3.12"]}'+ # The pinned upstream stack, named once. QUICK and APPROVAL hand it to the+ # jobs as `-c <path>`; FULL and RELEASE hand them nothing.+ PINNED_CONSTRAINTS: .github/constraints/pinned-upstream.txtoutputs:full: ${{ steps.decide.outputs.full }}matrix: ${{ steps.decide.outputs.matrix }}+ constraints: ${{ steps.decide.outputs.constraints }}steps:- name: Choose the release, full, approval or quick matrixid: decide@@ -249,20 +264,25 @@ jobs:if [ "$RELEASE" = "true" ]; thenfull=truematrix="$RELEASE_MATRIX"+ constraints=""elif [ "$FULL" = "true" ]; thenfull=truematrix="$FULL_MATRIX"+ constraints=""elif [ "$APPROVAL" = "true" ]; thenfull=truematrix="$APPROVAL_MATRIX"+ constraints="-c $PINNED_CONSTRAINTS"elsefull=falsematrix="$QUICK_MATRIX"+ constraints="-c $PINNED_CONSTRAINTS"echo "::notice title=Quick CI run::lint and test (ubuntu-latest, 3.12) only. A pull request gets the other required test cells and the smoke jobs when a maintainer adds the ci:full label; main gets the full matrix every night."fi{echo "full=$full"echo "matrix=$matrix"+ echo "constraints=$constraints"} >> "$GITHUB_OUTPUT"lint:@@ -347,7 +367,8 @@ jobs:with:python-version: "3.12"- name: Install only the MLX runtime and smoke-test dependency- run: pip install -e ".[mlx]" pytest+ # Ends with `plan`'s stack (above `plan`); a constraint installs nothing, so torch stays absent.+ run: pip install -e ".[mlx]" pytest ${{ needs.plan.outputs.constraints }}- name: Verify MLX imports and the PyTorch training stack is absentrun: |python -c "import mlx.core, mlx_lm; print(mlx.core.__version__, mlx_lm.__version__)"@@ -377,7 +398,8 @@ jobs:- name: Install the QAT extra (torchao) beside the dev stack# One spec with both extras: `-e ".[dev]" ".[qat]"` asks pip for# soup-cli twice, once editable and once not, and resolution fails.- run: pip install -e ".[dev,qat]" "torch>=2.6.0"+ # Ends with `plan`'s stack: pinned on a pull request, the newest at night; torchao floats.+ run: pip install -e ".[dev,qat]" "torch>=2.6.0" ${{ needs.plan.outputs.constraints }}- name: Prove torchao is actually importable, so the tests do not skiprun: python -c "import torchao; print(torchao.__version__)"- name: Resolve every torchao class Soup asks for@@ -430,7 +452,8 @@ jobs:# below 2.6.0 under CVE-2025-32434. Removing this pin because "[dev]# already pulls torch" breaks the job with a message naming the CVE# rather than the cause.- run: pip install -e ".[dev]" "torch>=2.6.0"+ # Ends with `plan`'s stack: pinned on a pull request, the newest at night.+ run: pip install -e ".[dev]" "torch>=2.6.0" ${{ needs.plan.outputs.constraints }}- name: Warm tiny GPT-2 cacheshell: python@@ -585,7 +608,8 @@ jobs:# psutil extra is what `-n logical` counts the CPUs with. Installed here# and not in the dev extra: a local run stays serial unless a contributor# asks for workers.- run: pip install -e ".[dev]" "pytest-xdist[psutil]"+ # Ends with `plan`'s stack: pinned on a pull request and a push to main, the newest at night.+ run: pip install -e ".[dev]" "pytest-xdist[psutil]" ${{ needs.plan.outputs.constraints }}- name: Warm HF Hub cache (models the tests load)# Pre-download the models the unit tests load, with retries, so a# transient HF Hub 429 (Too Many Requests) on a single matrix cell doesdiff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.ymlindex d809e308..1b6c2d23 100644--- a/.github/workflows/codspeed.yml+++ b/.github/workflows/codspeed.yml@@ -36,9 +36,24 @@ name: CodSpeed# not as a pass, so it does not bring back the unearned green a silent step# skip would.#-# TO TURN IT ON: install the CodSpeed GitHub App on this repository, then set-# the repository variable CODSPEED_ENABLED to `true` (Settings > Secrets and-# variables > Actions > Variables). Remove or unset it to turn it off again.+# THE TRIGGERS ARE OFF AS WELL (2026-10-12). A job-level skip still CREATES a+# run. With the `push` and `pull_request` triggers on and the variable unset,+# every pull-request event and every push to `main` started a run whose only+# job was skipped: 201 runs in the 48 hours from 2026-10-07 13:00Z, 96 of the+# newest hundred skipped (three more waiting for approval, one failed). A+# workflow that can report nothing should not start, so until the App is+# installed the one trigger left is a manual dispatch.+#+# TO TURN IT ON, in this order:+# 1. install the CodSpeed GitHub App on this repository;+# 2. set the repository variable CODSPEED_ENABLED to `true` (Settings >+# Secrets and variables > Actions > Variables);+# 3. start this workflow by hand on `main` (Actions > CodSpeed > Run+# workflow) and see the upload succeed;+# 4. restore the two triggers commented out under `on:` below, and correct+# the `benchmark` entry in CONTRIBUTING.md, which says it is off.+# To turn it off again, comment the two triggers out; unsetting the variable+# alone brings the empty runs back.## FORK PRs NEVER RUN IT, EVEN WITH THE APP INSTALLED. GitHub does not grant# id-token: write to a pull_request run triggered from a fork, whatever this@@ -53,10 +68,12 @@ name: CodSpeed# App uninstalled later, or CodSpeed unreachable): it says so instead of# leaving a bare red.on:- push:- branches: [main]- pull_request:- branches: [main]+ # Off until the App is installed: step 4 of TO TURN IT ON above restores these.+ # push:+ # branches: [main]+ # pull_request:+ # branches: [main]+ workflow_dispatch:concurrency:group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}@@ -64,8 +81,11 @@ concurrency:jobs:benchmark:+ # `!= 'pull_request'` and not `== 'push'`, so that the manual dispatch of+ # step 3 above runs the job as a push does. A pull request still needs to+ # come from this repository.if: >-- vars.CODSPEED_ENABLED == 'true' && (github.event_name == 'push' ||+ vars.CODSPEED_ENABLED == 'true' && (github.event_name != 'pull_request' ||github.event.pull_request.head.repo.full_name == github.repository)runs-on: ubuntu-latestpermissions:diff --git a/.github/workflows/dependency-drift.yml b/.github/workflows/dependency-drift.ymlindex c43530d8..167a4728 100644--- a/.github/workflows/dependency-drift.yml+++ b/.github/workflows/dependency-drift.yml@@ -13,6 +13,12 @@# Running the same resolve on a schedule turns "we find out when someone opens a# PR" into "we find out on Monday", and writes the resolved-vs-declared table# into the run summary so the gap is visible without reading logs.+#+# 2026-10-12: the first sentence above is history. Pull-request runs and pushes+# to `main` in ci.yml now install the pinned stack in+# .github/constraints/pinned-upstream.txt; the newest stack is resolved by+# ci.yml's nightly full run and by this job, which must never take that file+# (tests/test_ci_full_matrix_on_approval.py::TestPinnedUpstream).name: dependency drifton:diff --git a/.github/workflows/recipe-attach.yml b/.github/workflows/recipe-attach.ymlindex 73ffbefb..950e7bb1 100644--- a/.github/workflows/recipe-attach.yml+++ b/.github/workflows/recipe-attach.yml@@ -37,6 +37,7 @@ on:- 'examples/**'- 'pyproject.toml'- '.github/workflows/recipe-attach.yml'+ - '.github/constraints/pinned-upstream.txt'pull_request:branches: [main]paths:@@ -51,6 +52,7 @@ on:- 'examples/**'- 'pyproject.toml'- '.github/workflows/recipe-attach.yml'+ - '.github/constraints/pinned-upstream.txt'workflow_dispatch:permissions:@@ -79,7 +81,8 @@ jobs:- name: Install the training stack# `[train]`, not `[dev]`: the attach needs torch, transformers and peft# and nothing from the test extras.- run: pip install -e ".[train]"+ # The pinned stack of ci.yml's pull-request cells on a pull request and a push; a manual run resolves the newest.+ run: pip install -e ".[train]" ${{ (github.event_name == 'pull_request' || github.event_name == 'push') && '-c .github/constraints/pinned-upstream.txt' || '' }}- name: Ratchet every shipped config's attach# Exit 2 is a new cannot-attach, or a pinned config that now attaches;# exit 1 is the command itself failing. Skipped (gated, no token) exits 0diff --git a/.github/workflows/recipe-validation.yml b/.github/workflows/recipe-validation.ymlindex d1f6a4aa..e2276260 100644--- a/.github/workflows/recipe-validation.yml+++ b/.github/workflows/recipe-validation.yml@@ -22,6 +22,7 @@ on:- 'tests/test_recipes_v031.py'- 'tests/test_recipes.py'- '.github/workflows/recipe-validation.yml'+ - '.github/constraints/pinned-upstream.txt'pull_request:branches: [main]paths:@@ -32,6 +33,7 @@ on:- 'tests/test_recipes_v031.py'- 'tests/test_recipes.py'- '.github/workflows/recipe-validation.yml'+ - '.github/constraints/pinned-upstream.txt'# Supersede, do not queue.#@@ -85,6 +87,7 @@ jobs:with:python-version: "3.11"- name: Install dependencies- run: pip install -e ".[dev]"+ # The pinned stack of ci.yml's pull-request cells: this workflow runs on pull requests and pushes only.+ run: pip install -e ".[dev]" -c .github/constraints/pinned-upstream.txt- name: Validate every recipe (parameterised pytest)run: pytest tests/test_recipes_v031.py tests/test_recipes.py -v --tb=short --no-covdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d1941d1b..2b3a0ea0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -555,12 +555,13 @@ GitHub Actions runs on every push and PR:that pin.- **benchmark** (`.github/workflows/codspeed.yml`, #1065): a CodSpeedregression benchmark, its own workflow and not part of the matrix above.- The job is **skipped** everywhere until the repository variable- `CODSPEED_ENABLED` is `true` (set once the CodSpeed GitHub App is installed),- and always on fork PRs — GitHub does not grant a `pull_request` run from a- fork an OIDC token, so the upload could not authenticate. Since most- contributions here are fork PRs, expect "skipped" on yours; it is not a- required check and blocks nothing.+ It is **off**: the workflow starts only by manual dispatch, so it adds no+ check to your pull request. Turning it on takes the CodSpeed GitHub App, the+ repository variable `CODSPEED_ENABLED` set to `true`, and the `push` /+ `pull_request` triggers restored in the workflow file (its header is the+ checklist). Even then it never runs on a fork PR — GitHub does not grant a+ `pull_request` run from a fork an OIDC token, so the upload could not+ authenticate. It is not a required check and blocks nothing.**Pull requests run a quick subset first.** A push to a pull request runs `lint`and the tests on Ubuntu / Python 3.12 only. The required cells (Ubuntu on Python@@ -577,6 +578,20 @@ branch runs every cell.draft, whatever is pushed to it. Mark it ready for review and the quick setstarts on its current head.+**Pull-request CI installs a pinned upstream stack.** On a pull request and on a+push to `main`, every job that installs torch or transformers (the test cells,+the smoke jobs, `Recipe Validation` and `recipe attach`) takes them and the+packages they resolve with at the exact versions in+`.github/constraints/pinned-upstream.txt`, so a release upstream cannot turn+every open pull request red at once. The one exception is `transformers-floor`,+which installs its own exact floor, and packages outside that file (numpy,+pydantic, mlx, torchao, ...) still resolve the newest on every run. The nightly+run on `main` installs with no constraints, and that is where a new release of+a pinned package shows first. If your change moves a+bound in `pyproject.toml` past one of those pins, move the pin in the same pull+request: `tests/test_ci_pinned_upstream.py` names the pin, and the header of the+constraints file says how to pick the new version.+**CI runs the tests in parallel.** Every `test (...)` cell runs the suite with`pytest-xdist`, one test file per worker process (`-n logical --dist loadfile`).The tests of one file still run in order in one process, but two files can rundiff --git a/tests/test_ci_full_matrix_on_approval.py b/tests/test_ci_full_matrix_on_approval.pyindex 0fa7818d..448cbf25 100644--- a/tests/test_ci_full_matrix_on_approval.py+++ b/tests/test_ci_full_matrix_on_approval.py@@ -28,6 +28,18 @@ run has reported. APPROVAL must name exactly the required contexts: a cell itdrops that branch protection still requires would lock every merge, and arequired cell it drops silently would stop being tested before merge at all.+``plan`` makes one more decision with the matrix: which upstream stack the run+installs. QUICK and APPROVAL -- every pull-request run and every push to+``main`` -- install under ``.github/constraints/pinned-upstream.txt``, so a new+release of torch or transformers cannot redden every open pull request at once.+FULL and RELEASE install with no constraints, so the same release does show, on+``main``, within a day. A nightly run that was pinned by mistake would stay+green for ever and say nothing; ``TestPinnedUpstream`` pins both directions.+``TestEveryWorkflow`` holds the other workflows to the same rule: every job of+every workflow that runs ``pip install`` is pinned on a pull request and a+push, or is on a commented list of those that are not, for a checked reason.+``tests/test_ci_pinned_upstream.py`` checks the constraints file itself.+Nothing here talks to GitHub. The workflow is read as YAML, the ``plan`` step'sshell runs under a local bash, and the expressions GitHub would evaluate areevaluated by a small interpreter for exactly the operators they use.@@ -38,6 +50,7 @@ from __future__ import annotationsimport jsonimport osimport re+import shleximport shutilimport subprocessimport sys@@ -46,9 +59,12 @@ from typing import Anyimport pytestimport yaml+from packaging.requirements import InvalidRequirement, Requirement+from packaging.utils import canonicalize_nameROOT = Path(__file__).resolve().parents[1]CI = ROOT / ".github" / "workflows" / "ci.yml"+DRIFT = ROOT / ".github" / "workflows" / "dependency-drift.yml"CONTRIBUTING = ROOT / "CONTRIBUTING.md"LABEL = "ci:full"@@ -104,6 +120,19 @@ RELEASE_ONLY_CONTEXTS = frozenset({"test (windows-latest, 3.11)", "test (macos-l#: The condition on the two jobs that wait for nothing: everything but a draft pull request.DRAFT_GATE = "github.event_name != 'pull_request' || github.event.pull_request.draft == false"UNGATED_JOBS = ("plan", "lint")+#: The pinned upstream stack, relative to the checkout: what a pull-request run and a push+#: to ``main`` install under.+PINNED_CONSTRAINTS = ".github/constraints/pinned-upstream.txt"+#: The kinds of run that install under it. FULL and RELEASE resolve the newest release of+#: everything: they are where an upstream break has to show.+PINNED_KINDS = frozenset({"QUICK", "APPROVAL"})+#: The jobs that install the project and follow ``plan``'s choice of stack.+SWITCHED_JOBS = ("test", "pytorch-smoke", "torchao-contract", "mlx-smoke")+#: ``transformers-floor`` installs under its own exact floor on every run it is part of.+FLOOR_JOB = "transformers-floor"+FLOOR_CONSTRAINTS = ".github/constraints/transformers-floor.txt"+#: How a step refers to ``plan``'s choice.+CONSTRAINTS_OUTPUT = "needs.plan.outputs.constraints"# --- Reading the workflow ----------------------------------------------------@@ -562,6 +591,7 @@ class TestPlanDecision:assert plan["outputs"] == {"full": "${{ steps.decide.outputs.full }}","matrix": "${{ steps.decide.outputs.matrix }}",+ "constraints": "${{ steps.decide.outputs.constraints }}",}@pytest.mark.parametrize(("context", "kind"), EVENTS)@@ -749,9 +779,50 @@ def _posix_bash() -> str | None:BASH = _posix_bash()+NEEDS_BASH = pytest.mark.skipif(+ BASH is None, reason="no POSIX bash found (on Windows: Git for Windows)"+)+++def _decide(tmp_path: Path, *, release: str, full: str, approval: str) -> dict[str, str]:+ """Run the plan step's shell with the given decision values; return its outputs.++ The step sees the ``plan`` job's own ``env:`` -- the four matrices and the path of+ the pinned constraints -- as it does on the runner, and what it appends to+ ``$GITHUB_OUTPUT`` comes back as ``{name: value}``: exactly ``full``, ``matrix`` and+ ``constraints``, one line each.+ """+ assert BASH is not None+ output = tmp_path / "github_output"+ output.write_text("", encoding="utf-8")+ script = tmp_path / "decide.sh"+ script.write_bytes(_decide_step()["run"].encode("utf-8"))+ env = {+ **os.environ,+ **{name: str(value) for name, value in (_plan().get("env") or {}).items()},+ **{name: _literal(name) for name in MATRIX_NAMES},+ "RELEASE": release,+ "FULL": full,+ "APPROVAL": approval,+ "GITHUB_OUTPUT": output.as_posix(),+ }+ result = subprocess.run(+ [BASH, "--noprofile", "--norc", "-eo", "pipefail", script.as_posix()],+ env=env,+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ timeout=60,+ check=False,+ )+ assert result.returncode == 0, (result.stdout, result.stderr)+ lines = output.read_text(encoding="utf-8").splitlines()+ pairs = [line.partition("=") for line in lines]+ assert [key for key, _, _ in pairs] == ["full", "matrix", "constraints"], lines+ return {key: value for key, _, value in pairs}[email protected](BASH is None, reason="no POSIX bash found (on Windows: Git for Windows)")+@NEEDS_BASHclass TestTheDecideStepScript:"""Run the plan step's own shell, as the runner would, against a fake $GITHUB_OUTPUT."""@@ -759,35 +830,8 @@ class TestTheDecideStepScript:self, tmp_path: Path, *, release: str, full: str, approval: str) -> tuple[str, Any]:"""Run the step with the given decision values; return (full, parsed matrix)."""- assert BASH is not None- output = tmp_path / "github_output"- output.write_text("", encoding="utf-8")- script = tmp_path / "decide.sh"- script.write_bytes(_decide_step()["run"].encode("utf-8"))- env = {- **os.environ,- **{name: _literal(name) for name in MATRIX_NAMES},- "RELEASE": release,- "FULL": full,- "APPROVAL": approval,- "GITHUB_OUTPUT": output.as_posix(),- }- result = subprocess.run(- [BASH, "--noprofile", "--norc", "-eo", "pipefail", script.as_posix()],- env=env,- capture_output=True,- encoding="utf-8",- errors="replace",- timeout=60,- check=False,- )- assert result.returncode == 0, (result.stdout, result.stderr)- lines = output.read_text(encoding="utf-8").splitlines()- assert len(lines) == 2, lines- full_key, _, full_value = lines[0].partition("=")- matrix_key, _, matrix_value = lines[1].partition("=")- assert (full_key, matrix_key) == ("full", "matrix"), lines- return full_value, json.loads(matrix_value)+ outputs = _decide(tmp_path, release=release, full=full, approval=approval)+ return outputs["full"], json.loads(outputs["matrix"])@pytest.mark.parametrize(("context", "kind"), EVENTS)def test_each_event_gets_its_matrix(self, tmp_path, context, kind):@@ -821,6 +865,531 @@ class TestTheDecideStepScript:assert matrix == _matrix(f"{kind}_MATRIX")assert flag == ("false" if kind == "QUICK" else "true")+ @pytest.mark.parametrize(+ ("release", "full", "approval", "kind"),+ [+ ("true", "true", "false", "RELEASE"),+ ("false", "true", "false", "FULL"),+ ("false", "true", "true", "FULL"),+ ("false", "false", "true", "APPROVAL"),+ ("false", "false", "false", "QUICK"),+ ("yes", "yes", "yes", "QUICK"),+ ("", "", "", "QUICK"),+ ],+ )+ def test_the_stack_travels_with_the_matrix(self, tmp_path, release, full, approval, kind):+ """One chain picks both, so the two cannot disagree: no seven-cell run on the+ pinned stack, and no pull-request cell that resolves the newest release."""+ outputs = _decide(tmp_path, release=release, full=full, approval=approval)+ assert json.loads(outputs["matrix"]) == _matrix(f"{kind}_MATRIX")+ assert outputs["constraints"] == (+ f"-c {PINNED_CONSTRAINTS}" if kind in PINNED_KINDS else ""+ )+++def _constraint_files(command: str) -> list[str]:+ """The files a ``pip`` command line constrains itself with, in order.++ Read as the shell reads it: a ``-c`` behind a ``#`` is a comment, not a constraint.+ """+ args = shlex.split(command, comments=True)+ files = []+ for index, arg in enumerate(args):+ if arg in ("-c", "--constraint"):+ assert index + 1 < len(args), f"`{arg}` with no file: {command!r}"+ files.append(args[index + 1])+ elif arg.startswith("--constraint="):+ files.append(arg.split("=", 1)[1])+ elif re.fullmatch(r"-c[^-\s]\S*", arg):+ files.append(arg[2:])+ return files+++#: ``pip install`` of the project itself: ``-e .`` or ``-e ".[extra, ...]"``.+_PROJECT_INSTALL = re.compile(r"""\bpip install\b[^\n]*?-e\s+["']?\.(?=[\["'\s]|$)""")+++def _project_installs(job: dict[str, Any]) -> list[str]:+ """The ``run`` of every step of *job* that installs the project."""+ runs = [str(step.get("run", "")) for step in job.get("steps", [])]+ return [run for run in runs if _PROJECT_INSTALL.search(run)]+++def _install_command(job: str, constraints: str) -> str:+ """The one command of *job* that installs the project, as the runner executes it+ when ``plan`` has output *constraints*."""+ runs = _project_installs(_jobs()[job])+ assert len(runs) == 1, (job, runs)+ return _render(runs[0], {"needs": {"plan": {"outputs": {"constraints": constraints}}}})+++def _environments(workflow: dict[str, Any]) -> list[dict[str, Any]]:+ """Every ``env:`` mapping of a workflow: its own, each job's and each step's."""+ found = [workflow.get("env") or {}]+ for job in workflow["jobs"].values():+ found.append(job.get("env") or {})+ found.extend(step.get("env") or {} for step in job.get("steps", []))+ return found+++class TestPinnedUpstream:+ """Pull-request runs and pushes to ``main`` install the pinned upstream stack; the+ nightly run, a manual dispatch, ``release/**`` and the weekly drift job resolve the+ newest. Read off the parsed workflow and the rendered commands, never off the text:+ a comment that names the constraints file satisfies nothing here."""++ def test_the_readers_have_teeth(self):+ """CONTROL for every test of this class."""+ assert _constraint_files('pip install -e ".[dev]" "pytest-xdist[psutil]"') == []+ assert _constraint_files('pip install -e ".[dev]" "torch>=2.6.0" ') == []+ assert _constraint_files("pip install -e . -c a.txt --constraint b.txt") == [+ "a.txt",+ "b.txt",+ ]+ assert _constraint_files("pip install --constraint=a.txt -cb.txt -e .") == [+ "a.txt",+ "b.txt",+ ]+ assert _constraint_files("pip install -e . # -c a.txt") == []+ with pytest.raises(AssertionError, match="with no file"):+ _constraint_files("pip install -e . -c")+ for run in (+ 'pip install -e ".[dev]" "pytest-xdist[psutil]"',+ "pip install -e '.[mlx]' pytest",+ "python -m pip install --upgrade pip\npip install -e .\n",+ "pip install -e . --no-deps",+ ):+ assert _project_installs({"steps": [{"run": run}]}) == [run], run+ others = ["pip install ruff", "pip install mypy", "pip install -e ./vendor/x", "pytest"]+ steps = [{"uses": "actions/checkout@v4"}, *({"run": run} for run in others)]+ assert _project_installs({"steps": steps}) == []++ def test_plan_declares_the_constraints_file_and_no_step_names_it(self):+ """The path is written once, in `plan`. A step that names the file itself installs+ under it on every run, the nightly one included."""+ assert (_plan().get("env") or {}).get("PINNED_CONSTRAINTS") == PINNED_CONSTRAINTS+ assert (ROOT / PINNED_CONSTRAINTS).is_file()+ for name, job in _jobs().items():+ for step in job.get("steps", []):+ assert PINNED_CONSTRAINTS not in str(step.get("run", "")), (name, step)++ @NEEDS_BASH+ @pytest.mark.parametrize(("context", "kind"), EVENTS)+ def test_each_event_installs_the_pinned_stack_or_the_newest(self, tmp_path, context, kind):+ """End to end: the event, through GitHub's expressions and the step's shell, into+ the pip command of every job that installs the project."""+ outputs = _decide(+ tmp_path,+ release=_release_for(context),+ full=_full_for(context),+ approval=_approval_for(context),+ )+ pinned = kind in PINNED_KINDS+ assert outputs["constraints"] == (f"-c {PINNED_CONSTRAINTS}" if pinned else "")+ expected = [PINNED_CONSTRAINTS] if pinned else []+ for job in SWITCHED_JOBS:+ command = _install_command(job, outputs["constraints"])+ assert _constraint_files(command) == expected, (job, command)++ @pytest.mark.parametrize("job", SWITCHED_JOBS)+ def test_a_job_installs_under_what_plan_chose_and_nothing_else(self, job):+ """The same, without the shell. With nothing chosen the command has no+ constraints at all: a `-c` of the step's own would pin the nightly run too."""+ assert "plan" in _needs(_jobs()[job])+ pinned = _install_command(job, f"-c {PINNED_CONSTRAINTS}")+ assert _constraint_files(pinned) == [PINNED_CONSTRAINTS], pinned+ newest = _install_command(job, "")+ assert _constraint_files(newest) == [], newest+ assert shlex.split(newest)[:2] == ["pip", "install"], newest++ def test_the_floor_job_installs_under_its_own_floor_on_every_run(self):+ """Its purpose is the lower bound. The pinned stack is near the upper one."""+ (run,) = _project_installs(_jobs()[FLOOR_JOB])+ assert CONSTRAINTS_OUTPUT not in run+ for chosen in (f"-c {PINNED_CONSTRAINTS}", ""):+ assert _constraint_files(_install_command(FLOOR_JOB, chosen)) == [FLOOR_CONSTRAINTS]++ def test_every_job_that_installs_the_project_is_switched_or_is_the_floor(self):+ """A new job that installs `.[dev]` on its own resolves the newest release on+ every pull request, which is the failure this switch removed."""+ installing = {name for name, job in _jobs().items() if _project_installs(job)}+ assert installing == {*SWITCHED_JOBS, FLOOR_JOB}++ def test_no_environment_variable_constrains_a_job_behind_its_command_line(self):+ """`PIP_CONSTRAINT` in an `env:` applies to every pip of that job on every run,+ and shows on no command line."""+ for environment in _environments(_workflow()):+ assert "PIP_CONSTRAINT" not in {str(key).upper() for key in environment}++ def test_the_weekly_drift_job_installs_with_no_constraints(self):+ """It exists to meet the newest release. Pinned, it would report the pins."""+ workflow = yaml.safe_load(DRIFT.read_text(encoding="utf-8"))+ installs = [+ run for job in workflow["jobs"].values() for run in _project_installs(job)+ ]+ assert len(installs) == 1, installs+ assert _constraint_files(installs[0]) == [], installs[0]+ assert CONSTRAINTS_OUTPUT not in installs[0]+ for environment in _environments(workflow):+ assert "PIP_CONSTRAINT" not in {str(key).upper() for key in environment}+++# --- Every workflow, not only ci.yml ------------------------------------------+#+# ci.yml is not the only workflow that installs the project. The two recipe+# workflows install `.[dev]` and `.[train]` on a pull request, behind a path filter,+# and they went on resolving the newest release there after ci.yml had stopped. So+# every job of every workflow that runs `pip install` is in exactly one of three+# places: a switched job of ci.yml, PINNED_ON_PR_AND_PUSH, or UNPINNED_ON_PURPOSE+# with the reason that makes it safe -- and the reason is checked, not trusted.++WORKFLOWS = ROOT / ".github" / "workflows"+PR_AND_PUSH = frozenset({"pull_request", "push"})++#: Jobs outside ci.yml that install torch or transformers on a pull request or a push.+#: They have no ``plan``: on those two events their ``pip install`` names the pinned file+#: itself, and on any other event the workflow has (a manual run) it resolves the newest.+PINNED_ON_PR_AND_PUSH = frozenset(+ {+ ("recipe-validation.yml", "validate-recipes"),+ ("recipe-attach.yml", "verify"),+ }+)++FLOOR, TOOL, CORE, NEWEST = "floor", "tool", "core", "newest"+#: Every other job that runs ``pip install``, and why it may do so without the pinned+#: file. ``_why_not`` holds each entry to its reason.+UNPINNED_ON_PURPOSE = {+ # FLOOR: its purpose is the lower bound, so it installs under its own exact file.+ (CI.name, FLOOR_JOB): FLOOR,+ # TOOL: one tool and nothing of the stack (ruff, mypy, an exact ruff, build). The+ # project is not installed and no pinned package is asked for by name.+ (CI.name, "lint"): TOOL,+ (CI.name, "type-check"): TOOL,+ ("merge-freshness.yml", "gate"): TOOL,+ ("merge-freshness.yml", "reeval-open-prs"): TOOL,+ ("publish.yml", "publish"): TOOL,+ # CORE: the project with no extra, so no torch and no transformers to pin.+ ("codspeed.yml", "benchmark"): CORE,+ # NEWEST: started by a schedule or by hand, never by a pull request or a push, and+ # there to meet the newest release.+ ("dependency-drift.yml", "latest-stack"): NEWEST,+ ("recipe-repo-ids.yml", "resolve"): NEWEST,+}+++def _workflows() -> dict[str, dict[str, Any]]:+ """Every workflow file, parsed, by file name."""+ found = {}+ for path in sorted(WORKFLOWS.iterdir()):+ if path.suffix in (".yml", ".yaml"):+ data = yaml.safe_load(path.read_text(encoding="utf-8"))+ assert isinstance(data, dict) and isinstance(data.get("jobs"), dict), path.name+ found[path.name] = data+ return found+++def _events(workflow: dict[str, Any]) -> set[str]:+ """The events a workflow starts on. PyYAML reads the bare key ``on`` as ``True``."""+ triggers = workflow.get("on", workflow.get(True))+ return {triggers} if isinstance(triggers, str) else set(triggers or ())+++_EXPRESSION = re.compile(r"(\$\{\{.*?\}\})", re.DOTALL)+_PIP_INSTALL = re.compile(r"\bpip3?\s+install\b")+_PROJECT_SPEC = re.compile(r"\.(?:\[([^\]]*)\])?")+#: pip options whose value is the next argument, and is not something to install.+_PIP_VALUE_OPTIONS = frozenset(+ {+ "-c",+ "--constraint",+ "-r",+ "--requirement",+ "-i",+ "--index-url",+ "--extra-index-url",+ "-f",+ "--find-links",+ "-t",+ "--target",+ }+)+++def _shell_commands(run: str) -> list[str]:+ """*run* split into its commands: on newlines, ``&&``, ``||`` and ``;``, but never+ inside a ``${{ }}`` expression, which spells its own operators the same way."""+ commands = [""]+ for index, part in enumerate(_EXPRESSION.split(run)):+ if index % 2: # an expression: it belongs to the command it sits in+ commands[-1] += part+ continue+ first, *rest = re.split(r"\n|&&|\|\||;", part)+ commands[-1] += first+ commands.extend(rest)+ return [command.strip() for command in commands if command.strip()]+++def _pip_commands(job: dict[str, Any]) -> list[str]:+ """Every command of *job* that runs ``pip install``, its expressions not yet rendered."""+ commands = []+ for step in job.get("steps", []):+ if "python" in str(step.get("shell", "")):+ continue # a script for another interpreter, not a command line+ for command in _shell_commands(str(step.get("run", ""))):+ if _PIP_INSTALL.search(command):+ commands.append(command)+ return commands+++def _requested(command: str) -> tuple[set[str], set[str] | None]:+ """What a rendered ``pip install`` asks for: the canonical names it spells out, and the+ extras of the project it installs -- an empty set for a bare ``.``, ``None`` when the+ project is not installed at all."""+ args = shlex.split(command, comments=True)+ assert "install" in args, command+ names: set[str] = set()+ extras: set[str] | None = None+ skip = False+ for arg in args[args.index("install") + 1 :]:+ if skip:+ skip = False+ elif arg in _PIP_VALUE_OPTIONS:+ skip = True+ elif arg.startswith("-"):+ continue # `-e` too: its value is read like any other argument+ elif (project := _PROJECT_SPEC.fullmatch(arg)) is not None:+ listed = {extra.strip() for extra in (project.group(1) or "").split(",")}+ extras = (extras or set()) | (listed - {""})+ else:+ try:+ names.add(canonicalize_name(Requirement(arg).name))+ except InvalidRequirement:+ continue # a path that is not the project+ return names, extras+++def _pinned_names() -> set[str]:+ """The packages the constraints file pins; its format is checked in+ ``tests/test_ci_pinned_upstream.py``."""+ lines = (ROOT / PINNED_CONSTRAINTS).read_text(encoding="utf-8").splitlines()+ names = {+ canonicalize_name(line.split("==")[0].strip())+ for line in lines+ if "==" in line and not line.startswith("#")+ }+ assert names, f"{PINNED_CONSTRAINTS} pins nothing"+ return names+++def _contexts(workflow: dict[str, Any]) -> list[dict[str, Any]]:+ """One context per event the workflow starts on and per choice ``plan`` can make."""+ return [+ {+ "github": {"event_name": event},+ "needs": {"plan": {"outputs": {"constraints": chosen}}},+ }+ for event in sorted(_events(workflow))+ for chosen in (f"-c {PINNED_CONSTRAINTS}", "")+ ]+++def _why_not(kind: str, workflow: dict[str, Any], job: dict[str, Any]) -> list[str]:+ """What is wrong with *job* installing unpinned for the reason *kind*; empty if it holds."""+ assert kind in (FLOOR, TOOL, CORE, NEWEST), kind+ problems = set()+ started_by = _events(workflow) & {*PR_AND_PUSH, "pull_request_target"}+ if kind == NEWEST and started_by:+ problems.add(f"starts on {sorted(started_by)}, where the newest release must not decide")+ pinned = _pinned_names()+ for context in _contexts(workflow):+ for command in _pip_commands(job):+ rendered = _render(command, context)+ names, extras = _requested(rendered)+ files = _constraint_files(rendered)+ if kind == FLOOR and files != [FLOOR_CONSTRAINTS]:+ problems.add(f"is not under its floor file alone: {rendered}")+ if kind == NEWEST and files:+ problems.add(f"is constrained, and so does not meet the newest: {rendered}")+ if kind == TOOL and extras is not None:+ problems.add(f"installs the project: {rendered}")+ if kind == CORE and extras:+ problems.add(f"installs the extra {sorted(extras)}: {rendered}")+ if kind in (TOOL, CORE) and names & pinned:+ problems.add(f"asks for {sorted(names & pinned)} by name, unpinned: {rendered}")+ return sorted(problems)+++def pinned_job_extras() -> set[str]:+ """The extras of the project that a pinned job installs, read off the workflows.++ ``tests/test_ci_pinned_upstream.py`` holds every pin to the bounds these extras+ declare and to no others: an extra that no pinned job installs cannot make a+ pull-request cell unresolvable.+ """+ workflows = _workflows()+ context = {+ "github": {"event_name": "pull_request"},+ "needs": {"plan": {"outputs": {"constraints": f"-c {PINNED_CONSTRAINTS}"}}},+ }+ extras: set[str] = set()+ for file, name in {*((CI.name, job) for job in SWITCHED_JOBS), *PINNED_ON_PR_AND_PUSH}:+ for command in _pip_commands(workflows[file]["jobs"][name]):+ extras |= _requested(_render(command, context))[1] or set()+ return extras+++def _synthetic(run: str, *events: str) -> tuple[dict[str, Any], dict[str, Any]]:+ """A one-job workflow that starts on *events* and runs *run*."""+ job = {"steps": [{"uses": "actions/checkout@v4"}, {"run": run}]}+ return {"on": {event: None for event in events}, "jobs": {"job": job}}, job+++class TestEveryWorkflow:+ """Every job of every workflow that runs ``pip install`` is pinned on a pull request+ and a push, or is on the commented list of those that are not, for a checked reason."""++ def test_the_readers_have_teeth(self):+ """CONTROL for every test of this class."""+ expression = "${{ (a == 'x' || a == 'y') && '-c f.txt' || '' }}"+ assert _shell_commands(f"pip install -e . {expression}\npytest -q && echo ok; ls") == [+ f"pip install -e . {expression}",+ "pytest -q",+ "echo ok",+ "ls",+ ]+ job = {+ "steps": [+ {"run": "python -m pip install --upgrade pip && pip install -e '.[dev]'"},+ {"shell": "python", "run": "print('pip install nothing')"},+ {"run": "pytest tests/"},+ {"uses": "actions/checkout@v4"},+ ]+ }+ assert _pip_commands(job) == [+ "python -m pip install --upgrade pip",+ "pip install -e '.[dev]'",+ ]+ assert _requested('pip install -e ".[dev, qat]" "torch>=2.6.0" -c pins.txt') == (+ {"torch"},+ {"dev", "qat"},+ )+ assert _requested("pip install -e . pytest Pytest_Codspeed") == (+ {"pytest", "pytest-codspeed"},+ set(),+ )+ assert _requested("pip install '.[train]' -r reqs.txt") == (set(), {"train"})+ assert _requested("pip install ruff==0.16.0 -e ./vendor/x") == ({"ruff"}, None)+ assert _events({True: {"push": None, "schedule": []}}) == {"push", "schedule"}+ assert _events({"on": ["push", "pull_request"]}) == {"push", "pull_request"}+ assert _events({"on": "workflow_dispatch"}) == {"workflow_dispatch"}+ assert {"torch", "transformers", "huggingface-hub"} <= _pinned_names()++ @pytest.mark.parametrize(+ ("kind", "run", "events", "problem"),+ [+ (TOOL, "pip install ruff", ("pull_request",), None),+ (TOOL, 'pip install -e ".[dev]"', ("pull_request",), "installs the project"),+ (TOOL, "pip install -e . ruff", ("push",), "installs the project"),+ (TOOL, "pip install ruff && pip install -U torch", ("push",), "by name, unpinned"),+ (TOOL, "pip install huggingface_hub", ("schedule",), "by name, unpinned"),+ (CORE, "pip install -e . pytest", ("pull_request",), None),+ (CORE, 'pip install -e ".[train]" pytest', ("pull_request",), "installs the extra"),+ (CORE, "pip install -e . transformers", ("pull_request",), "by name, unpinned"),+ (NEWEST, 'pip install -e ".[dev,audio]"', ("schedule", "workflow_dispatch"), None),+ (NEWEST, 'pip install -e ".[dev]"', ("schedule", "pull_request"), "starts on"),+ (NEWEST, 'pip install -e ".[dev]"', ("push",), "starts on"),+ (NEWEST, 'pip install -e ".[dev]"', ("pull_request_target",), "starts on"),+ (NEWEST, 'pip install -e ".[dev]" -c x.txt', ("schedule",), "is constrained"),+ (FLOOR, f'pip install -e ".[dev]" -c {FLOOR_CONSTRAINTS}', ("push",), None),+ (FLOOR, 'pip install -e ".[dev]"', ("push",), "not under its floor file"),+ (FLOOR, f'pip install -e ".[dev]" -c {PINNED_CONSTRAINTS}', ("push",), "not under"),+ ],+ )+ def test_a_reason_is_checked_and_not_trusted(self, kind, run, events, problem):+ """CONTROL: listing a job as unpinned on purpose does not make it so."""+ workflow, job = _synthetic(run, *events)+ problems = _why_not(kind, workflow, job)+ if problem is None:+ assert problems == []+ else:+ assert any(problem in found for found in problems), problems++ def test_every_job_that_runs_pip_install_is_on_exactly_one_list(self):+ """A new workflow that installs `.[dev]` or `.[train]` on a pull request lands here:+ it is on no list until someone pins it, or writes down why it need not be."""+ found = {+ (file, name)+ for file, workflow in _workflows().items()+ for name, job in workflow["jobs"].items()+ if _pip_commands(job)+ }+ switched = {(CI.name, job) for job in SWITCHED_JOBS}+ unpinned = set(UNPINNED_ON_PURPOSE)+ assert not switched & PINNED_ON_PR_AND_PUSH+ assert not (switched | PINNED_ON_PR_AND_PUSH) & unpinned+ classified = switched | PINNED_ON_PR_AND_PUSH | unpinned+ assert sorted(found - classified) == [], (+ "these jobs run `pip install` and are on no list: give them the pinned stack "+ "(PINNED_ON_PR_AND_PUSH) or say why not (UNPINNED_ON_PURPOSE)"+ )+ assert sorted(classified - found) == [], "listed, but no such job runs `pip install`"++ @pytest.mark.parametrize(("file", "name"), sorted(PINNED_ON_PR_AND_PUSH))+ def test_a_job_outside_ci_installs_the_pinned_stack_on_a_pull_request_and_a_push(+ self, file, name+ ):+ """Every `pip install` of the job, on every event the workflow starts on: the pinned+ file on a pull request and a push, no constraint on a manual run."""+ workflow = _workflows()[file]+ events = _events(workflow)+ assert events & PR_AND_PUSH, f"{file} starts on neither: it belongs on the NEWEST list"+ commands = _pip_commands(workflow["jobs"][name])+ assert commands, (file, name)+ for event in sorted(events):+ expected = [PINNED_CONSTRAINTS] if event in PR_AND_PUSH else []+ for command in commands:+ rendered = _render(command, {"github": {"event_name": event}})+ assert _constraint_files(rendered) == expected, (event, rendered)++ @pytest.mark.parametrize(("file", "name"), sorted(PINNED_ON_PR_AND_PUSH))+ def test_a_pin_bump_starts_the_path_filtered_job(self, file, name):+ """A pull request that only moves a pin has to run every job that installs under+ it. Filtered out, a bad pin fails the next unrelated pull request to touch a recipe."""+ workflow = _workflows()[file]+ triggers = workflow.get("on", workflow.get(True))+ filtered = 0+ for event in sorted(PR_AND_PUSH & set(triggers)):+ trigger = triggers[event] or {}+ assert "paths-ignore" not in trigger, (file, event)+ if "paths" in trigger:+ filtered += 1+ assert PINNED_CONSTRAINTS in trigger["paths"], (file, event)+ assert filtered, f"{file} has no path filter left: drop it from this test's reach"++ @pytest.mark.parametrize("job", SWITCHED_JOBS)+ def test_every_pip_install_of_a_switched_job_ends_with_what_plan_chose(self, job):+ """Not only the one that installs the project: a later `pip install --upgrade torch`+ in the same job would undo the pin on a pull request without touching that line."""+ commands = _pip_commands(_jobs()[job])+ assert commands, job+ for chosen, expected in ((f"-c {PINNED_CONSTRAINTS}", [PINNED_CONSTRAINTS]), ("", [])):+ context = {"needs": {"plan": {"outputs": {"constraints": chosen}}}}+ for command in commands:+ rendered = _render(command, context)+ assert _constraint_files(rendered) == expected, rendered++ @pytest.mark.parametrize(("file", "name"), sorted(UNPINNED_ON_PURPOSE))+ def test_an_unpinned_install_is_what_its_reason_says(self, file, name):+ workflow = _workflows()[file]+ kind = UNPINNED_ON_PURPOSE[(file, name)]+ assert _why_not(kind, workflow, workflow["jobs"][name]) == [], (file, name, kind)++ def test_the_extras_the_pinned_jobs_install(self):+ """What `tests/test_ci_pinned_upstream.py` checks the pins against. A job that starts+ installing another extra adds its bounds to that check; update this with it."""+ assert pinned_job_extras() == {"dev", "qat", "mlx", "train"}+class TestADraftRunsNothing:"""A draft costs no runner: the two jobs that wait for nothing are skipped by theirdiff --git a/tests/test_ci_pinned_upstream.py b/tests/test_ci_pinned_upstream.pynew file mode 100644index 00000000..5fb5bf92--- /dev/null+++ b/tests/test_ci_pinned_upstream.py@@ -0,0 +1,400 @@+"""The upstream stack that pull-request CI installs is pinned, and the pins are sound.++A new release of torch, transformers or one of their companions fails for a reason no+contributor can fix from their branch, and it used to fail on every open pull request at+once, because every CI cell resolved the newest release on every run. ``pyproject.toml``+keeps one such day on record: ``datasets`` 5.1.0 dropped a dependency that ``trl`` imports+without declaring, and from that day a fresh install could not import two trainers.++So the runs a contributor sees -- every pull-request run and every push to ``main`` --+install under ``.github/constraints/pinned-upstream.txt``, and the runs that exist to meet+a new release -- the nightly full run, a manual dispatch, a push to ``release/**`` and the+weekly ``dependency drift`` job -- still resolve the newest. Which run gets which is the+``plan`` job's decision; ``tests/test_ci_full_matrix_on_approval.py`` pins that, event by+event, through the step's own shell. This file pins the constraints file itself:++* one line per package, an exact ``name==version`` and nothing else, no package twice --+ a range or a bare name is a pin that pins nothing, and a second line for one package is+ at best noise and at worst two pins ``pip`` cannot satisfy together;+* every pinned version inside every bound ``pyproject.toml`` declares for that package,+ in its core dependencies and in the extras a pinned job installs (read off the+ workflows) -- outside one, ``pip`` cannot resolve the cell at all, so a pull request+ that moves a bound moves the pin with it. An extra no pinned job installs is not read.++``pyproject.toml`` is read with regular expressions, not ``tomllib``, which is 3.11+ while+this repository supports 3.10: the convention of ``tests/test_requires_python_bound.py``.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from pathlib import Path++import pytest+from packaging.requirements import InvalidRequirement, Requirement+from packaging.utils import canonicalize_name+from packaging.version import InvalidVersion, Version++from tests.test_ci_full_matrix_on_approval import pinned_job_extras++ROOT = Path(__file__).resolve().parents[1]+PINNED = ROOT / ".github" / "constraints" / "pinned-upstream.txt"+PYPROJECT = ROOT / "pyproject.toml"+CONTRIBUTING = ROOT / "CONTRIBUTING.md"++#: What must not float on a pull request: torch, transformers and the four libraries the+#: `[train]` extra declares beside them, plus the three that transformers resolves with+#: (tokenizers, huggingface-hub and safetensors, which it bounds itself). A pin may be+#: added; dropping one of these lets that package float on pull requests again.+HEAVY_STACK = frozenset(+ {+ "torch",+ "transformers",+ "trl",+ "peft",+ "accelerate",+ "datasets",+ "tokenizers",+ "huggingface-hub",+ "safetensors",+ }+)+#: The ones ``pyproject.toml`` bounds directly. If the reader below stops finding one of+#: these, the bound check has gone vacuous, not green.+DECLARED_IN_PYPROJECT = frozenset(+ {"torch", "transformers", "trl", "peft", "accelerate", "datasets", "huggingface-hub"}+)+++# --- Reading the constraints file ---------------------------------------------+++def _pins(text: str) -> dict[str, str]:+ """Every pin in *text*, as ``{name: version}``; anything that is not one fails.++ A line is blank, a comment that starts the line, or exactly ``name==version`` with+ the name in its canonical spelling. Inline comments, ranges, wildcards, extras,+ markers, URLs and pip options are all refused: each of them is a way for a line to+ look like a pin and constrain nothing, or to change what every other line means.+ """+ pins: dict[str, str] = {}+ for number, raw in enumerate(text.splitlines(), start=1):+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ where = f"{PINNED.name}:{number}: {raw!r}"+ try:+ requirement = Requirement(line)+ except InvalidRequirement as exc:+ raise AssertionError(f"{where} is not a requirement pip can pin: {exc}") from exc+ clauses = list(requirement.specifier)+ assert (+ len(clauses) == 1+ and clauses[0].operator == "=="+ and not clauses[0].version.endswith(".*")+ ), f"{where} is not an exact pin: write one `name==version`, no range and no wildcard"+ assert (+ not requirement.extras and requirement.marker is None and requirement.url is None+ ), f"{where} carries an extra, a marker or a URL: a pin here is `name==version` only"+ version = clauses[0].version+ try:+ parsed = Version(version)+ except InvalidVersion as exc:+ raise AssertionError(f"{where} pins a version that does not parse: {exc}") from exc+ assert parsed.local is None, f"{where} pins a local version, which PyPI never serves"+ name = canonicalize_name(requirement.name)+ assert line == f"{name}=={version}", (+ f"{where} must be spelled `{name}=={version}`: the canonical name, no spaces and "+ "no trailing comment, so that one grep finds the pin"+ )+ assert name not in pins, (+ f"{where} pins {name} a second time (already =={pins[name]}): pip refuses "+ "two different pins and a reader cannot tell which one is meant"+ )+ pins[name] = version+ return pins+++def _committed_pins() -> dict[str, str]:+ assert PINNED.is_file(), f"{PINNED.relative_to(ROOT).as_posix()} is missing"+ return _pins(PINNED.read_text(encoding="utf-8"))+++# --- Reading pyproject.toml -----------------------------------------------------+++#: The project's own name: an extra that lists ``soup-cli[train]`` installs ``train`` too.+PROJECT = "soup-cli"+++def _requirements(block: str) -> list[Requirement]:+ """Every quoted requirement in a block of pyproject.toml, comment lines left out."""+ code = "\n".join(line for line in block.splitlines() if not line.lstrip().startswith("#"))+ return [Requirement(raw) for raw in re.findall(r'"([^"\n]+)"', code)]+++def _extras(text: str) -> dict[str, list[Requirement]]:+ """The ``[project.optional-dependencies]`` table: each extra with its requirements."""+ table = re.search(r"^\[project\.optional-dependencies\]\n(.*?)(?=^\[)", text, re.M | re.S)+ assert table is not None, "pyproject.toml has no [project.optional-dependencies] table"+ code = "\n".join(+ line for line in table.group(1).splitlines() if not line.lstrip().startswith("#")+ )+ # An array ends at a `]` that ends its line; the `]` of `soup-cli[train]` does not.+ arrays = re.findall(r"^([A-Za-z0-9_-]+)\s*=\s*\[(.*?)\]\s*$", code, re.M | re.S)+ return {canonicalize_name(name): _requirements(body) for name, body in arrays}+++def _declared(text: str, installed: Iterable[str]) -> dict[str, list[Requirement]]:+ """What a cell that installs the *installed* extras is bound by, by canonical name.++ The core dependencies, and each of those extras followed through self-references such+ as ``soup-cli[train,mcp,data]``. An extra that is not installed is not read.+ """+ core = re.search(r"^dependencies\s*=\s*\[\n(.*?)^\]", text, re.M | re.S)+ assert core is not None, "pyproject.toml has no [project] dependencies array"+ requirements = _requirements(core.group(1))+ table = _extras(text)+ pending = [canonicalize_name(extra) for extra in installed]+ seen: set[str] = set()+ while pending:+ extra = pending.pop()+ if extra in seen:+ continue+ seen.add(extra)+ assert extra in table, f"pyproject.toml declares no extra `{extra}`: {sorted(table)}"+ for requirement in table[extra]:+ requirements.append(requirement)+ if canonicalize_name(requirement.name) == PROJECT:+ pending.extend(canonicalize_name(inner) for inner in requirement.extras)+ declared: dict[str, list[Requirement]] = {}+ for requirement in requirements:+ declared.setdefault(canonicalize_name(requirement.name), []).append(requirement)+ return declared+++def _bounds() -> dict[str, list[Requirement]]:+ """The bounds on the committed tree: core plus the extras the pinned jobs install."""+ return _declared(PYPROJECT.read_text(encoding="utf-8"), pinned_job_extras())+++def _out_of_bounds(pins: dict[str, str], declared: dict[str, list[Requirement]]) -> list[str]:+ """One message per pin that a declared bound does not admit."""+ problems = []+ for name, version in sorted(pins.items()):+ for requirement in declared.get(name, []):+ if not requirement.specifier.contains(Version(version), prereleases=True):+ problems.append(+ f"{name}=={version} is outside pyproject.toml's `{requirement}`"+ )+ return problems+++# --- The file is a list of exact pins ------------------------------------------+++class TestTheReaderHasTeeth:+ """CONTROL. The checks on the committed file are only as good as this reader."""++ def test_comments_and_blank_lines_are_skipped_and_pins_are_read(self):+ text = "# a header\n\ntorch==2.14.1\n # indented comment\nhuggingface-hub==2.2.0\n"+ assert _pins(text) == {"torch": "2.14.1", "huggingface-hub": "2.2.0"}++ @pytest.mark.parametrize(+ "line",+ [+ "numpy", # a bare name constrains nothing+ "numpy>=2.0",+ "numpy<3",+ "torch~=2.14",+ "torch!=2.14.0",+ "torch==2.14.*",+ "torch===2.14.1",+ "torch==2.14.1,<3",+ "torch>=2.14.1,==2.14.1",+ ],+ )+ def test_a_line_that_does_not_pin_one_exact_version_is_refused(self, line):+ with pytest.raises(AssertionError, match="not an exact pin"):+ _pins(f"transformers==5.19.0\n{line}\n")++ @pytest.mark.parametrize(+ "line",+ [+ "torch[opt-einsum]==2.14.1",+ "torch==2.14.1; python_version < '3.12'",+ "torch==2.14.1 ; sys_platform == 'linux'",+ ],+ )+ def test_an_extra_or_a_marker_is_refused(self, line):+ with pytest.raises(AssertionError, match="an extra, a marker or a URL"):+ _pins(f"{line}\n")++ @pytest.mark.parametrize(+ "line",+ [+ "-r other.txt",+ "-c other.txt",+ "--extra-index-url https://example.invalid/simple",+ "-e .",+ "torch @ https://example.invalid/torch-2.14.1-py3-none-any.whl",+ "torch==2.14.1 --hash=sha256:" + "0" * 64,+ "torch==2.14.1 # the newest",+ "torch == 2.14.1",+ "Torch==2.14.1",+ "huggingface_hub==2.2.0",+ "torch==2.14.1+cpu",+ "torch==",+ "==2.14.1",+ ],+ )+ def test_an_option_a_url_or_another_spelling_is_refused(self, line):+ with pytest.raises(AssertionError):+ _pins(f"{line}\n")++ @pytest.mark.parametrize(+ "second",+ ["torch==2.14.1", "torch==2.13.0"],+ ids=["same-version", "another-version"],+ )+ def test_a_package_listed_twice_is_refused(self, second):+ with pytest.raises(AssertionError, match="a second time"):+ _pins(f"torch==2.14.1\ntransformers==5.19.0\n{second}\n")+++class TestTheCommittedFile:+ def test_every_line_is_one_exact_pin_and_no_package_is_listed_twice(self):+ pins = _committed_pins()+ assert pins, "the constraints file pins nothing"++ def test_the_heavy_stack_is_pinned(self):+ missing = HEAVY_STACK - set(_committed_pins())+ assert not missing, (+ f"{sorted(missing)} float on pull requests again: the next release of one of "+ "them fails every open pull request at once"+ )++ def test_it_says_when_and_how_to_bump_it(self):+ """The header is the procedure: a pinned file nobody knows how to move goes stale,+ and stale pins are how a pull request stays green on versions no user installs."""+ header = []+ for line in PINNED.read_text(encoding="utf-8").splitlines():+ if line.strip() and not line.startswith("#"):+ break+ header.append(line.lstrip("#").strip())+ text = " ".join(" ".join(header).split())+ assert "nightly" in text, "say which run has to be green on the newer versions"+ assert "pyproject.toml" in text, "say that a bound that moves takes its pin with it"+ assert 'python -m pip install --dry-run --ignore-installed -e ".[dev]"' in text, (+ "give the command that prints the versions to copy"+ )+ assert "tests/test_ci_pinned_upstream.py" in text, "name the test that checks a bump"+++# --- Every pin lies inside pyproject's bound -------------------------------------+++class TestPinsLieInsideTheDeclaredBounds:+ def test_the_bounds_of_the_declared_stack_were_found(self):+ """CONTROL: an empty reading of pyproject.toml would pass the check below."""+ declared = _bounds()+ missing = DECLARED_IN_PYPROJECT - set(declared)+ assert not missing, f"no declaration found in pyproject.toml for {sorted(missing)}"+ unbounded = sorted(+ name+ for name in DECLARED_IN_PYPROJECT+ if not any(len(requirement.specifier) for requirement in declared[name])+ )+ assert not unbounded, f"{unbounded} are declared with no version bound at all"++ def test_every_pin_is_inside_every_bound_pyproject_declares_for_it(self):+ problems = _out_of_bounds(_committed_pins(), _bounds())+ assert not problems, (+ "; ".join(problems)+ + ". pip cannot resolve a pull-request cell under such a pin. Move the pin "+ f"inside the bound: the header of {PINNED.relative_to(ROOT).as_posix()} says how"+ )++ @pytest.mark.parametrize(+ ("pin", "bound"),+ [+ ({"transformers": "6.0.0"}, "transformers>=5.16.1,<6.0.0"),+ ({"transformers": "5.16.0"}, "transformers>=5.16.1,<6.0.0"),+ ({"trl": "1.15.0"}, "trl>=0.29.0,<1.0.0"),+ ({"torch": "2.5.1"}, "torch>=2.6.0"),+ ({"huggingface-hub": "0.15.0"}, "huggingface_hub>=0.16.0"),+ ],+ )+ def test_a_pin_outside_a_bound_is_reported(self, pin, bound):+ """CONTROL, over both ends of a range and over a name spelled two ways."""+ requirement = Requirement(bound)+ declared = {canonicalize_name(requirement.name): [requirement]}+ (name, version), = pin.items()+ assert _out_of_bounds(pin, declared) == [+ f"{name}=={version} is outside pyproject.toml's `{requirement}`"+ ]++ PYPROJECT_LIKE = (+ "[project]\n"+ "dependencies = [\n"+ ' "huggingface-hub>=0.16.0",\n'+ "]\n\n"+ "[project.optional-dependencies]\n"+ "train = [\n"+ " # a comment with a \"quoted\" word\n"+ ' "transformers>=5.16.1,<6.0.0",\n'+ "]\n"+ 'dev = ["soup-cli[train,data]", "pytest>=7.0"]\n'+ 'data = ["datasketch>=1.6.0"]\n'+ 'mlx = ["mlx-lm>=0.31.3", "transformers>=5.20.0,<6.0.0"]\n'+ 'legacy = ["transformers<5.0.0", "optimum[onnxruntime]>=1.16.0"]\n'+ "\n[project.scripts]\n"+ )++ def test_a_pin_is_checked_against_every_installed_extra_that_declares_the_package(self):+ """Through the self-reference too: `dev` installs `train`, so `train` binds."""+ declared = _declared(self.PYPROJECT_LIKE, {"dev", "mlx"})+ assert sorted(declared) == [+ "datasketch",+ "huggingface-hub",+ "mlx-lm",+ "pytest",+ "soup-cli",+ "transformers",+ ]+ assert len(declared["transformers"]) == 2+ narrower = Requirement("transformers>=5.20.0,<6.0.0")+ assert _out_of_bounds({"transformers": "5.19.0"}, declared) == [+ f"transformers==5.19.0 is outside pyproject.toml's `{narrower}`"+ ]+ assert _out_of_bounds({"transformers": "5.20.1", "tokenizers": "0.23.3"}, declared) == []++ def test_an_extra_no_pinned_job_installs_cannot_fail_the_check(self):+ """`legacy` wants transformers below 5. No cell installs it, so it binds no cell."""+ assert sorted(_extras(self.PYPROJECT_LIKE)) == ["data", "dev", "legacy", "mlx", "train"]+ only_dev = _declared(self.PYPROJECT_LIKE, {"dev"})+ assert _out_of_bounds({"transformers": "5.19.0"}, only_dev) == []+ with_legacy = _declared(self.PYPROJECT_LIKE, {"dev", "legacy"})+ assert len(_out_of_bounds({"transformers": "5.19.0"}, with_legacy)) == 1+ with pytest.raises(AssertionError, match="declares no extra `nope`"):+ _declared(self.PYPROJECT_LIKE, {"nope"})++ def test_the_real_extras_are_read_and_followed(self):+ """CONTROL on the committed pyproject.toml: `dev` reaches torch through `train`,+ `mlx` alone does not, and both bound transformers."""+ text = PYPROJECT.read_text(encoding="utf-8")+ assert {"train", "dev", "mlx", "qat"} <= set(_extras(text))+ assert "torch" in _declared(text, {"dev"})+ assert "torch" not in _declared(text, {"mlx"})+ assert "transformers" in _declared(text, {"mlx"})+ assert set(_bounds()) >= DECLARED_IN_PYPROJECT+++# --- Contributors are told ------------------------------------------------------+++def test_contributing_says_pull_requests_install_a_pinned_stack():+ text = " ".join(CONTRIBUTING.read_text(encoding="utf-8").split())+ assert "`.github/constraints/pinned-upstream.txt`" in text+ assert "Pull-request CI installs a pinned upstream stack" in text