From 10e49a9c55b6d8965d6e8ec2e5d82b0e3e2fea37 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 18:52:39 +0000 Subject: [PATCH] =?UTF-8?q?feat(smoke=5Ftimings):=20ingest=20per-script=20?= =?UTF-8?q?smoke=20timings=20onto=20the=20=E2=8F=B1=20board=20(#202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The daily heart-health run now fetches each smoke-gate repo's newest smoke-timings- artifact via the Actions API, parses the smoke_timings/1 dataset, and renders per-script rows next to the workflow-level gates: slowest scripts per repo, TIMEOUT rows as hard events with a /bug prompt, run-to-run slowdowns as advisory warn rows (2.0x AND >=5s, declared in config/repos.yaml). The previous observation is self-carried through the published board.json's performance.scripts block, keyed by run id so a re-render never compares a run against itself; durable history is phase 2 of the ci-timing-fast-tests epic. Readiness verdict and badge untouched. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0151gQm9fk3XGLi5f18Urdba --- .github/workflows/heart-health.yml | 38 +- config/repos.yaml | 11 + heart/checks/smoke_timings.py | 811 +++++++++++++++++++++++++++++ heart/checks/smoke_timings.sh | 155 ++++++ heart/dashboard.py | 109 +++- heart/state.py | 1 + tests/test_dashboard.py | 177 +++++++ tests/test_heart_health_wiring.py | 65 +++ tests/test_smoke_timings.py | 479 +++++++++++++++++ tests/test_smoke_timings_script.py | 130 +++++ 10 files changed, 1952 insertions(+), 24 deletions(-) create mode 100644 heart/checks/smoke_timings.py create mode 100755 heart/checks/smoke_timings.sh create mode 100644 tests/test_heart_health_wiring.py create mode 100644 tests/test_smoke_timings.py create mode 100644 tests/test_smoke_timings_script.py diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index 3c20dd81..8e9a8818 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -4,9 +4,9 @@ name: Heart Health # the ONE unified health dashboard (heart/dashboard.py) alongside the existing # alerting. # -# It runs the four checks that need only the GitHub API (no local working tree) — -# CI status, open PRs, CI wall-clock timing and the NO_RUN census — across every -# polled repo, then: +# It runs the five checks that need only the GitHub API (no local working tree) — +# CI status, open PRs, CI wall-clock timing, the NO_RUN census and the +# per-script smoke timings — across every polled repo, then: # 1. renders the unified board (one renderer, many formats) and publishes it # three ways, all from the SAME snapshot so they cannot disagree: # * GitHub Pages — self-contained fmt="html" + a shields badge.json @@ -37,11 +37,15 @@ on: # contents: write → commit the README badge/block into Heart's OWN README # issues: write → the [heart-health] tracking issue # pages/id-token → publish the Pages board +# actions: read → list and download workflow artifacts (smoke_timings). The +# artifact endpoints need this scope even for the repo's own +# artifacts, and the default token grant does not include it. permissions: contents: write issues: write pages: write id-token: write + actions: read # Never let two runs publish Pages at once. cancel-in-progress is false so a # newer run QUEUES behind an in-progress one rather than cancelling it — we don't @@ -81,21 +85,33 @@ jobs: - name: Install PyYAML run: pip install --quiet pyyaml - - name: Run cloud-safe checks (ci_status, open_prs, ci_timing, no_run_census) + - name: Run cloud-safe checks (ci_status, open_prs, ci_timing, no_run_census, smoke_timings) env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # The repo-scoped GITHUB_TOKEN is enough for every check here except + # the artifact /zip downloads smoke_timings makes against OTHER repos: + # actions/download-artifact documents a cross-repo download as needing + # a token with actions:read ON THAT REPO, and the default token has no + # standing there — the endpoint answers 403. The check records that + # per repo as an honest error rather than a quiet-looking empty + # result, and the remedy is a secret, never a code change: a + # fine-grained PAT (Actions: read on the workspace repos) stored as + # HEART_TIMINGS_TOKEN. Absent that secret this falls back to the + # auto-provisioned token and Heart's own artifacts still ingest. + GH_TOKEN: ${{ secrets.HEART_TIMINGS_TOKEN || secrets.GITHUB_TOKEN }} run: | - # Four API-only checks: CI conclusions and open PRs (health), then CI - # wall-clock and the NO_RUN census (the ⏱ performance surface). - # ci_timing's aggregate step re-reads the board.json published by the - # previous run to carry its own per-gate history forward; a fetch - # failure there costs a sparkline, never the render. `set +e` keeps a - # single broken check from aborting the board. + # Five API-only checks: CI conclusions and open PRs (health), then CI + # wall-clock, the NO_RUN census and the per-script smoke timings (the + # ⏱ performance surface). ci_timing's and smoke_timings' aggregate + # steps re-read the board.json published by the previous run to carry + # their own history/previous observation forward; a fetch failure + # there costs a sparkline or a comparison, never the render. `set +e` + # keeps a single broken check from aborting the board. set +e bash heart/checks/ci_status.sh bash heart/checks/open_prs.sh bash heart/checks/ci_timing.sh bash heart/checks/no_run_census.sh + bash heart/checks/smoke_timings.sh exit 0 - name: Aggregate snapshot + compute readiness verdict diff --git a/config/repos.yaml b/config/repos.yaml index 1fdc634d..a0195c65 100644 --- a/config/repos.yaml +++ b/config/repos.yaml @@ -253,6 +253,17 @@ thresholds: yellow_factor: 1.5 # median / recent-history median >= this, AND min_delta_s: 120 # ... at least this many seconds slower history_cap: 30 # days of self-carried per-gate history + # Per-SCRIPT timing drift (heart/checks/smoke_timings.py). The same both-gates + # rule as ci_timing, with its own numbers because it is measuring a different + # size of thing: ci_timing's 1.5x / 120 s is sized for multi-minute gates, + # while a smoke script runs for 5-60 s and would never clear a 120 s floor no + # matter how badly it regressed. 2.0x is the profiling conductor's ratio, and + # a 5 s floor sits just above the ~5-7 s import-floor jitter every script + # pays. Advisory — a slowed script never reds the readiness verdict. + smoke_timings: + slow_factor: 2.0 # seconds / previous observation >= this, AND + min_delta_s: 5 # ... at least this many seconds slower + top_n: 5 # slowest scripts shown per repo on the board worktree_drift: orphan_red: true # orphan WT with uncommitted work → red orphan_yellow: true # orphan WT (clean) → yellow diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py new file mode 100644 index 00000000..68ffc2aa --- /dev/null +++ b/heart/checks/smoke_timings.py @@ -0,0 +1,811 @@ +"""heart/checks/smoke_timings.py — per-script CI timings (the fine-grained speed leg). + +``ci_timing`` measures the *gates* — how long a whole workflow keeps a +contributor waiting. That number moves for a reason, and until now the reason +was only recoverable by hand-scraping a job log before it expired: which script +inside the smoke suite got slower, which one hit its kill timer. The runners +already write that data (``smoke_timings.json``, the ``smoke_timings/1`` +dataset the shared result collector emits) and the PR gate already uploads +it as an artifact. This check *ingests* it: one row per script per repo per python +leg, standing on the ⏱ board beside the workflow-level gates. + +Two modes, same module (the ci_timing shape): + +* **per-repo** (``--name/--group/--owner``) — the bash entry point hands us one + repo's artifacts listing plus a directory of already-extracted artifacts, and + we write ``$HEART_PER_REPO_DIR/.smoke_timings.json``. +* **aggregate** (``--aggregate``) — read every sidecar plus the *previously + published* ``board.json`` and write the global rollup at + ``$HEART_STATE_DIR/smoke_timings.json``: per-repo/per-leg totals, every timed + row, run-to-run slowdowns, TIMEOUT events, and the errors. + +There is also a **--plan** mode: the shell leg needs to know *which* artifact +ids to download before it can download them, and the selection rule lives here +in Python rather than being re-derived in `jq`. + +Deliberate choices, each one a recorded lesson: + +* **Only the PR gate's artifact name is ingested.** ``ARTIFACT_RE`` matches + ``smoke-timings-.`` — the per-python-version legs of the smoke + gate. The WEEKLY sweep publishes ``smoke-timings-{scripts,notebooks}--`` + from a ~50-leg matrix; that is a different channel with a different cadence + and a different name shape, and it is deliberately NOT ingested here. Mixing + the two would compare a weekly full run against a PR smoke run and call the + difference a slowdown. +* **Newest non-expired artifact per name.** One row per python leg, from the + most recent run that still has a downloadable artifact. An expired artifact + is not data — GitHub deletes the blob and keeps the metadata. +* **``seconds: null`` is never zero.** The producer emits ``null`` for an entry + that never ran (skipped, or listed-but-missing). Counting those as 0 s would + put fabricated rows into a dataset whose whole purpose is timing, so a null + entry is carried as a row of the leg but never counted as ``timed`` and never + summed into ``total_s``. +* **Drift needs BOTH gates**, as in ci_timing: ``warn`` only when this run is + ≥ ``slow_factor`` × the previous observation AND ≥ ``min_delta_s`` slower. + The numbers differ from ci_timing's on purpose (scripts are seconds, not + minutes) and live in ``config/repos.yaml``, never here. +* **A run is never compared against itself.** The previous observation is + self-carried through the published board, so a re-render on the same day sees + the same run's rows. Every row carries its ``run_id``; a previous row from + the SAME run yields ``ok`` with no ratio rather than a reassuring 1.0×. +* **Drift is advisory.** Rows are ``ok`` or ``warn``, never ``fail``; only + TIMEOUT entries are hard rows. The readiness verdict is untouched — this is + a dashboard leg, not a gate. +* **A failed fetch is not a quiet repo.** ``--fetch-error`` records the reason + and writes NO legs; a leg whose download or parse failed keeps its provenance + with its own ``error`` and no entries. "We could not ask" must never render + as "all quiet", and one leg's 403 must never lose the other leg's data. + +Per-repo sidecar schema (``.smoke_timings.json``):: + + { + "name": "RepoA", "group": "workspaces", "owner": "OwnerX", + "error": "", # non-empty => the listing fetch failed + "ts": "...", + "legs": [ + {"python": "3.12", "artifact_id": 42, "run_id": 7, + "run_url": "https://github.com/OwnerX/RepoA/actions/runs/7", + "head_branch": "feat/x", "head_sha": "abc...", + "at": "2026-09-01T10:00:00Z", # the artifact's created_at + "env_profile": "smoke", "error": "", + "entries": [{"entry": "imaging/x.py", "kind": "script", + "status": "passed", "seconds": 12.5, "cap_s": 600.0, + "exit_code": 0}], + "counts": {"passed": 1, "failed": 0, "skipped": 0, "timeout": 0, + "timed": 1}, + "total_s": 12.5} + ] + } + +Global rollup schema (``smoke_timings.json``):: + + {"ts", + "repos": [{repo, python, run_id, run_url, head_branch, at, entries, + timed, total_s, error, slowest: [...]}], + "rows": [{repo, python, entry, kind, status, seconds, cap_s, exit_code, + run_id, run_url, prev_s, prev_run_id, ratio, delta_s, state, + prompt}], + "slowed": [...], "events": [...], "errors": [{repo, error}], + "thresholds": {...}} + +``rows`` is the block the NEXT render reads back as its previous observation +(through ``performance.scripts.rows`` on the published board), which is why +every row carries its ``run_id`` and ``run_url``. + +Every actionable row — a slowed script, a TIMEOUT — carries its own +ready-to-paste prompt string. The producer writes the prompt; the renderer +never re-derives it. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import re +import sys +from pathlib import Path +from typing import Any + +from heart.checks.ci_timing import read_prev_board # reused, never duplicated + +HEART_HOME = Path(__file__).resolve().parents[2] +CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" + +# The PR gate's per-python-version artifact, and ONLY that one. The weekly +# sweep's `smoke-timings-{scripts,notebooks}--` names are a +# different channel (different cadence, different matrix) and never match. +ARTIFACT_RE = re.compile(r"^smoke-timings-(\d+\.\d+)$") + +TIMINGS_FILENAME = "smoke_timings.json" +TIMINGS_SCHEMA = "smoke_timings/1" + +# Statuses the producer emits; counted per leg so the coverage behind a total +# stays visible next to it. +TRACKED_STATUSES = ("passed", "failed", "skipped", "timeout") + +# Fallback when config/repos.yaml is unreadable; kept in sync with the YAML. +DEFAULT_SMOKE_TIMINGS_THRESHOLDS = { + "slow_factor": 2.0, + "min_delta_s": 5, + "top_n": 5, +} + +NO_DATASET_ERROR = f"no {TIMINGS_FILENAME} in artifact" + + +# --- config ------------------------------------------------------------------ +def _load_config(config_path: Path | str = CONFIG_PATH) -> dict[str, Any]: + try: + import yaml + + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + return cfg if isinstance(cfg, dict) else {} + except Exception: + return {} + + +def load_thresholds(config_path: Path | str = CONFIG_PATH) -> dict[str, float]: + """Return the ``thresholds.smoke_timings`` block, defaulted key by key.""" + out = dict(DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + block = (_load_config(config_path).get("thresholds") or {}).get("smoke_timings") or {} + if isinstance(block, dict): + for key in out: + if isinstance(block.get(key), (int, float)) and not isinstance( + block.get(key), bool + ): + out[key] = block[key] + return out + + +# --- pure helpers ------------------------------------------------------------ +def _as_float(value: Any) -> float | None: + """A float, or None. ``bool`` is not a number here, and neither is junk.""" + if isinstance(value, bool) or value is None: + return None + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, str): + try: + return float(value.strip()) + except ValueError: + return None + return None + + +def _as_int(value: Any) -> int | None: + if isinstance(value, bool) or value is None: + return None + if isinstance(value, int): + return value + num = _as_float(value) + return int(num) if num is not None else None + + +def select_artifacts(listing: Any) -> list[dict[str, Any]]: + """The newest non-expired ``smoke-timings-`` artifact per python leg. + + Accepts the REST ``{"artifacts": [...]}`` object the shell leg fetches and + a bare list. Anything that is not an artifact object — a 404 body, a string, + a null — is skipped rather than raised over; this runs unattended. + + No URL is composed here: the selector is pure and knows nothing about a + GitHub host. ``build_sidecar`` owns ``run_url``, because it is the thing + that knows the owner and the repo name. + """ + if isinstance(listing, dict): + raw = listing.get("artifacts") or [] + elif isinstance(listing, list): + raw = listing + else: + raw = [] + if not isinstance(raw, list): + return [] + + best: dict[str, dict[str, Any]] = {} + for art in raw: + if not isinstance(art, dict): + continue + name = str(art.get("name") or "") + match = ARTIFACT_RE.match(name) + if not match: + continue + if art.get("expired"): + # The metadata outlives the blob; an expired artifact is not data. + continue + art_id = _as_int(art.get("id")) + if art_id is None: + continue + run = art.get("workflow_run") + run = run if isinstance(run, dict) else {} + row = { + "id": art_id, + "name": name, + "python": match.group(1), + "run_id": _as_int(run.get("id")), + "head_branch": str(run.get("head_branch") or ""), + "head_sha": str(run.get("head_sha") or ""), + "created_at": str(art.get("created_at") or ""), + } + current = best.get(name) + if current is None or row["created_at"] > current["created_at"]: + best[name] = row + return [best[name] for name in sorted(best)] + + +def parse_timings(text: str) -> tuple[dict[str, Any] | None, str]: + """One ``smoke_timings.json`` → (dataset, "") or (None, reason). + + The dataset's entries are normalised to exactly the six keys this check + stores, with every type coerced defensively: the file is written by another + organ on a runner we do not control, and a surprising value must degrade to + ``None`` rather than raise out of an unattended check. + """ + try: + data = json.loads(text) + except (TypeError, ValueError): + return None, f"{TIMINGS_FILENAME} was not valid JSON" + if not isinstance(data, dict): + return None, f"{TIMINGS_FILENAME} was not an object" + if str(data.get("schema") or "") != TIMINGS_SCHEMA: + return None, f"not a {TIMINGS_SCHEMA} dataset" + raw_entries = data.get("entries") + if not isinstance(raw_entries, list): + return None, "entries was not a list" + + entries: list[dict[str, Any]] = [] + for item in raw_entries: + if not isinstance(item, dict): + continue + entry = str(item.get("entry") or "") + if not entry: + continue + entries.append( + { + "entry": entry, + "kind": str(item.get("kind") or ""), + "status": str(item.get("status") or ""), + # NEVER 0.0 for a missing measurement: null means "never ran". + "seconds": _as_float(item.get("seconds")), + "cap_s": _as_float(item.get("cap_s")), + "exit_code": _as_int(item.get("exit_code")), + } + ) + return ( + { + "schema": TIMINGS_SCHEMA, + "project": str(data.get("project") or ""), + "directory": str(data.get("directory") or ""), + "run_type": str(data.get("run_type") or ""), + "env_profile": str(data.get("env_profile") or ""), + "python": str(data.get("python") or ""), + "ts": str(data.get("ts") or ""), + "entries": entries, + }, + "", + ) + + +def read_downloaded_leg(directory: Path | str) -> tuple[list[dict[str, Any]], str, dict[str, str]]: + """Every ``smoke_timings.json`` under one extracted artifact → (entries, error, meta). + + An artifact may hold more than one dataset (a report dir per project, the + glob in the upload step catches them all). They are merged on the entry + path, first file in sorted path order winning, exactly as the producer's own + ``merge_timings`` merges legs — the script and notebook legs contribute + disjoint paths, so both survive. + + A directory with no dataset and a directory whose datasets are all + unreadable get the SAME honest error: what we have is no usable dataset + either way, and the leg keeps its provenance so the board can say which run + it could not read. + """ + root = Path(directory) + entries: dict[str, dict[str, Any]] = {} + meta: dict[str, str] = {} + for path in sorted(root.rglob(TIMINGS_FILENAME)): + try: + text = path.read_text() + except OSError: + continue + data, err = parse_timings(text) + if data is None or err: + continue + if not meta: + meta = { + "env_profile": data.get("env_profile", ""), + "python": data.get("python", ""), + "ts": data.get("ts", ""), + } + for entry in data["entries"]: + entries.setdefault(entry["entry"], entry) + if not entries and not meta: + return [], NO_DATASET_ERROR, {} + return [entries[key] for key in sorted(entries)], "", meta + + +def leg_counts(entries: list[dict[str, Any]]) -> dict[str, Any]: + """Per-status counts + ``timed`` + ``total_s`` for one leg's entries. + + ``timed`` counts entries whose ``seconds`` is a number — the coverage + behind ``total_s``. A ``null`` duration is not a zero-second run, so it is + in neither. + """ + counts: dict[str, Any] = {k: 0 for k in TRACKED_STATUSES} + counts["timed"] = 0 + total = 0.0 + for entry in entries or []: + if not isinstance(entry, dict): + continue + status = str(entry.get("status") or "") + if status in counts and status != "timed": + counts[status] += 1 + seconds = entry.get("seconds") + if isinstance(seconds, (int, float)) and not isinstance(seconds, bool): + counts["timed"] += 1 + total += float(seconds) + counts["total_s"] = round(total, 1) + return counts + + +# --- prompts (written by the producer; never re-derived by a renderer) ------- +def timeout_prompt(repo: str, entry: str, cap_s: Any, run_url: str) -> str: + """The self-contained /bug prompt a TIMEOUT row copies.""" + cap = _as_float(cap_s) + cap_text = str(int(round(cap))) if cap is not None else "?" + return ( + f"/bug kill timer: {repo} {entry} TIMEOUT ({cap_text}s) on {run_url} " + f"— stack tail in the run log" + ) + + +def slow_prompt(repo: str, entry: str, prev_s: Any, now_s: Any, + prev_run_url: str, run_url: str) -> str: + """The self-contained /bug prompt a slowed script copies.""" + prev = _as_float(prev_s) or 0.0 + now = _as_float(now_s) or 0.0 + return ( + f"/bug slow script: {repo} {entry} {int(round(prev))}s → {int(round(now))}s " + f"between runs {prev_run_url} → {run_url}" + ) + + +# --- per-repo sidecar -------------------------------------------------------- +def build_sidecar( + name: str, + group: str, + owner: str, + legs: list[dict[str, Any]], + ts: str, + error: str = "", +) -> dict[str, Any]: + """Construct one repo's smoke_timings sidecar. + + ``legs`` is what the shell leg produced: one entry per selected artifact, + ``{"artifact": , "dir": , + "error": }``. + + ``error`` is the reason the artifacts listing could not be fetched. When + set the sidecar carries NO legs at all: a dead query must never render as a + repo with no slow scripts. A single leg that failed to download keeps its + provenance (run, python, url) with its own ``error`` and no entries — one + leg's 403 must not lose the other leg. + """ + if error: + return { + "name": name, "group": group, "owner": owner, "error": error, + "ts": ts, "legs": [], + } + + out_legs: list[dict[str, Any]] = [] + for leg in legs or []: + if not isinstance(leg, dict): + continue + art = leg.get("artifact") + art = art if isinstance(art, dict) else {} + run_id = art.get("run_id") + run_url = ( + f"https://github.com/{owner}/{name}/actions/runs/{run_id}" + if owner and name and run_id is not None + else "" + ) + leg_error = str(leg.get("error") or "") + entries: list[dict[str, Any]] = [] + meta: dict[str, str] = {} + if not leg_error: + directory = leg.get("dir") + if directory: + entries, leg_error, meta = read_downloaded_leg(directory) + else: + leg_error = "artifact was not downloaded" + counts = leg_counts(entries) + total_s = counts.pop("total_s") + out_legs.append( + { + "python": str(art.get("python") or meta.get("python") or ""), + "artifact_id": art.get("id"), + "run_id": run_id, + "run_url": run_url, + "head_branch": str(art.get("head_branch") or ""), + "head_sha": str(art.get("head_sha") or ""), + "at": str(art.get("created_at") or ""), + "env_profile": meta.get("env_profile", ""), + "error": leg_error, + "entries": entries, + "counts": counts, + "total_s": total_s, + } + ) + out_legs.sort(key=lambda leg: (str(leg.get("python") or ""), str(leg.get("artifact_id") or ""))) + return { + "name": name, "group": group, "owner": owner, "error": "", + "ts": ts, "legs": out_legs, + } + + +# --- aggregate --------------------------------------------------------------- +def prev_rows_of(prev_board: Any) -> dict[tuple[str, str, str], dict[str, Any]]: + """``performance.scripts.rows`` out of a previously published board.json. + + Keyed by (repo, python, entry) — the identity of a script row across runs. + Anything unexpected (a 404 page, an older board with no scripts block, a + rows list of nulls) degrades to no previous observation: a publish gap + costs a comparison, never a render. + """ + out: dict[tuple[str, str, str], dict[str, Any]] = {} + if not isinstance(prev_board, dict): + return out + perf = prev_board.get("performance") + if not isinstance(perf, dict): + return out + scripts = perf.get("scripts") + if not isinstance(scripts, dict): + return out + rows = scripts.get("rows") + if not isinstance(rows, list): + return out + for row in rows: + if not isinstance(row, dict): + continue + key = ( + str(row.get("repo") or ""), + str(row.get("python") or ""), + str(row.get("entry") or ""), + ) + if all(key): + out[key] = row + return out + + +def classify_drift( + seconds: Any, + prev_row: Any, + thresholds: dict[str, float], + run_id: Any = None, +) -> tuple[str, float | None, float | None]: + """(state, ratio, delta_s) — ``warn`` needs BOTH gates, else ``ok``. + + ``("ok", None, None)`` when either side is missing, or when the previous + observation came from the SAME run: the previous board is re-read on every + render, so a second render of the same day sees the same run's rows, and + comparing a run against itself would report a reassuring 1.0× that means + nothing. Never ``fail`` — a slowed script is advisory by construction. + """ + now = _as_float(seconds) + if not isinstance(prev_row, dict): + return "ok", None, None + prev = _as_float(prev_row.get("seconds")) + if now is None or prev is None or now <= 0 or prev <= 0: + return "ok", None, None + prev_run = prev_row.get("run_id") + if run_id is not None and prev_run is not None and prev_run == run_id: + return "ok", None, None + ratio = round(now / prev, 2) + delta = round(now - prev, 1) + if (ratio >= float(thresholds.get("slow_factor", 2.0)) + and delta >= float(thresholds.get("min_delta_s", 5))): + return "warn", ratio, delta + return "ok", ratio, delta + + +def aggregate( + sidecars: list[dict[str, Any]], + prev_board: Any, + ts: str, + thresholds: dict[str, float] | None = None, +) -> dict[str, Any]: + """Fold the per-repo sidecars + the previous board into the global rollup.""" + thr = dict(thresholds or DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + prev_rows = prev_rows_of(prev_board) + top_n = int(thr.get("top_n", 5) or 5) + + repos: list[dict[str, Any]] = [] + rows: list[dict[str, Any]] = [] + events: list[dict[str, Any]] = [] + errors: list[dict[str, str]] = [] + + def _name_of(side: Any) -> str: + return str(side.get("name") or "") if isinstance(side, dict) else "" + + for side in sorted(sidecars or [], key=_name_of): + if not isinstance(side, dict): + continue + repo = str(side.get("name") or "") + if side.get("error"): + errors.append({"repo": repo, "error": str(side["error"])}) + continue + legs = side.get("legs") + if not isinstance(legs, list): + continue + for leg in legs: + if not isinstance(leg, dict): + continue + python = str(leg.get("python") or "") + run_id = leg.get("run_id") + run_url = str(leg.get("run_url") or "") + at = str(leg.get("at") or "") + leg_error = str(leg.get("error") or "") + if leg_error: + # Provenance survives: which run we could not read, and why. + errors.append({"repo": repo, "error": f"{python or '?'}: {leg_error}"}) + entries = [e for e in (leg.get("entries") or []) if isinstance(e, dict)] + + leg_rows: list[dict[str, Any]] = [] + for entry in entries: + name = str(entry.get("entry") or "") + status = str(entry.get("status") or "") + seconds = _as_float(entry.get("seconds")) + cap_s = _as_float(entry.get("cap_s")) + if status == "timeout": + # Timed or not: a killed script is a hard row either way. + events.append({ + "kind": "timeout", + "repo": repo, + "python": python, + "entry": name, + "cap_s": cap_s, + "run_url": run_url, + "at": at, + "prompt": timeout_prompt(repo, name, cap_s, run_url), + }) + if seconds is None: + # `null` means the entry never ran. Not a zero-second row. + continue + prev_row = prev_rows.get((repo, python, name)) + state, ratio, delta = classify_drift(seconds, prev_row, thr, run_id=run_id) + prev_s = _as_float((prev_row or {}).get("seconds")) + prev_run_id = (prev_row or {}).get("run_id") + prev_run_url = str((prev_row or {}).get("run_url") or "") + leg_rows.append({ + "repo": repo, + "python": python, + "entry": name, + "kind": str(entry.get("kind") or ""), + "status": status, + "seconds": seconds, + "cap_s": cap_s, + "exit_code": _as_int(entry.get("exit_code")), + "run_id": run_id, + "run_url": run_url, + "prev_s": prev_s, + "prev_run_id": prev_run_id, + "ratio": ratio, + "delta_s": delta, + "state": state, + "prompt": (slow_prompt(repo, name, prev_s, seconds, + prev_run_url, run_url) + if state == "warn" else None), + }) + + counts = leg.get("counts") if isinstance(leg.get("counts"), dict) else {} + timed = _as_int(counts.get("timed")) + repos.append({ + "repo": repo, + "python": python, + "run_id": run_id, + "run_url": run_url, + "head_branch": str(leg.get("head_branch") or ""), + "at": at, + "entries": len(entries), + "timed": timed if timed is not None else len(leg_rows), + "total_s": _as_float(leg.get("total_s")) or 0.0, + "error": leg_error, + "slowest": sorted(leg_rows, key=lambda r: r["seconds"], reverse=True)[:top_n], + }) + rows.extend(leg_rows) + + repos.sort(key=lambda r: (str(r.get("repo") or ""), str(r.get("python") or ""))) + rows.sort(key=lambda r: (str(r.get("repo") or ""), str(r.get("python") or ""), + str(r.get("entry") or ""))) + return { + "ts": ts, + "repos": repos, + "rows": rows, + "slowed": [r for r in rows if r.get("state") == "warn"], + "events": events, + "errors": errors, + "thresholds": thr, + } + + +def read_sidecars(per_repo_dir: Path) -> list[dict[str, Any]]: + """Every ``*.smoke_timings.json`` sidecar under ``per_repo_dir`` (I/O).""" + out: list[dict[str, Any]] = [] + for path in sorted(Path(per_repo_dir).glob("*.smoke_timings.json")): + try: + data = json.loads(path.read_text()) + except (OSError, ValueError): + continue + if isinstance(data, dict): + out.append(data) + return out + + +def read_downloads( + artifacts: list[dict[str, Any]], downloads_dir: Path | str | None +) -> list[dict[str, Any]]: + """Pair each selected artifact with its extracted dir (or its error). + + The shell leg writes ``//`` for a download that worked and + ``/.error`` (one line of text) for one that did not, so a + 403 on one python leg still leaves the other leg's data intact. + """ + legs: list[dict[str, Any]] = [] + root = Path(downloads_dir) if downloads_dir else None + for art in artifacts: + directory = None + error = "" + if root is None: + error = "no downloads directory" + else: + err_file = root / f"{art['id']}.error" + art_dir = root / str(art["id"]) + if err_file.is_file(): + try: + error = " ".join(err_file.read_text().split())[:200] + except OSError: # pragma: no cover - unreadable marker file + error = "" + error = error or "artifact download failed" + elif art_dir.is_dir(): + directory = art_dir + else: + error = "artifact download failed" + legs.append({"artifact": art, "dir": directory, "error": error}) + return legs + + +# --- summary lines ----------------------------------------------------------- +def repo_summary_line(sidecar: dict[str, Any]) -> str: + """Coloured one-line per-repo summary for the daemon log.""" + from heart.heart_color import ( + c_info, c_meta, c_ok, c_warn, glyph_ok, glyph_warn, + ) + + name = sidecar.get("name", "?") + if sidecar.get("error"): + return (f"{glyph_warn()} {c_info(name)} {c_warn('smoke_timings UNAVAILABLE')} " + f"{c_meta(str(sidecar['error']))}") + legs = [leg for leg in (sidecar.get("legs") or []) if isinstance(leg, dict)] + timed = sum(_as_int((leg.get("counts") or {}).get("timed")) or 0 for leg in legs) + broken = [leg for leg in legs if leg.get("error")] + if broken: + return (f"{glyph_warn()} {c_info(name)} " + f"{c_warn(f'{len(broken)} leg(s) unavailable')} " + f"{c_meta(f'{timed} script(s) timed')}") + return (f"{glyph_ok()} {c_info(name)} {c_ok(f'{timed} script(s) timed')} " + f"{c_meta(f'{len(legs)} leg(s)')}") + + +def summary_line(rollup: dict[str, Any]) -> str: + """Coloured one-line summary of the global rollup.""" + from heart.heart_color import ( + c_info, c_meta, c_ok, c_warn, glyph_ok, glyph_warn, + ) + + rows = rollup.get("rows") or [] + repos = {str(r.get("repo") or "") for r in (rollup.get("repos") or []) + if isinstance(r, dict)} + slowed = len(rollup.get("slowed") or []) + events = len(rollup.get("events") or []) + errors = len(rollup.get("errors") or []) + body = (f"{len(rows)} scripts timed across {len(repos)} repos, " + f"{slowed} slowed, {events} timeouts") + if errors: + body += f", {errors} unavailable" + legs = len(rollup.get("repos") or []) + glyph = glyph_warn() if (slowed or events or errors) else glyph_ok() + tint = c_warn if (slowed or events or errors) else c_ok + return (f"{glyph} {c_info('smoke_timings:')} {tint(body)} " + f"{c_meta(f'({legs} leg(s))')}") + + +# --- I/O shell --------------------------------------------------------------- +def _write(out_path: Path, payload: dict[str, Any]) -> None: + sys.path.insert(0, str(HEART_HOME)) + from heart import state + + state.atomic_write_json(out_path, payload) + + +def _read_listing(path: str) -> tuple[Any, str]: + """The artifacts listing file → (payload, error).""" + try: + return json.loads(Path(path).read_text()), "" + except (OSError, ValueError): + return None, "artifacts listing was not valid JSON" + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="heart.checks.smoke_timings") + ap.add_argument("--plan", action="store_true", + help="read an artifacts listing on stdin and print the " + "' ' lines the shell leg should download") + ap.add_argument("--aggregate", action="store_true", + help="fold the per-repo sidecars into the global rollup") + ap.add_argument("--name", default="") + ap.add_argument("--group", default="") + ap.add_argument("--owner", default="") + ap.add_argument("--ts", default="") + ap.add_argument("--out", default="") + ap.add_argument("--listing", default="", + help="file holding the artifacts listing JSON (per-repo mode)") + ap.add_argument("--downloads", default="", + help="dir holding / extractions and " + ".error markers (per-repo mode)") + ap.add_argument("--prev-board", default="", + help="previously published board.json (aggregate mode); " + "missing/unreadable => no comparison, never an error") + ap.add_argument("--per-repo-dir", default="", + help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)") + ap.add_argument("--fetch-error", default="", + help="reason the artifacts listing fetch failed; recorded " + "instead of a bogus quiet repo") + ns = ap.parse_args(argv) + + if ns.plan: + try: + listing: Any = json.load(sys.stdin) + except (json.JSONDecodeError, ValueError): + # Nothing to download, and nothing to say: the per-repo call reads + # the same listing file and records the failure honestly there. + return 0 + for art in select_artifacts(listing): + print(f"{art['id']} {art['name']}") + return 0 + + if not ns.out: + ap.error("--out is required outside --plan mode") + ts = ns.ts or datetime.datetime.now(datetime.timezone.utc).isoformat() + + if ns.aggregate: + sys.path.insert(0, str(HEART_HOME)) + from heart import state as _state + + per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR + rollup = aggregate( + read_sidecars(per_repo), read_prev_board(ns.prev_board), ts, + load_thresholds(), + ) + _write(Path(ns.out), rollup) + print(summary_line(rollup)) + return 0 + + if not ns.name or not ns.group: + ap.error("--name and --group are required outside --aggregate mode") + + error = ns.fetch_error + legs: list[dict[str, Any]] = [] + if not error: + listing, listing_error = _read_listing(ns.listing) + error = listing_error + if not error: + legs = read_downloads(select_artifacts(listing), ns.downloads or None) + + sidecar = build_sidecar(ns.name, ns.group, ns.owner, legs, ts, error=error) + _write(Path(ns.out), sidecar) + print(repo_summary_line(sidecar)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/checks/smoke_timings.sh b/heart/checks/smoke_timings.sh new file mode 100755 index 00000000..7eb8df3d --- /dev/null +++ b/heart/checks/smoke_timings.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +# heart/checks/smoke_timings.sh — per-script CI timings (the fine-grained speed leg). +# +# For each polled repo whose required gate is the smoke suite, this lists the +# repo's artifacts via `gh api`, asks `heart.checks.smoke_timings --plan` which +# of them are the PR gate's `smoke-timings-` legs, downloads and unzips +# those, and hands the extracted directories to the per-repo Python call, which +# parses the `smoke_timings/1` datasets inside and writes +# $HEART_PER_REPO_DIR/.smoke_timings.json. A second, aggregate pass folds +# every sidecar plus the PREVIOUSLY PUBLISHED board.json into the global rollup +# at $HEART_STATE_DIR/smoke_timings.json (per-repo/per-leg totals, every timed +# row, run-to-run slowdowns, TIMEOUT events). +# +# Only the groups whose required gate is "Smoke Tests" are polled: a library has +# no smoke-timings artifact, and asking for one would manufacture a repo full of +# false "unavailable" rows. +# +# The previous observation is *self-carrying*, exactly as in ci_timing.sh: the +# aggregate step re-reads the board.json this repo published yesterday and +# compares each script against its own last row, keyed by run id so a re-render +# of the same run never compares it against itself. HEART_PREV_BOARD_URL +# overrides the URL (tests, staging boards); any fetch failure degrades to "no +# comparison", never to an error. +# +# Observer boundary: everything written lives under $HEART_STATE_DIR (plus +# mktemp scratch, cleaned up per repo). A repo whose listing fetch fails records +# the reason and NO legs — "we could not ask" must never render as "all quiet". + +set -u +source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh" + +# The groups whose required workflow is the smoke gate — the only repos that +# publish a `smoke-timings-` artifact at all. +_SMOKE_GROUPS="workspaces workspaces_test howto" + +# `per_page=100` is one page of artifacts, newest first: comfortably more than +# the handful of live `smoke-timings-*` legs, and the selector takes the newest +# non-expired one per name anyway. +_SMOKE_ARTIFACTS_PATH="actions/artifacts?per_page=100" + +ingest_one_repo() { + local owner_name="$1" + local group="$2" + local name="${owner_name##*/}" + local owner="${owner_name%%/*}" + + local listing downloads err ts rc + err="$(mktemp)" + listing="$(mktemp)" + gh api "repos/$owner_name/$_SMOKE_ARTIFACTS_PATH" >"$listing" 2>"$err" + rc=$? + ts="$(date -Iseconds)" + + if [[ $rc -ne 0 || ! -s "$listing" ]]; then + # Collapse gh's stderr to one line so it fits the sidecar and the log. + local fetch_error + fetch_error="$(tr '\n' ' ' <"$err" | cut -c1-200)" + [[ -z "${fetch_error// }" ]] && fetch_error="gh api exited $rc" + rm -f "$err" "$listing" + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings \ + --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ + --fetch-error "$fetch_error" \ + --out "$HEART_PER_REPO_DIR/$name.smoke_timings.json" + return 0 + fi + rm -f "$err" + + # The selection rule (newest non-expired artifact per python leg; the weekly + # sweep's names deliberately excluded) lives in Python, never re-derived here. + local plan + plan="$(PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings --plan <"$listing")" + + downloads="$(mktemp -d)" + local id artifact_name + while read -r id artifact_name; do + [[ -z "$id" ]] && continue + err="$(mktemp)" + # KNOWN RISK: the repo-scoped GITHUB_TOKEN may be refused (403) by the /zip + # endpoint for ANOTHER repo's artifacts. The remedy is a secret, not a code + # change — HEART_TIMINGS_TOKEN, a fine-grained PAT with Actions: read on the + # workspace repos (see .github/workflows/heart-health.yml). Either way one + # leg's failure is recorded as that leg's error and must not lose the repo's + # other leg, hence the `.error` marker and the `continue`. + if gh api "repos/$owner_name/actions/artifacts/$id/zip" >"$downloads/$id.zip" 2>"$err" \ + && unzip -o -q "$downloads/$id.zip" -d "$downloads/$id" 2>>"$err"; then + : + else + local reason + reason="$(tr '\n' ' ' <"$err" | cut -c1-200)" + [[ -z "${reason// }" ]] && reason="download of $artifact_name failed" + printf '%s\n' "$reason" >"$downloads/$id.error" + fi + rm -f "$err" "$downloads/$id.zip" + done <<<"$plan" + + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings \ + --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ + --listing "$listing" --downloads "$downloads" \ + --out "$HEART_PER_REPO_DIR/$name.smoke_timings.json" + + rm -rf "$downloads" + rm -f "$listing" +} + +# Print the path of a tempfile holding the previously published board.json, or +# nothing at all when it cannot be had. Never fails the check. +# +# A near-copy of ci_timing.sh's `_ci_timing_prev_board`: sourcing that file to +# reuse it would run its own top-level setup as a side effect, so the twenty +# lines are duplicated deliberately rather than the two checks being coupled. +_smoke_timings_prev_board() { + local url tmp + url="${HEART_PREV_BOARD_URL:-}" + if [[ -z "$url" ]]; then + url="$(PYTHONPATH="$HEART_HOME" python3 -c \ + "from heart.dashboard import PAGES_URL; print(PAGES_URL.rstrip('/') + '/board.json')" \ + 2>/dev/null || true)" + fi + [[ -z "$url" ]] && return 0 + tmp="$(mktemp)" + if curl -fsS --max-time 15 "$url" -o "$tmp" 2>/dev/null; then + printf '%s' "$tmp" + else + rm -f "$tmp" + fi +} + +check_smoke_timings_all() { + heart_state_dir + heart_log INFO "$(c_info "smoke_timings: ingesting per-script smoke-timings artifacts across the smoke-gated repos")" + while read -r line; do + [[ -z "$line" ]] && continue + local owner_name group + owner_name="${line%% *}" + group="${line##* }" + case " $_SMOKE_GROUPS " in + *" $group "*) ingest_one_repo "$owner_name" "$group" & ;; + *) continue ;; + esac + done < <(load_repos_yaml) + wait + + local prev + prev="$(_smoke_timings_prev_board)" + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings \ + --aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \ + --out "$HEART_STATE_DIR/smoke_timings.json" + [[ -n "$prev" ]] && rm -f "$prev" + + heart_log OK "$(c_ok "smoke_timings: done")" +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + check_smoke_timings_all +fi diff --git a/heart/dashboard.py b/heart/dashboard.py index 7bc8f71d..dc09f0f0 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -267,11 +267,11 @@ class Board: # 📋 buttons, the md links, and the json consumers act on. blockers: list[dict] = field(default_factory=list) # The ⏱ performance surface: CI wall-clock gates + their history, hang/kill - # events, and the NO_RUN census — the block the Brain board consumes - # verbatim. Every actionable row inside carries its own ready-to-paste - # prompt; the consumer never re-derives one. None when neither timing slice - # was observed (an absent block is honest; an empty one implies "measured, - # nothing there"). + # events, the per-SCRIPT smoke timings, and the NO_RUN census — the block + # the Brain board consumes verbatim. Every actionable row inside carries its + # own ready-to-paste prompt; the consumer never re-derives one. None when no + # timing slice was observed (an absent block is honest; an empty one implies + # "measured, nothing there"). performance: dict | None = None # {count, command, prompt}: one copyable plan that closes EVERY current # evidence gap, so a STALE board is one tap from being cleared instead of @@ -766,8 +766,8 @@ def build_board( details.append(f"{stale_n} stale parked script(s)") sections.append(Section("test_run", "Test run", st, summary, details)) - # CI wall-clock + the NO_RUN census (the ⏱ performance surface) ----------- - # Both are CLOUD-observed (the Actions API + the contents API), so they are + # CI wall-clock, per-script smoke timings + the NO_RUN census (⏱) --------- + # All three are CLOUD-observed (the Actions API + the contents API), so they are # deliberately NOT in LOCAL_ONLY_FAMILIES: the scheduled job measures them # first-hand and must not mark them "not observed here". Timing rows are # advisory — they never move the readiness verdict. @@ -946,6 +946,60 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict], links=links, action=action) +def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict], + slowed: list[dict], events: list[dict], + errors: list) -> Section: + """The per-script row: which script inside the gate is spending the time.""" + # A TIMEOUT is a killed script — the only hard row here. A slowed script, + # like a slowed gate, is advisory by construction: this measurement rides on + # whatever PRs happened to run, so an alarm on jitter would cry wolf. + if events: + state = FAIL + elif slowed or errors: + state = WARN + else: + state = OK + + repo_names = {str(r.get("repo") or "") for r in repos if r.get("repo")} + bits = [f"{len(rows)} scripts timed across {len(repo_names)} repos"] + slowest = max(rows, key=lambda r: r.get("seconds") or 0, default=None) + if slowest: + bits.append(f"slowest {slowest.get('repo')} {slowest.get('entry')} " + f"{_dur(slowest.get('seconds'))}") + if slowed: + bits.append(f"{len(slowed)} slowed") + if events: + bits.append(f"{len(events)} timeout" + ("" if len(events) == 1 else "s")) + if errors: + bits.append(f"{len(errors)} unavailable") + + details = [] + for r in sorted(repos, key=lambda r: r.get("total_s") or 0, reverse=True)[:6]: + top = [s for s in (r.get("slowest") or []) if isinstance(s, dict)][:3] + head = " · ".join(f"{s.get('entry')} {_dur(s.get('seconds'))}" for s in top) + # Coverage beside time, always: a leg that got faster by running less + # must not read as a leg that got faster. + tail = f"({_as_int(r.get('timed'))} scripts, {_dur(r.get('total_s'))} total)" + prefix = f"{r.get('repo')} py{r.get('python') or '?'}:" + details.append(f"{prefix} {head} {tail}" if head else f"{prefix} {tail}") + + links = [ + {"label": f"{e.get('repo')} {e.get('entry')} TIMEOUT", + "url": str(e.get("run_url")), "prompt": str(e.get("prompt") or "")} + for e in events if e.get("run_url") + ][:4] + + # Same rule as the gate row: a single slowed script's prompt rides the row's + # 📋; more than one and the board would have to pick a favourite, so they + # all stay in the `performance` block where each carries its own prompt. + action = None + if len(slowed) == 1 and slowed[0].get("prompt"): + action = {"label": "copy the slowdown prompt", "payload": str(slowed[0]["prompt"])} + + return Section("smoke_timings", "Smoke scripts", state, " · ".join(bits), details, + links=links, action=action) + + def _no_run_section(totals: dict, rows: list[dict], repo_rows: list[dict]) -> Section: """The NO_RUN census row: what the release run is not running, and why.""" slow = _as_int(totals.get("slow")) @@ -979,18 +1033,25 @@ def _no_run_section(totals: dict, rows: list[dict], repo_rows: list[dict]) -> Se def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | None: - """Append the two ⏱ rows (when observed) and return the `performance` block. + """Append the ⏱ rows (when observed) and return the `performance` block. The block is the contract the Brain board consumes verbatim: every - actionable row inside it — a slowed gate, a hang event, a marker row — - carries its own ready-to-paste prompt string, written by the producer and - never re-derived by a renderer. + actionable row inside it — a slowed gate, a slowed script, a hang event, a + TIMEOUT, a marker row — carries its own ready-to-paste prompt string, + written by the producer and never re-derived by a renderer. + + `scripts` is emitted ONLY when the smoke_timings slice was observed, so a + snapshot taken before this check existed still renders a byte-identical + block — and so the next render can tell "no per-script timing observed" + from "observed, nothing there" when it reads its own previous rows back. """ ct = snapshot.get("ci_timing") ct = ct if isinstance(ct, dict) else {} nr = snapshot.get("no_run_census") nr = nr if isinstance(nr, dict) else {} - if not ct and not nr: + st = snapshot.get("smoke_timings") + st = st if isinstance(st, dict) else {} + if not ct and not nr and not st: return None gates = [g for g in (ct.get("gates") or []) if isinstance(g, dict)] @@ -1001,12 +1062,21 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non rows = [r for r in (nr.get("rows") or []) if isinstance(r, dict)] repo_rows = [r for r in (nr.get("repos") or []) if isinstance(r, dict)] + st_repos = [r for r in (st.get("repos") or []) if isinstance(r, dict)] + st_rows = [r for r in (st.get("rows") or []) if isinstance(r, dict)] + st_slowed = [r for r in (st.get("slowed") or []) if isinstance(r, dict)] + st_events = [e for e in (st.get("events") or []) if isinstance(e, dict)] + st_errors = list(st.get("errors") or []) + if ct: sections.append(_ci_timing_section(ct, gates, events, errors, history)) + if st: + sections.append(_smoke_timings_section(st, st_repos, st_rows, st_slowed, + st_events, st_errors)) if nr: sections.append(_no_run_section(totals, rows, repo_rows)) - return { + block = { "schema": 1, "gates": [ { @@ -1032,6 +1102,19 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non "rows": rows[:10], }, } + if st: + # The rows the NEXT render reads back as its previous observation — + # carried whole, run id and all, so a re-render never compares a run + # against itself. + block["scripts"] = { + "schema": 1, + "repos": st_repos, + "rows": st_rows, + "slowed": st_slowed, + "events": st_events, + "errors": st_errors, + } + return block def _unobs_section(key: str, title: str) -> Section: diff --git a/heart/state.py b/heart/state.py index eeaa9759..6fe675ca 100644 --- a/heart/state.py +++ b/heart/state.py @@ -79,6 +79,7 @@ def aggregate() -> dict[str, Any]: "profiling_drift": _read_json_or_default(HEART_STATE_DIR / "profiling_drift.json", {}), "test_run": _read_json_or_default(HEART_STATE_DIR / "test_run.json", {}), "ci_timing": _read_json_or_default(HEART_STATE_DIR / "ci_timing.json", {}), + "smoke_timings": _read_json_or_default(HEART_STATE_DIR / "smoke_timings.json", {}), "no_run_census": _read_json_or_default(HEART_STATE_DIR / "no_run_census.json", {}), "workspace_testmode_timing": _read_json_or_default(HEART_STATE_DIR / "workspace_testmode_timing.json", {}), "version_skew": _read_json_or_default(HEART_STATE_DIR / "version_skew.json", {}), diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index aadbf8b5..3b513b08 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -836,6 +836,183 @@ def test_malformed_performance_slices_never_break_the_board(): now=FRESH_NOW), str) +# --- the ⏱ per-script row: smoke_timings (PyAutoHeart#202) ------------------ +# Fake names again — RepoA, an OwnerX-shaped URL on an invalid host, and +# workspace-relative entry paths that name no real script. +SCRIPT_RUN_URL = "https://ci.invalid/OwnerX/RepoA/actions/runs/7" +SCRIPT_PREV_RUN_URL = "https://ci.invalid/OwnerX/RepoA/actions/runs/6" +TIMEOUT_PROMPT = ( + f"/bug kill timer: RepoA imaging/slow.py TIMEOUT (600s) on {SCRIPT_RUN_URL} " + f"— stack tail in the run log" +) +SLOW_SCRIPT_PROMPT = ( + "/bug slow script: RepoA imaging/x.py 10s → 30s between runs " + f"{SCRIPT_PREV_RUN_URL} → {SCRIPT_RUN_URL}" +) + + +def _script_row(entry="imaging/x.py", seconds=30.0, *, state="ok", prompt=None): + return { + "repo": "RepoA", "python": "3.12", "entry": entry, "kind": "script", + "status": "passed", "seconds": seconds, "cap_s": 600.0, "exit_code": 0, + "run_id": 7, "run_url": SCRIPT_RUN_URL, + "prev_s": 10.0 if state == "warn" else None, + "prev_run_id": 6 if state == "warn" else None, + "ratio": 3.0 if state == "warn" else None, + "delta_s": 20.0 if state == "warn" else None, + "state": state, "prompt": prompt, + } + + +def _smoke_timings_slice(*, events=True, warn=True, errors=()): + rows = [ + _script_row("imaging/x.py", 30.0, + state="warn" if warn else "ok", + prompt=SLOW_SCRIPT_PROMPT if warn else None), + _script_row("imaging/y.py", 5.0), + ] + return { + "ts": TS, + "repos": [{ + "repo": "RepoA", "python": "3.12", "run_id": 7, + "run_url": SCRIPT_RUN_URL, "head_branch": "feat/x", "at": TS, + "entries": 3, "timed": 2, "total_s": 35.0, "error": "", + "slowest": [rows[0], rows[1]], + }], + "rows": rows, + "slowed": [r for r in rows if r["state"] == "warn"], + "events": ([{"kind": "timeout", "repo": "RepoA", "python": "3.12", + "entry": "imaging/slow.py", "cap_s": 600.0, + "run_url": SCRIPT_RUN_URL, "at": TS, + "prompt": TIMEOUT_PROMPT}] if events else []), + "errors": list(errors), + "thresholds": {"slow_factor": 2.0, "min_delta_s": 5, "top_n": 5}, + } + + +def _scripts_snapshot(**kw): + return make_snapshot(ci_timing=_ci_timing_slice(), no_run_census=_no_run_slice(), + smoke_timings=_smoke_timings_slice(**kw)) + + +def test_smoke_timings_section_renders_in_every_fmt_between_its_siblings(): + snap = _scripts_snapshot() + v = make_verdict() + keys = [s.key for s in dashboard.build_board(snap, v, now=FRESH_NOW).sections] + assert keys.index("ci_timing") < keys.index("smoke_timings") < keys.index("no_run_census") + for fmt in ("term", "md", "html", "json"): + out = dashboard.render(snap, v, fmt=fmt, now=FRESH_NOW).lower() + assert "smoke scripts" in out + + +def test_smoke_timings_summary_and_details_carry_coverage_beside_time(): + sec = _section(dashboard.build_board(_scripts_snapshot(), make_verdict(), + now=FRESH_NOW), "smoke_timings") + assert sec.state == dashboard.FAIL # a TIMEOUT is a hard row + assert "2 scripts timed across 1 repos" in sec.summary + assert "slowest RepoA imaging/x.py 30s" in sec.summary + assert "1 slowed" in sec.summary and "1 timeout" in sec.summary + assert sec.details[0] == ("RepoA py3.12: imaging/x.py 30s · imaging/y.py 5s" + " (2 scripts, 35s total)") + + +def test_smoke_timings_timeout_is_a_link_with_its_own_prompt(): + sec = _section(dashboard.build_board(_scripts_snapshot(), make_verdict(), + now=FRESH_NOW), "smoke_timings") + (link,) = sec.links + assert link["label"] == "RepoA imaging/slow.py TIMEOUT" + assert link["url"] == SCRIPT_RUN_URL and link["prompt"] == TIMEOUT_PROMPT + out = dashboard.render(_scripts_snapshot(), make_verdict(), fmt="html", + now=FRESH_NOW) + assert f'data-cmd="{_html_escape(TIMEOUT_PROMPT)}"' in out + + +def test_smoke_timings_without_a_timeout_is_warn_when_a_script_slowed(): + sec = _section(dashboard.build_board(_scripts_snapshot(events=False), + make_verdict(), now=FRESH_NOW), + "smoke_timings") + assert sec.state == dashboard.WARN + # exactly one slowed row → its prompt rides the row's 📋 (the gate rule) + assert sec.action["payload"] == SLOW_SCRIPT_PROMPT + + +def test_smoke_timings_all_quiet_is_ok(): + sec = _section(dashboard.build_board(_scripts_snapshot(events=False, warn=False), + make_verdict(), now=FRESH_NOW), + "smoke_timings") + assert sec.state == dashboard.OK + assert sec.action is None and sec.links == [] + + +def test_smoke_timings_errors_are_warn_not_silence(): + """A leg we could not download must never read as a leg with nothing slow.""" + snap = _scripts_snapshot(events=False, warn=False, + errors=[{"repo": "RepoA", "error": "3.11: HTTP 403"}]) + sec = _section(dashboard.build_board(snap, make_verdict(), now=FRESH_NOW), + "smoke_timings") + assert sec.state == dashboard.WARN and "1 unavailable" in sec.summary + + +def test_board_json_carries_the_scripts_block_verbatim(): + d = json.loads(dashboard.render(_scripts_snapshot(), make_verdict(), fmt="json", + now=FRESH_NOW)) + scripts = d["performance"]["scripts"] + assert scripts["schema"] == 1 + # The rows are what the NEXT render reads back as its previous observation, + # so the run id has to survive the round trip untouched. + row = next(r for r in scripts["rows"] if r["state"] == "warn") + assert row["run_id"] == 7 and row["run_url"] == SCRIPT_RUN_URL + assert row["prompt"] == SLOW_SCRIPT_PROMPT # verbatim, not re-derived + assert scripts["slowed"] == [row] + assert scripts["events"][0]["prompt"] == TIMEOUT_PROMPT + assert scripts["repos"][0]["timed"] == 2 + assert d["schema_version"] == dashboard.SCHEMA_VERSION # purely additive + + +def test_an_absent_smoke_slice_leaves_the_older_block_byte_identical(): + """A snapshot taken before this check existed must render exactly as it did: + no row, and no `scripts` key implying "measured, nothing there".""" + old = dashboard.build_board(_perf_snapshot(), make_verdict(), now=FRESH_NOW) + new = dashboard.build_board(_scripts_snapshot(), make_verdict(), now=FRESH_NOW) + assert "smoke_timings" not in [s.key for s in old.sections] + assert "ci_timing" in [s.key for s in old.sections] + assert "no_run_census" in [s.key for s in old.sections] + assert "scripts" not in old.performance + assert json.dumps(old.performance, sort_keys=True) == json.dumps( + {k: v for k, v in new.performance.items() if k != "scripts"}, sort_keys=True) + + +def test_smoke_timings_alone_still_yields_a_performance_block(): + board = dashboard.build_board(make_snapshot(smoke_timings=_smoke_timings_slice()), + make_verdict(), now=FRESH_NOW) + keys = [s.key for s in board.sections] + assert "smoke_timings" in keys + assert "ci_timing" not in keys and "no_run_census" not in keys + assert board.performance["scripts"]["rows"] + assert board.performance["gates"] == [] and board.performance["no_run"]["rows"] == [] + + +def test_malformed_smoke_timings_slices_never_break_the_board(): + for snap in (make_snapshot(smoke_timings="nope"), + make_snapshot(smoke_timings=[]), + make_snapshot(smoke_timings={"rows": None, "repos": [None, "x"], + "events": "nope", "errors": None}), + make_snapshot(smoke_timings={"rows": [None, "x"], + "repos": [{"slowest": [None, "x"]}]})): + for fmt in ("term", "md", "html", "json"): + assert isinstance(dashboard.render(snap, make_verdict(), fmt=fmt, + now=FRESH_NOW), str) + + +def test_smoke_timings_is_cloud_observed_not_local_only(): + """The artifacts come from the Actions API, so the scheduled job measures + them first-hand — marking the row "not observed here" would be a lie.""" + assert "smoke_timings" not in dashboard.LOCAL_ONLY_FAMILIES + board = dashboard.build_board(_scripts_snapshot(), make_verdict(), + unobserved=dashboard.LOCAL_ONLY_FAMILIES, + now=FRESH_NOW) + assert _section(board, "smoke_timings").state == dashboard.FAIL + def test_html_wears_the_shared_family_theme(): # The look is the Brain's `board/_theme.py`, not a stylesheet copied in # here: the page must carry this board's hero (mark, wordmark, tagline) diff --git a/tests/test_heart_health_wiring.py b/tests/test_heart_health_wiring.py new file mode 100644 index 00000000..98790016 --- /dev/null +++ b/tests/test_heart_health_wiring.py @@ -0,0 +1,65 @@ +"""tests/test_heart_health_wiring.py — the daily cloud job stays wired. + +The checks in `heart/checks/*.sh` are only observations if something runs them. +These tests parse heart-health.yml so a check silently dropped from the cloud +step — or a permission/token the artifact ingest needs going missing — fails +loudly here rather than as a board row that quietly stops updating. + +PyYAML parses the bare `on:` key as boolean True, hence the `data[True]` reads +in the sibling wiring test; nothing here needs the triggers. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +WORKFLOWS = Path(__file__).resolve().parent.parent / ".github" / "workflows" +CHECKS = Path(__file__).resolve().parent.parent / "heart" / "checks" + + +def _job(): + data = yaml.safe_load((WORKFLOWS / "heart-health.yml").read_text()) + return data, data["jobs"]["heart-health"] + + +def _cloud_step(job): + for step in job["steps"]: + if "Run cloud-safe checks" in step.get("name", ""): + return step + raise AssertionError("no cloud-safe checks step in heart-health.yml") + + +def test_the_cloud_step_runs_every_api_only_check(): + _, job = _job() + body = _cloud_step(job)["run"] + for script in ("ci_status.sh", "open_prs.sh", "ci_timing.sh", + "no_run_census.sh", "smoke_timings.sh"): + assert f"bash heart/checks/{script}" in body + assert (CHECKS / script).is_file() + + +def test_the_job_can_read_actions_artifacts(): + """The artifact list/download endpoints need `actions: read` — even for the + repo's own artifacts, and the default grant does not include it.""" + data, _ = _job() + assert data["permissions"]["actions"] == "read" + + +def test_the_cloud_step_prefers_the_timings_token_and_falls_back(): + """Cross-repo artifact downloads need a token with actions:read on THAT + repo; the remedy is a secret, not a code change. Absent it the step still + runs on the auto-provisioned token.""" + _, job = _job() + token = _cloud_step(job)["env"]["GH_TOKEN"] + assert "secrets.HEART_TIMINGS_TOKEN" in token + assert "secrets.GITHUB_TOKEN" in token + assert "||" in token + + +def test_the_snapshot_folds_in_the_smoke_timings_rollup(): + """A rollup nothing aggregates is a file, not a board row.""" + state_py = (Path(__file__).resolve().parent.parent / "heart" / "state.py").read_text() + assert '"smoke_timings": _read_json_or_default(' in state_py + assert '"smoke_timings.json"' in state_py diff --git a/tests/test_smoke_timings.py b/tests/test_smoke_timings.py new file mode 100644 index 00000000..f0dabd6c --- /dev/null +++ b/tests/test_smoke_timings.py @@ -0,0 +1,479 @@ +"""tests/test_smoke_timings.py — per-script CI timings: selection, parse, drift. + +Fake repo/owner/entry names throughout (the tenant firewall): instance facts +live in `config/repos.yaml`, which is the declared surface, never in test data. +""" + +from __future__ import annotations + +import json + +from heart.checks import smoke_timings as smt + +REPO = "RepoA" +OWNER = "OwnerX" +RUN_URL = f"https://github.com/{OWNER}/{REPO}/actions/runs/7" +PREV_RUN_URL = f"https://github.com/{OWNER}/{REPO}/actions/runs/6" + + +def _artifact(name="smoke-timings-3.12", *, id_=11, created="2026-09-01T10:00:00Z", + expired=False, run_id=7, branch="feat/x", sha="abc123"): + """One row of the REST /actions/artifacts payload.""" + return { + "id": id_, "name": name, "expired": expired, "created_at": created, + "archive_download_url": "https://ci.invalid/artifacts/%s/zip" % id_, + "workflow_run": {"id": run_id, "head_branch": branch, "head_sha": sha}, + } + + +def _selected(**kw): + """The SELECTED artifact dict (what the shell leg hands build_sidecar).""" + (picked,) = smt.select_artifacts([_artifact(**kw)]) + return picked + + +def _dataset(entries, *, schema="smoke_timings/1", python="3.12", profile="smoke"): + return json.dumps({ + "schema": schema, "project": "ProjA", "directory": "imaging", + "run_type": "scripts", "env_profile": profile, "python": python, + "ts": "2026-09-01T09:55:00Z", "entries": entries, + "legs": [{"project": "ProjA", "directory": "imaging"}], + }) + + +def _entry(entry="imaging/x.py", *, status="passed", seconds=12.0, cap=600.0, + exit_code=0, kind="script"): + return {"entry": entry, "kind": kind, "status": status, "seconds": seconds, + "cap_s": cap, "exit_code": exit_code} + + +def _extracted(tmp_path, entries, *, sub="art", filename="smoke_timings.json", **kw): + """An extracted-artifact directory holding one dataset file.""" + d = tmp_path / sub + d.mkdir(parents=True, exist_ok=True) + (d / filename).write_text(_dataset(entries, **kw)) + return d + + +def _cfg(tmp_path, factor=2.0, delta=5, top_n=5) -> str: + cfg = tmp_path / "repos.yaml" + cfg.write_text( + "thresholds:\n" + " smoke_timings:\n" + f" slow_factor: {factor}\n" + f" min_delta_s: {delta}\n" + f" top_n: {top_n}\n" + ) + return str(cfg) + + +# --- artifact selection: the PR gate's legs, newest, non-expired ------------- + +def test_selection_keeps_the_newest_artifact_per_python_leg(): + listing = {"artifacts": [ + _artifact(id_=1, created="2026-08-30T10:00:00Z", run_id=5), + _artifact(id_=2, created="2026-09-01T10:00:00Z", run_id=7), + _artifact("smoke-timings-3.11", id_=3, created="2026-09-01T10:00:00Z", run_id=7), + ]} + picked = smt.select_artifacts(listing) + assert [a["python"] for a in picked] == ["3.11", "3.12"] + by_py = {a["python"]: a for a in picked} + assert by_py["3.12"]["id"] == 2 and by_py["3.12"]["run_id"] == 7 + assert by_py["3.12"]["head_branch"] == "feat/x" + # The selector is pure: no URL host is composed here. + assert all("run_url" not in a for a in picked) + + +def test_selection_skips_expired_artifacts(): + listing = {"artifacts": [ + _artifact(id_=1, created="2026-09-02T10:00:00Z", expired=True), + _artifact(id_=2, created="2026-09-01T10:00:00Z"), + ]} + # The newest one's blob is gone; metadata is not data. + assert [a["id"] for a in smt.select_artifacts(listing)] == [2] + + +def test_selection_ignores_the_weekly_and_foreign_artifact_names(): + """The weekly sweep is a different channel with a different cadence.""" + listing = {"artifacts": [ + _artifact("smoke-timings-scripts-ProjA-imaging", id_=1), + _artifact("smoke-timings-notebooks-ProjA-imaging", id_=2), + _artifact("results-ProjA-imaging", id_=3), + _artifact("smoke-timings-3.12", id_=4), + ]} + assert [a["id"] for a in smt.select_artifacts(listing)] == [4] + + +def test_selection_accepts_a_bare_list_and_tolerates_garbage(): + assert [a["id"] for a in smt.select_artifacts([_artifact()])] == [11] + assert smt.select_artifacts(None) == [] + assert smt.select_artifacts("nope") == [] + assert smt.select_artifacts({"artifacts": "nope"}) == [] + assert smt.select_artifacts({"artifacts": [None, "x", {}]}) == [] + assert smt.select_artifacts({"artifacts": [_artifact(id_=None)]}) == [] + + +# --- parsing the smoke_timings/1 dataset ------------------------------------ + +def test_parse_rejects_a_foreign_schema_and_a_non_list_entries(): + data, err = smt.parse_timings(_dataset([_entry()], schema="smoke_timings/2")) + assert data is None and "smoke_timings/1" in err + data, err = smt.parse_timings(json.dumps({"schema": "smoke_timings/1", + "entries": {"a": 1}})) + assert data is None and err == "entries was not a list" + data, err = smt.parse_timings("not json at all") + assert data is None and "not valid JSON" in err + data, err = smt.parse_timings("[]") + assert data is None and err + + +def test_parse_normalises_entries_to_exactly_six_keys(): + data, err = smt.parse_timings(_dataset([ + dict(_entry(), extra="ignored", seconds="12.5", exit_code="1"), + ])) + assert err == "" + (row,) = data["entries"] + assert set(row) == {"entry", "kind", "status", "seconds", "cap_s", "exit_code"} + assert row["seconds"] == 12.5 and row["exit_code"] == 1 + + +def test_null_seconds_stay_null_and_are_never_counted_as_timed(): + """A skipped entry never ran: 0 s would be a fabricated measurement.""" + data, _ = smt.parse_timings(_dataset([ + _entry("imaging/skip.py", status="skipped", seconds=None, cap=None, + exit_code=None), + _entry("imaging/x.py", seconds=12.0), + ])) + by_entry = {e["entry"]: e for e in data["entries"]} + assert by_entry["imaging/skip.py"]["seconds"] is None + counts = smt.leg_counts(data["entries"]) + assert counts["timed"] == 1 and counts["skipped"] == 1 + assert counts["total_s"] == 12.0 + + +# --- reading one extracted artifact ----------------------------------------- + +def test_several_dataset_files_merge_on_the_entry_path(tmp_path): + root = tmp_path / "art" + (root / "a").mkdir(parents=True) + (root / "b").mkdir(parents=True) + (root / "a" / "smoke_timings.json").write_text( + _dataset([_entry("imaging/x.py", seconds=1.0)], profile="first")) + (root / "b" / "smoke_timings.json").write_text( + _dataset([_entry("imaging/x.py", seconds=99.0), + _entry("imaging/y.py", seconds=2.0)])) + entries, err, meta = smt.read_downloaded_leg(root) + assert err == "" + assert [e["entry"] for e in entries] == ["imaging/x.py", "imaging/y.py"] + # first file in sorted path order wins the shared path + assert entries[0]["seconds"] == 1.0 + assert meta["env_profile"] == "first" and meta["python"] == "3.12" + + +def test_an_artifact_with_no_usable_dataset_is_an_honest_error(tmp_path): + empty = tmp_path / "empty" + empty.mkdir() + assert smt.read_downloaded_leg(empty) == ([], smt.NO_DATASET_ERROR, {}) + bad = _extracted(tmp_path, [_entry()], sub="bad", schema="smoke_timings/0") + entries, err, meta = smt.read_downloaded_leg(bad) + assert entries == [] and err == smt.NO_DATASET_ERROR and meta == {} + + +def test_a_dataset_with_no_entries_is_measured_not_absent(tmp_path): + """"Observed, nothing there" must stay distinguishable from "absent".""" + entries, err, meta = smt.read_downloaded_leg(_extracted(tmp_path, [])) + assert entries == [] and err == "" and meta["python"] == "3.12" + + +# --- the per-repo sidecar ---------------------------------------------------- + +def test_sidecar_with_a_repo_level_error_carries_no_legs(): + side = smt.build_sidecar(REPO, "workspaces", OWNER, [], "T", + error="gh api exited 1") + assert side["error"] == "gh api exited 1" and side["legs"] == [] + + +def test_sidecar_leg_carries_provenance_counts_and_the_run_url(tmp_path): + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/x.py", seconds=12.0), + _entry("imaging/skip.py", status="skipped", seconds=None), + ]), "error": ""}] + (leg,) = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T")["legs"] + assert leg["python"] == "3.12" and leg["artifact_id"] == 11 + assert leg["run_id"] == 7 and leg["run_url"] == RUN_URL + assert leg["head_branch"] == "feat/x" and leg["head_sha"] == "abc123" + assert leg["at"] == "2026-09-01T10:00:00Z" and leg["env_profile"] == "smoke" + assert leg["counts"] == {"passed": 1, "failed": 0, "skipped": 1, + "timeout": 0, "timed": 1} + assert leg["total_s"] == 12.0 and "total_s" not in leg["counts"] + + +def test_a_failed_leg_keeps_its_provenance_and_loses_no_sibling(tmp_path): + """One leg's 403 must not cost the repo its other leg.""" + good = _selected(name="smoke-timings-3.11", id_=1, run_id=7) + bad = _selected(name="smoke-timings-3.12", id_=2, run_id=7) + legs = [ + {"artifact": good, "dir": _extracted(tmp_path, [_entry(seconds=3.0)]), + "error": ""}, + {"artifact": bad, "dir": None, "error": "HTTP 403: Resource not accessible"}, + ] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + by_py = {leg["python"]: leg for leg in side["legs"]} + assert by_py["3.11"]["entries"] and by_py["3.11"]["error"] == "" + assert by_py["3.12"]["entries"] == [] + assert "403" in by_py["3.12"]["error"] + assert by_py["3.12"]["run_url"] == RUN_URL # provenance survives + + +def test_read_downloads_pairs_artifacts_with_dirs_and_error_markers(tmp_path): + arts = smt.select_artifacts([_artifact(id_=1), _artifact("smoke-timings-3.11", id_=2)]) + (tmp_path / "1").mkdir() + (tmp_path / "2.error").write_text("HTTP 403: Resource not accessible\nby integration\n") + legs = {leg["artifact"]["id"]: leg for leg in smt.read_downloads(arts, tmp_path)} + assert legs[1]["dir"] == tmp_path / "1" and legs[1]["error"] == "" + assert legs[2]["dir"] is None and legs[2]["error"].startswith("HTTP 403") + + +# --- events, drift, and the prompts they carry ------------------------------ + +def test_a_timeout_becomes_an_event_with_its_own_prompt(tmp_path): + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/slow.py", status="timeout", seconds=None, cap=600.0, + exit_code=None), + ]), "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + roll = smt.aggregate([side], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + (event,) = roll["events"] + assert event["kind"] == "timeout" and event["entry"] == "imaging/slow.py" + assert event["run_url"] == RUN_URL and event["cap_s"] == 600.0 + assert event["prompt"] == ( + f"/bug kill timer: {REPO} imaging/slow.py TIMEOUT (600s) on {RUN_URL} " + f"— stack tail in the run log" + ) + # A killed entry has no duration, so it is an event and NOT a timed row. + assert roll["rows"] == [] + + +def test_a_timeout_without_a_cap_still_prompts(): + assert smt.timeout_prompt(REPO, "imaging/x.py", None, RUN_URL).startswith( + f"/bug kill timer: {REPO} imaging/x.py TIMEOUT (?s) on ") + + +def _prev_board(rows): + return {"performance": {"scripts": {"rows": rows}}} + + +def _prev_row(seconds=10.0, run_id=6, entry="imaging/x.py", python="3.12"): + return {"repo": REPO, "python": python, "entry": entry, "seconds": seconds, + "run_id": run_id, "run_url": PREV_RUN_URL} + + +def test_drift_needs_both_the_ratio_and_the_absolute_floor(): + thr = {"slow_factor": 2.0, "min_delta_s": 5} + # 3x but only +2s — jitter on a fast script, not a regression. + assert smt.classify_drift(3.0, _prev_row(1.0), thr, run_id=7)[0] == "ok" + # +40s but only 1.4x — big, but that is what a long script's noise looks like. + assert smt.classify_drift(140.0, _prev_row(100.0), thr, run_id=7)[0] == "ok" + state, ratio, delta = smt.classify_drift(30.0, _prev_row(10.0), thr, run_id=7) + assert (state, ratio, delta) == ("warn", 3.0, 20.0) + + +def test_drift_is_ok_when_either_side_is_missing(): + thr = {"slow_factor": 2.0, "min_delta_s": 5} + assert smt.classify_drift(None, _prev_row(), thr) == ("ok", None, None) + assert smt.classify_drift(30.0, None, thr) == ("ok", None, None) + assert smt.classify_drift(30.0, {"seconds": None}, thr) == ("ok", None, None) + + +def test_a_run_is_never_compared_against_itself(): + """The previous board is re-read on every render — a second render of the + same run must not report a reassuring 1.0x, or anything at all.""" + thr = {"slow_factor": 2.0, "min_delta_s": 5} + assert smt.classify_drift(30.0, _prev_row(10.0, run_id=7), thr, run_id=7) == ( + "ok", None, None) + + +def test_prev_rows_are_keyed_by_repo_python_and_entry(): + rows = smt.prev_rows_of(_prev_board([_prev_row(), _prev_row(python="3.11")])) + assert set(rows) == {(REPO, "3.12", "imaging/x.py"), (REPO, "3.11", "imaging/x.py")} + + +def test_malformed_prev_boards_mean_no_comparison(): + for board in (None, "nope", {}, {"performance": "nope"}, + {"performance": {"scripts": "nope"}}, + {"performance": {"scripts": {"rows": "nope"}}}, + {"performance": {"scripts": {"rows": [None, "x", {}]}}}): + assert smt.prev_rows_of(board) == {} + + +def test_aggregate_flags_a_slowed_row_with_its_prompt(tmp_path): + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/x.py", seconds=30.0)]), "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + roll = smt.aggregate([side], _prev_board([_prev_row(10.0)]), "T", + {"slow_factor": 2.0, "min_delta_s": 5, "top_n": 5}) + (row,) = roll["rows"] + assert row["state"] == "warn" and row["ratio"] == 3.0 and row["delta_s"] == 20.0 + assert row["prev_s"] == 10.0 and row["prev_run_id"] == 6 + assert row["run_id"] == 7 and row["run_url"] == RUN_URL + assert row["prompt"] == ( + f"/bug slow script: {REPO} imaging/x.py 10s → 30s between runs " + f"{PREV_RUN_URL} → {RUN_URL}" + ) + assert roll["slowed"] == [row] + assert roll["thresholds"]["slow_factor"] == 2.0 + + +def test_aggregate_repo_row_carries_coverage_and_the_slowest_entries(tmp_path): + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/a.py", seconds=1.0), + _entry("imaging/b.py", seconds=30.0), + _entry("imaging/c.py", seconds=10.0), + _entry("imaging/d.py", status="skipped", seconds=None), + ]), "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + roll = smt.aggregate([side], {}, "T", {"slow_factor": 2.0, "min_delta_s": 5, + "top_n": 2}) + (repo_row,) = roll["repos"] + assert repo_row["entries"] == 4 and repo_row["timed"] == 3 + assert repo_row["total_s"] == 41.0 and repo_row["python"] == "3.12" + assert [s["entry"] for s in repo_row["slowest"]] == ["imaging/b.py", "imaging/c.py"] + + +def test_aggregate_errors_carry_both_repo_and_leg_level_failures(tmp_path): + dead = smt.build_sidecar("RepoB", "workspaces", OWNER, [], "T", + error="gh api exited 1") + partial = smt.build_sidecar(REPO, "workspaces", OWNER, [ + {"artifact": _selected(), "dir": None, "error": "HTTP 403"}, + ], "T") + roll = smt.aggregate([dead, partial], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + assert {"repo": "RepoB", "error": "gh api exited 1"} in roll["errors"] + assert {"repo": REPO, "error": "3.12: HTTP 403"} in roll["errors"] + # ...and the dead repo contributes no rows that could read as "all quiet". + assert roll["rows"] == [] and roll["repos"][0]["error"] == "HTTP 403" + + +def test_aggregate_ordering_is_stable(tmp_path): + def side(repo, python, entries, art_id): + art = _selected(name=f"smoke-timings-{python}", id_=art_id) + return smt.build_sidecar(repo, "workspaces", OWNER, [ + {"artifact": art, "dir": _extracted(tmp_path, entries, + sub=f"{repo}-{python}"), + "error": ""}], "T") + + b = side("RepoB", "3.12", [_entry("imaging/z.py", seconds=1.0)], 1) + a = side(REPO, "3.12", [_entry("imaging/b.py", seconds=1.0), + _entry("imaging/a.py", seconds=2.0)], 2) + a11 = side(REPO, "3.11", [_entry("imaging/a.py", seconds=3.0)], 3) + roll = smt.aggregate([b, a, a11], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + assert [(r["repo"], r["python"]) for r in roll["repos"]] == [ + (REPO, "3.11"), (REPO, "3.12"), ("RepoB", "3.12")] + assert [(r["repo"], r["python"], r["entry"]) for r in roll["rows"]] == [ + (REPO, "3.11", "imaging/a.py"), + (REPO, "3.12", "imaging/a.py"), + (REPO, "3.12", "imaging/b.py"), + ("RepoB", "3.12", "imaging/z.py"), + ] + + +def test_aggregate_survives_garbage_sidecars(): + roll = smt.aggregate([None, "nope", {}, {"name": REPO, "legs": "nope"}, + {"name": REPO, "legs": [None, {"entries": "nope"}]}], + {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + assert roll["rows"] == [] and roll["events"] == [] + + +# --- thresholds -------------------------------------------------------------- + +def test_thresholds_load_from_config(tmp_path): + assert smt.load_thresholds(_cfg(tmp_path, 3.0, 9, 2)) == { + "slow_factor": 3.0, "min_delta_s": 9, "top_n": 2} + assert (smt.load_thresholds(tmp_path / "absent.yaml") + == smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + + +def test_real_config_declares_the_smoke_timings_thresholds(): + """The shipped policy file must carry the block the check reads.""" + thr = smt.load_thresholds() + assert thr["slow_factor"] >= 1.0 and thr["min_delta_s"] >= 1 + assert thr["top_n"] >= 1 + + +# --- main wiring ------------------------------------------------------------- + +def test_plan_prints_the_ids_to_download(monkeypatch, capsys): + listing = json.dumps({"artifacts": [ + _artifact(id_=1), _artifact("smoke-timings-3.11", id_=2), + _artifact("smoke-timings-scripts-ProjA-imaging", id_=3), + ]}) + monkeypatch.setattr("sys.stdin", __import__("io").StringIO(listing)) + assert smt.main(["--plan"]) == 0 + assert capsys.readouterr().out.split("\n")[:2] == [ + "2 smoke-timings-3.11", "1 smoke-timings-3.12"] + + +def test_plan_says_nothing_on_garbage(monkeypatch, capsys): + monkeypatch.setattr("sys.stdin", __import__("io").StringIO("not json")) + assert smt.main(["--plan"]) == 0 + assert capsys.readouterr().out == "" + + +def test_main_writes_sidecar_then_aggregates(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + listing = tmp_path / "listing.json" + listing.write_text(json.dumps({"artifacts": [_artifact()]})) + downloads = tmp_path / "downloads" + _extracted(downloads, [_entry("imaging/x.py", seconds=30.0)], sub="11") + + out = per_repo / f"{REPO}.smoke_timings.json" + assert smt.main(["--name", REPO, "--group", "workspaces", "--owner", OWNER, + "--ts", "T", "--listing", str(listing), + "--downloads", str(downloads), "--out", str(out)]) == 0 + side = json.loads(out.read_text()) + assert side["legs"][0]["counts"]["timed"] == 1 + assert "script(s) timed" in capsys.readouterr().out + + prev = tmp_path / "board.json" + prev.write_text(json.dumps(_prev_board([_prev_row(10.0)]))) + roll_path = tmp_path / "smoke_timings.json" + assert smt.main(["--aggregate", "--per-repo-dir", str(per_repo), + "--prev-board", str(prev), "--ts", "T", + "--out", str(roll_path)]) == 0 + roll = json.loads(roll_path.read_text()) + assert roll["rows"][0]["repo"] == REPO and roll["rows"][0]["state"] == "warn" + assert "scripts timed across 1 repos" in capsys.readouterr().out + + +def test_main_records_a_fetch_error(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + out = tmp_path / f"{REPO}.smoke_timings.json" + assert smt.main(["--name", REPO, "--group", "workspaces", "--ts", "T", + "--out", str(out), "--fetch-error", "gh api exited 1"]) == 0 + side = json.loads(out.read_text()) + assert side["error"] == "gh api exited 1" and side["legs"] == [] + assert "UNAVAILABLE" in capsys.readouterr().out + + +def test_main_treats_an_unparseable_listing_as_a_fetch_error(tmp_path, monkeypatch, + capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + listing = tmp_path / "listing.json" + listing.write_text("404") + out = tmp_path / f"{REPO}.smoke_timings.json" + assert smt.main(["--name", REPO, "--group", "workspaces", "--ts", "T", + "--listing", str(listing), "--out", str(out)]) == 0 + assert json.loads(out.read_text())["error"] == "artifacts listing was not valid JSON" + capsys.readouterr() + + +def test_summary_lines_are_honest_about_unavailability(monkeypatch): + monkeypatch.setenv("NO_COLOR", "1") + dead = smt.build_sidecar(REPO, "workspaces", OWNER, [], "T", error="boom") + assert "UNAVAILABLE" in smt.repo_summary_line(dead) + roll = smt.aggregate([dead], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + assert "1 unavailable" in smt.summary_line(roll) diff --git a/tests/test_smoke_timings_script.py b/tests/test_smoke_timings_script.py new file mode 100644 index 00000000..51793d2a --- /dev/null +++ b/tests/test_smoke_timings_script.py @@ -0,0 +1,130 @@ +"""tests/test_smoke_timings_script.py — the shell leg's per-artifact failure path. + +The load-bearing claim in `smoke_timings.sh` is that ONE artifact's 403 must not +cost the repo its other python leg: the failure is written to +`/.error` and the loop continues. Exercised the way +`test_ci_status_script.py` drives its helper — source the file, call the one +function, and put stub executables first on `PATH` so nothing here touches the +network, a real `gh`, or a real zip. + +Fake names throughout (the tenant firewall). +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import textwrap +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "heart" / "checks" / "smoke_timings.sh" + +OWNER_NAME = "OwnerX/RepoA" +REPO = "RepoA" + +LISTING = { + "artifacts": [ + {"id": 1, "name": "smoke-timings-3.11", "expired": False, + "created_at": "2026-09-01T10:00:00Z", + "workflow_run": {"id": 7, "head_branch": "feat/x", "head_sha": "abc123"}}, + {"id": 2, "name": "smoke-timings-3.12", "expired": False, + "created_at": "2026-09-01T10:00:00Z", + "workflow_run": {"id": 7, "head_branch": "feat/x", "head_sha": "abc123"}}, + ] +} + +DATASET = { + "schema": "smoke_timings/1", "project": "ProjA", "directory": "imaging", + "run_type": "scripts", "env_profile": "smoke", "python": "3.11", + "ts": "2026-09-01T09:55:00Z", + "entries": [{"entry": "imaging/x.py", "kind": "script", "status": "passed", + "seconds": 12.0, "cap_s": 600.0, "exit_code": 0}], +} + + +def write_stub(bin_dir: Path, name: str, body: str) -> None: + path = bin_dir / name + path.write_text("#!/usr/bin/env bash\n" + textwrap.dedent(body)) + path.chmod(0o755) + + +@pytest.fixture +def env(tmp_path): + """A stub `gh` (artifact 2 is a 403), a stub `unzip`, and a state dir.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (tmp_path / "state" / "per-repo").mkdir(parents=True) + (tmp_path / "listing.json").write_text(json.dumps(LISTING)) + (tmp_path / "dataset.json").write_text(json.dumps(DATASET)) + + write_stub(bin_dir, "gh", f""" + case "$*" in + *"/actions/artifacts?per_page=100") cat "{tmp_path}/listing.json" ;; + *"/artifacts/1/zip") printf 'PK-not-a-real-zip' ;; + *"/artifacts/2/zip") + echo "gh: HTTP 403: Resource not accessible by integration" >&2 + exit 1 ;; + *) echo "unexpected gh call: $*" >&2; exit 1 ;; + esac + """) + # The real unzip would extract the artifact; the stub just materialises what + # a successful extraction leaves behind — the dataset file in //. + write_stub(bin_dir, "unzip", f""" + dest="" + while [ $# -gt 0 ]; do + if [ "$1" = "-d" ]; then dest="$2"; shift; fi + shift + done + mkdir -p "$dest" + cp "{tmp_path}/dataset.json" "$dest/smoke_timings.json" + """) + return { + "PATH": f"{bin_dir}:{Path(sys.executable).parent}:/usr/bin:/bin", + "HOME": str(tmp_path), + "HEART_STATE_DIR": str(tmp_path / "state"), + "NO_COLOR": "1", + "PYTHONPATH": str(ROOT), + } + + +def _ingest(env): + return subprocess.run( + ["bash", "-c", + 'source "$1" >/dev/null 2>&1; ingest_one_repo "$2" "$3"', + "ingest_one_repo", str(SCRIPT), OWNER_NAME, "workspaces"], + capture_output=True, text=True, env={**os.environ, **env}, + ) + + +def test_one_leg_403_still_writes_the_other_leg_and_records_the_error(env): + proc = _ingest(env) + assert proc.returncode == 0, proc.stderr + side = json.loads( + (Path(env["HEART_STATE_DIR"]) / "per-repo" / f"{REPO}.smoke_timings.json").read_text() + ) + assert side["name"] == REPO and side["error"] == "" + legs = {leg["python"]: leg for leg in side["legs"]} + assert set(legs) == {"3.11", "3.12"} + # The leg that downloaded is intact... + assert legs["3.11"]["entries"][0]["entry"] == "imaging/x.py" + assert legs["3.11"]["error"] == "" and legs["3.11"]["total_s"] == 12.0 + # ...and the 403 leg keeps its provenance with an honest error. + assert "403" in legs["3.12"]["error"] and legs["3.12"]["entries"] == [] + assert legs["3.12"]["run_url"].endswith("/OwnerX/RepoA/actions/runs/7") + + +def test_a_failed_listing_fetch_is_recorded_not_silently_quiet(env, tmp_path): + write_stub(tmp_path / "bin", "gh", """ + echo "gh: HTTP 502" >&2 + exit 1 + """) + assert _ingest(env).returncode == 0 + side = json.loads( + (Path(env["HEART_STATE_DIR"]) / "per-repo" / f"{REPO}.smoke_timings.json").read_text() + ) + assert "502" in side["error"] and side["legs"] == []