From c18a37eebc43a68db6d855e293ac2fc6a40bf660 Mon Sep 17 00:00:00 2001 From: alkane-ci Date: Tue, 13 Oct 2026 23:27:22 +0000 Subject: [PATCH 01/99] ci: refresh README badges [skip release] --- badges/bench-baseline.json | 18 +++++++++--------- badges/bench-coverage.svg | 14 +++++++------- badges/bench.svg | 14 +++++++------- badges/loc.svg | 8 ++++---- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/badges/bench-baseline.json b/badges/bench-baseline.json index 4b5ded5d..419beab5 100644 --- a/badges/bench-baseline.json +++ b/badges/bench-baseline.json @@ -1,11 +1,11 @@ { - "bench_parse_line_near_max_addrs": 644187.0, - "bench_parse_targets_many_ranges_near_cap": 49565223.0, - "bench_render_cells": 3037944.0, - "bench_sort_by_each_column": 816884.0, - "bench_targets_to_cidrs_large_range": 443875.0, - "bench_upsert_cold_start_population": 8871040.0, - "bench_view_pipeline": 177652.0, - "bench_view_pipeline_default_sort": 203830.0, - "bench_view_pipeline_with_filter": 187371.0 + "bench_parse_line_near_max_addrs": 807160.0, + "bench_parse_targets_many_ranges_near_cap": 54465485.0, + "bench_render_cells": 3503112.0, + "bench_sort_by_each_column": 486975.0, + "bench_targets_to_cidrs_large_range": 482167.0, + "bench_upsert_cold_start_population": 8315814.0, + "bench_view_pipeline": 191794.0, + "bench_view_pipeline_default_sort": 193214.0, + "bench_view_pipeline_with_filter": 253085.0 } diff --git a/badges/bench-coverage.svg b/badges/bench-coverage.svg index 009c3f7f..ee54561c 100644 --- a/badges/bench-coverage.svg +++ b/badges/bench-coverage.svg @@ -1,19 +1,19 @@ - - bench coverage: pending + + bench coverage: 7% - + - - + + bench coverage bench coverage - pending - pending + 7% + 7% diff --git a/badges/bench.svg b/badges/bench.svg index ffe6b1d4..af5a70f0 100644 --- a/badges/bench.svg +++ b/badges/bench.svg @@ -1,19 +1,19 @@ - - bench: -79.9% vs prev + + bench: +7.4% vs prev - + - - + + bench bench - -79.9% vs prev - -79.9% vs prev + +7.4% vs prev + +7.4% vs prev diff --git a/badges/loc.svg b/badges/loc.svg index 457ba74a..7508990c 100644 --- a/badges/loc.svg +++ b/badges/loc.svg @@ -1,5 +1,5 @@ - - lines of code: 13.7k + + lines of code: 13.7K @@ -13,7 +13,7 @@ lines of code lines of code - 13.7k - 13.7k + 13.7K + 13.7K -- 2.54.0 From f89f220f3e0092b7a58ff8cecd42e30642840c86 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:04:45 -0600 Subject: [PATCH 02/99] Standardize toolkit CI badges and scoped release auth --- .gitea/workflows/ci-badge.yml | 19 ++++++ .gitea/workflows/next.yml | 5 +- .gitea/workflows/release.yml | 36 ++++------- README.md | 5 +- ci/last-attempt-badge.py | 115 ++++++++++++++++++++++++++++++++++ ci/release-rc.py | 3 +- ci/test-last-attempt-badge.py | 35 +++++++++++ 7 files changed, 191 insertions(+), 27 deletions(-) create mode 100644 .gitea/workflows/ci-badge.yml create mode 100644 ci/last-attempt-badge.py create mode 100644 ci/test-last-attempt-badge.py diff --git a/.gitea/workflows/ci-badge.yml b/.gitea/workflows/ci-badge.yml new file mode 100644 index 00000000..c2c89735 --- /dev/null +++ b/.gitea/workflows/ci-badge.yml @@ -0,0 +1,19 @@ +name: completed-ci-badge + +on: + workflow_run: + workflows: [build-test-release, next-build] + types: [completed] + +jobs: + publish: + runs-on: alkane-ci + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@v4 + - name: Publish last completed attempt + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/last-attempt-badge.py diff --git a/.gitea/workflows/next.yml b/.gitea/workflows/next.yml index 575f5c66..c98483df 100644 --- a/.gitea/workflows/next.yml +++ b/.gitea/workflows/next.yml @@ -4,6 +4,9 @@ on: push: branches: [next] +permissions: + contents: write + jobs: candidate: runs-on: alkane-ci @@ -41,5 +44,5 @@ jobs: - name: Create private prerelease if: steps.version.outputs.release == 'true' env: - GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} run: python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz" diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 3844c683..6241dc03 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -6,6 +6,10 @@ on: push: branches: [main] +permissions: + contents: write + actions: read + jobs: release: runs-on: alkane-ci @@ -27,6 +31,9 @@ jobs: - name: Test version logic run: bash ci/test-compute-version.sh + - name: Last-attempt badge checks + run: python3 ci/test-last-attempt-badge.py + - name: Install build dependencies run: | apt-get update -qq @@ -137,13 +144,10 @@ jobs: # Refresh the committed README badges from live metrics and push any change # back to main. Best-effort: a locked-down runner that can't push must not - # fail the release. A badges-only push does not bump the version (see - # compute-version.sh), so it does not loop back into another release. + # fail the release. The badge-only commit skips CI to prevent a loop. - name: Refresh badges if: steps.ver.outputs.release == 'true' continue-on-error: true - env: - TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | PASS=$(cargo test -p alkane-gui --offline 2>&1 \ | grep -hoE '[0-9]+ passed' | grep -oE '[0-9]+' | awk '{s+=$1} END{print s+0}') @@ -165,11 +169,8 @@ jobs: git config user.name "alkane-ci" git config user.email "ci@bluefla.re" git add badges - git commit -m "ci: refresh README badges [skip release]" - API="${GITHUB_API_URL:-https://gitea.bluefla.re/api/v1}" - HOST="${API%/api/v1}" - git -c http.extraheader="Authorization: token ${TOKEN}" \ - push "${HOST}/${GITHUB_REPOSITORY}.git" "HEAD:main" || echo "badge push skipped" + git commit -m "ci: refresh README badges [skip ci]" + git push origin "HEAD:main" || echo "badge push skipped" else echo "badges unchanged" fi @@ -198,21 +199,8 @@ jobs: - name: Create Gitea release + upload artifact if: steps.ver.outputs.release == 'true' env: - TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - TAG="${{ steps.ver.outputs.tag }}" - API="${GITHUB_API_URL:-https://gitea.bluefla.re/api/v1}" - REPO="${GITHUB_REPOSITORY}" - body="Automated ${{ steps.ver.outputs.bump }} release from ${GITHUB_SHA}." - rel=$(curl -sS -X POST -H "Authorization: token ${TOKEN}" -H "Content-Type: application/json" \ - "${API}/repos/${REPO}/releases" \ - -d "{\"tag_name\":\"${TAG}\",\"target_commitish\":\"${GITHUB_SHA}\",\"name\":\"${TAG}\",\"body\":\"${body}\"}") - id=$(echo "$rel" | grep -oE '"id":[0-9]+' | head -1 | cut -d: -f2) - if [ -z "$id" ]; then echo "release create failed: $rel"; exit 1; fi - curl -sS -X POST -H "Authorization: token ${TOKEN}" -H "Content-Type: application/gzip" \ - "${API}/repos/${REPO}/releases/${id}/assets?name=${{ steps.pkg.outputs.assetname }}" \ - --data-binary @"${{ steps.pkg.outputs.asset }}" | grep -oE '"browser_download_url":"[^"]+"' || true - echo "Released ${TAG}" + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/release-rc.py "${{ steps.ver.outputs.tag }}" false "${{ steps.pkg.outputs.asset }}" - name: No release needed if: steps.ver.outputs.release != 'true' diff --git a/README.md b/README.md index e446a078..8405b981 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # alkane-toolkit -[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions/workflows/release.yml/badge.svg?branch=main)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions) +[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions) ![tests](badges/tests.svg) ![coverage](badges/coverage.svg) ![bench](badges/bench.svg) @@ -10,6 +10,9 @@ ![dependencies](badges/dependencies.svg) ![license](badges/license.svg) +The CI badge shows the last completed attempt for this branch while newer +runs are queued. Its SVG is stored in a private, machine-maintained branch. + A cross-platform desktop toolkit for discovering, monitoring, and re-flashing ASIC miners. It scans a fleet over the network, shows live health and hashrate in a sortable table, and installs **stock** or **alkaneOS** firmware onto a diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py new file mode 100644 index 00000000..9352db22 --- /dev/null +++ b/ci/last-attempt-badge.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish the last completed main/next CI result to a private badge branch.""" + +import base64 +import json +import os +from pathlib import Path +from urllib.error import HTTPError +from urllib.parse import quote, urlencode +from urllib.request import Request, urlopen + + +WORKFLOWS = {"release.yml": "main", "next.yml": "next"} +BADGE_BRANCH = "ci-badges" + + +def badge(branch: str, conclusion: str, run_id: int) -> bytes: + passed = conclusion == "success" + word = "pass" if passed else "fail" + color = "#2ea043" if passed else "#d1242f" + title = f"CI {branch}: last completed attempt {word} (run {run_id})" + return (f'{title}' + '' + f'' + 'CI' + f'{word}\n').encode() + + +def request_json(url: str, token: str, method: str = "GET", + payload: dict | None = None) -> dict: + body = None if payload is None else json.dumps(payload).encode() + request = Request(url, data=body, method=method, + headers={"Authorization": f"token {token}", + "Content-Type": "application/json"}) + with urlopen(request, timeout=20) as response: + return json.load(response) + + +def latest_completed(api: str, repo: str, workflow: str, branch: str, + token: str) -> tuple[int, str]: + path = quote(workflow, safe="") + latest = None + for page in range(1, 21): + query = urlencode({"branch": branch, "limit": 50, "page": page}) + url = f"{api}/repos/{repo}/actions/workflows/{path}/runs?{query}" + runs = request_json(url, token).get("workflow_runs", []) + for run in runs: + if run.get("head_branch") != branch or run.get("status") != "completed": + continue + if run.get("conclusion") not in ("success", "failure"): + continue + candidate = (int(run["id"]), run["conclusion"]) + if latest is None or candidate[0] > latest[0]: + latest = candidate + if len(runs) < 50: + break + if latest is None: + raise RuntimeError(f"no completed {branch} run found for {workflow}") + return latest + + +def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None: + path = f"{api}/repos/{repo}/contents/{branch}.svg" + encoded = base64.b64encode(data).decode("ascii") + for attempt in range(3): + try: + current = request_json(path + "?ref=" + BADGE_BRANCH, token) + current_data = base64.b64decode(current["content"]) + if current_data == data: + return + sha = current["sha"] + method = "PUT" + except HTTPError as error: + if error.code != 404: + raise + sha = None + method = "POST" + payload = {"branch": BADGE_BRANCH, "content": encoded, + "message": f"Record completed {branch} CI attempt"} + if sha is not None: + payload["sha"] = sha + try: + request_json(path, token, method, payload) + return + except HTTPError as error: + if error.code not in (409, 422) or attempt == 2: + raise + raise RuntimeError("badge write did not complete") + + +def main() -> None: + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) + if event.get("action") != "completed": + raise RuntimeError("expected a completed workflow_run event") + run = event["workflow_run"] + workflow = run["path"].split("@", 1)[0].rsplit("/", 1)[-1] + expected_branch = WORKFLOWS.get(workflow) + if expected_branch is None or run.get("head_branch") != expected_branch: + raise RuntimeError("unexpected workflow or branch") + repo = os.environ["GITHUB_REPOSITORY"] + if event["repository"]["full_name"] != repo: + raise RuntimeError("repository mismatch") + api = os.environ["GITHUB_API_URL"].rstrip("/") + token = os.environ["GITEA_TOKEN"] + run_id, conclusion = latest_completed(api, repo, workflow, expected_branch, token) + publish(api, repo, expected_branch, badge(expected_branch, conclusion, run_id), token) + print(f"{expected_branch} badge records completed run {run_id}: {conclusion}") + + +if __name__ == "__main__": + main() diff --git a/ci/release-rc.py b/ci/release-rc.py index 5e324cd4..762c4240 100644 --- a/ci/release-rc.py +++ b/ci/release-rc.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# SPDX-License-Identifier: MIT """Create one Gitea release and attach files using the runner's scoped token.""" import json @@ -27,7 +28,7 @@ def main(): api = os.environ.get("GITHUB_API_URL", "https://gitea.bluefla.re/api/v1").rstrip("/") repo = os.environ["GITHUB_REPOSITORY"] sha = os.environ["GITHUB_SHA"] - body = f"Automated Alkane OS build from {sha}. Conformance results are in the repository." + body = f"Automated Alkane toolkit build from {sha}." metadata = { "tag_name": tag, "target_commitish": sha, diff --git a/ci/test-last-attempt-badge.py b/ci/test-last-attempt-badge.py new file mode 100644 index 00000000..80b55a8a --- /dev/null +++ b/ci/test-last-attempt-badge.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Check that queued CI runs do not displace the last completed result.""" + +import importlib.util +from pathlib import Path +from unittest.mock import patch +import xml.etree.ElementTree as ET + +path = Path(__file__).with_name("last-attempt-badge.py") +spec = importlib.util.spec_from_file_location("last_attempt_badge", path) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +def runs(_url, _token): + return {"workflow_runs": [ + {"id": 105, "head_branch": "main", "status": "completed", "conclusion": "cancelled"}, + {"id": 104, "head_branch": "main", "status": "queued", "conclusion": None}, + {"id": 103, "head_branch": "main", "status": "completed", "conclusion": "failure"}, + {"id": 102, "head_branch": "main", "status": "completed", "conclusion": "success"}, + ]} + + +with patch.object(module, "request_json", runs): + assert module.latest_completed("https://example.invalid/api/v1", "owner/repo", + "release.yml", "main", "token") == (103, "failure") + +svg = module.badge("main", "failure", 103) +root = ET.fromstring(svg) +assert root.attrib["aria-label"] == "CI main: last completed attempt fail (run 103)" +assert b">fail" in svg +assert b"#d1242f" in svg +assert b">pass" in module.badge("next", "success", 108) +print("last completed CI badge: queued run ignored, pass/fail SVGs valid") -- 2.54.0 From cf1eaebae1caf8d21d81bc006eb0cbc1b7d80514 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:21:19 -0600 Subject: [PATCH 03/99] Record private toolkit benchmark history --- .gitea/workflows/release.yml | 20 ++++- ci/badge_store.py | 54 +++++++++++++ ci/bench_history.py | 153 +++++++++++++++++++++++++++++++++++ ci/test-bench-history.py | 46 +++++++++++ 4 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 ci/badge_store.py create mode 100644 ci/bench_history.py create mode 100644 ci/test-bench-history.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 6241dc03..5533ccff 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -8,7 +8,7 @@ on: permissions: contents: write - actions: read + actions: write jobs: release: @@ -34,6 +34,9 @@ jobs: - 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: Install build dependencies run: | apt-get update -qq @@ -74,6 +77,11 @@ jobs: run: | cargo test -p alkane-gui --offline + - name: Load previous main benchmark measurement + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/bench_history.py prepare + - name: Microbenchmarks run: | # Capture the bench stdout for the weighted-average delta badge (round 19 @@ -83,6 +91,16 @@ jobs: cargo test -p alkane-gui --release --offline -- --ignored --nocapture bench_ \ | tee bench-current.txt + - 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-toolkit-benchmark-site-preview + path: bench-site/index.html + - name: Headless UI self-test run: | apt-get update -qq && apt-get install -y -qq --no-install-recommends \ diff --git a/ci/badge_store.py b/ci/badge_store.py new file mode 100644 index 00000000..bc3250df --- /dev/null +++ b/ci/badge_store.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: MIT +"""Write small badge artifacts to the private Gitea CI badge branch.""" + +import base64 +import json +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import Request, urlopen + +BADGE_BRANCH = "ci-badges" + + +def request_json(url: str, token: str, method: str = "GET", + payload: dict | None = None) -> dict: + body = None if payload is None else json.dumps(payload).encode() + request = Request(url, data=body, method=method, + headers={"Authorization": f"token {token}", + "Content-Type": "application/json"}) + with urlopen(request, timeout=20) as response: + return json.load(response) + + +def publish_file(api: str, repo: str, filename: str, data: bytes, + 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) > 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): + try: + current = request_json(path + "?ref=" + BADGE_BRANCH, token) + if base64.b64decode(current["content"]) == data: + return + sha = current["sha"] + method = "PUT" + except HTTPError as error: + if error.code != 404: + raise + sha = None + method = "POST" + payload = {"branch": BADGE_BRANCH, "content": encoded, + "message": message + " [skip ci]"} + if sha is not None: + payload["sha"] = sha + try: + request_json(path, token, method, payload) + return + except HTTPError as error: + if error.code not in (409, 422) or attempt == 2: + raise + raise RuntimeError("badge write did not complete") diff --git a/ci/bench_history.py b/ci/bench_history.py new file mode 100644 index 00000000..2f225f7f --- /dev/null +++ b/ci/bench_history.py @@ -0,0 +1,153 @@ +#!/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 +import importlib.util +from urllib.error import HTTPError +from urllib.parse import quote + +from badge_store import BADGE_BRANCH, publish_file, request_json + +bench_spec = importlib.util.spec_from_file_location( + "bench_badge", Path(__file__).with_name("bench-badge.py")) +bench_badge = importlib.util.module_from_spec(bench_spec) +bench_spec.loader.exec_module(bench_badge) + +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 Toolkit benchmarks" + "

Alkane Toolkit 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 = {"bench_ns_per_op": bench_badge.parse_bench( + Path("bench-current.txt").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 Toolkit benchmarks", max_bytes=1_048_576) + publish_file(api, repo, INDEX, json.dumps(index, indent=2).encode() + b"\n", + token, "Update Alkane Toolkit 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/test-bench-history.py b/ci/test-bench-history.py new file mode 100644 index 00000000..a8b0a291 --- /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("", - "metrics": {"bench_ns_per_op": {"hash": 10.0}}} + "metrics": {"bench_ns_per_op": {"hash": 10.0}, + "bench_host": {"cpu_model": ""}}} page = render_html({"entries": [entry]}) self.assertIn("<script>", page) self.assertNotIn("", "metrics": {"bench_ns_per_op": {"hash": 10.0}, - "bench_host": {"cpu_model": ""}}} + "bench_host": {"cpu_model": ""}, + "bench_context": {"schema": 1, "same_inputs": True}}} page = render_html({"entries": [entry]}) self.assertIn("<script>", page) self.assertNotIn("