Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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 = ('<p>Measured regressions</p><ul>' +
''.join(f'<li>{_html.escape(d)}</li>' for d in details) +
'</ul>' + 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))

Expand Down
137 changes: 118 additions & 19 deletions heart/timing_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -91,11 +91,12 @@ def imports(slice_, summary):
rendered.append(f'<article class="timing-card"><h4>{escape(name)}</h4>'
f'<div class="timing-metrics">{metric("Current", row.get("seconds"))}</div>'
f'<p>{escape(comparison)}</p><p>{escape(status)} · {escape(coverage)}</p>'
f'{source(row, slice_.get("ts") or summary.get("ts"), "CI import probe" if ci else "Local import probe")}</article>')
+ (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")}</article>')
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"))}
Expand Down Expand Up @@ -129,30 +130,38 @@ def suites(slice_):
rendered.append(f'<article class="timing-card"><h4>{escape(name)}</h4>'
f'<div class="timing-metrics">{metric("Suite wall-clock", leg.get("wall_s"))}</div>'
f'<p>{escape(counts)}</p>' + (f'<p>{escape(cache_text)}</p>' 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") +
'<p>Slowest tests by duration · slowness alone is not a regression.</p>' + top +
source(leg, slice_.get("ts"), "CI suite; parallel Python legs are shown separately") + '</article>')
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 '<p>No measured daily history yet.</p>'
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('<polyline points="' + ' '.join(segment) + '"/>')
segment = []
Expand All @@ -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'<circle cx="{x:.1f}" cy="{y:.1f}" r="3"><title>{day}: {duration(value)}</title></circle>')
marks.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="3"><title>{day}: {fmt(value)}</title></circle>')
if segment:
marks.append('<polyline points="' + ' '.join(segment) + '"/>')
label = f"{key}: daily median seconds, {start} to {end}; {len(valid)} measured days; gaps are unavailable"
table = '<ul>' + ''.join(f'<li>{d}: {duration(v)}</li>' for d, v in points) + '</ul>'
table = '<ul>' + ''.join(f'<li>{d}: {fmt(v)}</li>' for d, v in points) + '</ul>'
return (f'<figure class="timing-chart"><figcaption>{escape(label)}</figcaption>'
f'<div class="chart-range">Range {duration(low)} – {duration(high)}</div>'
f'<div class="chart-range">Range {fmt(low)} – {fmt(high)}</div>'
f'<svg viewBox="0 0 320 90" role="img" aria-label="{escape(label)}"><title>{escape(label)}</title>'
+ ''.join(marks) + f'</svg><div class="chart-dates"><span>{start}</span><span>{end}</span></div>'
+ disclosure("Daily median values (text)", table) + '</figure>')
+ disclosure(f"{values} (text)", table) + '</figure>')


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 '<p>No measured daily history yet.</p>'
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 '<p>No main-branch history in the timing record yet.</p>'
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'<article class="timing-card"><h4>Organism total · unit tests</h4>'
f'<div class="timing-metrics"><span>Tests <strong class="duration">{count(total)}</strong></span></div>'
f'<p>{escape(len(per_repo))} libraries · latest main run of each · from the committed timing record</p>'
+ (plot(points, label, count, gaps=False, values="Totals per day") if points else
'<p>No day yet on which every library has a count.</p>') + '</article>')
return plain, f'<div class="timings">{html_}</div>'


def gates(ct):
Expand Down
58 changes: 58 additions & 0 deletions heart/timings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading