From 56a63ef5252d784cfd8dc86b7f9a07b7cb7d40e9 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 21 Oct 2026 11:31:11 +0100 Subject: [PATCH] fix(ci_timing): treat PR runs cancelled by their PR closing as abandoned A cancelled pull_request run with no successor was a kill suspect even when its PR had just been closed unmerged: GitHub empties the run's pull_requests once the PR closes, so the collector could not see the closure. ci_timing.sh now also fetches one page of recently closed PRs per repo (head ref + closed_at) and passes it as --closed-prs; a failed or empty fetch degrades to the superseded-only behaviour. classify_cancelled returns "abandoned" for a non-superseded pull_request cancel (not on main) when a same-head-branch PR closed between the run's created_at and updated_at + SUPERSEDE_SLACK_S. Abandoned is benign: counted in a new per-gate "abandoned" key (sidecar + rollup), no event. Push/main cancels never use the rule; thresholds, weights and slack are unchanged. Fixes #314 Co-Authored-By: Claude Opus 5.5 --- heart/checks/ci_timing.py | 98 ++++++++++++++++++++-- heart/checks/ci_timing.sh | 30 ++++++- tests/test_ci_timing.py | 149 +++++++++++++++++++++++++++++++++ tests/test_ci_timing_script.py | 89 ++++++++++++++++++++ 4 files changed, 356 insertions(+), 10 deletions(-) create mode 100644 tests/test_ci_timing_script.py diff --git a/heart/checks/ci_timing.py b/heart/checks/ci_timing.py index 1aef9a1a..29c943b9 100644 --- a/heart/checks/ci_timing.py +++ b/heart/checks/ci_timing.py @@ -40,6 +40,14 @@ ``cancelled`` run with no such successor is a kill/hang suspect and becomes an *event* (``pull_request`` runs also keep the older, looser "any newer run on the PR branch" test). ``timed_out`` is always an event. +* **A PR cancelled because its PR closed is ``abandoned``, not a suspect.** + Closing a PR cancels its in-flight runs with no successor at all, and GitHub + empties the run's ``pull_requests`` once the PR is closed, so the closure is + read from the repo's recently closed PRs (``--closed-prs``). A cancelled + ``pull_request`` run that was not superseded is abandoned when a PR on the + same head branch closed between the run's creation and its end + (``updated_at`` + ``SUPERSEDE_SLACK_S``). Push/``main`` cancels never use + this rule, and with no closed-PR feed it simply does not fire. * **Drift needs BOTH gates.** A gate is flagged ``warn`` only when today's median is ≥ ``yellow_factor`` × its recent history *and* ≥ ``min_delta_s`` above it in absolute terms — the profiling conductor's doctrine. The ratio @@ -73,6 +81,7 @@ "conclusions": {"success": 14, "failure": 1, "cancelled": 3, "timed_out": 0}, "superseded": 2, # of those `cancelled`, benign ones + "abandoned": 1, # cancelled because their PR closed "actions_url": "https://github.com/OwnerX/RepoA/actions" } }, @@ -104,8 +113,9 @@ CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" # Conclusions whose *count* is recorded per workflow. `cancelled` is recorded -# raw (superseded PR runs included) with the benign share reported separately -# as `superseded`, so the mix always adds up to what the API actually said. +# raw (superseded and abandoned PR runs included) with the benign shares +# reported separately as `superseded` and `abandoned`, so the mix always adds +# up to what the API actually said. TRACKED_CONCLUSIONS = ("success", "failure", "cancelled", "timed_out") # How long after a cancelled run's recorded end (``updated_at``) its successor @@ -246,8 +256,44 @@ def queue_s(run: dict[str, Any]) -> float | None: return round(max(0.0, (started - created).total_seconds()), 1) -def classify_cancelled(run: dict[str, Any], siblings: list[dict[str, Any]]) -> str: - """``"superseded"`` (benign) or ``"suspect"`` (a kill/hang candidate). +def normalize_closed_prs(payload: Any) -> list[dict[str, str]]: + """Coerce a closed-PR feed into ``[{"head_ref", "closed_at"}]``. + + Accepts the slim list ``ci_timing.sh`` writes (``head_ref``/``closed_at``) + and the raw REST ``/pulls`` shape (``head.ref``). Anything unusable — no + feed, a fetch error, garbage — degrades to ``[]``, which disables the + abandoned rule rather than failing the check. + """ + if not isinstance(payload, list): + return [] + out: list[dict[str, str]] = [] + for pr in payload: + if not isinstance(pr, dict): + continue + head = pr.get("head") if isinstance(pr.get("head"), dict) else {} + ref = str(pr.get("head_ref") or head.get("ref") or "") + closed = str(pr.get("closed_at") or "") + if ref and closed: + out.append({"head_ref": ref, "closed_at": closed}) + return out + + +def read_closed_prs(path: str | Path | None) -> list[dict[str, str]]: + """The closed-PR feed at ``path``, or ``[]`` on any problem (I/O).""" + if not path: + return [] + try: + return normalize_closed_prs(json.loads(Path(path).read_text())) + except (OSError, ValueError): + return [] + + +def classify_cancelled( + run: dict[str, Any], + siblings: list[dict[str, Any]], + closed_prs: list[dict[str, str]] | None = None, +) -> str: + """``"superseded"`` / ``"abandoned"`` (benign) or ``"suspect"``. A workflow's concurrency group cancels the in-flight run when a newer run of the same workflow on the same ``head_branch`` arrives — on ``main`` @@ -259,6 +305,15 @@ def classify_cancelled(run: dict[str, Any], siblings: list[dict[str, Any]]) -> s handling is no looser and no stricter than before. Anything else — no successor at all, or one created long after the run had already ended — is nobody's design: a kill-timer or hang suspect, and an event. + + The one exception is a closed PR. Closing a PR cancels its in-flight + ``pull_request`` runs (not on ``main``) with no successor, so such a run + is ``"abandoned"`` when ``closed_prs`` holds a PR on the same head branch + whose ``closed_at`` lies in [run ``created_at``, ``updated_at`` + + ``SUPERSEDE_SLACK_S``]. The lower bound stops an older PR on a reused + branch name from matching; the upper bound keeps a PR that stayed open + past the cancel, or closed long after, a suspect. Supersession is checked + first, so a run that was both superseded and later abandoned counts once. """ branch = run.get("head_branch") workflow = run.get("workflow") @@ -281,6 +336,13 @@ def classify_cancelled(run: dict[str, Any], siblings: list[dict[str, Any]]) -> s if (mine_dt is not None and theirs_dt is not None and deadline is not None and mine_dt < theirs_dt <= deadline): return "superseded" + if legacy_pr and mine_dt is not None and deadline is not None: + for pr in closed_prs or []: + if pr.get("head_ref") != branch: + continue + closed_dt = _parse_iso(pr.get("closed_at")) + if closed_dt is not None and mine_dt <= closed_dt <= deadline: + return "abandoned" return "suspect" @@ -308,13 +370,16 @@ def _median(values: list[float]) -> float | None: def time_workflow( - repo: str, workflow: str, runs: list[dict[str, Any]], actions_url: str + repo: str, workflow: str, runs: list[dict[str, Any]], actions_url: str, + closed_prs: list[dict[str, str]] | None = None, ) -> tuple[dict[str, Any], list[dict[str, Any]]]: """Time one workflow's runs → (entry, events). Only *completed* runs with a usable ``run_started_at`` participate: an in-flight run has no duration, and a run with no start stamp cannot be - timed honestly. + timed honestly. ``closed_prs`` (the repo's recently closed PRs) lets a + PR run cancelled by its PR's closure count as ``abandoned`` rather than + become an event; ``None``/``[]`` keeps the superseded-only behaviour. """ mine = [ r for r in runs @@ -329,6 +394,7 @@ def time_workflow( queues: list[float] = [] conclusions = {k: 0 for k in TRACKED_CONCLUSIONS} superseded = 0 + abandoned = 0 events: list[dict[str, Any]] = [] window_from = "" @@ -355,8 +421,11 @@ def time_workflow( if concl == "timed_out": kind = "timed_out" elif concl == "cancelled": - if classify_cancelled(run, siblings) == "superseded": + verdict = classify_cancelled(run, siblings, closed_prs) + if verdict == "superseded": superseded += 1 + elif verdict == "abandoned": + abandoned += 1 else: kind = "suspect_cancelled" if kind: @@ -380,6 +449,7 @@ def time_workflow( "window_from": window_from, "conclusions": conclusions, "superseded": superseded, + "abandoned": abandoned, "actions_url": actions_url, } return entry, events @@ -393,11 +463,14 @@ def build_sidecar( ts: str, config_path: Path | str = CONFIG_PATH, error: str = "", + closed_prs: Any = None, ) -> dict[str, Any]: """Construct one repo's ci_timing sidecar. ``error`` is the reason the runs fetch failed. When set the sidecar carries NO workflows and NO events: a dead query must never render as a quiet repo. + ``closed_prs`` is the repo's recently closed PRs (see + ``normalize_closed_prs``); missing or unusable means no abandoned rule. """ actions_url = f"https://github.com/{owner}/{name}/actions" if owner else "" if error: @@ -407,10 +480,11 @@ def build_sidecar( } normalized = normalize_runs(runs) + closed = normalize_closed_prs(closed_prs) workflows: dict[str, Any] = {} events: list[dict[str, Any]] = [] for workflow in tracked_workflows(name, group, config_path): - entry, evts = time_workflow(name, workflow, normalized, actions_url) + entry, evts = time_workflow(name, workflow, normalized, actions_url, closed) # A workflow with no completed runs in the window is not evidence of # anything; recording it as a zero-run gate keeps the board honest # about coverage rather than dropping it silently. @@ -568,6 +642,7 @@ def aggregate( "window_from": entry.get("window_from", ""), "conclusions": entry.get("conclusions") or {}, "superseded": entry.get("superseded", 0), + "abandoned": entry.get("abandoned", 0), "actions_url": actions_url, "baseline_s": baseline, "ratio": ratio, @@ -687,6 +762,10 @@ def main(argv: list[str] | None = None) -> int: "previous board.json only the fallback") ap.add_argument("--fetch-error", default="", help="reason the runs fetch failed; recorded instead of a bogus quiet repo") + ap.add_argument("--closed-prs", default="", + help="JSON list of the repo's recently closed PRs (head_ref, " + "closed_at); missing/unreadable => no abandoned rule, " + "never an error") ns = ap.parse_args(argv) ts = ns.ts or datetime.datetime.now(datetime.timezone.utc).isoformat() @@ -729,7 +808,8 @@ def main(argv: list[str] | None = None) -> int: runs = [] error = error or "runs payload was not valid JSON" - sidecar = build_sidecar(ns.name, ns.group, ns.owner, runs, ts, error=error) + sidecar = build_sidecar(ns.name, ns.group, ns.owner, runs, ts, error=error, + closed_prs=read_closed_prs(ns.closed_prs)) _write(Path(ns.out), sidecar) print(repo_summary_line(sidecar)) return 0 diff --git a/heart/checks/ci_timing.sh b/heart/checks/ci_timing.sh index 0ae71c8a..b6c879ae 100644 --- a/heart/checks/ci_timing.sh +++ b/heart/checks/ci_timing.sh @@ -22,6 +22,12 @@ # render. HEART_PREV_BOARD_URL overrides the URL (tests, staging boards); any # fetch failure degrades to "no history", never to an error. # +# A second, best-effort call per repo fetches the recently CLOSED pull requests +# (head ref + closed_at only): GitHub empties a run's `pull_requests` once its +# PR closes, so this is the only way to tell a PR run cancelled by its PR's +# closure ("abandoned", benign) from a kill. Its failure degrades to the +# superseded-only classification, never to an error or a fetch_error. +# # Observer boundary: everything written lives under $HEART_STATE_DIR. A repo # whose runs fetch fails records the reason and NO workflows — "we could not # ask" must never render as "all quiet". @@ -31,6 +37,22 @@ source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh" # Recent runs, newest first, every branch and every event. _CI_TIMING_RUNS_PATH="actions/runs?per_page=50" +# Recently closed PRs, newest-updated first; one page covers the runs window. +_CI_TIMING_CLOSED_PRS_PATH="pulls?state=closed&per_page=50" +_CI_TIMING_CLOSED_PRS_JQ='[.[] | {head_ref: .head.ref, closed_at: .closed_at}]' + +# Print the path of a tempfile holding the repo's slim closed-PR list, or +# nothing when it cannot be had. Never fails the check. +_ci_timing_closed_prs() { + local owner_name="$1" tmp + tmp="$(mktemp)" + if gh api "repos/$owner_name/$_CI_TIMING_CLOSED_PRS_PATH" \ + --jq "$_CI_TIMING_CLOSED_PRS_JQ" >"$tmp" 2>/dev/null && [[ -s "$tmp" ]]; then + printf '%s' "$tmp" + else + rm -f "$tmp" + fi +} time_one_repo_ci() { local owner_name="$1" @@ -53,10 +75,16 @@ time_one_repo_ci() { fi rm -f "$err" + local closed_prs="" + [[ -z "$fetch_error" ]] && closed_prs="$(_ci_timing_closed_prs "$owner_name")" + printf '%s' "$runs" | PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_timing \ --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ - --fetch-error "$fetch_error" \ + --fetch-error "$fetch_error" --closed-prs "$closed_prs" \ --out "$HEART_PER_REPO_DIR/$name.ci_timing.json" + rc=$? + [[ -n "$closed_prs" ]] && rm -f "$closed_prs" + return $rc } # Print the path of a tempfile holding the previously published board.json, or diff --git a/tests/test_ci_timing.py b/tests/test_ci_timing.py index 943c39f2..700727cb 100644 --- a/tests/test_ci_timing.py +++ b/tests/test_ci_timing.py @@ -678,3 +678,152 @@ def test_main_aggregate_compares_only_inside_the_current_epoch(tmp_path, # ...and the pre-boundary day is not in the rolled-forward history either. assert [h["date"] for h in roll["history"]] == ["2026-09-05", "2026-09-06"] capsys.readouterr() + + +# --- a PR run cancelled because its PR closed is `abandoned`, not a suspect --- +# +# Closing a PR cancels its in-flight runs with no successor, and GitHub empties +# a run's `pull_requests` once the PR is closed, so closure comes from the +# repo's closed-PR feed (`--closed-prs`). + +def _closed(branch, closed_at): + return {"head_ref": branch, "closed_at": closed_at} + + +def _abandoned_payload(): + """Modelled on two workspace-test smoke PR runs, 2026-09-19: each was + cancelled ~20 s after its PR closed unmerged, with no successor run.""" + return {"workflow_runs": [ + _run("Gate One", "cancelled", event="pull_request", branch="feat/regroup", + created="2026-09-19T10:59:28Z", started="2026-09-19T10:59:30Z", + updated="2026-09-19T11:06:13Z", url="https://github.invalid/run/a"), + _run("Gate Two", "cancelled", event="pull_request", branch="feat/regroup", + created="2026-09-19T10:59:26Z", started="2026-09-19T10:59:28Z", + updated="2026-09-19T11:06:08Z", url="https://github.invalid/run/b"), + ]} + + +def test_pr_runs_cancelled_by_their_pr_closing_are_abandoned(tmp_path): + closed = [_closed("feat/regroup", "2026-09-19T11:05:51Z")] + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), "T", + config_path=_cfg(tmp_path), closed_prs=closed) + assert side["events"] == [] + for workflow in ("Gate One", "Gate Two"): + entry = side["workflows"][workflow] + assert entry["abandoned"] == 1 + assert entry["superseded"] == 0 + assert entry["conclusions"]["cancelled"] == 1 + + +def test_the_raw_rest_pulls_shape_is_accepted_too(tmp_path): + closed = [{"head": {"ref": "feat/regroup"}, "closed_at": "2026-09-19T11:05:47Z"}] + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), "T", + config_path=_cfg(tmp_path), closed_prs=closed) + assert side["events"] == [] + + +def test_pr_cancel_with_its_pr_still_open_stays_suspect(tmp_path): + """No closure in the feed (the PR is open): nobody's design, an event.""" + closed = [_closed("feat/other", "2026-09-19T11:05:51Z")] + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), "T", + config_path=_cfg(tmp_path), closed_prs=closed) + assert [e["kind"] for e in side["events"]] == ["suspect_cancelled"] * 2 + assert side["workflows"]["Gate One"]["abandoned"] == 0 + + +def test_pr_closed_ten_minutes_after_the_cancel_stays_suspect(tmp_path): + closed = [_closed("feat/regroup", "2026-09-19T11:16:13Z")] + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), "T", + config_path=_cfg(tmp_path), closed_prs=closed) + assert len(side["events"]) == 2 + assert side["workflows"]["Gate One"]["abandoned"] == 0 + + +def test_a_closure_from_before_the_run_was_created_does_not_count(tmp_path): + """An older PR on a reused branch name cannot have cancelled a later run.""" + closed = [_closed("feat/regroup", "2026-09-19T10:00:00Z")] + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), "T", + config_path=_cfg(tmp_path), closed_prs=closed) + assert len(side["events"]) == 2 + + +def test_closure_within_the_slack_after_the_end_counts_and_beyond_does_not(): + run = ct.normalize_runs([_run( + "Gate One", "cancelled", event="pull_request", branch="feat/x", + created="2026-10-17T20:00:00Z", updated="2026-10-17T20:01:00Z")])[0] + end = datetime.datetime(2026, 10, 17, 20, 1, tzinfo=datetime.timezone.utc) + inside = (end + datetime.timedelta(seconds=ct.SUPERSEDE_SLACK_S) + ).isoformat().replace("+00:00", "Z") + outside = (end + datetime.timedelta(seconds=ct.SUPERSEDE_SLACK_S + 1) + ).isoformat().replace("+00:00", "Z") + assert ct.classify_cancelled(run, [run], [_closed("feat/x", inside)]) == "abandoned" + assert ct.classify_cancelled(run, [run], [_closed("feat/x", outside)]) == "suspect" + + +def test_missing_or_empty_closed_pr_feed_keeps_todays_behaviour(tmp_path): + for feed in (None, [], {}, "garbage", [None, {"head_ref": "feat/regroup"}]): + side = ct.build_sidecar(REPO, "workspaces", "OwnerX", _abandoned_payload(), + "T", config_path=_cfg(tmp_path), closed_prs=feed) + assert [e["kind"] for e in side["events"]] == ["suspect_cancelled"] * 2 + assert side["workflows"]["Gate One"]["abandoned"] == 0 + + +def test_main_push_cancel_never_uses_the_abandoned_rule(tmp_path): + payload = {"workflow_runs": [ + _run("Gate One", "cancelled", event="push", branch="main", + created="2026-09-19T10:59:28Z", started="2026-09-19T10:59:30Z", + updated="2026-09-19T11:06:13Z"), + ]} + closed = [_closed("main", "2026-09-19T11:05:51Z")] + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path), closed_prs=closed) + (event,) = side["events"] + assert event["kind"] == "suspect_cancelled" + assert side["workflows"]["Gate One"]["abandoned"] == 0 + + +def test_superseded_wins_over_abandoned(): + """A run with both a successor and a later closure counts once, as superseded.""" + run, successor = ct.normalize_runs([ + _run("Gate One", "cancelled", event="pull_request", branch="feat/x", + created="2026-10-17T20:00:00Z", updated="2026-10-17T20:01:00Z"), + _run("Gate One", "success", event="pull_request", branch="feat/x", + created="2026-10-17T20:00:59Z"), + ]) + assert ct.classify_cancelled( + run, [run, successor], [_closed("feat/x", "2026-10-17T20:00:30Z")] + ) == "superseded" + + +def test_aggregate_carries_the_abandoned_count(): + side = _sidecar(600.0) + side["workflows"]["Gate One"]["abandoned"] = 2 + roll = ct.aggregate([side], {}, "2026-08-24", "T", ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert roll["gates"][0]["abandoned"] == 2 + # an older sidecar without the key reads as zero + roll = ct.aggregate([_sidecar(600.0)], {}, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert roll["gates"][0]["abandoned"] == 0 + + +def test_main_reads_the_closed_pr_file_and_degrades_without_it(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + payload = json.dumps({"workflow_runs": [ + _run("Tests", "cancelled", event="pull_request", branch="feat/regroup", + created="2026-09-19T10:59:28Z", started="2026-09-19T10:59:30Z", + updated="2026-09-19T11:06:13Z"), + ]}) + feed = tmp_path / "closed.json" + feed.write_text(json.dumps([_closed("feat/regroup", "2026-09-19T11:05:51Z")])) + out = tmp_path / "LibA.ci_timing.json" + for closed_arg, n_events in ((str(feed), 0), ("", 1), + (str(tmp_path / "missing.json"), 1)): + monkeypatch.setattr("sys.stdin", __import__("io").StringIO(payload)) + rc = ct.main(["--name", "LibA", "--group", "libraries", "--owner", "OwnerX", + "--ts", "T", "--closed-prs", closed_arg, "--out", str(out)]) + assert rc == 0 + side = json.loads(out.read_text()) + assert side["error"] == "" + assert len(side["events"]) == n_events + capsys.readouterr() diff --git a/tests/test_ci_timing_script.py b/tests/test_ci_timing_script.py new file mode 100644 index 00000000..ade1669b --- /dev/null +++ b/tests/test_ci_timing_script.py @@ -0,0 +1,89 @@ +"""tests/test_ci_timing_script.py — the shell leg's closed-PR plumbing. + +`time_one_repo_ci` makes a second, best-effort `gh api` call for the repo's +recently closed PRs and hands it to the Python step as `--closed-prs`. Driven +like `test_ci_status_script.py`: source the script, call the one function, and +put a stub `gh` first on `PATH` so nothing here touches the network. + +Generic repo names only (the tenant firewall): `gh` is stubbed, so the name is +never resolved. +""" + +import json +import subprocess +import textwrap +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "heart" / "checks" / "ci_timing.sh" + +RUNS = {"workflow_runs": [{ + "name": "Tests", "conclusion": "cancelled", "status": "completed", + "event": "pull_request", "head_branch": "feat/regroup", + "created_at": "2026-09-19T10:59:28Z", "run_started_at": "2026-09-19T10:59:30Z", + "updated_at": "2026-09-19T11:06:13Z", "html_url": "https://github.invalid/run/a", +}]} +CLOSED = [{"head_ref": "feat/regroup", "closed_at": "2026-09-19T11:05:51Z"}] + + +def write_gh(bin_dir: Path, pulls_body: str) -> None: + """A `gh` that answers the runs query and runs `pulls_body` for the PR one.""" + path = bin_dir / "gh" + path.write_text("#!/usr/bin/env bash\n" + textwrap.dedent(f"""\ + case "$2" in + */actions/runs*) cat <<'JSON' + {json.dumps(RUNS)} + JSON + ;; + */pulls*) {pulls_body} ;; + *) exit 1 ;; + esac + """)) + path.chmod(0o755) + + +def run_one_repo(tmp_path: Path, bin_dir: Path) -> dict: + state = tmp_path / "state" + (state / "per-repo").mkdir(parents=True) + result = subprocess.run( + ["bash", "-c", + 'source "$1" >/dev/null 2>&1; time_one_repo_ci "ExampleOrg/ExampleRepo" libraries', + "ci_timing", str(SCRIPT)], + capture_output=True, text=True, + env={"PATH": f"{bin_dir}:/usr/bin:/bin", "HOME": str(tmp_path), + "HEART_STATE_DIR": str(state), "NO_COLOR": "1"}, + ) + assert result.returncode == 0, result.stderr + return json.loads((state / "per-repo" / "ExampleRepo.ci_timing.json").read_text()) + + +@pytest.fixture +def bin_dir(tmp_path): + d = tmp_path / "bin" + d.mkdir() + return d + + +def test_closed_prs_reach_the_python_step(tmp_path, bin_dir): + write_gh(bin_dir, f"echo '{json.dumps(CLOSED)}'") + side = run_one_repo(tmp_path, bin_dir) + assert side["error"] == "" + assert side["events"] == [] + assert side["workflows"]["Tests"]["abandoned"] == 1 + + +def test_a_failed_closed_pr_fetch_degrades_to_todays_behaviour(tmp_path, bin_dir): + write_gh(bin_dir, "echo 'HTTP 403' >&2; exit 1") + side = run_one_repo(tmp_path, bin_dir) + assert side["error"] == "" # not a fetch failure + assert [e["kind"] for e in side["events"]] == ["suspect_cancelled"] + assert side["workflows"]["Tests"]["abandoned"] == 0 + + +def test_an_empty_closed_pr_fetch_degrades_to_todays_behaviour(tmp_path, bin_dir): + write_gh(bin_dir, "true") + side = run_one_repo(tmp_path, bin_dir) + assert side["error"] == "" + assert len(side["events"]) == 1