Skip to content

Commit 2e5143b

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, and a run: step that calls apt-install.sh directly adds that call with its own options. 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 2e5143b

3 files changed

Lines changed: 324 additions & 3 deletions

File tree

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

Lines changed: 165 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,24 @@
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+
APT_OPTION = re.compile(r"--(tries|budget|delay|update-timeout|"
64+
r"install-timeout)[= ]\s*['\"]?([^\s'\"\\]+)")
65+
4466

4567
def iter_run_steps(doc: object) -> list[tuple[str, str]]:
4668
"""Yield (location, script) for every `run:` step in a parsed file.
@@ -80,6 +102,145 @@ def scan_steps(steps: object, where: str) -> None:
80102
return found
81103

82104

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

277+
errors += check_timeouts(path, doc, apt_defaults())
278+
116279
return (errors, warnings, biggest)
117280

118281

119282
def main() -> int:
120283
p = argparse.ArgumentParser(
121284
description="Lint GitHub Actions workflow files for the 21000 "
122-
"character per-run-step limit.")
285+
"character per-run-step limit and job time budgets.")
123286
p.add_argument("paths", nargs="*", metavar="FILE",
124287
help="files to check (default: all workflows and "
125288
"composite actions under .github/)")
@@ -151,7 +314,7 @@ def main() -> int:
151314
print(f"checked {len(paths)} files; largest run: step is {biggest} "
152315
f"characters (limit {HARD_LIMIT})")
153316
if errors:
154-
print(f"FAILED: {errors} step(s) over the limit")
317+
print(f"FAILED: {errors} error(s)")
155318
return 1
156319
if warnings:
157320
print(f"{warnings} step(s) approaching the limit")

‎.github/scripts/test_ci_scripts.py‎

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
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_direct_apt_install(self):
71+
call = {"run": "x/apt-install.sh --tries 2 \\\n"
72+
" --warn-only --budget 600 pkg || true"}
73+
self.assertEqual(errors(13, [call]), 0)
74+
self.assertEqual(errors(12, [call]), 1)
75+
bad = {"run": 'x/apt-install.sh --tries "$N"'}
76+
self.assertEqual(errors(60, [bad]), 1)
77+
78+
def test_run_bounds(self):
79+
ok = run("--timeout=10 --deadline=20")
80+
self.assertEqual(errors(25, [ok]), 0)
81+
self.assertEqual(errors(24, [ok]), 1)
82+
self.assertEqual(errors(45, [ok, ok]), 0)
83+
self.assertEqual(errors(44, [ok, ok]), 1)
84+
self.assertEqual(errors(60, [run("--timeout=10")]), 1)
85+
two = {"run": ok["run"] + "\n" + ok["run"]}
86+
self.assertEqual(errors(45, [two]), 0)
87+
self.assertEqual(errors(44, [two]), 1)
88+
self.assertEqual(errors(60, [{"run": run("")["run"] + "\n"
89+
+ ok["run"]}]), 1)
90+
self.assertEqual(errors(60, [run("--timeout=30 --deadline=20")]), 1)
91+
self.assertEqual(errors(60, [run("--timeout=${{ m.t }} "
92+
"--deadline=20")]), 0)
93+
94+
95+
class Deadline(unittest.TestCase):
96+
def run_pmc(self, configs: list, *opts: str,
97+
autogen: str = "") -> tuple[int, dict]:
98+
with tempfile.TemporaryDirectory() as tmp:
99+
scripts = pathlib.Path(tmp) / ".github/scripts"
100+
scripts.mkdir(parents=True)
101+
shutil.copy(SCRIPTS / "parallel-make-check.py", scripts)
102+
if autogen:
103+
script = pathlib.Path(tmp) / "autogen.sh"
104+
script.write_text(f"#!/bin/sh\n{autogen}\n")
105+
script.chmod(0o755)
106+
cfg = pathlib.Path(tmp) / "cfg.json"
107+
cfg.write_text(json.dumps(configs))
108+
out = subprocess.run(
109+
[sys.executable, str(scripts / "parallel-make-check.py"),
110+
"--threads", "2", "--timeout", "5", *opts, str(cfg)],
111+
capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"})
112+
self.stdout = out.stdout
113+
return out.returncode, dict(re.findall(
114+
r"^\| (\w+) \| (.+?) \| [\d.]+ \|$", out.stdout, re.M))
115+
116+
def config(self, name: str, minutes: float, *cmd: str) -> dict:
117+
return {"name": name, "minutes": minutes, "build": False,
118+
"run": [list(cmd)]}
119+
120+
def test_every_config_cut_off_is_labelled(self):
121+
configs = [self.config("a", 3, "sleep", "600"),
122+
self.config("b", 2, "sleep", "600"),
123+
self.config("c", 1, "sleep", "1")]
124+
for mode in ("--fail-fast", "--no-fail-fast"):
125+
with self.subTest(mode=mode):
126+
rc, got = self.run_pmc(configs, mode, "--deadline", "0.05")
127+
self.assertEqual(rc, 1)
128+
self.assertIn("run deadline in sleep 600", got["a"])
129+
self.assertIn("run deadline in sleep 600", got["b"])
130+
self.assertIn("run deadline before", got["c"])
131+
132+
def test_real_failure_is_not_a_deadline(self):
133+
configs = [self.config("bad", 3, "bash", "-c", "sleep 1; exit 1"),
134+
self.config("b", 2, "sleep", "600"),
135+
self.config("c", 1, "sleep", "1")]
136+
rc, got = self.run_pmc(configs, "--fail-fast", "--deadline", "0.05")
137+
self.assertEqual(rc, 1)
138+
self.assertIn("FAIL (bash -c sleep 1; exit 1)", got["bad"])
139+
self.assertIn("aborted", got["b"])
140+
self.assertIn("aborted", got["c"])
141+
142+
143+
def test_autogen_is_bounded(self):
144+
configs = [{"name": "a", "minutes": 1}]
145+
rc, _ = self.run_pmc(configs, "--deadline", "0.05",
146+
autogen="sleep 600")
147+
self.assertEqual(rc, 1)
148+
self.assertIn("autogen.sh hit --deadline", self.stdout)
149+
150+
151+
if __name__ == "__main__":
152+
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)