Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions ci-attestations.yml
Original file line number Diff line number Diff line change
@@ -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}
Expand Down
12 changes: 11 additions & 1 deletion ci/prooft_verify.py
Original file line number Diff line number Diff line change
@@ -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]

Expand Down
15 changes: 10 additions & 5 deletions docs/FRACTIONAL_CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
214 changes: 7 additions & 207 deletions push
Original file line number Diff line number Diff line change
@@ -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
Comment thread
zackees marked this conversation as resolved.
Resolved
"""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:]])
Comment thread
zackees marked this conversation as resolved.
Resolved
Loading
Loading