From e67ffcd204aeb710e63e730cb5a56e8bb322c8eb Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:17:23 -0600 Subject: [PATCH] Record private per-commit OS benchmark history --- .gitea/workflows/main.yml | 14 ++++ ci/badge_store.py | 6 +- ci/bench_history.py | 146 ++++++++++++++++++++++++++++++++++++++ ci/metrics.py | 3 +- ci/test-bench-history.py | 46 ++++++++++++ 5 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 ci/bench_history.py create mode 100644 ci/test-bench-history.py 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'{sha[:10]}', + f'{html.escape(entry["timestamp"])}'] + values = valid_benches(entry["metrics"]) + cells += [f'{values[name]:.3f}' if name in values else 'new' + for name in names] + rows.append("" + "".join(cells) + "") + headings = "".join(f"{html.escape(name)} (ns/op)" for name in names) + return ("\n" + "" + "Alkane OS benchmarks" + "

Alkane OS microbenchmarks

" + "

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"
" + f"{headings}{''.join(rows)}" + "
CommitUTC
\n") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=("prepare", "publish")) + args = parser.parse_args() + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + token = os.environ["GITEA_TOKEN"] + sha = os.environ["GITHUB_SHA"] + index = read_artifact(api, repo, token, INDEX) or {"schema": 1, "entries": []} + if index.get("schema") != 1 or not isinstance(index.get("entries"), list): + raise ValueError("unsupported benchmark history index") + if args.action == "prepare": + baseline = previous_measurement(index, sha) + Path("badges").mkdir(exist_ok=True) + Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n") + print(f"Loaded {len(baseline)} prior benchmark measurements") + return + metrics = json.loads(Path("badges/metrics.json").read_text()) + timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") + index = updated_index(index, sha, metrics, timestamp) + record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n" + publish_file(api, repo, f"history/{sha}.json", record, token, + "Record Alkane OS benchmarks", max_bytes=1_048_576) + publish_file(api, repo, INDEX, json.dumps(index, indent=2).encode() + b"\n", + token, "Update Alkane OS benchmark index", max_bytes=1_048_576) + Path("bench-site").mkdir(exist_ok=True) + Path("bench-site/index.html").write_text(render_html(index)) + print(f"Recorded benchmarks for {sha[:10]}") + + +if __name__ == "__main__": + main() diff --git a/ci/metrics.py b/ci/metrics.py index fc6a6e2..c86ccec 100644 --- a/ci/metrics.py +++ b/ci/metrics.py @@ -51,6 +51,7 @@ def main(): parser.add_argument("--tests-coverage", required=True) parser.add_argument("--bench-output", required=True) parser.add_argument("--bench-coverage", required=True) + parser.add_argument("--bench-baseline", default="badges/bench-baseline.json") args = parser.parse_args() test_output = pathlib.Path(args.tests_output).read_text() tests = sum(map(int, re.findall(r"test result: ok\. (\d+) passed", test_output))) @@ -59,7 +60,7 @@ def main(): current = bench_results(args.bench_output) if not current or any(value <= 0 for value in current.values()): raise SystemExit("microbenchmark result missing or zero") - base_path = pathlib.Path("badges/bench-baseline.json") + base_path = pathlib.Path(args.bench_baseline) baseline = json.loads(base_path.read_text()) if base_path.exists() else {} common = [name for name in current if name in baseline and baseline[name] > 0] delta = (sum((baseline[name] - current[name]) / baseline[name] for name in common) diff --git a/ci/test-bench-history.py b/ci/test-bench-history.py new file mode 100644 index 0000000..a8b0a29 --- /dev/null +++ b/ci/test-bench-history.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise benchmark history selection and safe site rendering.""" + +import sys +from pathlib import Path +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from bench_history import previous_measurement, render_html, updated_index + + +class HistoryTests(unittest.TestCase): + def test_retry_uses_previous_commit(self): + first = "a" * 40 + second = "b" * 40 + index = {"schema": 1, "entries": [ + {"sha": first, "timestamp": "2026-01-01T00:00:00+00:00", + "metrics": {"bench_ns_per_op": {"hash": 10.0}}}, + {"sha": second, "timestamp": "2026-01-02T00:00:00+00:00", + "metrics": {"bench_ns_per_op": {"hash": 8.0}}}]} + self.assertEqual(previous_measurement(index, second, + lambda ancestor, sha: 1 if ancestor == first else None), + {"hash": 10.0}) + updated = updated_index(index, second, {"bench_ns_per_op": {"hash": 7.5}}, + "2026-01-03T00:00:00+00:00") + self.assertEqual(len(updated["entries"]), 2) + self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5) + + def test_invalid_measurement_and_sha_rejected(self): + with self.assertRaises(ValueError): + updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now") + with self.assertRaises(ValueError): + updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now") + + def test_site_escapes_history_content(self): + entry = {"sha": "a" * 40, "timestamp": "", + "metrics": {"bench_ns_per_op": {"hash": 10.0}}} + page = render_html({"entries": [entry]}) + self.assertIn("<script>", page) + self.assertNotIn("