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: run the full matrix at approval (ci:full), a quick subset on other PR pushes (#1381)
Alpamys Makazhan8fcd8b90e320
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0a6554cb..a13d2587 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -9,6 +9,10 @@ on:branches: [main, 'release/**']pull_request:branches: [main]+ # The first three are GitHub's defaults. `labeled` is what starts the full+ # matrix when a maintainer adds `ci:full` (see the comment above the `plan`+ # job); it stays a plain pull_request run -- never pull_request_target.+ types: [opened, synchronize, reopened, ready_for_review, labeled]# Supersede, do not queue.#@@ -47,7 +51,12 @@ on:# commit. `release/**` keeps the per-commit key, because the release checklist# needs a green matrix on the exact commit being tagged.concurrency:- group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || (github.ref == 'refs/heads/main' && 'main-push' || github.sha) }}+ # A run started by adding any label other than `ci:full` keys on its run id, so+ # nothing shares its group: it cannot cancel a full matrix already running on+ # the pull request, and no later push cancels it. Adding `ci:full` keys on the+ # ref like every other pull-request event, so the full run supersedes the quick+ # one. The whole policy is in the comment above the `plan` job.+ group: ${{ github.workflow }}-${{ github.event.action == 'labeled' && github.event.label.name != 'ci:full' && format('labeled-{0}', github.run_id) || github.event_name == 'pull_request' && github.ref || (github.ref == 'refs/heads/main' && 'main-push' || github.sha) }}cancel-in-progress: ${{ github.event_name == 'pull_request' }}# Bound every job explicitly.@@ -96,6 +105,113 @@ concurrency:# save runner-minutes that are only ever spent when a job is already hung.jobs:+ # Quick runs, the full matrix at approval, and every cell on a release branch.+ #+ # Measured 2026-09-28 07:30Z: the Actions account sat at its free-plan cap of+ # 20 concurrent jobs (8 ubuntu, 8 windows, 4 macos running) with 301 jobs+ # queued, and every push to a pull request cost 15 jobs of this workflow: the+ # nine test cells plus lint, type-check, mlx-smoke, torchao-contract,+ # pytorch-smoke and transformers-floor.+ #+ # So `plan` picks one of three matrices, and every job except `lint` follows it:+ #+ # push to release/** RELEASE: all nine test cells + the five gated jobs+ # push to main, or a pull FULL: seven test cells (no Windows or macOS+ # request labelled ci:full on 3.11) + the five gated jobs+ # any other pull request run QUICK: lint + test (ubuntu-latest, 3.12)+ #+ # 3.11 runs on ubuntu in every full run, and on Windows and macOS only for+ # release/**, where the release checklist needs every cell green on the tagged+ # commit. Measured basis (soup-97): macOS was the binding limit 63% of the+ # time, and dropping the two cells takes a full run from 4 macOS jobs to 3+ # (x1.33 on that limit). What it gives up: 3 of 64 failing attempts failed on+ # windows-3.11 alone, and a failure like that now surfaces on the release+ # branch instead of before merge. Branch protection requires neither cell.+ #+ # A quick push costs 3 jobs (lint, plan, one ubuntu cell) instead of 15, and+ # none of them on Windows or macOS. A maintainer adds `ci:full` at approval.+ # The pull request's current labels decide, not the event, so every run on a+ # labelled pull request is full -- including each later push, which a merge on+ # the current head needs anyway. Remove the label to go back to quick runs. A+ # labelled run is an ordinary pull_request run, with the token and secrets a+ # push to that pull request already gets.+ #+ # What this costs, and why the merge gate still holds:+ #+ # - Contributors see only ubuntu / Python 3.12 until approval. A failure that+ # exists only on Windows, macOS, 3.10 or 3.11 surfaces at approval (on the+ # release branch, for Windows and macOS on 3.11), so that round trip starts+ # later than it used to.+ # - The required smokes (mlx-smoke, pytorch-smoke, transformers-floor) read as+ # SKIPPED on a quick run, and branch protection counts a job skipped by its+ # `if:` as passing. So the smokes are not what blocks a merge; the test cells+ # are. `test` takes its matrix from `plan`, so a quick run never CREATES the+ # other six required `test (...)` contexts, and a required context nothing+ # reported stays "Expected" and keeps the merge button locked. Do not turn the+ # matrix back into a static list with a per-cell `if:`: a skipped cell passes.+ # For the same reason FULL and branch protection must name the same cells: a+ # required cell FULL drops is never reported and locks every merge, and a FULL+ # cell that is not required gates nothing.+ # - Maintainers merge only when all 11 required checks read SUCCESS on the+ # current head. Skipped is not success: a quick run after a full one on the+ # same head (say the label was removed and another one added) replaces the+ # smokes' results, a failure included, with skipped -- which the merge button+ # accepts.+ # - Adding any other label to a pull request that already carries `ci:full`+ # starts a second full run, in a concurrency group of its own so it cannot+ # cancel the first, and no later push cancels it either. Add other labels+ # before `ci:full`.+ # - Coverage uploads from the ubuntu / 3.11 cell only, so a pull request's+ # Codecov report arrives at approval.+ #+ # `timeout-minutes: 5` is not a measurement: one shell step, no checkout, no+ # install.+ plan:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ env:+ # The three matrices, each declared once as a JSON literal the tests parse.+ # RELEASE is the support matrix, every cell: tests/test_requires_python_bound.py+ # derives requires-python from it. FULL is RELEASE minus Windows and macOS on+ # 3.11, and tests/test_ci_full_matrix_on_approval.py pins it to exactly the+ # required `test (...)` contexts. QUICK is one required cell. Keep the key+ # order (it names the checks) and the versions as strings (a JSON 3.10 is 3.1).+ RELEASE_MATRIX: >-+ {"os": ["ubuntu-latest", "windows-latest", "macos-latest"],+ "python-version": ["3.10", "3.11", "3.12"]}+ FULL_MATRIX: >-+ {"os": ["ubuntu-latest", "windows-latest", "macos-latest"],+ "python-version": ["3.10", "3.11", "3.12"],+ "exclude": [{"os": "windows-latest", "python-version": "3.11"},+ {"os": "macos-latest", "python-version": "3.11"}]}+ QUICK_MATRIX: '{"os": ["ubuntu-latest"], "python-version": ["3.12"]}'+ outputs:+ full: ${{ steps.decide.outputs.full }}+ matrix: ${{ steps.decide.outputs.matrix }}+ steps:+ - name: Choose the release, full or quick matrix+ id: decide+ env:+ RELEASE: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/') }}+ FULL: ${{ github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'ci:full') }}+ run: |+ set -euo pipefail+ if [ "$RELEASE" = "true" ]; then+ full=true+ matrix="$RELEASE_MATRIX"+ elif [ "$FULL" = "true" ]; then+ full=true+ matrix="$FULL_MATRIX"+ else+ full=false+ matrix="$QUICK_MATRIX"+ echo "::notice title=Quick CI run::lint and test (ubuntu-latest, 3.12) only. The other required test cells and the smoke jobs run when a maintainer adds the ci:full label."+ fi+ {+ echo "full=$full"+ echo "matrix=$matrix"+ } >> "$GITHUB_OUTPUT"+lint:runs-on: ubuntu-latesttimeout-minutes: 15@@ -142,6 +258,8 @@ jobs:"${RUNNER_TEMP}/actionlint" -colortype-check:+ needs: plan+ if: needs.plan.outputs.full == 'true'runs-on: ubuntu-latesttimeout-minutes: 15# Non-blocking type-check baseline. The codebase adopts annotations@@ -161,6 +279,8 @@ jobs:mypy || echo "::warning title=mypy::Type issues reported (non-blocking baseline — see the log above)"mlx-smoke:+ needs: plan+ if: needs.plan.outputs.full == 'true'# #394: prove the documented standalone install on an Apple Silicon runner.# Keep this separate from the main matrix because `.[dev]` deliberately# installs the PyTorch/TRL stack and would hide an accidental MLX dependency.@@ -186,6 +306,8 @@ jobs:# with a constant 0.0 left the suite green (#1018 review).run: pytest -o addopts= -q tests/test_rewind_mlx.pytorchao-contract:+ needs: plan+ if: needs.plan.outputs.full == 'true'# #826: every torchao class Soup names is resolved against the REAL package# here. The 3x3 matrix cannot do it -- `torchao` is not in `[dev]`, so those# cells skip these tests, which is how three names torchao never exported@@ -217,6 +339,8 @@ jobs:tests/test_issue835_fp8_gate.py \tests/test_v07121.pypytorch-smoke:+ needs: plan+ if: needs.plan.outputs.full == 'true'# #596: exercise the real PyTorch SFT + DPO training pipeline on every PR.# Keep this separate from the 3x3 matrix so the expensive model-backed# smoke tests run once, not nine times.@@ -276,6 +400,8 @@ jobs:# trl 0.29 / PEFT 0.20 support stack and Plotext 6.0.0 so pip cannot silently# upgrade the cell, then assert every pinned compatibility boundary.transformers-floor:+ needs: plan+ if: needs.plan.outputs.full == 'true'runs-on: ubuntu-latesttimeout-minutes: 20env:@@ -349,11 +475,14 @@ jobs:tests/test_issue265_xcodec2_audio_contract.pytest:+ needs: planstrategy:fail-fast: false- matrix:- os: [ubuntu-latest, windows-latest, macos-latest]- python-version: ["3.10", "3.11", "3.12"]+ # From `plan`: all nine cells on a push to release/**, seven on a full run+ # (no Windows or macOS 3.11), test (ubuntu-latest, 3.12) alone on a quick+ # one. The cells a run leaves out are MISSING, not skipped, and that is what+ # keeps a required one blocking a merge.+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}runs-on: ${{ matrix.os }}timeout-minutes: 90env:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a54128c3..939601f4 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -522,6 +522,14 @@ GitHub Actions runs on every push and PR:contributions here are fork PRs, expect "skipped" on yours; it is not arequired 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 full matrix (Windows and macOS+as well as Ubuntu, Python 3.10 to 3.12 with 3.11 on Ubuntu only, plus the smoke+jobs) runs when a maintainer adds the `ci:full` label at approval, and on every+later push while the label stays. Until then the other `test (...)` checks show+as *Expected* and the smoke jobs as *skipped*; neither is a failure on your side.+A PR is merged only when the full matrix is green on its current head.+See `.github/workflows/ci.yml`.### Stale CI marks (#1017)diff --git a/tests/test_ci_full_matrix_on_approval.py b/tests/test_ci_full_matrix_on_approval.pynew file mode 100644index 00000000..42b1a237--- /dev/null+++ b/tests/test_ci_full_matrix_on_approval.py@@ -0,0 +1,684 @@+"""A pull-request push runs a quick CI subset; the full matrix runs at approval.++Measured 2026-09-28 07:30Z: the Actions account sat at its free-plan cap of 20+concurrent jobs (8 ubuntu, 8 windows, 4 macos) with 301 jobs queued, and every+push to a pull request cost 15 jobs of ``ci.yml``. So ``plan`` picks one of+three matrices by event:++* RELEASE, every cell of the 3x3 support matrix, for pushes to ``release/**``+ -- the release checklist needs all of them green on the tagged commit;+* FULL, the same minus Windows and macOS on 3.11, for pushes to ``main`` and+ pull requests a maintainer has labelled ``ci:full``;+* QUICK, ``test (ubuntu-latest, 3.12)`` alone, for any other pull-request run.++The merge gate survives that because of one shape, and these tests pin it: the+``test`` job's matrix is whatever the ``plan`` job outputs, so a quick run never+CREATES the other six required ``test (...)`` contexts. Branch protection+passes a skipped job and waits on a missing one, so it is the missing cells --+not the skipped smokes -- that keep the merge button locked until the full+matrix has run. FULL must name exactly the required contexts: a cell it drops+that branch protection still requires would lock every merge, and a required+cell it drops silently would stop being tested before merge at all.++Nothing here talks to GitHub. The workflow is read as YAML, the ``plan`` step's+shell runs under a local bash, and the expressions GitHub would evaluate are+evaluated by a small interpreter for exactly the operators they use.+"""++from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import sys+from pathlib import Path+from typing import Any++import pytest+import yaml++ROOT = Path(__file__).resolve().parents[1]+CI = ROOT / ".github" / "workflows" / "ci.yml"+CONTRIBUTING = ROOT / "CONTRIBUTING.md"++LABEL = "ci:full"+GATE = "needs.plan.outputs.full == 'true'"+GATED_JOBS = (+ "type-check",+ "mlx-smoke",+ "torchao-contract",+ "pytorch-smoke",+ "transformers-floor",+)+#: The support matrix: what RELEASE runs, and what requires-python must match.+SUPPORT_MATRIX = {+ "os": ["ubuntu-latest", "windows-latest", "macos-latest"],+ "python-version": ["3.10", "3.11", "3.12"],+}+#: What FULL leaves out of it. 3.11 still runs on ubuntu in every full run.+FULL_EXCLUDE = (+ {"os": "windows-latest", "python-version": "3.11"},+ {"os": "macos-latest", "python-version": "3.11"},+)+QUICK_MATRIX = {"os": ["ubuntu-latest"], "python-version": ["3.12"]}+#: The seven ``test`` contexts branch protection on ``main`` requires, read on+#: 2026-09-28 with ``gh api repos/MakazhanAlpamys/Soup/branches/main/protection/+#: required_status_checks`` after the owner dropped Windows and macOS 3.11 (11+#: required checks: these plus lint, mlx-smoke, pytorch-smoke, transformers-floor).+#: A cell named any other way is a context nobody waits on.+REQUIRED_TEST_CONTEXTS = frozenset(+ {+ "test (ubuntu-latest, 3.10)",+ "test (ubuntu-latest, 3.11)",+ "test (ubuntu-latest, 3.12)",+ "test (windows-latest, 3.10)",+ "test (windows-latest, 3.12)",+ "test (macos-latest, 3.10)",+ "test (macos-latest, 3.12)",+ }+)+#: The two cells only a push to ``release/**`` runs. Not required, so not a merge gate.+RELEASE_ONLY_CONTEXTS = frozenset({"test (windows-latest, 3.11)", "test (macos-latest, 3.11)"})+++# --- Reading the workflow ----------------------------------------------------+++def _workflow() -> dict[str, Any]:+ data = yaml.safe_load(CI.read_text(encoding="utf-8"))+ assert isinstance(data, dict), "ci.yml did not parse to a mapping"+ return data+++def _triggers() -> Any:+ data = _workflow()+ # PyYAML (YAML 1.1) reads the bare key `on` as the boolean True.+ return data.get("on", data.get(True))+++def _jobs() -> dict[str, Any]:+ return _workflow()["jobs"]+++def _plan() -> dict[str, Any]:+ plan = _jobs().get("plan")+ assert isinstance(plan, dict), "ci.yml has no `plan` job"+ return plan+++def _needs(job: dict[str, Any]) -> list[str]:+ needs = job.get("needs", [])+ return [needs] if isinstance(needs, str) else list(needs)+++def _decide_step() -> dict[str, Any]:+ steps = [step for step in _plan().get("steps", []) if step.get("id") == "decide"]+ assert len(steps) == 1, "the plan job must have exactly one step with `id: decide`"+ return steps[0]+++MATRIX_NAMES = ("RELEASE_MATRIX", "FULL_MATRIX", "QUICK_MATRIX")+++def _literal(name: str) -> str:+ literal = (_plan().get("env") or {}).get(name)+ assert isinstance(literal, str), (+ f"the plan job must declare {name} once, as a JSON literal in its env"+ )+ return literal+++def _matrix(name: str) -> dict[str, Any]:+ return json.loads(_literal(name))+++def _cells(matrix: dict[str, Any]) -> set[str]:+ """The ``test (...)`` contexts GitHub creates for *matrix*.++ The product of the two axes, titled with the values in key order (os first),+ minus every cell an ``exclude`` entry matches -- GitHub excludes on a PARTIAL+ match, so ``{"python-version": "3.11"}`` alone would drop all three 3.11 cells.+ """+ assert set(matrix) <= {"os", "python-version", "exclude"}, sorted(matrix)+ names = set()+ for runner in matrix["os"]:+ for python in matrix["python-version"]:+ cell = {"os": runner, "python-version": python}+ if any(+ all(cell.get(key) == value for key, value in rule.items())+ for rule in matrix.get("exclude", [])+ ):+ continue+ names.add(f"test ({runner}, {python})")+ return names+++def _rules(entries: Any) -> list[tuple[tuple[str, Any], ...]]:+ """Exclude entries compared as a multiset, whatever order they are listed in."""+ return sorted(tuple(sorted(entry.items())) for entry in entries)+++def _version(text: str) -> tuple[int, ...]:+ return tuple(int(part) for part in text.split("."))+++# --- A small evaluator for the GitHub expressions these tests need -----------+#+# It covers exactly what ci.yml's concurrency key and the plan decision use:+# string literals, true/false/null, property paths (with one `*` object+# filter), parentheses, ! == != && || and the functions format(), contains()+# and startsWith(). The semantics are GitHub's: && and || return an OPERAND,+# not a boolean; ! binds tighter than == and !=, which bind tighter than &&,+# then ||; strings compare case-insensitively; a missing property is null.+# Anything else fails loudly instead of being guessed at.++_TOKEN = re.compile(+ r"(?P<string>'(?:[^']|'')*')"+ r"|(?P<op>==|!=|&&|\|\||!|\(|\)|,)"+ r"|(?P<name>[A-Za-z_][\w-]*(?:\.(?:\*|[A-Za-z_][\w-]*))*)"+)+_TEMPLATE = re.compile(r"\$\{\{(.*?)\}\}", re.DOTALL)+_KEYWORDS = {"true": True, "false": False, "null": None}+++def _tokenize(source: str) -> list[tuple[str, str]]:+ tokens: list[tuple[str, str]] = []+ position = 0+ while position < len(source):+ if source[position].isspace():+ position += 1+ continue+ match = _TOKEN.match(source, position)+ assert match, f"expression syntax this evaluator does not know: {source[position:]!r}"+ kind = match.lastgroup+ assert kind is not None+ tokens.append((kind, match.group(kind)))+ position = match.end()+ return tokens+++def _truthy(value: Any) -> bool:+ return value not in (None, False, 0, "")+++def _text(value: Any) -> str:+ if value is None:+ return ""+ if isinstance(value, bool):+ return "true" if value else "false"+ return str(value)+++def _equal(left: Any, right: Any) -> bool:+ if isinstance(left, str) and isinstance(right, str):+ return left.casefold() == right.casefold()+ return left == right+++def _lookup(context: dict[str, Any], path: str) -> Any:+ value: Any = context+ spread = False+ for part in path.split("."):+ if part == "*":+ assert not spread, "nested object filters are not modelled"+ if isinstance(value, dict):+ value = list(value.values())+ elif not isinstance(value, list):+ value = []+ spread = True+ elif spread:+ value = [item.get(part) for item in value if isinstance(item, dict)]+ else:+ value = value.get(part) if isinstance(value, dict) else None+ return value+++def _call(name: str, args: list[Any]) -> Any:+ function = name.lower() # GitHub function names are case-insensitive+ if function == "format" and args:+ template, *values = args+ return re.sub(+ r"\{(\d+)\}", lambda match: _text(values[int(match.group(1))]), _text(template)+ )+ if function == "contains" and len(args) == 2:+ haystack, needle = args+ if isinstance(haystack, list):+ return any(_equal(item, needle) for item in haystack)+ return _text(needle).casefold() in _text(haystack).casefold()+ if function == "startswith" and len(args) == 2:+ text, prefix = args+ return _text(text).casefold().startswith(_text(prefix).casefold())+ raise AssertionError(f"{name}() is not modelled by this test's evaluator; add it to _call()")+++class _Expression:+ """Recursive descent over GitHub's precedence: || < && < == != < ! < primary."""++ def __init__(self, source: str, context: dict[str, Any]) -> None:+ self._tokens = _tokenize(source)+ self._position = 0+ self._context = context++ def value(self) -> Any:+ result = self._either()+ assert self._position == len(self._tokens), f"unparsed: {self._tokens[self._position:]}"+ return result++ def _take(self, operator: str) -> bool:+ if self._position < len(self._tokens) and self._tokens[self._position] == (+ "op",+ operator,+ ):+ self._position += 1+ return True+ return False++ def _either(self) -> Any:+ result = self._both()+ while self._take("||"):+ right = self._both()+ result = result if _truthy(result) else right+ return result++ def _both(self) -> Any:+ result = self._compare()+ while self._take("&&"):+ right = self._compare()+ result = right if _truthy(result) else result+ return result++ def _compare(self) -> Any:+ result = self._unary()+ while True:+ if self._take("=="):+ result = _equal(result, self._unary())+ elif self._take("!="):+ result = not _equal(result, self._unary())+ else:+ return result++ def _unary(self) -> Any:+ if self._take("!"):+ return not _truthy(self._unary())+ return self._primary()++ def _primary(self) -> Any:+ assert self._position < len(self._tokens), "the expression ends early"+ kind, text = self._tokens[self._position]+ self._position += 1+ if kind == "string":+ return text[1:-1].replace("''", "'")+ if (kind, text) == ("op", "("):+ result = self._either()+ assert self._take(")"), "unbalanced parenthesis"+ return result+ assert kind == "name", f"unexpected {text!r}"+ if self._take("("):+ args: list[Any] = []+ if not self._take(")"):+ args.append(self._either())+ while self._take(","):+ args.append(self._either())+ assert self._take(")"), f"unterminated call to {text}()"+ return _call(text, args)+ if text in _KEYWORDS:+ return _KEYWORDS[text]+ return _lookup(self._context, text)+++def _render(template: str, context: dict[str, Any]) -> str:+ """Substitute every ``${{ ... }}`` in *template* the way the runner would."""+ return _TEMPLATE.sub(+ lambda match: _text(_Expression(match.group(1), context).value()), template+ )+++def _push(ref: str = "refs/heads/main", *, run_id: str = "900") -> dict[str, Any]:+ return {+ "github": {+ "workflow": "CI",+ "event_name": "push",+ "ref": ref,+ "sha": "a" * 40,+ "run_id": run_id,+ "event": {"ref": ref},+ }+ }+++def _pull_request(+ action: str,+ *,+ labels: tuple[str, ...] = (),+ label: str | None = None,+ run_id: str = "100",+) -> dict[str, Any]:+ """A pull_request context shaped like GitHub's payload.++ On ``labeled``, ``event.label`` is the label just added and+ ``event.pull_request.labels`` already includes it.+ """+ names = list(labels)+ event: dict[str, Any] = {"action": action, "number": 7}+ if label is not None:+ event["label"] = {"name": label}+ if label not in names:+ names.append(label)+ event["pull_request"] = {"labels": [{"name": name} for name in names]}+ return {+ "github": {+ "workflow": "CI",+ "event_name": "pull_request",+ "ref": "refs/pull/7/merge",+ "sha": "b" * 40,+ "run_id": run_id,+ "event": event,+ }+ }+++def _group(context: dict[str, Any]) -> str:+ return _render(_workflow()["concurrency"]["group"], context)+++def _full_for(context: dict[str, Any]) -> str:+ return _render(_decide_step()["env"]["FULL"], context)+++def _release_for(context: dict[str, Any]) -> str:+ return _render(_decide_step()["env"]["RELEASE"], context)+++#: Which matrix each event must get: the one table both the expression tests and+#: the end-to-end run of the step's shell read.+EVENTS = [+ pytest.param(_push("refs/heads/main"), "FULL", id="push-main"),+ pytest.param(_push("refs/heads/release/v0.76.0"), "RELEASE", id="push-release"),+ pytest.param(_pull_request("opened"), "QUICK", id="pr-opened"),+ pytest.param(_pull_request("synchronize", labels=("bug",)), "QUICK", id="pr-push-other-label"),+ pytest.param(_pull_request("synchronize", labels=("bug", LABEL)), "FULL", id="pr-push-ci-full"),+ pytest.param(_pull_request("labeled", label=LABEL), "FULL", id="adds-ci-full"),+ pytest.param(_pull_request("labeled", label="bug"), "QUICK", id="adds-other"),+ pytest.param(+ _pull_request("labeled", label="bug", labels=(LABEL,)),+ "FULL",+ id="adds-other-while-ci-full",+ ),+]+++# --- Tests -------------------------------------------------------------------+++class TestTheEvaluatorHasTeeth:+ """CONTROL. The concurrency and plan tests below are only as good as this."""++ def test_and_or_return_operands_with_github_precedence(self):+ context = {"github": {"ref": "r"}}+ assert _Expression("'a' && 'b' || 'c'", context).value() == "b"+ assert _Expression("null && 'b' || 'c'", context).value() == "c"+ assert _Expression("'' || github.ref", context).value() == "r"+ assert _Expression("!('x' == 'y') && 'yes'", context).value() == "yes"++ def test_strings_compare_case_insensitively(self):+ assert _Expression("'CI:Full' == 'ci:full'", {}).value() is True+ assert _Expression("'bug' != 'ci:full'", {}).value() is True++ def test_missing_properties_are_null_and_the_filter_spreads(self):+ context = {"github": {"event": {"items": [{"name": "a"}, {"name": "B"}]}}}+ assert _Expression("github.event.nothing.here", context).value() is None+ assert _Expression("contains(github.event.items.*.name, 'b')", context).value()+ assert not _Expression("contains(github.event.none.*.name, 'b')", context).value()++ def test_templates_and_format(self):+ context = {"github": {"workflow": "CI", "run_id": "42"}}+ rendered = _render("${{ github.workflow }}-${{ format('x-{0}', github.run_id) }}", context)+ assert rendered == "CI-x-42"++ def test_starts_with_is_a_case_insensitive_prefix_test(self):+ context = {"github": {"ref": "refs/heads/Release/v1"}}+ assert _Expression("startsWith(github.ref, 'refs/heads/release/')", context).value()+ assert not _Expression("startsWith(github.ref, 'refs/heads/main')", context).value()+ assert not _Expression("startsWith(github.nothing, 'refs/')", context).value()++ def test_what_it_does_not_model_fails_instead_of_guessing(self):+ with pytest.raises(AssertionError, match="not modelled"):+ _Expression("toJSON(github)", {}).value()+ with pytest.raises(AssertionError, match="does not know"):+ _Expression("github.run_number >= 2", {}).value()+++class TestTriggers:+ def test_pull_requests_run_on_these_five_actions(self):+ pull_request = _triggers()["pull_request"]+ assert pull_request["branches"] == ["main"]+ assert sorted(pull_request.get("types", [])) == sorted(+ ["opened", "synchronize", "reopened", "ready_for_review", "labeled"]+ ), "without `labeled`, adding ci:full at approval starts nothing"++ def test_there_is_no_pull_request_target(self):+ """A labelled run stays an ordinary pull_request run, with the same token and secrets+ a push to the pull request gets -- never the privileged _target variant."""+ assert "pull_request_target" not in _triggers()++ def test_pushes_to_main_and_release_branches_still_trigger(self):+ assert _triggers()["push"]["branches"] == ["main", "release/**"]+++class TestPlanDecision:+ def test_plan_is_short_unconditional_and_exports_its_decision(self):+ plan = _plan()+ assert plan["runs-on"] == "ubuntu-latest"+ assert plan["timeout-minutes"] == 5+ assert "if" not in plan and "needs" not in plan+ assert plan["outputs"] == {+ "full": "${{ steps.decide.outputs.full }}",+ "matrix": "${{ steps.decide.outputs.matrix }}",+ }++ @pytest.mark.parametrize(("context", "kind"), EVENTS)+ def test_the_decision_follows_the_event_and_the_current_labels(self, context, kind):+ """RELEASE only for a push to release/**; FULL for any other push and for a pull+ request whose CURRENT labels carry ci:full, whichever event started the run."""+ assert _release_for(context) == ("true" if kind == "RELEASE" else "false")+ assert _full_for(context) == ("false" if kind == "QUICK" else "true")+++class TestGatedJobs:+ @pytest.mark.parametrize("name", GATED_JOBS)+ def test_the_smoke_and_contract_jobs_run_only_on_a_full_run(self, name):+ job = _jobs()[name]+ assert "plan" in _needs(job), f"{name} does not need plan"+ assert job.get("if") == GATE, f"{name} is not gated on plan's decision"++ def test_lint_always_runs_and_waits_for_nothing(self):+ lint = _jobs()["lint"]+ assert "if" not in lint+ assert "needs" not in lint++ def test_every_job_is_classified(self):+ """A new job must be declared quick or full here, or it lands on every PR push."""+ assert sorted(_jobs()) == sorted(["plan", "lint", "test", *GATED_JOBS])+++class TestMatrix:+ def test_the_test_job_takes_its_matrix_from_plan(self):+ """A static matrix with a per-cell `if:` would SKIP the missing cells, and a skipped+ job passes branch protection; a matrix from plan never creates them."""+ test = _jobs()["test"]+ assert "plan" in _needs(test)+ assert "if" not in test+ assert test["strategy"]["fail-fast"] is False+ assert test["strategy"]["matrix"] == "${{ fromJSON(needs.plan.outputs.matrix) }}"+ assert test["runs-on"] == "${{ matrix.os }}"++ def test_release_is_the_support_matrix_with_nothing_excluded(self):+ release = _matrix("RELEASE_MATRIX")+ assert release == SUPPORT_MATRIX, "RELEASE must be every cell: no exclude, no include"+ assert list(release) == ["os", "python-version"], "the key order names the checks"+ assert all(isinstance(python, str) for python in release["python-version"]), (+ "a JSON number 3.10 is 3.1, which renames the check context"+ )++ def test_full_is_the_support_matrix_minus_exactly_two_cells(self):+ full = _matrix("FULL_MATRIX")+ assert list(full) == ["os", "python-version", "exclude"]+ assert full["os"] == SUPPORT_MATRIX["os"]+ assert full["python-version"] == SUPPORT_MATRIX["python-version"]+ assert _rules(full["exclude"]) == _rules(FULL_EXCLUDE)+ # Nothing else excluded, whatever the entries look like (a partial rule+ # such as {"python-version": "3.11"} would drop the ubuntu cell too).+ assert _cells(_matrix("RELEASE_MATRIX")) - _cells(full) == RELEASE_ONLY_CONTEXTS++ def test_full_names_exactly_the_required_test_contexts(self):+ assert _cells(_matrix("FULL_MATRIX")) == REQUIRED_TEST_CONTEXTS++ def test_release_runs_every_required_cell_and_the_two_full_skips(self):+ assert _cells(_matrix("RELEASE_MATRIX")) == REQUIRED_TEST_CONTEXTS | RELEASE_ONLY_CONTEXTS++ def test_the_quick_matrix_is_the_newest_python_on_ubuntu(self):+ quick = _matrix("QUICK_MATRIX")+ assert quick == QUICK_MATRIX+ assert list(quick) == ["os", "python-version"]+ names = _cells(quick)+ assert len(names) == 1 and names <= REQUIRED_TEST_CONTEXTS+ support_pythons = SUPPORT_MATRIX["python-version"]+ assert quick["python-version"] == [max(support_pythons, key=_version)]++ @pytest.mark.parametrize("name", MATRIX_NAMES)+ def test_the_matrix_literals_are_single_lines(self, name):+ """$GITHUB_OUTPUT takes one `name=value` per line; a newline would end the value."""+ assert "\n" not in _literal(name)+++class TestConcurrency:+ def test_a_label_other_than_ci_full_cannot_share_the_pull_request_group(self):+ pull_request = _group(_pull_request("synchronize", labels=(LABEL,)))+ for labels in ((), (LABEL,)):+ labelled = _group(_pull_request("labeled", label="bug", labels=labels))+ assert labelled != pull_request, (+ "a run started by an unrelated label shares the pull request's group, "+ "so it cancels a full matrix already running there"+ )++ def test_each_such_run_is_alone_in_its_group(self):+ first = _group(_pull_request("labeled", label="bug", run_id="1"))+ second = _group(_pull_request("labeled", label="bug", run_id="2"))+ assert first != second++ def test_adding_ci_full_supersedes_the_quick_run(self):+ quick = _group(_pull_request("synchronize"))+ assert _group(_pull_request("labeled", label=LABEL, run_id="2")) == quick++ @pytest.mark.parametrize("action", ["opened", "synchronize", "reopened", "ready_for_review"])+ def test_every_other_pull_request_event_still_supersedes(self, action):+ earlier = _group(_pull_request("synchronize", run_id="1"))+ assert _group(_pull_request(action, run_id="2")) == earlier++ def test_a_push_is_never_in_a_pull_request_or_label_group(self):+ for ref in ("refs/heads/main", "refs/heads/release/v0.76.0"):+ push = _group(_push(ref, run_id="1"))+ assert push != _group(_pull_request("synchronize", run_id="1"))+ assert push != _group(_pull_request("labeled", label="bug", run_id="1"))++ def test_cancellation_stays_pull_request_only(self):+ concurrency = _workflow()["concurrency"]+ assert concurrency["cancel-in-progress"] == "${{ github.event_name == 'pull_request' }}"++ @pytest.mark.parametrize("label", [LABEL, LABEL.upper(), "bug"])+ def test_the_group_and_the_plan_agree_on_what_ci_full_is(self, label):+ """Renaming the label in one expression only would make the approval label either+ start a quick run or cancel nothing -- both silently."""+ event = _pull_request("labeled", label=label)+ joins = _group(event) == _group(_pull_request("synchronize"))+ assert joins == (_full_for(event) == "true")+++def _posix_bash() -> str | None:+ """A bash that runs a POSIX script; on Windows, Git for Windows' copy.++ On Windows ``shutil.which("bash")`` can answer ``System32\\bash.exe``, the WSL+ launcher, which does not run the script at all. Git for Windows ships a real+ bash beside git, and the Windows runners and dev boxes here all have git.+ """+ if sys.platform != "win32":+ return shutil.which("bash")+ git = shutil.which("git")+ if git is None:+ return None+ for parent in Path(git).resolve().parents:+ candidate = parent / "bin" / "bash.exe"+ if candidate.is_file():+ return str(candidate)+ return None+++BASH = _posix_bash()++[email protected](BASH is None, reason="no POSIX bash found (on Windows: Git for Windows)")+class TestTheDecideStepScript:+ """Run the plan step's own shell, as the runner would, against a fake $GITHUB_OUTPUT."""++ def _outputs(self, tmp_path: Path, *, release: str, full: 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,+ "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)++ @pytest.mark.parametrize(("context", "kind"), EVENTS)+ def test_each_event_gets_its_matrix(self, tmp_path, context, kind):+ """End to end: the event, through GitHub's expressions, through the shell."""+ full, matrix = self._outputs(+ tmp_path, release=_release_for(context), full=_full_for(context)+ )+ assert matrix == _matrix(f"{kind}_MATRIX")+ assert full == ("false" if kind == "QUICK" else "true")++ @pytest.mark.parametrize(+ ("release", "full", "kind"),+ [+ ("false", "false", "QUICK"),+ ("false", "", "QUICK"),+ ("false", "yes", "QUICK"),+ ("", "true", "FULL"),+ ("yes", "true", "FULL"),+ ],+ )+ def test_only_the_exact_string_true_selects(self, tmp_path, release, full, kind):+ """Quick is the fail-closed answer on a pull request: fewer cells, more missing+ required contexts, a locked merge button."""+ flag, matrix = self._outputs(tmp_path, release=release, full=full)+ assert matrix == _matrix(f"{kind}_MATRIX")+ assert flag == ("false" if kind == "QUICK" else "true")+++def test_contributing_tells_contributors_about_the_label():+ assert f"`{LABEL}`" in CONTRIBUTING.read_text(encoding="utf-8")diff --git a/tests/test_requires_python_bound.py b/tests/test_requires_python_bound.pyindex d3b853a4..0eea5497 100644--- a/tests/test_requires_python_bound.py+++ b/tests/test_requires_python_bound.py@@ -9,19 +9,25 @@ Soup code executes, so the user has nothing to act on.The bound is derived from the CI matrix rather than hardcoded, because a floatingdeclaration and a fixed matrix drifting apart is exactly the failure this fileexists to catch. Widening the matrix and widening the bound must happen together.++The matrix is read from the `plan` job's `RELEASE_MATRIX` literal: the support+matrix, every cell, which pushes to `release/**` run. The `test` job's own matrix+is whatever `plan` outputs -- FULL (the same minus Windows and macOS on 3.11) or+a single QUICK cell -- which is a run-time choice, not the support statement."""+import jsonimport pathlibimport reimport pytest+import yamlROOT = pathlib.Path(__file__).resolve().parents[1]PYPROJECT = ROOT / "pyproject.toml"CI_WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml"_REQUIRES_PYTHON = re.compile(r'^requires-python\s*=\s*"([^"]+)"', re.M)-_MATRIX_LINE = re.compile(r'^\s*python-version:\s*\[([^\]]+)\]', re.M)def _requires_python(text: str) -> str:@@ -50,12 +56,28 @@ def _parse_bounds(spec: str) -> tuple[tuple[int, int], tuple[int, int]]:def _ci_python_versions() -> list[tuple[int, int]]:- """The matrix `python-version` list from the test job in ci.yml."""- match = _MATRIX_LINE.search(CI_WORKFLOW.read_text(encoding="utf-8"))- assert match, "no `python-version: [...]` matrix found in .github/workflows/ci.yml"- versions = re.findall(r"(\d+)\.(\d+)", match.group(1))- assert versions, "the python-version matrix parsed to an empty list"- return sorted((int(major), int(minor)) for major, minor in versions)+ """The `python-version` list of the support matrix the `plan` job in ci.yml declares."""+ workflow = yaml.safe_load(CI_WORKFLOW.read_text(encoding="utf-8"))+ plan = (workflow.get("jobs") or {}).get("plan") or {}+ literal = (plan.get("env") or {}).get("RELEASE_MATRIX")+ assert isinstance(literal, str), (+ "no `plan.env.RELEASE_MATRIX` JSON literal found in .github/workflows/ci.yml"+ )+ matrix = json.loads(literal)+ assert not {"exclude", "include"} & set(matrix), (+ "the support matrix must be a plain product, or a listed Python may run nowhere"+ )+ versions = matrix.get("python-version")+ assert versions, "the support matrix has an empty python-version list"+ parsed = []+ for version in versions:+ assert isinstance(version, str), (+ f"python-version {version!r} must be a JSON string: a number 3.10 reads as 3.1"+ )+ match = re.fullmatch(r"(\d+)\.(\d+)", version)+ assert match, f"python-version {version!r} is not MAJOR.MINOR"+ parsed.append((int(match.group(1)), int(match.group(2))))+ return sorted(parsed)class TestRequiresPythonHasAnUpperBound: