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

' + 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'

{escape(row["error"])}

' if row.get("error") else "" + identifiers = rows(row.get("slowest")) + full_names = ('

Full test identifiers

') 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'
  • {escape(short_name)} ' + f'{duration(row.get("seconds"))}
    {escape(comparison)}
  • ') + 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'{escape(label)}' + + ''.join(marks) + 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'

    {escape(name)}

    ' + f'
    {metric("Median", row.get("median_s"))}{metric("Max", row.get("max_s"))}
    ' + f'

    {escape(coverage)}

    {escape(comparison)}

    ' + + chart(ct.get("history"), f"{row.get('repo')}/{row.get('workflow')}") + + source(row, ct.get("ts"), "CI workflow wall-clock") + '
    ') + return plain, cards(rendered, "CI gates") diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index d78ad5a4..f42f4a4a 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -735,9 +735,9 @@ def test_ci_timing_section_states_and_summary(): assert "2 gates" in sec.summary assert "slowest RepoA Gate One 15m" in sec.summary assert "1 slowed" in sec.summary and "1 hang event" in sec.summary - # coverage beside time, always — and the gate's own history as a sparkline - assert sec.details[0].startswith("RepoA Gate One p50 15m max 20m (17 runs)") - assert sec.details[0].rstrip().endswith("▁▃█") + # Coverage beside time; accessible history is separate from the summary. + assert sec.details[0].startswith("RepoA · Gate One: median 900.00s · max 1,200.00s · 17 completed runs") + assert 'role="img"' in sec.timing_html def test_ci_timing_without_events_is_warn_when_a_gate_slowed(): @@ -1443,15 +1443,14 @@ def test_the_ingested_sections_render_their_detail_lines_only_with_the_slice(): unit_timings=_unit_timings_slice()), make_verdict(), now=FRESH_NOW) unit = _section(board, "unit_test_timing") - # Worst wall-clock first, with the slowest test in the suite beside it. - assert unit.details == [ - "RepoA py3.12: 1500 tests 7m slowest test_x 12.5s", - "RepoB py3.12: 200 tests 30s", - ] + # Suite wall-clock is separate from per-test comparisons and never summed. + assert unit.details[0].startswith("RepoA · Python 3.12: wall-clock 412.00s · 1500 tests") + assert "tests/foo/test_bar.py::test_x: 12.50s" in unit.details[1] + assert "measured regression" in unit.details[1] + assert unit.details[2].startswith("RepoB · Python 3.12: wall-clock 30.00s · 200 tests") imports = _section(board, "import_time") - # A null-seconds import has no number, so it gets no line — never a 0.00s. - assert imports.details == ["pkg_a py3.12: 3.60s"] - # ...and neither section's state came from the new lines. + assert "pkg_a · Python 3.12: 3.60s · Baseline 1.00s · change +260%" in imports.details[0] + assert "pkg_b · Python 3.12: unavailable" in imports.details[1] assert unit.state == dashboard.OK and imports.state == dashboard.OK @@ -1686,23 +1685,16 @@ def _unit_line(cache): return _section(board, "unit_test_timing").details[0] -def test_a_known_unit_cache_state_is_bracketed_on_the_suite_line(): - """Same format as the scripts row, in the shorter wording a unit line can - afford — and the numbers after it are untouched.""" - assert _unit_line({"jax": "hit", "numba": "miss", "epoch": "1"}) == ( - "RepoA py3.12 [jax hit, numba miss]: 1500 tests 7m slowest test_x 12.5s") - assert _unit_line({"jax": "miss", "numba": "miss", "epoch": "1"}) == ( - "RepoA py3.12 [jax miss, numba miss]: 1500 tests 7m slowest test_x 12.5s") - # One known half is still worth saying; the unknown half is simply absent. - assert _unit_line({"jax": "hit", "numba": "unknown"}) == ( - "RepoA py3.12 [jax hit]: 1500 tests 7m slowest test_x 12.5s") +def test_a_known_unit_cache_state_is_beside_the_suite_time(): + assert "jax cache hit · numba cache miss" in _unit_line({"jax": "hit", "numba": "miss"}) + assert "jax cache miss · numba cache miss" in _unit_line({"jax": "miss", "numba": "miss"}) + assert _unit_line({"jax": "hit", "numba": "unknown"}).endswith("jax cache hit") def test_an_unknown_or_absent_unit_cache_state_leaves_the_line_unchanged(): - """A leg from before the sidecar existed renders exactly as it always did — - no bracket, and certainly no claim that it ran cold.""" - unchanged = "RepoA py3.12: 1500 tests 7m slowest test_x 12.5s" - for cache in (None, {}, {"jax": "unknown", "numba": "unknown"}, + unchanged = _unit_line(None) + assert "cache" not in unchanged + for cache in ({}, {"jax": "unknown", "numba": "unknown"}, {"jax": "warm", "numba": None}, "nonsense"): assert _unit_line(cache) == unchanged diff --git a/tests/test_dashboard_timings.py b/tests/test_dashboard_timings.py new file mode 100644 index 00000000..bb6e967a --- /dev/null +++ b/tests/test_dashboard_timings.py @@ -0,0 +1,131 @@ +"""Timing clarity must not turn missing evidence into a passing measurement.""" +import copy +import json +import re + +import pytest + +from heart import dashboard, timing_display as display +from tests.test_dashboard import ( + FRESH_NOW, _ci_timing_slice, _legacy_import, _legacy_unit, + _section, _unit_timings_slice, make_snapshot, make_verdict, +) + + +def test_four_building_and_one_unavailable_import_are_not_green(): + snapshot = make_snapshot(import_time=_legacy_import( + packages_measured=4, green_count=0, new_packages_no_baseline=4, + packages_unavailable=["pkg_missing"])) + before = copy.deepcopy(snapshot) + board = dashboard.build_board(snapshot, make_verdict(), now=FRESH_NOW) + section = _section(board, "import_time") + assert section.state == dashboard.WARN + assert "4 baseline building" in section.summary + assert "1 unavailable" in section.summary + assert "0 imports within baseline" not in section.summary + assert "pkg_missing: unavailable" in section.details[0] + assert board.score == 100 and board.verdict == "green" # advisory != readiness + assert snapshot == before + + +@pytest.mark.parametrize("overrides,state", [ + ({"green_count": 0, "new_packages_no_baseline": 2}, dashboard.INFO), + ({"packages_measured": 0, "green_count": 0}, dashboard.WARN), + ({"green_count": 2}, dashboard.OK), + ({"red_count": 1, "new_packages_no_baseline": 1}, dashboard.FAIL), +]) +def test_import_coverage_preserves_real_regressions(overrides, state): + board = dashboard.build_board(make_snapshot(import_time=_legacy_import(**overrides)), + make_verdict(), now=FRESH_NOW) + assert _section(board, "import_time").state == state + + +def test_import_cards_keep_failed_rows_baseline_and_source(): + plain, html = display.imports(_unit_timings_slice(), {}) + assert "unavailable" in plain[1] and "0.00s" not in plain[1] + assert "Baseline 1.00s · change +260%" in html + assert "3 baseline samples" in html and "source run" in html + assert "Measured regression" in html + + +def test_suites_rank_tests_and_disclose_without_dropping_parallel_legs(): + data = _unit_timings_slice() + leg = data["repos"][0] + leg["slowest"] = [{"nodeid": f"test_{i}", "seconds": i} for i in range(6)] + data["repos"] = [dict(leg, python=f"3.{i}") for i in range(10, 18)] + plain, html = display.suites(data) + assert sum("wall-clock 412.00s" in s for s in plain) == 8 + assert "3,296" not in html # never sum parallel durations + assert "Show 5 more suite legs" in html + assert "Show 3 more measured tests" in html + assert html.index("test_5") < html.index("test_4") < html.index("test_3") < html.index("test_2") + assert "3 skipped" in html and "0 failures" in html + assert "No comparable previous run" in html + + +def test_previous_time_without_comparable_ratio_is_not_a_regression(): + data = _unit_timings_slice() + data["tests"][0]["ratio"] = None + _, html = display.suites(data) + assert "No comparable previous run" in html + assert "measured regression" not in html + + +def test_ci_chart_labels_statistics_and_leaves_missing_day_as_gap(): + ct = _ci_timing_slice() + ct["gates"][0]["window_from"] = "2026-08-01T00:00:00Z" + ct["history"][1]["gates"] = {} + plain, html = display.gates(ct) + assert "17 completed runs" in plain[0] and "2026-08-01" in plain[0] + assert html.index("Median") < html.index("unavailable" in section.timing_html diff --git a/tests/test_fix.py b/tests/test_fix.py index 003af5d5..52acafc2 100644 --- a/tests/test_fix.py +++ b/tests/test_fix.py @@ -94,9 +94,9 @@ def test_html_all_tiers_complete_disclosure_and_safe_fallback(): def test_numeric_emphasis_is_built_from_fields_and_escapes_subjects(): row = {"imports": [{"package": "", "python": "3.12", "seconds": 3.5}]} - html = dashboard._unit_import_details(row, html=True)[0] + plain, html = dashboard.timing_display.imports(row, {}) assert '<pkg>' in html and '3.50s' in html - assert dashboard._unit_import_details(row)[0] == " py3.12: 3.50s" + assert plain[0].startswith(" · Python 3.12: 3.50s") def test_bash_dispatch_exposes_all_topic(tmp_path): diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index fee45ff0..02613eeb 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -590,9 +590,9 @@ def test_the_ingested_summaries_drive_the_board_ok_warn_and_fail(tmp_path): unit, imports = ut.legacy_summaries(fail_roll, THRESHOLDS) sections = _board(unit_summary=unit, import_summary=imports) assert sections["unit_test_timing"].state == dashboard.FAIL - # The import summary of the same rollup measured its package and found - # nothing red: the two sections are fed from one rollup and judge apart. - assert sections["import_time"].state == dashboard.OK + # No import baseline exists yet: absence of a regression is not a pass. + assert sections["import_time"].state == dashboard.INFO + assert "baseline building" in sections["import_time"].summary # --- thresholds --------------------------------------------------------------