|
| 1 | +"""Compare pytest-benchmark JSON output against stored baselines.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import json |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +THRESHOLD = 1.20 |
| 11 | + |
| 12 | +# Sub-ms timings are too noisy for a fixed 20% gate on ubuntu CI. |
| 13 | +EXCLUDED_FROM_GATE = frozenset( |
| 14 | + { |
| 15 | + "test_parse_session_small", |
| 16 | + "test_search_full_corpus", |
| 17 | + } |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class BenchmarkDataError(ValueError): |
| 22 | + """Raised when benchmark JSON input is malformed or missing required fields.""" |
| 23 | + |
| 24 | + |
| 25 | +def load_results(results_path: str | Path) -> dict[str, float]: |
| 26 | + path = Path(results_path) |
| 27 | + try: |
| 28 | + data = json.loads(path.read_text(encoding="utf-8")) |
| 29 | + except OSError as exc: |
| 30 | + raise BenchmarkDataError(f"cannot read {path}: {exc}") from exc |
| 31 | + except json.JSONDecodeError as exc: |
| 32 | + raise BenchmarkDataError(f"invalid JSON in {path}: {exc}") from exc |
| 33 | + try: |
| 34 | + benchmarks = data["benchmarks"] |
| 35 | + except (KeyError, TypeError) as exc: |
| 36 | + raise BenchmarkDataError(f"{path} missing top-level 'benchmarks' array") from exc |
| 37 | + if not isinstance(benchmarks, list): |
| 38 | + raise BenchmarkDataError(f"{path} 'benchmarks' must be an array") |
| 39 | + |
| 40 | + results: dict[str, float] = {} |
| 41 | + for index, entry in enumerate(benchmarks): |
| 42 | + if not isinstance(entry, dict): |
| 43 | + raise BenchmarkDataError(f"{path} benchmarks[{index}] must be an object") |
| 44 | + try: |
| 45 | + name = entry["name"] |
| 46 | + mean = float(entry["stats"]["mean"]) |
| 47 | + except (KeyError, TypeError, ValueError) as exc: |
| 48 | + raise BenchmarkDataError( |
| 49 | + f"{path} benchmarks[{index}] missing 'name' or 'stats.mean'" |
| 50 | + ) from exc |
| 51 | + name = str(name) |
| 52 | + if name in results: |
| 53 | + raise BenchmarkDataError(f"{path} duplicate benchmark name {name!r}") |
| 54 | + results[name] = mean |
| 55 | + return results |
| 56 | + |
| 57 | + |
| 58 | +def load_baseline_means(baselines_path: str | Path) -> dict[str, float]: |
| 59 | + path = Path(baselines_path) |
| 60 | + try: |
| 61 | + data = json.loads(path.read_text(encoding="utf-8")) |
| 62 | + except OSError as exc: |
| 63 | + raise BenchmarkDataError(f"cannot read {path}: {exc}") from exc |
| 64 | + except json.JSONDecodeError as exc: |
| 65 | + raise BenchmarkDataError(f"invalid JSON in {path}: {exc}") from exc |
| 66 | + if not isinstance(data, dict): |
| 67 | + raise BenchmarkDataError(f"{path} root value must be an object") |
| 68 | + |
| 69 | + if "groups" not in data: |
| 70 | + raise BenchmarkDataError(f"{path} missing required 'groups' key") |
| 71 | + groups = data["groups"] |
| 72 | + if not isinstance(groups, dict): |
| 73 | + raise BenchmarkDataError(f"{path} 'groups' must be an object") |
| 74 | + |
| 75 | + means: dict[str, float] = {} |
| 76 | + for group_name, value in groups.items(): |
| 77 | + if not isinstance(value, dict): |
| 78 | + continue |
| 79 | + for name, mean in value.items(): |
| 80 | + name = str(name) |
| 81 | + if name in means: |
| 82 | + raise BenchmarkDataError(f"{path} duplicate benchmark name {name!r} across groups") |
| 83 | + try: |
| 84 | + means[name] = float(mean) |
| 85 | + except (TypeError, ValueError) as exc: |
| 86 | + raise BenchmarkDataError( |
| 87 | + f"{path} groups[{group_name!r}][{name!r}] is not a numeric mean" |
| 88 | + ) from exc |
| 89 | + return means |
| 90 | + |
| 91 | + |
| 92 | +def check_regression( |
| 93 | + results_path: str | Path, |
| 94 | + baselines_path: str | Path, |
| 95 | + *, |
| 96 | + threshold: float = THRESHOLD, |
| 97 | +) -> int: |
| 98 | + """Return 0 when within threshold; 1 when any gated benchmark regresses.""" |
| 99 | + flat = load_results(results_path) |
| 100 | + baseline_means = load_baseline_means(baselines_path) |
| 101 | + |
| 102 | + failures: list[str] = [] |
| 103 | + for name, base in baseline_means.items(): |
| 104 | + if name in EXCLUDED_FROM_GATE: |
| 105 | + continue |
| 106 | + cur = flat.get(name) |
| 107 | + if cur is None: |
| 108 | + print(f"WARN: no current result for baseline {name!r}; skipping") |
| 109 | + continue |
| 110 | + if base == 0: |
| 111 | + print(f"WARN: baseline for {name!r} is zero; skipping ratio check") |
| 112 | + continue |
| 113 | + ratio = cur / base |
| 114 | + tag = "FAIL" if ratio > threshold else "ok" |
| 115 | + print(f"[{tag}] {name}: {cur:.6f}s vs {base:.6f}s ({ratio:.2f}x)") |
| 116 | + if ratio > threshold: |
| 117 | + failures.append(name) |
| 118 | + |
| 119 | + for name in flat: |
| 120 | + if name in EXCLUDED_FROM_GATE: |
| 121 | + continue |
| 122 | + if name not in baseline_means: |
| 123 | + print(f"WARN: {name!r} has no baseline yet; not gated") |
| 124 | + |
| 125 | + if failures: |
| 126 | + print(f"\nREGRESSION: {len(failures)} benchmark(s) exceeded {threshold:.0%}") |
| 127 | + return 1 |
| 128 | + return 0 |
| 129 | + |
| 130 | + |
| 131 | +def main(argv: list[str] | None = None) -> int: |
| 132 | + parser = argparse.ArgumentParser(description=__doc__) |
| 133 | + parser.add_argument("results_path", help="pytest-benchmark --benchmark-json output") |
| 134 | + parser.add_argument("baselines_path", help="path to benchmarks/baselines.json") |
| 135 | + parser.add_argument( |
| 136 | + "--threshold", |
| 137 | + type=float, |
| 138 | + default=THRESHOLD, |
| 139 | + help="fail when current mean exceeds baseline by more than this ratio (default: 1.20)", |
| 140 | + ) |
| 141 | + args = parser.parse_args(argv) |
| 142 | + try: |
| 143 | + return check_regression( |
| 144 | + args.results_path, |
| 145 | + args.baselines_path, |
| 146 | + threshold=args.threshold, |
| 147 | + ) |
| 148 | + except BenchmarkDataError as exc: |
| 149 | + print(f"ERROR: {exc}", file=sys.stderr) |
| 150 | + return 2 |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + sys.exit(main()) |
0 commit comments