Skip to content

Commit af3fd1a

Browse files
committed
CI: check setup budgets and run deadlines in check-workflows.py
Add two checks to the workflow lint that runs on every PR, so the limits set in the previous commits do not quietly regress: - A job's worst-case apt time must leave 2 minutes of timeout-minutes. install-apt-deps is modelled as pull-timeout plus apt-install.sh replaying its own budget split (per-command floors, 10s kill grace, doubling retry delays), with the input defaults read from the action; ccache-setup adds its mirror fallback. install-apt-deps steps behind an if: count as alternatives. - Every parallel-make-check.py invocation needs --timeout and --deadline above 0 with --timeout no larger, and worst-case setup plus the job's deadlines, summed over every invocation, plus 5 minutes within timeout-minutes. The 5 minutes cover the steps around the run (setup-python, brew, autogen.sh, log upload, cache save). A value that is a GitHub expression draws a warning instead. test_ci_scripts.py checks the model's numbers against apt-install.sh and ccache-setup themselves, so a change there fails the tests instead of silently weakening the lint, and covers the --deadline labels. It runs in check-source-text.yml.
1 parent 9fb82e6 commit af3fd1a

3 files changed

Lines changed: 300 additions & 3 deletions

File tree

‎.github/scripts/check-workflows.py‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,17 @@
2323
# * every `run:` step is under the hard cap (error) and under the soft
2424
# warning threshold (warning, so a growing list is noticed with
2525
# runway left rather than at the cliff)
26+
# * a job's worst-case apt setup fits in its timeout-minutes, and every
27+
# parallel-make-check.py call has a --deadline that fits after it
2628
#
2729
# Findings are emitted as GitHub workflow commands (::error / ::warning)
2830
# so they surface as annotations on the run, and as plain text so the log
2931
# is readable when run locally.
3032

3133
import argparse
34+
import functools
3235
import pathlib
36+
import re
3337
import sys
3438

3539
import yaml
@@ -41,6 +45,22 @@
4145
# offending content out of the workflow before it becomes a failure.
4246
SOFT_LIMIT = 18000
4347

48+
# Seconds of timeout-minutes left for checkout and the build after setup.
49+
SETUP_MARGIN = 120
50+
51+
# Seconds left around a parallel-make-check --deadline for the steps before
52+
# it (setup-python, brew, autogen.sh) and after it (logs, cache save).
53+
DEADLINE_MARGIN = 300
54+
55+
# apt-install.sh's split_budget() limits and kill grace.
56+
UPDATE_MIN, UPDATE_MAX, INSTALL_MIN, KILL_GRACE = 20, 90, 40, 10
57+
58+
# The apt-install.sh limits ccache-setup falls back to.
59+
CCACHE_APT = {"tries": 2, "update": 60, "install": 90}
60+
61+
ACTIONS = pathlib.Path(__file__).resolve().parent.parent / "actions"
62+
PMC_OPTION = re.compile(r"--(timeout|deadline)[= ]\s*['\"]?([^\s'\"\\]+)")
63+
4464

