Compare commits

...
5 Commits
10 changed files with 215 additions and 22 deletions
+34
View File
@@ -0,0 +1,34 @@
name: public-benchmark-pages
on:
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
group: alkane-toolkit-public-benchmark-pages
cancel-in-progress: false
jobs:
publish:
runs-on: alkane-pages
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- name: Render measured benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py render
- name: Publish public benchmark page
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
run: python3 ci/publish-bench-pages.py toolkit
- name: Clean generated page
if: always()
run: python3 ci/cleanup-generated.py
+4
View File
@@ -4,6 +4,10 @@ on:
push: push:
branches: [next] branches: [next]
concurrency:
group: alkane-toolkit-next
cancel-in-progress: false
permissions: permissions:
contents: write contents: write
+4 -1
View File
@@ -6,6 +6,10 @@ on:
push: push:
branches: [main] branches: [main]
concurrency:
group: alkane-toolkit-main
cancel-in-progress: false
permissions: permissions:
contents: write contents: write
actions: write actions: write
@@ -108,7 +112,6 @@ jobs:
with: with:
name: alkane-toolkit-benchmark-site-preview name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html path: bench-site/index.html
- name: Headless UI self-test - name: Headless UI self-test
run: | run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends \ apt-get update -qq && apt-get install -y -qq --no-install-recommends \
+2
View File
@@ -57,6 +57,8 @@ publishes qualifying releases; `next` builds `-rc` candidates. Badges
report host tests and benchmarks, not installation support. Benchmark report host tests and benchmarks, not installation support. Benchmark
comparisons require the same CPU class. The code quality letter reports the comparisons require the same CPU class. The code quality letter reports the
Clippy gate; the separate coverage badge reports exercised lines. Clippy gate; the separate coverage badge reports exercised lines.
The [benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/toolkit/)
is readable without a Gitea login.
## Firmware safety ## Firmware safety
+18 -8
View File
@@ -48,6 +48,18 @@ def require_suite(results: dict) -> dict:
return results return results
def benchmark_delta(current: dict, baseline: dict) -> float | None:
"""Average each comparable benchmark's percentage improvement."""
if not baseline:
return None
changes = [(baseline[name] - current[name]) / baseline[name]
for name in baseline]
delta = math.fsum(changes) / len(changes) * 100
if not math.isfinite(delta):
raise ValueError("benchmark comparison is not finite")
return delta
def main() -> int: def main() -> int:
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("--current", required=True, help="captured bench stdout") ap.add_argument("--current", required=True, help="captured bench stdout")
@@ -79,14 +91,12 @@ def main() -> int:
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr) print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
return 1 return 1
common = list(baseline) try:
if common: delta = benchmark_delta(current, baseline)
sum_new = sum(current[k] for k in common) except ValueError as error:
sum_old = sum(baseline[k] for k in common) print(f"bench-badge: {error}", file=sys.stderr)
delta = (sum_new / sum_old - 1.0) * 100.0 if sum_old > 0 else 0.0 return 1
print(f"{delta:.1f}") print("NEW" if delta is None else f"{delta:.1f}")
else:
print("NEW")
if not args.no_write: if not args.no_write:
os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True) os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True)
+8 -1
View File
@@ -126,7 +126,7 @@ def render_html(index: dict) -> str:
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("prepare", "publish")) parser.add_argument("action", choices=("prepare", "publish", "render"))
args = parser.parse_args() args = parser.parse_args()
api = os.environ["GITHUB_API_URL"].rstrip("/") api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"] repo = os.environ["GITHUB_REPOSITORY"]
@@ -141,6 +141,13 @@ def main() -> None:
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") print(f"Loaded {len(baseline)} prior benchmark measurements")
return return
if args.action == "render":
if not index["entries"]:
raise ValueError("no measured benchmark history to publish")
Path("bench-site").mkdir(exist_ok=True)
Path("bench-site/index.html").write_text(render_html(index))
print(f"Rendered {len(index['entries'])} measured benchmark commits")
return
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()}
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
+1 -1
View File
@@ -9,7 +9,7 @@ import sys
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage") DIRECTORIES = ("target", "dist", "coverage", "bench-site")
FILES = ("bench-current.txt",) FILES = ("bench-current.txt",)
+10 -11
View File
@@ -108,13 +108,13 @@ def loc_color(n: int) -> str:
def bench_color(delta_pct: float) -> str: def bench_color(delta_pct: float) -> str:
# Negative delta = faster than the previous release. A +/-2% dead band absorbs # Positive delta means faster than the previous release. A +/-2% band
# the run-to-run jitter of microbenchmarks on a shared CI runner. # absorbs run-to-run jitter on the dedicated CI runner.
if delta_pct <= -2.0: if delta_pct >= 2.0:
return "brightgreen" return "brightgreen"
if delta_pct < 2.0: if delta_pct > -2.0:
return "blue" return "blue"
if delta_pct < 10.0: if delta_pct > -10.0:
return "yellow" return "yellow"
return "orange" return "orange"
@@ -161,9 +161,8 @@ def main() -> int:
ap.add_argument("--coverage", type=float, default=None) ap.add_argument("--coverage", type=float, default=None)
ap.add_argument("--bench-coverage", type=float, default=None) ap.add_argument("--bench-coverage", type=float, default=None)
ap.add_argument("--bench", default=None) ap.add_argument("--bench", default=None)
# Weighted-average microbench delta vs the previous release, as a signed # Mean per-benchmark improvement vs the previous release, as a signed
# percentage string (e.g. "-3.2"), or "NEW"/"" when there is no baseline yet # percentage string, or "NEW" when there is no baseline.
# (round 19 #1). Takes precedence over --bench for the bench badge.
ap.add_argument("--bench-delta", default=None) ap.add_argument("--bench-delta", default=None)
ap.add_argument("--clippy", choices=("clean", "failed")) ap.add_argument("--clippy", choices=("clean", "failed"))
args = ap.parse_args() args = ap.parse_args()
@@ -197,8 +196,8 @@ 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")
# Bench badge: prefer the weighted-average delta vs the previous release; fall # Bench badge: prefer the mean per-benchmark improvement vs the previous
# back to the static label (first run, or when the delta could not be computed). # release. Use the static label when no comparison is available.
delta = None delta = None
if args.bench_delta not in (None, "", "NEW"): if args.bench_delta not in (None, "", "NEW"):
try: try:
@@ -206,7 +205,7 @@ def main() -> int:
except ValueError: except ValueError:
delta = None delta = None
if delta is not None: if delta is not None:
# Negative = faster than the previous release (good). # Positive = faster than the previous release.
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev" msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
write("bench", "bench", msg, bench_color(delta)) write("bench", "bench", msg, bench_color(delta))
elif args.bench_delta == "NEW": elif args.bench_delta == "NEW":
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Publish a measured benchmark page to the public, data-only Pages repo."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
import tempfile
from urllib.request import Request, urlopen
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
PAGES_HOST = "gitea.bluefla.re"
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
def run(*args: str, env: dict[str, str] | None = None,
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, env=env, cwd=cwd, text=True,
capture_output=True, check=True)
def current_main_sha() -> str:
api = os.environ["GITHUB_API_URL"].rstrip("/")
repo = os.environ["GITHUB_REPOSITORY"]
token = os.environ["GITEA_TOKEN"]
request = Request(f"{api}/repos/{repo}/branches/main",
headers={"Authorization": f"token {token}"})
with urlopen(request, timeout=20) as response:
branch = json.load(response)
return branch["commit"]["id"]
def publish(site: str) -> None:
if os.environ.get("GITHUB_REF") != "refs/heads/main":
raise ValueError("benchmark Pages publication requires main")
sha = os.environ["GITHUB_SHA"]
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
page = Path("bench-site/index.html").read_bytes()
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
raise ValueError("invalid benchmark page")
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
temporary = Path(directory)
guard_checkout = temporary / "guard"
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
GUARD_REPO, str(guard_checkout))
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
cwd=guard_checkout).stdout
guard_script = temporary / "validate_site.py"
guard_script.write_text(guard_source)
run("python3", str(guard_script), "--page", site,
str(Path("bench-site/index.html").resolve()))
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
raise ValueError("missing benchmark Pages deploy key")
key_path = temporary / "deploy_key"
key_path.write_text(key.rstrip("\n") + "\n")
key_path.chmod(0o600)
known_hosts = temporary / "known_hosts"
known_hosts.write_text(PAGES_HOST_KEY + "\n")
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
if fingerprint != PAGES_HOST_FINGERPRINT:
raise ValueError("benchmark Pages SSH host key changed")
git_env = os.environ.copy()
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
git_env["GIT_SSH_COMMAND"] = ssh_command
git_env["GIT_TERMINAL_PROMPT"] = "0"
checkout = temporary / "site"
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
PAGES_REPO, str(checkout), env=git_env)
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
for attempt in range(3):
if current_main_sha() != sha:
print("Skipping benchmark page from a superseded main commit")
return
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
cwd=checkout)
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
cwd=checkout)
destination = checkout / site / "index.html"
destination.parent.mkdir(exist_ok=True)
destination.write_bytes(page)
run("git", "add", f"{site}/index.html", cwd=checkout)
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
cwd=checkout, check=False)
if changed.returncode == 0:
print(f"{site} benchmark page is already current")
return
if changed.returncode != 1:
raise RuntimeError("cannot compare benchmark page")
run("git", "commit", "-q", "-m",
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
pushed = subprocess.run(("git", "push", "--quiet", "origin",
"HEAD:gh-pages"), env=git_env, cwd=checkout,
text=True, capture_output=True, check=False)
if pushed.returncode == 0:
print(f"Published {site} benchmark page for {sha[:10]}")
return
if attempt == 2:
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
raise RuntimeError("benchmark Pages publication did not complete")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
publish(parser.parse_args().site)
if __name__ == "__main__":
main()
+13
View File
@@ -13,6 +13,10 @@ spec = importlib.util.spec_from_file_location("bench_badge", ROOT / "ci/bench-ba
assert spec is not None and spec.loader is not None assert spec is not None and spec.loader is not None
badge = importlib.util.module_from_spec(spec) badge = importlib.util.module_from_spec(spec)
spec.loader.exec_module(badge) spec.loader.exec_module(badge)
badge_spec = importlib.util.spec_from_file_location("gen_badges", ROOT / "ci/gen-badges.py")
assert badge_spec is not None and badge_spec.loader is not None
gen_badges = importlib.util.module_from_spec(badge_spec)
badge_spec.loader.exec_module(gen_badges)
class BenchBadgeTests(unittest.TestCase): class BenchBadgeTests(unittest.TestCase):
@@ -37,6 +41,15 @@ class BenchBadgeTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "missing timing"): with self.assertRaisesRegex(ValueError, "missing timing"):
badge.parse_bench(lines[0].replace("10ms/op", "missing")) badge.parse_bench(lines[0].replace("10ms/op", "missing"))
def test_badge_averages_each_benchmark_improvement(self):
current = {"short": 50.0, "long": 900.0}
baseline = {"short": 100.0, "long": 1000.0}
self.assertEqual(badge.benchmark_delta(current, baseline), 30.0)
self.assertAlmostEqual(badge.benchmark_delta(baseline, current), -55.5555556)
self.assertIsNone(badge.benchmark_delta(current, {}))
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()