stocks / scripts /perf_check.py
user
python version
ee446e8
Raw History Blame Contribute Delete
3.16 kB
"""Compare pytest-benchmark output with the checked-in baseline (PERF-P5).
Reports the tail (p50/p95/p99) next to the mean, because a mean hides the one
request in fifty a user would call slow, and the plan's targets are written
against percentiles.
The gate still decides on the **mean**. That is deliberate: a percentile over
the handful of rounds a benchmark actually runs moves with the round count, so
gating on it trades a stable gate for a number that would have to be re-baselined
whenever a machine got busier. The percentiles are for the report and for
PERF-P1's p95 target, which is a measured figure rather than a pass/fail.
A baseline entry with no benchmark behind it any more is reported as stale and
does not fail the gate. The reverse -- a benchmark with no baseline entry -- is
unbaselined and prints its numbers without a ratio. Previously either case
failed the run, which meant a deleted benchmark kept `make perf-check` red
forever with no way to clear it short of editing the baseline by hand.
"""
from __future__ import annotations
import json
import math
import subprocess
import sys
from pathlib import Path
# Run as `python -m scripts.perf_check` (see the Makefile target): the root has
# to be on sys.path for the package import below, and a direct
# `python scripts/perf_check.py` puts scripts/ there instead.
from scripts.perf_report import format_summary, summary_from_benchmark_stats
BASELINE = Path("tests/perf/baseline.json")
LATEST = Path("tests/perf/latest.json")
LIMIT = 1.20
def load_stats(path: Path) -> dict[str, dict[str, object]]:
data = json.loads(path.read_text(encoding="utf-8"))
return {item["name"]: item["stats"] for item in data["benchmarks"]}
def main() -> int:
subprocess.run(
["uv", "run", "pytest", "tests/perf/test_benchmark.py", "--benchmark-only", f"--benchmark-json={LATEST}"],
check=True,
)
baseline = load_stats(BASELINE)
current = load_stats(LATEST)
failures: list[str] = []
stale: list[str] = []
unbaselined: list[str] = []
for name, baseline_stats in baseline.items():
if name not in current:
stale.append(f"{name}: in the baseline but not in the suite any more")
continue
current_stats = current[name]
print(f" {format_summary(name, current_stats)}")
baseline_mean = float(baseline_stats["mean"])
current_mean = float(summary_from_benchmark_stats(current_stats)["mean"])
ratio = current_mean / baseline_mean if baseline_mean else math.inf
print(f" mean vs baseline {baseline_mean:.6g}s ({ratio:.1%}, fails over {LIMIT:.0%})")
if ratio > LIMIT:
failures.append(f"{name}: {ratio:.1%} > {LIMIT:.0%}")
for name in current:
if name not in baseline:
unbaselined.append(f"{name}: no baseline entry, reporting without a ratio")
for line in [*unbaselined, *stale]:
print(f" ! {line}", file=sys.stderr)
if failures:
print("Performance regression detected:", *failures, sep="\n- ", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())