Merge pull request 7: ci benchmark input context
This commit is contained in:
+70
-9
@@ -15,6 +15,7 @@ import subprocess
|
|||||||
import importlib.util
|
import importlib.util
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
import yaml
|
||||||
|
|
||||||
from badge_store import BADGE_BRANCH, publish_file, request_json
|
from badge_store import BADGE_BRANCH, publish_file, request_json
|
||||||
from bench_host import identity as benchmark_host
|
from bench_host import identity as benchmark_host
|
||||||
@@ -26,6 +27,12 @@ bench_spec.loader.exec_module(bench_badge)
|
|||||||
|
|
||||||
INDEX = "history/index.json"
|
INDEX = "history/index.json"
|
||||||
MAX_INDEX_ENTRIES = 50
|
MAX_INDEX_ENTRIES = 50
|
||||||
|
BENCH_INPUT_PATHS = (
|
||||||
|
"Cargo.toml", "Cargo.lock", ".cargo", "crates", "thirdparty", "vendor",
|
||||||
|
"rust-toolchain.toml", "ci/bench-badge.py", "ci/bench_host.py",
|
||||||
|
"ci/ensure-build-deps.sh", "ci/ensure-wx-prefix.sh",
|
||||||
|
"ci/configure-rust-cache.sh", "ci/wx-cache-key.sh",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def read_artifact(api: str, repo: str, token: str, filename: str):
|
def read_artifact(api: str, repo: str, token: str, filename: str):
|
||||||
@@ -51,6 +58,8 @@ def valid_benches(metrics: dict) -> dict[str, float]:
|
|||||||
|
|
||||||
|
|
||||||
def git_distance(ancestor: str, sha: str) -> int | None:
|
def git_distance(ancestor: str, sha: str) -> int | None:
|
||||||
|
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
|
||||||
|
return None
|
||||||
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
|
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
|
||||||
capture_output=True, text=True, check=False)
|
capture_output=True, text=True, check=False)
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
@@ -60,7 +69,7 @@ def git_distance(ancestor: str, sha: str) -> int | None:
|
|||||||
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
|
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
|
||||||
|
|
||||||
|
|
||||||
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
|
def previous_entry(index: dict, sha: str, distance=None, host=None) -> dict | None:
|
||||||
distance = distance or git_distance
|
distance = distance or git_distance
|
||||||
choices = []
|
choices = []
|
||||||
for entry in index.get("entries", []):
|
for entry in index.get("entries", []):
|
||||||
@@ -73,8 +82,41 @@ def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dic
|
|||||||
if gap is not None and gap > 0:
|
if gap is not None and gap > 0:
|
||||||
choices.append((gap, entry))
|
choices.append((gap, entry))
|
||||||
if not choices:
|
if not choices:
|
||||||
return {}
|
return None
|
||||||
return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"])
|
return min(choices, key=lambda item: item[0])[1]
|
||||||
|
|
||||||
|
|
||||||
|
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
|
||||||
|
entry = previous_entry(index, sha, distance, host)
|
||||||
|
return valid_benches(entry["metrics"]) if entry else {}
|
||||||
|
|
||||||
|
|
||||||
|
def benchmark_build_settings(sha: str, root: Path | str = ".") -> dict:
|
||||||
|
source = subprocess.check_output(
|
||||||
|
("git", "show", f"{sha}:.gitea/workflows/release.yml"),
|
||||||
|
cwd=root, text=True)
|
||||||
|
job = yaml.load(source, Loader=yaml.BaseLoader)["jobs"]["release"]
|
||||||
|
commands = {step.get("name", ""): step.get("run") for step in job["steps"]}
|
||||||
|
selected = ("Install build dependencies", "Configure bounded Rust compiler cache",
|
||||||
|
"Build wxWidgets (once, then cached)", "Build release", "Microbenchmarks")
|
||||||
|
return {"image": job["container"]["image"], "env": job.get("env", {}),
|
||||||
|
"commands": {name: commands.get(name) for name in selected}}
|
||||||
|
|
||||||
|
|
||||||
|
def same_benchmark_inputs(ancestor: str, sha: str, root: Path | str = ".") -> bool:
|
||||||
|
"""Identify changes that only reroute CI without changing benchmark inputs."""
|
||||||
|
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
|
||||||
|
raise ValueError("invalid benchmark comparison commit")
|
||||||
|
diff = subprocess.run(("git", "diff", "--quiet", ancestor, sha, "--",
|
||||||
|
*BENCH_INPUT_PATHS), cwd=root, check=False)
|
||||||
|
if diff.returncode not in (0, 1):
|
||||||
|
raise ValueError("cannot inspect benchmark input changes")
|
||||||
|
if diff.returncode == 1:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return benchmark_build_settings(ancestor, root) == benchmark_build_settings(sha, root)
|
||||||
|
except (KeyError, TypeError, subprocess.CalledProcessError, yaml.YAMLError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
|
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
|
||||||
@@ -101,6 +143,12 @@ def render_html(index: dict) -> str:
|
|||||||
host = entry["metrics"].get("bench_host", {})
|
host = entry["metrics"].get("bench_host", {})
|
||||||
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
|
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
|
||||||
cells.append(f'<td>{html.escape(str(host_label))}</td>')
|
cells.append(f'<td>{html.escape(str(host_label))}</td>')
|
||||||
|
context = entry["metrics"].get("bench_context", {})
|
||||||
|
if isinstance(context, dict) and context.get("schema") == 1:
|
||||||
|
context_label = "same inputs" if context.get("same_inputs") else "changed inputs"
|
||||||
|
else:
|
||||||
|
context_label = "unclassified"
|
||||||
|
cells.append(f'<td>{context_label}</td>')
|
||||||
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
|
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
|
||||||
for name in names]
|
for name in names]
|
||||||
rows.append("<tr>" + "".join(cells) + "</tr>")
|
rows.append("<tr>" + "".join(cells) + "</tr>")
|
||||||
@@ -115,12 +163,14 @@ def render_html(index: dict) -> str:
|
|||||||
"th{background:#edf2f6;position:sticky;top:0}a{color:#145a9a}"
|
"th{background:#edf2f6;position:sticky;top:0}a{color:#145a9a}"
|
||||||
".scroll{overflow-x:auto}small{color:#55616d}</style></head><body>"
|
".scroll{overflow-x:auto}small{color:#55616d}</style></head><body>"
|
||||||
"<h1>Alkane Toolkit microbenchmarks</h1>"
|
"<h1>Alkane Toolkit microbenchmarks</h1>"
|
||||||
"<p>Measured on main CI. Lower ns/op is faster. Results depend on runner load and are "
|
"<p>Measured on main CI. Lower ns/op is faster. Runner load affects results. "
|
||||||
"not board performance. A new benchmark has no earlier comparison.</p>"
|
"Same inputs marks a repeat of the benchmark source and build settings. "
|
||||||
|
"A new benchmark has no earlier comparison.</p>"
|
||||||
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
|
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
|
||||||
"in the private ci-badges branch.</small></p>"
|
"in the private ci-badges branch.</small></p>"
|
||||||
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
|
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
|
||||||
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>{headings}</tr></thead><tbody>{''.join(rows)}"
|
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>"
|
||||||
|
f"<th scope=\"col\">Inputs</th>{headings}</tr></thead><tbody>{''.join(rows)}"
|
||||||
"</tbody></table></div></body></html>\n")
|
"</tbody></table></div></body></html>\n")
|
||||||
|
|
||||||
|
|
||||||
@@ -136,10 +186,16 @@ def main() -> None:
|
|||||||
if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
|
if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
|
||||||
raise ValueError("unsupported benchmark history index")
|
raise ValueError("unsupported benchmark history index")
|
||||||
if args.action == "prepare":
|
if args.action == "prepare":
|
||||||
baseline = previous_measurement(index, sha, host=benchmark_host())
|
entry = previous_entry(index, sha, host=benchmark_host())
|
||||||
|
baseline = valid_benches(entry["metrics"]) if entry else {}
|
||||||
|
same_inputs = same_benchmark_inputs(entry["sha"], sha) if entry else False
|
||||||
Path("badges").mkdir(exist_ok=True)
|
Path("badges").mkdir(exist_ok=True)
|
||||||
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
||||||
print(f"Loaded {len(baseline)} prior benchmark measurements")
|
Path("badges/bench-context.json").write_text(
|
||||||
|
json.dumps({"schema": 1, "same_inputs": same_inputs,
|
||||||
|
"baseline_sha": entry["sha"] if entry else None}) + "\n")
|
||||||
|
print(f"Loaded {len(baseline)} prior benchmark measurements; "
|
||||||
|
f"same inputs: {str(same_inputs).lower()}")
|
||||||
return
|
return
|
||||||
if args.action == "render":
|
if args.action == "render":
|
||||||
if not index["entries"]:
|
if not index["entries"]:
|
||||||
@@ -148,8 +204,13 @@ def main() -> None:
|
|||||||
Path("bench-site/index.html").write_text(render_html(index))
|
Path("bench-site/index.html").write_text(render_html(index))
|
||||||
print(f"Rendered {len(index['entries'])} measured benchmark commits")
|
print(f"Rendered {len(index['entries'])} measured benchmark commits")
|
||||||
return
|
return
|
||||||
|
context = json.loads(Path("badges/bench-context.json").read_text())
|
||||||
|
if (not isinstance(context, dict) or context.get("schema") != 1 or
|
||||||
|
not isinstance(context.get("same_inputs"), bool)):
|
||||||
|
raise ValueError("invalid benchmark comparison context")
|
||||||
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
|
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
|
||||||
Path("bench-current.txt").read_text())), "bench_host": benchmark_host()}
|
Path("bench-current.txt").read_text())), "bench_host": benchmark_host(),
|
||||||
|
"bench_context": context}
|
||||||
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
index = updated_index(index, sha, metrics, timestamp)
|
index = updated_index(index, sha, metrics, timestamp)
|
||||||
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
|
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import sys
|
|||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
|
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
|
||||||
FILES = ("bench-current.txt",)
|
FILES = ("bench-current.txt",)
|
||||||
|
BADGE_FILES = ("bench-baseline.json", "bench-context.json")
|
||||||
|
|
||||||
|
|
||||||
def cleanup() -> None:
|
def cleanup() -> None:
|
||||||
@@ -32,6 +33,16 @@ def cleanup() -> None:
|
|||||||
if path.is_file():
|
if path.is_file():
|
||||||
path.unlink()
|
path.unlink()
|
||||||
print(f"Removed generated file: {name}")
|
print(f"Removed generated file: {name}")
|
||||||
|
badge_dir = ROOT / "badges"
|
||||||
|
if badge_dir.is_symlink():
|
||||||
|
raise ValueError("unsafe generated badge directory")
|
||||||
|
for name in BADGE_FILES:
|
||||||
|
path = badge_dir / name
|
||||||
|
if path.is_symlink() or path.parent.resolve() != badge_dir.resolve():
|
||||||
|
raise ValueError(f"unsafe generated badge file: {path}")
|
||||||
|
if path.is_file():
|
||||||
|
path.unlink()
|
||||||
|
print(f"Removed generated badge file: {name}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+15
-2
@@ -11,8 +11,10 @@ Metrics not passed on the command line are computed here (LOC from the source
|
|||||||
tree, dependency count from Cargo.lock, license from Cargo.toml).
|
tree, dependency count from Cargo.lock, license from Cargo.toml).
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
import math
|
import math
|
||||||
import os
|
import os
|
||||||
|
from pathlib import Path
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@@ -196,6 +198,14 @@ def main() -> int:
|
|||||||
write("bench-coverage", "bench coverage",
|
write("bench-coverage", "bench coverage",
|
||||||
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
|
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
|
||||||
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
|
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
|
||||||
|
context_path = Path(args.root) / args.out / "bench-context.json"
|
||||||
|
same_inputs = False
|
||||||
|
if context_path.is_file():
|
||||||
|
context = json.loads(context_path.read_text())
|
||||||
|
if (not isinstance(context, dict) or context.get("schema") != 1 or
|
||||||
|
not isinstance(context.get("same_inputs"), bool)):
|
||||||
|
raise ValueError("invalid benchmark comparison context")
|
||||||
|
same_inputs = context["same_inputs"]
|
||||||
# Bench badge: prefer the mean per-benchmark improvement vs the previous
|
# Bench badge: prefer the mean per-benchmark improvement vs the previous
|
||||||
# release. Use the static label when no comparison is available.
|
# release. Use the static label when no comparison is available.
|
||||||
delta = None
|
delta = None
|
||||||
@@ -206,8 +216,11 @@ def main() -> int:
|
|||||||
delta = None
|
delta = None
|
||||||
if delta is not None:
|
if delta is not None:
|
||||||
# Positive = faster than the previous release.
|
# Positive = faster than the previous release.
|
||||||
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
|
msg = f"{'+' if delta > 0 else ''}{delta:.1f}%"
|
||||||
write("bench", "bench", msg, bench_color(delta))
|
if same_inputs:
|
||||||
|
write("bench", "bench", msg + " same inputs", "lightgrey")
|
||||||
|
else:
|
||||||
|
write("bench", "bench", msg + " vs prev", bench_color(delta))
|
||||||
elif args.bench_delta == "NEW":
|
elif args.bench_delta == "NEW":
|
||||||
write("bench", "bench", "baseline set", "blue")
|
write("bench", "bench", "baseline set", "blue")
|
||||||
elif args.bench is not None:
|
elif args.bench is not None:
|
||||||
|
|||||||
@@ -3,11 +3,15 @@
|
|||||||
"""Exercise benchmark history selection and safe site rendering."""
|
"""Exercise benchmark history selection and safe site rendering."""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
from bench_history import bench_badge, previous_measurement, render_html, updated_index
|
from bench_history import (bench_badge, git_distance, previous_measurement, render_html,
|
||||||
|
same_benchmark_inputs, updated_index)
|
||||||
|
|
||||||
|
|
||||||
class HistoryTests(unittest.TestCase):
|
class HistoryTests(unittest.TestCase):
|
||||||
@@ -41,6 +45,7 @@ class HistoryTests(unittest.TestCase):
|
|||||||
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
|
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
|
||||||
|
|
||||||
def test_invalid_measurement_and_sha_rejected(self):
|
def test_invalid_measurement_and_sha_rejected(self):
|
||||||
|
self.assertIsNone(git_distance("--bad", "a" * 40))
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
|
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
@@ -56,14 +61,69 @@ class HistoryTests(unittest.TestCase):
|
|||||||
{"hash": 10.0})
|
{"hash": 10.0})
|
||||||
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
|
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
|
||||||
|
|
||||||
|
def test_routing_change_is_marked_same_inputs_but_code_or_build_change_is_not(self):
|
||||||
|
with tempfile.TemporaryDirectory(prefix="alkane-bench-inputs-") as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
workflow = root / ".gitea/workflows/release.yml"
|
||||||
|
workflow.parent.mkdir(parents=True)
|
||||||
|
code = root / "crates/alkane-gui/src/main.rs"
|
||||||
|
code.parent.mkdir(parents=True)
|
||||||
|
code.write_text("fn main() {}\n")
|
||||||
|
workflow.write_text(
|
||||||
|
"jobs:\n release:\n runs-on: alkane-verify\n"
|
||||||
|
" container:\n image: pinned-image\n"
|
||||||
|
" env:\n RUSTFLAGS: stable\n steps:\n"
|
||||||
|
" - name: Build release\n run: cargo build --release\n"
|
||||||
|
" - name: Microbenchmarks\n run: cargo test --release bench_\n")
|
||||||
|
|
||||||
|
def git(*args):
|
||||||
|
return subprocess.check_output(("git", "-C", str(root), *args),
|
||||||
|
text=True, stderr=subprocess.DEVNULL).strip()
|
||||||
|
|
||||||
|
git("init", "-q")
|
||||||
|
git("config", "user.name", "CI Test")
|
||||||
|
git("config", "user.email", "ci@example.invalid")
|
||||||
|
git("add", ".")
|
||||||
|
git("commit", "-qm", "base")
|
||||||
|
base = git("rev-parse", "HEAD")
|
||||||
|
workflow.write_text(workflow.read_text().replace("alkane-verify", "alkane-ci"))
|
||||||
|
git("commit", "-qam", "route")
|
||||||
|
route = git("rev-parse", "HEAD")
|
||||||
|
self.assertTrue(same_benchmark_inputs(base, route, root))
|
||||||
|
code.write_text("fn main() { println!(\"changed\"); }\n")
|
||||||
|
git("commit", "-qam", "code")
|
||||||
|
changed_code = git("rev-parse", "HEAD")
|
||||||
|
self.assertFalse(same_benchmark_inputs(route, changed_code, root))
|
||||||
|
workflow.write_text(workflow.read_text().replace("RUSTFLAGS: stable", "RUSTFLAGS: tuned"))
|
||||||
|
git("commit", "-qam", "flags")
|
||||||
|
flags = git("rev-parse", "HEAD")
|
||||||
|
self.assertFalse(same_benchmark_inputs(changed_code, flags, root))
|
||||||
|
|
||||||
|
def test_badge_keeps_raw_delta_and_marks_identical_inputs(self):
|
||||||
|
with tempfile.TemporaryDirectory(prefix="alkane-bench-badge-context-") as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
badges = root / "badges"
|
||||||
|
badges.mkdir()
|
||||||
|
(badges / "bench-context.json").write_text(
|
||||||
|
json.dumps({"schema": 1, "same_inputs": True, "baseline_sha": "a" * 40}))
|
||||||
|
command = (sys.executable, str(Path(__file__).with_name("gen-badges.py")),
|
||||||
|
"--root", str(root), "--bench-delta=-36.4")
|
||||||
|
subprocess.run(command, check=True, capture_output=True)
|
||||||
|
self.assertIn("-36.4% same inputs", (badges / "bench.svg").read_text())
|
||||||
|
(badges / "bench-context.json").unlink()
|
||||||
|
subprocess.run(command, check=True, capture_output=True)
|
||||||
|
self.assertIn("-36.4% vs prev", (badges / "bench.svg").read_text())
|
||||||
|
|
||||||
def test_site_escapes_history_content(self):
|
def test_site_escapes_history_content(self):
|
||||||
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
|
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
|
||||||
"metrics": {"bench_ns_per_op": {"hash": 10.0},
|
"metrics": {"bench_ns_per_op": {"hash": 10.0},
|
||||||
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
|
"bench_host": {"cpu_model": "<script>cpu</script>"},
|
||||||
|
"bench_context": {"schema": 1, "same_inputs": True}}}
|
||||||
page = render_html({"entries": [entry]})
|
page = render_html({"entries": [entry]})
|
||||||
self.assertIn("<script>", page)
|
self.assertIn("<script>", page)
|
||||||
self.assertNotIn("<script>", page)
|
self.assertNotIn("<script>", page)
|
||||||
self.assertIn("10.000", page)
|
self.assertIn("10.000", page)
|
||||||
|
self.assertIn("same inputs", page)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user