From 7604b4decf2a75e882f0c78c110ed5f72a61cef1 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 12 Nov 2026 19:05:29 +0000 Subject: [PATCH] feat(board): unit-test trends on every suite and import card + organism total The unit record (timings/unit/.jsonl) has been written daily since 2026-09-06, but the board drew a trend only for CI gates: 27 of 27 gate cards carried a chart, 0 of 12 unit-suite and 0 of 12 import cards did. - heart.timings.unit_history: main-branch lines only, one point per (python leg, run day), last run of the day wins, epoch-bounded. - `timings append` writes it beside the census (timings_record.json), after today's lines land, so the charts end on today. census() and `show` are unchanged. - timing_display: chart() generalised into plot(); gate output unchanged. Suite cards draw wall-clock and test count; import cards draw import seconds; one "Organism total" card with the summed test count trend. - A render handed no record (dev box) draws nothing rather than "no history". Refs PyAutoLabs/PyAutoHeart#338 (SIG-2). SIG-3 (Brain hygiene ledger) is out of this worktree's scope and left for a PyAutoBrain task. Co-Authored-By: Claude Opus 5.5 --- heart/dashboard.py | 23 ++++++- heart/timing_display.py | 137 ++++++++++++++++++++++++++++++++------ heart/timings.py | 58 ++++++++++++++++ tests/test_unit_trends.py | 115 ++++++++++++++++++++++++++++++++ 4 files changed, 312 insertions(+), 21 deletions(-) create mode 100644 tests/test_unit_trends.py diff --git a/heart/dashboard.py b/heart/dashboard.py index ff5d9f00..f33d98ce 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -442,6 +442,18 @@ def _as_int(v: Any, default: int = 0) -> int: return default +def _unit_history(snapshot: dict) -> dict | None: + """The unit record's main-branch trend (``heart.timings.unit_history``). + + The daily job's ``timings append`` writes it beside the census, after + today's lines land. ``None`` when this render was handed no record (a + dev-box board), so the cards say nothing rather than "no history". + """ + record = snapshot.get("timings_record") + history = record.get("unit_history") if isinstance(record, dict) else None + return history if isinstance(history, dict) else None + + def _as_float(v: Any, default: float | None = None) -> float | None: """A float, or ``default``. ``bool`` is not a number here, nor is junk.""" if isinstance(v, bool): @@ -859,7 +871,8 @@ def build_board( summary += f" · {building} baseline building" if unavailable: summary += f" · {unavailable} unavailable" - details, timing_html = timing_display.imports(snapshot.get("unit_timings"), imp) + details, timing_html = timing_display.imports(snapshot.get("unit_timings"), imp, + _unit_history(snapshot)) sections.append(Section("import_time", "Import timing", st, summary, details, timing_html=timing_html)) @@ -887,12 +900,18 @@ def build_board( 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")) + history = _unit_history(snapshot) + suite_details, timing_html = timing_display.suites(snapshot.get("unit_timings"), history) if details and timing_html: timing_html = ('

Measured regressions

    ' + ''.join(f'
  • {_html.escape(d)}
  • ' for d in details) + '
' + timing_html) details += suite_details + # The organism's whole unit suite in one row, with its trend. + total_line, total_html = timing_display.organism_total(history) + if total_line: + details.append(total_line) + timing_html = total_html + (timing_html or "") sections.append(Section("unit_test_timing", "Unit-test timing", st, summary, details, timing_html=timing_html)) diff --git a/heart/timing_display.py b/heart/timing_display.py index 138a141f..6652e765 100644 --- a/heart/timing_display.py +++ b/heart/timing_display.py @@ -68,7 +68,7 @@ def change(row, baseline_key="baseline_s"): return f"Baseline {duration(baseline)} · change {delta:+.0f}%" -def imports(slice_, summary): +def imports(slice_, summary, history=None): slice_ = slice_ if isinstance(slice_, dict) else {} measured = rows(slice_.get("imports")) ci = bool(measured) @@ -91,11 +91,12 @@ def imports(slice_, summary): rendered.append(f'

{escape(name)}

' f'
{metric("Current", row.get("seconds"))}
' f'

{escape(comparison)}

{escape(status)} · {escape(coverage)}

' - f'{source(row, slice_.get("ts") or summary.get("ts"), "CI import probe" if ci else "Local import probe")}
') + + (unit_trend(history, row.get("repo"), row.get("python"), "import_s") if ci and row.get("repo") else "") + + f'{source(row, slice_.get("ts") or summary.get("ts"), "CI import probe" if ci else "Local import probe")}') return plain, cards(rendered, "imports") -def suites(slice_): +def suites(slice_, history=None): slice_ = slice_ if isinstance(slice_, dict) else {} legs = sorted(rows(slice_.get("repos")), key=lambda r: -(seconds(r.get("wall_s")) or 0)) comparisons = {(r.get("repo"), r.get("python"), r.get("nodeid")): r for r in rows(slice_.get("tests"))} @@ -129,30 +130,38 @@ def suites(slice_): rendered.append(f'

{escape(name)}

' f'
{metric("Suite wall-clock", leg.get("wall_s"))}
' f'

{escape(counts)}

' + (f'

{escape(cache_text)}

' if cache_text else '') + + unit_trend(history, leg.get("repo"), leg.get("python"), "wall_s") + + unit_trend(history, leg.get("repo"), leg.get("python"), "tests") + '

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'{escape(label)}' + ''.join(marks) + 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 "
  • 2026-09-05: 1,700
  • " in html + assert display.organism_total({}) == (None, "") + assert display.organism_total(None) == (None, "") + + +def test_unit_section_carries_the_total_row_and_charts_only_with_a_record(): + snapshot = make_snapshot(unit_timings=_unit_timings_slice(), import_time=_legacy_import(), + unit_test_timing=_legacy_unit(), + timings_record={"unit_history": _history()}) + board = dashboard.build_board(snapshot, make_verdict(), now=FRESH_NOW) + unit = _section(board, "unit_test_timing") + assert unit.details[-1].startswith("Organism total: 1,700 unit tests") + assert unit.timing_html.index("Organism total") < unit.timing_html.index("Suite wall-clock") + assert "import seconds on main" in _section(board, "import_time").timing_html + + plain = dashboard.build_board(make_snapshot(unit_timings=_unit_timings_slice(), + unit_test_timing=_legacy_unit()), + make_verdict(), now=FRESH_NOW) + assert "Organism total" not in _section(plain, "unit_test_timing").timing_html