diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py index 4cdc1b79..af390609 100644 --- a/heart/checks/unit_timings.py +++ b/heart/checks/unit_timings.py @@ -565,6 +565,11 @@ def aggregate( ) -> dict[str, Any]: """Fold the per-repo sidecars + the committed record into the rollup. + Test baselines use seven distinct prior runs from the same Python leg + and compatible cache state. A median suite speed ratio (at least five + shared tests with three samples each) normalizes common runner variation. + Raw seconds, baseline run IDs, sample counts and the factor remain visible. + ``record_prev_rows`` is ``{(repo, python, nodeid): prev_row}`` and ``record_import_history`` is ``{(repo, package, python): [seconds]}``, both out of ``heart.timings`` (``timings/unit/.jsonl``). Unlike @@ -614,6 +619,24 @@ def _name_of(side: Any) -> str: slowest = [row for row in (leg.get("slowest") or []) if isinstance(row, dict)] + # At least five shared tests with three prior observations: a + # lone slow test must not explain away its own regression. The + # median resists isolated outliers; sparse histories stay unscaled. + speed_ratios = [] + for row in slowest: + previous = prev_rows.get((repo, python, str(row.get("nodeid") or "")), {}) + baseline = _as_float(previous.get("seconds")) + seconds = _as_float(row.get("seconds")) + previous_cache = previous.get("cache_state") + compatible = not (leg_cache_state in {"hit", "miss"} + and previous_cache in {"hit", "miss"} + and leg_cache_state != previous_cache) + if (compatible and previous.get("run_id") != run_id + and previous.get("samples", 1) >= 3 + and baseline and baseline > 0 and seconds and seconds > 0): + speed_ratios.append(seconds / baseline) + run_speed_factor = statistics.median(speed_ratios) if len(speed_ratios) >= 5 else 1.0 + for row in slowest: nodeid = str(row.get("nodeid") or "") seconds = _as_float(row.get("seconds")) @@ -621,7 +644,7 @@ def _name_of(side: Any) -> str: continue prev_row = prev_rows.get((repo, python, nodeid)) state, ratio, delta = classify_test_drift( - seconds, prev_row, thr, run_id=run_id, + seconds / run_speed_factor, prev_row, thr, run_id=run_id, cache=leg_cache_state, prev_cache_key="cache_state", ) prev_s = _as_float((prev_row or {}).get("seconds")) @@ -636,13 +659,22 @@ def _name_of(side: Any) -> str: "run_id": run_id, "run_url": run_url, "prev_s": prev_s, + "samples": (prev_row or {}).get("samples", 1 if prev_row else 0), + "run_speed_factor": run_speed_factor, + "normalized_seconds": seconds / run_speed_factor, + "baseline_run_ids": (prev_row or {}).get("baseline_run_ids", []), "prev_run_id": prev_run_id, "ratio": ratio, "delta_s": delta, "state": state, - "prompt": (test_prompt(repo, nodeid, prev_s, seconds, - prev_run_url, run_url) - if state == "warn" else None), + "prompt": (( + f"/hygiene perf: {repo} {nodeid}: {seconds:.2f}s raw, " + f"{seconds / run_speed_factor:.2f}s normalized vs {prev_s:.2f}s " + f"median ({(prev_row or {}).get('samples', 1)} samples; " + f"runner factor {run_speed_factor:.3f}); {run_url}" + ) if state == "warn" and (prev_row or {}).get("samples", 1) > 1 + else test_prompt(repo, nodeid, prev_s, seconds, prev_run_url, run_url) + if state == "warn" else None), }) imported = leg.get("import") if isinstance(leg.get("import"), dict) else None @@ -748,9 +780,9 @@ def legacy_summaries( "latest_seconds": round(_as_float(row.get("seconds")) or 0.0, 3), "baseline_seconds": round(_as_float(row.get("prev_s")) or 0.0, 3), "ratio": ratio, - # One recorded previous observation is the whole baseline here (the - # both-gates rule compares run to run), never a rolling window. - "samples": 1, + "samples": row.get("samples", 1), + "run_speed_factor": row.get("run_speed_factor", 1.0), + "normalized_seconds": row.get("normalized_seconds", row.get("seconds")), } if ratio > LEGACY_RED_FACTOR: unit["red"].append(entry) @@ -998,7 +1030,7 @@ def main(argv: list[str] | None = None) -> int: rollup = aggregate( sidecars, ts, thresholds, record_prev_rows=_timings.previous_unit_rows( - unit_dir, since=since, current_runs=current_runs), + unit_dir, since=since, current_runs=current_runs, window=7), record_import_history=_timings.import_history( unit_dir, int(thresholds.get("import_window", 7) or 7), since=since, diff --git a/heart/dashboard.py b/heart/dashboard.py index 320ac525..ac87ee93 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -882,7 +882,9 @@ def build_board( st, summary = OK, f"{g} tracked tests within baseline" details = [ f"✗ {e['repo']} {e['test'].split('::')[-1]} " - f"{e['latest_seconds']:.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)" + f"{e.get('normalized_seconds', e['latest_seconds']):.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)" + + (f" · raw {e['latest_seconds']:.2f}s / runner {e['run_speed_factor']:.3f}" + if e.get('run_speed_factor', 1.0) != 1.0 else "") for e in (ut.get("red") or [])[:5] ] suite_details, timing_html = timing_display.suites(snapshot.get("unit_timings")) diff --git a/heart/timings.py b/heart/timings.py index d12a7453..036578f0 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -106,6 +106,7 @@ import argparse import datetime import json +import statistics import sys from pathlib import Path from typing import Any @@ -741,8 +742,13 @@ def append_unit(path: Path | str, lines: list[dict[str, Any]]) -> int: def previous_unit_rows( unit_dir: Path | str = UNIT_DIR, since: str = "", current_runs: dict[tuple[str, str], dict[str, Any]] | None = None, + window: int = 1, ) -> dict[tuple[str, str, str], dict[str, Any]]: - """``{(repo, python, nodeid): prev_row}`` — the last recorded observation. + """``{(repo, python, nodeid): prev_row}`` — a comparable prior baseline. + + ``window > 1`` selects a median over the latest distinct comparable runs. + Chronology, Python leg, epoch and known cache-state boundaries are honored. + Missing top-N test measurements are never treated as zero. The shape is exactly what ``smoke_timings.classify_drift`` expects of a previous row (``seconds``/``run_id``/``run_url``/``cache_state``), which is @@ -791,6 +797,7 @@ def observed(record: dict[str, Any]) -> tuple[datetime.datetime, datetime.dateti repo = path.name[: -len(".jsonl")] records, _ = read_jsonl(path) latest: dict[str, dict[str, Any]] = {} + candidates: dict[str, list[dict[str, Any]]] = {} for record in records: if not _within_epoch(record, since): continue @@ -804,10 +811,36 @@ def observed(record: dict[str, Any]) -> tuple[datetime.datetime, datetime.dateti before, now = observed(record), observed(current) if before is None or now is None or before[1] >= now[0]: continue + if window > 1: + current_cache = unit_cache_state(current.get("cache")) + prior_cache = unit_cache_state(record.get("cache")) + if current_cache in {"hit", "miss"} and prior_cache in {"hit", "miss"} and current_cache != prior_cache: + continue + candidates.setdefault(python, []).append(record) previous = latest.get(python) if previous is not None and observed(previous)[1] >= before[1]: continue + if current_runs is None: + candidates.setdefault(python, []).append(record) latest[python] = record + samples_by_test = {} + if window > 1: + for python, records in candidates.items(): + if current_runs is not None: + records.sort(key=lambda record: observed(record)[1]) + unique = {str(record.get("run_id")): record for record in records} + records = list(unique.values())[-window:] + values = {} + for record in records: + for nodeid, value in (record.get("slowest") or {}).items(): + seconds = _as_float(value) + if seconds is not None and seconds > 0: + values.setdefault(nodeid, []).append(seconds) + baseline = dict(latest[python]) + baseline["slowest"] = {nodeid: statistics.median(v) for nodeid, v in values.items()} + baseline["baseline_run_ids"] = [record.get("run_id") for record in records] + latest[python] = baseline + samples_by_test.update({(python, nodeid): len(v) for nodeid, v in values.items()}) for python, record in latest.items(): slowest = record.get("slowest") if not isinstance(slowest, dict): @@ -818,6 +851,8 @@ def observed(record: dict[str, Any]) -> tuple[datetime.datetime, datetime.dateti continue out[(repo, python, str(nodeid))] = { "seconds": seconds, + **({"samples": samples_by_test.get((python, str(nodeid)), 1), + "baseline_run_ids": record.get("baseline_run_ids", [])} if window > 1 else {}), "run_id": record.get("run_id"), "run_url": str(record.get("run_url") or ""), # The state this baseline was measured under, so diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index ca1b7bd3..3f5ea257 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -523,7 +523,8 @@ def test_the_legacy_unit_buckets_keep_the_sections_wording_truthful(tmp_path): assert unit["red_count"] == 1 and unit["yellow_count"] == 0 (entry,) = unit["red"] assert entry == {"repo": REPO, "test": NODEID, "latest_seconds": 8.0, - "baseline_seconds": 2.0, "ratio": 4.0, "samples": 1} + "baseline_seconds": 2.0, "ratio": 4.0, "samples": 1, + "run_speed_factor": 1.0, "normalized_seconds": 8.0} side = _sidecar(tmp_path, sub="yellow", junit=_junit(_case(time="4.0"))) roll = ut.aggregate([side], "T", THRESHOLDS, record_prev_rows=_prev_rows(2.0)) @@ -873,3 +874,47 @@ def test_drift_is_never_classified_across_two_known_cache_states(tmp_path): (row,) = ut.aggregate([side], "T", THRESHOLDS, record_prev_rows=_prev_rows(1.5))["tests"] assert row["state"] == "warn" + + +def test_rolling_test_baseline_normalizes_common_runner_speed(tmp_path): + def record(run, at, values, python="3.12", cache=None): + return {"date": at[:10], "at": at, "python": python, "run_id": run, + "cache": cache or {}, "slowest": values} + nodes = {f"tests/test_demo.py::test_{i}": 6.0 for i in range(7)} + path = tmp_path / "RepoA.jsonl" + records = [record(i, f"2026-10-{i:02d}T10:00:00Z", nodes) for i in range(1, 5)] + # One exceptionally quick runner must not become every test's baseline. + records.append(record(5, "2026-10-05T10:00:00Z", {n: 1.5 for n in nodes})) + # Future and current-run evidence are excluded even if appended last. + records.append(record(9, "2026-10-09T10:00:00Z", {n: 1000 for n in nodes})) + path.write_text("\n".join(json.dumps(r) for r in records)) + current = record(6, "2026-10-06T10:00:00Z", nodes) + previous = timings.previous_unit_rows(tmp_path, current_runs={(REPO, "3.12"): current}, window=7) + assert all(r["seconds"] == 6.0 and r["samples"] == 5 for r in previous.values()) + for common_speed in (1.0, 2.1): + latest = [{"nodeid": n, "seconds": v * common_speed} for n, v in nodes.items()] + latest[0]["seconds"] *= 4 + leg = {**current, "slowest": latest} + roll = ut.aggregate([{"name": REPO, "legs": [leg]}], "T", record_prev_rows=previous) + unit, _ = ut.legacy_summaries(roll) + assert unit["red_count"] == 1 and unit["yellow_count"] == 0 + assert unit["red"][0]["test"] == latest[0]["nodeid"] + assert unit["red"][0]["ratio"] == 4.0 + assert abs(unit["red"][0]["run_speed_factor"] - common_speed) < 1e-10 + + +def test_rolling_baseline_respects_python_epoch_and_cache(tmp_path): + records = [ + {"date": "2026-10-01", "at": "2026-10-01T00:00:00Z", "run_id": 1, + "python": "3.12", "cache": {"jax": "hit", "numba": "hit"}, "slowest": {NODEID: 6}}, + {"date": "2026-10-02", "at": "2026-10-02T00:00:00Z", "run_id": 2, + "python": "3.12", "cache": {"jax": "miss", "numba": "miss"}, "slowest": {NODEID: 100}}, + {"date": "2026-10-03", "at": "2026-10-03T00:00:00Z", "run_id": 3, + "python": "3.13", "cache": {}, "slowest": {NODEID: 200}}, + ] + (tmp_path / "RepoA.jsonl").write_text("\n".join(json.dumps(r) for r in records)) + current = {**records[0], "run_id": 4, "at": "2026-10-04T00:00:00Z"} + rows = timings.previous_unit_rows(tmp_path, current_runs={(REPO, "3.12"): current}, window=7) + assert rows[(REPO, "3.12", NODEID)]["seconds"] == 6 + assert rows[(REPO, "3.12", NODEID)]["samples"] == 1 + assert not timings.previous_unit_rows(tmp_path, since="2026-10-02", current_runs={(REPO, "3.12"): current}, window=7)