From eab56d34cf84b9d9e801895d8704ae2a727d992e Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:10:08 +0000 Subject: [PATCH] Retry continuous integration jobs that GitHub did not start. GitHub cancels a job when no hosted runner picks it up, which has happened several times on macOS. The run then fails although no test failed. A second workflow now re-runs the failed jobs of such a run, up to three attempts in total, when the only jobs that did not pass had no runner and no steps. A job that ran and failed is not repeated, so its result stands. The report sources of each platform are now deleted only when both Chrono jobs passed. A re-run of a Chrono job runs the PDF job again, which needs the sources of every platform; before, it would have produced the reports of the re-run platform only. --- .github/workflows/ci.yml | 15 ++- .github/workflows/retry-unstarted-jobs.yml | 69 ++++++++++ scripts/ci/unstarted_jobs.py | 113 ++++++++++++++++ tests/README.md | 1 + tests/unit/CMakeLists.txt | 4 + tests/unit/python/test_unstarted_jobs.py | 148 +++++++++++++++++++++ 6 files changed, 347 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/retry-unstarted-jobs.yml create mode 100644 scripts/ci/unstarted_jobs.py create mode 100644 tests/unit/python/test_unstarted_jobs.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c12ffb8..f2ac3ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -417,7 +417,8 @@ jobs: retention-days: 14 # Markdown reports with their figures, for the test-reports job, which - # converts them to PDF and then deletes this artifact. + # converts them to PDF and deletes this artifact once the Chrono jobs of + # every platform have passed. - name: Hand over the reports if: ${{ !cancelled() && steps.build.conclusion == 'success' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -827,7 +828,8 @@ jobs: retention-days: 14 # Markdown reports with their figures, for the test-reports job, which - # converts them to PDF and then deletes this artifact. + # converts them to PDF and deletes this artifact once the Chrono jobs of + # every platform have passed. - name: Hand over the reports if: ${{ !cancelled() && steps.build.conclusion == 'success' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -910,6 +912,9 @@ jobs: echo "[OK] ${platform}/$(basename "${source_pdf}"): $(du -h "${source_pdf}" | cut -f1) -> $(du -h "${screen_pdf}" | cut -f1)" done + # When this job runs again in a later attempt of the same run, its reports + # replace those of the earlier attempt, which lack the platforms whose + # jobs had not passed yet. - name: Upload the PDF reports uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -917,11 +922,15 @@ jobs: path: test-reports/ if-no-files-found: error retention-days: 30 + overwrite: true + # The sources are deleted only when both Chrono jobs passed. Otherwise a + # re-run of a failed or unstarted job runs this job again, which then + # needs the sources of every platform; they expire after one day. # Best effort: a pull request from a fork gets a read-only token, and the # artifacts then expire after one day instead. - name: Delete the converted report sources - if: ${{ always() }} + if: ${{ always() && needs.chrono.result == 'success' && needs.chrono-windows.result == 'success' }} env: GH_TOKEN: ${{ github.token }} run: | diff --git a/.github/workflows/retry-unstarted-jobs.yml b/.github/workflows/retry-unstarted-jobs.yml new file mode 100644 index 0000000..2d38e26 --- /dev/null +++ b/.github/workflows/retry-unstarted-jobs.yml @@ -0,0 +1,69 @@ +# Repeats the jobs of a CI run that GitHub never started. +# +# GitHub cancels a job when no hosted runner picks it up, which happens now and +# then on macOS. The job "All checks" then fails although no test failed. This +# workflow runs when a CI run has finished and re-runs its failed jobs if the +# only jobs that did not pass were never started. A job that ran and failed is +# never repeated here: its result stands until someone looks at it. +# +# A run gets at most three attempts in total. If a job is still unstarted after +# that, the run stays failed; use "Re-run failed jobs" on the run page. +# +# A workflow_run workflow is read from the default branch and has a token that +# may write, also for runs of pull requests from forks. It therefore checks out +# the default branch only and never the code of the run it looks at. +name: Retry unstarted jobs + +on: + workflow_run: + workflows: [CI] + types: [completed] + +permissions: + contents: read + +jobs: + retry: + name: Re-run jobs that GitHub did not start + # A run that was cancelled by a newer push or by hand ends as "cancelled", + # not "failure", and is left alone. + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.run_attempt < 3 }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + # To re-run the failed jobs of the CI run. + actions: write + defaults: + run: + # Named explicitly so that a failing command in a pipe fails the step. + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} + steps: + - name: Check out the helper script + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: scripts/ci + + - name: Look for jobs that were never started + id: decide + run: | + echo "CI run ${RUN_ID}, attempt ${RUN_ATTEMPT}" + gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}/jobs?filter=latest&per_page=100" > "${RUNNER_TEMP}/jobs.json" + python3 scripts/ci/unstarted_jobs.py "${RUNNER_TEMP}/jobs.json" \ + --gate "All checks" --github-output "${GITHUB_OUTPUT}" | tee "${RUNNER_TEMP}/decision.txt" + { + echo "### CI run ${RUN_ID}, attempt ${RUN_ATTEMPT}" + echo + echo '```' + cat "${RUNNER_TEMP}/decision.txt" + echo '```' + } >> "${GITHUB_STEP_SUMMARY}" + + - name: Re-run the failed jobs of the CI run + if: ${{ steps.decide.outputs.retry == 'true' }} + run: gh api --method POST "repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}/rerun-failed-jobs" diff --git a/scripts/ci/unstarted_jobs.py b/scripts/ci/unstarted_jobs.py new file mode 100644 index 0000000..550e7c7 --- /dev/null +++ b/scripts/ci/unstarted_jobs.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Decide whether a failed workflow run should be retried because of unstarted jobs. + +Usage: + python3 scripts/ci/unstarted_jobs.py --gate NAME [--github-output FILE] + + is the response of the GitHub REST API for the jobs of one workflow +run (GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs). + +GitHub cancels a job when no hosted runner picks it up. Such a job ran nothing: +it has no runner and no steps. It says nothing about the code under test, so +repeating it is safe. A job that ran and failed must not be repeated +automatically, because a second attempt could hide a test that fails only +sometimes. + +The run is retried only when both conditions hold: + - at least one job was never started; + - every other job passed or was skipped. The job named by --gate is exempt: + it fails whenever another job did not pass. + +--github-output appends "retry=true" or "retry=false" to FILE (for example the +file named by GITHUB_OUTPUT). + +Exit code 0 = decision made, 2 = usage error or unreadable job list. +Standard library only. +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import NamedTuple + + +class Decision(NamedTuple): + retry: bool + unstarted: list[str] # names of the jobs that GitHub never started + blocking: list[str] # "name: conclusion" of the jobs that rule out a retry + + +def is_unstarted(job: dict) -> bool: + """True for a job that was cancelled before any runner picked it up.""" + return (job.get("conclusion") == "cancelled" + and not job.get("runner_id") + and not job.get("runner_name") + and not job.get("steps")) + + +def decide(jobs: list[dict], gate: str) -> Decision: + unstarted: list[str] = [] + blocking: list[str] = [] + for job in jobs: + name = job.get("name", "") + conclusion = job.get("conclusion") + if conclusion in ("success", "skipped"): + continue + if is_unstarted(job): + unstarted.append(name) + elif name != gate: + blocking.append(f"{name}: {conclusion or 'not completed'}") + return Decision(bool(unstarted) and not blocking, unstarted, blocking) + + +def read_jobs(path: Path) -> list[dict]: + """Read the job list; raise ValueError if it is malformed or incomplete.""" + payload = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(payload, dict) or not isinstance(payload.get("jobs"), list): + raise ValueError('expected a JSON object with a "jobs" list') + jobs = payload["jobs"] + total = payload.get("total_count", len(jobs)) + if total != len(jobs): + raise ValueError(f"the list holds {len(jobs)} of {total} jobs; request a larger page") + if not all(isinstance(job, dict) for job in jobs): + raise ValueError("every job must be a JSON object") + return jobs + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("jobs", type=Path, help="JSON list of the jobs of one workflow run") + parser.add_argument("--gate", required=True, + help="name of the job that fails whenever another job did not pass") + parser.add_argument("--github-output", type=Path, + help="append retry=true or retry=false to this file") + args = parser.parse_args() + + try: + jobs = read_jobs(args.jobs) + except (OSError, ValueError) as error: + print(f"[FAIL] cannot read {args.jobs}: {error}", file=sys.stderr) + return 2 + + decision = decide(jobs, args.gate) + for name in decision.unstarted: + print(f" [not started] {name}") + for entry in decision.blocking: + print(f" [did not pass] {entry}") + if decision.retry: + print("[RETRY] the only jobs that did not pass were never started") + elif decision.unstarted: + print("[NO RETRY] a job that ran did not pass; that result stands") + else: + print("[NO RETRY] every job was started") + + if args.github_output is not None: + with args.github_output.open("a", encoding="utf-8") as handle: + handle.write(f"retry={'true' if decision.retry else 'false'}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/README.md b/tests/README.md index 8038bd9..b9025d4 100644 --- a/tests/README.md +++ b/tests/README.md @@ -73,6 +73,7 @@ The Chrono job also runs the **full suites** (verification, comparison, long reg - **Benchmarks do not fail the run.** Timings on shared runners are for information only. - **Results:** each job uploads its JUnit reports and logs. The page of a workflow run shows each report's table of checks against limits for every platform. - **PDF reports:** the artifact `test-reports` holds the reports of all three platforms as PDF, in the folders `linux`, `macos` and `windows`, with the figures resampled to 150 dpi for reading on screen. The regression reports are in every run; the verification and comparison reports come with the full suites. The Chrono jobs write the reports as Markdown, and a final job converts them on Linux, where pandoc and LaTeX are installed. +- **Jobs that GitHub does not start:** GitHub cancels a job when no hosted runner picks it up, which happens now and then on macOS; the run then fails although no test failed. A second workflow ([`.github/workflows/retry-unstarted-jobs.yml`](../.github/workflows/retry-unstarted-jobs.yml)) re-runs the failed jobs of such a run, up to three attempts in total, when `scripts/ci/unstarted_jobs.py` finds that the only jobs that did not pass were never started. A job that ran and failed is not repeated automatically. A run whose job is still unstarted after the last attempt stays failed; use "Re-run failed jobs" on the run page. - **Not covered:** the VSG GUI build and the release packages. ## Test-only environment variables diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 5b3ac59..5a2bf3e 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -437,6 +437,10 @@ if(Python3_FOUND) add_test(NAME test_report_summary COMMAND ${Python3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/python/test_report_summary.py") set_tests_properties(test_report_summary PROPERTIES LABELS "unit;chrono-free") + # Retry decision for workflow runs with unstarted jobs (standard library only). + add_test(NAME test_unstarted_jobs + COMMAND ${Python3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/python/test_unstarted_jobs.py") + set_tests_properties(test_unstarted_jobs PROPERTIES LABELS "unit;chrono-free") add_test( NAME test_demo_features_python COMMAND ${Python3_EXECUTABLE} diff --git a/tests/unit/python/test_unstarted_jobs.py b/tests/unit/python/test_unstarted_jobs.py new file mode 100644 index 0000000..6ad331b --- /dev/null +++ b/tests/unit/python/test_unstarted_jobs.py @@ -0,0 +1,148 @@ +"""Retry decision for workflow runs with unstarted jobs (scripts/ci/unstarted_jobs.py).""" + +import json +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "scripts" / "ci")) +from unstarted_jobs import decide, is_unstarted, read_jobs + +GATE = "All checks" + + +def _ran(name, conclusion): + """A job that a runner picked up, as the GitHub REST API lists it.""" + return {"name": name, "conclusion": conclusion, "runner_id": 1000000337, + "runner_name": "GitHub Actions 1000000337", "steps": [{"name": "Set up job"}]} + + +def _unstarted(name): + """A job that GitHub cancelled because no runner picked it up.""" + return {"name": name, "conclusion": "cancelled", "runner_id": 0, + "runner_name": "", "steps": []} + + +class IsUnstartedTest(unittest.TestCase): + def test_a_cancelled_job_without_runner_and_steps_is_unstarted(self): + self.assertTrue(is_unstarted(_unstarted("Chrono build and tests (macOS)"))) + # The API may also leave the runner fields out or set them to null. + self.assertTrue(is_unstarted({"name": "job", "conclusion": "cancelled"})) + self.assertTrue(is_unstarted({"name": "job", "conclusion": "cancelled", + "runner_id": None, "runner_name": None, "steps": None})) + + def test_a_job_that_a_runner_picked_up_is_not_unstarted(self): + for conclusion in ("success", "failure", "cancelled", "timed_out"): + with self.subTest(conclusion=conclusion): + self.assertFalse(is_unstarted(_ran("job", conclusion))) + + def test_only_a_cancelled_job_is_unstarted(self): + for conclusion in ("failure", "skipped", "success", None): + with self.subTest(conclusion=conclusion): + job = dict(_unstarted("job"), conclusion=conclusion) + self.assertFalse(is_unstarted(job)) + + +class DecideTest(unittest.TestCase): + def test_retry_when_the_only_job_that_did_not_pass_was_never_started(self): + decision = decide([ + _ran("Chrono build and tests (Linux)", "success"), + _unstarted("Chrono build and tests (macOS)"), + _ran("Chrono build and tests (Windows)", "success"), + _ran("PDF test reports", "success"), + _ran(GATE, "failure"), + ], GATE) + self.assertTrue(decision.retry) + self.assertEqual(decision.unstarted, ["Chrono build and tests (macOS)"]) + self.assertEqual(decision.blocking, []) + + def test_retry_names_every_unstarted_job(self): + decision = decide([ + _unstarted("Chrono-free build and tests (macOS)"), + _unstarted("Chrono build and tests (macOS)"), + _ran(GATE, "failure"), + ], GATE) + self.assertTrue(decision.retry) + self.assertEqual(decision.unstarted, ["Chrono-free build and tests (macOS)", + "Chrono build and tests (macOS)"]) + + def test_skipped_jobs_do_not_rule_out_a_retry(self): + decision = decide([ + _unstarted("Chrono build and tests (macOS)"), + {"name": "PDF test reports", "conclusion": "skipped", "runner_id": 0, + "runner_name": "", "steps": []}, + _ran(GATE, "failure"), + ], GATE) + self.assertTrue(decision.retry) + + def test_no_retry_when_every_job_passed(self): + decision = decide([_ran("Chrono build and tests (Linux)", "success"), + _ran(GATE, "success")], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.unstarted, []) + + def test_no_retry_for_a_job_that_ran_and_failed(self): + decision = decide([ + _ran("Chrono build and tests (Linux)", "success"), + _ran("Chrono build and tests (Windows)", "failure"), + _ran(GATE, "failure"), + ], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.blocking, ["Chrono build and tests (Windows): failure"]) + + def test_a_failed_job_rules_out_the_retry_of_an_unstarted_one(self): + decision = decide([ + _unstarted("Chrono build and tests (macOS)"), + _ran("Chrono build and tests (Windows)", "failure"), + _ran(GATE, "failure"), + ], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.unstarted, ["Chrono build and tests (macOS)"]) + self.assertEqual(decision.blocking, ["Chrono build and tests (Windows): failure"]) + + def test_no_retry_for_a_job_cancelled_while_it_ran(self): + decision = decide([_ran("Chrono build and tests (macOS)", "cancelled"), + _ran(GATE, "failure")], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.blocking, ["Chrono build and tests (macOS): cancelled"]) + + def test_no_retry_while_a_job_has_no_conclusion(self): + decision = decide([_unstarted("Chrono build and tests (macOS)"), + _ran("Chrono build and tests (Linux)", None)], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.blocking, ["Chrono build and tests (Linux): not completed"]) + + def test_only_the_named_gate_is_exempt(self): + decision = decide([_unstarted("Chrono build and tests (macOS)"), + _ran("PDF test reports", "failure"), + _ran(GATE, "failure")], GATE) + self.assertFalse(decision.retry) + self.assertEqual(decision.blocking, ["PDF test reports: failure"]) + + +class ReadJobsTest(unittest.TestCase): + def _read(self, payload): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "jobs.json" + path.write_text(payload if isinstance(payload, str) else json.dumps(payload), + encoding="utf-8") + return read_jobs(path) + + def test_reads_the_jobs_of_an_api_response(self): + jobs = self._read({"total_count": 1, "jobs": [_ran("job", "success")]}) + self.assertEqual([job["name"] for job in jobs], ["job"]) + + def test_rejects_an_incomplete_or_malformed_list(self): + for payload in ({"total_count": 2, "jobs": [_ran("job", "success")]}, # one page of two + {"message": "Not Found"}, + [_ran("job", "success")], + {"jobs": ["job"]}, + "not json"): + with self.subTest(payload=payload): + with self.assertRaises(ValueError): + self._read(payload) + + +if __name__ == "__main__": + unittest.main()