4565
def iter_run_steps(doc: object) -> list[tuple[str, str]]:
4666
"""Yield (location, script) for every `run:` step in a parsed file.
@@ -80,6 +100,131 @@ def scan_steps(steps: object, where: str) -> None:
80100
return found
81101

82102

103+
@functools.cache
104+
def apt_defaults() -> dict:
105+
"""The install-apt-deps input defaults, read from the action itself."""
106+
doc = yaml.safe_load((ACTIONS / "install-apt-deps" / "action.yml")
107+
.read_text())
108+
return {k: v.get("default", "") for k, v in doc["inputs"].items()}
109+
110+
111+
def apt_install_worst(tries: int, budget: int = 0, delay: int = 5,
112+
update: int = 90, install: int = 300) -> int:
113+
"""Worst-case seconds of apt-install.sh, replaying its budget split."""
114+
spent = 0
115+
for n in range(1, tries + 1):
116+
up, inst = update, install
117+
if budget:
118+
per = int((budget - spent) / (tries - n + 1))
119+
up = min(UPDATE_MAX, max(UPDATE_MIN, int(per / 2)))
120+
inst = max(INSTALL_MIN, per - up)
121+
spent += up + inst + 2 * KILL_GRACE
122+
if n < tries:
123+
spent += delay
124+
delay *= 2
125+
return spent
126+
127+
128+
def apt_worst(inputs: dict) -> int:
129+
"""Worst-case seconds of one install-apt-deps step, or -1 if unknown."""
130+
try:
131+
pull = int(inputs["pull-timeout"]) + KILL_GRACE
132+
worst = apt_install_worst(int(inputs["retries"]),
133+
int(inputs["budget-seconds"]),
134+
int(inputs["retry-delay"]))
135+
except (KeyError, TypeError, ValueError):
136+
return -1
137+
return worst + (pull if inputs.get("ghcr-debs-tag") else 0)
138+
139+
140+
def check_timeouts(path: pathlib.Path, doc: object, defaults: dict) -> int:
141+
"""Check each job's apt setup and run deadlines against timeout-minutes."""
142+
errors = 0
143+
jobs = doc.get("jobs") if isinstance(doc, dict) else None
144+
if not isinstance(jobs, dict):
145+
return 0
146+
147+
def error(where: str, msg: str) -> None:
148+
nonlocal errors
149+
print(f"::error file={path}::{where}: {msg}")
150+
errors += 1
151+
152+
for job_id, job in jobs.items():
153+
if not isinstance(job, dict) or not isinstance(job.get("steps"), list):
154+
continue
155+
always = 0
156+
# install-apt-deps steps behind an if: are taken as alternatives.
157+
branches = [0]
158+
runs = []
159+
for i, step in enumerate(job["steps"]):
160+
if not isinstance(step, dict):
161+
continue
162+
where = f"jobs.{job_id} / {step.get('name') or f'step {i + 1}'}"
163+
run = step.get("run")
164+
for part in str(run or "").split("parallel-make-check.py")[1:]:
165+
cmd = re.split(r"(?<!\\)\n", part, maxsplit=1)[0]
166+
runs.append((where, dict(PMC_OPTION.findall(cmd))))
167+
uses = str(step.get("uses") or "")
168+
if uses.endswith("/install-apt-deps"):
169+
with_ = step.get("with")
170+
cost = apt_worst({**defaults,
171+
**(with_ if isinstance(with_, dict)
172+
else {})})
173+
if cost < 0:
174+
error(where, "give retries, retry-delay, budget-seconds "
175+
"and pull-timeout literal numbers so the "
176+
"setup budget can be checked")
177+
elif "if" in step:
178+
branches.append(cost)
179+
else:
180+
always += cost
181+
elif uses.endswith("/ccache-setup") \
182+
and "macos" not in str(job.get("runs-on", "")):
183+
always += apt_install_worst(**CCACHE_APT)
184+
setup = always + max(branches)
185+
186+
limit = job.get("timeout-minutes", 360)
187+
fixed = isinstance(limit, (int, float))
188+
if fixed and setup and setup + SETUP_MARGIN > limit * 60:
189+
need = -(-(setup + SETUP_MARGIN) // 60)
190+
error(f"jobs.{job_id}",
191+
f"apt setup can take {setup}s against a slow or dead "
192+
f"mirror, which leaves no room in timeout-minutes: {limit}. "
193+
f"The job is then cancelled instead of failing with the "
194+
f"apt error. Raise timeout-minutes to at least {need}, or "
195+
f"lower budget-seconds / pull-timeout.")
196+
197+
deadlines = 0.0
198+
for where, opts in runs:
199+
traw, draw = opts.get("timeout", ""), opts.get("deadline", "")
200+
if "$" in traw + draw:
201+
print(f"::warning file={path}::{where}: --timeout/--deadline "
202+
f"is not a literal, so it is not checked")
203+
continue
204+
try:
205+
timeout, deadline = float(traw), float(draw)
206+
except ValueError:
207+
timeout = deadline = -1.0
208+
if timeout <= 0 or deadline <= 0 or timeout > deadline:
209+
error(where, f"parallel-make-check.py needs --timeout and "
210+
f"--deadline above 0 with --timeout no larger, "
211+
f"got --timeout='{traw}' --deadline='{draw}'. "
212+
f"Without them a wedged config runs into "
213+
f"timeout-minutes, which cancels the job and "
214+
f"loses every config's log.")
215+
continue
216+
deadlines += deadline
217+
need = -(-(setup + deadlines * 60 + DEADLINE_MARGIN) // 60)
218+
if fixed and need > limit:
219+
error(where, f"--deadline={draw} plus {setup}s of worst-case "
220+
f"apt setup does not fit timeout-minutes: "
221+
f"{limit}, so the job can be cancelled before "
222+
f"the deadline fires. Raise timeout-minutes to "
223+
f"at least {int(need)}, or lower --deadline.")
224+
225+
return errors
226+
227+
83228
def check_file(path: pathlib.Path) -> tuple[int, int, int]:
84229
"""Lint one file. Returns (errors, warnings, largest run: step)."""
85230
errors = 0
@@ -113,13 +258,15 @@ def check_file(path: pathlib.Path) -> tuple[int, int, int]:
113258
f"limit the whole file stops loading.")
114259
warnings += 1
115260

261+
errors += check_timeouts(path, doc, apt_defaults())
262+
116263
return (errors, warnings, biggest)
117264

118265

119266
def main() -> int:
120267
p = argparse.ArgumentParser(
121268
description="Lint GitHub Actions workflow files for the 21000 "
122-
"character per-run-step limit.")
269+
"character per-run-step limit and job time budgets.")
123270
p.add_argument("paths", nargs="*", metavar="FILE",
124271
help="files to check (default: all workflows and "
125272
"composite actions under .github/)")
@@ -151,7 +298,7 @@ def main() -> int:
151298
print(f"checked {len(paths)} files; largest run: step is {biggest} "
152299
f"characters (limit {HARD_LIMIT})")
153300
if errors:
154-
print(f"FAILED: {errors} step(s) over the limit")
301+
print(f"FAILED: {errors} error(s)")
155302
return 1
156303
if warnings:
157304
print(f"{warnings} step(s) approaching the limit")

