diff --git a/docs/internals.md b/docs/internals.md
index e9c3d602..947b12a8 100644
--- a/docs/internals.md
+++ b/docs/internals.md
@@ -49,6 +49,16 @@ including its evidence and prompt. Entries containing private local paths stay
local. Fresh observations retain their timestamp; expired observations remain
unobserved on the cloud board.
+Timing cards are a pure presentation layer in `heart/timing_display.py`.
+They expose seconds, comparison coverage and source separately; missing imports
+and baseline-building observations never imply a passing comparison. Suite
+legs stay separate (parallel wall-clocks are never summed); the three slowest
+measured tests appear first, with remaining tests and legs under disclosures.
+CI charts use dated daily medians with gaps for missing observations and an
+equivalent text list. `performance` schema 1, its values and `gates[].spark`
+remain unchanged for Brain and hygiene consumers. Plain section details retain
+all measured rows; disclosures are HTML-only.
+
## Repo structure
```
diff --git a/heart/dashboard.py b/heart/dashboard.py
index 0aaf1efc..03ddaa7f 100644
--- a/heart/dashboard.py
+++ b/heart/dashboard.py
@@ -54,7 +54,7 @@
from dataclasses import dataclass, field
from typing import Any, Iterable, Sequence
-from heart import _workspace, validate
+from heart import _workspace, validate, timing_display
from heart.checks.test_run import counts_measured as tr_counts_measured
from heart.heart_color import (
c_bold, c_dim, c_fail, c_info, c_meta, c_ok, c_warn,
@@ -260,6 +260,7 @@ class Section:
# HTML-only projection built from measurement fields, never parsed prose.
detail_html: list[str] = field(default_factory=list)
entries: list[dict] = field(default_factory=list)
+ timing_html: str = ""
@dataclass
@@ -365,12 +366,6 @@ def _dur(seconds: Any) -> str:
return f"{int(round(seconds / 60))}m"
-# How many ingested unit rows a section shows before it is a wall of text. Six
-# is two python legs across three libraries — enough to see the shape, short
-# enough to stay a detail block under a one-line summary.
-UNIT_DETAIL_CAP = 6
-
-
def _setup_seconds(cache):
"""A leg's measured setup seconds out of its cache block, or ``None``.
@@ -411,77 +406,6 @@ def _cache_bracket(cache: Any, jax_label: str = "jax") -> str:
return f" [{', '.join(parts)}]" if parts else ""
-def _unit_suite_details(slice_: Any, *, html: bool = False) -> list[str]:
- """One line per ingested suite leg, slowest wall-clock first.
-
- Fed by ``heart/checks/unit_timings.py``'s rollup (#206). The legacy summary
- above counts regressions; this says what was measured — how long each
- library's suite takes on CI and what the slowest test in it is. Absent slice
- => no lines at all, so a snapshot from before the ingest renders exactly as
- it did.
- """
- if not isinstance(slice_, dict):
- return []
- legs = [leg for leg in (slice_.get("repos") or []) if isinstance(leg, dict)]
- legs.sort(key=lambda leg: (-(_as_float(leg.get("wall_s")) or 0.0),
- str(leg.get("repo") or ""),
- str(leg.get("python") or "")))
- lines: list[str] = []
- for leg in legs[:UNIT_DETAIL_CAP]:
- repo = str(leg.get("repo") or "?")
- python = str(leg.get("python") or "?")
- tests = _as_int(leg.get("tests"))
- # Same bracket as the scripts row, in the shorter wording a unit line
- # can afford: `RepoA py3.12 [jax hit, numba miss]: 1500 tests 6m52s`.
- bracket = _cache_bracket(leg.get("cache"))
- duration = _dur(leg.get('wall_s'))
- if html:
- repo, python, bracket = map(_html.escape, (repo, python, bracket))
- duration = f'{duration}'
- line = (f"{repo} py{python}{bracket}: "
- f"{tests} tests {duration}")
- slowest = [row for row in (leg.get("slowest") or []) if isinstance(row, dict)]
- if slowest:
- top = slowest[0]
- seconds = _as_float(top.get("seconds"))
- nodeid = str(top.get("nodeid") or "?").split("::")[-1]
- if seconds is not None:
- value = f"{seconds:.1f}s"
- if html:
- nodeid = _html.escape(nodeid)
- value = f'{value}'
- line += f" slowest {nodeid} {value}"
- lines.append(line)
- return lines
-
-
-def _unit_import_details(slice_: Any, *, html: bool = False) -> list[str]:
- """One line per ingested import measurement (#206).
-
- A package whose import failed carries ``seconds: null`` — no number, so no
- line: a fabricated 0.00s would be worse than the silence, and the row is
- already counted as unavailable in the summary above.
- """
- if not isinstance(slice_, dict):
- return []
- lines: list[str] = []
- for row in (slice_.get("imports") or []):
- if not isinstance(row, dict):
- continue
- seconds = _as_float(row.get("seconds"))
- if seconds is None:
- continue
- subject = f"{row.get('package') or '?'} py{row.get('python') or '?'}"
- value = f"{seconds:.2f}s"
- if html:
- subject = _html.escape(subject)
- value = f'{value}'
- lines.append(f"{subject}: {value}")
- if len(lines) >= UNIT_DETAIL_CAP:
- break
- return lines
-
-
def _gate_spark(history: Sequence[Any], key: str) -> str:
"""The sparkline of one gate's daily p50s, oldest first."""
values: list[float] = []
@@ -880,28 +804,25 @@ def build_board(
r = _as_int(imp.get("red_count"))
y = _as_int(imp.get("yellow_count"))
g = _as_int(imp.get("green_count"))
+ building = _as_int(imp.get("new_packages_no_baseline"))
+ unavailable = len(imp.get("packages_unavailable") or [])
if r:
st, summary = FAIL, f"{r} import regressions (>3× baseline), {y} slow (>1.5×)"
elif y:
st, summary = WARN, f"{y} imports >1.5× baseline, {g} within"
elif not _as_int(imp.get("packages_measured")):
st, summary = WARN, "no libraries importable (set HYGIENE_PYTHON)"
+ elif unavailable or building or not g:
+ st, summary = (WARN if unavailable else INFO), "import comparisons incomplete"
else:
st, summary = OK, f"{g} imports within baseline"
- details = [
- f"✗ {e['package']} "
- f"{e['latest_seconds']:.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)"
- for e in (imp.get("red") or [])[:5]
- ]
- # What was actually measured, when the CI ingest observed it: the
- # summary above counts regressions, and a row that says only "3
- # imports within baseline" never says how long an import takes.
- # Purely additive — the section's state logic is untouched.
- detail_html = [_html.escape(d) for d in details]
- detail_html += _unit_import_details(snapshot.get("unit_timings"), html=True)
- details += _unit_import_details(snapshot.get("unit_timings"))
+ if building:
+ summary += f" · {building} baseline building"
+ if unavailable:
+ summary += f" · {unavailable} unavailable"
+ details, timing_html = timing_display.imports(snapshot.get("unit_timings"), imp)
sections.append(Section("import_time", "Import timing", st, summary, details,
- detail_html=detail_html))
+ timing_html=timing_html))
# Unit-test timing (advisory; off-tick) -----------------------------------
if "unit_test_timing" in unobserved:
@@ -925,14 +846,14 @@ def build_board(
f"{e['latest_seconds']:.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)"
for e in (ut.get("red") or [])[:5]
]
- # The suites behind the summary, slowest wall-clock first: which
- # library's suite costs what, and the single slowest test in it.
- # Purely additive — the section's state logic is untouched.
- detail_html = [_html.escape(d) for d in details]
- detail_html += _unit_suite_details(snapshot.get("unit_timings"), html=True)
- details += _unit_suite_details(snapshot.get("unit_timings"))
+ suite_details, timing_html = timing_display.suites(snapshot.get("unit_timings"))
+ if details and timing_html:
+ timing_html = ('
Measured regressions
' +
+ ''.join(f'
{_html.escape(d)}
' for d in details) +
+ '
' + timing_html)
+ details += suite_details
sections.append(Section("unit_test_timing", "Unit-test timing", st, summary, details,
- detail_html=detail_html))
+ timing_html=timing_html))
# Profiling pinned-value drift -------------------------------------------
if "profiling_drift" in unobserved:
@@ -1291,6 +1212,8 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],
st = FAIL
elif warned or errors:
st = WARN
+ elif not timed:
+ st = INFO
else:
st = OK
@@ -1306,19 +1229,13 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],
if errors:
bits.append(f"{len(errors)} unavailable")
- details = []
- for g in sorted(timed, key=lambda g: g.get("median_s") or 0, reverse=True)[:5]:
- # Coverage beside time, always: a speed row without the run count
- # rewards a gate that got faster by running less.
- line = (f"{g.get('repo')} {g.get('workflow')} p50 {_dur(g.get('median_s'))} "
- f"max {_dur(g.get('max_s'))} ({_as_int(g.get('runs_counted'))} runs)")
- spark = _gate_spark(history, f"{g.get('repo')}/{g.get('workflow')}")
- details.append(f"{line} {spark}" if spark else line)
+ details, timing_html = timing_display.gates(ct)
# How much durable history stands behind those sparklines. Absent census
# (an older snapshot) adds no line at all.
gates_line = _record_lines(record)[0]
if gates_line:
details.append(gates_line)
+ timing_html += f"
{_html.escape(gates_line)}
"
links = [
{"label": f"{e.get('repo')} {e.get('kind')}", "url": str(e.get("run_url")),
@@ -1335,7 +1252,7 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict],
action = {"label": "copy the slowdown prompt", "payload": str(warned[0]["prompt"])}
return Section("ci_timing", "CI wall-clock", st, " · ".join(bits), details,
- links=links, action=action)
+ links=links, action=action, timing_html=timing_html)
def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict],
@@ -2076,8 +1993,9 @@ def _html_reason(item: dict) -> str:
summary{cursor:pointer;overflow-wrap:anywhere;white-space:normal;padding:.6rem 0;
color:var(--fg)}
summary:focus-visible,button:focus-visible{outline:3px solid var(--fg);outline-offset:3px}
-body button.copy,body table button.copy{min-width:44px;min-height:44px;
- width:auto;height:auto;padding:.55rem .8rem;white-space:normal;font-size:1rem}
+body button.copy,body table.board button.copy.text{min-width:44px;min-height:44px;
+ width:auto;height:auto;padding:.55rem .8rem;white-space:normal;font-size:1rem;
+ overflow:visible;text-overflow:clip}
.actions{display:flex;gap:.65rem;flex-wrap:wrap;margin:1rem 0}
.actions button{font-weight:650}
.prompt-fallback pre,#copy-fallback{white-space:pre-wrap;overflow-wrap:anywhere;
@@ -2093,6 +2011,25 @@ def _html_reason(item: dict) -> str:
#copy-status{min-height:1.5em}
"""
+_EXTRA_CSS += """
+.timings{margin-top:.8rem;min-width:0}
+.timing-card{border:1px solid var(--line);border-radius:10px;padding:1rem;margin:.75rem 0;
+ overflow-wrap:anywhere;min-width:0;color:var(--fg)}
+.timing-card h4{font:inherit;font-weight:700;color:var(--fg);margin:0 0 .65rem}
+.timing-card p{margin:.6rem 0}
+.timing-metrics{display:flex;gap:.6rem 1.5rem;flex-wrap:wrap}
+.timing-metrics span{display:flex;flex-direction:column}
+.timings .duration{color:#075a9c;font-size:1.25rem}
+@media(prefers-color-scheme:dark){.timings .duration{color:#7cc9ff}}
+.bottlenecks{padding-left:1.3rem}.bottlenecks li{margin:.8rem 0}
+.test-name{overflow-wrap:anywhere}
+.timing-chart{margin:1rem 0 0;max-width:30rem}.timing-chart svg{display:block;width:100%;height:auto;color:#075a9c}
+.timing-chart polyline{fill:none;stroke:currentColor;stroke-width:2}
+.timing-chart circle{fill:currentColor}
+@media(prefers-color-scheme:dark){.timing-chart svg{color:#7cc9ff}}
+.chart-dates{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap}
+"""
+
# Heart owns truthful clipboard feedback; the family listener calls this
# override at click time. Never display success after a rejected copy.
_COPY_JS = """
@@ -2206,7 +2143,9 @@ def _render_html(board: Board) -> str:
"copy command" if payload.startswith("pyauto-heart ")
else "copy prompt")
details = ""
- if sec.entries:
+ if sec.timing_html:
+ details = sec.timing_html
+ elif sec.entries:
opened = " open" if sec.state in (FAIL, WARN) else ""
details = (f'{_html.escape(sec.title)} — '
f'observations ({len(sec.entries)}){_html_entries(sec.entries)}')
diff --git a/heart/timing_display.py b/heart/timing_display.py
new file mode 100644
index 00000000..138a141f
--- /dev/null
+++ b/heart/timing_display.py
@@ -0,0 +1,190 @@
+"""Pure timing presentation. Never changes collector data or readiness policy."""
+
+import datetime
+import html
+import math
+
+
+def escape(value):
+ return html.escape(str(value if value is not None else "unknown"))
+
+
+def rows(value):
+ return [r for r in value if isinstance(r, dict)] if isinstance(value, list) else []
+
+
+def seconds(value):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ return value if math.isfinite(value) and value >= 0 else None
+
+
+def duration(value):
+ value = seconds(value)
+ return "unavailable" if value is None else f"{value:,.2f}s"
+
+
+def metric(label, value):
+ return f'{escape(label)} {duration(value)}'
+
+
+def date_label(value):
+ try:
+ return datetime.date.fromisoformat(str(value)[:10]).isoformat()
+ except ValueError:
+ return "unknown"
+
+
+def disclosure(label, body):
+ return f'{escape(label)}{body}'
+
+
+def cards(items, kind):
+ if not items:
+ return ""
+ shown = ''.join(items[:3])
+ if len(items) > 3:
+ shown += disclosure(f"Show {len(items) - 3} more {kind}", ''.join(items[3:]))
+ return f'
{shown}
'
+
+
+def source(row, stamp=None, label="CI measurement"):
+ url = str(row.get("run_url") or row.get("actions_url") or "")
+ link = f' · source run ↗' if url.startswith(("https://", "http://")) else ""
+ error = f'
') if identifiers else ""
+ return disclosure("Source and coverage", f'{escape(label)} · observed {escape(row.get("at") or stamp)}{link}{error}{full_names}')
+
+
+def change(row, baseline_key="baseline_s"):
+ baseline, now = seconds(row.get(baseline_key)), seconds(row.get("seconds"))
+ if now is None:
+ return "Unavailable / import failed; no duration measured"
+ if baseline is None or baseline <= 0:
+ return "Baseline building — no comparable baseline yet"
+ delta = (now / baseline - 1) * 100
+ return f"Baseline {duration(baseline)} · change {delta:+.0f}%"
+
+
+def imports(slice_, summary):
+ slice_ = slice_ if isinstance(slice_, dict) else {}
+ measured = rows(slice_.get("imports"))
+ ci = bool(measured)
+ if not measured:
+ # Older/local collectors expose only regression rows, not all imports.
+ measured = [dict(r, seconds=r.get("latest_seconds"), baseline_s=r.get("baseline_seconds"), state=state)
+ for state in ("red", "yellow") for r in rows(summary.get(state))]
+ measured += [{"package": p, "seconds": None} for p in summary.get("packages_unavailable", [])]
+ plain, rendered = [], []
+ for row in measured:
+ name = str(row.get("package") or "?")
+ if row.get("python"):
+ name += f" · Python {row['python']}"
+ status = ("Measured regression" if row.get("state") in ("red", "yellow") else
+ "Within baseline" if seconds(row.get("baseline_s")) and seconds(row.get("seconds")) is not None else
+ "No comparison")
+ comparison = change(row)
+ coverage = f"{row.get('samples', 'unknown')} baseline samples"
+ plain.append(f"{name}: {duration(row.get('seconds'))} · {comparison} · {coverage}")
+ 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")}')
+ return plain, cards(rendered, "imports")
+
+
+def suites(slice_):
+ 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"))}
+ plain, rendered = [], []
+ for leg in legs:
+ name = f"{leg.get('repo', '?')} · Python {leg.get('python', '?')}"
+ suite = leg.get("suite") if isinstance(leg.get("suite"), dict) else {}
+ counts = f"{leg.get('tests', 'unknown')} tests · " + " · ".join(
+ f"{suite.get(k, 'unknown')} {k}" for k in ("failures", "errors", "skipped"))
+ cache = leg.get("cache") if isinstance(leg.get("cache"), dict) else {}
+ cache_text = " · ".join(f"{k} cache {cache[k]}" for k in ("jax", "numba") if cache.get(k) in ("hit", "miss"))
+ plain.append(f"{name}: wall-clock {duration(leg.get('wall_s'))} · {counts}" + (f" · {cache_text}" if cache_text else ""))
+ tests = []
+ for row in sorted(rows(leg.get("slowest")), key=lambda r: -(seconds(r.get("seconds")) or 0)):
+ node = row.get("nodeid") or "?"
+ prev = comparisons.get((leg.get("repo"), leg.get("python"), node), {})
+ # Collector ratio=None means no comparable run (same run/cache change
+ # included). A previous duration alone must not imply a regression.
+ if seconds(prev.get("ratio")) is not None and seconds(prev.get("prev_s")) is not None:
+ comparison = f"Previous {duration(prev['prev_s'])} · change {(prev['ratio'] - 1) * 100:+.0f}%"
+ comparison += " · measured regression" if prev.get("state") == "warn" else " · within drift threshold"
+ else:
+ comparison = "No comparable previous run"
+ plain.append(f" {node}: {duration(row.get('seconds'))} · {comparison}")
+ short_name = str(node).split("::")[-1]
+ tests.append(f'
')
+ top = '' + ''.join(tests[:3]) + '' if tests else '
No per-test measurements available.
'
+ if len(tests) > 3:
+ top += disclosure(f"Show {len(tests) - 3} more measured tests", '' + ''.join(tests[3:]) + '')
+ 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 '') +
+ '
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"))))
+ valid = [(d, v) for d, v in points if v is not None]
+ if not valid:
+ return '
No measured daily history yet.
'
+ 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 segment:
+ marks.append('')
+ segment = []
+ last = day
+ if value is None:
+ 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)}')
+ 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) + '
'
+ return (f'{escape(label)}'
+ f'
Range {duration(low)} – {duration(high)}
'
+ f'
{start}{end}
'
+ + disclosure("Daily median values (text)", table) + '')
+
+
+def gates(ct):
+ plain, rendered = [], []
+ for row in sorted(rows(ct.get("gates")), key=lambda r: -(seconds(r.get("median_s")) or 0)):
+ name = f"{row.get('repo', '?')} · {row.get('workflow', '?')}"
+ window = f"Window {date_label(row.get('window_from'))} → {date_label(ct.get('ts'))}"
+ coverage = f"{row.get('runs_counted', 0)} completed runs · {window}"
+ plain.append(f"{name}: median {duration(row.get('median_s'))} · max {duration(row.get('max_s'))} · {coverage}")
+ comparison = (f"Baseline median {duration(row['baseline_s'])}" if seconds(row.get("baseline_s")) is not None else "Baseline building")
+ comparison += " · measured slowdown" if row.get("state") == "warn" else ""
+ rendered.append(f'