"""Percentile and summary helpers for the perf suite (PERF-P5). `pytest-benchmark` reports min/max/mean/median/stddev and quartiles, but not the tail the plan's targets are written against: a mean hides the one request in fifty that a user would call slow. These helpers compute nearest-rank percentiles from the raw samples pytest-benchmark already records in `stats.data`, so nothing is estimated from a fitted distribution and two runs of the same code are summarised the same way. Nearest-rank, not interpolated: for a sample list the p95 is the value at ceil(0.95 * n). It needs no interpolation rule, and with the handful of rounds a benchmark actually runs it is the honest answer -- an interpolated p95 of ten samples invents a number between two measurements and moves with the round count. Pure functions only, so both the benchmarks and `scripts/perf_check.py` can use them, and so they can be tested without a benchmark run. """ from __future__ import annotations import math from collections.abc import Mapping, Sequence #: The percentiles the plan's targets are written against. p50 is the median #: pytest-benchmark already reports; it is included so one line carries the #: whole shape of a distribution. DEFAULT_POINTS = (50, 90, 95, 99) def percentile(samples: Sequence[float], point: float) -> float: """Nearest-rank percentile of `samples`; 0.0 for an empty sample. Raises ValueError for a point outside 0..100 rather than clamping, because a clamped percentile is a number that looks measured and is not. """ if not 0.0 <= point <= 100.0: raise ValueError(f"percentile point out of range: {point}") if not samples: return 0.0 ordered = sorted(samples) rank = max(1, math.ceil(point / 100.0 * len(ordered))) return float(ordered[min(rank, len(ordered)) - 1]) def percentiles(samples: Sequence[float], points: Sequence[float] = DEFAULT_POINTS) -> dict[str, float]: """Every requested percentile, keyed ``p50``/``p95``/... .""" return {f"p{int(point)}": percentile(samples, point) for point in points} def summarize(samples: Sequence[float], points: Sequence[float] = DEFAULT_POINTS) -> dict[str, float]: """Count, extremes, mean and the requested percentiles of `samples`.""" if not samples: return {"samples": 0.0, "min": 0.0, "max": 0.0, "mean": 0.0, **percentiles([], points)} total = float(sum(samples)) return { "samples": float(len(samples)), "min": float(min(samples)), "max": float(max(samples)), "mean": total / len(samples), **percentiles(samples, points), } def summary_from_benchmark_stats( stats: Mapping[str, object], points: Sequence[float] = DEFAULT_POINTS, ) -> dict[str, float]: """A summary for one entry of a pytest-benchmark JSON `stats` block. Prefers the recorded `data` samples. A stats block without them (a saved baseline written before the samples were recorded) still summarises, off its median and mean treated as a two-sample distribution, so an old baseline file keeps comparing instead of raising. Read the tail of such a summary as the mean it is: with two values the p95 is the larger one, and a report must not present it as a measured tail. """ raw = stats.get("data") if isinstance(raw, list) and raw: return summarize([float(value) for value in raw], points) fallback: list[float] = [] for key in ("median", "mean"): value = stats.get(key) if isinstance(value, (int, float)): fallback.append(float(value)) return summarize(fallback, points) def format_summary(name: str, stats: Mapping[str, object], unit: str = "s", digits: int = 4) -> str: """One report line: the name, then p50/p95/p99 and the mean, in `unit`.""" summary = summary_from_benchmark_stats(stats) return ( f"{name}: p50 {summary['p50']:.{digits}g}{unit} " f"p95 {summary['p95']:.{digits}g}{unit} " f"p99 {summary['p99']:.{digits}g}{unit} " f"mean {summary['mean']:.{digits}g}{unit} " f"over {int(summary['samples'])} round(s)" )