‎.github/scripts/test_ci_scripts.py‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
#!/usr/bin/env python3
2+
# Tests for check-workflows.py and parallel-make-check.py.
3+
#
4+
# python3 -m unittest discover -s .github/scripts -p 'test_*.py'
5+
6+
import contextlib
7+
import importlib.util
8+
import io
9+
import json
10+
import pathlib
11+
import re
12+
import shutil
13+
import subprocess
14+
import sys
15+
import tempfile
16+
import unittest
17+
18+
SCRIPTS = pathlib.Path(__file__).resolve().parent
19+
ACTIONS = SCRIPTS.parent / "actions"
20+
21+
spec = importlib.util.spec_from_file_location(
22+
"check_workflows", SCRIPTS / "check-workflows.py")
23+
cw = importlib.util.module_from_spec(spec)
24+
spec.loader.exec_module(cw)
25+
26+
27+
class AptModel(unittest.TestCase):
28+
def test_worst_cases(self):
29+
self.assertEqual(cw.apt_install_worst(2, budget=120), 175)
30+
self.assertEqual(cw.apt_install_worst(2, budget=600), 620)
31+
self.assertEqual(cw.apt_install_worst(2), 825)
32+
self.assertEqual(cw.apt_install_worst(**cw.CCACHE_APT), 345)
33+
inputs = {**cw.apt_defaults(), "ghcr-debs-tag": "ubuntu-24.04-full"}
34+
self.assertEqual(cw.apt_worst(inputs), 130 + 620)
35+
36+
def test_matches_the_scripts(self):
37+
script = (ACTIONS / "install-apt-deps/apt-install.sh").read_text()
38+
for line in ("update_timeout=90", "install_timeout=300", "delay=5",
39+
f'[ "$update_timeout" -le {cw.UPDATE_MAX} ]',
40+
f'[ "$update_timeout" -ge {cw.UPDATE_MIN} ]',
41+
f'[ "$install_timeout" -ge {cw.INSTALL_MIN} ]',
42+
f"timeout -k {cw.KILL_GRACE} "):
43+
self.assertIn(line, script)
44+
ccache = (ACTIONS / "ccache-setup/action.yml").read_text()
45+
self.assertIn(f"--tries {cw.CCACHE_APT['tries']}", ccache)
46+
self.assertIn(f"--update-timeout {cw.CCACHE_APT['update']}", ccache)
47+
self.assertIn(f"--install-timeout {cw.CCACHE_APT['install']}", ccache)
48+
49+
50+
APT = {"uses": "./.github/actions/install-apt-deps",
51+
"with": {"packages": "p", "ghcr-debs-tag": "ubuntu-24.04-full"}}
52+
53+
54+
def errors(limit: object, steps: list) -> int:
55+
doc = {"jobs": {"j": {"timeout-minutes": limit, "steps": steps}}}
56+
# Keep the ::error lines out of a CI log, where they would annotate.
57+
with contextlib.redirect_stdout(io.StringIO()):
58+
return cw.check_timeouts(pathlib.Path("t.yml"), doc, cw.apt_defaults())
59+
60+
61+
def run(opts: str) -> dict:
62+
return {"run": f".github/scripts/parallel-make-check.py {opts} c.json"}
63+
64+
65+
class CheckTimeouts(unittest.TestCase):
66+
def test_setup(self):
67+
self.assertEqual(errors(15, [APT]), 0)
68+
self.assertEqual(errors(14, [APT]), 1)
69+
70+
def test_run_bounds(self):
71+
ok = run("--timeout=10 --deadline=20")
72+
self.assertEqual(errors(25, [ok]), 0)
73+
self.assertEqual(errors(24, [ok]), 1)
74+
self.assertEqual(errors(45, [ok, ok]), 0)
75+
self.assertEqual(errors(44, [ok, ok]), 1)
76+
self.assertEqual(errors(60, [run("--timeout=10")]), 1)
77+
two = {"run": ok["run"] + "\n" + ok["run"]}
78+
self.assertEqual(errors(45, [two]), 0)
79+
self.assertEqual(errors(44, [two]), 1)
80+
self.assertEqual(errors(60, [{"run": run("")["run"] + "\n"
81+
+ ok["run"]}]), 1)
82+
self.assertEqual(errors(60, [run("--timeout=30 --deadline=20")]), 1)
83+
self.assertEqual(errors(60, [run("--timeout=${{ m.t }} "
84+
"--deadline=20")]), 0)
85+
86+
87+
class Deadline(unittest.TestCase):
88+
def run_pmc(self, configs: list, *opts: str,
89+
autogen: str = "") -> tuple[int, dict]:
90+
with tempfile.TemporaryDirectory() as tmp:
91+
scripts = pathlib.Path(tmp) / ".github/scripts"
92+
scripts.mkdir(parents=True)
93+
shutil.copy(SCRIPTS / "parallel-make-check.py", scripts)
94+
if autogen:
95+
script = pathlib.Path(tmp) / "autogen.sh"
96+
script.write_text(f"#!/bin/sh\n{autogen}\n")
97+
script.chmod(0o755)
98+
cfg = pathlib.Path(tmp) / "cfg.json"
99+
cfg.write_text(json.dumps(configs))
100+
out = subprocess.run(
101+
[sys.executable, str(scripts / "parallel-make-check.py"),
102+
"--threads", "2", "--timeout", "5", *opts, str(cfg)],
103+
capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"})
104+
self.stdout = out.stdout
105+
return out.returncode, dict(re.findall(
106+
r"^\| (\w+) \| (.+?) \| [\d.]+ \|$", out.stdout, re.M))
107+
108+
def config(self, name: str, minutes: float, *cmd: str) -> dict:
109+
return {"name": name, "minutes": minutes, "build": False,
110+
"run": [list(cmd)]}
111+
112+
def test_every_config_cut_off_is_labelled(self):
113+
configs = [self.config("a", 3, "sleep", "600"),
114+
self.config("b", 2, "sleep", "600"),
115+
self.config("c", 1, "sleep", "1")]
116+
for mode in ("--fail-fast", "--no-fail-fast"):
117+
with self.subTest(mode=mode):
118+
rc, got = self.run_pmc(configs, mode, "--deadline", "0.05")
119+
self.assertEqual(rc, 1)
120+
self.assertIn("run deadline in sleep 600", got["a"])
121+
self.assertIn("run deadline in sleep 600", got["b"])
122+
self.assertIn("run deadline before", got["c"])
123+
124+
def test_real_failure_is_not_a_deadline(self):
125+
configs = [self.config("bad", 3, "bash", "-c", "sleep 1; exit 1"),
126+
self.config("b", 2, "sleep", "600"),
127+
self.config("c", 1, "sleep", "1")]
128+
rc, got = self.run_pmc(configs, "--fail-fast", "--deadline", "0.05")
129+
self.assertEqual(rc, 1)
130+
self.assertIn("FAIL (bash -c sleep 1; exit 1)", got["bad"])
131+
self.assertIn("aborted", got["b"])
132+
self.assertIn("aborted", got["c"])
133+
134+
135+
def test_autogen_is_bounded(self):
136+
configs = [{"name": "a", "minutes": 1}]
137+
rc, _ = self.run_pmc(configs, "--deadline", "0.05",
138+
autogen="sleep 600")
139+
self.assertEqual(rc, 1)
140+
self.assertIn("autogen.sh hit --deadline", self.stdout)
141+
142+
143+
if __name__ == "__main__":
144+
unittest.main()

‎.github/workflows/check-source-text.yml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ name: Check Source Text
88
# * bash -n + shellcheck (warning level) on shell scripts.
99
# * check-workflows.py: every `run:` step against GitHub's 21000
1010
# character cap, past which GitHub stops loading the workflow file
11-
# altogether and its runs fail in 0s with zero jobs.
11+
# altogether and its runs fail in 0s with zero jobs, and each job's
12+
# apt setup budget and parallel-make-check.py --timeout/--deadline.
1213
# * check-ci-deps.py: every install-apt-deps call against the .deb bundle
1314
# it names, since a package missing from the bundle costs that job the
1415
# apt mirror without failing anything.
16+
# * test_ci_scripts.py: unit tests for check-workflows.py and
17+
# parallel-make-check.py.
1518
#
1619
# Scope:
1720
# * pull_request: only files changed in the PR (catches new violations
@@ -91,6 +94,9 @@ jobs:
9194
- name: Check the ci-deps bundle contract
9295
run: ./.github/scripts/check-ci-deps.py
9396

97+
- name: Test the CI scripts
98+
run: python3 -m unittest discover -s .github/scripts -p 'test_*.py'
99+
94100
- name: Run check-source-text (PR changed files)
95101
if: github.event_name == 'pull_request' && steps.files.outputs.count != '0'
96102
run: |

0 commit comments

Comments
 (0)