Slowest tests by duration · slowness alone is not a regression.
' + top +
source(leg, slice_.get("ts"), "CI suite; parallel Python legs are shown separately") + '')
return plain, cards(rendered, "suite legs")
-def chart(history, key):
- points = []
- for day in sorted(rows(history), key=lambda r: str(r.get("date") or "")):
- try:
- date = datetime.date.fromisoformat(str(day.get("date")))
- except ValueError:
- continue
- gates = day.get("gates") if isinstance(day.get("gates"), dict) else {}
- row = gates.get(key) if isinstance(gates.get(key), dict) else {}
- points.append((date, seconds(row.get("p50_s"))))
+def count(value):
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+ return "unavailable"
+ return f"{value:,}"
+
+
+def plot(points, label, fmt=duration, *, gaps=True, values="Daily median values"):
+ """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.
+ """
+ points = sorted(points, key=lambda p: p[0])
valid = [(d, v) for d, v in points if v is not None]
if not valid:
return '
No measured daily history yet.
'
+ if not gaps:
+ points = valid
low, high = min(v for _, v in valid), max(v for _, v in valid)
start, end = points[0][0], points[-1][0]
span = max((end - start).days, 1)
marks, segment, last = [], [], None
for day, value in points:
- if value is None or (last and (day - last).days > 1):
+ if value is None or (gaps and last and (day - last).days > 1):
if segment:
marks.append('')
segment = []
@@ -161,16 +170,106 @@ def chart(history, key):
continue
x, y = 10 + 300 * (day - start).days / span, 75 - 60 * (value - low) / max(high - low, 1)
segment.append(f"{x:.1f},{y:.1f}")
- marks.append(f'{day}: {duration(value)}')
+ marks.append(f'{day}: {fmt(value)}')
if segment:
marks.append('')
- label = f"{key}: daily median seconds, {start} to {end}; {len(valid)} measured days; gaps are unavailable"
- table = '
' + ''.join(f'
{d}: {duration(v)}
' for d, v in points) + '
'
+ table = '
' + ''.join(f'
{d}: {fmt(v)}
' for d, v in points) + '
'
return (f'{escape(label)}'
- f'
Range {duration(low)} – {duration(high)}
'
+ f'
Range {fmt(low)} – {fmt(high)}
'
f'
{start}{end}
'
- + disclosure("Daily median values (text)", table) + '')
+ + disclosure(f"{values} (text)", table) + '')
+
+
+def _day(value):
+ try:
+ return datetime.date.fromisoformat(str(value))
+ except ValueError:
+ return None
+
+
+def chart(history, key):
+ points = []
+ for day in sorted(rows(history), key=lambda r: str(r.get("date") or "")):
+ date = _day(day.get("date"))
+ if date is None:
+ continue
+ gates = day.get("gates") if isinstance(day.get("gates"), dict) else {}
+ row = gates.get(key) if isinstance(gates.get(key), dict) else {}
+ points.append((date, seconds(row.get("p50_s"))))
+ valid = [p for p in points if p[1] is not None]
+ if not valid:
+ return '
No measured daily history yet.
'
+ label = (f"{key}: daily median seconds, {points[0][0]} to {points[-1][0]}; "
+ f"{len(valid)} measured days; gaps are unavailable")
+ return plot(points, label)
+
+
+def unit_trend(history, repo, python, field):
+ """One library leg's main-branch trend from the committed unit record.
+
+ ``history`` is ``heart.timings.unit_history``'s ``{repo: [points]}``.
+ ``field`` is ``tests``, ``wall_s`` or ``import_s``.
+ """
+ if not isinstance(history, dict):
+ return "" # no record handed to this render (a dev-box board): say nothing
+ points = []
+ for row in rows(history.get(repo)):
+ if str(row.get("python") or "") != str(python or ""):
+ continue
+ date = _day(row.get("date"))
+ if date is None:
+ continue
+ 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)
+ 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")
+ return plot(points, label, count if field == "tests" else duration, gaps=False,
+ values="Values per main run day")
+
+
+def organism_total(history):
+ """The organism's unit-test count over time: ``(plain line, card html)``.
+
+ Per library and day, the largest count across its Python legs (a skipped
+ leg must not read as fewer tests); a library with no run that day carries
+ its last count forward. Days before every recorded library has a count are
+ left out, so the total never jumps when a library first appears.
+ """
+ history = history if isinstance(history, dict) else {}
+ per_repo = {}
+ for repo, points in history.items():
+ for row in rows(points):
+ date, tests = _day(row.get("date")), row.get("tests")
+ if date is None or count(tests) == "unavailable":
+ continue
+ day = per_repo.setdefault(repo, {})
+ day[date] = max(day.get(date, 0), tests)
+ if not per_repo:
+ return None, ""
+ latest, points = {}, []
+ for date in sorted({d for days in per_repo.values() for d in days}):
+ for repo, days in per_repo.items():
+ if date in days:
+ latest[repo] = days[date]
+ if len(latest) == len(per_repo):
+ points.append((date, sum(latest.values())))
+ total = sum(latest.values())
+ plain = f"Organism total: {total:,} unit tests across {len(per_repo)} libraries (latest main run of each)"
+ label = (f"Organism unit tests on main, {points[0][0]} to {points[-1][0]}; "
+ f"each library's latest count carried forward") if points else ""
+ html_ = (f'
Organism total · unit tests
'
+ f'
Tests {count(total)}
'
+ f'
{escape(len(per_repo))} libraries · latest main run of each · from the committed timing record
'
+ + (plot(points, label, count, gaps=False, values="Totals per day") if points else
+ '
No day yet on which every library has a count.
') + '')
+ return plain, f'
{html_}
'
def gates(ct):
diff --git a/heart/timings.py b/heart/timings.py
index 036578f0..f343b730 100644
--- a/heart/timings.py
+++ b/heart/timings.py
@@ -902,6 +902,59 @@ def import_history(
return out
+def unit_history(
+ unit_dir: Path | str = UNIT_DIR, since: str = "", cap: int = 90
+) -> dict[str, list[dict[str, Any]]]:
+ """``{repo: [{"date", "python", "tests", "wall_s", "import_s"}, ...]}``.
+
+ The board's trend view of the unit record: suite size and suite wall-clock
+ per library and Python leg, oldest first. Only ``main`` lines count — a
+ feature branch's suite is not the library's suite, and mixing the two
+ 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.
+ ``since`` is the current epoch's date, as everywhere else in this record.
+ ``cap`` keeps the last N days per leg.
+ """
+ out: dict[str, list[dict[str, Any]]] = {}
+ root = Path(unit_dir)
+ if not root.is_dir():
+ return out
+ for path in sorted(root.glob("*.jsonl")):
+ repo = path.name[: -len(".jsonl")]
+ records, _ = read_jsonl(path)
+ days: dict[tuple[str, str], dict[str, Any]] = {}
+ for record in records:
+ if record.get("head_branch") != "main" or not _within_epoch(record, since):
+ 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):
+ 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,
+ "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")),
+ }
+ points: list[dict[str, Any]] = []
+ for python in sorted({p for p, _ in days}):
+ leg = sorted((v for (p, _), v in days.items() if p == python),
+ key=lambda v: v["date"])
+ points.extend(leg[-int(cap):] if cap and int(cap) > 0 else leg)
+ if points:
+ out[repo] = points
+ return out
+
+
# --- census ------------------------------------------------------------------
def census(directory: Path | str = TIMINGS_DIR) -> dict[str, Any]:
"""What the record holds — the one-screen answer, and the board's detail.
@@ -1010,6 +1063,11 @@ def _do_append(ns: argparse.Namespace) -> int:
# slice whether or not this run was handed a rollup for it.)
if ns.unit_timings:
payload["appended_today"]["unit"] = appended_unit
+ # The unit trend the board draws, read back AFTER today's append so the
+ # charts end on today. Beside the census, never inside `census()`: that is
+ # the record's key set (and `show`'s output), this is a view for the render.
+ since = (current_epoch(read_epochs(directory / "epochs.jsonl"), today) or {}).get("date") or ""
+ payload["unit_history"] = unit_history(directory / "unit", since=since)
out_path = Path(ns.census_out) if ns.census_out else _default_census_out()
try:
state.atomic_write_json(out_path, payload)
diff --git a/tests/test_unit_trends.py b/tests/test_unit_trends.py
new file mode 100644
index 00000000..4e1fc758
--- /dev/null
+++ b/tests/test_unit_trends.py
@@ -0,0 +1,115 @@
+"""The unit record drawn on the board: suite/import trends + the organism total."""
+import json
+
+from heart import dashboard, timings, timing_display as display
+from tests.test_dashboard import (
+ FRESH_NOW, _legacy_import, _legacy_unit, _section, _unit_timings_slice,
+ make_snapshot, make_verdict,
+)
+
+
+def _line(day, tests, wall, *, branch="main", python="3.12", run_id=1, at=None, imp=1.0):
+ 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,
+ "suite": {"tests": tests, "failures": 0, "errors": 0, "skipped": 0,
+ "wall_s": wall}}
+
+
+def _write(directory, repo, lines):
+ path = directory / "unit" / f"{repo}.jsonl"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ 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):
+ _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"),
+ _line("2026-09-02", 110, 11.0, run_id=3, at="2026-09-01T09:00:00Z"),
+ _line("2026-09-03", 120, 12.0, run_id=4, python="3.13"),
+ _line("2026-09-04", True, -1, run_id=5, imp=None),
+ ])
+ 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.
+ 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[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
+
+
+def test_unit_history_respects_the_epoch_and_the_cap(tmp_path):
+ _write(tmp_path, "RepoA", [_line(f"2026-09-0{d}", 100 + d, 1.0, run_id=d) for d in range(1, 8)])
+ history = timings.unit_history(tmp_path / "unit", since="2026-09-03", cap=2)
+ assert [p["date"] for p in history["RepoA"]] == ["2026-09-06", "2026-09-07"]
+ assert timings.unit_history(tmp_path / "missing") == {}
+
+
+def test_append_hands_the_render_a_unit_history_that_ends_today(tmp_path):
+ record = tmp_path / "record"
+ _write(record, "RepoA", [_line("2026-09-01", 100, 10.0)])
+ out = tmp_path / "census.json"
+ assert timings.main(["append", "--dir", str(record), "--census-out", str(out),
+ "--today", "2026-09-02"]) == 0
+ payload = json.loads(out.read_text())
+ assert payload["unit_history"]["RepoA"][0]["tests"] == 100
+ # The census itself (the record's key set, `show`) is unchanged.
+ assert "unit_history" not in timings.census(record)
+
+
+def _history():
+ return {"RepoA": [{"date": "2026-09-01", "python": "3.12", "tests": 1400, "wall_s": 300.0, "import_s": 3.0},
+ {"date": "2026-09-05", "python": "3.12", "tests": 1500, "wall_s": 412.0, "import_s": 3.6}],
+ "RepoB": [{"date": "2026-09-03", "python": "3.12", "tests": 200, "wall_s": 30.0, "import_s": None}]}
+
+
+def test_every_suite_card_draws_wall_clock_and_test_count_from_the_record():
+ _, html = display.suites(_unit_timings_slice(), _history())
+ assert html.count('class="timing-chart"') == 4 # two legs x (wall-clock, tests)
+ assert "RepoA · Python 3.12: suite wall-clock seconds on main" in html
+ assert "Range 1,400 – 1,500" in html and "Range 300.00s – 412.00s" in html
+ # Runs are not daily: the measured points are joined, not broken at gaps.
+ segments = html.count("2026-09-03: 1,600" in html and "