Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -910,18 +912,25 @@ 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:
name: test-reports
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: |
Expand Down
69 changes: 69 additions & 0 deletions .github/workflows/retry-unstarted-jobs.yml
Original file line number Diff line number Diff line change
@@ -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"
113 changes: 113 additions & 0 deletions scripts/ci/unstarted_jobs.py
Original file line number Diff line number Diff line change
@@ -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 <jobs.json> --gate NAME [--github-output FILE]

<jobs.json> 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", "<unnamed>")
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())
1 change: 1 addition & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
148 changes: 148 additions & 0 deletions tests/unit/python/test_unstarted_jobs.py
Original file line number Diff line number Diff line change
@@ -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()
Loading