Skip to content
pi-c Artifact [167b359a09]
Login

Artifact [167b359a09]

Artifact 167b359a09641941b9a9dcfe4d3c5382bab4ac65a01091659ab616758700a4d1:


#!/usr/bin/env python3
"""S0 benchmark report summarizer.

Report-only: reads the shell-written run metadata and the per-candidate
measurement JSON emitted by bench/measure.c, verifies recorded hashes against
the retained files, and writes results.json plus report.csv. It never
compiles, spawns a process, or times anything.

A required candidate that is missing or not measured fails the run. LTO is an
optional candidate: its absence or failure is recorded but does not flip the
required gate. Every comparison is fixture-only and informational.

Exit codes: 0 PASS, 1 FAIL, 2 GATED (the compiler was unavailable).

Usage: python3 -I tools/benchmark.py --metadata FILE --report-json FILE
                                     [--report-csv FILE]
"""
import argparse
import csv
import hashlib
import json
import os
import statistics
import sys

PASS, FAIL, GATED = "PASS", "FAIL", "GATED"
EXIT = {PASS: 0, FAIL: 1, GATED: 2}
REQUIRED = ("o2", "o3")

DISCLAIMERS = [
    "Fixture only: an empty in-process state transition and an effect record "
    "in synthetic C; not product code; no SQLite, commit, fsync, filesystem, "
    "or network.",
    "No SLO asserted; no candidate declared universally fastest; one host; "
    "informational, not a capacity claim.",
    "The fixture checksum makes elision of this workload observable; it is not "
    "a general optimizer barrier for arbitrary code.",
    "Optimized candidates keep the fixture's checks; none are disabled.",
]


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for chunk in iter(lambda: handle.read(1 << 20), b""):
            digest.update(chunk)
    return digest.hexdigest()


def parse_metadata(path):
    """Return (fields, candidates) from the block-oriented metadata record."""
    fields, candidates, current = {}, [], None
    with open(path, encoding="utf-8") as handle:
        for raw in handle:
            line = raw.rstrip("\n")
            if not line:
                continue
            if line == "candidate_end":
                if current is None:
                    raise ValueError("candidate_end without candidate_begin")
                candidates.append(current)
                current = None
                continue
            if "=" not in line:
                continue
            key, value = line.split("=", 1)
            if key == "candidate_begin":
                if current is not None:
                    raise ValueError(f"candidate {current.get('name')} "
                                     "was not closed")
                current = {"name": value}
            elif current is not None:
                current[key] = value
            else:
                fields[key] = value
    if current is not None:
        raise ValueError(f"candidate {current.get('name')} was not closed")
    return fields, candidates


def summarize(values):
    if not values:
        return {"count": 0, "median": None, "min": None, "max": None}
    return {"count": len(values), "median": statistics.median(values),
            "min": min(values), "max": max(values)}


def _exit_code(text):
    if text is None:
        return None
    try:
        return int(text)
    except (TypeError, ValueError):
        return None


def describe(candidate):
    """Load and check one candidate without trusting its metadata."""
    name = candidate["name"]
    entry = {
        "name": name,
        "required": candidate.get("required", "0") == "1",
        "flags": candidate.get("flags", "").split(),
        "binary": candidate.get("binary"),
        "raw": candidate.get("raw"),
        "binary_sha256": candidate.get("binary_sha256"),
        "binary_sha256_verified": None,
        "source_sha256": candidate.get("source_sha256"),
        "source_sha256_verified": None,
        "status": "FAIL",
        "reason": None,
        "measurement_status": candidate.get("measurement_status"),
        "measurement_exit": _exit_code(candidate.get("measurement_exit")),
    }
    if entry["binary"] and os.path.isfile(entry["binary"]):
        entry["binary_sha256_verified"] = sha256_file(entry["binary"])

    recorded = entry["measurement_status"]
    if recorded == "timed_out" or entry["measurement_exit"] == 124:
        entry["status"] = "FAIL"
        entry["reason"] = "measurement exceeded its deadline"
        return entry
    if recorded in ("failed", "missing"):
        entry["status"] = "FAIL"
        entry["reason"] = (candidate.get("reason")
                           or "measurement did not produce evidence")
        return entry

    if entry["raw"] and os.path.isfile(entry["raw"]):
        with open(entry["raw"], encoding="utf-8") as handle:
            measurement = json.load(handle)
        entry["status"] = "PASS" if measurement.get("status") == "ok" else "FAIL"
        if entry["status"] == "FAIL":
            entry["reason"] = measurement.get("reason", "measurement failed")
        entry["startup_ms"] = measurement.get("startup_ms", [])
        entry["work_ms"] = measurement.get("work_ms", [])
        entry["startup_summary"] = summarize(entry["startup_ms"])
        entry["work_summary"] = summarize(entry["work_ms"])
        entry["checksum"] = measurement.get("checksum")
        entry["iterations"] = measurement.get("iterations")
        entry["work_iterations"] = measurement.get("work_iterations")
    elif recorded == "measured":
        # Metadata claims a measurement but no JSON survived: not evidence.
        entry["status"] = "FAIL"
        entry["reason"] = "measurement JSON missing"
    elif candidate.get("reason"):
        entry["status"] = "FAIL"
        entry["reason"] = candidate["reason"]
    return entry


