Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

ci: skip main-push jobs a green PR run already passed on the identical tree (#5850)

Francesco Bonaccia9f89bf836a0
diff --git a/.github/scripts/ci_reuse_pr_result.py b/.github/scripts/ci_reuse_pr_result.py
new file mode 100644
index 0000000000..385573e3f9
--- /dev/null
+++ b/.github/scripts/ci_reuse_pr_result.py
@@ -0,0 +1,363 @@
+#!/usr/bin/env python3
+"""Reuse a green pull request run on the push to main that lands the same tree.
+
+A squash merge pushes a commit to main. When no other commit reached main
+between the pull request's last run and the merge, that commit's tree is
+byte for byte the tree the pull request run already tested (the run checks out
+GitHub's merge of the head onto main). Re-running those jobs on main spends
+runner time and proves nothing new.
+
+The same tree is not the same inputs. A job also reads what floats outside the
+repository: the runner image, `rust-toolchain@stable`, `node-version: "22"`,
+the newest uv. So the stamp carries a fingerprint of those, and a run is reused
+only when the fingerprint still matches and the run is recent (see MAX_AGE:
+unpinned pip, npm and apt installs cannot be fingerprinted).
+
+Two steps, both fail open (any doubt means "run everything"):
+
+ stamp On a pull_request run, record the tree that run tested and the
+ fingerprint of its floating inputs as a notice annotation on one job:
+ `ci-reuse tree=<40 hex> fp=<16 hex>`.
+ reuse On a push to main, find the pull request behind the commit, find its
+ successful runs of this same workflow, keep those whose stamp equals
+ the pushed tree and today's fingerprint, and report the names of their
+ successful jobs.
+
+`run` does the right one for the event and writes step outputs:
+
+ reused JSON array of job names whose result can be reused ([] if none)
+ <name> "true" when every job named in `--subset name=a|b|c` was reused
+ (all or nothing; "false" otherwise, and on every other event)
+
+`legs` removes already-reused legs from a matrix list.
+
+Only these jobs are skipped on main: ones that ran, with the same name, on a
+green run of the same workflow for the identical tree. Legs the pull request
+did not run (the macOS and Windows lanes) are never in the reused list, so they
+still run on main. Push runs on any other branch, nightly runs and manual runs
+are never reduced.
+
+The whole `run` step has a time budget (BUDGET_SECONDS). Every network call
+takes what is left of it; when it is spent the step answers "run everything".
+Workflows also give the step a hard `timeout-minutes: 1`.
+
+Modes (repository variable CI_REUSE_PR_RESULTS, passed as REUSE_MODE). Only
+these values are valid; anything else is treated as "off" (no reuse, no stamp):
+ unset or empty enforce
+ "on" enforce
+ "shadow" decide and report, but reuse nothing
+ "off" do nothing (the rollback switch; also stops writing stamps)
+Case and surrounding spaces are ignored; a value that is only spaces is invalid.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import subprocess
+import sys
+import time
+import urllib.request
+from datetime import datetime, timedelta, timezone
+from typing import Callable
+
+DEFAULT_BRANCH = "main"
+STAMP_RE = re.compile(r"^ci-reuse tree=([0-9a-f]{40}) fp=([0-9a-f]{16}|none)$")
+MAX_RUNS = 5
+# A run older than this is never reused. Pull requests merge in about 75 minutes
+# (p90 200); the cap bounds drift in inputs no fingerprint covers (pip, npm and
+# apt installs without pins, macOS and Windows runner images).
+MAX_AGE = timedelta(hours=6)
+BUDGET_SECONDS = 45
+CALL_SECONDS = 20
+MODES = ("on", "shadow", "off")
+
+Api = Callable[[str], object]
+
+_deadline: float | None = None
+
+
+def set_budget(seconds: float | None) -> None:
+ global _deadline
+ _deadline = None if seconds is None else time.monotonic() + seconds
+
+
+def time_left() -> float:
+ """Seconds one call may take; raises once the budget is spent."""
+ if _deadline is None:
+ return CALL_SECONDS
+ left = _deadline - time.monotonic()
+ if left <= 0.5:
+ raise TimeoutError("time budget spent")
+ return min(CALL_SECONDS, left)
+
+
+def gh_api(path: str) -> object:
+ out = subprocess.run(
+ ["gh", "api", path], check=True, capture_output=True, text=True, timeout=time_left()
+ ).stdout
+ return json.loads(out)
+
+
+def gh_api_jobs(path: str) -> list[dict]:
+ """All jobs of a run (the jobs endpoint pages at 100)."""
+ out = subprocess.run(
+ ["gh", "api", "--paginate", path, "--jq", ".jobs[]"],
+ check=True, capture_output=True, text=True, timeout=time_left(),
+ ).stdout
+ return [json.loads(line) for line in out.splitlines() if line.strip()]
+
+
+def tree_of(sha: str) -> str:
+ return subprocess.run(
+ ["git", "rev-parse", f"{sha}^{{tree}}"], check=True, capture_output=True, text=True, timeout=time_left()
+ ).stdout.strip()
+
+
+# ---- fingerprint of the inputs that float outside the repository -----------------
+
+
+def http_text(url: str) -> str:
+ req = urllib.request.Request(url, headers={"User-Agent": "cua-ci-reuse"})
+ with urllib.request.urlopen(req, timeout=time_left()) as resp:
+ return resp.read().decode()
+
+
+def _rust_stable() -> str:
+ # The hash of the manifest rustup resolves `stable` to: it changes on every release.
+ return http_text("https://static.rust-lang.org/dist/channel-rust-stable.toml.sha256").split()[0]
+
+
+def _node_22() -> str:
+ return re.search(r"node-v(22\.\d+\.\d+)", http_text("https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt")).group(1)
+
+
+def _python_312() -> str:
+ versions = re.findall(r'href="(3\.12\.\d+)/"', http_text("https://www.python.org/ftp/python/"))
+ return max(versions, key=lambda v: tuple(int(p) for p in v.split(".")))
+
+
+def _latest_release(repo: str) -> str:
+ return gh_api(f"repos/{repo}/releases/latest")["tag_name"]
+
+
+# Name -> how to resolve what the floating spec means today. A workflow lists
+# the ones its jobs use with `--float`.
+FLOATS: dict[str, Callable[[], str]] = {
+ "rust-stable": _rust_stable, # dtolnay/rust-toolchain@stable
+ "node-22": _node_22, # actions/setup-node with node-version "22"
+ "python-3.12": _python_312, # actions/setup-python with python-version "3.12"
+ "uv": lambda: _latest_release("astral-sh/uv"), # astral-sh/setup-uv (latest)
+ "python-standalone": lambda: _latest_release("astral-sh/python-build-standalone"), # uv's managed Python
+}
+
+
+def fingerprint(env: dict[str, str], floats: list[str], resolvers: dict[str, Callable[[], str]] | None = None) -> str:
+ """16 hex chars, or "none" when any input cannot be resolved (never matches)."""
+ resolvers = FLOATS if resolvers is None else resolvers
+ try:
+ if not env.get("ImageVersion"):
+ return "none"
+ parts = {"image": f"{env.get('ImageOS', '')}/{env['ImageVersion']}"}
+ for name in sorted(floats):
+ parts[name] = resolvers[name]()
+ return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()[:16]
+ except Exception:
+ return "none"
+
+
+# ---- decision --------------------------------------------------------------------
+
+
+def parse_time(value: str) -> datetime:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+def find_reusable(
+ api: Api,
+ jobs_of: Callable[[str], list[dict]],
+ repo: str,
+ sha: str,
+ tree: str,
+ run_id: str,
+ stamp_job: str,
+ fp_fn: Callable[[], str],
+ now: datetime,
+) -> tuple[list[str], str]:
+ """Names of jobs that already passed on `tree`, and a one-line reason."""
+ commit = api(f"repos/{repo}/commits/{sha}")
+ parents = commit.get("parents", [])
+ if len(parents) != 1:
+ return [], f"{sha[:10]} is not a single-parent commit"
+ prs = [
+ pr
+ for pr in api(f"repos/{repo}/commits/{sha}/pulls")
+ if pr.get("merge_commit_sha") == sha and pr.get("merged_at") and pr["base"]["ref"] == DEFAULT_BRANCH
+ ]
+ if len(prs) != 1:
+ return [], f"{sha[:10]} is not the squash commit of exactly one pull request"
+ pr = prs[0]
+ head = pr["head"]["sha"]
+ workflow_id = api(f"repos/{repo}/actions/runs/{run_id}")["workflow_id"]
+ runs = api(
+ f"repos/{repo}/actions/workflows/{workflow_id}/runs"
+ f"?head_sha={head}&event=pull_request&status=success&per_page=100"
+ )["workflow_runs"]
+ runs = sorted(runs, key=lambda r: r["created_at"], reverse=True)[:MAX_RUNS]
+ if not runs:
+ return [], f"PR #{pr['number']} has no successful run of this workflow on its head"
+ reused: list[str] = []
+ matched: list[str] = []
+ stamps = same_tree = too_old = 0
+ current_fp: str | None = None
+ for run in runs:
+ jobs = jobs_of(f"repos/{repo}/actions/runs/{run['id']}/jobs?filter=latest&per_page=100")
+ stamp = next((j for j in jobs if j["name"] == stamp_job), None)
+ if stamp is None:
+ continue
+ notes = api(f"repos/{repo}/check-runs/{stamp['id']}/annotations")
+ found = [m.groups() for n in notes if (m := STAMP_RE.match(n.get("message") or ""))]
+ stamps += len(found)
+ for stamped_tree, stamped_fp in found:
+ if stamped_tree != tree:
+ continue
+ same_tree += 1
+ if now - parse_time(run["created_at"]) > MAX_AGE:
+ too_old += 1
+ continue
+ if current_fp is None:
+ current_fp = fp_fn()
+ if "none" in (stamped_fp, current_fp) or stamped_fp != current_fp:
+ continue
+ matched.append(str(run["id"]))
+ for job in jobs:
+ if job["conclusion"] == "success" and job["name"] not in reused:
+ reused.append(job["name"])
+ break
+ if matched:
+ return reused, f"tree {tree[:10]} was tested green by PR #{pr['number']} run {', '.join(matched)}"
+ who = f"PR #{pr['number']}"
+ if not stamps:
+ return [], f"{who} runs carry no tree stamp"
+ if not same_tree:
+ return [], f"{who} was last tested on a different tree (main moved or the head changed)"
+ if too_old == same_tree:
+ return [], f"{who} tested this tree more than {MAX_AGE.total_seconds() / 3600:g} hours ago"
+ return [], f"{who} tested this tree, but the runner image or a floating tool version changed since"
+
+
+def parse_mode(raw: str | None) -> str | None:
+ """The mode, or None for a value that is not valid."""
+ if raw is None or raw == "":
+ return "on"
+ mode = raw.strip().lower()
+ return mode if mode in MODES else None
+
+
+def decide(
+ env: dict[str, str],
+ subsets: dict[str, list[str]],
+ stamp_job: str,
+ floats: list[str] | None = None,
+ api: Api = gh_api,
+ jobs_of: Callable[[str], list[dict]] = gh_api_jobs,
+ tree_fn: Callable[[str], str] = tree_of,
+ fp_fn: Callable[[], str] | None = None,
+ now: datetime | None = None,
+) -> tuple[list[str], dict[str, bool], str, str | None]:
+ """Returns (reused, subset flags, reason, annotation to print or None)."""
+ none = {name: False for name in subsets}
+ raw = env.get("REUSE_MODE")
+ mode = parse_mode(raw)
+ event = env.get("GITHUB_EVENT_NAME", "")
+ sha = env.get("GITHUB_SHA", "")
+ if mode is None:
+ return [], none, f"CI_REUSE_PR_RESULTS={raw!r} is not one of {', '.join(MODES)}: reuse is off", None
+ if mode == "off":
+ return [], none, "disabled by CI_REUSE_PR_RESULTS=off", None
+ fp_fn = fp_fn or (lambda: fingerprint(env, floats or []))
+ try:
+ if event == "pull_request":
+ tree = tree_fn(sha)
+ fp = fp_fn()
+ return [], none, f"stamped tree {tree[:10]} fp {fp}", f"::notice title=ci-reuse::ci-reuse tree={tree} fp={fp}"
+ if event != "push" or env.get("GITHUB_REF") != f"refs/heads/{DEFAULT_BRANCH}":
+ return [], none, f"{event or 'this event'} always runs everything", None
+ reused, why = find_reusable(
+ api, jobs_of, env["GITHUB_REPOSITORY"], sha, tree_fn(sha), env["GITHUB_RUN_ID"], stamp_job,
+ fp_fn, now or datetime.now(timezone.utc),
+ )
+ except Exception as err: # fail open: a lookup problem must never cost coverage
+ return [], none, f"lookup failed, running everything ({type(err).__name__}: {err})", None
+ flags = {name: bool(names) and all(n in reused for n in names) for name, names in subsets.items()}
+ if mode == "shadow":
+ return [], none, f"shadow: would reuse {len(reused)} jobs, {why}", None
+ return reused, flags, why, None
+
+
+def remaining_legs(legs: list[str], template: str, reused: list[str]) -> list[str]:
+ return [leg for leg in legs if template.replace("{os}", leg) not in reused]
+
+
+def write_outputs(pairs: dict[str, str]) -> None:
+ path = os.environ.get("GITHUB_OUTPUT")
+ for key, value in pairs.items():
+ print(f"{key}={value}")
+ if path:
+ with open(path, "a") as fh:
+ fh.write(f"{key}={value}\n")
+
+
+def summary(line: str) -> None:
+ path = os.environ.get("GITHUB_STEP_SUMMARY")
+ print(line)
+ if path:
+ with open(path, "a") as fh:
+ fh.write(line + "\n")
+
+
+def parse_subset(arg: str) -> tuple[str, list[str]]:
+ name, _, names = arg.partition("=")
+ return name, [n for n in names.split("|") if n]
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ run = sub.add_parser("run")
+ run.add_argument("--stamp-job", required=True, help="name of the job that carries the stamp annotation")
+ run.add_argument("--subset", action="append", default=[], metavar="OUTPUT=job|job|...")
+ run.add_argument("--float", action="append", default=[], choices=sorted(FLOATS), dest="floats",
+ help="a floating tool spec the workflow's jobs install (repeatable)")
+ run.add_argument("--budget", type=float, default=BUDGET_SECONDS, help="seconds for every lookup together")
+ legs = sub.add_parser("legs")
+ legs.add_argument("--template", required=True, help="job name with {os}, e.g. 'rust ({os})'")
+ legs.add_argument("--output", required=True)
+ args = parser.parse_args(argv)
+
+ if args.cmd == "run":
+ set_budget(args.budget)
+ subsets = dict(parse_subset(s) for s in args.subset)
+ reused, flags, why, note = decide(dict(os.environ), subsets, args.stamp_job, args.floats)
+ if note:
+ print(note)
+ summary(f"CI reuse: {why}")
+ if reused:
+ summary("Reused on this tree: " + ", ".join(f"`{n}`" for n in reused))
+ write_outputs({"reused": json.dumps(reused), **{k: str(v).lower() for k, v in flags.items()}})
+ return 0
+
+ reused = json.loads(os.environ.get("REUSED") or "[]")
+ all_legs = json.loads(os.environ["LEGS"])
+ left = remaining_legs(all_legs, args.template, reused)
+ write_outputs({args.output: json.dumps(left)})
+ if left != all_legs:
+ summary(f"CI reuse: `{args.template}` skips {sorted(set(all_legs) - set(left))}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/.github/scripts/tests/test_ci_reuse_pr_result.py b/.github/scripts/tests/test_ci_reuse_pr_result.py
new file mode 100644
index 0000000000..cf4f319150
--- /dev/null
+++ b/.github/scripts/tests/test_ci_reuse_pr_result.py
@@ -0,0 +1,523 @@
+"""Tests for ci_reuse_pr_result.py and its wiring in the three workflows that use it."""
+
+import json
+import re
+import sys
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+import yaml
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import ci_reuse_pr_result as reuse # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[3]
+WORKFLOWS = ROOT / ".github/workflows"
+
+REPO = "trycua/cua"
+SHA = "a" * 40
+HEAD = "b" * 40
+TREE = "c" * 40
+OTHER_TREE = "d" * 40
+FP = "1" * 16
+OTHER_FP = "2" * 16
+NOW = datetime(2026, 10, 24, 3, 0, tzinfo=timezone.utc)
+RUN_AT = "2026-10-24T01:00:00Z" # two hours before NOW
+STAMP_JOB = "contract clients / changes"
+PUSH = {
+ "GITHUB_EVENT_NAME": "push",
+ "GITHUB_REF": "refs/heads/main",
+ "GITHUB_SHA": SHA,
+ "GITHUB_REPOSITORY": REPO,
+ "GITHUB_RUN_ID": "900",
+}
+
+
+def world(*, tree=TREE, parents=1, prs=None, runs=None, jobs=None, notes=None):
+ """A fake GitHub: path -> response for the calls find_reusable makes."""
+ prs = [{"number": 7, "merge_commit_sha": SHA, "merged_at": "t", "base": {"ref": "main"}, "head": {"sha": HEAD}}] if prs is None else prs
+ runs = [{"id": 11, "created_at": RUN_AT}] if runs is None else runs
+ jobs = {
+ 11: [
+ {"id": 1, "name": STAMP_JOB, "conclusion": "success"},
+ {"id": 2, "name": "Portable contract parity (ubuntu-latest)", "conclusion": "success"},
+ {"id": 3, "name": "Portable contract parity (macos-latest)", "conclusion": "skipped"},
+ {"id": 4, "name": "Generated contract and SDK bindings", "conclusion": "success"},
+ ]
+ } if jobs is None else jobs
+ notes = {1: [{"message": f"ci-reuse tree={TREE} fp={FP}"}]} if notes is None else notes
+ calls = []
+
+ def api(path):
+ calls.append(path)
+ if path == f"repos/{REPO}/commits/{SHA}":
+ return {"parents": [{"sha": "p"}] * parents}
+ if path == f"repos/{REPO}/commits/{SHA}/pulls":
+ return prs
+ if path == f"repos/{REPO}/actions/runs/900":
+ return {"workflow_id": 55}
+ if path.startswith(f"repos/{REPO}/actions/workflows/55/runs?"):
+ assert f"head_sha={HEAD}" in path and "event=pull_request" in path and "status=success" in path
+ return {"workflow_runs": runs}
+ m = re.fullmatch(rf"repos/{REPO}/check-runs/(\d+)/annotations", path)
+ if m:
+ return notes.get(int(m.group(1)), [])
+ raise AssertionError(f"unexpected api call {path}")
+
+ def jobs_of(path):
+ m = re.fullmatch(rf"repos/{REPO}/actions/runs/(\d+)/jobs\?filter=latest&per_page=100", path)
+ assert m, path
+ return jobs[int(m.group(1))]
+
+ return api, jobs_of, calls
+
+
+def decide(env=None, subsets=None, tree=TREE, fp=FP, now=NOW, **kw):
+ api, jobs_of, calls = world(**kw)
+ out = reuse.decide(
+ {**PUSH, **(env or {})}, subsets or {}, STAMP_JOB, api=api, jobs_of=jobs_of, tree_fn=lambda sha: tree,
+ fp_fn=lambda: fp, now=now,
+ )
+ return (*out, calls)
+
+
+def test_reuses_the_jobs_that_passed_on_the_same_tree():
+ reused, flags, why, note, _ = decide(subsets={"all": ["Portable contract parity (ubuntu-latest)", "Generated contract and SDK bindings"]})
+ assert reused == [STAMP_JOB, "Portable contract parity (ubuntu-latest)", "Generated contract and SDK bindings"]
+ assert flags == {"all": True}
+ assert "PR #7" in why and note is None
+
+
+def test_skipped_jobs_are_never_reused():
+ reused, flags, *_ = decide(subsets={"mac": ["Portable contract parity (macos-latest)"]})
+ assert "Portable contract parity (macos-latest)" not in reused
+ assert flags == {"mac": False}
+
+
+def test_subset_is_all_or_nothing():
+ reused, flags, *_ = decide(subsets={"s": ["Generated contract and SDK bindings", "never ran on the PR"]})
+ assert "Generated contract and SDK bindings" in reused
+ assert flags == {"s": False}
+
+
+def test_empty_subset_is_never_true():
+ assert decide(subsets={"s": []})[1] == {"s": False}
+
+
+def test_a_different_tree_reuses_nothing():
+ # Main moved between the pull request run and the merge: the squash commit
+ # is a tree nobody tested, so every job runs.
+ reused, flags, why, *_ = decide(tree=OTHER_TREE, subsets={"s": ["Generated contract and SDK bindings"]})
+ assert reused == [] and flags == {"s": False}
+ assert "different tree" in why
+
+
+def test_unstamped_run_reuses_nothing():
+ reused, _, why, *_ = decide(notes={})
+ assert reused == [] and "no tree stamp" in why
+ assert decide(notes={1: [{"message": "something else"}]})[0] == []
+ # A stamp from before fingerprints existed has no fp and is not trusted.
+ assert decide(notes={1: [{"message": f"ci-reuse tree={TREE}"}]})[0] == []
+ assert decide(jobs={11: [{"id": 2, "name": "Generated contract and SDK bindings", "conclusion": "success"}]})[0] == []
+
+
+def test_stamp_on_another_job_is_ignored():
+ assert decide(notes={4: [{"message": f"ci-reuse tree={TREE}"}]})[0] == []
+
+
+def test_no_green_run_reuses_nothing():
+ reused, _, why, *_ = decide(runs=[])
+ assert reused == [] and "no successful run" in why
+
+
+def test_only_the_squash_commit_of_one_merged_pr_counts():
+ base = {"number": 7, "merged_at": "t", "base": {"ref": "main"}, "head": {"sha": HEAD}}
+ assert decide(prs=[])[0] == []
+ assert decide(prs=[{**base, "merge_commit_sha": "e" * 40}])[0] == [] # not the commit pushed
+ assert decide(prs=[{**base, "merge_commit_sha": SHA, "merged_at": None}])[0] == []
+ assert decide(prs=[{**base, "merge_commit_sha": SHA, "base": {"ref": "release"}}])[0] == []
+ two = [{**base, "merge_commit_sha": SHA}, {**base, "number": 8, "merge_commit_sha": SHA}]
+ assert decide(prs=two)[0] == []
+
+
[email protected]("parents", [0, 2])
+def test_merge_commits_and_root_commits_reuse_nothing(parents):
+ assert decide(parents=parents)[0] == []
+
+
+def test_a_lookup_error_runs_everything():
+ def boom(path):
+ raise RuntimeError("rate limited")
+
+ reused, flags, why, *_ = reuse.decide(PUSH, {"s": ["x"]}, STAMP_JOB, api=boom, jobs_of=None, tree_fn=lambda s: TREE)
+ assert reused == [] and flags == {"s": False} and "running everything" in why
+
+
+def test_runs_that_are_not_a_push_to_main_are_never_reduced():
+ for env in (
+ {"GITHUB_EVENT_NAME": "schedule"},
+ {"GITHUB_EVENT_NAME": "workflow_dispatch"},
+ {"GITHUB_REF": "refs/heads/feature"},
+ ):
+ _, _, _, _, calls = decide(env=env)
+ assert decide(env=env)[0] == [] and calls == []
+
+
+def test_pull_request_run_writes_a_stamp():
+ reused, flags, _, note, calls = decide(env={"GITHUB_EVENT_NAME": "pull_request", "GITHUB_REF": "refs/pull/7/merge"}, subsets={"s": ["x"]})
+ assert reused == [] and flags == {"s": False} and calls == []
+ assert note == f"::notice title=ci-reuse::ci-reuse tree={TREE} fp={FP}"
+ assert reuse.STAMP_RE.match(note.split("::")[-1])
+
+
+def test_modes():
+ subsets = {"s": ["Generated contract and SDK bindings"]}
+ reused, flags, why, *_ = decide(env={"REUSE_MODE": "shadow"}, subsets=subsets)
+ assert reused == [] and flags == {"s": False} and why.startswith("shadow: would reuse 3 jobs")
+ off = decide(env={"REUSE_MODE": "off"}, subsets=subsets)
+ assert off[0] == [] and off[4] == []
+ stamp_off = decide(env={"REUSE_MODE": "off", "GITHUB_EVENT_NAME": "pull_request"})
+ assert stamp_off[3] is None
+
+
[email protected]("raw", [None, "", "on", "ON", " on ", "On\n"])
+def test_valid_modes_that_enforce(raw):
+ env = {} if raw is None else {"REUSE_MODE": raw}
+ assert decide(env=env, subsets={"s": ["Generated contract and SDK bindings"]})[1] == {"s": True}
+
+
[email protected]("raw", ["shadow", " Shadow "])
+def test_shadow_is_case_and_space_insensitive(raw):
+ assert decide(env={"REUSE_MODE": raw}, subsets={"s": ["Generated contract and SDK bindings"]})[1] == {"s": False}
+
+
[email protected]("raw", ["disabled", " ", " ", "\t", "false", "0", "1", "true", "enabled", "off-", "o n", "yes", "no", "none"])
+def test_unknown_modes_mean_no_reuse_and_no_stamp(raw):
+ # Only the allowlisted words enable anything; a typo or a stray space must not
+ # silently turn skipping on.
+ reused, flags, why, note, calls = decide(env={"REUSE_MODE": raw}, subsets={"s": ["Generated contract and SDK bindings"]})
+ assert reused == [] and flags == {"s": False} and calls == []
+ assert "is not one of on, shadow, off" in why
+ stamp = decide(env={"REUSE_MODE": raw, "GITHUB_EVENT_NAME": "pull_request"})
+ assert stamp[3] is None
+
+
+def test_parse_mode():
+ assert reuse.parse_mode(None) == "on" and reuse.parse_mode("") == "on"
+ assert [reuse.parse_mode(x) for x in ("on", "SHADOW", " off ")] == ["on", "shadow", "off"]
+ assert all(reuse.parse_mode(x) is None for x in (" ", "disabled", "onn"))
+
+
+# ---- fingerprint: the tree is the same, the inputs may not be --------------------
+
+
+def test_a_new_toolchain_since_the_pr_run_reuses_nothing():
+ # dtolnay/rust-toolchain@stable moved between the PR run and the merge.
+ reused, flags, why, *_ = decide(fp=OTHER_FP, subsets={"s": ["Generated contract and SDK bindings"]})
+ assert reused == [] and flags == {"s": False}
+ assert "runner image or a floating tool version changed" in why
+
+
[email protected]("stamped,current", [("none", FP), (FP, "none"), ("none", "none")])
+def test_an_unresolved_fingerprint_never_matches(stamped, current):
+ notes = {1: [{"message": f"ci-reuse tree={TREE} fp={stamped}"}]}
+ assert decide(fp=current, notes=notes)[0] == []
+
+
+def test_a_run_older_than_the_cap_is_not_reused():
+ just_inside = (NOW - reuse.MAX_AGE + timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ just_outside = (NOW - reuse.MAX_AGE - timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ assert decide(runs=[{"id": 11, "created_at": just_inside}])[0] != []
+ reused, _, why, *_ = decide(runs=[{"id": 11, "created_at": just_outside}])
+ assert reused == [] and "hours ago" in why
+
+
+def test_fingerprint_is_only_resolved_when_a_stamp_matches_the_tree():
+ calls = []
+
+ def fp():
+ calls.append(1)
+ return FP
+
+ api, jobs_of, _ = world(tree=OTHER_TREE)
+ reuse.decide(PUSH, {}, STAMP_JOB, api=api, jobs_of=jobs_of, tree_fn=lambda s: OTHER_TREE, fp_fn=fp, now=NOW)
+ assert calls == []
+
+
+def resolvers(**override):
+ base = {"rust-stable": lambda: "r1", "node-22": lambda: "n1"}
+ return {**base, **override}
+
+
+def test_fingerprint_changes_with_each_input():
+ env = {"ImageOS": "ubuntu24", "ImageVersion": "20260101.1.0"}
+ base = reuse.fingerprint(env, ["rust-stable", "node-22"], resolvers())
+ assert re.fullmatch(r"[0-9a-f]{16}", base)
+ assert reuse.fingerprint(env, ["node-22", "rust-stable"], resolvers()) == base # order does not matter
+ assert reuse.fingerprint(env, ["rust-stable", "node-22"], resolvers(**{"rust-stable": lambda: "r2"})) != base
+ assert reuse.fingerprint(env, ["rust-stable", "node-22"], resolvers(**{"node-22": lambda: "n2"})) != base
+ assert reuse.fingerprint({**env, "ImageVersion": "20260108.1.0"}, ["rust-stable", "node-22"], resolvers()) != base
+ assert reuse.fingerprint(env, ["rust-stable"], resolvers()) != base # another set of floats
+
+
+def test_fingerprint_is_none_when_anything_cannot_be_resolved():
+ env = {"ImageOS": "ubuntu24", "ImageVersion": "20260101.1.0"}
+
+ def down():
+ raise OSError("network down")
+
+ assert reuse.fingerprint(env, ["rust-stable"], resolvers(**{"rust-stable": down})) == "none"
+ assert reuse.fingerprint(env, ["unknown-tool"], resolvers()) == "none"
+ assert reuse.fingerprint({}, ["rust-stable"], resolvers()) == "none" # not a GitHub-hosted image
+
+
+def test_every_float_the_workflows_use_has_a_resolver():
+ assert {"rust-stable", "node-22", "python-3.12", "uv", "python-standalone"} == set(reuse.FLOATS)
+
+
+# ---- the lookup never outlives its budget ----------------------------------------
+
+
+def test_a_spent_budget_runs_everything(monkeypatch):
+ reuse.set_budget(0)
+ try:
+ with pytest.raises(TimeoutError):
+ reuse.time_left()
+ reused, flags, why, *_ = reuse.decide(
+ PUSH, {"s": ["x"]}, STAMP_JOB, api=lambda p: reuse.gh_api(p), tree_fn=lambda s: TREE, fp_fn=lambda: FP
+ )
+ assert reused == [] and flags == {"s": False} and "running everything" in why
+ finally:
+ reuse.set_budget(None)
+
+
+def test_each_call_gets_what_is_left_of_the_budget():
+ reuse.set_budget(100)
+ try:
+ assert reuse.time_left() == reuse.CALL_SECONDS
+ finally:
+ reuse.set_budget(3)
+ try:
+ assert 0 < reuse.time_left() <= 3
+ finally:
+ reuse.set_budget(None)
+ assert reuse.time_left() == reuse.CALL_SECONDS
+
+
+def test_a_slow_lookup_is_cut_off_and_runs_everything():
+ def slow(path):
+ raise TimeoutError("gh api took too long")
+
+ reused, _, why, *_ = reuse.decide(PUSH, {"s": ["x"]}, STAMP_JOB, api=slow, tree_fn=lambda s: TREE, fp_fn=lambda: FP)
+ assert reused == [] and "running everything" in why
+
+
+def test_newest_matching_runs_all_contribute():
+ runs = [{"id": 11, "created_at": "2026-10-24T01:00:00Z"}, {"id": 12, "created_at": "2026-10-24T02:00:00Z"}]
+ jobs = {
+ 11: [{"id": 1, "name": STAMP_JOB, "conclusion": "success"}, {"id": 2, "name": "a", "conclusion": "success"}],
+ 12: [{"id": 5, "name": STAMP_JOB, "conclusion": "success"}, {"id": 6, "name": "b", "conclusion": "success"}],
+ }
+ notes = {1: [{"message": f"ci-reuse tree={OTHER_TREE} fp={FP}"}], 5: [{"message": f"ci-reuse tree={TREE} fp={FP}"}]}
+ reused = decide(runs=runs, jobs=jobs, notes=notes)[0]
+ assert reused == [STAMP_JOB, "b"] # run 11 tested another tree
+
+
+def test_remaining_legs():
+ reused = ["fmt, clippy, test (ubuntu-latest)", "relay e2e (docker)"]
+ legs = ["ubuntu-latest", "macos-26", "windows-latest"]
+ assert reuse.remaining_legs(legs, "fmt, clippy, test ({os})", reused) == ["macos-26", "windows-latest"]
+ assert reuse.remaining_legs(legs, "other ({os})", reused) == legs
+ assert reuse.remaining_legs(["ubuntu-latest"], "fmt, clippy, test ({os})", reused) == []
+
+
+def test_cli_writes_outputs_and_legs(tmp_path, monkeypatch, capsys):
+ out = tmp_path / "out"
+ monkeypatch.setenv("GITHUB_OUTPUT", str(out))
+ monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(tmp_path / "sum"))
+ monkeypatch.setenv("REUSED", json.dumps(["t (ubuntu-latest)"]))
+ monkeypatch.setenv("LEGS", json.dumps(["ubuntu-latest", "macos-26"]))
+ assert reuse.main(["legs", "--template", "t ({os})", "--output", "legs"]) == 0
+ assert out.read_text() == 'legs=["macos-26"]\n'
+ out.write_text("")
+ for var in PUSH:
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("GITHUB_EVENT_NAME", "schedule")
+ assert reuse.main(["run", "--stamp-job", "x", "--subset", "s=a|b"]) == 0
+ assert out.read_text().splitlines() == ["reused=[]", "s=false"]
+
+
+# ---- wiring in the workflows --------------------------------------------------
+
+
+def load(name):
+ return yaml.safe_load((WORKFLOWS / name).read_text())
+
+
+def job_names(workflow, expand_os=()):
+ """Every job name the workflow can produce (matrix.os expanded)."""
+ names = set()
+ for job in workflow["jobs"].values():
+ name = job.get("name")
+ if not name:
+ continue
+ if "matrix.os" in name:
+ for os_ in expand_os:
+ names.add(name.replace("${{ matrix.os }}", os_))
+ else:
+ names.add(name)
+ return names
+
+
+def reuse_run_command(workflow):
+ steps = workflow["jobs"]["reuse"]["steps"]
+ return next(s["run"] for s in steps if s.get("id") == "reuse")
+
+
+def test_cua_sdk_subset_names_are_real_jobs_with_the_pull_request_legs():
+ wf = load("ci-cua-sdk.yml")
+ command = reuse_run_command(wf)
+ names = re.search(r'--subset "pr_subset=([^"]+)"', command).group(1).split("|")
+ assert len(names) == len(set(names))
+ assert '--stamp-job "reuse PR results"' in command
+ assert wf["jobs"]["reuse"]["name"] == "reuse PR results"
+ assert set(names) <= job_names(wf, expand_os=("ubuntu-latest", "windows-latest"))
+
+
+def literals(expr):
+ return [json.loads(x) for x in re.findall(r"'(\[[^']*\])'", expr)]
+
+
+MATRIX_JOBS = {
+ # job id: legs a pull request runs and which of them are in the reused subset
+ "rust-lint": ["ubuntu-latest", "windows-latest"],
+ "rust": ["ubuntu-latest"],
+ "spaces-e2e": ["ubuntu-latest"],
+ "bindings": ["ubuntu-latest"],
+ "python": ["ubuntu-latest"],
+ "node": ["ubuntu-latest"],
+}
+
+
[email protected]("job_id", MATRIX_JOBS)
+def test_cua_sdk_matrix_on_main_is_the_full_matrix_minus_the_pull_request_legs(job_id):
+ wf = load("ci-cua-sdk.yml")
+ job = wf["jobs"][job_id]
+ assert "reuse" in (job["needs"] if isinstance(job["needs"], list) else [job["needs"]])
+ main_only, full, pr = literals(job["strategy"]["matrix"]["os"])
+ assert pr == MATRIX_JOBS[job_id]
+ assert main_only == [leg for leg in full if leg not in pr]
+ # Every dropped leg is one the subset covers, and none is dropped when it is not.
+ subset = re.search(r'--subset "pr_subset=([^"]+)"', reuse_run_command(wf)).group(1).split("|")
+ prefix = job["name"].split("(")[0].replace("${{ matrix.os }}", "").strip()
+ for leg in pr:
+ assert f"{prefix} ({leg})" in subset
+
+
+def test_cua_sdk_jobs_in_the_subset_skip_only_when_it_is_reused():
+ wf = load("ci-cua-sdk.yml")
+ skip = "needs.reuse.outputs.pr_subset != 'true'"
+ for job_id in ("crates-dry-run", "kotlin", "build-sdk", "build-fixtures", "build-cli", "browser"):
+ assert skip in wf["jobs"][job_id]["if"], job_id
+ assert wf["jobs"][job_id]["if"].startswith("${{ !cancelled() && ")
+ # The macOS and Windows legs of python/node still run when the Linux builds are skipped.
+ for job_id in ("python", "node"):
+ cond = wf["jobs"][job_id]["if"]
+ assert "pr_subset" not in cond and "!cancelled()" in cond
+ for need in ("build-sdk", "build-fixtures", "build-cli"):
+ assert f"needs.{need}.result != 'failure'" in cond and f"needs.{need}.result != 'cancelled'" in cond
+ # Jobs outside the subset are untouched by the reuse.
+ assert "reuse" not in str(wf["jobs"]["swift"])
+
+
+def test_cua_sdk_reuse_job_cannot_block_the_run():
+ wf = load("ci-cua-sdk.yml")
+ step = next(s for s in wf["jobs"]["reuse"]["steps"] if s.get("id") == "reuse")
+ assert step["continue-on-error"] is True
+ assert step["timeout-minutes"] == 1 # inside the job's 5 minutes, with room to spare
+ assert wf["jobs"]["reuse"]["timeout-minutes"] == 5
+ assert step["env"]["REUSE_MODE"] == "${{ vars.CI_REUSE_PR_RESULTS }}"
+ assert wf["jobs"]["reuse"]["permissions"] == {
+ "contents": "read", "actions": "read", "checks": "read", "pull-requests": "read",
+ }
+
+
+LANES = {
+ # workflow: (stamp job, matrix job id -> (name template, legs step id), job id -> name reused as is)
+ "ci-cua-spacesd.yml": (
+ "cua-spacesd / changes",
+ {"test": ("fmt, clippy, test ({os})", "legs_test")},
+ {"relay-e2e": "relay e2e (docker)"},
+ ),
+ "ci-cua-driver-contract-clients.yml": (
+ "contract clients / changes",
+ {
+ "mcp-client-discovery": ("MCP discovery in pinned clients ({os})", "legs_discovery"),
+ "runtime-parity": ("Portable contract parity ({os})", "legs_parity"),
+ },
+ {"verify": "Generated contract and SDK bindings"},
+ ),
+}
+
+
[email protected]("filename", LANES)
+def test_scoped_lanes_wiring(filename):
+ stamp_job, matrix_jobs, named_jobs = LANES[filename]
+ wf = load(filename)
+ changes = wf["jobs"]["changes"]
+ assert changes["name"] == stamp_job
+ steps = {s.get("id"): s for s in changes["steps"]}
+ assert f'--stamp-job "{stamp_job}"' in steps["reuse"]["run"]
+ assert steps["reuse"]["continue-on-error"] is True
+ assert steps["reuse"]["timeout-minutes"] == 1
+ assert changes["timeout-minutes"] == 5
+ for job_id, (template, step_id) in matrix_jobs.items():
+ job = wf["jobs"][job_id]
+ assert job["name"].replace("${{ matrix.os }}", "{os}") == template
+ step = steps[step_id]
+ assert f'--template "{template}"' in step["run"]
+ assert step["continue-on-error"] is True and step["timeout-minutes"] == 1
+ assert step["env"] == {"REUSED": "${{ steps.reuse.outputs.reused }}", "LEGS": "${{ steps.scope.outputs.matrix }}"}
+ assert job["strategy"]["matrix"]["os"] == f"${{{{ fromJSON(needs.changes.outputs.{step_id}) }}}}"
+ assert f"needs.changes.outputs.{step_id} != '[]'" in job["if"]
+ # A failed legs step falls back to the unreduced matrix.
+ assert changes["outputs"][step_id] == f"${{{{ steps.{step_id}.outputs.legs || steps.scope.outputs.matrix }}}}"
+ for job_id, name in named_jobs.items():
+ job = wf["jobs"][job_id]
+ assert job["name"] == name
+ assert f"!contains(fromJSON(needs.changes.outputs.reused), '{name}')" in job["if"]
+ assert changes["outputs"]["reused"] == "${{ steps.reuse.outputs.reused || '[]' }}"
+ assert {"actions": "read", "checks": "read"}.items() <= changes["permissions"].items()
+
+
[email protected]("filename", ["ci-cua-sdk.yml", *LANES])
+def test_script_change_triggers_the_workflow(filename):
+ wf = load(filename)
+ for event in ("pull_request", "push"):
+ assert ".github/scripts/ci_reuse_pr_result.py" in wf[True][event]["paths"]
+
+
+# What each workflow's jobs install from a floating spec: the stamp must cover it.
+FLOATING = {
+ "ci-cua-spacesd.yml": {"rust-stable"},
+ "ci-cua-driver-contract-clients.yml": {"node-22", "python-3.12"},
+ "ci-cua-sdk.yml": {"node-22", "uv", "python-standalone"},
+}
+
+
[email protected]("filename", FLOATING)
+def test_floating_inputs_are_fingerprinted(filename):
+ text = (WORKFLOWS / filename).read_text()
+ flags = set(re.findall(r"--float ([\w.\-]+)", text))
+ assert flags == FLOATING[filename]
+ assert flags <= set(reuse.FLOATS)
+ # Anything the workflow installs from a moving spec has to be in the list.
+ if "dtolnay/rust-toolchain@stable" in text:
+ assert "rust-stable" in flags
+ if 'node-version: "22"' in text:
+ assert "node-22" in flags
+ if 'python-version: "3.12"' in text:
+ assert "python-3.12" in flags
+ if "astral-sh/setup-uv" in text:
+ assert {"uv", "python-standalone"} <= flags
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index aecc111693..cc9af43ea6 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -30,6 +30,7 @@ on:
- ".github/workflows/cd-py-cua-driver.yml"
- ".github/workflows/ci-cua-driver-contract-clients.yml"
- ".github/scripts/ci_component_scope.py"
+ - ".github/scripts/ci_reuse_pr_result.py"
push:
branches: [main]
paths:
@@ -60,6 +61,7 @@ on:
- ".github/workflows/cd-py-cua-driver.yml"
- ".github/workflows/ci-cua-driver-contract-clients.yml"
- ".github/scripts/ci_component_scope.py"
+ - ".github/scripts/ci_reuse_pr_result.py"
workflow_dispatch:
permissions:
@@ -86,9 +88,14 @@ jobs:
permissions:
contents: read
pull-requests: read
+ actions: read
+ checks: read
outputs:
run: ${{ steps.scope.outputs.run }}
matrix: ${{ steps.scope.outputs.matrix }}
+ reused: ${{ steps.reuse.outputs.reused || '[]' }}
+ legs_discovery: ${{ steps.legs_discovery.outputs.legs || steps.scope.outputs.matrix }}
+ legs_parity: ${{ steps.legs_parity.outputs.legs || steps.scope.outputs.matrix }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
@@ -110,17 +117,46 @@ jobs:
files=$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files?per_page=100" --jq '.[].filename')
fi
python3 .github/scripts/ci_component_scope.py contract-clients <<< "$files" | tee -a "$GITHUB_STEP_SUMMARY"
+ # Reuse results by tree: a squash-merge push whose exact tree a green pull
+ # request run of this workflow already tested skips the lanes that run
+ # did. Lanes the pull request never ran (other OSes) still run. Any doubt
+ # means "run everything": see .github/scripts/ci_reuse_pr_result.py.
+ # Rollback: set the repository variable CI_REUSE_PR_RESULTS to "off".
+ # A step that cannot finish in a minute is killed and the suites run in
+ # full: the lookup never eats the job's 5 minutes.
+ - id: reuse
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REUSE_MODE: ${{ vars.CI_REUSE_PR_RESULTS }}
+ # Floating inputs the jobs install: setup-node "22" and setup-python "3.12".
+ run: python3 .github/scripts/ci_reuse_pr_result.py run --stamp-job "contract clients / changes" --float node-22 --float python-3.12
+ - id: legs_discovery
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ REUSED: ${{ steps.reuse.outputs.reused }}
+ LEGS: ${{ steps.scope.outputs.matrix }}
+ run: python3 .github/scripts/ci_reuse_pr_result.py legs --template "MCP discovery in pinned clients ({os})" --output legs
+ - id: legs_parity
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ REUSED: ${{ steps.reuse.outputs.reused }}
+ LEGS: ${{ steps.scope.outputs.matrix }}
+ run: python3 .github/scripts/ci_reuse_pr_result.py legs --template "Portable contract parity ({os})" --output legs
mcp-client-discovery:
name: MCP discovery in pinned clients (${{ matrix.os }})
needs: changes
- if: needs.changes.outputs.run == 'true'
+ if: needs.changes.outputs.run == 'true' && needs.changes.outputs.legs_discovery != '[]'
runs-on: ${{ matrix.os }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON(needs.changes.outputs.matrix) }}
+ os: ${{ fromJSON(needs.changes.outputs.legs_discovery) }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: dtolnay/rust-toolchain@4716b85f2fac3e324e64fa2810f6b5c3905760a5 # 1.97.1
@@ -175,13 +211,13 @@ jobs:
runtime-parity:
name: Portable contract parity (${{ matrix.os }})
needs: changes
- if: needs.changes.outputs.run == 'true'
+ if: needs.changes.outputs.run == 'true' && needs.changes.outputs.legs_parity != '[]'
runs-on: ${{ matrix.os }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON(needs.changes.outputs.matrix) }}
+ os: ${{ fromJSON(needs.changes.outputs.legs_parity) }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: dtolnay/rust-toolchain@4716b85f2fac3e324e64fa2810f6b5c3905760a5 # 1.97.1
@@ -257,7 +293,7 @@ jobs:
verify:
name: Generated contract and SDK bindings
needs: changes
- if: needs.changes.outputs.run == 'true' && contains(needs.changes.outputs.matrix, 'ubuntu')
+ if: needs.changes.outputs.run == 'true' && contains(needs.changes.outputs.matrix, 'ubuntu') && !contains(fromJSON(needs.changes.outputs.reused), 'Generated contract and SDK bindings')
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.yml
index 88fe6dd04e..a1f4ba1e8e 100644
--- a/.github/workflows/ci-cua-sdk.yml
+++ b/.github/workflows/ci-cua-sdk.yml
@@ -17,6 +17,7 @@ on:
- "libs/cua-spacesd/tests/spaces-e2e/**"
- ".github/workflows/ci-cua-sdk.yml"
- ".github/actions/linux-rust-prep/**"
+ - ".github/scripts/ci_reuse_pr_result.py"
push:
branches: [main]
paths:
@@ -27,6 +28,7 @@ on:
- "libs/cua-driver/rust/**"
- ".github/workflows/ci-cua-sdk.yml"
- ".github/actions/linux-rust-prep/**"
+ - ".github/scripts/ci_reuse_pr_result.py"
schedule:
- cron: "41 18 * * *"
workflow_dispatch:
@@ -61,17 +63,59 @@ env:
CARGO_BUILD_JOBS: "4"
jobs:
- rust-lint:
+ # Reuse results by tree: a squash-merge push to main whose tree a green pull
+ # request run of this workflow already tested skips the jobs that run did
+ # (the Linux set below). The macOS and Windows legs only run on main, so they
+ # always run there. Any doubt means "run everything": see
+ # .github/scripts/ci_reuse_pr_result.py. Rollback: set the repository
+ # variable CI_REUSE_PR_RESULTS to "off".
+ reuse:
if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ name: reuse PR results
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ actions: read
+ checks: read
+ pull-requests: read
+ outputs:
+ reused: ${{ steps.reuse.outputs.reused }}
+ pr_subset: ${{ steps.reuse.outputs.pr_subset }}
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ sparse-checkout: .github/scripts
+ # `pr_subset` is true only when every job a pull request runs (the names
+ # below, the Linux jobs) passed on this exact tree.
+ # A step that cannot finish in a minute is killed and the jobs run in
+ # full: the lookup never delays the suites by more than that.
+ # Floating inputs the subset's jobs install: setup-node "22" and
+ # setup-uv (latest uv, uv's managed Python).
+ - id: reuse
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REUSE_MODE: ${{ vars.CI_REUSE_PR_RESULTS }}
+ run: |
+ python3 .github/scripts/ci_reuse_pr_result.py run \
+ --stamp-job "reuse PR results" \
+ --float node-22 --float uv --float python-standalone \
+ --subset "pr_subset=rust (ubuntu-latest)|rust lint (ubuntu-latest)|rust lint (windows-latest)|crates.io dry run|spaces e2e (ubuntu-latest)|bindings drift (ubuntu-latest)|kotlin compile|build SDK (linux, release)|build test fixtures (linux)|build cua and cua-spaces CLIs (linux)|python smoke (ubuntu-latest)|node smoke (ubuntu-latest)|browser (wasm32) build + smoke"
+
+ rust-lint:
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') }}
name: rust lint (${{ matrix.os }})
runs-on: ${{ matrix.os }}
+ needs: reuse
# Windows clippy runs on every pull request: Windows-only compile errors
# used to surface only on release PRs.
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26","windows-latest"]' || '["ubuntu-latest","windows-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26"]' || '["ubuntu-latest","macos-26","windows-latest"]') || '["ubuntu-latest","windows-latest"]') }}
defaults:
run:
working-directory: libs/cua
@@ -141,15 +185,16 @@ jobs:
fi
rust:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') }}
name: rust (${{ matrix.os }})
runs-on: ${{ matrix.os }}
+ needs: reuse
# Tests only: lint runs in rust-lint, in parallel.
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26","windows-latest"]' || '["ubuntu-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26","windows-latest"]' || '["ubuntu-latest","macos-26","windows-latest"]') || '["ubuntu-latest"]') }}
defaults:
run:
working-directory: libs/cua
@@ -208,9 +253,10 @@ jobs:
# (a path dependency without a version, a file embedded from outside the
# crate, a dependency on an unpublished crate).
crates-dry-run:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
name: crates.io dry run
runs-on: ubuntu-latest
+ needs: reuse
timeout-minutes: 60
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -230,14 +276,15 @@ jobs:
# cua-spacesd server core in process. A standalone workspace so libs/cua
# never depends on the driver workspace (see the boundary check above).
spaces-e2e:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') }}
name: spaces e2e (${{ matrix.os }})
runs-on: ${{ matrix.os }}
+ needs: reuse
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26"]' || '["ubuntu-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26"]' || '["ubuntu-latest","macos-26"]') || '["ubuntu-latest"]') }}
defaults:
run:
working-directory: libs/cua-spacesd/tests/spaces-e2e
@@ -269,14 +316,15 @@ jobs:
RUST_MIN_STACK: "8388608"
bindings:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') }}
name: bindings drift (${{ matrix.os }})
runs-on: ${{ matrix.os }}
+ needs: reuse
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26"]' || '["ubuntu-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26"]' || '["ubuntu-latest","macos-26"]') || '["ubuntu-latest"]') }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: ./.github/actions/linux-rust-prep
@@ -304,11 +352,12 @@ jobs:
cargo run --locked -q -p cua-spaces --bin cua-spaces-control-fixtures -- --check
kotlin:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
# The generated binding must compile (an exported `close` once clashed
# with AutoCloseable.close; uniffi.toml renames such methods).
name: kotlin compile
runs-on: ubuntu-latest
+ needs: reuse
timeout-minutes: 20
container: gradle:8.10.2-jdk17
steps:
@@ -321,9 +370,10 @@ jobs:
# compile all of them: 45-55 minutes cold on a 2-vCPU runner). macOS and
# Windows legs (ci:full) still build their own.
build-sdk:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
name: build SDK (linux, release)
runs-on: ubuntu-latest
+ needs: reuse
timeout-minutes: 90
defaults:
run:
@@ -350,9 +400,10 @@ jobs:
compression-level: 1
build-fixtures:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
name: build test fixtures (linux)
runs-on: ubuntu-latest
+ needs: reuse
timeout-minutes: 90
defaults:
run:
@@ -379,9 +430,10 @@ jobs:
compression-level: 1
build-cli:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
name: build cua and cua-spaces CLIs (linux)
runs-on: ubuntu-latest
+ needs: reuse
timeout-minutes: 90
defaults:
run:
@@ -408,17 +460,20 @@ jobs:
compression-level: 1
python:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--')
+ && needs.build-sdk.result != 'failure' && needs.build-sdk.result != 'cancelled'
+ && needs.build-fixtures.result != 'failure' && needs.build-fixtures.result != 'cancelled'
+ && needs.build-cli.result != 'failure' && needs.build-cli.result != 'cancelled' }}
name: python smoke (${{ matrix.os }})
runs-on: ${{ matrix.os }}
- needs: [build-sdk, build-fixtures, build-cli]
+ needs: [reuse, build-sdk, build-fixtures, build-cli]
# A cold Windows run builds cua-sdk (release), the fixtures and the CLI:
# it passed 45 minutes still compiling.
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26","windows-latest"]' || '["ubuntu-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26","windows-latest"]' || '["ubuntu-latest","macos-26","windows-latest"]') || '["ubuntu-latest"]') }}
defaults:
run:
shell: bash
@@ -481,17 +536,20 @@ jobs:
--with "$WHEEL" --with-editable . pytest -q -p no:cacheprovider tests/test_conformance.py
node:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--')
+ && needs.build-sdk.result != 'failure' && needs.build-sdk.result != 'cancelled'
+ && needs.build-fixtures.result != 'failure' && needs.build-fixtures.result != 'cancelled'
+ && needs.build-cli.result != 'failure' && needs.build-cli.result != 'cancelled' }}
name: node smoke (${{ matrix.os }})
runs-on: ${{ matrix.os }}
- needs: [build-sdk, build-fixtures, build-cli]
+ needs: [reuse, build-sdk, build-fixtures, build-cli]
# A cold macOS run (release cua-sdk, fixtures, both CLIs) passed 45
# minutes still compiling, as python smoke did on Windows.
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
- os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && '["ubuntu-latest","macos-26"]' || '["ubuntu-latest"]') }}
+ os: ${{ fromJSON((github.event_name != 'pull_request' || startsWith(github.head_ref, 'release-please--') || contains(github.event.pull_request.labels.*.name, 'ci:full')) && (needs.reuse.outputs.pr_subset == 'true' && '["macos-26"]' || '["ubuntu-latest","macos-26"]') || '["ubuntu-latest"]') }}
defaults:
run:
working-directory: libs/cua
@@ -542,10 +600,10 @@ jobs:
npm --prefix typescript/integrations/pi-durable test
browser:
- if: ${{ !startsWith(github.head_ref, 'release-please--branches--') }}
+ if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--') && needs.reuse.outputs.pr_subset != 'true' }}
name: browser (wasm32) build + smoke
runs-on: ubuntu-latest
- needs: build-fixtures
+ needs: [reuse, build-fixtures]
timeout-minutes: 45
defaults:
run:
diff --git a/.github/workflows/ci-cua-spacesd.yml b/.github/workflows/ci-cua-spacesd.yml
index 97f13423bd..0f7c456ff3 100644
--- a/.github/workflows/ci-cua-spacesd.yml
+++ b/.github/workflows/ci-cua-spacesd.yml
@@ -31,6 +31,7 @@ on:
- ".github/workflows/ci-cua-spacesd.yml"
- ".github/actions/linux-rust-prep/**"
- ".github/scripts/ci_component_scope.py"
+ - ".github/scripts/ci_reuse_pr_result.py"
push:
branches: [main]
paths:
@@ -58,6 +59,7 @@ on:
- ".github/workflows/ci-cua-spacesd.yml"
- ".github/actions/linux-rust-prep/**"
- ".github/scripts/ci_component_scope.py"
+ - ".github/scripts/ci_reuse_pr_result.py"
workflow_dispatch:
permissions:
@@ -93,9 +95,13 @@ jobs:
permissions:
contents: read
pull-requests: read
+ actions: read
+ checks: read
outputs:
run: ${{ steps.scope.outputs.run }}
matrix: ${{ steps.scope.outputs.matrix }}
+ reused: ${{ steps.reuse.outputs.reused || '[]' }}
+ legs_test: ${{ steps.legs_test.outputs.legs || steps.scope.outputs.matrix }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
@@ -117,17 +123,39 @@ jobs:
files=$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files?per_page=100" --jq '.[].filename')
fi
python3 .github/scripts/ci_component_scope.py spacesd <<< "$files" | tee -a "$GITHUB_STEP_SUMMARY"
+ # Reuse results by tree: a squash-merge push whose exact tree a green pull
+ # request run of this workflow already tested skips the lanes that run
+ # did. Lanes the pull request never ran (other OSes) still run. Any doubt
+ # means "run everything": see .github/scripts/ci_reuse_pr_result.py.
+ # Rollback: set the repository variable CI_REUSE_PR_RESULTS to "off".
+ # A step that cannot finish in a minute is killed and the suites run in
+ # full: the lookup never eats the job's 5 minutes.
+ - id: reuse
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REUSE_MODE: ${{ vars.CI_REUSE_PR_RESULTS }}
+ # Floating inputs the jobs install: dtolnay/rust-toolchain@stable.
+ run: python3 .github/scripts/ci_reuse_pr_result.py run --stamp-job "cua-spacesd / changes" --float rust-stable
+ - id: legs_test
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ REUSED: ${{ steps.reuse.outputs.reused }}
+ LEGS: ${{ steps.scope.outputs.matrix }}
+ run: python3 .github/scripts/ci_reuse_pr_result.py legs --template "fmt, clippy, test ({os})" --output legs
test:
name: fmt, clippy, test (${{ matrix.os }})
needs: changes
- if: needs.changes.outputs.run == 'true'
+ if: needs.changes.outputs.run == 'true' && needs.changes.outputs.legs_test != '[]'
strategy:
fail-fast: false
matrix:
# macOS 26: the ScreenCaptureKit dependency compiles Metal bindings for
# macOS 26 APIs and needs that SDK.
- os: ${{ fromJSON(needs.changes.outputs.matrix) }}
+ os: ${{ fromJSON(needs.changes.outputs.legs_test) }}
runs-on: ${{ matrix.os }}
timeout-minutes: 60
defaults:
@@ -281,7 +309,7 @@ jobs:
relay-e2e:
name: relay e2e (docker)
needs: changes
- if: needs.changes.outputs.run == 'true' && contains(needs.changes.outputs.matrix, 'ubuntu')
+ if: needs.changes.outputs.run == 'true' && contains(needs.changes.outputs.matrix, 'ubuntu') && !contains(fromJSON(needs.changes.outputs.reused), 'relay e2e (docker)')
runs-on: ubuntu-latest
timeout-minutes: 90
defaults: