diff --git a/heart/timing_display.py b/heart/timing_display.py
index 6652e765..d819d9b3 100644
--- a/heart/timing_display.py
+++ b/heart/timing_display.py
@@ -143,12 +143,17 @@ def count(value):
return f"{value:,}"
-def plot(points, label, fmt=duration, *, gaps=True, values="Daily median values"):
+def plot(points, label, fmt=duration, *, gaps=True, values="Daily median values", min_span=1):
"""An SVG trend of ``[(date, value-or-None), ...]`` with its text twin.
``gaps=True`` breaks the line at a missing day (a gate measured daily: a
hole is an unavailable measurement). ``gaps=False`` joins the measured
points, for a series that is only observed on days something ran.
+
+ ``min_span`` floors the y-scale's span, in the series' own units. The gate
+ charts keep the historical floor of 1; a unit trend passes 0 so a
+ sub-second series (an import time) fills the chart height instead of
+ hugging its floor. A flat series is drawn on the floor either way.
"""
points = sorted(points, key=lambda p: p[0])
valid = [(d, v) for d, v in points if v is not None]
@@ -157,6 +162,7 @@ def plot(points, label, fmt=duration, *, gaps=True, values="Daily median values"
if not gaps:
points = valid
low, high = min(v for _, v in valid), max(v for _, v in valid)
+ scale = max(high - low, min_span) or 1 # a flat series with no floor: no division by zero
start, end = points[0][0], points[-1][0]
span = max((end - start).days, 1)
marks, segment, last = [], [], None
@@ -168,7 +174,7 @@ def plot(points, label, fmt=duration, *, gaps=True, values="Daily median values"
last = day
if value is None:
continue
- x, y = 10 + 300 * (day - start).days / span, 75 - 60 * (value - low) / max(high - low, 1)
+ x, y = 10 + 300 * (day - start).days / span, 75 - 60 * (value - low) / scale
segment.append(f"{x:.1f},{y:.1f}")
marks.append(f'{day}: {fmt(value)}')
if segment:
@@ -223,15 +229,17 @@ def unit_trend(history, repo, python, field):
value = row.get(field)
value = (value if count(value) != "unavailable" else None) if field == "tests" else seconds(value)
points.append((date, value))
- measured = sum(v is not None for _, v in points)
+ measured = sorted(d for d, v in points if v is not None)
if not measured:
return '
No main-branch history in the timing record yet.
'
what = {"tests": "tests collected", "wall_s": "suite wall-clock seconds",
"import_s": "import seconds"}.get(field, field)
- label = (f"{repo} · Python {python}: {what} on main, {points[0][0]} to {points[-1][0]}; "
- f"{measured} days with a main run; days without one are joined")
+ # The axis joins measured points only (gaps=False), so the label's range
+ # names the same first and last day the axis does.
+ label = (f"{repo} · Python {python}: {what} on main, {measured[0]} to {measured[-1]}; "
+ f"{len(measured)} days with a main run; days without one are joined")
return plot(points, label, count if field == "tests" else duration, gaps=False,
- values="Values per main run day")
+ values="Values per main run day", min_span=0)
def organism_total(history):
diff --git a/heart/timings.py b/heart/timings.py
index f343b730..7569b929 100644
--- a/heart/timings.py
+++ b/heart/timings.py
@@ -913,9 +913,19 @@ def unit_history(
would draw a branch's half-written tests as a dip in the trend.
One point per (python leg, day): the day is when the run happened (``at``),
- falling back to the line's ``date``; when a day holds several main runs the
- one recorded last wins, the file being append-only. A value that is not a
- measurement stays ``None`` and is drawn as missing, never as zero.
+ falling back to the line's ``date``. The epoch boundary is applied to that
+ same day, so the filter and the plotted x never disagree about which side
+ of the boundary a run fell on.
+
+ A day can hold several main runs, and a suite's wall-clock is noisy run to
+ run (one library on 2026-10-26: 100 s and 296 s, both cache hits). So
+ ``wall_s`` and ``import_s`` are the median of that day's runs, taken over
+ its cache-``hit`` runs when it has any (a cold run measures the cache, not
+ the suite) and over all of them otherwise. ``tests`` is the last run's
+ count, the file being append-only: the suite's size is not noisy, and the
+ newest run has the newest tests. A value that is not a measurement stays
+ ``None`` and is drawn as missing, never as zero; it is left out of a
+ median rather than counted as zero.
``since`` is the current epoch's date, as everywhere else in this record.
``cap`` keeps the last N days per leg.
"""
@@ -923,27 +933,41 @@ def unit_history(
root = Path(unit_dir)
if not root.is_dir():
return out
+
+ def _median(runs: list[dict[str, Any]], field: str) -> float | None:
+ values = [run[field] for run in runs if run[field] is not None]
+ return statistics.median(values) if values else None
+
for path in sorted(root.glob("*.jsonl")):
repo = path.name[: -len(".jsonl")]
records, _ = read_jsonl(path)
- days: dict[tuple[str, str], dict[str, Any]] = {}
+ runs_by_day: dict[tuple[str, str], list[dict[str, Any]]] = {}
for record in records:
- if record.get("head_branch") != "main" or not _within_epoch(record, since):
+ if record.get("head_branch") != "main":
continue
day = str(record.get("at") or "")[:10]
if not _is_iso_date(day):
day = str(record.get("date") or "")
- if not _is_iso_date(day):
+ if not _is_iso_date(day) or (since and day < since):
continue
python = str(record.get("python") or "")
suite = record.get("suite") if isinstance(record.get("suite"), dict) else {}
tests = suite.get("tests")
- days[(python, day)] = {
- "date": day,
- "python": python,
+ runs_by_day.setdefault((python, day), []).append({
"tests": tests if isinstance(tests, int) and not isinstance(tests, bool) and tests >= 0 else None,
"wall_s": _as_float(suite.get("wall_s")),
"import_s": _as_float(record.get("import_s")),
+ "hit": unit_cache_state(record.get("cache")) == "hit",
+ })
+ days: dict[tuple[str, str], dict[str, Any]] = {}
+ for (python, day), runs in runs_by_day.items():
+ timed = [run for run in runs if run["hit"]] or runs
+ days[(python, day)] = {
+ "date": day,
+ "python": python,
+ "tests": runs[-1]["tests"],
+ "wall_s": _median(timed, "wall_s"),
+ "import_s": _median(timed, "import_s"),
}
points: list[dict[str, Any]] = []
for python in sorted({p for p, _ in days}):
diff --git a/tests/golden/gate_chart.html b/tests/golden/gate_chart.html
new file mode 100644
index 00000000..298c6633
--- /dev/null
+++ b/tests/golden/gate_chart.html
@@ -0,0 +1 @@
+unit: daily median seconds, 2026-09-01 to 2026-09-06; 4 measured days; gaps are unavailable
Range 0.42s – 0.51s
2026-09-012026-09-06
Daily median values (text)
2026-09-01: 0.42s
2026-09-02: 0.47s
2026-09-04: 0.51s
2026-09-05: unavailable
2026-09-06: 0.44s
diff --git a/tests/test_unit_trends.py b/tests/test_unit_trends.py
index 4e1fc758..505044e2 100644
--- a/tests/test_unit_trends.py
+++ b/tests/test_unit_trends.py
@@ -1,5 +1,7 @@
"""The unit record drawn on the board: suite/import trends + the organism total."""
import json
+import re
+from pathlib import Path
from heart import dashboard, timings, timing_display as display
from tests.test_dashboard import (
@@ -8,10 +10,12 @@
)
-def _line(day, tests, wall, *, branch="main", python="3.12", run_id=1, at=None, imp=1.0):
+def _line(day, tests, wall, *, branch="main", python="3.12", run_id=1, at=None, imp=1.0,
+ cache=None):
return {"date": day, "at": at if at is not None else f"{day}T02:00:00Z",
"python": python, "run_id": run_id, "head_branch": branch,
"package": "pkg_a", "import_s": imp,
+ **({"cache": cache} if cache is not None else {}),
"suite": {"tests": tests, "failures": 0, "errors": 0, "skipped": 0,
"wall_s": wall}}
@@ -22,7 +26,7 @@ def _write(directory, repo, lines):
path.write_text("".join(json.dumps(line) + "\n" for line in lines))
-def test_unit_history_keeps_main_only_and_the_last_run_of_each_day(tmp_path):
+def test_unit_history_keeps_main_only_and_one_point_per_run_day(tmp_path):
_write(tmp_path, "RepoA", [
_line("2026-09-01", 100, 10.0, run_id=1),
_line("2026-09-01", 999, 99.0, run_id=2, branch="feature/x"),
@@ -32,10 +36,12 @@ def test_unit_history_keeps_main_only_and_the_last_run_of_each_day(tmp_path):
])
history = timings.unit_history(tmp_path / "unit")
points = history["RepoA"]
- # The run DAY (`at`) is the point's date; the later run that day wins.
+ # The run DAY (`at`) is the point's date; the later run's test count wins,
+ # the day's wall-clock is the median of its runs.
assert [(p["python"], p["date"], p["tests"]) for p in points] == [
("3.12", "2026-09-01", 110), ("3.12", "2026-09-04", None),
("3.13", "2026-09-03", 120)]
+ assert points[0]["wall_s"] == 10.5
assert points[1]["import_s"] is None # never a zero
assert all(p["tests"] != 999 for p in points) # the branch run is not main's suite
@@ -113,3 +119,78 @@ def test_unit_section_carries_the_total_row_and_charts_only_with_a_record():
unit_test_timing=_legacy_unit()),
make_verdict(), now=FRESH_NOW)
assert "Organism total" not in _section(plain, "unit_test_timing").timing_html
+
+
+HIT, MISS = {"jax": "hit", "numba": "hit"}, {"jax": "miss", "numba": "miss"}
+
+
+def test_unit_history_takes_the_median_of_a_days_runs_preferring_cache_hits(tmp_path):
+ _write(tmp_path, "RepoA", [
+ # 09-01: three hits and a cold run -> median of the hits only.
+ _line("2026-09-01", 100, 100.0, run_id=1, cache=HIT, imp=1.0),
+ _line("2026-09-01", 100, 296.0, run_id=2, cache=HIT, imp=3.0),
+ _line("2026-09-01", 100, 120.0, run_id=3, cache=HIT, imp=2.0),
+ _line("2026-09-01", 101, 900.0, run_id=4, cache=MISS, imp=9.0),
+ # 09-02: no hit at all -> median over every run; a null is left out.
+ _line("2026-09-02", 102, 50.0, run_id=5, cache=MISS),
+ _line("2026-09-02", 102, None, run_id=6),
+ _line("2026-09-02", 103, 70.0, run_id=7),
+ ])
+ first, second = timings.unit_history(tmp_path / "unit")["RepoA"]
+ assert (first["wall_s"], first["import_s"], first["tests"]) == (120.0, 2.0, 101)
+ assert (second["wall_s"], second["tests"]) == (60.0, 103)
+
+
+def test_unit_history_applies_the_epoch_to_the_day_it_plots(tmp_path):
+ _write(tmp_path, "RepoA", [
+ # Recorded the next day but run before the boundary: outside the epoch.
+ _line("2026-09-03", 100, 1.0, run_id=1, at="2026-09-02T17:30:00Z"),
+ # Recorded on the eve of the boundary but run on it: inside the epoch.
+ _line("2026-09-02", 200, 2.0, run_id=2, at="2026-09-03T01:00:00Z"),
+ # No usable `at`: the line's own date is the day, and the filter's day.
+ _line("2026-09-04", 300, 3.0, run_id=3, at=""),
+ ])
+ points = timings.unit_history(tmp_path / "unit", since="2026-09-03")["RepoA"]
+ assert [(p["date"], p["tests"]) for p in points] == [("2026-09-03", 200), ("2026-09-04", 300)]
+
+
+def _ys(html):
+ return [float(y) for y in re.findall(r'cy="([0-9.]+)"', html)]
+
+
+def test_a_sub_second_unit_trend_fills_the_chart_height():
+ history = {"RepoN": [{"date": f"2026-09-0{d}", "python": "3.12", "tests": 10,
+ "wall_s": 1.0, "import_s": v}
+ for d, v in ((1, 0.41), (2, 0.47), (3, 0.44))]}
+ ys = _ys(display.unit_trend(history, "RepoN", "3.12", "import_s"))
+ assert min(ys) == 15.0 and max(ys) == 75.0 # top to bottom, not 10-14% of it
+ # A flat series is drawn, on the floor, with no division by zero.
+ flat = {"RepoN": [dict(row, import_s=0.5) for row in history["RepoN"]]}
+ assert set(_ys(display.unit_trend(flat, "RepoN", "3.12", "import_s"))) == {75.0}
+
+
+def test_a_unit_trend_label_names_the_days_its_axis_draws():
+ history = {"RepoA": [{"date": "2026-09-01", "python": "3.12", "tests": 10, "wall_s": 1.0, "import_s": None},
+ {"date": "2026-09-03", "python": "3.12", "tests": 10, "wall_s": 1.0, "import_s": 0.5},
+ {"date": "2026-09-05", "python": "3.12", "tests": 10, "wall_s": 1.0, "import_s": 0.6},
+ {"date": "2026-09-07", "python": "3.12", "tests": 10, "wall_s": 1.0, "import_s": None}]}
+ html = display.unit_trend(history, "RepoA", "3.12", "import_s")
+ assert "import seconds on main, 2026-09-03 to 2026-09-05; 2 days with a main run" in html
+ assert '
2026-09-032026-09-05
' in html
+
+
+GOLDEN = Path(__file__).parent / "golden" / "gate_chart.html"
+
+
+def test_gate_charts_are_unchanged_byte_for_byte():
+ """The unit-trend fixes must not move a gate chart, sub-second gates included.
+
+ The golden file is the chart as it rendered before them. Regenerate it only
+ for a deliberate gate-chart change, and say so in the PR.
+ """
+ history = [{"date": "2026-09-01", "gates": {"unit": {"p50_s": 0.42}}},
+ {"date": "2026-09-02", "gates": {"unit": {"p50_s": 0.47}}},
+ {"date": "2026-09-04", "gates": {"unit": {"p50_s": 0.51}}},
+ {"date": "2026-09-05", "gates": {"unit": {"p50_s": None}}},
+ {"date": "2026-09-06", "gates": {"unit": {"p50_s": 0.44}}}]
+ assert display.chart(history, "unit") + "\n" == GOLDEN.read_text()