diff --git a/scripts/sentry-ci-report.py b/scripts/sentry-ci-report.py index abb4fc22..3c891044 100644 --- a/scripts/sentry-ci-report.py +++ b/scripts/sentry-ci-report.py @@ -90,11 +90,21 @@ CRON_SCHEDULES = { "iOS TestFlight ship (GitHub-hosted macOS)": "26,56 * * * *", - # auto-merge-prs.yml: fleet auto-merge sweep (15 min). - "Auto-merge PRs": "*/15 * * * *", } _CRON_SCHEDULES_FOLDED = {name.casefold(): expr for name, expr in CRON_SCHEDULES.items()} +# Scheduled workflows that deliberately send NO Crons check-in (AFC-626). +# `auto-merge-prs.yml` asks for a 15-minute schedule, but GitHub starts it +# about once an hour, so a `*/15` monitor recorded three misses for every real +# run and stayed red while the sweep worked. A missed sweep tick is harmless +# (the next one picks the PR up), and a FAILED run still raises the error event +# in section 2 of main(), so the cron monitor added nothing but noise. A +# schedule run of a name listed here skips both check-in phases (see +# resolve_cron_expr()) without the unmapped-schedule drift event that an +# unlisted name would raise. +UNMONITORED_SCHEDULES = frozenset({"Auto-merge PRs"}) +_UNMONITORED_FOLDED = {name.casefold() for name in UNMONITORED_SCHEDULES} + DEFAULT_CHECKIN_MARGIN = 15 # GitHub `schedule` delivery is best-effort. These daily/weekday/hourly # monitors always eventually run, but the start is hours late, so a 15-minute @@ -105,20 +115,23 @@ # `ci-CI-refs/heads/main` group can also queue or drop that tick. Do not # copy this onto 30-min macos ship crons (FLEET-INFRA-CC / DA / CX): those # drop ticks entirely, so a wider margin still misses. -CHECKIN_MARGIN_OVERRIDES = { - # Auto-merge PRs is a 15-minute cron; the reporter check-in arrives - # only after the run completes plus workflow_run dispatch. 30 minutes - # covers ordinary GitHub lag and a short sweep without hiding a - # dropped tick the next window would also miss. - "Auto-merge PRs": 30, -} +CHECKIN_MARGIN_OVERRIDES = {} _CHECKIN_MARGINS_FOLDED = {name.casefold(): margin for name, margin in CHECKIN_MARGIN_OVERRIDES.items()} DEFAULT_MAX_RUNTIME = 60 MAX_RUNTIME_OVERRIDES = {} _MAX_RUNTIMES_FOLDED = {name.casefold(): runtime for name, runtime in MAX_RUNTIME_OVERRIDES.items()} -FLAP_DEBOUNCE_OVERRIDES = {} +# AFC-626: the 30-minute macOS ship cron is the dropped-tick class named above +# (FLEET-INFRA-CC / DA / CX), so one miss is routine and a wider margin alone +# still misses a dropped tick. Three failed or missed check-ins in a row is a +# real stop; one ok check-in closes the issue again. +FLAP_DEBOUNCE_OVERRIDES = { + "iOS TestFlight ship (GitHub-hosted macOS)": { + "failure_issue_threshold": 3, + "recovery_threshold": 1, + }, +} _FLAP_DEBOUNCE_FOLDED = {name.casefold(): cfg for name, cfg in FLAP_DEBOUNCE_OVERRIDES.items()} WORKFLOWS_DIR = Path(__file__).resolve().parent.parent / ".github" / "workflows" @@ -164,15 +177,27 @@ def discover_workflow_names(workflows_dir: Path = WORKFLOWS_DIR) -> set[str] | N def find_cron_schedule_drift(known_names: set[str] | None) -> list[str]: - """CRON_SCHEDULES keys that match no real workflow `name:`, case-insensitively. + """CRON_SCHEDULES keys and UNMONITORED_SCHEDULES names that match no real + workflow `name:`, case-insensitively, plus any name listed in both maps. - Empty when the workflow set is unknown (None) or empty — "I could not read - the workflows" must never masquerade as "every key is stale". + A stale UNMONITORED_SCHEDULES entry is drift too: after a rename it exempts + nothing, while the renamed workflow raises unmapped-schedule drift on every + tick. Empty when the workflow set is unknown (None) or empty — "I could + not read the workflows" must never masquerade as "every key is stale". """ if not known_names: return [] folded = {name.casefold() for name in known_names} - return sorted(key for key in CRON_SCHEDULES if key.casefold() not in folded) + # A name in both maps, in any casing, is drift as well: UNMONITORED_SCHEDULES + # wins, so its CRON_SCHEDULES entry would silently never check in. Both + # spellings are reported, so neither half of the duplicate is hidden. + overlap = {key.casefold() for key in CRON_SCHEDULES} & { + name.casefold() for name in UNMONITORED_SCHEDULES + } + configured = set(CRON_SCHEDULES) | set(UNMONITORED_SCHEDULES) + return sorted( + key for key in configured if key.casefold() not in folded or key.casefold() in overlap + ) def checkin_id_for_run(run_id: str, run_attempt: str) -> str: @@ -241,14 +266,22 @@ def resolve_cron_expr( ) -> str | None: """Look up the mirrored cron expression for a scheduled workflow, or None. - On a miss this both warns in the job log and raises the `unmapped-schedule` - config-drift issue in Sentry, then returns None so the caller skips the - check-in. Shared by the requested and completed phases: duplicating it - would let one phase send a check-in the other silently dropped. + A name in UNMONITORED_SCHEDULES returns None quietly, so the caller skips + the check-in. On any other miss this both warns in the job log and raises + the `unmapped-schedule` config-drift issue in Sentry, then returns None so + the caller skips the check-in. Shared by the requested and completed + phases: duplicating it would let one phase send a check-in the other + silently dropped. Lookup is case-folded — a workflow rename that only changes capitalisation must never again silently detach a job from its Crons monitor. """ + if workflow_name.casefold() in _UNMONITORED_FOLDED: + print( + f"Workflow '{workflow_name}' is listed in UNMONITORED_SCHEDULES; " + "no cron check-in sent." + ) + return None cron_expr = _CRON_SCHEDULES_FOLDED.get(workflow_name.casefold()) if cron_expr: return cron_expr @@ -439,15 +472,18 @@ def main() -> int: if stale_keys: joined = ", ".join(repr(key) for key in stale_keys) print( - f"::error::CRON_SCHEDULES key(s) {joined} match no workflow `name:` under " - ".github/workflows/ — those cron check-ins are not being sent. " - "Re-key CRON_SCHEDULES in scripts/sentry-ci-report.py to the current name." + f"::error::CRON_SCHEDULES / UNMONITORED_SCHEDULES name(s) {joined} match no " + "workflow `name:` under .github/workflows/, or are listed in both maps — " + "a stale CRON_SCHEDULES key sends no cron check-in, a stale " + "UNMONITORED_SCHEDULES entry exempts nothing, and a name in both never " + "checks in. Re-key or de-duplicate it in scripts/sentry-ci-report.py." ) send_config_drift_event( envelope_url, auth_header, "stale-cron-key", - f"sentry-ci-report CRON_SCHEDULES has stale workflow name(s): {joined} [{APP}]", + f"sentry-ci-report CRON_SCHEDULES/UNMONITORED_SCHEDULES has stale or duplicated " + f"workflow name(s): {joined} [{APP}]", ["ci-report-config-drift", APP, "stale-cron-key"], {"stale_keys": stale_keys, "run_url": run_url}, ) diff --git a/scripts/sentry_ci_report_test.py b/scripts/sentry_ci_report_test.py new file mode 100644 index 00000000..6fa1496a --- /dev/null +++ b/scripts/sentry_ci_report_test.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Self-tests for the AFC-626 cron-monitor rules in scripts/sentry-ci-report.py. + +Stdlib only, no network: send_envelope is replaced with a recorder and the +Actions API lookup is disabled by clearing GITHUB_TOKEN. +Run with `python3 scripts/sentry_ci_report_test.py`. +""" + +import importlib.util +import os +import re +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location( + "sentry_ci_report", ROOT / "scripts" / "sentry-ci-report.py") +reporter = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reporter) + +DSN = "https://abc123@o1.ingest.example.test/42" +SHIP = "iOS TestFlight ship (GitHub-hosted macOS)" + + +def run_reporter(workflow_name, conclusion, action="completed", event="schedule", branch="main", + workflow_names=None): + """Run main() with send_envelope recorded. + + The stale-key drift guard is stubbed to report nothing, so these + assertions do not depend on the live checkout's workflow names, unless + workflow_names is given: then discover_workflow_names() returns it and the + real drift guard runs against it. + """ + sent = [] + env = { + "SENTRY_FLEET_DSN": DSN, + "WORKFLOW_NAME": workflow_name, + "WORKFLOW_CONCLUSION": conclusion, + "WORKFLOW_EVENT": event, + "WORKFLOW_BRANCH": branch, + "WORKFLOW_ACTOR": "agent", + "WORKFLOW_RUN_URL": "https://example.test/run/1", + "WORKFLOW_RUN_ID": "1", + "WORKFLOW_RUN_ACTION": action, + "WORKFLOW_RUN_ATTEMPT": "1", + "GITHUB_TOKEN": "", + } + if workflow_names is None: + drift_patch = mock.patch.object(reporter, "find_cron_schedule_drift", return_value=[]) + else: + drift_patch = mock.patch.object( + reporter, "discover_workflow_names", return_value=set(workflow_names)) + with mock.patch.object( + reporter, "send_envelope", lambda url, auth, item_type, payload: sent.append((item_type, payload)) + ), mock.patch.dict(os.environ, env, clear=False), drift_patch: + rc = reporter.main() + return rc, sent + + +class UnmonitoredScheduleTests(unittest.TestCase): + def test_every_scheduled_workflow_is_mapped_or_unmonitored(self): + found = {} + for path in sorted(reporter.WORKFLOWS_DIR.glob("*.y*ml")): + text = path.read_text(encoding="utf-8", errors="replace") + crons = re.findall(r"^\s*-\s*cron:\s*['\"]?([^'\"#\n]+?)['\"]?\s*(?:#.*)?$", text, re.MULTILINE) + name = re.search(r"^name:\s*(.+?)\s*$", text, re.MULTILINE) + if crons and name: + found[name.group(1).strip().strip("\"'")] = crons[0].strip() + # Case-folded on both sides, like main() and find_cron_schedule_drift(). + unmonitored_folded = {name.casefold() for name in reporter.UNMONITORED_SCHEDULES} + self.assertEqual(unmonitored_folded - {name.casefold() for name in found}, set()) + self.assertEqual( + {name.casefold(): cron for name, cron in reporter.CRON_SCHEDULES.items()}, + { + name.casefold(): cron + for name, cron in found.items() + if name.casefold() not in unmonitored_folded + }, + ) + + def test_requested_sweep_opens_no_checkin_and_raises_no_drift(self): + rc, sent = run_reporter("Auto-merge PRs", "", action="requested") + self.assertEqual(rc, 0) + self.assertEqual(sent, []) + + def test_completed_sweep_sends_no_checkin_and_no_drift(self): + rc, sent = run_reporter("Auto-merge PRs", "success") + self.assertEqual(rc, 0) + self.assertEqual(sent, []) + + def test_failed_sweep_still_raises_its_error_event(self): + rc, sent = run_reporter("Auto-merge PRs", "failure") + self.assertEqual(rc, 0) + self.assertEqual([item_type for item_type, _ in sent], ["event"]) + self.assertEqual(sent[0][1]["fingerprint"], ["ci-failure", "codecaps", "Auto-merge PRs"]) + + def test_an_unlisted_unmapped_schedule_still_raises_drift(self): + rc, sent = run_reporter("Some new scheduled job", "success") + self.assertEqual(rc, 0) + self.assertEqual(len(sent), 1) + self.assertIn("unmapped-schedule", sent[0][1]["fingerprint"]) + + +class ConfigDriftTests(unittest.TestCase): + def test_stale_unmonitored_entry_is_reported_like_a_stale_cron_key(self): + live = set(reporter.CRON_SCHEDULES) + self.assertEqual( + reporter.find_cron_schedule_drift(live), sorted(reporter.UNMONITORED_SCHEDULES)) + + def test_unmonitored_entry_matches_live_names_case_insensitively(self): + live = {name.casefold() for name in reporter.CRON_SCHEDULES} + live |= {name.casefold() for name in reporter.UNMONITORED_SCHEDULES} + self.assertEqual(reporter.find_cron_schedule_drift(live), []) + + def test_name_in_both_maps_is_reported_as_drift(self): + live = set(reporter.CRON_SCHEDULES) | set(reporter.UNMONITORED_SCHEDULES) + with mock.patch.dict(reporter.CRON_SCHEDULES, {"Auto-merge PRs": "*/15 * * * *"}): + self.assertEqual(reporter.find_cron_schedule_drift(live), ["Auto-merge PRs"]) + # A duplicate that differs only by case reports both spellings. + with mock.patch.dict(reporter.CRON_SCHEDULES, {"AUTO-MERGE PRS": "*/15 * * * *"}): + self.assertEqual( + reporter.find_cron_schedule_drift(live), ["AUTO-MERGE PRS", "Auto-merge PRs"]) + + def test_stale_unmonitored_entry_raises_the_stale_cron_key_event(self): + rc, sent = run_reporter( + "CI", "success", event="push", workflow_names=set(reporter.CRON_SCHEDULES)) + self.assertEqual(rc, 0) + self.assertEqual([item_type for item_type, _ in sent], ["event"]) + payload = sent[0][1] + self.assertEqual(payload["fingerprint"], ["ci-report-config-drift", "codecaps", "stale-cron-key"]) + self.assertEqual(payload["extra"]["stale_keys"], sorted(reporter.UNMONITORED_SCHEDULES)) + + +class FailureThresholdTests(unittest.TestCase): + def test_ship_monitor_needs_three_misses_in_a_row(self): + config = reporter.build_monitor_config(SHIP, "26,56 * * * *") + self.assertEqual(config["failure_issue_threshold"], 3) + self.assertEqual(config["recovery_threshold"], 1) + self.assertEqual(config["checkin_margin"], reporter.DEFAULT_CHECKIN_MARGIN) + self.assertEqual(config["max_runtime"], reporter.DEFAULT_MAX_RUNTIME) + + def test_unlisted_monitor_keeps_sentry_defaults(self): + config = reporter.build_monitor_config("CI", "47 7 * * *") + self.assertNotIn("failure_issue_threshold", config) + self.assertNotIn("recovery_threshold", config) + + def test_both_ship_phases_send_the_threshold(self): + for action, conclusion in (("requested", ""), ("completed", "success")): + rc, sent = run_reporter(SHIP, conclusion, action=action) + self.assertEqual(rc, 0) + checkins = [payload for item_type, payload in sent if item_type == "check_in"] + self.assertEqual(len(checkins), 1, action) + self.assertEqual(checkins[0]["monitor_config"]["failure_issue_threshold"], 3) + self.assertEqual(checkins[0]["monitor_config"]["recovery_threshold"], 1) + + +if __name__ == "__main__": + unittest.main()