diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 671402b..30b6018 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -20,6 +20,8 @@ jobs: run: cargo fmt --check - name: Last-attempt badge checks run: python3 ci/test-last-attempt-badge.py + - name: Benchmark history checks + run: python3 ci/test-bench-history.py - name: Quality run: cargo clippy --all-targets --locked -- -D warnings - name: Build @@ -47,6 +49,10 @@ jobs: run: | CARGO_TARGET_DIR=target/coverage-bench cargo llvm-cov --json \ --output-path coverage/bench.json --locked -- --ignored + - name: Load previous main benchmark measurement + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/bench_history.py prepare - name: Generate measured badges run: | python3 ci/metrics.py --tests-output tests-current.txt \ @@ -64,6 +70,14 @@ jobs: env: GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} run: python3 ci/publish-metrics.py + - name: Record private benchmark history + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/bench_history.py publish + - uses: actions/upload-artifact@v4 + with: + name: alkane-os-benchmark-site-preview + path: bench-site/index.html - name: Pairing and simulator conformance run: python3 ci/check-conformance.py - name: Select release version diff --git a/ci/badge_store.py b/ci/badge_store.py index 679c917..bc3250d 100644 --- a/ci/badge_store.py +++ b/ci/badge_store.py @@ -21,12 +21,12 @@ def request_json(url: str, token: str, method: str = "GET", def publish_file(api: str, repo: str, filename: str, data: bytes, - token: str, message: str) -> None: + token: str, message: str, max_bytes: int = 65_536) -> None: if not filename or filename.startswith("/") or any( part in ("", ".", "..") for part in filename.split("/")): raise ValueError("invalid badge path") - if len(data) > 65_536: - raise ValueError("badge artifact exceeds 64 KiB") + if len(data) > max_bytes: + raise ValueError("artifact exceeds size limit") path = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}" encoded = base64.b64encode(data).decode("ascii") for attempt in range(3): diff --git a/ci/bench_history.py b/ci/bench_history.py new file mode 100644 index 0000000..8591779 --- /dev/null +++ b/ci/bench_history.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Keep measured main-branch benchmarks in the private CI artifact branch.""" + +import argparse +import base64 +from datetime import datetime, timezone +import html +import json +import math +import os +from pathlib import Path +import re +import subprocess +from urllib.error import HTTPError +from urllib.parse import quote + +from badge_store import BADGE_BRANCH, publish_file, request_json + +INDEX = "history/index.json" +MAX_INDEX_ENTRIES = 50 + + +def read_artifact(api: str, repo: str, token: str, filename: str): + url = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}?ref={BADGE_BRANCH}" + try: + value = request_json(url, token) + except HTTPError as error: + if error.code == 404: + return None + raise + return json.loads(base64.b64decode(value["content"])) + + +def valid_benches(metrics: dict) -> dict[str, float]: + values = metrics.get("bench_ns_per_op") + if not isinstance(values, dict) or not values: + raise ValueError("benchmark measurements are missing") + if any(not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key) + or not isinstance(value, (float, int)) or isinstance(value, bool) + or not math.isfinite(value) or value <= 0 for key, value in values.items()): + raise ValueError("benchmark measurements are invalid") + return values + + +def git_distance(ancestor: str, sha: str) -> int | None: + result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"), + capture_output=True, text=True, check=False) + if result.returncode != 0: + return None + ancestor_check = subprocess.run(("git", "merge-base", "--is-ancestor", ancestor, sha), + capture_output=True, check=False) + return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None + + +def previous_measurement(index: dict, sha: str, distance=None) -> dict: + distance = distance or git_distance + choices = [] + for entry in index.get("entries", []): + ancestor = entry.get("sha") + if ancestor == sha or not isinstance(ancestor, str): + continue + gap = distance(ancestor, sha) + if gap is not None and gap > 0: + choices.append((gap, entry)) + if not choices: + return {} + return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"]) + + +def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict: + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("invalid commit SHA") + valid_benches(metrics) + entries = [entry for entry in index.get("entries", []) if entry.get("sha") != sha] + entries.append({"sha": sha, "timestamp": timestamp, "metrics": metrics}) + return {"schema": 1, "entries": entries[-MAX_INDEX_ENTRIES:]} + + +def render_html(index: dict) -> str: + entries = list(reversed(index.get("entries", []))) + names = sorted({name for entry in entries + for name in valid_benches(entry["metrics"])}) + rows = [] + for entry in entries: + sha = entry["sha"] + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("invalid commit SHA in history") + cells = [f'
Measured on main CI. Lower ns/op is faster. Results depend on runner load and are " + "not board performance. A new benchmark has no earlier comparison.
" + f"Most recent {len(entries)} measured commits. Full per-commit JSON is retained " + "in the private ci-badges branch.
" + f"| Commit | " + f"UTC | {headings}
|---|