Skip to content

Commit 59453b9

Browse files
authored
ci: hold a CodSpeed run to the machine main's baseline was measured on (#8644)
* ci: hold a CodSpeed run to the machine main's baseline was measured on CodSpeed compares a run against a base run and refuses to call the comparison meaningful when the two ran on different machines: the runner uploads a `SystemInfo` record beside the profile carrying the OS, the architecture, the CPU's vendor id, brand and flags, the physical core count and the installed memory, and a hosted pool hands out whatever machine is free. A simulated measurement is fixed against how fast the machine is, but not against what it makes the process execute -- glibc selects `memcpy` and the string routines through IFUNC on CPU flags, a new stable rustc emits different code, and these benchmarks run each program under CPython through pyo3 as well as under RustPython, so the runner's default interpreter is an input too. `scripts/codspeed-environment.py` records those fields plus the rustc, libc and CPython versions, and compares a run against a recording. The benchmark job now restores the recording main last wrote, records over it when the ref is main, and compares against it otherwise; the install, build and measure steps carry `if: steps.environment.outputs.match != 'false'`, so a run that drew a different machine finishes green having uploaded nothing. A missing or unfetchable recording is read as "nothing to disagree with" rather than as a mismatch. Assisted-by: Claude * ci: read an unreadable environment recording as not a match A cache miss, an eviction or a cache-service outage leaves the reference file absent, and the comparison then reported `match=true`: every guarded step ran and the run uploaded a measurement without having identified the machine it was taken on. An absent recording now reports `match=false`, and says so as a `::warning` rather than the `::notice` a mismatch emits, so a job that measures nothing because it has nothing to compare against is distinguishable from one that measures nothing because the machine differs. Assisted-by: Claude
1 parent 1a71353 commit 59453b9

3 files changed

Lines changed: 341 additions & 0 deletions

File tree

‎.github/workflows/codspeed.yaml‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,31 @@ jobs:
5151
# The benchmarks are linked against libpython through the pyo3 dev-dependency.
5252
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
5353

54+
- name: Restore the machine main last measured on
55+
# A recording that cannot be fetched is read as "none yet", which the step
56+
# below treats as nothing to disagree with. Failing here instead would
57+
# turn a cache outage into a red benchmark job.
58+
continue-on-error: true
59+
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
60+
with:
61+
path: build/codspeed-environment-reference.json
62+
key: codspeed-environment-${{ runner.os }}-${{ runner.arch }}-${{ github.run_id }}
63+
restore-keys: codspeed-environment-${{ runner.os }}-${{ runner.arch }}-
64+
65+
- name: Name the machine this run drew
66+
id: environment
67+
shell: bash
68+
run: |
69+
reference=build/codspeed-environment-reference.json
70+
if [ "$GITHUB_REF" = refs/heads/main ]; then
71+
args=(--record "$reference")
72+
else
73+
args=(--record build/codspeed-environment.json --reference "$reference")
74+
fi
75+
python3 scripts/codspeed-environment.py "${args[@]}" --github-output
76+
5477
- name: Restore cache
78+
if: ${{ steps.environment.outputs.match != 'false' }}
5579
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
5680
with:
5781
path: ${{ env.CACHE_PATHS }}
@@ -60,9 +84,11 @@ jobs:
6084
continue-on-error: true
6185

6286
- name: Install cargo-codspeed
87+
if: ${{ steps.environment.outputs.match != 'false' }}
6388
run: cargo install cargo-codspeed --locked --version ^5
6489

6590
- name: Build the benchmark targets
91+
if: ${{ steps.environment.outputs.match != 'false' }}
6692
run: cargo codspeed build --locked --measurement-mode simulation -p rustpython -p rustpython-sre_engine
6793

6894
- name: Save cache
@@ -74,7 +100,15 @@ jobs:
74100
continue-on-error: true
75101

76102
- name: Run the benchmarks
103+
if: ${{ steps.environment.outputs.match != 'false' }}
77104
uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1
78105
with:
79106
mode: simulation
80107
run: cargo codspeed run -p rustpython -p rustpython-sre_engine
108+
109+
- name: Record the machine this baseline was measured on
110+
if: ${{ success() && github.ref == 'refs/heads/main' }}
111+
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
112+
with:
113+
path: build/codspeed-environment-reference.json
114+
key: codspeed-environment-${{ runner.os }}-${{ runner.arch }}-${{ github.run_id }}

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ wasm-pack.log
1616
flame-graph.html
1717
flame.txt
1818
flamescope.json
19+
/build/codspeed-environment*.json
1920
/wapm.lock
2021
/wapm_packages
2122
/.cargo/config

