diff --git a/scripts/ci/queue_janitor.py b/scripts/ci/queue_janitor.py index b4ce10a4e003..fe153d83106f 100644 --- a/scripts/ci/queue_janitor.py +++ b/scripts/ci/queue_janitor.py @@ -80,6 +80,17 @@ exceptions hold: a bot's attempt, a run that already failed, a newer run at its head (never a second workflow_dispatch: each dispatch is its own request), no re-run state, `no-janitor`, and an unfinished sibling. + A cascade job of a same-repository cmux-next pull request run queued on a + Blacksmith macOS label (blacksmith_leg()) counts too, past + BLACKSMITH_LEG_SECONDS (25 minutes, the cascade's own stall wait), while + owned pools are on: nothing else moves it, and the janitor's re-run, made + only with an App's token (in category e too), sends it to the owned side + label the rescue watches. + +cmux-next runs follow feat-cmux-next's workflow copy, not main's inert +registration, so they are listed like any macOS workflow's +(follows_another_copy()): the pool snapshot counts their Blacksmith queue for +next_macos_cascade.py, and every category above may act on them. Draft pull requests are deliberately not a category: a draft can be an active integration branch other work depends on, and ci.yml has no ready_for_review @@ -270,6 +281,21 @@ UNCLAIMED_MIN_SAMPLES = 5 # The snapshot key with each owned pool's p90 wait in seconds. WAIT_P90_KEY = "wait_p90_seconds" +# Category f also moves a cmux-next leg queued on a Blacksmith macOS label (blacksmith_leg()). Its bound +# is next_macos_cascade.STALL_MINUTES, the wait at which the cascade itself calls such a label stalled. +BLACKSMITH_MACOS_LABEL = re.compile(r"blacksmith-[0-9]+vcpu-macos-[0-9]+") +BLACKSMITH_LEG_SECONDS = 25 * 60 +# The cmux-next jobs next_macos_cascade.py places (its CASCADE_JOBS), by their names in feat-cmux-next's +# cmux-next.yml. Each one's runs-on sends a re-run github-actions[bot] did not start to +# needs.macos-placement.outputs.runner, the owned side label, before any Blacksmith label. The GUI and +# session jobs (swift test, daemon tests, generated files) are left out: with no GUI or session runner +# online their re-run still takes blacksmith-6vcpu-macos-26. +CASCADE_JOB_NAMES = frozenset({ + "cmux-next fast tier", + "cmux-next Swift canary", + "cmux-next Release compile (Xcode 26)", + "cmux app scheme compile (Debug)", +}) SNAPSHOT_UNREADABLE = (ValueError, KeyError, EOFError, NotImplementedError, zipfile.BadZipFile, zlib.error) # The jobs whose failure decides ci-status. ci-macos.yml shards the app-host @@ -387,7 +413,7 @@ def linux_only_workflow_paths(workflows_dir: Path) -> frozenset[str]: def needs_jobs(run: Mapping[str, Any], linux_only_paths: frozenset[str], now: dt.datetime) -> bool: """Whether a run's jobs are worth one API call this sweep.""" - if run.get("path") in linux_only_paths: + if run.get("path") in linux_only_paths and not follows_another_copy(run): return False if run.get("event") in PROTECTED_EVENTS - {"merge_group"}: # Deployment/tag bookkeeping never holds pool capacity worth counting. @@ -409,28 +435,38 @@ def run_target_branch(run: Mapping[str, Any]) -> str | None: return None -def starved_scope_runs(runs: Sequence[Mapping[str, Any]], listed: Mapping[int, Any], - linux_only_paths: frozenset[str], now: dt.datetime) -> list[Mapping[str, Any]]: - """Runs whose jobs only the starved-label alert reads: skipped as linux-only, yet on another branch's copy. +def follows_another_copy(run: Mapping[str, Any]) -> bool: + """A run that may follow a workflow copy other than main's, so main's linux-only reading says nothing about it. linux_only_workflow_paths() reads main's workflow files, but a run into or on another branch follows that branch's copy: main's cmux-next.yml is an - inert registration while feat-cmux-next's runs the build-fleet compile on - a glaeda-* label. These runs' jobs feed starved_labels only, never the - cancel policy, and cost one jobs listing each. + inert registration, while feat-cmux-next's puts Mac jobs on the minis, + Blacksmith macOS and hosted macOS. Until 2026-10-26 those runs were listed + for the starved-label alert only, so the pool snapshot that + next_macos_cascade.py reads to count a Blacksmith label's queue and spot a + stall never saw a cmux-next job: at 02:32Z that day the cascade counted 2 + queued on blacksmith-12vcpu-macos-26 while about ten cmux-next jobs waited + there, and sent run 40259152940's fast tier into a queue it then sat in + for over 90 minutes. A same-repository pull request run that names no pull + request has lost it when the pull request closed (run 40259152940 named + none once PR #24021 landed), so its base is unknown and it is listed too: + category b cancels it while it holds a Mac job. """ - return [run for run in runs - if run.get("id") not in listed and run.get("path") in linux_only_paths - and needs_jobs(run, frozenset(), now) and run_target_branch(run) not in (None, "main")] + target = run_target_branch(run) + if target is not None: + return target != "main" + head = (run.get("head_repository") or {}).get("id") + return (run.get("event") == "pull_request" and not run.get("pull_requests") + and head is not None and head == (run.get("repository") or {}).get("id")) def starved_result(github: "GitHub", runs: Sequence[Mapping[str, Any]], jobs_by_run: Mapping[int, Sequence[Mapping[str, Any]]], evidence_jobs: Mapping[int, Sequence[Mapping[str, Any]]], *, - linux_only_paths: frozenset[str], now: dt.datetime) -> dict[str, Any]: + now: dt.datetime) -> dict[str, Any]: """The snapshot's `starved` and `unserved` (starved_labels.py), and `starved_incomplete` when a listing failed. - Reads the sweep's jobs plus starved_scope_runs()'s. Starts in completed runs + Reads the sweep's jobs, cmux-next's among them (follows_another_copy()). Starts in completed runs count as service: the lost-assignment evidence already listed and, only for a label about to alert, up to LOST_EVIDENCE_RUNS_PER_WORKFLOW completed runs of each of its stuck jobs' workflows (at most LOST_EVIDENCE_WORKFLOWS) that @@ -441,12 +477,6 @@ def starved_result(github: "GitHub", runs: Sequence[Mapping[str, Any]], fleet_jobs: dict[int, Sequence[Mapping[str, Any]]] = dict(jobs_by_run) evidence: dict[int, Sequence[Mapping[str, Any]]] = dict(evidence_jobs) incomplete = False - for run in starved_scope_runs(runs, jobs_by_run, linux_only_paths, now): - try: - fleet_jobs[run["id"]] = github.jobs(run["id"]) - except RuntimeError as error: - incomplete = True - print(f"queue-janitor: starved-label jobs of run {run['id']}: {error}", file=sys.stderr) found = starved_labels.starved(runs, fleet_jobs, now=now, evidence=evidence) alerting = {entry["label"] for entry in found} earliest: dict[str, dt.datetime] = {} @@ -907,6 +937,8 @@ class Candidate: # Category e at the current head of an open pull request: once the cancel # has settled, a later sweep re-runs the run's failed jobs (new_lost_reruns()). rerun: bool = False + # That re-run must come from an App's token, never GITHUB_TOKEN (a Blacksmith leg, blacksmith_leg()). + app_actor: bool = False def classify( @@ -1407,6 +1439,35 @@ class UnclaimedJob: pool: str queued_since: dt.datetime bound_seconds: int + blacksmith: bool = False + + +def blacksmith_leg(run: Mapping[str, Any], job: Mapping[str, Any]) -> str | None: + """The Blacksmith macOS label a cmux-next job waits on, if any. + + next_macos_cascade.py sends a cmux-next Mac job no idle mini takes to a + Blacksmith macOS label it reads as free, and no rescue watches it there: + owned_pool_rescue.py moves only owned legs, and GitHub never re-routes a + queued job. Run 40259152940's fast tier waited on + blacksmith-12vcpu-macos-26 from 02:32Z on 2026-10-26, and in the 18 hours + before, 58 of 110 cmux-next jobs sent to that label never got a runner. + Category f moves such a leg as it moves an owned one, only because the + janitor re-runs as an App: cmux-next.yml sends a re-run that + github-actions[bot] did not start to the placement's owned side label + (`github.triggering_actor != 'github-actions[bot]' && ...outputs.runner`), + where the owned-pool rescue watches it, while that bot's attempt 2 takes + attempt 1's Blacksmith placement again. So only a cascade job + (CASCADE_JOB_NAMES) of a same-repository pull request run counts: a fork's + runs-on takes Blacksmith first whoever re-runs it, and a push or dispatch + would need a branch-head read this rule does not spend. + """ + head = (run.get("head_repository") or {}).get("id") + if (run.get("path") != rescue.CMUX_NEXT_WORKFLOW_PATH or run.get("event") != "pull_request" + or head is None or head != (run.get("repository") or {}).get("id") + or job.get("name") not in CASCADE_JOB_NAMES): + return None + return next((str(label) for label in job.get("labels") or () if BLACKSMITH_MACOS_LABEL.fullmatch(str(label))), + None) def _unclaimed_scope(run: Mapping[str, Any]) -> bool: @@ -1421,31 +1482,39 @@ def find_unclaimed( now: dt.datetime, lost: Mapping[int, Any] | None = None, evidence_jobs: Mapping[int, Sequence[Mapping[str, Any]]] | None = None, + blacksmith_legs: bool = False, ) -> dict[int, UnclaimedJob]: """Run id -> its longest-waiting unclaimed leg, for in-flight runs category e does not already hold. A leg is unclaimed when it is unassigned(), asks for an owned label - (owned_pool_rescue.job_pool(): a Blacksmith leg's re-run would rejoin the - same label) and could have run (lost_wait_start()) for longer than - unclaimed_bound(). As in category e, a run with any other unfinished job - that is not unclaimed itself is left alone (_gated()). + (owned_pool_rescue.job_pool(): another Blacksmith leg's re-run would rejoin + the same label) and could have run (lost_wait_start()) for longer than + unclaimed_bound(). With `blacksmith_legs` (owned pools on, so cmux-next's + placement names an owned side label), a cmux-next leg on a Blacksmith macOS + label (blacksmith_leg()) counts too, past BLACKSMITH_LEG_SECONDS. As in + category e, a run with any other unfinished job that is not unclaimed + itself is left alone (_gated()). """ p90 = pool_wait_p90(jobs_by_run, evidence_jobs) held = set(lost or ()) found_by_run: dict[int, UnclaimedJob] = {} for run in runs: - if run["id"] in held or not _unclaimed_scope(run): + if not _unclaimed_scope(run): continue run_jobs = jobs_by_run.get(run["id"]) or () found: list[tuple[Mapping[str, Any], UnclaimedJob]] = [] for job in run_jobs: pool = rescue.job_pool(job) - if not pool or not unassigned(job): + blacksmith = None if pool or not blacksmith_legs else blacksmith_leg(run, job) + # A run category e holds is judged here only for a Blacksmith leg, in case e leaves it (a bot's + # attempt): no other rule moves that leg. + if not (pool or blacksmith) or not unassigned(job) or (run["id"] in held and not blacksmith): continue since = lost_wait_start(job, run_jobs) - bound = unclaimed_bound(pool, p90) + bound = BLACKSMITH_LEG_SECONDS if blacksmith else unclaimed_bound(str(pool), p90) if since is not None and (now - since).total_seconds() > bound: - found.append((job, UnclaimedJob(str(job.get("name") or ""), pool, since, bound))) + found.append((job, UnclaimedJob(str(job.get("name") or ""), str(pool or blacksmith), since, bound, + blacksmith=bool(blacksmith)))) if found and not _gated(run_jobs, [job for job, _ in found]): found_by_run[run["id"]] = min((item for _, item in found), key=lambda item: item.queued_since) return found_by_run @@ -1461,9 +1530,17 @@ def classify_unclaimed( rerun_state: bool, newer: Mapping[str, Any] | None = None, branch_head: str | None = None, + app_rerun: bool = False, ) -> LostVerdict | None: """What category f does with a run holding an unclaimed leg, or None to leave it to the other categories. + A Blacksmith leg (blacksmith_leg()) is moved only while this sweep holds an + App's token (`app_rerun`), and its re-run is made only with one + (Candidate.app_actor); a bot's attempt is no reason to skip it, since no + rescue watches a Blacksmith leg, but past owned_pool_rescue. + REFUSAL_RESCUE_ATTEMPT it is left alone, so the janitor adds one attempt + to the rescue's ladder at most. + Only a run at a live head is touched (lost_pr_state() "current"): one at the head of an open pull request, or a push or dispatch at its branch's head. Without evidence that the pool skipped the leg, a stale or unknown @@ -1478,9 +1555,9 @@ def classify_unclaimed( if prs is None: return None state, pr, why = lost_pr_state(run, prs, branch_head) + bound = ("the cascade's stall wait" if leg.blacksmith else "45m, or the pool's p90 wait when longer") evidence = (f"unclaimed leg: `{leg.job_name}` queued {format_age(now - leg.queued_since)} with no runner on " - f"`{leg.pool}`, past its {format_age(dt.timedelta(seconds=leg.bound_seconds))} bound (45m, or the " - "pool's p90 wait when longer)") + f"`{leg.pool}`, past its {format_age(dt.timedelta(seconds=leg.bound_seconds))} bound ({bound})") if state != "current": return None if pr is not None and JANITOR_OPT_OUT_LABEL in pr_labels(pr): @@ -1488,10 +1565,16 @@ def classify_unclaimed( if pr is not None and not labels_complete(pr): return LostVerdict("skip", evidence, f"PR #{pr.get('number')} has more labels than were read", pr=pr) attempt = int(run.get("run_attempt") or 1) - if bot_rerun(run): + if leg.blacksmith: + if attempt > rescue.REFUSAL_RESCUE_ATTEMPT: + return LostVerdict("skip", f"{evidence}; {why}", f"attempt {attempt} is past the rescue's ladder", pr=pr) + if not app_rerun: + return LostVerdict("skip", f"{evidence}; {why}", "no App token this sweep: a GITHUB_TOKEN re-run would " + "take attempt 1's Blacksmith placement again", pr=pr) + elif bot_rerun(run): return LostVerdict("skip", f"{evidence}; {why}", f"attempt {attempt} is a bot's re-run, left to the " "owned-pool rescue and the orphan pass", pr=pr) - if not rescue.bot_rerun_leaves_owned(str(run.get("path") or ""), attempt): + elif not rescue.bot_rerun_leaves_owned(str(run.get("path") or ""), attempt): return LostVerdict("skip", f"{evidence}; {why}", f"a re-run of attempt {attempt} would stay on the owned " "label; left to the owned-pool rescue", pr=pr) if any(job.get("status") == "completed" and job.get("conclusion") == "failure" for job in run_jobs): @@ -1501,7 +1584,8 @@ def classify_unclaimed( return LostVerdict("skip", f"{evidence}; {why}", f"newer run {newer.get('id')} at its head took over", pr=pr) if not rerun_state: return LostVerdict("skip", f"{evidence}; {why}", "no re-run state to carry the re-run to a later sweep", pr=pr) - return LostVerdict("cancel", f"{evidence}; {why}: its failed jobs are re-run off the owned label once the " + off = "the Blacksmith label, by an App," if leg.blacksmith else "the owned label" + return LostVerdict("cancel", f"{evidence}; {why}: its failed jobs are re-run off {off} once the " "cancel settles", rerun=True, pr=pr) @@ -1555,9 +1639,12 @@ def new_lost_reruns(candidates: Iterable[Candidate], results: Mapping[int, str], result = results.get(candidate.run["id"]) or "" if candidate.rerun and (result == "cancelled" or result.startswith("force-cancelled")): run = candidate.run - entries.append({"run_id": run["id"], "attempt": int(run.get("run_attempt") or 1), - "head_sha": str(run.get("head_sha") or ""), "branch": str(run.get("head_branch") or ""), - "cancelled_at": _iso(now)}) + entry = {"run_id": run["id"], "attempt": int(run.get("run_attempt") or 1), + "head_sha": str(run.get("head_sha") or ""), "branch": str(run.get("head_branch") or ""), + "cancelled_at": _iso(now)} + if candidate.app_actor: + entry["app_actor"] = True + entries.append(entry) return entries @@ -1577,6 +1664,7 @@ def plan_lost_reruns( now: dt.datetime, head_runs: Mapping[int, Sequence[Mapping[str, Any]]], branch_heads: Mapping[str, str] | None = None, + app_token: bool = True, ) -> list[LostRerun]: """Which pending category-e and category-f cancels to re-run now. @@ -1593,7 +1681,8 @@ def plan_lost_reruns( branch or head not looked up is kept for the next sweep, until LOST_RERUN_TTL. A push or dispatch run is current at a live branch's head (`branch_heads`, lost_pr_state()); one whose branch head was not read - is kept too. + is kept too. An entry that needs an App's re-run (`app_actor`, a + Blacksmith leg) is kept while this sweep has none (`app_token`). """ decisions: list[LostRerun] = [] reruns = 0 @@ -1646,6 +1735,9 @@ def plan_lost_reruns( decisions.append(LostRerun(entry, "drop", f"not re-run: newer run {newer.get('id')} at its head " "took over", run)) continue + if entry.get("app_actor") and not app_token: + decisions.append(LostRerun(entry, "keep", "needs an App's re-run; this sweep has only GITHUB_TOKEN", run)) + continue if reruns >= LOST_RERUN_MAX: decisions.append(LostRerun(entry, "keep", f"re-run cap of {LOST_RERUN_MAX} reached", run)) continue @@ -1695,6 +1787,7 @@ def build_plan( rerun_state: bool = True, unclaimed: Mapping[int, UnclaimedJob] | None = None, branch_heads: Mapping[str, str] | None = None, + app_rerun: bool = False, ) -> Plan: """Decide every category's candidates under the shared cap. @@ -1730,6 +1823,12 @@ def build_plan( branch = str(run.get("head_branch") or "") lost_verdict = None held_category = "lost" + # A cmux-next run holding a Blacksmith leg is re-run only by an App, whichever category cancels + # it: a GITHUB_TOKEN re-run is github-actions[bot]'s, whose attempt 2 keeps attempt 1's placement. + # No earlier snapshot's pending entry names a cmux-next run: none was listed before. + app_actor = run.get("path") == rescue.CMUX_NEXT_WORKFLOW_PATH and any( + unassigned(job) and any(BLACKSMITH_MACOS_LABEL.fullmatch(str(label)) for label in job.get("labels") or ()) + for job in jobs_by_run.get(run["id"], ())) if run["id"] in lost or run["id"] in unclaimed: # A newer run at its head, or a later CI run waiting to take over ci-status. newer = newer_run_at_head(run, runs) or next( @@ -1739,14 +1838,19 @@ def build_plan( lost_verdict = classify_lost( run, jobs_by_run.get(run["id"], ()), lost[run["id"]], branch_prs, now=now, rerun_state=rerun_state, newer=newer, branch_head=heads.get(branch)) - else: + if run["id"] in unclaimed and (lost_verdict is None or lost_verdict.action != "cancel"): held_category = "unclaimed" lost_verdict = classify_unclaimed( run, jobs_by_run.get(run["id"], ()), unclaimed[run["id"]], branch_prs, now=now, - rerun_state=rerun_state, newer=newer, branch_head=heads.get(branch)) + rerun_state=rerun_state, newer=newer, branch_head=heads.get(branch), app_rerun=app_rerun) + if (lost_verdict is not None and lost_verdict.action == "cancel" and lost_verdict.rerun + and app_actor and not app_rerun): + lost_verdict = LostVerdict("skip", lost_verdict.reason, "no App token this sweep: a GITHUB_TOKEN " + "re-run would take attempt 1's Blacksmith placement again", + pr=lost_verdict.pr) if lost_verdict is not None and lost_verdict.action == "cancel": candidates.append(Candidate(run, held_category, lost_verdict.reason, usage, lost_verdict.pr, - rerun=lost_verdict.rerun)) + rerun=lost_verdict.rerun, app_actor=app_actor)) continue pr = None if run.get("event") == "pull_request": @@ -2054,6 +2158,10 @@ def orphan_protected_reason(run: Mapping[str, Any]) -> str | None: return f"tag-like ref {branch}" if ORPHAN_PROTECTED_WORKFLOW.search(" ".join(str(run.get(key) or "") for key in ("name", "path"))): return "release/publish workflow" + if event == "push" and branch in PROTECTED_PUSH_BRANCHES - {"main"}: + # Listed since follows_another_copy(): a feat-cmux-next push gates the nightly-next build, + # which is cancelled only when stuck past its timeout (ci.yml's main pushes are listed as before). + return f"push to {branch}" return None @@ -2381,6 +2489,8 @@ def __init__(self, token: str, repo: str, fallback_token: str = "") -> None: self._token = token self.calls = 0 self.fallback_token = fallback_token if fallback_token != token else "" + # An App's token is in use: one was minted beside the workflow's, and it was not refused yet. + self.app_token = bool(self.fallback_token) # Rate limit resource ("core", "graphql") -> the newest response's values. self.rate_limits: dict[str, dict[str, int]] = {} self.headers = { @@ -2390,7 +2500,7 @@ def __init__(self, token: str, repo: str, fallback_token: str = "") -> None: "User-Agent": "cmux-ci-queue-janitor", } - def request(self, method: str, path: str, body: Any | None = None) -> Any: + def request(self, method: str, path: str, body: Any | None = None, *, app_only: bool = False) -> Any: self.calls += 1 data = json.dumps(body).encode() if body is not None else None headers = dict(self.headers) @@ -2407,13 +2517,14 @@ def request(self, method: str, path: str, body: Any | None = None) -> Any: if error.code in (403, 429) and rate_limited(error): raise RuntimeError(f"{method} {path.split('?')[0]} failed ({error.code}: rate limit; " "the sweep stops rather than spend the workflow token)") from error - if error.code in (401, 403) and self.fallback_token: + if error.code in (401, 403) and self.fallback_token and not app_only: print(f"queue-janitor: App token refused ({error.code}) on {path.split('?')[0]}; " "using the workflow token for the rest of the sweep", file=sys.stderr) self.headers["Authorization"] = f"Bearer {self.fallback_token}" # The snapshot download (download()) uses the same token. self._token = self.fallback_token self.fallback_token = "" + self.app_token = False return self.request(method, path, body) raise RuntimeError(f"{method} {path.split('?')[0]} failed ({error.code})") from error except urllib.error.URLError as error: @@ -2491,8 +2602,11 @@ def cancel(self, run_id: int) -> None: def force_cancel(self, run_id: int) -> None: self.request("POST", f"/repos/{self.repo}/actions/runs/{run_id}/force-cancel") - def rerun_failed(self, run_id: int) -> None: - self.request("POST", f"/repos/{self.repo}/actions/runs/{run_id}/rerun-failed-jobs") + def rerun_failed(self, run_id: int, *, app_only: bool = False) -> None: + """Re-run the run's failed and cancelled jobs; `app_only` never retries it on the workflow's token.""" + if app_only and not self.app_token: + raise RuntimeError(f"run {run_id} needs an App's re-run; this sweep has only GITHUB_TOKEN") + self.request("POST", f"/repos/{self.repo}/actions/runs/{run_id}/rerun-failed-jobs", app_only=app_only) def request_ui_tests(self, run: Mapping[str, Any], attempt: int) -> None: """Start ci-ui-tests.yml for the attempt a re-run of a pull request's CI began. @@ -2583,7 +2697,7 @@ def rerun_lost(github: GitHub, decisions: Sequence[LostRerun]) -> tuple[list[dic continue run_id = int(decision.entry["run_id"]) try: - github.rerun_failed(run_id) + github.rerun_failed(run_id, app_only=bool(decision.entry.get("app_actor"))) results[run_id] = "re-ran failed jobs" except Exception as error: # noqa: BLE001 one failed re-run never drops the other entries failures += 1 @@ -2669,7 +2783,8 @@ def main(argv: Sequence[str] | None = None) -> int: except RuntimeError as error: print(f"queue-janitor: lost-assignment evidence for {workflow}: {error}", file=sys.stderr) lost = find_lost(runs, jobs_by_run, now=now, evidence_jobs=evidence_jobs) - unclaimed = find_unclaimed(runs, jobs_by_run, now=now, lost=lost, evidence_jobs=evidence_jobs) + unclaimed = find_unclaimed(runs, jobs_by_run, now=now, lost=lost, evidence_jobs=evidence_jobs, + blacksmith_legs=os.environ.get("PR_POOL_OWNED", "").strip() == "1") # The re-runs an earlier sweep left pending, from its pool snapshot. # None means unknown: then nothing at an open pull request's head is # cancelled for a re-run this sweep could not carry on. @@ -2741,7 +2856,7 @@ def read_heads(branches_wanted: Sequence[str]) -> None: snapshot[WAIT_P90_KEY] = waits # Fleet labels no runner is taking jobs from; the workflow's alert step # (starved_labels.py) annotates them and keeps one issue per label. - snapshot.update(starved_result(github, runs, jobs_by_run, evidence_jobs, linux_only_paths=linux_only, now=now)) + snapshot.update(starved_result(github, runs, jobs_by_run, evidence_jobs, now=now)) # Warm affinity on: which root runner kept a build of which main # commits (owned_warm_state.py). A failure leaves `warm` out, and the # picker then routes admission by the root label as before. @@ -2756,6 +2871,7 @@ def read_heads(branches_wanted: Sequence[str]) -> None: runs, jobs_by_run, prs_by_branch, threshold=threshold, max_cancels=max_cancels, pull_request_policy=args.pull_request_policy, now=now, lost=lost, rerun_state=pending is not None, unclaimed=unclaimed, branch_heads=branch_heads, + app_rerun=github.app_token, ) results: dict[int, str] = {} @@ -2801,7 +2917,7 @@ def save_lost_reruns(entries: Sequence[Mapping[str, Any]]) -> None: read_heads(branch_head_lookups(settled, {run.get("id") for run in settled}, prs_by_branch=prs_by_branch, known=branch_heads, cap=PENDING_HEAD_LOOKUPS)) rerun_decisions = plan_lost_reruns(pending, runs_now, prs_by_branch, now=now, head_runs=head_runs, - branch_heads=branch_heads) + branch_heads=branch_heads, app_token=github.app_token) if args.dry_run: # Nothing acted on, so only an expired entry goes. still_pending = [dict(decision.entry) for decision in rerun_decisions diff --git a/tests/test_ci_queue_janitor.py b/tests/test_ci_queue_janitor.py index 8f28f36d4727..bc98f3dad7ab 100644 --- a/tests/test_ci_queue_janitor.py +++ b/tests/test_ci_queue_janitor.py @@ -1009,6 +1009,7 @@ def __init__(self, runs, jobs=None, *, refuse_cancel=(), ignore_cancel=(), refus # Completed runs per workflow file, for the lost-assignment evidence listing. self.completed = {} self.refuse_rerun = set() + self.app_only_posts = [] self.refuse_dispatch = False # (method, path, body) of every POST. self.bodies = [] @@ -1017,9 +1018,11 @@ def __init__(self, runs, jobs=None, *, refuse_cancel=(), ignore_cancel=(), refus # Branch -> head sha (GET /branches/); a branch missing here answers 404. self.branches = {} - def request(self, method, path, body=None): + def request(self, method, path, body=None, *, app_only=False): self.calls += 1 self.log.append((method, path)) + if app_only: + self.app_only_posts.append(path) if method == "POST": self.bodies.append((method, path, body)) path = path.replace("/repos/manaflow-ai/cmux", "", 1) @@ -1068,8 +1071,9 @@ def request(self, method, path, body=None): if run_id in self.refuse_rerun: raise RuntimeError(f"POST /actions/runs/{run_id}/rerun-failed-jobs failed (403)") run = self.runs[run_id] + actor = "cmux-bot[bot]" if app_only else "github-actions[bot]" run.update(status="queued", conclusion=None, run_attempt=run["run_attempt"] + 1, - triggering_actor={"login": "github-actions[bot]"}) + triggering_actor={"login": actor}) return {} if method == "GET" and parts[-1] == "artifacts": return {"artifacts": []} @@ -1234,7 +1238,7 @@ class StarvedLabelSnapshotTests(unittest.TestCase): FLEET = "glaeda-side-light-xcode-26.6" NEXT = "feat-cmux-" + "next" - def snapshot(self, runs, jobs, *, fail_jobs=(), completed=None): + def snapshot(self, runs, jobs, *, fail_jobs=(), completed=None, code=0): fake = FakeGitHub({r["id"]: dict(r) for r in runs}, jobs) fake.completed = dict(completed or {}) listing_runs = fake.completed_runs @@ -1267,8 +1271,8 @@ def jobs_or_fail(run_id): mock.patch.object(janitor.time, "sleep", lambda _: None), \ mock.patch.object(janitor, "utc_now", lambda: NOW), \ mock.patch("builtins.print"): - self.assertEqual(janitor.main(argv), 0) - return json.loads(out.read_text()), fake + self.assertEqual(janitor.main(argv), code) + return (json.loads(out.read_text()) if out.exists() else None), fake def compile_job(self): return {"status": "queued", "name": "cmux-next app compile (build fleet)", "labels": [self.FLEET], @@ -1293,12 +1297,13 @@ def test_a_dispatch_on_a_branch_follows_that_branch_copy(self): snapshot, _ = self.snapshot([run], {run["id"]: [self.compile_job()]}) self.assertEqual([entry["label"] for entry in snapshot["starved"]], [self.FLEET]) - def test_a_failed_listing_marks_the_result_incomplete(self): + def test_a_failed_listing_of_a_branch_run_fails_the_sweep_like_any_other(self): + # cmux-next runs are listed with every other run now (follows_another_copy()), so a failed listing + # stops the sweep before it writes a snapshot from a partial inventory, as any run's does. run = make_run(path=".github/workflows/cmux-next.yml", name="cmux-next", branch="lane/x") run["pull_requests"] = [{"number": 7, "base": {"ref": self.NEXT}}] - snapshot, _ = self.snapshot([run], {run["id"]: [self.compile_job()]}, fail_jobs={run["id"]}) - self.assertEqual(snapshot["starved"], []) - self.assertTrue(snapshot["starved_incomplete"]) + snapshot, _ = self.snapshot([run], {run["id"]: [self.compile_job()]}, fail_jobs={run["id"]}, code=1) + self.assertIsNone(snapshot) def test_a_complete_listing_is_not_marked_incomplete(self): run = make_run(path=".github/workflows/cmux-next.yml", name="cmux-next", branch="lane/x") @@ -2435,5 +2440,263 @@ def test_the_snapshot_carries_each_owned_pools_p90_wait(self): self.assertEqual(fake.posts(), []) +NEXT_PATH = ".github/workflows/cmux-next.yml" +NEXT_BRANCH = "feat-cmux-" + "next" +LARGE_MAC = "blacksmith-12vcpu-macos-26" + + +def next_pr_run(*, branch="steer-default-2/new-chat-default-mode", sha="5353d57a", prs=True, age=95, + attempt=1, actor="leo", status="queued"): + """Run 40259152940: a cmux-next pull request run into feat-cmux-next, from this repository.""" + run = make_run(path=NEXT_PATH, name="cmux-next", branch=branch, sha=sha, age=age, attempt=attempt, + status=status) + run["pull_requests"] = [{"number": 24021, "base": {"ref": NEXT_BRANCH}}] if prs else [] + run["head_repository"]["id"] = 1 + run["repository"] = {"id": 1, "full_name": "manaflow-ai/cmux"} + run["triggering_actor"] = {"login": actor} + return run + + +def fast_tier_leg(*, age=90, label=LARGE_MAC): + return unassigned_job(age=age, label=label, name="cmux-next fast tier") + + +def finished_sibling(*, conclusion="success"): + job = started_job(age=100, label=LINUX, status="completed", conclusion=conclusion) + job["completed_at"] = iso(95) + return job + + +class BranchCopyListingTests(unittest.TestCase): + """main's cmux-next.yml is an inert registration; feat-cmux-next's runs put Mac jobs on Blacksmith macOS.""" + + LINUX_ONLY = frozenset({NEXT_PATH}) + + def test_runs_that_follow_feat_cmux_next_are_listed(self): + into_next = next_pr_run() + push = make_run(event="push", path=NEXT_PATH, branch=NEXT_BRANCH) + landed = next_pr_run(prs=False) + for run in (into_next, push, landed): + with self.subTest(run=run["event"], prs=run["pull_requests"]): + self.assertTrue(janitor.needs_jobs(run, self.LINUX_ONLY, NOW)) + + def test_runs_that_follow_main_or_a_fork_stay_unlisted(self): + into_main = next_pr_run() + into_main["pull_requests"] = [{"number": 7, "base": {"ref": "main"}}] + fork = next_pr_run(prs=False) + fork["head_repository"]["id"] = 2 + unknown = make_run(path=NEXT_PATH) # no repository ids: nothing says it is this repository's + for run in (into_main, fork, unknown): + with self.subTest(run=run["pull_requests"], head=run["head_repository"]): + self.assertFalse(janitor.needs_jobs(run, self.LINUX_ONLY, NOW)) + + def sweep(self, runs, jobs, prs=None): + fake = FakeGitHub({run["id"]: dict(run) for run in runs}, jobs) + fake.prs = dict(prs or {}) + with tempfile.TemporaryDirectory() as temp: + workflows = Path(temp) / "workflows" + workflows.mkdir() + (workflows / "cmux-next.yml").write_text("name: cmux-next\non:\n workflow_dispatch:\n") + out, summary = Path(temp) / "pool.json", Path(temp) / "summary.md" + argv = ["--repo", "manaflow-ai/cmux", "--summary", str(summary), "--workflows-dir", str(workflows), + "--pool-load", str(out)] + with mock.patch.object(janitor, "GitHub", lambda token, repo, fallback_token="": fake), \ + mock.patch.dict("os.environ", {"GH_TOKEN": "t"}), \ + mock.patch.object(janitor.time, "sleep", lambda _: None), \ + mock.patch.object(janitor, "utc_now", lambda: NOW), \ + mock.patch("builtins.print"): + self.assertEqual(janitor.main(argv), 0) + return json.loads(out.read_text()), fake + + def test_run_40259152940_the_snapshot_counts_cmux_next_blacksmith_queue(self): + # At 02:32Z the cascade counted 2 queued on the 12 vCPU label; cmux-next's own jobs there were missing. + runs, jobs = [], {} + for index in range(10): + run = next_pr_run(branch=f"lane/{index}", sha=f"s{index}", age=30 + index) + runs.append(run) + jobs[run["id"]] = [fast_tier_leg(age=20 + index)] + prs = {run["head_branch"]: [make_pr(100 + index, head=run["head_sha"])] for index, run in enumerate(runs)} + snapshot, _ = self.sweep(runs, jobs, prs) + self.assertEqual(snapshot["pools"][LARGE_MAC]["queued"], 10) + self.assertEqual(snapshot["pools"][LARGE_MAC]["oldest_queued_minutes"], 29) + + def test_run_40259152940_is_cancelled_once_its_pull_request_landed(self): + run = next_pr_run(prs=False) + jobs = {run["id"]: [fast_tier_leg(), finished_sibling(conclusion="failure")]} + _, fake = self.sweep([run], jobs, {run["head_branch"]: [make_pr(24021, state="MERGED", head=run["head_sha"])]}) + self.assertEqual(fake.posts(), [[str(run["id"]), "cancel"]]) + + +class BlacksmithLegTests(unittest.TestCase): + """Category f moves a cmux-next leg off a Blacksmith macOS label no runner serves, by an App's re-run.""" + + def world(self, *, age=30, label=LARGE_MAC, attempt=1, actor="leo", path=NEXT_PATH, siblings=None): + run = next_pr_run(attempt=attempt, actor=actor, age=age + 10) + run["path"] = path + jobs = {run["id"]: [fast_tier_leg(age=age, label=label), *(siblings or [finished_sibling()])]} + # The sibling finished 95 minutes ago; the leg could run from its own creation. + return run, jobs + + def plan(self, run, jobs, *, app_rerun=True): + prs = {run["head_branch"]: [make_pr(24021, head=run["head_sha"])]} + unclaimed = janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True) + return janitor.build_plan([run], jobs, prs, threshold=6, max_cancels=10, pull_request_policy="compile-only", + now=NOW, unclaimed=unclaimed, branch_heads={}, app_rerun=app_rerun) + + def test_a_leg_waiting_past_the_cascades_stall_wait_is_unclaimed(self): + run, jobs = self.world(age=26) + found = janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True) + self.assertEqual(found[run["id"]].pool, LARGE_MAC) + self.assertTrue(found[run["id"]].blacksmith) + self.assertEqual(found[run["id"]].bound_seconds, 25 * 60) + run, jobs = self.world(age=24) + self.assertEqual(janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True), {}) + + def test_only_cmux_next_legs_with_owned_pools_on_count(self): + run, jobs = self.world(age=60) + self.assertEqual(janitor.find_unclaimed([run], jobs, now=NOW), {}) + run, jobs = self.world(age=60, path=TUI) + self.assertEqual(janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True), {}) + run, jobs = self.world(age=60, label="macos-26") + self.assertEqual(janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True), {}) + + def test_it_is_cancelled_for_an_apps_re_run(self): + run, jobs = self.world(age=40) + decision = decision_for(self.plan(run, jobs), run) + self.assertEqual((decision.action, decision.candidate.category), ("cancel", "unclaimed")) + self.assertTrue(decision.candidate.rerun) + self.assertTrue(decision.candidate.app_actor) + entries = janitor.new_lost_reruns([decision.candidate], {run["id"]: "cancelled"}, now=NOW) + self.assertEqual([entry.get("app_actor") for entry in entries], [True]) + + def test_a_rescue_attempt_counts_but_not_past_its_ladder(self): + run, jobs = self.world(age=40, attempt=2, actor="github-actions[bot]") + self.assertEqual(decision_for(self.plan(run, jobs), run).action, "cancel") + run, jobs = self.world(age=40, attempt=janitor.rescue.REFUSAL_RESCUE_ATTEMPT + 1, actor="github-actions[bot]") + decision = decision_for(self.plan(run, jobs), run) + self.assertEqual(decision.action, "skip") + self.assertIn("ladder", decision.note) + + def test_without_an_app_token_it_is_left_alone(self): + run, jobs = self.world(age=40) + decision = decision_for(self.plan(run, jobs, app_rerun=False), run) + self.assertEqual(decision.action, "skip") + self.assertIn("App", decision.note) + + def test_a_failed_run_is_still_never_re_run(self): + run, jobs = self.world(age=40, siblings=[finished_sibling(conclusion="failure")]) + self.assertEqual(decision_for(self.plan(run, jobs), run).action, "skip") + + def test_an_app_entry_waits_for_an_app_token(self): + run = next_pr_run(status="completed") + run["conclusion"] = "cancelled" + entry = {**pending_entry(run), "app_actor": True} + prs = {run["head_branch"]: [make_pr(24021, head=run["head_sha"])]} + for app_token, action in ((False, "keep"), (True, "rerun")): + with self.subTest(app_token=app_token): + decisions = janitor.plan_lost_reruns([entry], {run["id"]: run}, prs, now=NOW, + head_runs={run["id"]: []}, app_token=app_token) + self.assertEqual([d.action for d in decisions], [action]) + + def test_an_app_only_re_run_never_falls_back_to_the_workflow_token(self): + github = janitor.GitHub("app", "manaflow-ai/cmux", fallback_token="workflow") + self.assertTrue(github.app_token) + refused = urllib.error.HTTPError("https://api.github.com/x", 403, "Forbidden", email.message.Message(), + io.BytesIO(b"{}")) + with mock.patch.object(janitor.urllib.request, "urlopen", side_effect=refused), \ + mock.patch("builtins.print"): + with self.assertRaises(RuntimeError): + github.rerun_failed(1, app_only=True) + self.assertTrue(github.app_token) + self.assertEqual(github.headers["Authorization"], "Bearer app") + workflow_only = janitor.GitHub("workflow", "manaflow-ai/cmux", fallback_token="workflow") + self.assertFalse(workflow_only.app_token) + with self.assertRaises(RuntimeError): + workflow_only.rerun_failed(1, app_only=True) + + def test_sweeps_cancel_then_re_run_it_once_as_an_app(self): + run, jobs = self.world(age=40) + fake = FakeGitHub({run["id"]: dict(run)}, jobs) + fake.app_token = True + fake.prs[run["head_branch"]] = [make_pr(24021, head=run["head_sha"])] + with tempfile.TemporaryDirectory() as temp, mock.patch.dict("os.environ", {"PR_POOL_OWNED": "1"}): + code, text = LostAssignmentSweepTests.sweep(self, fake, temp) + self.assertEqual(code, 0) + self.assertEqual(fake.posts(), [[str(run["id"]), "cancel"]]) + self.assertEqual([entry.get("app_actor") for entry in fake.snapshots[-1]["lost_reruns"]], [True]) + fake.runs[run["id"]].update(status="completed", conclusion="cancelled") + fake.log.clear() + LostAssignmentSweepTests.sweep(self, fake, temp) + self.assertEqual(fake.posts(), [[str(run["id"]), "rerun-failed-jobs"]]) + self.assertEqual(len(fake.app_only_posts), 1) + self.assertEqual(fake.runs[run["id"]]["triggering_actor"], {"login": "cmux-bot[bot]"}) + self.assertEqual(fake.snapshots[-1]["lost_reruns"], []) + + def test_a_bots_attempt_category_e_leaves_is_moved_by_category_f(self): + run, jobs = self.world(age=40, attempt=2, actor="github-actions[bot]") + other = make_run(path=NEXT_PATH, name="cmux-next", branch="lane/other", status="in_progress", age=20) + jobs[other["id"]] = [started_job(age=10, label=LARGE_MAC)] + lost = janitor.find_lost([run, other], jobs, now=NOW) + unclaimed = janitor.find_unclaimed([run, other], jobs, now=NOW, lost=lost, blacksmith_legs=True) + self.assertEqual((sorted(lost), sorted(unclaimed)), ([run["id"]], [run["id"]])) + prs = {run["head_branch"]: [make_pr(24021, head=run["head_sha"])], "lane/other": [make_pr(9)]} + result = janitor.build_plan([run, other], jobs, prs, threshold=6, max_cancels=10, + pull_request_policy="compile-only", now=NOW, lost=lost, unclaimed=unclaimed, + branch_heads={}, app_rerun=True) + decision = decision_for(result, run) + self.assertEqual((decision.action, decision.candidate.category), ("cancel", "unclaimed")) + self.assertTrue(decision.candidate.app_actor) + + def test_a_lost_gui_job_on_blacksmith_also_needs_an_app(self): + run, jobs = self.world(age=40) + jobs[run["id"]][0]["name"] = "cmux-next swift test" + jobs[run["id"]][0]["labels"] = ["blacksmith-6vcpu-macos-26"] + other = make_run(path=NEXT_PATH, name="cmux-next", branch="lane/other", status="in_progress", age=20) + jobs[other["id"]] = [started_job(age=10, label="blacksmith-6vcpu-macos-26")] + lost = janitor.find_lost([run, other], jobs, now=NOW) + prs = {run["head_branch"]: [make_pr(24021, head=run["head_sha"])], "lane/other": [make_pr(9)]} + result = janitor.build_plan([run, other], jobs, prs, threshold=6, max_cancels=10, + pull_request_policy="compile-only", now=NOW, lost=lost, unclaimed={}, + branch_heads={}, app_rerun=False) + self.assertEqual(decision_for(result, run).action, "skip") + + def test_a_feat_cmux_next_push_is_never_an_orphan_to_cancel(self): + push = make_run(event="push", path=NEXT_PATH, name="cmux-next", branch=NEXT_BRANCH) + self.assertIn("push to", janitor.orphan_protected_reason(push)) + main_push = make_run(event="push", path=".github/workflows/ci.yml", branch="main") + self.assertIsNone(janitor.orphan_protected_reason(main_push)) + + def test_only_same_repository_pull_request_cascade_jobs_count(self): + run, jobs = self.world(age=60) + self.assertIsNotNone(janitor.blacksmith_leg(run, jobs[run["id"]][0])) + fork, jobs = self.world(age=60) + fork["head_repository"]["id"] = 2 + self.assertEqual(janitor.find_unclaimed([fork], jobs, now=NOW, blacksmith_legs=True), {}) + dispatch, jobs = self.world(age=60) + dispatch["event"] = "workflow_dispatch" + self.assertEqual(janitor.find_unclaimed([dispatch], jobs, now=NOW, blacksmith_legs=True), {}) + run, jobs = self.world(age=60) + jobs[run["id"]][0]["name"] = "cmux-next swift test" + self.assertEqual(janitor.find_unclaimed([run], jobs, now=NOW, blacksmith_legs=True), {}) + + def test_a_lost_blacksmith_leg_is_re_run_only_by_an_app(self): + # Category e can hold the run first (a newer job on the same label started): its re-run needs an App too. + run, jobs = self.world(age=40) + other = make_run(path=NEXT_PATH, name="cmux-next", branch="lane/other", status="in_progress", age=20) + newer = started_job(age=10, label=LARGE_MAC) + jobs[other["id"]] = [newer] + lost = janitor.find_lost([run, other], jobs, now=NOW) + self.assertEqual(sorted(lost), [run["id"]]) + prs = {run["head_branch"]: [make_pr(24021, head=run["head_sha"])], "lane/other": [make_pr(9)]} + for app_rerun, action in ((False, "skip"), (True, "cancel")): + with self.subTest(app_rerun=app_rerun): + result = janitor.build_plan([run, other], jobs, prs, threshold=6, max_cancels=10, + pull_request_policy="compile-only", now=NOW, lost=lost, unclaimed={}, + branch_heads={}, app_rerun=app_rerun) + decision = decision_for(result, run) + self.assertEqual((decision.action, decision.candidate.category), (action, "lost")) + self.assertTrue(decision.candidate.app_actor or action == "skip") + + if __name__ == "__main__": unittest.main()