diff --git a/scripts/ci/delivery_workflows.py b/scripts/ci/delivery_workflows.py index 8fd51d10af03..34939680c88b 100644 --- a/scripts/ci/delivery_workflows.py +++ b/scripts/ci/delivery_workflows.py @@ -9,6 +9,13 @@ stuck past its timeout; the answer to that is capacity, not a cancel (run 40428578701, a DEV publish, was cancelled as an orphan on 2026-10-27). +The one exception is a run that never got going: "When nightly runs for older +commits are stuck waiting (queued for a runner or a gate), skip them and build +from the tip: cancel the stale runs and move the nightly branch to the tip" +(Leo, 2026-10-26). superseded_unstarted() below is that rule, read by the +queue janitor (which skips such runs) and by the agents' cancel guard, which +reads this file from origin/main. + Nightly promotion runs inside nightly.yml (promote-nightly-next), so the nightly glob covers it. A glob picks up a new workflow on its own; REQUIRED names make a rename or deletion fail the test instead of quietly dropping out. @@ -16,8 +23,12 @@ from __future__ import annotations +import datetime as _dt +import re +from collections.abc import Callable, Iterable, Mapping, Sequence from fnmatch import fnmatch from pathlib import PurePosixPath +from typing import Any DELIVERY_GLOBS = ( "nightly*.yml", # nightly.yml, nightly-sign.yml, nightly-next-*.yml @@ -56,3 +67,177 @@ def is_delivery_run(path: str | None, *names: str | None) -> bool: return True prefixes = DELIVERY_RUN_NAME_PREFIXES.get(_file_name(path), ()) return any(str(name or "").startswith(prefix) for name in names for prefix in prefixes) + + +# --- skipping a superseded run that never got going --------------------------- +# A delivery run may be skipped (cancelled) only when both hold: +# - its build has not started: no job is running or holds a runner, and no +# finished job did build work: one that ran on a Mac, ran longer than +# GATE_JOB_MAX, or whose name says it builds the app, compiles, signs, +# notarizes, verifies, publishes, promotes, uploads or makes deltas. Gate +# and input jobs that finished in a few minutes on Linux (decide, resolve +# inputs, pick a runner) are not the build. A queued job's started_at is +# set when it is queued, so it is never read as a start. +# - a newer head of the same branch has its own run of the same workflow, +# which builds the tip in its place: a delivery run itself (not an +# ordinary run of a shared workflow), from the same event and the same +# head repository (never a fork's branch of the same name), not finished +# other than in success, and whose own jobs show the same build: every job +# the old run waits on is listed there and not skipped or failed (a +# cache-only or throttled run skips them). +# Anything unread (no jobs list, no branch, head or head repository) is not a +# skip, and neither is a re-run (run_attempt > 1): only the latest attempt's +# jobs are read, and an earlier attempt may have built. +WAITING_JOB_STATUSES = frozenset({"queued", "waiting", "pending", "requested"}) +BUILD_JOB_NAME = re.compile( + r"publish|promot|sign|notari[sz]|release|upload|deploy|verif|delta|dmg|archive|compile|\bapp\b", + re.IGNORECASE) +GATE_JOB_MAX = _dt.timedelta(minutes=10) +KNOWN_CONCLUSIONS = frozenset({"success", "failure", "cancelled", "neutral", "timed_out", "action_required", + "stale", "startup_failure"}) + + +def _time(value: Any) -> _dt.datetime | None: + try: + return _dt.datetime.fromisoformat(str(value).replace("Z", "+00:00")) if value else None + except ValueError: + return None + + +def build_started(jobs: Iterable[Mapping[str, Any]]) -> str | None: + """Why the run's build counts as started, or None when only gate jobs have run and the rest waits.""" + for job in jobs: + name = str(job.get("name") or "") + status = job.get("status") + if status in WAITING_JOB_STATUSES: + if job.get("runner_name"): + return f"its job {name!r} has a runner" + continue + if status != "completed": + return f"its job {name!r} is {status or 'in an unknown state'}" + if job.get("conclusion") == "skipped": + continue + if job.get("conclusion") not in KNOWN_CONCLUSIONS: + return f"its job {name!r} finished with an unknown conclusion ({job.get('conclusion')!r})" + if any("macos" in str(label).lower() for label in job.get("labels") or ()): + return f"its job {name!r} ran on a Mac" + if BUILD_JOB_NAME.search(name): + return f"its job {name!r} has run" + started, completed = _time(job.get("started_at")), _time(job.get("completed_at")) + if started is None or completed is None: + return f"its job {name!r} has run, and for how long cannot be read" + if completed - started > GATE_JOB_MAX: + return f"its job {name!r} ran {int((completed - started).total_seconds() // 60)} min" + return None + + +def _workflow_key(run: Mapping[str, Any]) -> Any: + return run.get("workflow_id") or _file_name(run.get("path")) + + +def _head_repo(run: Mapping[str, Any]) -> str: + return str(((run.get("head_repository") or {}).get("full_name")) or "").lower() + + +def newer_head_runs(run: Mapping[str, Any], runs: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]: + """Delivery runs of the same workflow, event, head repository and branch, created after `run` at another head, + and not finished other than in success; newest first.""" + branch, sha, repo = run.get("head_branch"), run.get("head_sha"), _head_repo(run) + created = _time(run.get("created_at")) + if not branch or not sha or not repo or not run.get("event") or created is None: + return [] + found: dict[Any, tuple[_dt.datetime, Mapping[str, Any]]] = {} + for other in runs: + if _workflow_key(other) != _workflow_key(run) or other.get("head_branch") != branch: + continue + if not other.get("head_sha") or other.get("head_sha") == sha: + continue + if _head_repo(other) != repo or other.get("event") != run.get("event"): + continue + if other.get("run_attempt") != 1: # a re-run's jobs are only its latest attempt's; missing is unread + continue + if not is_delivery_run(other.get("path"), other.get("name"), other.get("display_title")): + continue + status = other.get("status") + if status == "completed" and other.get("conclusion") != "success": + continue + if status != "completed" and status not in WAITING_JOB_STATUSES and status != "in_progress": + continue # unknown or missing: unread + when = _time(other.get("created_at")) + if when is not None and when > created: + found[other.get("id")] = (when, other) + return [other for _, other in sorted(found.values(), key=lambda pair: pair[0], reverse=True)] + + +def is_build_job(job: Mapping[str, Any]) -> bool: + """A job that does build work: it asks for a Mac, or its name says it builds, signs or publishes.""" + return (any("macos" in str(label).lower() for label in job.get("labels") or ()) + or bool(BUILD_JOB_NAME.search(str(job.get("name") or "")))) + + +def builds_the_same(waiting: Sequence[str], other_jobs: Sequence[Mapping[str, Any]] | None) -> str | None: + """Why `other_jobs` (a newer run's) do not show that run doing the same work, or None when they do: each job + of the old run that is not skipped (`waiting`: those waiting and the gates that ran) is listed in the newer one + and has not been skipped or failed. A cache-only or throttled run skips its build jobs, and one still deciding + has not listed them yet.""" + if other_jobs is None: + return "its jobs could not be read" + listed: dict[str, list[Mapping[str, Any]]] = {} + for job in other_jobs: + listed.setdefault(str(job.get("name") or ""), []).append(job) + for name in sorted(set(waiting)): + legs = listed.get(name) or [] + want = list(waiting).count(name) + if len(legs) < want: + return f"it lists {len(legs)} job(s) {name!r} where the old run has {want}" + for leg in legs: + live = leg.get("status") in WAITING_JOB_STATUSES or leg.get("status") == "in_progress" + if not live and not (leg.get("status") == "completed" and leg.get("conclusion") == "success"): + return f"its job {name!r} was skipped, did not succeed, or is {leg.get('status') or 'unknown'}" + return None + + +REPLACEMENT_JOB_READS = 3 + + +def superseded_unstarted(run: Mapping[str, Any], jobs: Sequence[Mapping[str, Any]] | None, + runs: Iterable[Mapping[str, Any]], + jobs_of: Callable[[Mapping[str, Any]], Sequence[Mapping[str, Any]] | None] | None = None, + ) -> tuple[bool, str]: + """(True, why) when a delivery run may be skipped for the tip; (False, why not) otherwise. + + `jobs` is the run's complete latest-attempt job list (None when unread); `runs` are runs to find the newer + head's run among (the same workflow's runs on the branch, or every in-flight run); `jobs_of(newer)` reads a + newer run's jobs (None when unread), at most REPLACEMENT_JOB_READS of them. The newer run must show the same + build: each job the old run waits on is listed there and not skipped or failed.""" + if run.get("status") not in WAITING_JOB_STATUSES and run.get("status") != "in_progress": + return False, f"it is {run.get('status') or 'in an unknown state'}" + if jobs is None: + return False, "its jobs could not be read" + if run.get("run_attempt") != 1: + return False, (f"it is attempt {run.get('run_attempt')}, and an earlier attempt's jobs are not read" + if run.get("run_attempt") else "its attempt could not be read") + started = build_started(jobs) + if started: + return False, f"its build has started: {started}" + pending = [job for job in jobs if job.get("status") in WAITING_JOB_STATUSES] + if not any(is_build_job(job) for job in pending): + # Still at its gates (decide, inputs): whether it would build at all is not known yet, so nothing can show + # that a newer run does the same. + return False, "it waits on no build job yet, so what it would deliver cannot be matched" + # Every leg, with multiplicity: matrix legs may share a name, and each needs its own leg in the newer run. + waiting = sorted(str(job.get("name") or "") for job in jobs if job.get("conclusion") != "skipped") + newer = newer_head_runs(run, runs) + if not newer: + return False, f"no newer head of {run.get('head_branch') or 'its branch'} has its own run of this workflow" + if jobs_of is None: + return False, "the newer runs' jobs were not read" + why_not = "" + for other in newer[:REPLACEMENT_JOB_READS]: + problem = builds_the_same(waiting, jobs_of(other)) + if problem is None: + return True, (f"its build has not started ({len(pending)} job(s) waiting, only gate jobs done) and run " + f"{other.get('id')} builds the newer head {str(other.get('head_sha'))[:12]} of " + f"{run.get('head_branch')} with the same job(s)") + why_not = why_not or f"run {other.get('id')}: {problem}" + return False, f"no newer run of {run.get('head_branch')} shows the same build ({why_not})" diff --git a/scripts/ci/queue_janitor.py b/scripts/ci/queue_janitor.py index 4ee51e95921f..188ff1585901 100644 --- a/scripts/ci/queue_janitor.py +++ b/scripts/ci/queue_janitor.py @@ -160,6 +160,16 @@ (CI_JANITOR_ORPHAN_MINUTES, 120 by default) and never re-runs; a run (e) cancels this sweep is excluded from it. An orphan at an open pull request's head, whatever its event, is skipped like every category's (open_pr_at_head()). + +Superseded delivery runs are one more pass (skip_superseded_delivery): "When +nightly runs for older commits are stuck waiting (queued for a runner or a +gate), skip them and build from the tip: cancel the stale runs" (Leo, +2026-10-26). A nightly, DEV or promote run is cancelled only when +delivery_workflows.superseded_unstarted() says so: its build has not started +and a newer head of its branch has its own run of the same workflow. The +agents' cancel guard reads that same function, so the two never disagree. A +run's jobs are read again right before its cancel, and a run whose build +started in between is kept. Its own cap; no force-cancel. """ from __future__ import annotations @@ -194,7 +204,8 @@ import owned_warm_state # noqa: E402 import ui_tests_dispatch # noqa: E402 import starved_labels # noqa: E402 -from delivery_workflows import is_delivery_run # noqa: E402 +from delivery_workflows import REPLACEMENT_JOB_READS, build_started, is_delivery_run # noqa: E402 +from delivery_workflows import newer_head_runs, superseded_unstarted # noqa: E402 API = "https://api.github.com" @@ -2285,6 +2296,176 @@ def orphan_protected_reason(run: Mapping[str, Any]) -> str | None: PULL_REQUEST_EVENTS = ("pull_request", "pull_request_target") +# --- superseded delivery runs ---------------------------------------------------------------------------------- +SUPERSEDED_MAX_CANCELS = 10 +# A candidate with no newer run among the in-flight ones gets one listing of its workflow's runs on its branch +# (the newer run may have finished already); at most this many listings a sweep. +SUPERSEDED_BRANCH_LISTINGS = 3 +# Delivery runs whose jobs the sweep did not list (queued past GHOST_QUEUED_RUN_AGE): at most this many read a sweep. +SUPERSEDED_EXTRA_JOBS = 5 +# Jobs of newer runs the sweep did not list (a finished one found by a branch listing): at most this many a sweep. +SUPERSEDED_REPLACEMENT_READS = 5 + + +def complete_jobs(jobs: Sequence[Mapping[str, Any]] | None) -> Sequence[Mapping[str, Any]] | None: + """A job listing, or None (unread) when it filled every page GitHub.jobs() reads, so some jobs may be missing.""" + return None if jobs is None or len(jobs) >= 100 * MAX_JOB_PAGES else jobs + + +def superseded_candidates(runs: Sequence[Mapping[str, Any]], + jobs_by_run: Mapping[int, Sequence[Mapping[str, Any]]]) -> list[Mapping[str, Any]]: + """In-flight nightly, DEV or promote runs whose build has not started (no I/O), oldest first.""" + found = [run for run in runs + if run.get("status") in IN_FLIGHT_RUN_STATUSES and run.get("id") in jobs_by_run + and is_delivery_run(run.get("path"), run.get("name"), run.get("display_title")) + and complete_jobs(jobs_by_run[run["id"]]) is not None and build_started(jobs_by_run[run["id"]]) is None] + return sorted(found, key=lambda run: (str(run.get("created_at") or ""), run["id"])) + + +@dataclasses.dataclass +class SupersededDecision: + run: Mapping[str, Any] + action: str # "cancel" or "keep" + note: str + + +def skip_superseded_delivery( + github: "GitHub", + candidates: Sequence[Mapping[str, Any]], + runs: Sequence[Mapping[str, Any]], + jobs_by_run: Mapping[int, Sequence[Mapping[str, Any]]], + prs_by_branch: Mapping[str, Sequence[Mapping[str, Any]]], + *, + dry_run: bool, + max_cancels: int = SUPERSEDED_MAX_CANCELS, +) -> tuple[list[SupersededDecision], int]: + """Cancel each candidate delivery_workflows.superseded_unstarted() allows, re-reading its jobs first.""" + decisions: list[SupersededDecision] = [] + failures = 0 + listed: dict[tuple[Any, str], list[Mapping[str, Any]]] = {} + read_jobs: dict[int, list[dict[str, Any]] | None] = {} + + def jobs_of(other: Mapping[str, Any]) -> Sequence[Mapping[str, Any]] | None: + """A newer run's jobs: the sweep's listing, else one read (at most SUPERSEDED_REPLACEMENT_READS a sweep).""" + other_id = other.get("id") + if other_id in jobs_by_run: + return complete_jobs(jobs_by_run[other_id]) + if other_id not in read_jobs: + if len(read_jobs) >= SUPERSEDED_REPLACEMENT_READS or not isinstance(other_id, int): + return None + try: + read_jobs[other_id] = complete_jobs(github.jobs(other_id)) + except RateLimited: + raise + except RuntimeError as error: + read_jobs[other_id] = None + print(f"queue-janitor: jobs of run {other_id}: {error}", file=sys.stderr) + return read_jobs[other_id] + + cancels = 0 + for run in candidates: + run_id = run["id"] + ok, why = superseded_unstarted(run, complete_jobs(jobs_by_run.get(run_id)), runs, jobs_of) + if not ok and (why.startswith("no newer head") or why.startswith("no newer run")): + key = (run.get("workflow_id") or run.get("path"), str(run.get("head_branch") or "")) + if key not in listed and len(listed) < SUPERSEDED_BRANCH_LISTINGS: + try: + listed[key] = github.branch_runs(run) + except RateLimited: + raise + except RuntimeError as error: + listed[key] = [] + print(f"queue-janitor: runs of {key[1]} for run {run_id}: {error}", file=sys.stderr) + ok, why = superseded_unstarted(run, complete_jobs(jobs_by_run.get(run_id)), [*runs, *listed.get(key, [])], + jobs_of) + if not ok: + decisions.append(SupersededDecision(run, "keep", why)) + continue + at_head = open_pr_at_head(run, prs_by_branch.get(str(run.get("head_branch") or ""), ())) + if at_head is not None: + decisions.append(SupersededDecision(run, "keep", f"at the head of open PR #{at_head.get('number')}; " + f"{OPEN_HEAD_RULE}")) + continue + if cancels >= max_cancels: + decisions.append(SupersededDecision(run, "keep", f"cap of {max_cancels} reached")) + continue + if dry_run: + decisions.append(SupersededDecision(run, "cancel", f"would cancel: {why}")) + cancels += 1 + continue + # Right before the cancel, the run, its jobs and the newer runs that may replace it (each run and its jobs) + # are read again: a run whose build started since, or whose replacement failed or was cancelled, is kept. + try: + current, jobs = github.run(run_id), complete_jobs(github.jobs(run_id)) + # The run once more after its jobs: a re-run that began between the two reads changes its attempt. + after = github.run(run_id) + pool = [*runs, *[r for rs in listed.values() for r in rs]] + fresh_runs = [github.run(other["id"]) for other in newer_head_runs(current, pool)[:REPLACEMENT_JOB_READS]] + fresh_jobs = {other["id"]: complete_jobs(github.jobs(other["id"])) for other in fresh_runs} + # Each replacement once more after its jobs: one cancelled, failed or re-run meanwhile does not count. + for other in fresh_runs: + again = github.run(other["id"]) + if (again.get("run_attempt"), again.get("status"), again.get("conclusion")) != ( + other.get("run_attempt"), other.get("status"), other.get("conclusion")): + fresh_jobs[other["id"]] = None + except RateLimited: + raise + except RuntimeError as error: + failures += 1 + decisions.append(SupersededDecision(run, "keep", f"failed to re-read: {error}")) + continue + if (after.get("run_attempt"), after.get("status")) != (current.get("run_attempt"), current.get("status")): + decisions.append(SupersededDecision(run, "keep", "on re-read: it changed while its jobs were read")) + continue + ok, why = superseded_unstarted(current, jobs, fresh_runs, lambda other: fresh_jobs.get(other.get("id"))) + if not ok: + decisions.append(SupersededDecision(run, "keep", f"on re-read: {why}")) + continue + # The branch's open pull requests again too: one may have been opened at this head during the reads. + branch = str(current.get("head_branch") or "") + try: + fresh_prs = github.pull_requests([branch]).get(branch, []) if branch else [] + except RateLimited: + raise + except RuntimeError as error: + failures += 1 + decisions.append(SupersededDecision(run, "keep", f"failed to re-read open PRs: {error}")) + continue + at_head = open_pr_at_head(current, fresh_prs) + if at_head is not None: + decisions.append(SupersededDecision(run, "keep", f"on re-read, at the head of open PR " + f"#{at_head.get('number')}; {OPEN_HEAD_RULE}")) + continue + try: + github.cancel(run_id) + except RuntimeError as error: + if not _cancel_refused(error): + failures += 1 + decisions.append(SupersededDecision(run, "keep", f"cancel failed: {error}")) + continue + decisions.append(SupersededDecision(run, "cancel", f"cancelled: {why}")) + cancels += 1 + return decisions, failures + + +def render_superseded_summary(decisions: Sequence[SupersededDecision]) -> str: + lines = ["", "### Superseded nightly, DEV and promote runs", "", + "A delivery run whose build never started, at a head a newer run of its workflow on the same branch " + "has superseded with the same build jobs, is skipped so the tip builds (delivery_workflows.superseded_unstarted()).", ""] + if not decisions: + lines.append("None waiting.") + return "\n".join(lines) + "\n" + lines.append("| Decision | Run | Workflow | Head | Why |") + lines.append("| --- | --- | --- | --- | --- |") + for decision in decisions: + run = decision.run + url = run.get("html_url") or f"run {run.get('id')}" + name = str(run.get("name") or run.get("path") or "").replace("|", "\\|") + lines.append(f"| {decision.action} | {url} | {name} | {str(run.get('head_sha') or '')[:12]} | " + f"{decision.note.replace('|', '/')} |") + return "\n".join(lines) + "\n" + + def left_to_github(orphan: Orphan, now: dt.datetime) -> bool: """A ghost past GHOST_GIVE_UP_AGE that no human was asked to look at.""" return (orphan.job_name is None and orphan.queued_since is not None @@ -2812,6 +2993,13 @@ def runs_at_head(self, run: Mapping[str, Any]) -> list[dict[str, Any]]: payload = self.request("GET", f"/repos/{self.repo}/actions/workflows/{urllib.parse.quote(workflow)}/runs?{query}") return [other for other in payload.get("workflow_runs") or [] if isinstance(other, Mapping)] + def branch_runs(self, run: Mapping[str, Any]) -> list[dict[str, Any]]: + """One page of the newest runs of `run`'s workflow on its branch (skip_superseded_delivery()).""" + workflow = str(run.get("path") or "").rsplit("/", 1)[-1] + query = urllib.parse.urlencode({"branch": run.get("head_branch") or "", "per_page": 20}) + payload = self.request("GET", f"/repos/{self.repo}/actions/workflows/{urllib.parse.quote(workflow)}/runs?{query}") + return [other for other in payload.get("workflow_runs") or [] if isinstance(other, Mapping)] + def completed_runs(self, workflow: str, since: str) -> list[dict[str, Any]]: """One page of `workflow`'s completed runs created at or after `since`, newest first.""" query = urllib.parse.urlencode({"status": "completed", "created": f">={since}", @@ -3008,7 +3196,21 @@ def main(argv: Sequence[str] | None = None) -> int: # Orphans read only what is already fetched; their PR branches join # the one batched GraphQL lookup for the no-janitor label. orphans = find_orphans(runs, jobs_by_run, min_age=orphan_age, now=now) + # A delivery run queued past GHOST_QUEUED_RUN_AGE has no listing (needs_jobs()); read a few of them here. + delivery_jobs = dict(jobs_by_run) + unlisted = sorted((r for r in runs if r["id"] not in jobs_by_run and r.get("status") in IN_FLIGHT_RUN_STATUSES + and is_delivery_run(r.get("path"), r.get("name"), r.get("display_title"))), + key=lambda r: (str(r.get("created_at") or ""), r["id"])) # oldest first + for run in unlisted[:SUPERSEDED_EXTRA_JOBS]: + try: + delivery_jobs[run["id"]] = github.jobs(run["id"]) + except RateLimited: + raise + except RuntimeError as error: # unread: never a candidate + print(f"queue-janitor: jobs of delivery run {run['id']}: {error}", file=sys.stderr) + superseded = superseded_candidates(runs, delivery_jobs) branches = sorted(set(branches_to_resolve(runs, jobs_by_run)) | set(orphan_branches(orphans, now)) + | {str(run["head_branch"]) for run in superseded if run.get("head_branch")} | set(lost_branches(runs, {**lost, **unclaimed}, pending or []))) prs_by_branch = github.pull_requests(branches) if branches else {} except RuntimeError as error: @@ -3173,10 +3375,19 @@ def save_lost_reruns(entries: Sequence[Mapping[str, Any]]) -> None: orphan_results, orphan_failures = cancel_orphans(github, orphan_decisions) failures += orphan_failures + try: + superseded_decisions, superseded_failures = skip_superseded_delivery( + github, superseded, runs, delivery_jobs, prs_by_branch, dry_run=args.dry_run) + except RuntimeError as error: # a rate limit: what was cancelled before it is in the next sweep's inventory + print(f"queue-janitor: superseded delivery runs: {error}", file=sys.stderr) + superseded_decisions, superseded_failures = [], 1 + failures += superseded_failures + summary = render_summary(plan, dry_run=args.dry_run, now=now, results=results) summary += render_lost_reruns(rerun_decisions, dry_run=args.dry_run, results=rerun_results) summary += render_orphan_summary(orphan_decisions, dry_run=args.dry_run, now=now, min_age=orphan_age, results=orphan_results) + summary += render_superseded_summary(superseded_decisions) summary += f"\n_{len(runs)} in-flight runs, {len(jobs_by_run)} job listings, {len(branches)} PR branches, " \ f"{len(orphans)} orphans, {len(lost)} lost assignments, {len(unclaimed)} unclaimed legs, " \ f"{head_reads} branch head reads, {len(evidence_jobs)} evidence job listings, " \ diff --git a/tests/test_ci_queue_janitor.py b/tests/test_ci_queue_janitor.py index 49eed1228714..61be029b164e 100644 --- a/tests/test_ci_queue_janitor.py +++ b/tests/test_ci_queue_janitor.py @@ -1202,6 +1202,242 @@ def posts(self): return [path.rsplit("/", 2)[-2:] for method, path in self.log if method == "POST" and "graphql" not in path] +def nightly_run(sha, age, *, status="queued", branch="nightly-next"): + run = make_run(event="push", branch=branch, path=".github/workflows/nightly.yml", name="Nightly macOS build", + status=status, sha=sha, age=age) + run["workflow_id"] = 234270400 + return run + + +def gate_jobs(age, *, build=None): + """Run 40505473184's shape: Linux gate jobs done in minutes, `build-nightly-app` queued for a Mac.""" + jobs = [{"name": "decide", "status": "completed", "conclusion": "success", "labels": [LINUX], + "runner_name": "r1", "started_at": iso(age), "completed_at": iso(age - 1)}, + {"name": "build nightly inputs", "status": "completed", "conclusion": "success", "labels": [LINUX], + "runner_name": "r2", "started_at": iso(age - 1), "completed_at": iso(age - 4)}, + {"name": "promote-nightly-next", "status": "completed", "conclusion": "skipped", "labels": [LINUX], + "started_at": iso(age), "completed_at": iso(age)}, + # GitHub sets a queued job's started_at when it is queued. + {"name": "build-nightly-app", "status": "queued", "conclusion": None, "labels": [MAC], + "runner_name": None, "started_at": iso(age - 2), "completed_at": None}] + if build: + jobs[-1].update(build) + return jobs + + +class SupersededDeliveryTests(unittest.TestCase): + """Leo, 2026-10-26: "When nightly runs for older commits are stuck waiting (queued for a runner or a gate), + skip them and build from the tip: cancel the stale runs and move the nightly branch to the tip".""" + + def judge(self, old, old_jobs, runs, newer_jobs=None): + # Every newer run lists the same waiting build job unless told otherwise. + return janitor.superseded_unstarted(old, old_jobs, runs, + lambda other: (newer_jobs or {}).get(other["id"], gate_jobs(10))) + + def test_unstarted_on_a_superseded_head_is_skipped(self): + old, new = nightly_run("864dceb6", 60), nightly_run("ccb74c4d", 20) + ok, why = self.judge(old, gate_jobs(60), [old, new]) + self.assertTrue(ok, why) + self.assertIn(str(new["id"]), why) + + def test_a_started_build_on_an_old_head_is_kept(self): + old, new = nightly_run("864dceb6", 60), nightly_run("ccb74c4d", 20) + for build in ({"status": "in_progress", "runner_name": "mini-1"}, # running + {"runner_name": "mini-1"}, # queued, but has a runner + {"status": "completed", "conclusion": "success", "runner_name": "mini-1", + "completed_at": iso(5)}): # ran on a Mac + with self.subTest(build=build): + ok, why = self.judge(old, gate_jobs(60, build=build), [old, new]) + self.assertFalse(ok) + self.assertIn("started", why) + # A Linux job named for the build (sign, publish, ...) or one that ran past GATE_JOB_MAX is the build too. + for job in ({"name": "publish-nightly", "labels": [LINUX]}, + {"name": "build nightly inputs", "labels": [LINUX], "completed_at": iso(60 - 1 - 11)}): + with self.subTest(job=job): + jobs = gate_jobs(60) + jobs[1] = {**jobs[1], **job} + self.assertFalse(self.judge(old, jobs, [old, new])[0]) + + def test_unstarted_with_no_newer_head_run_is_kept(self): + old = nightly_run("864dceb6", 60) + same_head = nightly_run("864dceb6", 30) + cancelled = {**nightly_run("ccb74c4d", 20), "status": "completed", "conclusion": "cancelled"} + failed = {**nightly_run("ccb74c4d", 20), "status": "completed", "conclusion": "failure"} + fork = nightly_run("ccb74c4d", 20) + fork["head_repository"] = {"full_name": "someone/cmux", "owner": {"login": "someone"}} + dispatched = {**nightly_run("ccb74c4d", 20), "event": "workflow_dispatch"} + ordinary = {**nightly_run("ccb74c4d", 20), "path": ".github/workflows/cmux-next.yml", "workflow_id": 9, + "name": "cmux-next", "display_title": "cmux-next tip Swift suite"} + other_branch = nightly_run("ccb74c4d", 20, branch="main") + other_workflow = {**nightly_run("ccb74c4d", 20), "workflow_id": 1, "path": ".github/workflows/ci.yml"} + older = nightly_run("0ldhead0", 90) + no_status = {**nightly_run("ccb74c4d", 20), "status": None} + rerun = {**nightly_run("ccb74c4d", 20), "run_attempt": 2} + for others in ([no_status], [rerun], [], [same_head], [cancelled], [failed], [fork], [dispatched], [other_branch], [other_workflow], + [older]): + with self.subTest(others=others): + ok, why = self.judge(old, gate_jobs(60), [old, *others]) + self.assertFalse(ok) + self.assertIn("no newer head", why) + self.assertFalse(self.judge(old, None, [old, nightly_run("ccb74c4d", 20)])[0]) + # Without a way to read the newer run's jobs, nothing is skipped. + self.assertFalse(janitor.superseded_unstarted(old, gate_jobs(60), [old, nightly_run("ccb74c4d", 20)])[0]) + # A shared workflow's DEV delivery run is not superseded by an ordinary run of that workflow. + dev = {**nightly_run("864dceb6", 60), "path": ".github/workflows/cmux-next.yml", "workflow_id": 9, + "name": "cmux-next", "display_title": "cmux NEXT DEV daily · 864dceb6"} + self.assertFalse(self.judge(dev, gate_jobs(60), [dev, {**ordinary, "event": "push"}])[0]) + self.assertTrue(self.judge( + dev, gate_jobs(60), [dev, {**ordinary, "display_title": "cmux NEXT DEV daily · ccb74c4d"}])[0]) + + def test_a_newer_run_that_does_not_do_the_build_does_not_supersede(self): + # A cache-only warmup or a throttled push at a newer head skips the app build; one still deciding has not + # listed it; an unreadable one proves nothing. + old, new = nightly_run("864dceb6", 60), nightly_run("ccb74c4d", 20) + skipped = gate_jobs(20, build={"status": "completed", "conclusion": "skipped", "runner_name": None}) + deciding = gate_jobs(20)[:1] + unknown = gate_jobs(20, build={"status": None}) + for newer_jobs in (skipped, deciding, unknown, None): + with self.subTest(newer_jobs=newer_jobs): + ok, why = janitor.superseded_unstarted(old, gate_jobs(60), [old, new], lambda other: newer_jobs) + self.assertFalse(ok) + self.assertIn("same build", why) + # An old run still at its gates (only `decide` queued) is not matched to anything: a cache-only run's + # `decide` succeeds too. + at_gates = [{"name": "decide", "status": "queued", "labels": [LINUX], "runner_name": None}] + ok, why = janitor.superseded_unstarted(old, at_gates, [old, new], lambda other: skipped) + self.assertFalse(ok) + self.assertIn("no build job", why) + # A newer run that skipped a gate the old one ran (a different path) is not the same build either. + other_path = gate_jobs(20) + other_path[1] = {**other_path[1], "status": "completed", "conclusion": "skipped"} + self.assertFalse(janitor.superseded_unstarted(old, gate_jobs(60), [old, new], lambda other: other_path)[0]) + # Two newer runs: a cache-only one first, a building one behind it. + building = nightly_run("e3ca669f", 30) + ok, why = self.judge(old, gate_jobs(60), [old, building, new], {new["id"]: skipped}) + self.assertTrue(ok, why) + self.assertIn(str(building["id"]), why) + + def test_a_rerun_is_kept(self): + # Only the latest attempt's jobs are read; an earlier attempt may have built. + old, new = {**nightly_run("864dceb6", 60), "run_attempt": 2}, nightly_run("ccb74c4d", 20) + ok, why = self.judge(old, gate_jobs(60), [old, new]) + self.assertFalse(ok) + self.assertIn("attempt 2", why) + for broken in ({"run_attempt": None}, {"status": None}, {"status": "completed"}, {"status": "weird"}): + with self.subTest(broken=broken): + self.assertFalse(self.judge({**old, "run_attempt": 1, **broken}, gate_jobs(60), [old, new])[0]) + + def sweep(self, runs, jobs, *, completed=(), dry_run=False, prs=None, rejob=None, extra_runs=()): + fake = FakeGitHub({r["id"]: dict(r) for r in [*runs, *extra_runs]}, jobs) + fake.completed["nightly.yml"] = list(completed) + fake.prs = prs or {} + if rejob: # what the re-read right before the cancel sees + fake.job_map = {**jobs, **rejob} + candidates = janitor.superseded_candidates(runs, jobs) + decisions, failures = janitor.skip_superseded_delivery(fake, candidates, runs, jobs, fake.prs, + dry_run=dry_run) + return fake, {d.run["id"]: d for d in decisions}, failures + + def test_the_sweep_cancels_every_superseded_unstarted_run_and_keeps_the_tip(self): + a, b, tip = nightly_run("864dceb6", 70), nightly_run("5cec7c8d", 50), nightly_run("ccb74c4d", 20) + started = nightly_run("e3ca669f", 40) + jobs = {a["id"]: gate_jobs(70), b["id"]: gate_jobs(50), tip["id"]: gate_jobs(20), + started["id"]: gate_jobs(40, build={"status": "in_progress", "runner_name": "mini-1"})} + fake, decided, failures = self.sweep([a, b, started, tip], jobs) + self.assertEqual(failures, 0) + self.assertEqual({k for k, d in decided.items() if d.action == "cancel"}, {a["id"], b["id"]}) + self.assertNotIn(started["id"], decided) # a started build is never a candidate + self.assertEqual(decided[tip["id"]].action, "keep") + self.assertEqual(sorted(fake.posts()), sorted([[str(a["id"]), "cancel"], [str(b["id"]), "cancel"]])) + + def test_a_dry_run_cancels_nothing(self): + old, tip = nightly_run("864dceb6", 70), nightly_run("ccb74c4d", 20) + fake, decided, _ = self.sweep([old, tip], {old["id"]: gate_jobs(70), tip["id"]: gate_jobs(20)}, + dry_run=True) + self.assertEqual(decided[old["id"]].action, "cancel") + self.assertEqual(fake.posts(), []) + + def test_a_build_that_starts_before_the_cancel_is_kept(self): + old, tip = nightly_run("864dceb6", 70), nightly_run("ccb74c4d", 20) + jobs = {old["id"]: gate_jobs(70), tip["id"]: gate_jobs(20)} + rejob = {old["id"]: gate_jobs(70, build={"status": "in_progress", "runner_name": "mini-1"})} + fake, decided, _ = self.sweep([old, tip], jobs, rejob=rejob) + self.assertEqual(decided[old["id"]].action, "keep") + self.assertIn("on re-read", decided[old["id"]].note) + self.assertEqual(fake.posts(), []) + + def test_a_replacement_that_fails_before_the_cancel_keeps_the_old_run(self): + old, tip = nightly_run("864dceb6", 70), nightly_run("ccb74c4d", 20) + jobs = {old["id"]: gate_jobs(70), tip["id"]: gate_jobs(20)} + fake = FakeGitHub({r["id"]: dict(r) for r in (old, tip)}, jobs) + fake.runs[tip["id"]].update(status="completed", conclusion="cancelled") # what the re-read sees + candidates = janitor.superseded_candidates([old, tip], jobs) + decisions, _ = janitor.skip_superseded_delivery(fake, candidates, [old, tip], jobs, {}, dry_run=False) + self.assertEqual({d.run["id"]: d.action for d in decisions}[old["id"]], "keep") + self.assertEqual(fake.posts(), []) + + def test_a_pr_opened_at_the_head_during_the_sweep_keeps_the_run(self): + old, tip = nightly_run("864dceb6", 70), nightly_run("ccb74c4d", 20) + jobs = {old["id"]: gate_jobs(70), tip["id"]: gate_jobs(20)} + fake = FakeGitHub({r["id"]: dict(r) for r in (old, tip)}, jobs) + fake.prs = {"nightly-next": [make_pr(9, head="864dceb6")]} # what the re-read sees; the snapshot had none + candidates = janitor.superseded_candidates([old, tip], jobs) + decisions, _ = janitor.skip_superseded_delivery(fake, candidates, [old, tip], jobs, {}, dry_run=False) + self.assertIn("open PR #9", {d.run["id"]: d.note for d in decisions}[old["id"]]) + self.assertEqual(fake.posts(), []) + + def test_a_gate_with_no_conclusion_is_unread(self): + old, new = nightly_run("864dceb6", 60), nightly_run("ccb74c4d", 20) + jobs = gate_jobs(60) + jobs[1] = {**jobs[1], "conclusion": None} + ok, why = self.judge(old, jobs, [old, new]) + self.assertFalse(ok) + self.assertIn("unknown conclusion", why) + + def test_a_newer_run_that_skips_the_build_sends_the_sweep_to_the_branch_listing(self): + old, cache_only = nightly_run("864dceb6", 70), nightly_run("e3ca669f", 40) + done = {**nightly_run("ccb74c4d", 20, status="completed"), "conclusion": "success"} + skipped = gate_jobs(40, build={"status": "completed", "conclusion": "skipped", "runner_name": None}) + built = gate_jobs(20, build={"status": "completed", "conclusion": "success", "runner_name": "mini-1"}) + fake, decided, _ = self.sweep([old, cache_only], {old["id"]: gate_jobs(70), cache_only["id"]: skipped}, + completed=[done], rejob={done["id"]: built}, extra_runs=[done]) + self.assertEqual(decided[old["id"]].action, "cancel", decided[old["id"]].note) + + def test_a_full_jobs_listing_is_unread(self): + old = nightly_run("864dceb6", 60) + full = gate_jobs(60) + [dict(gate_jobs(60)[0]) for _ in range(100 * janitor.MAX_JOB_PAGES)] + self.assertEqual(janitor.superseded_candidates([old], {old["id"]: full}), []) + self.assertIsNone(janitor.complete_jobs(full)) + + def test_matrix_legs_need_a_leg_each(self): + old, new = nightly_run("864dceb6", 60), nightly_run("ccb74c4d", 20) + two = gate_jobs(60) + [dict(gate_jobs(60)[-1])] # two `build-nightly-app` legs + one = gate_jobs(20) + self.assertFalse(janitor.superseded_unstarted(old, two, [old, new], lambda other: one)[0]) + self.assertTrue(janitor.superseded_unstarted(old, two, [old, new], lambda other: one + [dict(one[-1])])[0]) + + def test_a_finished_newer_run_is_found_by_one_branch_listing(self): + old = nightly_run("864dceb6", 70) + done = {**nightly_run("ccb74c4d", 20, status="completed"), "conclusion": "success"} + built = gate_jobs(20, build={"status": "completed", "conclusion": "success", "runner_name": "mini-1"}) + fake, decided, _ = self.sweep([old], {old["id"]: gate_jobs(70)}, completed=[done], rejob={done["id"]: built}, + extra_runs=[done]) + self.assertEqual(decided[old["id"]].action, "cancel") + self.assertEqual([p for m, p in fake.log if "/actions/workflows/" in p], + ["/repos/manaflow-ai/cmux/actions/workflows/nightly.yml/runs?branch=nightly-next&per_page=20"]) + + def test_a_run_at_an_open_prs_head_is_kept(self): + old, tip = nightly_run("864dceb6", 70), nightly_run("ccb74c4d", 20) + prs = {"nightly-next": [make_pr(7, head="864dceb6")]} + fake, decided, _ = self.sweep([old, tip], {old["id"]: gate_jobs(70), tip["id"]: gate_jobs(20)}, prs=prs) + self.assertEqual(decided[old["id"]].action, "keep") + self.assertEqual(fake.posts(), []) + + def test_ordinary_runs_are_never_candidates(self): + ci = make_run(status="queued", sha="old") + self.assertEqual(janitor.superseded_candidates([ci], {ci["id"]: gate_jobs(60)}), []) + + class OrphanExecutionTests(unittest.TestCase): def run_one(self, **fake_kwargs): ghost = make_run(status="queued", age=60 * 48)