‎scripts/codspeed-environment.py‎

Lines changed: 306 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
#!/usr/bin/env python3
2+
"""Name the machine a CodSpeed measurement was taken on, and hold a branch to it.
3+
4+
CodSpeed reports a run as a change against a base run, and the runner uploads a
5+
description of the machine beside the profile: `SystemInfo` in
6+
`CodSpeedHQ/runner` carries the OS and its version, the architecture, the CPU's
7+
vendor id, brand and flags, the physical core count and the installed memory.
8+
When the two runs disagree on it the report says "different runtime
9+
environments detected" and the numbers below that line are not a comparison of
10+
two trees. A hosted runner pool hands out whatever machine is free, so two runs
11+
of the same workflow do not share one by construction.
12+
13+
A simulated measurement does not move with how fast the machine is -- the cache
14+
geometry the runner hands Valgrind is fixed, and two runs whose wall clock
15+
differs by half still report the same counts. It does move with what the
16+
machine makes the process execute: glibc resolves `memcpy`, `memset` and the
17+
string routines through IFUNC selectors keyed on CPU flags, so one binary has
18+
one instruction stream per selection. The toolchain is the same class of input
19+
one level up, since a new stable rustc emits different code. So is the CPython
20+
these benchmarks are linked against: `benches/execution.rs` and
21+
`benches/microbenchmarks.rs` run each program under CPython through pyo3 as well
22+
as under RustPython, and the runner's default interpreter moves with its image.
23+
24+
The rule this enforces: `main` defines the environment. Every run on it records
25+
what it measured on, and a run on any other ref measures only when it matches
26+
that recording. Anything else is skipped rather than uploaded, because an
27+
uploaded cross-environment run is published as a regression of the branch that
28+
happened to draw the other machine. A recording that cannot be read is
29+
"anything else" too: an unknown machine is not a matching one, and reading it as
30+
one would leave the guard open exactly while it has nothing to check against.
31+
32+
codspeed-environment.py --record build/codspeed-environment.json
33+
codspeed-environment.py --record CURRENT --reference REFERENCE --github-output
34+
35+
Exits 0 whether or not the environments match; the verdict is the `match`
36+
output, so the caller decides what a mismatch costs.
37+
"""
38+
39+
import argparse
40+
import hashlib
41+
import json
42+
import math
43+
import os
44+
import platform
45+
import re
46+
import subprocess
47+
import sys
48+
49+
# The fields a comparison is made over. `SystemInfo` also carries the host name
50+
# and the invoking user, which a hosted runner changes on every run and which
51+
# therefore cannot be part of a rule that any run is expected to satisfy.
52+
COMPARED_FIELDS = (
53+
"os",
54+
"arch",
55+
"cpu_vendor_id",
56+
"cpu_brand",
57+
"cpu_cores",
58+
"total_memory_gb",
59+
"cpu_flags",
60+
"rustc",
61+
"libc",
62+
"python",
63+
)
64+
65+
66+
def _command_output(argv):
67+
try:
68+
out = subprocess.run(
69+
argv, capture_output=True, text=True, check=False, timeout=60
70+
)
71+
except (OSError, subprocess.SubprocessError):
72+
return ""
73+
# A probe that fails contributes nothing rather than an error string, so a
74+
# field absent on one platform stays absent instead of becoming a value.
75+
return out.stdout.strip() if out.returncode == 0 else ""
76+
77+
78+
def _os_release():
79+
"""The distribution and its version, as `SupportedOs` spells them."""
80+
try:
81+
with open("/etc/os-release", encoding="utf-8") as handle:
82+
fields = dict(
83+
line.rstrip("\n").split("=", 1)
84+
for line in handle
85+
if "=" in line and not line.startswith("#")
86+
)
87+
except OSError:
88+
return f"{platform.system()} {platform.release()}"
89+
name = fields.get("ID", "linux").strip('"')
90+
version = fields.get("VERSION_ID", "").strip('"')
91+
return f"{name} {version}".strip()
92+
93+
94+
def _linux_cpu():
95+
with open("/proc/cpuinfo", encoding="utf-8") as handle:
96+
return parse_cpuinfo(handle.read())
97+
98+
99+
def parse_cpuinfo(text):
100+
blocks = [block for block in text.split("\n\n") if block.strip()]
101+
102+
def field(block, name):
103+
match = re.search(rf"^{name}\s*:\s*(.*)$", block, re.MULTILINE)
104+
return match.group(1).strip() if match else ""
105+
106+
first = blocks[0] if blocks else ""
107+
# Count distinct physical cores the way `sysinfo::System::physical_core_count`
108+
# does: one entry per (socket, core), so a hyperthreaded pair counts once.
109+
# aarch64 names neither, and the file ends in a machine-wide block that no
110+
# `processor` line introduces, so the fallback counts those lines instead.
111+
cores = {(field(block, "physical id"), field(block, "core id")) for block in blocks}
112+
cores.discard(("", ""))
113+
logical = len(re.findall(r"^processor\s*:", text, re.MULTILINE))
114+
# x86_64 spells the CPU's identity one way and aarch64 another; a field
115+
# missing on one architecture is constant there and carries no signal.
116+
vendor = field(first, "vendor_id") or field(first, "CPU implementer")
117+
brand = (
118+
field(first, "model name")
119+
or " ".join(
120+
field(first, name) for name in ("CPU part", "CPU variant", "CPU revision")
121+
).strip()
122+
)
123+
flags = field(first, "flags") or field(first, "Features")
124+
return {
125+
"cpu_vendor_id": vendor,
126+
"cpu_brand": brand,
127+
"cpu_cores": len(cores) or logical,
128+
"cpu_flags": sorted(flags.split()),
129+
}
130+
131+
132+
def _darwin_cpu():
133+
def sysctl(name):
134+
return _command_output(["sysctl", "-n", name])
135+
136+
flags = " ".join(
137+
sysctl(name) for name in ("machdep.cpu.features", "hw.optional.arm.caps")
138+
)
139+
return {
140+
"cpu_vendor_id": sysctl("machdep.cpu.vendor") or platform.machine(),
141+
"cpu_brand": sysctl("machdep.cpu.brand_string"),
142+
"cpu_cores": int(sysctl("hw.physicalcpu") or 0),
143+
"cpu_flags": sorted(flags.split()),
144+
}
145+
146+
147+
def _total_memory_gb():
148+
"""Installed memory in whole GiB, rounded up as `sysinfo` reports it."""
149+
try:
150+
with open("/proc/meminfo", encoding="utf-8") as handle:
151+
for line in handle:
152+
if line.startswith("MemTotal:"):
153+
return math.ceil(int(line.split()[1]) * 1024 / 1024**3)
154+
except OSError:
155+
pass
156+
size = _command_output(["sysctl", "-n", "hw.memsize"])
157+
return math.ceil(int(size) / 1024**3) if size.isdigit() else 0
158+
159+
160+
def _libc_version():
161+
"""The C library whose IFUNC selectors decide the string routines."""
162+
version = _command_output(["ldd", "--version"])
163+
return version.splitlines()[0].strip() if version else ""
164+
165+
166+
def _python_version():
167+
"""The interpreter the benchmarks measure beside RustPython.
168+
169+
Read from the process running this script rather than from a subprocess, so
170+
it names the `python3` the workflow put on PATH -- which is the one the
171+
pyo3 build resolves libpython from.
172+
"""
173+
return f"{platform.python_implementation()} {platform.python_version()}"
174+
175+
176+
def collect():
177+
cpu = _linux_cpu() if sys.platform.startswith("linux") else _darwin_cpu()
178+
environment = {
179+
"os": _os_release(),
180+
"arch": platform.machine(),
181+
"total_memory_gb": _total_memory_gb(),
182+
"rustc": _command_output(["rustc", "--version"]),
183+
"libc": _libc_version(),
184+
"python": _python_version(),
185+
**cpu,
186+
}
187+
environment["digest"] = digest(environment)
188+
return environment
189+
190+
191+
def digest(environment):
192+
payload = json.dumps(
193+
{name: environment.get(name) for name in COMPARED_FIELDS},
194+
sort_keys=True,
195+
separators=(",", ":"),
196+
)
197+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
198+
199+
200+
def differences(current, reference):
201+
return [
202+
(name, reference.get(name), current.get(name))
203+
for name in COMPARED_FIELDS
204+
if reference.get(name) != current.get(name)
205+
]
206+
207+
208+
def _render(environment):
209+
for name in COMPARED_FIELDS:
210+
value = environment.get(name)
211+
if name == "cpu_flags":
212+
value = f"{len(value)} flags"
213+
print(f" {name:<17}{value}")
214+
print(f" {'digest':<17}{environment['digest']}")
215+
216+
217+
def main(argv=None):
218+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
219+
parser.add_argument(
220+
"--record", metavar="PATH", help="write this machine's environment as JSON"
221+
)
222+
parser.add_argument(
223+
"--reference",
224+
metavar="PATH",
225+
help="compare against a previously recorded environment; a file that"
226+
" cannot be read leaves the machine unidentified, which is not a match",
227+
)
228+
parser.add_argument(
229+
"--github-output",
230+
action="store_true",
231+
help="append `match` and `digest` to $GITHUB_OUTPUT",
232+
)
233+
args = parser.parse_args(argv)
234+
235+
current = collect()
236+
print("Benchmark environment:")
237+
_render(current)
238+
239+
match = True
240+
annotation = ""
241+
if args.reference:
242+
try:
243+
with open(args.reference, encoding="utf-8") as handle:
244+
reference = json.load(handle)
245+
except (OSError, ValueError):
246+
match = False
247+
# A warning rather than a notice: a mismatch is the guard working,
248+
# while an unreadable recording means it has nothing to work from,
249+
# and a job that quietly measures nothing forever looks the same as
250+
# one that measures.
251+
annotation = (
252+
"::warning title=CodSpeed benchmarks skipped::No recording of the"
253+
" machine the comparison base was measured on could be read at"
254+
f" {args.reference}, so a measurement taken here cannot be shown"
255+
" to be comparable with it."
256+
)
257+
print(f"\nNo reference environment at {args.reference}.")
258+
else:
259+
moved = differences(current, reference)
260+
if moved:
261+
match = False
262+
annotation = (
263+
"::notice title=CodSpeed benchmarks skipped::"
264+
f"This runner ({current['cpu_brand']}, {current['digest']}) is"
265+
" not the machine the comparison base was measured on, and an"
266+
" upload from it would be published as a regression."
267+
)
268+
# Digest the reference's own fields rather than reading back the
269+
# digest stored beside them, so a recording written by an older
270+
# field set is named by what it actually holds.
271+
print(
272+
f"\nThis machine is not the one the reference was taken on"
273+
f" ({digest(reference)} -> {current['digest']}):"
274+
)
275+
for name, was, now in moved:
276+
if name == "cpu_flags":
277+
was_set, now_set = set(was or ()), set(now or ())
278+
was = " ".join(sorted(was_set - now_set)) or "-"
279+
now = " ".join(sorted(now_set - was_set)) or "-"
280+
print(f" {name}: {was} -> {now}")
281+
else:
282+
print(f"\nThis machine matches the reference ({current['digest']}).")
283+
284+
if args.record:
285+
directory = os.path.dirname(args.record)
286+
if directory:
287+
os.makedirs(directory, exist_ok=True)
288+
with open(args.record, "w", encoding="utf-8") as handle:
289+
json.dump(current, handle, indent=2, sort_keys=True)
290+
handle.write("\n")
291+
292+
if args.github_output:
293+
# A skipped job is otherwise indistinguishable from one that never had
294+
# benchmarks, and the reason is the one fact a reader needs.
295+
if annotation:
296+
print(annotation)
297+
output = os.environ.get("GITHUB_OUTPUT")
298+
if output:
299+
with open(output, "a", encoding="utf-8") as handle:
300+
handle.write(f"match={'true' if match else 'false'}\n")
301+
handle.write(f"digest={current['digest']}\n")
302+
return 0
303+
304+
305+
if __name__ == "__main__":
306+
sys.exit(main())

0 commit comments

Comments
 (0)