From fe6217ae5226ea2216d42c09f03ef04a0dcc6871 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 13:48:38 -0500 Subject: [PATCH] ci(release): accept a later first-parent commit's green run on the same package tree (proposal A) newest_green.py now accepts a successful push run on main for any first-parent commit between a package's subject and the tip, when the package tree there is identical (git diff --quiet) and the package's own jobs ran and passed. The merge queue pushing several merges at once leaves the subject with no run of its own; this stranded openadapt-flow 4.1.0. Runs that skipped the package's jobs, runs off the first-parent path, other branches, events and forks stay refused, and a tree change after the subject fails closed. --- .github/workflows/README.md | 7 +- scripts/ci/newest_green.py | 133 ++++++++++++++++----- scripts/ci/post_merge_batching.md | 19 ++- scripts/ci/release_plan.py | 3 +- tests/test_newest_green.py | 190 ++++++++++++++++++++++++++++++ 5 files changed, 315 insertions(+), 37 deletions(-) diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 0d1db81917..2d1dc438a3 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -278,8 +278,11 @@ A package publishes only when all of these hold: - The newest commit on main's first-parent history that changed the package has a successful push run on main, with the package's own jobs run and - passed (`scripts/ci/newest_green.py`). A cancelled or failed run blocks the - release until a re-run passes. + passed (`scripts/ci/newest_green.py`). A push run on a later first-parent + commit counts too when the package's tree there is identical and its jobs + ran and passed, as when the merge queue pushes several merges at once + (proposal A in `scripts/ci/post_merge_batching.md`). Otherwise a cancelled + or failed run blocks the release until a re-run passes. - Its version is not on PyPI, is higher than every version there, and has no tag yet. - Its CHANGELOG.md starts with an entry for exactly that version. diff --git a/scripts/ci/newest_green.py b/scripts/ci/newest_green.py index 848ddb89d5..4371773927 100644 --- a/scripts/ci/newest_green.py +++ b/scripts/ci/newest_green.py @@ -3,18 +3,27 @@ Every release follows one rule (desktop-release.yml set it first): take the newest commit on main's own history (first parent) that changed the package, -and require that commit's latest successful push run on main, with the -package's own jobs run and passed. The release then builds main's tip. Nothing -changed the package after that commit, so the package's tree is the one that -run tested. +the subject S, and require a successful push run on main with the package's +own jobs run and passed. The release then builds main's tip. Nothing changed +the package after S, so the package's tree is the one that run tested. + +The run may be S's own, or (proposal A in scripts/ci/post_merge_batching.md) +the push run of a later first-parent commit C on the way from S to the tip +whose package tree is identical to S's (checked with `git diff --quiet`, so a +wrong S fails closed). This covers the merge queue pushing several merges at +once: only the last commit of the push gets a run, and its scope diff (against +the previous tip) still selects the package. The newest qualifying C wins. +S's own runs are always looked up; later commits are found among the recent +successful push runs on main. python scripts/ci/newest_green.py flow --tip "$GITHUB_SHA" \\ --github-output "$GITHUB_OUTPUT" -It writes `sha` (the commit) and `run_id` (the green run), or exits 1 and -says why: no commit changed the package, the commit's run is still going, or -it failed and needs a re-run. Needs git history (fetch-depth: 0) and the gh -CLI with GH_TOKEN (actions: read). +It writes `sha` (the commit whose run passed) and `run_id` (the green run), or +exits 1 and says why: no commit changed the package, no run on S or a later +commit with the same package tree passed with the package's jobs, or the tree +changed after S. Needs git history (fetch-depth: 0) and the gh CLI with +GH_TOKEN (actions: read). """ from __future__ import annotations @@ -61,6 +70,10 @@ ), } FAILED = {"failure", "cancelled", "timed_out", "startup_failure"} +# How many recent successful push runs on main to search for a later commit. +RECENT_RUNS = 100 +# How many later commits' green runs to inspect for the package's jobs. +MAX_LATER_RUNS = 5 def subject(tip: str, paths: list[str]) -> str | None: @@ -73,6 +86,34 @@ def subject(tip: str, paths: list[str]) -> str | None: return out or None +def _git(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run(["git", *args], capture_output=True, text=True) + + +def is_ancestor(ancestor: str, commit: str) -> bool: + return _git("merge-base", "--is-ancestor", ancestor, commit).returncode == 0 + + +def tree_equal(subject: str, commit: str, paths: list[str]) -> bool: + """True when `paths` are identical at both commits; False on any error.""" + return _git("diff", "--quiet", subject, commit, "--", *paths).returncode == 0 + + +def candidates(tip: str, subject: str) -> list[str]: + """First-parent commits from tip back to subject, newest first. + + The subject is last. main() also checks that a commit descends from the + subject before it accepts that commit's run. + """ + out = subprocess.run( + ["git", "rev-list", "--first-parent", tip, f"^{subject}"], + check=True, + capture_output=True, + text=True, + ).stdout.split() + return [*out, subject] + + def select_run(runs: list[dict], sha: str, repo: str) -> dict | None: """The newest successful push run on this repository's main for `sha`.""" green = [ @@ -106,9 +147,9 @@ def job_problems(jobs: list[dict], prefixes: list[str]) -> list[str]: return problems -def _gh(path: str, key: str) -> list[dict]: +def _gh(path: str, key: str, paginate: bool = True) -> list[dict]: out = subprocess.run( - ["gh", "api", "--paginate", path, "--jq", f".{key}[]"], + ["gh", "api", *(["--paginate"] if paginate else []), path, "--jq", f".{key}[]"], check=True, capture_output=True, text=True, @@ -131,31 +172,65 @@ def main(argv: list[str] | None = None) -> int: if not sha: print(f"No commit on main changes {args.package}.", file=sys.stderr) return 1 - runs = _gh( - f"repos/{repo}/actions/workflows/{workflow}/runs" - f"?head_sha={sha}&event=push&branch=main&per_page=50", - "workflow_runs", + shas = candidates(args.tip, sha) + base = f"repos/{repo}/actions/workflows/{workflow}/runs" + # S's own runs (any state, for the message), plus the recent green push + # runs on main, where a later commit's run would be. + own = _gh( + f"{base}?head_sha={sha}&event=push&branch=main&per_page=50", "workflow_runs" + ) + recent = ( + _gh( + f"{base}?event=push&branch=main&status=success&per_page={RECENT_RUNS}", + "workflow_runs", + paginate=False, + ) + if len(shas) > 1 + else [] ) - run = select_run(runs, sha, repo) + runs = own + recent + run, problems_seen, looked_up = None, [], 0 + for later in shas: # newest first; the subject is last + green = select_run(runs, later, repo) + if green is None: + continue + if later != sha and not is_ancestor(sha, later): + continue + if not tree_equal(sha, later, paths): + print( + f"Refusing to release {args.package}: its tree at {later[:12]} " + f"differs from {sha[:12]}, the newest commit that changed it.", + file=sys.stderr, + ) + return 1 + if later != sha: + # Bound the API calls: a package unchanged for weeks has many + # later green runs that skipped its jobs. The subject is always + # checked, as before. + if looked_up >= MAX_LATER_RUNS: + continue + looked_up += 1 + problems = job_problems( + _gh(f"repos/{repo}/actions/runs/{green['id']}/jobs?per_page=100", "jobs"), + prefixes, + ) + if not problems: + run, sha = green, later + break + problems_seen.append( + f"run {green['id']} for {later[:12]} passed but {'; '.join(problems)}" + ) if run is None: - states = sorted({f"{r.get('status')}/{r.get('conclusion')}" for r in runs}) or [ + states = sorted({f"{r.get('status')}/{r.get('conclusion')}" for r in own}) or [ "none" ] + detail = f" ({'; '.join(problems_seen)})" if problems_seen else "" print( f"Refusing to release {args.package}: {sha[:12]}, the newest commit that " - f"changed it, has no successful {workflow} push run on main (runs: " - f"{', '.join(states)}). Wait for it, or re-run it until it passes.", - file=sys.stderr, - ) - return 1 - problems = job_problems( - _gh(f"repos/{repo}/actions/runs/{run['id']}/jobs?per_page=100", "jobs"), - prefixes, - ) - if problems: - print( - f"Refusing to release {args.package}: run {run['id']} for {sha[:12]} " - f"passed but {'; '.join(problems)}.", + f"changed it, has no successful {workflow} push run on main with its " + f"jobs passed (its runs: {', '.join(states)}), and neither does any " + f"later commit with the same package tree{detail}. Wait for one, or " + "re-run it until it passes.", file=sys.stderr, ) return 1 diff --git a/scripts/ci/post_merge_batching.md b/scripts/ci/post_merge_batching.md index 5bac57e979..7b2341eeab 100644 --- a/scripts/ci/post_merge_batching.md +++ b/scripts/ci/post_merge_batching.md @@ -1,8 +1,17 @@ -# Post-merge batching: accept a later commit's green run (design only) - -Status: proposal for the coordinator. Nothing here is implemented. The release -rule described under "Today" stays in force until a separate pull request -changes it. +# Post-merge batching: accept a later commit's green run + +Status: A is implemented in `scripts/ci/newest_green.py`, so it applies to +release-package.yml, release-program-graph.yml and release-and-publish.yml. +`desktop-release.yml` still uses the rule under "Today". B and C are not +implemented. + +A shipped without B on purpose. A merge-queue push that lands several merges +at once starts one push run, for its last commit, and that run's `scope` +diffs against the previous tip, so it already runs the jobs of every package +the batch changed. That is the case that stranded openadapt-flow 4.1.0 on +2026-12-01. A later run that skipped a package's jobs is still refused. +The script inspects at most five later commits' green runs, then the +subject's own runs, as before. ## Problem diff --git a/scripts/ci/release_plan.py b/scripts/ci/release_plan.py index 8beb604033..6f5af851db 100644 --- a/scripts/ci/release_plan.py +++ b/scripts/ci/release_plan.py @@ -6,7 +6,8 @@ every package and publishes a package when all of these hold: - the newest commit on main's first-parent history that changed the package - has a successful push run with the package's own jobs run and passed + has a successful push run with the package's own jobs run and passed, or + a later first-parent commit with the identical package tree does (scripts/ci/newest_green.py, the rule desktop-release.yml set); - the version in its pyproject.toml is not on PyPI, is higher than every version PyPI has, and has no tag yet; diff --git a/tests/test_newest_green.py b/tests/test_newest_green.py index 0912a8991e..19ce180de9 100644 --- a/tests/test_newest_green.py +++ b/tests/test_newest_green.py @@ -161,3 +161,193 @@ def test_every_released_package_has_a_rule() -> None: ]["inputs"]["package"]["options"] assert set(choices) - {"all"} <= set(NG.PACKAGES) assert {"desktop", "launcher", "program-graph"} <= set(NG.PACKAGES) + + +# Proposal A (scripts/ci/post_merge_batching.md): a green push run on a later +# first-parent commit whose package tree is identical to the subject's counts. + +FLOW_JOBS = [ + {"name": "flow core lint (ruff, mypy)", "conclusion": "success"}, + {"name": "flow core unit (shard 1/2)", "conclusion": "success"}, + {"name": "flow core unit (shard 2/2)", "conclusion": "success"}, + {"name": "flow core critical (golden)", "conclusion": "success"}, +] +SKIPPED_JOBS = [{**job, "conclusion": "skipped"} for job in FLOW_JOBS] + + +def _repo(tmp_path: Path) -> tuple[callable, dict[str, str]]: + def git(*args: str) -> str: + return subprocess.run( + ["git", "-C", str(tmp_path), *args], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + def commit(name: str, path: str, text: str) -> str: + target = tmp_path / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text) + git("add", "-A") + git("commit", "-qm", name) + return git("rev-parse", "HEAD") + + git("init", "-q", "-b", "main") + git("config", "user.email", "t@example.com") + git("config", "user.name", "t") + shas = { + "base": commit("base", "packages/flow/a.py", "0"), + "subject": commit("subject", "packages/flow/a.py", "1"), + "batched": commit("batched", "openadapt/x.py", "1"), + "later": commit("later", "openadapt/x.py", "2"), + "tip": commit("tip", "README.md", "x"), + } + # A side branch off the subject that main never merged. + git("checkout", "-qb", "side", shas["subject"]) + shas["side"] = commit("side", "README.md", "side") + git("checkout", "-q", "main") + return git, shas + + +def _main(monkeypatch, tmp_path, runs: list[dict], jobs: dict[int, list[dict]]): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + calls = [] + + def fake_gh(path: str, key: str, paginate: bool = True) -> list[dict]: + calls.append(path) + if key == "jobs": + run_id = int(path.split("/runs/")[1].split("/")[0]) + return jobs.get(run_id, []) + if "head_sha=" in path: + sha = path.split("head_sha=")[1].split("&")[0] + return [run for run in runs if run["head_sha"] == sha] + return [run for run in runs if run["conclusion"] == "success"] + + monkeypatch.setattr(NG, "_gh", fake_gh) + out = tmp_path / "out" + code = NG.main(["flow", "--tip", "HEAD", "--github-output", str(out)]) + return code, (out.read_text() if out.exists() else ""), calls + + +def _green(sha: str, run_id: int) -> dict: + return _run(id=run_id, head_sha=sha, html_url=f"https://example/{run_id}") + + +def test_candidates_run_from_the_tip_back_to_the_subject(tmp_path: Path) -> None: + _, shas = _repo(tmp_path) + import os + + cwd = os.getcwd() + os.chdir(tmp_path) + try: + assert NG.candidates(shas["tip"], shas["subject"]) == [ + shas["tip"], + shas["later"], + shas["batched"], + shas["subject"], + ] + assert NG.tree_equal(shas["subject"], shas["tip"], ["packages/flow"]) + assert not NG.tree_equal(shas["base"], shas["tip"], ["packages/flow"]) + finally: + os.chdir(cwd) + + +def test_a_later_green_run_with_the_package_jobs_is_accepted( + tmp_path: Path, monkeypatch +) -> None: + # The subject's push was batched: it has no run of its own. + _, shas = _repo(tmp_path) + runs = [_green(shas["later"], 11), _green(shas["tip"], 12)] + code, out, _ = _main(monkeypatch, tmp_path, runs, {11: FLOW_JOBS, 12: SKIPPED_JOBS}) + assert code == 0 + assert out == f"sha={shas['later']}\nrun_id=11\n" + + +def test_a_later_green_run_without_the_package_jobs_is_refused( + tmp_path: Path, monkeypatch, capsys +) -> None: + _, shas = _repo(tmp_path) + runs = [_green(shas["later"], 11), _green(shas["tip"], 12)] + code, out, _ = _main( + monkeypatch, tmp_path, runs, {11: SKIPPED_JOBS, 12: SKIPPED_JOBS} + ) + assert code == 1 and out == "" + assert "Refusing to release flow" in capsys.readouterr().err + + +def test_a_run_on_a_commit_off_the_first_parent_path_is_refused( + tmp_path: Path, monkeypatch +) -> None: + _, shas = _repo(tmp_path) + code, out, calls = _main( + monkeypatch, tmp_path, [_green(shas["side"], 13)], {13: FLOW_JOBS} + ) + assert code == 1 and out == "" + assert not any("/runs/13/" in call for call in calls) + + +def test_a_run_from_another_branch_or_event_is_refused( + tmp_path: Path, monkeypatch +) -> None: + _, shas = _repo(tmp_path) + runs = [ + {**_green(shas["later"], 14), "head_branch": "feature"}, + {**_green(shas["later"], 15), "event": "workflow_dispatch"}, + {**_green(shas["later"], 16), "repository": {"full_name": "fork/OpenAdapt"}}, + ] + code, _, _ = _main( + monkeypatch, tmp_path, runs, {14: FLOW_JOBS, 15: FLOW_JOBS, 16: FLOW_JOBS} + ) + assert code == 1 + + +def test_a_package_tree_change_after_the_subject_is_refused( + tmp_path: Path, monkeypatch, capsys +) -> None: + # A wrong subject must fail closed: pretend git named the base commit. + _, shas = _repo(tmp_path) + monkeypatch.setattr(NG, "subject", lambda tip, paths: shas["base"]) + code, out, _ = _main( + monkeypatch, tmp_path, [_green(shas["later"], 17)], {17: FLOW_JOBS} + ) + assert code == 1 and out == "" + assert "differs from" in capsys.readouterr().err + + +def test_the_subject_own_run_still_releases(tmp_path: Path, monkeypatch) -> None: + _, shas = _repo(tmp_path) + code, out, _ = _main( + monkeypatch, tmp_path, [_green(shas["subject"], 18)], {18: FLOW_JOBS} + ) + assert code == 0 + assert out == f"sha={shas['subject']}\nrun_id=18\n" + + +def test_the_newest_qualifying_commit_wins(tmp_path: Path, monkeypatch) -> None: + _, shas = _repo(tmp_path) + runs = [_green(shas["subject"], 19), _green(shas["batched"], 20)] + code, out, _ = _main(monkeypatch, tmp_path, runs, {19: FLOW_JOBS, 20: FLOW_JOBS}) + assert code == 0 + assert out == f"sha={shas['batched']}\nrun_id=20\n" + + +def test_later_run_lookups_are_bounded_but_the_subject_is_always_checked( + tmp_path: Path, monkeypatch +) -> None: + _, shas = _repo(tmp_path) + monkeypatch.setattr(NG, "MAX_LATER_RUNS", 1) + runs = [ + _green(shas["tip"], 21), + _green(shas["later"], 22), + _green(shas["subject"], 23), + ] + code, out, calls = _main( + monkeypatch, + tmp_path, + runs, + {21: SKIPPED_JOBS, 22: FLOW_JOBS, 23: FLOW_JOBS}, + ) + assert code == 0 + assert out == f"sha={shas['subject']}\nrun_id=23\n" + assert not any("/runs/22/" in call for call in calls)