|
| 1 | +"""Reduce pytest-benchmark JSON into benchmarks/baselines.json.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import json |
| 7 | +import sys |
| 8 | +from datetime import UTC, datetime |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +_REPO_ROOT = Path(__file__).resolve().parent.parent |
| 12 | +if str(_REPO_ROOT) not in sys.path: |
| 13 | + sys.path.insert(0, str(_REPO_ROOT)) |
| 14 | + |
| 15 | +from scripts.check_benchmark_regression import ( |
| 16 | + EXCLUDED_FROM_GATE, |
| 17 | + BenchmarkDataError, |
| 18 | + normalize_benchmark_name, |
| 19 | +) |
| 20 | + |
| 21 | +GATED_GROUPS = ("parse", "export", "search", "summary-cache") |
| 22 | + |
| 23 | + |
| 24 | +def _positive_float(value: str) -> float: |
| 25 | + parsed = float(value) |
| 26 | + if parsed <= 0: |
| 27 | + raise argparse.ArgumentTypeError("slack must be greater than zero") |
| 28 | + return parsed |
| 29 | + |
| 30 | + |
| 31 | +def reduce_baselines( |
| 32 | + raw_path: str | Path, |
| 33 | + out_path: str | Path, |
| 34 | + *, |
| 35 | + slack: float = 1.0, |
| 36 | +) -> dict[str, object]: |
| 37 | + path = Path(raw_path) |
| 38 | + try: |
| 39 | + raw = json.loads(path.read_text(encoding="utf-8")) |
| 40 | + except json.JSONDecodeError as exc: |
| 41 | + raise BenchmarkDataError(f"invalid JSON in {path}: {exc}") from exc |
| 42 | + except OSError as exc: |
| 43 | + raise BenchmarkDataError(f"cannot read {path}: {exc}") from exc |
| 44 | + |
| 45 | + try: |
| 46 | + entries = raw["benchmarks"] |
| 47 | + except (KeyError, TypeError) as exc: |
| 48 | + raise BenchmarkDataError(f"{path} missing top-level 'benchmarks' array") from exc |
| 49 | + if not isinstance(entries, list): |
| 50 | + raise BenchmarkDataError(f"{path} 'benchmarks' must be an array") |
| 51 | + |
| 52 | + groups: dict[str, dict[str, float]] = {group: {} for group in GATED_GROUPS} |
| 53 | + for index, entry in enumerate(entries): |
| 54 | + if not isinstance(entry, dict): |
| 55 | + raise BenchmarkDataError(f"{path} benchmarks[{index}] must be an object") |
| 56 | + try: |
| 57 | + raw_name = entry["name"] |
| 58 | + mean = float(entry["stats"]["mean"]) |
| 59 | + except (KeyError, TypeError, ValueError) as exc: |
| 60 | + raise BenchmarkDataError( |
| 61 | + f"{path} benchmarks[{index}] missing 'name' or 'stats.mean'" |
| 62 | + ) from exc |
| 63 | + bench_name = normalize_benchmark_name(str(raw_name)) |
| 64 | + group = entry.get("group") |
| 65 | + if group not in GATED_GROUPS: |
| 66 | + continue |
| 67 | + groups[group][bench_name] = mean * slack |
| 68 | + |
| 69 | + excluded = ", ".join(sorted(EXCLUDED_FROM_GATE)) |
| 70 | + slack_note = f" Values multiplied by {slack}× slack at generation time." if slack != 1.0 else "" |
| 71 | + machine_info = raw.get("machine_info") |
| 72 | + machine = machine_info.get("system") if isinstance(machine_info, dict) else None |
| 73 | + output: dict[str, object] = { |
| 74 | + "_note": ( |
| 75 | + "Gated means from ubuntu-latest CI benchmark-results.json." |
| 76 | + f"{slack_note} " |
| 77 | + f"Excluded from gate (recorded for reference): {excluded}. " |
| 78 | + "Refresh after intentional speedups via reduce_baselines.py." |
| 79 | + ), |
| 80 | + "updated": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 81 | + "machine": machine, |
| 82 | + "groups": groups, |
| 83 | + } |
| 84 | + out = Path(out_path) |
| 85 | + try: |
| 86 | + out.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") |
| 87 | + except OSError as exc: |
| 88 | + raise BenchmarkDataError(f"cannot write {out}: {exc}") from exc |
| 89 | + return output |
| 90 | + |
| 91 | + |
| 92 | +def main(argv: list[str] | None = None) -> int: |
| 93 | + parser = argparse.ArgumentParser(description=__doc__) |
| 94 | + parser.add_argument("raw_path", help="pytest-benchmark --benchmark-json output") |
| 95 | + parser.add_argument("out_path", help="destination baselines.json path") |
| 96 | + parser.add_argument( |
| 97 | + "--slack", |
| 98 | + type=_positive_float, |
| 99 | + default=1.0, |
| 100 | + help="multiply means by this factor (must be > 0)", |
| 101 | + ) |
| 102 | + args = parser.parse_args(argv) |
| 103 | + try: |
| 104 | + reduce_baselines(args.raw_path, args.out_path, slack=args.slack) |
| 105 | + except BenchmarkDataError as exc: |
| 106 | + print(f"ERROR: {exc}", file=sys.stderr) |
| 107 | + return 2 |
| 108 | + return 0 |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + sys.exit(main()) |
0 commit comments