def check(entry, fields):
    """Return a list of integrity reasons for one candidate."""
    reasons = []
    if entry["binary_sha256"] != entry["binary_sha256_verified"]:
        reasons.append(f"{entry['name']}: binary hash mismatch")
    source = fields.get("source")
    recorded = entry["source_sha256"]
    if source and os.path.isfile(source):
        entry["source_sha256_verified"] = sha256_file(source)
        if recorded != entry["source_sha256_verified"]:
            reasons.append(f"{entry['name']}: source hash mismatch")
    return reasons


def build_report(fields, candidates):
    entries = [describe(c) for c in candidates]
    by_name = {entry["name"]: entry for entry in entries}
    reasons = []
    for entry in entries:
        reasons.extend(check(entry, fields))
    for name in REQUIRED:
        if name not in by_name:
            reasons.append(f"required candidate {name} was not run")
        elif by_name[name]["status"] != "PASS":
            reasons.append(
                f"required candidate {name} did not measure: "
                f"{by_name[name]['status']}")
    measured = [e for e in entries if e["status"] == "PASS"]
    checksums = {e.get("checksum") for e in measured}
    consistent = len(checksums) <= 1
    if not consistent:
        reasons.append(f"checksum drift across candidates: {sorted(checksums)}")
    if fields.get("compiler_available") == "0":
        status = GATED
        reasons = ["compiler unavailable"] + reasons
    elif reasons:
        status = FAIL
    else:
        status = PASS
    return {
        "status": status,
        "informational": True,
        "reasons": reasons,
        "checksums_consistent": consistent,
        "args": {"samples": int(fields.get("samples", 0)),
                 "iterations": int(fields.get("iterations", 0)),
                 "deadline": int(fields.get("deadline", 0))},
        "compiler": fields.get("compiler"),
        "compiler_version": fields.get("compiler_version"),
        "source": fields.get("source"),
        "source_sha256": sha256_file(fields["source"])
        if fields.get("source") and os.path.isfile(fields["source"]) else None,
        "host": {"platform": fields.get("host_platform"),
                 "machine": fields.get("host_machine")},
        "candidates": entries,
        "disclaimers": DISCLAIMERS,
    }


def write_json(path, report):
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(report, handle, indent=2, sort_keys=True)
        handle.write("\n")


def write_csv(path, report):
    columns = ["candidate", "required", "status", "flags", "binary_sha256",
               "source_sha256", "checksum", "samples", "startup_median_ms",
               "work_median_ms", "work_us_per_iteration", "reason"]
    with open(path, "w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=columns)
        writer.writeheader()
        for entry in report["candidates"]:
            startup = entry.get("startup_summary") or {}
            work = entry.get("work_summary") or {}
            iterations = entry.get("work_iterations") or 0
            per_iteration = (work.get("median") * 1000.0 / iterations
                             if work.get("median") and iterations else None)
            writer.writerow({
                "candidate": entry["name"],
                "required": int(entry["required"]),
                "status": entry["status"],
                "flags": " ".join(entry["flags"]),
                "binary_sha256": entry["binary_sha256"],
                "source_sha256": entry["source_sha256"],
                "checksum": entry.get("checksum"),
                "samples": startup.get("count", 0),
                "startup_median_ms": startup.get("median"),
                "work_median_ms": work.get("median"),
                "work_us_per_iteration": per_iteration,
                "reason": entry.get("reason") or "",
            })


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--metadata", required=True,
                        help="shell-written candidate metadata record")
    parser.add_argument("--report-json", required=True)
    parser.add_argument("--report-csv", default=None)
    args = parser.parse_args(argv)

    try:
        fields, candidates = parse_metadata(args.metadata)
        report = build_report(fields, candidates)
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        report = {"status": FAIL, "informational": True,
                  "reasons": [f"invalid metadata: {exc}"], "candidates": [],
                  "disclaimers": DISCLAIMERS}

    write_json(args.report_json, report)
    if args.report_csv:
        write_csv(args.report_csv, report)
    print(f"{report['status']}: " + ", ".join(
        f"{c['name']}={c['status']}" for c in report["candidates"]))
    for reason in report.get("reasons", []):
        print(f"  - {reason}")
    print(f"evidence: {args.report_json}")
    return EXIT[report["status"]]


if __name__ == "__main__":
    sys.exit(main())