From d177fc3d53679ed29e07b2c73b8cea3b93f525ce Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 19:49:19 -0800 Subject: [PATCH 1/6] Carry Failing and Stale Pull Requests and Failing Branches in backlog_metrics.py JSON, Name Cut Lists, Make Billing Opt-In Add a per-repository attention object to the JSON document with failing pull requests, stale pull requests, failing branches, and recovered branches. Add truncated_lists beside truncated. Skip the billing read unless --billing is given, with billing null and no note when skipped. Co-Authored-By: Claude Sonnet 5.5 --- scripts/README.md | 14 +- scripts/backlog_metrics.py | 235 +++++++++++++++++++++++++-- tests/test_backlog_metrics.py | 293 +++++++++++++++++++++++++++++++++- 3 files changed, 522 insertions(+), 20 deletions(-) diff --git a/scripts/README.md b/scripts/README.md index a15df1b99..7f54e664b 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -348,13 +348,14 @@ Prints a weekly backlog and review-cost report for the cataloged repositories to ```sh uv run --no-project --script scripts/backlog_metrics.py uv run --no-project --script scripts/backlog_metrics.py --days 14 --format json --repo Example +uv run --no-project --script scripts/backlog_metrics.py --billing ``` It is a uv script, with the same inline metadata as `pr_review.py`. That lets it import the review gate's readers instead of keeping copies that would drift from them. The table has a row per repository and a totals row. The columns are issues opened and closed in the window, handoff issues created, and issues open now. Next come pull requests merged, issues opened per merged pull request (`n/a` without a merge), and workflow runs. Last come runs named `Running Copilot Code Review` and those review runs per merged pull request (`n/a` without a merge). Every issue count except the handoff column leaves out issues labeled `handoff`. In the Markdown output each repository name links to its GitHub page. Each issue and pull request count links to the GitHub search listing what it counts. Each dated search runs from the window's first day through its last, and the open-now search lists what is open when it is opened. The workflow run counts print plain, since they come from `gh run list` rather than from a search. -A line per repository follows with its open issues by label, and an issue with several labels counts under each. The labels the script names print first, a zero included, and every other label an open issue carries follows them. An issue labeled `handoff` is left out here too. The month's Actions minutes per repository and Copilot gross come from the user billing usage endpoint. They cover the calendar month to date rather than the window, so the report does not divide them by the window's merges. A failed call prints one line saying billing was unavailable rather than a zero. A list that reaches the item limit is noted in the report. A failed issue, pull request, or run call exits `1` with no report. +A line per repository follows with its open issues by label, and an issue with several labels counts under each. The labels the script names print first, a zero included, and every other label an open issue carries follows them. An issue labeled `handoff` is left out here too. With `--billing`, the month's Actions minutes per repository and Copilot gross come from the user billing usage endpoint. They cover the calendar month to date rather than the window, so the report does not divide them by the window's merges. A failed call prints one line saying billing was unavailable rather than a zero. Without the flag, which is the default, the read is skipped and the report prints no billing line and no billing note. The endpoint needs the "Plan" user permission, which a fine-grained personal access token cannot be granted, so only a classic token reaches it. A list that reaches the item limit is noted in the report. A failed issue, pull request, or run call exits `1` with no report. Two more tables measure what the pull request bots return for what they cost. They let a move from automatic to requested review be judged before and after. They read the window's merged pull requests through one paged GraphQL search per repository, newest created first. A pull request that appears twice while paging is counted once and noted. The search stops at 500 pull requests per repository, and each pull request connection is capped as well. A cap that was reached is named in the report, so a truncated figure never reads as a whole one. The bot logins come from the gate's reviewer vocabularies. A promotion pull request, one from `develop` into the default branch, is left out and counted in its own column. It would otherwise dominate the commit and failing-head counts. @@ -374,9 +375,16 @@ The policy trigger is read once per repository from `.github/agent-policy.json` - `schema` is `1`. `start` and `end` are the window's dates, as `YYYY-MM-DD`. - `totals` holds the totals row as numbers. Its fields are `issues_opened`, `issues_closed`, `handoffs_created`, `issues_open`, `prs_merged`, `issues_opened_per_merged_pr`, `workflow_runs`, `copilot_review_runs`, and `copilot_review_runs_per_merged_pr`. A ratio is `null` where the Markdown prints `n/a`. -- `billing` holds `month`, `error`, `actions_minutes` (repository name to minutes), and `copilot_gross_usd`. Where billing failed, `error` names the failure and the two figures are `null`, and otherwise `error` is `null`. +- `billing` is `null` where the run skipped the billing read, which is the default and adds no note. With `--billing` it holds `month`, `error`, `actions_minutes` (repository name to minutes), and `copilot_gross_usd`. Where that read failed, `error` names the failure and the two figures are `null`, and otherwise `error` is `null`. - `notes` is the list of billing lines and notes the Markdown report prints after its label lines. Those label lines are each repository's `open_issues_by_label` here. -- `repositories` holds one entry per repository, in the order read. Each carries `name`, `html_url`, and the same nine fields `totals` carries, counted for that repository. Next come `open_issues_by_label`, label name to count, and `truncated`, true where a list reached the item limit. +- `repositories` holds one entry per repository, in the order read. Each carries `name`, `html_url`, and the same nine fields `totals` carries, counted for that repository. Next come `open_issues_by_label`, label name to count, and `truncated`, true where a list reached the item limit. `truncated_lists` names each list that reached it, from `issues_opened`, `issues_closed`, `issues_open`, `prs_merged`, and `workflow_runs`, and is empty where `truncated` is false. Then comes `attention`. +- Each repository's `attention` is read only for `--format json`, and is `null` where that read failed. A failed read adds one note, names the error on stderr, and exits `1`. Open pull requests are read newest-updated first, up to 500, and drafts are in no list. It holds these lists, each empty where nothing needs the maintainer: + - `failing_pull_requests`: open pull requests whose head has a check run concluded `FAILURE`, `TIMED_OUT`, `ACTION_REQUIRED`, or `STARTUP_FAILURE`, or a status context in `FAILURE` or `ERROR`. `CANCELLED` is left out. Each entry has `number`, `title`, `html_url`, `author`, `base_branch`, and `failing_checks`, the names of the failing checks. + - `stale_pull_requests`: open pull requests with no update for `--stale-days` days, 7 by default, and no failing check. Each entry has the same fields, with `updated_at` in place of `failing_checks`. + - `failing_branches`: for the default branch, and `develop` where it exists, each workflow whose latest completed run concluded `failure`, `timed_out`, or `startup_failure`. Each entry has `branch`, `workflow`, `conclusion`, the run's `html_url`, and `failed_runs_in_window`. The latest 200 runs of each branch are read. + - `recovered_branches`: on those branches, each workflow that failed in the window while its latest completed run did not. Each entry has `branch`, `workflow`, `failed_runs_in_window`, and the `html_url` of its newest failed run. + - `truncated`: strings naming a cap that was reached, such as a cut pull request list or run list. + The open `decision` issues are already in `items.issues_open`. - Each repository's `items` lists what each count counted, under the same names. `issues_opened`, `issues_closed`, `handoffs_created`, and `issues_open` hold issues as `number`, `title`, `html_url`, and `labels`. `prs_merged` holds pull requests as `number`, `title`, and `html_url`. `workflow_runs` and `copilot_review_runs` hold runs as `id`, `name`, and `html_url`. - Each repository's `review` is `null` where the review query failed. Otherwise it holds the per-repository table's figures: `merged_prs_read`, `promotion_prs_excluded`, `commits_per_merged_pr`, `local_findings`, `local_attestations_unknown`, `failing_heads`, and `failing_heads_after_clean_local_review`. Then come `policy_branch`, `policy_error`, and `policy_history_error`, each a string or `null`. `policy_changes` lists the dates the policy file changed, as `YYYY-MM-DD`. An entry reads `unknown` for a commit carrying no date, and a last entry reads `more than 10 commits` past that many. `truncated` lists the caps reached. `bots` maps each bot to its per-bot row. That row holds `policy_trigger`, `policy_from_default`, `requests_by_automation`, `requests_by_user`, `automatic_rounds`, `explicit_rounds`, `unclassified_rounds`, `rounds_per_reviewed_pr_mean`, `rounds_per_reviewed_pr_max`, `threaded_findings`, `findings_missed_by_local_review`, and `findings_on_green_heads`. A figure the Markdown prints as `n/a` or `error` is `null`. `policy_trigger` is the trigger as the policy states it, and `policy_from_default` is true where it comes from the hub default, which the Markdown marks `(default)`. diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index 970e6c1bd..f043a69b3 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -20,6 +20,7 @@ Usage uv run --no-project --script scripts/backlog_metrics.py [--owner OWNER] [--repo NAME ...] [--days N] [--format markdown|json] + [--billing] [--stale-days N] It is a uv script because it imports the review gate's own readers, which parse Markdown. A copy of those readers here would drift from the gate and report figures the gate would not. @@ -40,12 +41,15 @@ line saying the review figures were unavailable and names the error on stderr, then exits 1. Four reads fail more softly: the default branch, whether `develop` exists, the policy file, and its history. A failed one still writes the report, names that read on stderr, and - exits 1. Where the policy itself went unread, the report shows `error` in its place. + exits 1. Where the policy itself went unread, the report shows `error` in its place. So does a + failed read of the attention lists, which `--format json` makes. Each repository's + `attention` is then `null`, one note says so, and the exit status is 1. 2 the command line was wrong. """ import argparse import contextlib +import dataclasses import datetime import json import os @@ -88,6 +92,10 @@ INTEGRATION_BRANCH = "develop" HISTORY_CAP = 10 FAILED_STATES = frozenset({"FAILURE", "ERROR"}) +FAILING_CHECKS = frozenset({"FAILURE", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"}) +FAILING_RUNS = frozenset({"failure", "timed_out", "startup_failure"}) +ATTENTION_RUN_LIMIT = 200 +CHECK_CAP = 100 LABELS = ("pre-existing", "prose", "documentation", "bug", "script", "enhancement", "decision") Items = Sequence[Mapping[str, Any]] @@ -115,6 +123,8 @@ class RepoMetrics: truncated: bool = False url: str = "" items: Mapping[str, Items] = field(default_factory=dict) + truncated_lists: tuple[str, ...] = () + attention: Mapping[str, Any] | None = None def run_gh(args: Sequence[str]) -> Any: @@ -196,7 +206,14 @@ def compute_metrics( url: str = "", ) -> RepoMetrics: """Reduce one repository's parsed lists to the report's counts and the items behind each.""" - lists = (opened_items, closed_items, open_items, merged_prs, runs) + lists = { + "issues_opened": opened_items, + "issues_closed": closed_items, + "issues_open": open_items, + "prs_merged": merged_prs, + "workflow_runs": runs, + } + cut = tuple(key for key, items in lists.items() if len(items) >= LIST_LIMIT) def issues(items: Items, handoff: bool) -> list[dict[str, Any]]: return [issue_item(i) for i in items if (HANDOFF_LABEL in label_names(i)) == handoff] @@ -212,7 +229,8 @@ def issues(items: Items, handoff: bool) -> list[dict[str, Any]]: merged=len(merged_prs), runs=len(runs), review_runs=count_named(runs, REVIEW_WORKFLOW), - truncated=any(len(items) >= LIST_LIMIT for items in lists), + truncated=bool(cut), + truncated_lists=cut, url=url, items={ "issues_opened": issues(opened_items, False), @@ -724,10 +742,12 @@ def render_json( metrics: Sequence[RepoMetrics], billing: Sequence[str], reviews: Sequence[ReviewMetrics], - billing_figures: Mapping[str, Any], + billing_figures: Mapping[str, Any] | None, ) -> str: """The report as one JSON document, the headline totals at its top level. + `billing` is `null` where the run skipped the billing read, which is the default. + `notes` holds the billing lines and the notes the Markdown report lists after its label lines. A consumer can then print what this run noted without re-deriving it. `scripts/README.md` documents each field. @@ -738,7 +758,7 @@ def render_json( "start": start.isoformat(), "end": end.isoformat(), "totals": counts(metrics), - "billing": dict(billing_figures), + "billing": None if billing_figures is None else dict(billing_figures), "notes": [*billing, *notes(metrics), *review_notes(reviews)], "repositories": [ { @@ -747,6 +767,8 @@ def render_json( **counts([m]), "open_issues_by_label": dict(m.open_by_label), "truncated": m.truncated, + "truncated_lists": list(m.truncated_lists), + "attention": None if m.attention is None else dict(m.attention), "items": {key: list(value) for key, value in m.items.items()}, "review": review_data(by_name[m.name]) if m.name in by_name else None, } @@ -838,14 +860,16 @@ def graphql(query: str, variables: dict[str, object]) -> dict[str, Any]: return dict(request(query, variables).data) -def walked(fetch: Callable[[str | None], dict]) -> Iterator[dict]: - """Each page of the search, a walk's own `GraphQLError` raised as a `GhError`. +def walked( + fetch: Callable[[str | None], dict], path: Sequence[str] = ("search",) +) -> Iterator[dict]: + """Each page of the connection at `path`, a walk's own `GraphQLError` raised as a `GhError`. The walk raises for a page claiming another without a moving cursor, as `request` raises for a failed query. Both then reach `main` as the one error type it names on stderr. """ try: - yield from walk(fetch, ["search"]) + yield from walk(fetch, path) except GraphQLError as error: raise GhError(f"{error} {error.detail}".strip()) from error @@ -969,6 +993,167 @@ def fetch(after: str | None) -> dict: return result +ATTENTION_QUERY = """ +query($owner: String!, $name: String!, $after: String) { + repository(owner: $owner, name: $name) { + defaultBranchRef { name } + develop: ref(qualifiedName: "refs/heads/develop") { name } + pullRequests(states: OPEN, first: @PAGE@, after: $after, + orderBy: {field: UPDATED_AT, direction: DESC}) { + pageInfo { hasNextPage endCursor } + nodes { + number + title + url + isDraft + updatedAt + baseRefName + author { login } + commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: @CHECK@) { + pageInfo { hasNextPage } + nodes { + __typename + ... on CheckRun { name conclusion } + ... on StatusContext { context state } + } + } } } } } + } + } + } +} +""".replace("@PAGE@", str(PAGE_SIZE)).replace("@CHECK@", str(CHECK_CAP)) + + +def failing_checks(pr: Mapping[str, Any]) -> tuple[list[str], bool]: + """The names of a pull request's failing checks, and whether its check list was cut.""" + commits = nodes_of(pr.get("commits")) + rollup = (commits[0].get("commit") or {}).get("statusCheckRollup") if commits else None + contexts = (rollup or {}).get("contexts") or {} + names = [] + for node in nodes_of(contexts): + if node.get("__typename") == "CheckRun" and node.get("conclusion") in FAILING_CHECKS: + names.append(str(node.get("name") or "")) + elif node.get("__typename") == "StatusContext" and node.get("state") in FAILED_STATES: + names.append(str(node.get("context") or "")) + return names, bool((contexts.get("pageInfo") or {}).get("hasNextPage")) + + +def pr_attention(pr: Mapping[str, Any]) -> dict[str, Any]: + author = pr.get("author") or {} + return { + **pr_item(pr), + "author": str(author.get("login") or ""), + "base_branch": str(pr.get("baseRefName") or ""), + } + + +def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[list, list]: + """The workflows whose latest completed run on `branch` failed, and those that recovered. + + `runs` is newest first, as `gh run list` prints it. A workflow recovered where a run failed in + the window and its latest completed run did not. + """ + latest: dict[str, Mapping[str, Any]] = {} + failed: dict[str, list[Mapping[str, Any]]] = {} + for run in runs: + workflow = str(run.get("workflowName") or run.get("name") or "") + if not run.get("conclusion"): + continue + latest.setdefault(workflow, run) + if run["conclusion"] in FAILING_RUNS and str(run.get("createdAt") or "")[:10] >= str(since): + failed.setdefault(workflow, []).append(run) + still, recovered = [], [] + for workflow, run in latest.items(): + in_window = failed.get(workflow, []) + if run["conclusion"] in FAILING_RUNS: + still.append( + { + "branch": branch, + "workflow": workflow, + "conclusion": run["conclusion"], + "html_url": str(run.get("url") or ""), + "failed_runs_in_window": len(in_window), + } + ) + elif in_window: + recovered.append( + { + "branch": branch, + "workflow": workflow, + "html_url": str(in_window[0].get("url") or ""), + "failed_runs_in_window": len(in_window), + } + ) + return still, recovered + + +def collect_attention( + owner: str, name: str, since: datetime.date, today: datetime.date, stale_days: int +) -> dict[str, Any]: + """What needs the maintainer now in one repository: failing and stale pull requests, branches. + + Open non-draft pull requests are read, up to `PR_CAP`. A stale one has had no update for + `stale_days` and has no failing check. The default branch and `develop`, where it exists, are + read for two kinds of workflow. One kind's latest completed run failed. The other kind failed + in the window and recovered. + """ + + def fetch(after: str | None) -> dict: + variables: dict[str, object] = {"owner": owner, "name": name} + if after is not None: + variables["after"] = after + return graphql(ATTENTION_QUERY, variables) + + result: dict[str, Any] = { + "failing_pull_requests": [], + "stale_pull_requests": [], + "failing_branches": [], + "recovered_branches": [], + "truncated": [], + } + stale_before = window_start(today, stale_days).isoformat() + branches: list[str] = [] + seen = 0 + for page in walked(fetch, ("repository", "pullRequests")): + for ref in ("defaultBranchRef", "develop"): + branch = str((page.get(ref) or {}).get("name") or "") + if branch and branch not in branches: + branches.append(branch) + for pr in page["pullRequests"].get("nodes") or []: + if seen >= PR_CAP: + break + seen += 1 + if pr.get("isDraft"): + continue + names, cut = failing_checks(pr) + if cut: + result["truncated"].append(f"checks of #{pr.get('number')} cut at {CHECK_CAP}") + if names: + result["failing_pull_requests"].append( + {**pr_attention(pr), "failing_checks": names} + ) + elif str(pr.get("updatedAt") or "")[:10] <= stale_before: + result["stale_pull_requests"].append( + {**pr_attention(pr), "updated_at": str(pr.get("updatedAt") or "")} + ) + if seen >= PR_CAP: + if (page["pullRequests"].get("pageInfo") or {}).get("hasNextPage"): + result["truncated"].append(f"open pull requests cut at {PR_CAP}") + break + for branch in branches: + runs = run_gh( + ["run", "list", "--repo", f"{owner}/{name}", "--branch", branch] + + ["--limit", str(ATTENTION_RUN_LIMIT)] + + ["--json", "databaseId,workflowName,url,conclusion,createdAt"] + ) + still, recovered = branch_attention(branch, runs, since) + result["failing_branches"] += still + result["recovered_branches"] += recovered + if len(runs) >= ATTENTION_RUN_LIMIT: + result["truncated"].append(f"runs of {branch} cut at {ATTENTION_RUN_LIMIT}") + return result + + def fetch_billing(owner: str, today: datetime.date) -> tuple[Mapping[str, Any] | None, str]: path = f"/users/{owner}/settings/billing/usage?year={today.year}&month={today.month:02d}" try: @@ -1004,6 +1189,17 @@ def build_parser() -> argparse.ArgumentParser: ) parser.add_argument("--days", type=positive_int, default=7, help="window length in days") parser.add_argument("--format", choices=("markdown", "json"), default="markdown") + parser.add_argument( + "--billing", + action="store_true", + help="also read the owner's billing, which a user account's fine-grained token cannot do", + ) + parser.add_argument( + "--stale-days", + type=positive_int, + default=7, + help="days without an update before an open pull request is stale, read for --format json", + ) return parser @@ -1026,13 +1222,28 @@ def main(argv: Sequence[str] | None = None) -> int: except GhError as error: review_error = str(error) print(f"backlog_metrics.py: reading the review figures failed: {error}", file=sys.stderr) - usage, error_text = fetch_billing(owner, end) + attention_error = "" + if args.format == "json": + try: + attention = {n: collect_attention(owner, n, start, end, args.stale_days) for n in names} + metrics = [dataclasses.replace(m, attention=attention[m.name]) for m in metrics] + except GhError as error: + attention_error = str(error) + print( + f"backlog_metrics.py: reading the attention lists failed: {error}", file=sys.stderr + ) month = f"{end.year}-{end.month:02d}" - billing = billing_lines(month, names, usage, error_text) + billing: list[str] = [] + figures: dict[str, Any] | None = None + if args.billing: + usage, error_text = fetch_billing(owner, end) + billing = billing_lines(month, names, usage, error_text) + figures = billing_data(month, names, usage, error_text) if review_error: billing.append(f"Review figures were unavailable: {review_error}") + if attention_error: + billing.append(f"Attention lists were unavailable: {attention_error}") if args.format == "json": - figures = billing_data(month, names, usage, error_text) sys.stdout.write(render_json(start, end, metrics, billing, reviews, figures)) else: sys.stdout.write(render_markdown(start, end, metrics, billing, reviews)) @@ -1044,7 +1255,7 @@ def main(argv: Sequence[str] | None = None) -> int: ] for line in failed: print(line, file=sys.stderr) - return 1 if failed or review_error else 0 + return 1 if failed or review_error or attention_error else 0 received: list[int] = [] diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index b364f7171..6c30564d4 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -118,6 +118,13 @@ def test_a_full_list_marks_the_result_truncated(self) -> None: self.assertTrue(bm.compute_metrics("alpha", full, [], [], [], []).truncated) self.assertFalse(bm.compute_metrics("alpha", [issue()], [], [], [], []).truncated) + def test_each_cut_list_is_named_beside_the_flag(self) -> None: + full = [issue()] * bm.LIST_LIMIT + result = bm.compute_metrics("alpha", [], full, [issue()], [], full) + self.assertEqual(result.truncated_lists, ("issues_closed", "workflow_runs")) + self.assertTrue(result.truncated) + self.assertEqual(bm.compute_metrics("alpha", [], [], [], [], []).truncated_lists, ()) + def test_a_ratio_has_one_decimal_and_na_without_a_merge(self) -> None: self.assertEqual(bm.ratio_text(bm.ratio(7, 2)), "3.5") self.assertEqual(bm.ratio_text(bm.ratio(1, 3)), "0.3") @@ -291,6 +298,7 @@ def test_json_carries_the_figures_with_each_item_linked(self) -> None: self.assertEqual({k: entry[k] for k in doc["totals"]}, doc["totals"]) self.assertEqual(entry["open_issues_by_label"]["bug"], 1) self.assertFalse(entry["truncated"]) + self.assertEqual((entry["truncated_lists"], entry["attention"]), ([], None)) linked = {"number": 7, "title": "A title", "html_url": item["url"], "labels": ["bug"]} self.assertEqual(entry["items"]["issues_opened"], [linked]) self.assertEqual(entry["items"]["issues_open"], [linked]) @@ -312,8 +320,8 @@ def test_json_carries_the_figures_with_each_item_linked(self) -> None: ) self.assertEqual( list(entry), - ["name", "html_url", *doc["totals"], "open_issues_by_label", "truncated", "items"] - + ["review"], + ["name", "html_url", *doc["totals"], "open_issues_by_label", "truncated"] + + ["truncated_lists", "attention", "items", "review"], ) review = entry["review"] self.assertEqual( @@ -1159,7 +1167,7 @@ def fake(args: list[str]) -> object: contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), ): - code = bm.main(["--owner", "o", "--repo", "alpha"]) + code = bm.main(["--owner", "o", "--repo", "alpha", "--billing"]) self.assertEqual(code, 1) report = out.getvalue() self.assertIn("| [alpha](https://github.com/o/alpha) |", report) @@ -1195,6 +1203,277 @@ def test_a_side_reviewer_row_prints_each_round_class(self) -> None: self.assertEqual(len(row), len(bm.REVIEW_BOT_HEADERS)) +def attention_page( + prs: list[dict[str, object]], more: bool = False, develop: bool = True +) -> dict[str, object]: + return { + "repository": { + "defaultBranchRef": {"name": "main"}, + "develop": {"name": "develop"} if develop else None, + "pullRequests": { + "pageInfo": {"hasNextPage": more, "endCursor": "c" if more else None}, + "nodes": prs, + }, + } + } + + +def open_pr(number: int, *contexts: dict[str, object], **fields: object) -> dict[str, object]: + rollup = {"contexts": {"pageInfo": {"hasNextPage": False}, "nodes": list(contexts)}} + return { + "number": number, + "title": f"PR {number}", + "url": f"u{number}", + "isDraft": False, + "updatedAt": "2026-11-23T00:00:00Z", + "baseRefName": "develop", + "author": {"login": "dependabot"}, + "commits": {"nodes": [{"commit": {"statusCheckRollup": rollup}}]}, + } | fields + + +def check(name: str, conclusion: str) -> dict[str, object]: + return {"__typename": "CheckRun", "name": name, "conclusion": conclusion} + + +def run_record(workflow: str, conclusion: str, day: str, url: str) -> dict[str, object]: + return { + "workflowName": workflow, + "conclusion": conclusion, + "createdAt": f"{day}T00:00:00Z", + "url": url, + } + + +class AttentionTests(unittest.TestCase): + START = datetime.date(2026, 11, 17) + TODAY = datetime.date(2026, 11, 24) + + def attention( + self, + prs: list[dict[str, object]], + runs: dict[str, list[dict[str, object]]] | None = None, + **kwargs: object, + ) -> dict[str, object]: + runs = runs or {} + + def fake(args: list[str]) -> object: + return runs.get(args[args.index("--branch") + 1], []) + + with ( + unittest.mock.patch.object( + bm, + "graphql", + side_effect=[attention_page(prs, **kwargs)], # type: ignore[arg-type] + ), + unittest.mock.patch.object(bm, "run_gh", side_effect=fake), + ): + return bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + + def test_a_failing_check_or_status_names_the_pull_request(self) -> None: + failing = open_pr( + 1, + check("compile", "FAILURE"), + check("lint", "SUCCESS"), + {"__typename": "StatusContext", "context": "ci/legacy", "state": "ERROR"}, + ) + result = self.attention([failing]) + self.assertEqual( + result["failing_pull_requests"], + [ + { + "number": 1, + "title": "PR 1", + "html_url": "u1", + "author": "dependabot", + "base_branch": "develop", + "failing_checks": ["compile", "ci/legacy"], + } + ], + ) + + def test_each_failing_conclusion_counts_and_cancelled_does_not(self) -> None: + for conclusion in sorted(bm.FAILING_CHECKS): + with self.subTest(conclusion=conclusion): + result = self.attention([open_pr(1, check("x", conclusion))]) + self.assertEqual(len(result["failing_pull_requests"]), 1) # type: ignore[arg-type] + result = self.attention([open_pr(1, check("x", "CANCELLED"))]) + self.assertEqual(result["failing_pull_requests"], []) + + def test_a_draft_is_in_no_list(self) -> None: + draft = open_pr(1, check("x", "FAILURE"), isDraft=True, updatedAt="2026-01-01T00:00:00Z") + result = self.attention([draft]) + self.assertEqual((result["failing_pull_requests"], result["stale_pull_requests"]), ([], [])) + + def test_a_stale_pull_request_has_no_failing_check_and_a_failing_one_is_not_stale(self) -> None: + old = "2026-11-17T09:00:00Z" + stale = open_pr(1, check("x", "SUCCESS"), updatedAt=old) + failing = open_pr(2, check("x", "FAILURE"), updatedAt=old) + fresh = open_pr(3, updatedAt="2026-11-18T00:00:00Z") + result = self.attention([stale, failing, fresh]) + self.assertEqual([p["number"] for p in result["stale_pull_requests"]], [1]) # type: ignore[attr-defined] + self.assertEqual(result["stale_pull_requests"][0]["updated_at"], old) # type: ignore[index] + self.assertEqual([p["number"] for p in result["failing_pull_requests"]], [2]) # type: ignore[attr-defined] + + def test_a_cut_check_list_is_named(self) -> None: + pr = open_pr(5, check("x", "SUCCESS")) + pr["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["pageInfo"] = { # type: ignore[index] + "hasNextPage": True + } + self.assertEqual(self.attention([pr])["truncated"], [f"checks of #5 cut at {bm.CHECK_CAP}"]) + + def test_a_failing_latest_run_names_the_workflow_and_a_recovered_one_is_apart(self) -> None: + runs = { + "main": [ + run_record("Build", "failure", "2026-11-23", "b2"), + run_record("Build", "failure", "2026-11-22", "b1"), + run_record("Build", "success", "2026-11-21", "b0"), + run_record("CodeQL", "success", "2026-11-23", "c2"), + run_record("CodeQL", "failure", "2026-11-20", "c1"), + run_record("Old", "failure", "2026-10-01", "o1"), + run_record("Cancelled", "cancelled", "2026-11-23", "x1"), + run_record("Running", "", "2026-11-23", "r1"), + ], + "develop": [run_record("Build", "timed_out", "2026-11-23", "d1")], + } + result = self.attention([], runs) + self.assertEqual( + result["failing_branches"], + [ + { + "branch": "main", + "workflow": "Build", + "conclusion": "failure", + "html_url": "b2", + "failed_runs_in_window": 2, + }, + { + "branch": "main", + "workflow": "Old", + "conclusion": "failure", + "html_url": "o1", + "failed_runs_in_window": 0, + }, + { + "branch": "develop", + "workflow": "Build", + "conclusion": "timed_out", + "html_url": "d1", + "failed_runs_in_window": 1, + }, + ], + ) + self.assertEqual( + result["recovered_branches"], + [ + { + "branch": "main", + "workflow": "CodeQL", + "html_url": "c1", + "failed_runs_in_window": 1, + } + ], + ) + + def test_only_the_default_branch_is_read_where_develop_is_absent(self) -> None: + with ( + unittest.mock.patch.object( + bm, "graphql", side_effect=[attention_page([], develop=False)] + ), + unittest.mock.patch.object(bm, "run_gh", return_value=[]) as run, + ): + bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + self.assertEqual( + [c.args[0][c.args[0].index("--branch") + 1] for c in run.call_args_list], ["main"] + ) + + def test_pull_request_pages_are_followed(self) -> None: + pages = [attention_page([open_pr(1, check("x", "FAILURE"))], more=True)] + pages.append(attention_page([open_pr(2, check("x", "FAILURE"))])) + with ( + unittest.mock.patch.object(bm, "graphql", side_effect=pages), + unittest.mock.patch.object(bm, "run_gh", return_value=[]), + ): + result = bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + self.assertEqual([p["number"] for p in result["failing_pull_requests"]], [1, 2]) + + def test_a_failed_read_leaves_attention_null_and_exits_one(self) -> None: + def graphql(query: str, variables: dict[str, object]) -> dict[str, object]: + if "pullRequests" in query: + raise bm.GhError("attention down") + return page([], False, 0) + + out, err = io.StringIO(), io.StringIO() + with ( + unittest.mock.patch.object(bm, "graphql", side_effect=graphql), + unittest.mock.patch.object(bm, "run_gh", side_effect=quiet_rest), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(err), + ): + code = bm.main(["--owner", "o", "--repo", "alpha", "--format", "json"]) + self.assertEqual(code, 1) + doc = json.loads(out.getvalue()) + self.assertIsNone(doc["repositories"][0]["attention"]) + self.assertIn("Attention lists were unavailable: attention down", doc["notes"]) + self.assertIn("reading the attention lists failed", err.getvalue()) + + def test_markdown_reads_no_attention_lists(self) -> None: + def graphql(query: str, variables: dict[str, object]) -> dict[str, object]: + self.assertNotIn("pullRequests", query) + return page([], False, 0) + + with ( + unittest.mock.patch.object(bm, "graphql", side_effect=graphql), + unittest.mock.patch.object(bm, "run_gh", side_effect=quiet_rest), + contextlib.redirect_stdout(io.StringIO()), + ): + self.assertEqual(bm.main(["--owner", "o", "--repo", "alpha"]), 0) + + +class BillingOptInTests(unittest.TestCase): + def read(self, *flags: str) -> tuple[str, list[str]]: + calls: list[list[str]] = [] + + def fake(args: list[str]) -> object: + calls.append(args) + if args[0] == "api" and "contents" in args[1]: + raise bm.GhError("gh: Not Found (HTTP 404)") + return {"usageItems": []} if args[0] == "api" and "usage" in args[1] else [] + + out = io.StringIO() + with ( + unittest.mock.patch.object( + bm, + "graphql", + side_effect=lambda q, v: ( + attention_page([]) if "pullRequests" in q else page([], False, 0) + ), + ), + unittest.mock.patch.object(bm, "run_gh", side_effect=fake), + contextlib.redirect_stdout(out), + ): + bm.main(["--owner", "o", "--repo", "alpha", *flags]) + return out.getvalue(), [" ".join(c) for c in calls if "billing" in " ".join(c)] + + def test_billing_is_not_read_by_default_and_prints_nothing(self) -> None: + text, billing_calls = self.read() + self.assertEqual(billing_calls, []) + self.assertNotIn("illing", text) + self.assertNotIn("Actions minutes", text) + + def test_json_billing_is_null_and_noteless_where_skipped(self) -> None: + text, billing_calls = self.read("--format", "json") + doc = json.loads(text) + self.assertEqual(billing_calls, []) + self.assertIsNone(doc["billing"]) + self.assertEqual(doc["notes"], []) + + def test_the_flag_reads_billing_and_prints_it(self) -> None: + text, billing_calls = self.read("--billing") + self.assertEqual(len(billing_calls), 1) + self.assertIn("Actions minutes", text) + + class MainTests(unittest.TestCase): def test_main_writes_the_report_to_stdout(self) -> None: def fake(args: list[str]) -> object: @@ -1238,15 +1517,19 @@ def fake(args: list[str]) -> object: return [{"databaseId": 5, "name": "Build", "url": "r5"}] return [{"number": 2, "url": "https://github.com/o/alpha/pull/2"}] + def graphql(query: str, variables: dict[str, object]) -> dict[str, object]: + return attention_page([]) if "pullRequests" in query else page([], False, 0) + out = io.StringIO() with ( - unittest.mock.patch.object(bm, "graphql", return_value=page([], False, 0)), + unittest.mock.patch.object(bm, "graphql", side_effect=graphql), unittest.mock.patch.object(bm, "run_gh", side_effect=fake), contextlib.redirect_stdout(out), ): - code = bm.main(["--owner", "o", "--repo", "alpha", "--format", "json"]) + code = bm.main(["--owner", "o", "--repo", "alpha", "--format", "json", "--billing"]) self.assertEqual(code, 0) doc = json.loads(out.getvalue()) + self.assertEqual(doc["repositories"][0]["attention"]["failing_pull_requests"], []) self.assertEqual(doc["totals"]["prs_merged"], 1) self.assertEqual(doc["billing"]["error"], "billing denied") self.assertIn("Billing was unavailable", doc["notes"][0]) From 8a3bb94a4718442ebbbe6d8a6fa0b7a4c50c1808 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 19:53:32 -0800 Subject: [PATCH 2/6] Read Attention Checks Through the Gate's Readers and Decide Cancelled Runs, Stale Instants, and Caps Co-Authored-By: Claude Sonnet 5.5 --- scripts/README.md | 8 +-- scripts/backlog_metrics.py | 85 ++++++++++++++++++------------- tests/test_backlog_metrics.py | 95 +++++++++++++++++++++++++++++++---- 3 files changed, 138 insertions(+), 50 deletions(-) diff --git a/scripts/README.md b/scripts/README.md index 7f54e664b..2831dc64e 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -378,10 +378,10 @@ The policy trigger is read once per repository from `.github/agent-policy.json` - `billing` is `null` where the run skipped the billing read, which is the default and adds no note. With `--billing` it holds `month`, `error`, `actions_minutes` (repository name to minutes), and `copilot_gross_usd`. Where that read failed, `error` names the failure and the two figures are `null`, and otherwise `error` is `null`. - `notes` is the list of billing lines and notes the Markdown report prints after its label lines. Those label lines are each repository's `open_issues_by_label` here. - `repositories` holds one entry per repository, in the order read. Each carries `name`, `html_url`, and the same nine fields `totals` carries, counted for that repository. Next come `open_issues_by_label`, label name to count, and `truncated`, true where a list reached the item limit. `truncated_lists` names each list that reached it, from `issues_opened`, `issues_closed`, `issues_open`, `prs_merged`, and `workflow_runs`, and is empty where `truncated` is false. Then comes `attention`. -- Each repository's `attention` is read only for `--format json`, and is `null` where that read failed. A failed read adds one note, names the error on stderr, and exits `1`. Open pull requests are read newest-updated first, up to 500, and drafts are in no list. It holds these lists, each empty where nothing needs the maintainer: - - `failing_pull_requests`: open pull requests whose head has a check run concluded `FAILURE`, `TIMED_OUT`, `ACTION_REQUIRED`, or `STARTUP_FAILURE`, or a status context in `FAILURE` or `ERROR`. `CANCELLED` is left out. Each entry has `number`, `title`, `html_url`, `author`, `base_branch`, and `failing_checks`, the names of the failing checks. - - `stale_pull_requests`: open pull requests with no update for `--stale-days` days, 7 by default, and no failing check. Each entry has the same fields, with `updated_at` in place of `failing_checks`. - - `failing_branches`: for the default branch, and `develop` where it exists, each workflow whose latest completed run concluded `failure`, `timed_out`, or `startup_failure`. Each entry has `branch`, `workflow`, `conclusion`, the run's `html_url`, and `failed_runs_in_window`. The latest 200 runs of each branch are read. +- Each repository's `attention` is read only for `--format json`, and is `null` where that read failed. A failed read adds one note, names the error on stderr, and exits `1`. Open pull requests are read newest-updated first, up to 500, drafts counting toward that cap and in no list. It holds these lists, each empty where nothing needs the maintainer: + - `failing_pull_requests`: open pull requests whose head has a check run concluded `FAILURE`, `TIMED_OUT`, `ACTION_REQUIRED`, or `STARTUP_FAILURE`, or a status context in `FAILURE` or `ERROR`. The checks are read as the review gate reads them. `CANCELLED` is left out. Each entry has `number`, `title`, `html_url`, `author`, `base_branch`, and `failing_checks`, the names of the failing checks. + - `stale_pull_requests`: open pull requests with no update for `--stale-days` days, 7 by default, counted to the instant, and no failing check. Each entry has the same fields, with `updated_at` in place of `failing_checks`. + - `failing_branches`: for the default branch, and `develop` where it exists, each workflow whose latest completed run concluded `failure`, `timed_out`, or `startup_failure`. Each entry has `branch`, `workflow`, `conclusion`, the run's `html_url`, and `failed_runs_in_window`. The latest 200 runs of each branch are read. A cancelled or skipped run decides nothing. A pull request's run is left out, since a fork's branch can share the name. - `recovered_branches`: on those branches, each workflow that failed in the window while its latest completed run did not. Each entry has `branch`, `workflow`, `failed_runs_in_window`, and the `html_url` of its newest failed run. - `truncated`: strings naming a cap that was reached, such as a cut pull request list or run list. The open `decision` issues are already in `items.issues_open`. diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index f043a69b3..01f24229b 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -41,9 +41,9 @@ line saying the review figures were unavailable and names the error on stderr, then exits 1. Four reads fail more softly: the default branch, whether `develop` exists, the policy file, and its history. A failed one still writes the report, names that read on stderr, and - exits 1. Where the policy itself went unread, the report shows `error` in its place. So does a - failed read of the attention lists, which `--format json` makes. Each repository's - `attention` is then `null`, one note says so, and the exit status is 1. + exits 1. Where the policy itself went unread, the report shows `error` in its place. A failed + read of the attention lists, which `--format json` makes, writes the report too. Each + repository's `attention` is then `null`, one note says so, and the exit status is 1. 2 the command line was wrong. """ @@ -64,7 +64,7 @@ import pr_review_rounds as rounds import pr_review_side as side from gh_graphql import GraphQLError, request, run_subprocess, said_absent, walk -from pr_review_checks import utc_instant +from pr_review_checks import check_nodes, checks_truncated, utc_instant from pr_review_copilot import VOCABULARIES from pr_review_policy import BOTS, COMMANDS, POLICY_PATH, PolicyError, fetch @@ -94,6 +94,8 @@ FAILED_STATES = frozenset({"FAILURE", "ERROR"}) FAILING_CHECKS = frozenset({"FAILURE", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"}) FAILING_RUNS = frozenset({"failure", "timed_out", "startup_failure"}) +UNDECIDED_RUNS = frozenset({"cancelled", "skipped", "neutral"}) +PR_EVENTS = frozenset({"pull_request", "pull_request_target"}) ATTENTION_RUN_LIMIT = 200 CHECK_CAP = 100 LABELS = ("pre-existing", "prose", "documentation", "bug", "script", "enhancement", "decision") @@ -855,7 +857,7 @@ def issues(state: str, search: str | None, fields: str) -> Any: def graphql(query: str, variables: dict[str, object]) -> dict[str, Any]: """Run one GraphQL document through the shared reader, so a null node or error raises. - The one caller reads through `walked`, which names a `GraphQLError` as a `GhError`. + Each caller reads through `walked`, which names a `GraphQLError` as a `GhError`. """ return dict(request(query, variables).data) @@ -993,11 +995,12 @@ def fetch(after: str | None) -> dict: return result -ATTENTION_QUERY = """ +ATTENTION_QUERY = ( + """ query($owner: String!, $name: String!, $after: String) { repository(owner: $owner, name: $name) { defaultBranchRef { name } - develop: ref(qualifiedName: "refs/heads/develop") { name } + develop: ref(qualifiedName: "refs/heads/@INTEGRATION@") { name } pullRequests(states: OPEN, first: @PAGE@, after: $after, orderBy: {field: UPDATED_AT, direction: DESC}) { pageInfo { hasNextPage endCursor } @@ -1008,34 +1011,39 @@ def fetch(after: str | None) -> dict: isDraft updatedAt baseRefName + headRefOid author { login } - commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: @CHECK@) { + commits(last: 1) { nodes { commit { oid statusCheckRollup { contexts(first: @CHECK@) { pageInfo { hasNextPage } nodes { __typename - ... on CheckRun { name conclusion } - ... on StatusContext { context state } + ... on CheckRun { name status conclusion startedAt completedAt + checkSuite { databaseId status app { slug databaseId } + workflowRun { databaseId workflow { databaseId } } } } + ... on StatusContext { context state createdAt creator { login } } } } } } } } } } } } -""".replace("@PAGE@", str(PAGE_SIZE)).replace("@CHECK@", str(CHECK_CAP)) +""".replace("@PAGE@", str(PAGE_SIZE)) + .replace("@CHECK@", str(CHECK_CAP)) + .replace("@INTEGRATION@", INTEGRATION_BRANCH) +) -def failing_checks(pr: Mapping[str, Any]) -> tuple[list[str], bool]: - """The names of a pull request's failing checks, and whether its check list was cut.""" - commits = nodes_of(pr.get("commits")) - rollup = (commits[0].get("commit") or {}).get("statusCheckRollup") if commits else None - contexts = (rollup or {}).get("contexts") or {} - names = [] - for node in nodes_of(contexts): - if node.get("__typename") == "CheckRun" and node.get("conclusion") in FAILING_CHECKS: - names.append(str(node.get("name") or "")) - elif node.get("__typename") == "StatusContext" and node.get("state") in FAILED_STATES: - names.append(str(node.get("context") or "")) - return names, bool((contexts.get("pageInfo") or {}).get("hasNextPage")) +def failing_checks(pr: Mapping[str, Any]) -> list[str]: + """The names of a pull request's failing checks, read as the review gate reads them. + + `check_nodes` keeps the newest suite per workflow, so a workflow re-run on the same commit + counts by its latest run. A finished check a newer run is replacing is left out as well. + """ + return [ + str(node["name"]) + for node in check_nodes(dict(pr)) + if node["conclusion"] in FAILING_CHECKS | FAILED_STATES and not node.get("superseded") + ] def pr_attention(pr: Mapping[str, Any]) -> dict[str, Any]: @@ -1050,14 +1058,18 @@ def pr_attention(pr: Mapping[str, Any]) -> dict[str, Any]: def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[list, list]: """The workflows whose latest completed run on `branch` failed, and those that recovered. - `runs` is newest first, as `gh run list` prints it. A workflow recovered where a run failed in + `runs` is newest first, as `gh run list` prints it. A cancelled or skipped run decided nothing, + so it is never a workflow's latest. A pull request's run is left out, since a fork's branch + can share the name. A workflow recovered where a run failed in the window and its latest completed run did not. """ latest: dict[str, Mapping[str, Any]] = {} failed: dict[str, list[Mapping[str, Any]]] = {} for run in runs: workflow = str(run.get("workflowName") or run.get("name") or "") - if not run.get("conclusion"): + if not run.get("conclusion") or run["conclusion"] in UNDECIDED_RUNS: + continue + if run.get("event") in PR_EVENTS: continue latest.setdefault(workflow, run) if run["conclusion"] in FAILING_RUNS and str(run.get("createdAt") or "")[:10] >= str(since): @@ -1088,12 +1100,12 @@ def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[li def collect_attention( - owner: str, name: str, since: datetime.date, today: datetime.date, stale_days: int + owner: str, name: str, since: datetime.date, now: datetime.datetime, stale_days: int ) -> dict[str, Any]: """What needs the maintainer now in one repository: failing and stale pull requests, branches. - Open non-draft pull requests are read, up to `PR_CAP`. A stale one has had no update for - `stale_days` and has no failing check. The default branch and `develop`, where it exists, are + Open pull requests are read, up to `PR_CAP`, drafts counting toward it and in no list. A stale + one has had no update for `stale_days`, to the instant, and has no failing check. The default branch and `develop`, where it exists, are read for two kinds of workflow. One kind's latest completed run failed. The other kind failed in the window and recovered. """ @@ -1111,7 +1123,7 @@ def fetch(after: str | None) -> dict: "recovered_branches": [], "truncated": [], } - stale_before = window_start(today, stale_days).isoformat() + stale_before = now - datetime.timedelta(days=stale_days) branches: list[str] = [] seen = 0 for page in walked(fetch, ("repository", "pullRequests")): @@ -1125,14 +1137,16 @@ def fetch(after: str | None) -> dict: seen += 1 if pr.get("isDraft"): continue - names, cut = failing_checks(pr) - if cut: + names = failing_checks(pr) + if checks_truncated(dict(pr)): result["truncated"].append(f"checks of #{pr.get('number')} cut at {CHECK_CAP}") if names: result["failing_pull_requests"].append( {**pr_attention(pr), "failing_checks": names} ) - elif str(pr.get("updatedAt") or "")[:10] <= stale_before: + elif ( + updated := utc_instant(str(pr.get("updatedAt") or "")) + ) and updated <= stale_before: result["stale_pull_requests"].append( {**pr_attention(pr), "updated_at": str(pr.get("updatedAt") or "")} ) @@ -1144,7 +1158,7 @@ def fetch(after: str | None) -> dict: runs = run_gh( ["run", "list", "--repo", f"{owner}/{name}", "--branch", branch] + ["--limit", str(ATTENTION_RUN_LIMIT)] - + ["--json", "databaseId,workflowName,url,conclusion,createdAt"] + + ["--json", "databaseId,workflowName,url,conclusion,createdAt,event"] ) still, recovered = branch_attention(branch, runs, since) result["failing_branches"] += still @@ -1208,7 +1222,8 @@ def main(argv: Sequence[str] | None = None) -> int: default_owner, default_names = registry_defaults() owner = args.owner or default_owner names = args.repo or default_names - end = datetime.datetime.now(datetime.UTC).date() + now = datetime.datetime.now(datetime.UTC) + end = now.date() start = window_start(end, args.days) try: metrics = [collect(owner, name, start) for name in names] @@ -1225,7 +1240,7 @@ def main(argv: Sequence[str] | None = None) -> int: attention_error = "" if args.format == "json": try: - attention = {n: collect_attention(owner, n, start, end, args.stale_days) for n in names} + attention = {n: collect_attention(owner, n, start, now, args.stale_days) for n in names} metrics = [dataclasses.replace(m, attention=attention[m.name]) for m in metrics] except GhError as error: attention_error = str(error) diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index 6c30564d4..20cc4b570 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -1228,16 +1228,32 @@ def open_pr(number: int, *contexts: dict[str, object], **fields: object) -> dict "updatedAt": "2026-11-23T00:00:00Z", "baseRefName": "develop", "author": {"login": "dependabot"}, - "commits": {"nodes": [{"commit": {"statusCheckRollup": rollup}}]}, + "headRefOid": "h", + "commits": {"nodes": [{"commit": {"oid": "h", "statusCheckRollup": rollup}}]}, } | fields -def check(name: str, conclusion: str) -> dict[str, object]: - return {"__typename": "CheckRun", "name": name, "conclusion": conclusion} +def check(name: str, conclusion: str, suite: int | None = None) -> dict[str, object]: + node: dict[str, object] = { + "__typename": "CheckRun", + "name": name, + "status": "COMPLETED", + "conclusion": conclusion, + } + if suite is not None: + node["checkSuite"] = { + "databaseId": suite, + "status": "COMPLETED", + "workflowRun": {"databaseId": suite, "workflow": {"databaseId": 1}}, + } + return node -def run_record(workflow: str, conclusion: str, day: str, url: str) -> dict[str, object]: +def run_record( + workflow: str, conclusion: str, day: str, url: str, event: str = "push" +) -> dict[str, object]: return { + "event": event, "workflowName": workflow, "conclusion": conclusion, "createdAt": f"{day}T00:00:00Z", @@ -1247,7 +1263,7 @@ def run_record(workflow: str, conclusion: str, day: str, url: str) -> dict[str, class AttentionTests(unittest.TestCase): START = datetime.date(2026, 11, 17) - TODAY = datetime.date(2026, 11, 24) + NOW = datetime.datetime(2026, 11, 24, 8, 0, tzinfo=datetime.UTC) def attention( self, @@ -1268,14 +1284,19 @@ def fake(args: list[str]) -> object: ), unittest.mock.patch.object(bm, "run_gh", side_effect=fake), ): - return bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + return bm.collect_attention("o", "alpha", self.START, self.NOW, 7) def test_a_failing_check_or_status_names_the_pull_request(self) -> None: failing = open_pr( 1, check("compile", "FAILURE"), check("lint", "SUCCESS"), - {"__typename": "StatusContext", "context": "ci/legacy", "state": "ERROR"}, + { + "__typename": "StatusContext", + "context": "ci/legacy", + "state": "ERROR", + "createdAt": "2026-11-23T00:00:00Z", + }, ) result = self.attention([failing]) self.assertEqual( @@ -1306,15 +1327,67 @@ def test_a_draft_is_in_no_list(self) -> None: self.assertEqual((result["failing_pull_requests"], result["stale_pull_requests"]), ([], [])) def test_a_stale_pull_request_has_no_failing_check_and_a_failing_one_is_not_stale(self) -> None: - old = "2026-11-17T09:00:00Z" + old = "2026-11-17T08:00:00Z" stale = open_pr(1, check("x", "SUCCESS"), updatedAt=old) failing = open_pr(2, check("x", "FAILURE"), updatedAt=old) - fresh = open_pr(3, updatedAt="2026-11-18T00:00:00Z") + fresh = open_pr(3, updatedAt="2026-11-17T08:00:01Z") result = self.attention([stale, failing, fresh]) self.assertEqual([p["number"] for p in result["stale_pull_requests"]], [1]) # type: ignore[attr-defined] self.assertEqual(result["stale_pull_requests"][0]["updated_at"], old) # type: ignore[index] self.assertEqual([p["number"] for p in result["failing_pull_requests"]], [2]) # type: ignore[attr-defined] + def test_a_rerun_workflow_counts_by_its_newest_run(self) -> None: + rerun = open_pr( + 1, check("compile", "FAILURE", suite=10), check("compile", "SUCCESS", suite=11) + ) + self.assertEqual(self.attention([rerun])["failing_pull_requests"], []) + failed_again = open_pr( + 2, check("compile", "SUCCESS", suite=10), check("compile", "FAILURE", suite=11) + ) + self.assertEqual(len(self.attention([failed_again])["failing_pull_requests"]), 1) # type: ignore[arg-type] + + def test_a_cancelled_run_after_a_failure_is_neither_recovery_nor_latest(self) -> None: + runs = { + "main": [ + run_record("Build", "cancelled", "2026-11-23", "b2"), + run_record("Build", "failure", "2026-11-22", "b1"), + run_record("Fork", "failure", "2026-11-23", "f1", event="pull_request"), + ] + } + result = self.attention([], runs) + self.assertEqual([e["html_url"] for e in result["failing_branches"]], ["b1"]) # type: ignore[attr-defined] + self.assertEqual(result["recovered_branches"], []) + + def test_the_caps_are_named_where_reached(self) -> None: + prs = [open_pr(n) for n in range(1, bm.PR_CAP + 2)] + runs = { + "main": [run_record("Build", "success", "2026-11-23", "r")] * bm.ATTENTION_RUN_LIMIT + } + result = self.attention(prs, runs, more=True) + self.assertEqual( + result["truncated"], + [ + f"open pull requests cut at {bm.PR_CAP}", + f"runs of main cut at {bm.ATTENTION_RUN_LIMIT}", + ], + ) + + def test_stale_days_reaches_the_read(self) -> None: + seen: list[int] = [] + + def read(owner: str, name: str, since: object, now: object, stale_days: int) -> dict: + seen.append(stale_days) + return {} + + with ( + unittest.mock.patch.object(bm, "collect_attention", side_effect=read), + unittest.mock.patch.object(bm, "graphql", return_value=page([], False, 0)), + unittest.mock.patch.object(bm, "run_gh", side_effect=quiet_rest), + contextlib.redirect_stdout(io.StringIO()), + ): + bm.main(["--owner", "o", "--repo", "alpha", "--format", "json", "--stale-days", "3"]) + self.assertEqual(seen, [3]) + def test_a_cut_check_list_is_named(self) -> None: pr = open_pr(5, check("x", "SUCCESS")) pr["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["pageInfo"] = { # type: ignore[index] @@ -1382,7 +1455,7 @@ def test_only_the_default_branch_is_read_where_develop_is_absent(self) -> None: ), unittest.mock.patch.object(bm, "run_gh", return_value=[]) as run, ): - bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + bm.collect_attention("o", "alpha", self.START, self.NOW, 7) self.assertEqual( [c.args[0][c.args[0].index("--branch") + 1] for c in run.call_args_list], ["main"] ) @@ -1394,7 +1467,7 @@ def test_pull_request_pages_are_followed(self) -> None: unittest.mock.patch.object(bm, "graphql", side_effect=pages), unittest.mock.patch.object(bm, "run_gh", return_value=[]), ): - result = bm.collect_attention("o", "alpha", self.START, self.TODAY, 7) + result = bm.collect_attention("o", "alpha", self.START, self.NOW, 7) self.assertEqual([p["number"] for p in result["failing_pull_requests"]], [1, 2]) def test_a_failed_read_leaves_attention_null_and_exits_one(self) -> None: From b885fe3706bcda584fdda96395d434383e8c0983 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 19:57:36 -0800 Subject: [PATCH 3/6] Leave Copilot Review Runs Out of Branch Failures and Align the README With Opt-In Billing and the All-or-Nothing Attention Read Co-Authored-By: Claude Sonnet 5.5 --- scripts/README.md | 8 ++++---- scripts/backlog_metrics.py | 24 +++++++++++++----------- tests/test_backlog_metrics.py | 22 +++++++++++++++++++--- 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/scripts/README.md b/scripts/README.md index 2831dc64e..940dab752 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -355,7 +355,7 @@ It is a uv script, with the same inline metadata as `pr_review.py`. That lets it The table has a row per repository and a totals row. The columns are issues opened and closed in the window, handoff issues created, and issues open now. Next come pull requests merged, issues opened per merged pull request (`n/a` without a merge), and workflow runs. Last come runs named `Running Copilot Code Review` and those review runs per merged pull request (`n/a` without a merge). Every issue count except the handoff column leaves out issues labeled `handoff`. In the Markdown output each repository name links to its GitHub page. Each issue and pull request count links to the GitHub search listing what it counts. Each dated search runs from the window's first day through its last, and the open-now search lists what is open when it is opened. The workflow run counts print plain, since they come from `gh run list` rather than from a search. -A line per repository follows with its open issues by label, and an issue with several labels counts under each. The labels the script names print first, a zero included, and every other label an open issue carries follows them. An issue labeled `handoff` is left out here too. With `--billing`, the month's Actions minutes per repository and Copilot gross come from the user billing usage endpoint. They cover the calendar month to date rather than the window, so the report does not divide them by the window's merges. A failed call prints one line saying billing was unavailable rather than a zero. Without the flag, which is the default, the read is skipped and the report prints no billing line and no billing note. The endpoint needs the "Plan" user permission, which a fine-grained personal access token cannot be granted, so only a classic token reaches it. A list that reaches the item limit is noted in the report. A failed issue, pull request, or run call exits `1` with no report. +A line per repository follows with its open issues by label, and an issue with several labels counts under each. The labels the script names print first, a zero included, and every other label an open issue carries follows them. An issue labeled `handoff` is left out here too. With `--billing`, the month's Actions minutes per repository and Copilot gross come from the user billing usage endpoint. They cover the calendar month to date rather than the window, so the report does not divide them by the window's merges. A failed call prints one line saying billing was unavailable rather than a zero. Without the flag, which is the default, the read is skipped and the report prints no billing line and no billing note. The endpoint needs the "Plan" user permission, which a fine-grained personal access token cannot be granted, so only a classic token reaches it. A list that reaches the item limit is noted in the report. A failed issue, pull request, or run call in the backlog counts exits `1` with no report. Two more tables measure what the pull request bots return for what they cost. They let a move from automatic to requested review be judged before and after. They read the window's merged pull requests through one paged GraphQL search per repository, newest created first. A pull request that appears twice while paging is counted once and noted. The search stops at 500 pull requests per repository, and each pull request connection is capped as well. A cap that was reached is named in the report, so a truncated figure never reads as a whole one. The bot logins come from the gate's reviewer vocabularies. A promotion pull request, one from `develop` into the default branch, is left out and counted in its own column. It would otherwise dominate the commit and failing-head counts. @@ -369,7 +369,7 @@ Threaded findings are the review threads the bot opened. Qodo's findings listed The per-repository table lists commits per merged pull request. It lists the sum of local attestation findings, with `unknown` attestations counted apart. The gate's own readers decide what counts, `trusted_comments` and its attestation pattern. So a marker counts only from an owner, member or collaborator, in a comment that is not minimized. Its `base=` must match the pull request's base, and the marker must stand on a line of its own outside a code block. The first marker for a head is the one counted, as the gate reads it. The table also lists the failing heads and how many of those had a `findings=0` attestation on the same head. -The policy trigger is read once per repository from `.github/agent-policy.json` at the head of `develop`. The review gate reads a pull request's policy from its base, and feature pull requests merge there. A repository without `develop` falls back to its default branch, and the table names the branch read. The file is read through `pr_review_policy.py`'s `fetch`, as the review gate reads it. So a file the gate refuses prints `error` here as well. A file the gate takes as absent, or one stating no `review` section, prints the trigger from the hub's `spec/agent-policy.default.json`. That trigger is marked `(default)`, since the repository runs under it. The file's commit history on that branch is read for the window too. Where it changed inside the window, a note names the dates, because the window may then mix two review policies. The file holds other sections too, so a change there may leave the review policy as it was. A failed trigger read prints `error`. So does a failed read of the default branch or of whether `develop` exists, which also prints `n/a` as the branch. A failed history read prints its own note and leaves the trigger as read. Each still writes the report, names the failed read on stderr, and exits `1`. A failed review query leaves the two review tables out. The report still carries the backlog table and the billing lines. It adds one line saying the review figures were unavailable, with the error. It also names the error on stderr and exits `1`. A failed backlog read still exits `1` with no report. +The policy trigger is read once per repository from `.github/agent-policy.json` at the head of `develop`. The review gate reads a pull request's policy from its base, and feature pull requests merge there. A repository without `develop` falls back to its default branch, and the table names the branch read. The file is read through `pr_review_policy.py`'s `fetch`, as the review gate reads it. So a file the gate refuses prints `error` here as well. A file the gate takes as absent, or one stating no `review` section, prints the trigger from the hub's `spec/agent-policy.default.json`. That trigger is marked `(default)`, since the repository runs under it. The file's commit history on that branch is read for the window too. Where it changed inside the window, a note names the dates, because the window may then mix two review policies. The file holds other sections too, so a change there may leave the review policy as it was. A failed trigger read prints `error`. So does a failed read of the default branch or of whether `develop` exists, which also prints `n/a` as the branch. A failed history read prints its own note and leaves the trigger as read. Each still writes the report, names the failed read on stderr, and exits `1`. A failed review query leaves the two review tables out. The report still carries the backlog table, and the billing lines where `--billing` asked for them. It adds one line saying the review figures were unavailable, with the error. It also names the error on stderr and exits `1`. A failed backlog read still exits `1` with no report. `--format json` prints the same figures as one JSON document, for a consumer that renders its own report. A test pins this shape, since a downstream template depends on its field names. A change that renames or removes a field raises `schema`. Each `html_url` is that item's GitHub page. @@ -378,10 +378,10 @@ The policy trigger is read once per repository from `.github/agent-policy.json` - `billing` is `null` where the run skipped the billing read, which is the default and adds no note. With `--billing` it holds `month`, `error`, `actions_minutes` (repository name to minutes), and `copilot_gross_usd`. Where that read failed, `error` names the failure and the two figures are `null`, and otherwise `error` is `null`. - `notes` is the list of billing lines and notes the Markdown report prints after its label lines. Those label lines are each repository's `open_issues_by_label` here. - `repositories` holds one entry per repository, in the order read. Each carries `name`, `html_url`, and the same nine fields `totals` carries, counted for that repository. Next come `open_issues_by_label`, label name to count, and `truncated`, true where a list reached the item limit. `truncated_lists` names each list that reached it, from `issues_opened`, `issues_closed`, `issues_open`, `prs_merged`, and `workflow_runs`, and is empty where `truncated` is false. Then comes `attention`. -- Each repository's `attention` is read only for `--format json`, and is `null` where that read failed. A failed read adds one note, names the error on stderr, and exits `1`. Open pull requests are read newest-updated first, up to 500, drafts counting toward that cap and in no list. It holds these lists, each empty where nothing needs the maintainer: +- Each repository's `attention` is read only for `--format json`, and is `null` for every repository where that read failed. It reads all of them in one pass, so a failure in any one leaves every `attention` `null`. A failed read adds one note, names the error on stderr, and exits `1`. Open pull requests are read newest-updated first, up to 500, drafts counting toward that cap and in no list. It holds these lists, each empty where nothing needs the maintainer: - `failing_pull_requests`: open pull requests whose head has a check run concluded `FAILURE`, `TIMED_OUT`, `ACTION_REQUIRED`, or `STARTUP_FAILURE`, or a status context in `FAILURE` or `ERROR`. The checks are read as the review gate reads them. `CANCELLED` is left out. Each entry has `number`, `title`, `html_url`, `author`, `base_branch`, and `failing_checks`, the names of the failing checks. - `stale_pull_requests`: open pull requests with no update for `--stale-days` days, 7 by default, counted to the instant, and no failing check. Each entry has the same fields, with `updated_at` in place of `failing_checks`. - - `failing_branches`: for the default branch, and `develop` where it exists, each workflow whose latest completed run concluded `failure`, `timed_out`, or `startup_failure`. Each entry has `branch`, `workflow`, `conclusion`, the run's `html_url`, and `failed_runs_in_window`. The latest 200 runs of each branch are read. A cancelled or skipped run decides nothing. A pull request's run is left out, since a fork's branch can share the name. + - `failing_branches`: for the default branch, and `develop` where it exists, each workflow whose latest completed run concluded `failure`, `timed_out`, or `startup_failure`. Each entry has `branch`, `workflow`, `conclusion`, the run's `html_url`, and `failed_runs_in_window`. The latest 200 runs of each branch are read. A cancelled, skipped, or neutral run decides nothing. A pull request's run and a Copilot review run are left out, since both carry another branch's name. - `recovered_branches`: on those branches, each workflow that failed in the window while its latest completed run did not. Each entry has `branch`, `workflow`, `failed_runs_in_window`, and the `html_url` of its newest failed run. - `truncated`: strings naming a cap that was reached, such as a cut pull request list or run list. The open `decision` issues are already in `items.issues_open`. diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index 01f24229b..c0caa8343 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -37,8 +37,9 @@ Exit codes 0 the report was written. 1 a `gh` call for issues, pull requests, or runs failed, so no number is guessed and no report - is written. A failed review query still writes the backlog and billing report. It adds one - line saying the review figures were unavailable and names the error on stderr, then exits 1. + is written. A failed review query still writes the backlog report, with billing where asked for. + It adds one line saying the review figures were unavailable and names the error on stderr, + then exits 1. Four reads fail more softly: the default branch, whether `develop` exists, the policy file, and its history. A failed one still writes the report, names that read on stderr, and exits 1. Where the policy itself went unread, the report shows `error` in its place. A failed @@ -1058,18 +1059,19 @@ def pr_attention(pr: Mapping[str, Any]) -> dict[str, Any]: def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[list, list]: """The workflows whose latest completed run on `branch` failed, and those that recovered. - `runs` is newest first, as `gh run list` prints it. A cancelled or skipped run decided nothing, - so it is never a workflow's latest. A pull request's run is left out, since a fork's branch - can share the name. A workflow recovered where a run failed in - the window and its latest completed run did not. + `runs` is newest first, as `gh run list` prints it. A cancelled, skipped, or neutral run + decided nothing, so it is never a workflow's latest. A pull request's run is left out, since a + fork's branch can share the name. So is a Copilot review run, which carries the reviewed pull + request's head branch. A workflow recovered where a run failed in the window and its latest + completed run did not. """ latest: dict[str, Mapping[str, Any]] = {} failed: dict[str, list[Mapping[str, Any]]] = {} for run in runs: - workflow = str(run.get("workflowName") or run.get("name") or "") + workflow = str(run.get("workflowName") or "") if not run.get("conclusion") or run["conclusion"] in UNDECIDED_RUNS: continue - if run.get("event") in PR_EVENTS: + if run.get("event") in PR_EVENTS or workflow == REVIEW_WORKFLOW: continue latest.setdefault(workflow, run) if run["conclusion"] in FAILING_RUNS and str(run.get("createdAt") or "")[:10] >= str(since): @@ -1105,8 +1107,8 @@ def collect_attention( """What needs the maintainer now in one repository: failing and stale pull requests, branches. Open pull requests are read, up to `PR_CAP`, drafts counting toward it and in no list. A stale - one has had no update for `stale_days`, to the instant, and has no failing check. The default branch and `develop`, where it exists, are - read for two kinds of workflow. One kind's latest completed run failed. The other kind failed + one has had no update for `stale_days`, to the instant, and has no failing check. The default + branch and `develop`, where it exists, are read for two kinds of workflow. One kind's latest completed run failed. The other kind failed in the window and recovered. """ @@ -1158,7 +1160,7 @@ def fetch(after: str | None) -> dict: runs = run_gh( ["run", "list", "--repo", f"{owner}/{name}", "--branch", branch] + ["--limit", str(ATTENTION_RUN_LIMIT)] - + ["--json", "databaseId,workflowName,url,conclusion,createdAt,event"] + + ["--json", "workflowName,url,conclusion,createdAt,event"] ) still, recovered = branch_attention(branch, runs, since) result["failing_branches"] += still diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index 20cc4b570..8e6ed5f6d 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -1233,17 +1233,19 @@ def open_pr(number: int, *contexts: dict[str, object], **fields: object) -> dict } | fields -def check(name: str, conclusion: str, suite: int | None = None) -> dict[str, object]: +def check( + name: str, conclusion: str, suite: int | None = None, status: str = "COMPLETED" +) -> dict[str, object]: node: dict[str, object] = { "__typename": "CheckRun", "name": name, - "status": "COMPLETED", + "status": status, "conclusion": conclusion, } if suite is not None: node["checkSuite"] = { "databaseId": suite, - "status": "COMPLETED", + "status": status, "workflowRun": {"databaseId": suite, "workflow": {"databaseId": 1}}, } return node @@ -1346,6 +1348,20 @@ def test_a_rerun_workflow_counts_by_its_newest_run(self) -> None: ) self.assertEqual(len(self.attention([failed_again])["failing_pull_requests"]), 1) # type: ignore[arg-type] + def test_a_failure_of_a_workflow_with_a_newer_unfinished_run_is_superseded(self) -> None: + superseded = open_pr( + 1, + check("lint", "FAILURE", suite=10), + check("compile", "", suite=11, status="IN_PROGRESS"), + ) + self.assertEqual(self.attention([superseded])["failing_pull_requests"], []) + + def test_a_copilot_review_run_is_not_a_branch_failure(self) -> None: + runs = { + "develop": [run_record(bm.REVIEW_WORKFLOW, "failure", "2026-11-23", "c", "dynamic")] + } + self.assertEqual(self.attention([], runs)["failing_branches"], []) + def test_a_cancelled_run_after_a_failure_is_neither_recovery_nor_latest(self) -> None: runs = { "main": [ From 0e949d216bba2e999097e47b01eb2978e569e8d8 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 20:21:04 -0800 Subject: [PATCH 4/6] Read the Head's Check Suites, Key Branch Workflows by Id, and Reuse the Gate's Checks Window in the Attention Read Co-Authored-By: Claude Sonnet 5.5 --- scripts/backlog_metrics.py | 57 ++++++++++++++++++++--------------- tests/test_backlog_metrics.py | 15 ++++++++- 2 files changed, 46 insertions(+), 26 deletions(-) diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index c0caa8343..b216c7603 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -37,9 +37,9 @@ Exit codes 0 the report was written. 1 a `gh` call for issues, pull requests, or runs failed, so no number is guessed and no report - is written. A failed review query still writes the backlog report, with billing where asked for. - It adds one line saying the review figures were unavailable and names the error on stderr, - then exits 1. + is written. A failed review query still writes the backlog report, with billing where asked + for. It adds one line saying the review figures were unavailable and names the error on + stderr, then exits 1. Four reads fail more softly: the default branch, whether `develop` exists, the policy file, and its history. A failed one still writes the report, names that read on stderr, and exits 1. Where the policy itself went unread, the report shows `error` in its place. A failed @@ -65,7 +65,7 @@ import pr_review_rounds as rounds import pr_review_side as side from gh_graphql import GraphQLError, request, run_subprocess, said_absent, walk -from pr_review_checks import check_nodes, checks_truncated, utc_instant +from pr_review_checks import CHECKS_WINDOW, check_nodes, checks_truncated, utc_instant from pr_review_copilot import VOCABULARIES from pr_review_policy import BOTS, COMMANDS, POLICY_PATH, PolicyError, fetch @@ -98,7 +98,6 @@ UNDECIDED_RUNS = frozenset({"cancelled", "skipped", "neutral"}) PR_EVENTS = frozenset({"pull_request", "pull_request_target"}) ATTENTION_RUN_LIMIT = 200 -CHECK_CAP = 100 LABELS = ("pre-existing", "prose", "documentation", "bug", "script", "enhancement", "decision") Items = Sequence[Mapping[str, Any]] @@ -1014,22 +1013,27 @@ def fetch(after: str | None) -> dict: baseRefName headRefOid author { login } - commits(last: 1) { nodes { commit { oid statusCheckRollup { contexts(first: @CHECK@) { - pageInfo { hasNextPage } - nodes { - __typename - ... on CheckRun { name status conclusion startedAt completedAt - checkSuite { databaseId status app { slug databaseId } - workflowRun { databaseId workflow { databaseId } } } } - ... on StatusContext { context state createdAt creator { login } } - } - } } } } } + commits(last: 1) { nodes { commit { + oid + statusCheckRollup { contexts(first: @CHECK@) { + pageInfo { hasNextPage } + nodes { + __typename + ... on CheckRun { name status conclusion startedAt completedAt + checkSuite { databaseId status app { slug databaseId } + workflowRun { databaseId workflow { databaseId } } } } + ... on StatusContext { context state createdAt creator { login } } + } + } } + checkSuites(last: 50) { nodes { databaseId status createdAt app { slug } + workflowRun { databaseId workflow { databaseId } } } } + } } } } } } } """.replace("@PAGE@", str(PAGE_SIZE)) - .replace("@CHECK@", str(CHECK_CAP)) + .replace("@CHECK@", str(CHECKS_WINDOW)) .replace("@INTEGRATION@", INTEGRATION_BRANCH) ) @@ -1061,7 +1065,8 @@ def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[li `runs` is newest first, as `gh run list` prints it. A cancelled, skipped, or neutral run decided nothing, so it is never a workflow's latest. A pull request's run is left out, since a - fork's branch can share the name. So is a Copilot review run, which carries the reviewed pull + fork's branch can share the name. A workflow is keyed by its database id, since two workflow + files can share a display name. So is a Copilot review run, which carries the reviewed pull request's head branch. A workflow recovered where a run failed in the window and its latest completed run did not. """ @@ -1069,16 +1074,18 @@ def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[li failed: dict[str, list[Mapping[str, Any]]] = {} for run in runs: workflow = str(run.get("workflowName") or "") + key = str(run.get("workflowDatabaseId") or workflow) if not run.get("conclusion") or run["conclusion"] in UNDECIDED_RUNS: continue if run.get("event") in PR_EVENTS or workflow == REVIEW_WORKFLOW: continue - latest.setdefault(workflow, run) + latest.setdefault(key, run) if run["conclusion"] in FAILING_RUNS and str(run.get("createdAt") or "")[:10] >= str(since): - failed.setdefault(workflow, []).append(run) + failed.setdefault(key, []).append(run) still, recovered = [], [] - for workflow, run in latest.items(): - in_window = failed.get(workflow, []) + for key, run in latest.items(): + workflow = str(run.get("workflowName") or "") + in_window = failed.get(key, []) if run["conclusion"] in FAILING_RUNS: still.append( { @@ -1108,8 +1115,8 @@ def collect_attention( Open pull requests are read, up to `PR_CAP`, drafts counting toward it and in no list. A stale one has had no update for `stale_days`, to the instant, and has no failing check. The default - branch and `develop`, where it exists, are read for two kinds of workflow. One kind's latest completed run failed. The other kind failed - in the window and recovered. + branch and `develop`, where it exists, are read for two kinds of workflow. One kind's latest + completed run failed. The other kind failed in the window and recovered. """ def fetch(after: str | None) -> dict: @@ -1141,7 +1148,7 @@ def fetch(after: str | None) -> dict: continue names = failing_checks(pr) if checks_truncated(dict(pr)): - result["truncated"].append(f"checks of #{pr.get('number')} cut at {CHECK_CAP}") + result["truncated"].append(f"checks of #{pr.get('number')} cut at {CHECKS_WINDOW}") if names: result["failing_pull_requests"].append( {**pr_attention(pr), "failing_checks": names} @@ -1160,7 +1167,7 @@ def fetch(after: str | None) -> dict: runs = run_gh( ["run", "list", "--repo", f"{owner}/{name}", "--branch", branch] + ["--limit", str(ATTENTION_RUN_LIMIT)] - + ["--json", "workflowName,url,conclusion,createdAt,event"] + + ["--json", "workflowName,workflowDatabaseId,url,conclusion,createdAt,event"] ) still, recovered = branch_attention(branch, runs, since) result["failing_branches"] += still diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index 8e6ed5f6d..2af643f5e 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -1356,6 +1356,17 @@ def test_a_failure_of_a_workflow_with_a_newer_unfinished_run_is_superseded(self) ) self.assertEqual(self.attention([superseded])["failing_pull_requests"], []) + def test_two_workflows_sharing_a_name_are_told_apart_by_id(self) -> None: + failing = {**run_record("CI", "failure", "2026-11-22", "a"), "workflowDatabaseId": 1} + passing = {**run_record("CI", "success", "2026-11-23", "b"), "workflowDatabaseId": 2} + result = self.attention([], {"main": [passing, failing]}) + self.assertEqual([e["html_url"] for e in result["failing_branches"]], ["a"]) # type: ignore[attr-defined] + self.assertEqual(result["recovered_branches"], []) + + def test_the_query_reads_the_head_check_suites_the_gate_reads(self) -> None: + self.assertIn("checkSuites(last: 50)", bm.ATTENTION_QUERY) + self.assertIn(f"contexts(first: {bm.CHECKS_WINDOW})", bm.ATTENTION_QUERY) + def test_a_copilot_review_run_is_not_a_branch_failure(self) -> None: runs = { "develop": [run_record(bm.REVIEW_WORKFLOW, "failure", "2026-11-23", "c", "dynamic")] @@ -1409,7 +1420,9 @@ def test_a_cut_check_list_is_named(self) -> None: pr["commits"]["nodes"][0]["commit"]["statusCheckRollup"]["contexts"]["pageInfo"] = { # type: ignore[index] "hasNextPage": True } - self.assertEqual(self.attention([pr])["truncated"], [f"checks of #5 cut at {bm.CHECK_CAP}"]) + self.assertEqual( + self.attention([pr])["truncated"], [f"checks of #5 cut at {bm.CHECKS_WINDOW}"] + ) def test_a_failing_latest_run_names_the_workflow_and_a_recovered_one_is_apart(self) -> None: runs = { From db41b412e4389a9f8e536a3d361b2678dcd86fde Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 20:25:25 -0800 Subject: [PATCH 5/6] Key Branch Workflows by Id Alone in the Attention Read Co-Authored-By: Claude Sonnet 5.5 --- scripts/backlog_metrics.py | 8 ++++---- tests/test_backlog_metrics.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index b216c7603..38843b577 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -1065,16 +1065,16 @@ def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[li `runs` is newest first, as `gh run list` prints it. A cancelled, skipped, or neutral run decided nothing, so it is never a workflow's latest. A pull request's run is left out, since a - fork's branch can share the name. A workflow is keyed by its database id, since two workflow - files can share a display name. So is a Copilot review run, which carries the reviewed pull - request's head branch. A workflow recovered where a run failed in the window and its latest + fork's branch can share the name. So is a Copilot review run, which carries the reviewed pull + request's head branch. A workflow is keyed by its database id, since two workflow files can + share a display name. A workflow recovered where a run failed in the window and its latest completed run did not. """ latest: dict[str, Mapping[str, Any]] = {} failed: dict[str, list[Mapping[str, Any]]] = {} for run in runs: workflow = str(run.get("workflowName") or "") - key = str(run.get("workflowDatabaseId") or workflow) + key = str(run.get("workflowDatabaseId")) if not run.get("conclusion") or run["conclusion"] in UNDECIDED_RUNS: continue if run.get("event") in PR_EVENTS or workflow == REVIEW_WORKFLOW: diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index 2af643f5e..cea6d5c51 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -1256,6 +1256,7 @@ def run_record( ) -> dict[str, object]: return { "event": event, + "workflowDatabaseId": sum(map(ord, workflow)), "workflowName": workflow, "conclusion": conclusion, "createdAt": f"{day}T00:00:00Z", From 07811cf8ac2198ee096d9fff4d25e6977b837d6d Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 23 Nov 2026 20:28:40 -0800 Subject: [PATCH 6/6] Match the Copilot Review Run by Its Run Name Too in the Attention Read Co-Authored-By: Claude Sonnet 5.5 --- scripts/backlog_metrics.py | 4 ++-- tests/test_backlog_metrics.py | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/backlog_metrics.py b/scripts/backlog_metrics.py index 38843b577..36acffcd7 100755 --- a/scripts/backlog_metrics.py +++ b/scripts/backlog_metrics.py @@ -1077,7 +1077,7 @@ def branch_attention(branch: str, runs: Items, since: datetime.date) -> tuple[li key = str(run.get("workflowDatabaseId")) if not run.get("conclusion") or run["conclusion"] in UNDECIDED_RUNS: continue - if run.get("event") in PR_EVENTS or workflow == REVIEW_WORKFLOW: + if run.get("event") in PR_EVENTS or REVIEW_WORKFLOW in (workflow, run.get("name")): continue latest.setdefault(key, run) if run["conclusion"] in FAILING_RUNS and str(run.get("createdAt") or "")[:10] >= str(since): @@ -1167,7 +1167,7 @@ def fetch(after: str | None) -> dict: runs = run_gh( ["run", "list", "--repo", f"{owner}/{name}", "--branch", branch] + ["--limit", str(ATTENTION_RUN_LIMIT)] - + ["--json", "workflowName,workflowDatabaseId,url,conclusion,createdAt,event"] + + ["--json", "name,workflowName,workflowDatabaseId,url,conclusion,createdAt,event"] ) still, recovered = branch_attention(branch, runs, since) result["failing_branches"] += still diff --git a/tests/test_backlog_metrics.py b/tests/test_backlog_metrics.py index cea6d5c51..8ad8870fa 100755 --- a/tests/test_backlog_metrics.py +++ b/tests/test_backlog_metrics.py @@ -1374,6 +1374,11 @@ def test_a_copilot_review_run_is_not_a_branch_failure(self) -> None: } self.assertEqual(self.attention([], runs)["failing_branches"], []) + def test_a_review_run_named_by_its_run_name_is_not_a_branch_failure(self) -> None: + review = {**run_record("dynamic/copilot", "failure", "2026-11-23", "c", "dynamic")} + review["name"] = bm.REVIEW_WORKFLOW + self.assertEqual(self.attention([], {"develop": [review]})["failing_branches"], []) + def test_a_cancelled_run_after_a_failure_is_neither_recovery_nor_latest(self) -> None: runs = { "main": [