diff --git a/ci-attestations.yml b/ci-attestations.yml index 9d4f066a..967fbe21 100644 --- a/ci-attestations.yml +++ b/ci-attestations.yml @@ -1,8 +1,13 @@ version: 1 lanes: + # `run`: what the bare `prooft` runner (and so `./push`) executes; lint runs before tests. lint: + stage: lint + run: [./lint] inputs: ["crates/**", "dylints/**", "src/**", "ci/**", "tests/**", "examples/**", "demo/**", "vscode-plugin/**", ".github/workflows/_lint.yml", Cargo.toml, Cargo.lock, rust-toolchain.toml, pyproject.toml, uv.lock, setup.py, MANIFEST.in, README.md, LICENSE, lint, push, ci-attestations.yml] test: + stage: test + run: [uv, run, --no-project, python, ci/attest_test.py] inputs: ["crates/**", "dylints/**", "src/**", "ci/**", "tests/**", "examples/**", "demo/**", "vscode-plugin/**", ".github/workflows/**", Cargo.toml, Cargo.lock, rust-toolchain.toml, pyproject.toml, uv.lock, setup.py, MANIFEST.in, README.md, LICENSE, lint, test, push, ci-attestations.yml] gates: general/linux-x64/lint: {lane: lint} diff --git a/ci/prooft_verify.py b/ci/prooft_verify.py index 639f94a3..194c9c9f 100644 --- a/ci/prooft_verify.py +++ b/ci/prooft_verify.py @@ -1,15 +1,25 @@ """Plan PR skips using the verifier and policy checked out from the base.""" +import platform import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PROOFT_SOURCE = ( - "git+https://github.com/forge-ci/prooft@d08d58bebcd8592e4526b9bde9ca4717966a8786" + "git+https://github.com/forge-ci/prooft@cf897d4a49735c880c22c5994f5c95ac63a2d352" ) +def require_attesting_host() -> None: + """Refuse to attest anywhere but the host the policy's linux-x64 gates name.""" + host = (platform.system(), platform.machine(), platform.libc_ver()[0]) + if host != ("Linux", "x86_64", "glibc"): + raise SystemExit( + f"./push: the attestation lanes require Linux x86_64 with glibc, not {host}" + ) + + def prooft(*args: str) -> list[str]: return ["uvx", "--from", PROOFT_SOURCE, "prooft", "-C", str(ROOT), *args] diff --git a/docs/FRACTIONAL_CI.md b/docs/FRACTIONAL_CI.md index 4c2b2ed6..336ac27e 100644 --- a/docs/FRACTIONAL_CI.md +++ b/docs/FRACTIONAL_CI.md @@ -12,11 +12,16 @@ tests for a targeted diagnosis. It does not satisfy the full-coverage gate. ## Publish an attested PR -Run `./push` from a clean Linux x86-64 feature branch. It attests `./lint` -and `./test`, verifies the stamps on HEAD, pushes the branch, and opens the -PR. Use `./push --label ci-test` at creation to request Linux integration -coverage. Use `--prove-only` to stamp HEAD without publishing or `--no-pr` -to push without opening a PR. `--remote` selects a Git remote. +Run `./push` from a clean Linux x86-64 feature branch. It is a thin +delegate to the prooft runner (`prooft --push`, ci.yml GATE-014), pinned in +[`ci/prooft_verify.py`](../ci/prooft_verify.py). The runner runs the +lint-stage lanes of [`ci-attestations.yml`](../ci-attestations.yml) first +(`./lint`), stamps HEAD, pushes the branch with a lease, and opens or reuses +the PR. `./push --test` also attests the unit-test lane (`./test`) after lint +passes. `--no-pr` pushes without opening a PR, `--remote` selects a Git +remote, and `--dry-run` prints the steps. Run bare `prooft` (no `--push`) to +stamp HEAD without publishing. Add the `ci-test` label to the PR to request +Linux integration coverage. Prooft reuses a lane's proof for up to 24 hours while its tracked inputs stay unchanged. Attestation skips apply to the Linux x86 PR lint and diff --git a/push b/push index 9857e3c5..a644de4f 100755 --- a/push +++ b/push @@ -1,214 +1,14 @@ -#!/usr/bin/env -S uv run --no-project --script -# /// script -# requires-python = ">=3.11" -# dependencies = [] -# /// -"""Attest Linux x86_64 lint and unit tests, push HEAD, and open a PR. +#!/usr/bin/env python +"""Publish this branch through the prooft runner (forge-ci/ci.yml GATE-014). -Exit codes: 0 success, 1 step failed, 2 usage, 3 refused. +Lint first, `--test` adds the test lane, then a lease push and the PR are opened or reused. """ -import argparse -import json -import platform -import subprocess +import os import sys -from typing import NamedTuple -from ci.prooft_verify import ROOT, prooft +from ci.prooft_verify import PROOFT_SOURCE, require_attesting_host +require_attesting_host() -class Lane(NamedTuple): - name: str - gates: set[str] - command: tuple[str, ...] - - -LANES = ( - Lane( - "lint", - { - "general/linux-x64/lint", - "rust/all/fmt", - "rust/x86_64-unknown-linux-gnu/clippy", - "rust/x86_64-unknown-linux-gnu/dylint", - }, - ("./lint",), - ), - Lane( - "test", - {"rust/x86_64-unknown-linux-gnu/test", "python/linux-x64/test"}, - ("uv", "run", "--no-project", "python", "ci/attest_test.py"), - ), -) -# A worktree-local ref keeps the latest proof available across commits. -CACHE = "refs/worktree/fastled-prooft" - - -def git(*args: str) -> str: - return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() - - -def step(argv: list[str], *, input_text: str | None = None) -> int: - print(f"./push: $ {' '.join(argv)}", flush=True) - return subprocess.run( - argv, cwd=ROOT, input=input_text, text=True, check=False - ).returncode - - -def proof_states(rev: str = "HEAD") -> tuple[int, dict[str, str]]: - result = subprocess.run( - prooft("verify", rev, "--json"), - cwd=ROOT, - stdout=subprocess.PIPE, - text=True, - check=False, - ) - rows = json.loads(result.stdout) - return result.returncode, {row["gate"]: row["state"] for row in rows} - - -def reuse_cached_proof(states: dict[str, str]) -> bool: - """Restore previously verified gates if prooft accepts them for this HEAD.""" - cached = subprocess.run( - ["git", "rev-parse", "--verify", "--quiet", CACHE], - cwd=ROOT, - stdout=subprocess.PIPE, - text=True, - check=False, - ).stdout.strip() - if not cached or cached == git("rev-parse", "HEAD"): - return False - bundle = json.loads(subprocess.check_output(prooft("emit", cached), text=True)) - bundle["attestations"] = [ - proof - for proof in bundle["attestations"] - if states.get(proof["gate"]) != "valid" - ] - if bundle["attestations"]: - # Exit 1 also means the cached inputs no longer match. The next verify - # determines which lanes still need a new run. - return step(prooft("apply", "-"), input_text=json.dumps(bundle)) == 0 - return False - - -def attest() -> str: - _, states = proof_states() - required = set().union(*(lane.gates for lane in LANES)) - if not required.issubset(states): - raise RuntimeError("the policy is missing required gates") - if any(states[gate] != "valid" for gate in required) and reuse_cached_proof(states): - _, states = proof_states() - for lane in LANES: - if all(states.get(gate) == "valid" for gate in lane.gates): - print(f"./push: reusing {lane.name} proof", flush=True) - continue - if step(prooft("run", lane.name, "--", *lane.command)) != 0: - raise RuntimeError(f"the {lane.name} lane failed") - git("update-ref", CACHE, "HEAD") - head = git("rev-parse", "HEAD") - code, states = proof_states(head) - if ( - code - or not required.issubset(states) - or any(state != "valid" for state in states.values()) - ): - raise RuntimeError(f"HEAD did not verify: {states}") - git("update-ref", CACHE, head) - return head - - -def refusal(branch: str, remote: str) -> str | None: - remote_head = subprocess.run( - ["git", "symbolic-ref", "--quiet", "--short", f"refs/remotes/{remote}/HEAD"], - cwd=ROOT, - stdout=subprocess.PIPE, - text=True, - check=False, - ).stdout.strip() - if branch in {"HEAD", "main"} or remote_head == f"{remote}/{branch}": - return "work on a feature branch" - if git("status", "--porcelain", "--untracked-files=no"): - return "tracked files have uncommitted changes" - return None - - -def gh_json(*args: str): - return json.loads(subprocess.check_output(["gh", *args], cwd=ROOT, text=True)) - - -def open_pr(remote: str, branch: str, labels: list[str]) -> int: - url = git("remote", "get-url", "--push", remote) - repo = gh_json("repo", "view", url, "--json", "nameWithOwner,url") - url = repo["url"] - prs = gh_json( - "pr", - "list", - "--repo", - url, - "--head", - branch, - "--state", - "open", - "--limit", - "100", - "--json", - "headRepository,headRefName", - ) - if any( - pr["headRefName"] == branch - and (pr.get("headRepository") or {}).get("nameWithOwner") - == repo["nameWithOwner"] - for pr in prs - ): - return 0 - create = ["gh", "pr", "create", "--repo", url, "--fill", "--head", branch] - for label in labels: - create.extend(("--label", label)) - return int(step(create) != 0) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False) - parser.add_argument( - "--prove-only", action="store_true", help="attest without pushing" - ) - parser.add_argument( - "--no-pr", action="store_true", help="push without opening a PR" - ) - parser.add_argument("--remote", default="origin", help="git remote to push to") - parser.add_argument("--label", action="append", default=[], help="label a new PR") - args = parser.parse_args() - - try: - branch = git("rev-parse", "--abbrev-ref", "HEAD") - if reason := refusal(branch, args.remote): - print(f"./push: refusing: {reason}", file=sys.stderr) - return 3 - if ( - platform.system() != "Linux" - or platform.machine() != "x86_64" - or platform.libc_ver()[0] != "glibc" - ): - raise RuntimeError("the attestation lanes require Linux x86_64 with glibc") - head = attest() - if args.prove_only: - return 0 - if ( - git("rev-parse", "HEAD") != head - or git("rev-parse", "--abbrev-ref", "HEAD") != branch - ): - raise RuntimeError("HEAD or the branch changed after verification") - target = f"{head}:refs/heads/{branch}" - if step(["git", "push", "--force-with-lease", "-u", args.remote, target]): - return 1 - # Git only configures -u automatically when the source is a branch ref. - git("branch", "--set-upstream-to", f"{args.remote}/{branch}", branch) - return 0 if args.no_pr else open_pr(args.remote, branch, args.label) - except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error: - print(f"./push: {error}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - sys.exit(main()) +os.execvp("uvx", ["uvx", "--from", PROOFT_SOURCE, "prooft", "--push", *sys.argv[1:]]) diff --git a/tests/unit/test_push_attestation.py b/tests/unit/test_push_attestation.py index d2fcf455..48ed26d1 100644 --- a/tests/unit/test_push_attestation.py +++ b/tests/unit/test_push_attestation.py @@ -1,153 +1,114 @@ -"""Exercise the publishing contract without a real remote or Rust build.""" +"""Pin the publishing contract: ./push delegates to the prooft runner (GATE-014).""" +import ast +import runpy import subprocess from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[2] -VERIFY = ROOT / "ci/prooft_verify.py" - - -def git(repo: Path, *args: str) -> str: - return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip() +PUSH = ROOT / "push" +POLICY = ROOT / "ci-attestations.yml" @pytest.fixture -def checkout(tmp_path): - git(tmp_path, "init", "--initial-branch=main") - git(tmp_path, "config", "user.email", "test@example.com") - git(tmp_path, "config", "user.name", "FastLED test") - (tmp_path / "push").write_bytes((ROOT / "push").read_bytes()) - (tmp_path / "ci").mkdir() - (tmp_path / "ci/__init__.py").touch() - (tmp_path / "ci/prooft_verify.py").write_bytes(VERIFY.read_bytes()) - git(tmp_path, "add", ".") - git(tmp_path, "commit", "-m", "test") - return tmp_path - - -def run_push(repo: Path, *args: str): - return subprocess.run( - ["uv", "run", "--no-project", "python", "push", *args], - cwd=repo, - text=True, - capture_output=True, - check=False, - ) - +def delegate(monkeypatch): + """Run ./push in-process with os.execvp captured instead of replacing pytest.""" + import os + import platform + import sys -@pytest.mark.parametrize("state", ["main", "detached", "staged", "unstaged"]) -def test_refuses_unprovable_checkout(checkout, state): - if state == "detached": - git(checkout, "checkout", "--detach") - if state in {"staged", "unstaged"}: - git(checkout, "checkout", "-b", "feature") - with (checkout / "push").open("a") as stream: - stream.write("\n") - if state == "staged": - git(checkout, "add", "push") - assert run_push(checkout).returncode == 3 + calls = [] + monkeypatch.syspath_prepend(str(ROOT)) + monkeypatch.setattr(platform, "system", lambda: "Linux") + monkeypatch.setattr(platform, "machine", lambda: "x86_64") + monkeypatch.setattr(platform, "libc_ver", lambda: ("glibc", "2.39")) + monkeypatch.setattr(os, "execvp", lambda file, argv: calls.append((file, argv))) + def run(*args: str): + monkeypatch.setattr(sys, "argv", ["push", *args]) + runpy.run_path(str(PUSH), run_name="__main__") + return calls -def test_no_proof_bypass(checkout): - assert run_push(checkout, "--no-proof").returncode == 2 + return run -@pytest.fixture -def publisher(checkout, monkeypatch): - from importlib.machinery import SourceFileLoader - from importlib.util import module_from_spec, spec_from_loader +@pytest.mark.parametrize("args", [(), ("--test",), ("--no-pr", "--remote", "mirror")]) +def test_push_execs_the_pinned_prooft_runner(delegate, args): + from ci.prooft_verify import PROOFT_SOURCE - monkeypatch.syspath_prepend(str(ROOT)) - spec = spec_from_loader( - "publisher", SourceFileLoader("publisher", str(checkout / "push")) - ) - assert spec and spec.loader - module = module_from_spec(spec) - spec.loader.exec_module(module) - monkeypatch.setattr(module, "ROOT", checkout) - monkeypatch.setattr(module.platform, "system", lambda: "Linux") - monkeypatch.setattr(module.platform, "machine", lambda: "x86_64") - monkeypatch.setattr(module.platform, "libc_ver", lambda: ("glibc", "2.39")) - git(checkout, "checkout", "-b", "feature") - (checkout / "untracked.txt").write_text("untracked changes are allowed") - return module + assert delegate(*args) == [ + ("uvx", ["uvx", "--from", PROOFT_SOURCE, "prooft", "--push", *args]) + ] @pytest.mark.parametrize( - ("failure", "flags", "expected", "commands"), - [ - (None, ["--no-pr"], 0, ["lint", "test", "verify", "push"]), - (None, ["--prove-only"], 0, ["lint", "test", "verify"]), - ("lint", [], 1, ["lint"]), - ("test", [], 1, ["lint", "test"]), - ("verify", [], 1, ["lint", "test", "verify"]), - ], + ("system", "machine", "libc"), + [("Darwin", "x86_64", ""), ("Linux", "aarch64", "glibc"), ("Linux", "x86_64", "")], ) -def test_attest_and_verify_before_push( - publisher, monkeypatch, failure, flags, expected, commands +def test_push_refuses_hosts_the_gates_do_not_name( + delegate, monkeypatch, system, machine, libc ): - import sys + import platform - calls = [] - states = {gate: "missing" for lane in publisher.LANES for gate in lane.gates} - - head = git(publisher.ROOT, "rev-parse", "HEAD") - - def verify(rev="HEAD"): - if calls: - assert rev == head - calls.append("verify") - return (1 if failure == "verify" else 0), states - return 0, states - - def step(argv): - if argv[0] == "git": - assert argv == [ - "git", - "push", - "--force-with-lease", - "-u", - "mirror", - f"{head}:refs/heads/feature", - ] - calls.append("push") - return 0 - assert argv[0:2] == ["uvx", "--from"] - assert argv[6] == "run" - lane = next(lane for lane in publisher.LANES if lane.name == argv[7]) - calls.append(lane.name) - assert argv[8:] == ["--", *lane.command] - if failure == lane.name: - return 1 - states.update(dict.fromkeys(lane.gates, "valid")) - return 0 - - monkeypatch.setattr(sys, "argv", ["push", "--remote", "mirror", *flags]) - actual_git = publisher.git - - def git_command(*args): - if args[0] == "branch": - assert args == ("branch", "--set-upstream-to", "mirror/feature", "feature") - return "" - return actual_git(*args) - - monkeypatch.setattr(publisher, "git", git_command) - monkeypatch.setattr(publisher, "proof_states", verify) - monkeypatch.setattr(publisher, "step", step) - assert publisher.main() == expected - assert calls == commands - - -def test_valid_lanes_are_reused(publisher, monkeypatch): - states = {gate: "valid" for lane in publisher.LANES for gate in lane.gates} - monkeypatch.setattr(publisher, "proof_states", lambda _rev="HEAD": (0, states)) - monkeypatch.setattr(publisher, "step", lambda *_: pytest.fail("ran a proven lane")) - publisher.attest() - - -def test_verifier_shares_pin_and_uses_base_policy(publisher, monkeypatch): + monkeypatch.setattr(platform, "system", lambda: system) + monkeypatch.setattr(platform, "machine", lambda: machine) + monkeypatch.setattr(platform, "libc_ver", lambda: (libc, "")) + with pytest.raises(SystemExit, match="Linux x86_64 with glibc"): + delegate() + + +def test_push_is_a_thin_python_delegate(): + source = PUSH.read_text() + assert source.startswith("#!/usr/bin/env python\n") + mode = subprocess.check_output( + ["git", "-C", str(ROOT), "ls-files", "-s", "push"], text=True + ) + assert mode.startswith("100755 ") + tree = ast.parse(source) + strings = { + node.value + for node in ast.walk(tree) + if isinstance(node, ast.Constant) and isinstance(node.value, str) + } + # The runner owns lint, tests, the push and the PR; ./push never does them. + assert not strings & {"git", "gh", "run", "soldr", "apply", "--no-lint"} + # One pin: the source comes from ci/prooft_verify.py, never a second literal. + assert "prooft@" not in source + code = [ + line + for line in source.splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + assert len(code) <= 25 + + +def test_policy_runs_lint_before_tests(): + lanes: dict[str, dict[str, str]] = {} + section = lane = None + for line in POLICY.read_text().splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line.startswith(" "): + section = line.rstrip(":") + elif section == "lanes" and not line.startswith(" "): + lane = line.strip().rstrip(":") + lanes[lane] = {} + elif section == "lanes" and lane: + key, _, value = line.strip().partition(":") + lanes[lane][key] = value.strip() + assert lanes["lint"]["stage"] == "lint" + assert lanes["lint"]["run"] == "[./lint]" + assert lanes["test"]["stage"] == "test" + assert lanes["test"]["run"] == ( + "[uv, run, --no-project, python, ci/attest_test.py]" + ) + assert list(lanes) == ["lint", "test"] + + +def test_verifier_shares_pin_and_uses_base_policy(monkeypatch): + monkeypatch.syspath_prepend(str(ROOT)) import ci.prooft_verify as verifier calls = [] @@ -160,7 +121,7 @@ def run(argv, **_): monkeypatch.setattr(verifier.subprocess, "run", run) assert verifier.main("base", "head", "--literal title") == 0 assert calls[0] == ["git", "fetch", "--no-tags", "origin", "head"] - assert calls[1] == publisher.prooft( + assert calls[1] == verifier.prooft( "plan", "--base", "base", @@ -180,64 +141,3 @@ def test_concurrency_tracks_host_load(monkeypatch, cpus, load, workers): from ci.attest_test import load_aware_workers assert load_aware_workers(cpus, load) == workers - - -def test_changed_head_refuses_to_publish(publisher, monkeypatch): - import sys - - monkeypatch.setattr(sys, "argv", ["push"]) - head = git(publisher.ROOT, "rev-parse", "HEAD") - - def attest(): - git(publisher.ROOT, "commit", "--allow-empty", "-m", "concurrent commit") - return head - - monkeypatch.setattr(publisher, "attest", attest) - monkeypatch.setattr( - publisher, "step", lambda *_: pytest.fail("published another HEAD") - ) - assert publisher.main() == 1 - - -@pytest.mark.parametrize("same_repository", [True, False]) -def test_open_pr_matches_pushed_repository(publisher, monkeypatch, same_repository): - url = "https://github.com/FastLED/cli.git" - branch = "feature" - git(publisher.ROOT, "remote", "add", "mirror", url) - calls = [] - - def gh_json(*args): - if args[:2] == ("repo", "view"): - assert args[2] == url - return {"nameWithOwner": "FastLED/cli", "url": url} - assert args[:6] == ("pr", "list", "--repo", url, "--head", branch) - owner = "FastLED" if same_repository else "another-fork" - return [ - {"headRepository": {"nameWithOwner": f"{owner}/cli"}, "headRefName": branch} - ] - - def create(argv): - calls.append(argv) - return 0 - - monkeypatch.setattr(publisher, "gh_json", gh_json) - monkeypatch.setattr(publisher, "step", create) - assert publisher.open_pr("mirror", branch, ["ci-test"]) == 0 - assert calls == ( - [] - if same_repository - else [ - [ - "gh", - "pr", - "create", - "--repo", - url, - "--fill", - "--head", - branch, - "--label", - "ci-test", - ] - ] - )