diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index 8e9a8818..f35d7132 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -13,6 +13,11 @@ name: Heart Health # * step summary — fmt="md" into $GITHUB_STEP_SUMMARY (zero hosting) # * README — a shields verdict badge + an auto-updated # … md block +# and commits, beside that block, the day's lines of the PERMANENT timing +# record (timings/gates.jsonl + timings/scripts/.jsonl). This job is +# the record's single writer; the two timing checks read it back as the +# first source for their baselines, with the published board.json only as +# the fallback, so a Pages gap no longer loses history. # 2. opens-or-updates a single "[heart-health]" tracking ISSUE when anything # is red/degraded and closes it when clean — the ALERTING channel (kept). # @@ -114,6 +119,26 @@ jobs: bash heart/checks/smoke_timings.sh exit 0 + - name: Append today's observations to the timing record + run: | + # ORDERING: after the checks, before the render. The checks' aggregate + # passes have already READ the record for their baselines, and neither + # can be fooled by today's own line — ci_timing's `history_baseline` + # excludes today's date, and smoke_timings compares by run id and + # refuses to compare a run against itself. So appending here is safe, + # and it lets the render census a record that already includes today. + # + # SINGLE WRITER: only this workflow appends. The record is committed + # into this repo (below, beside the README block), and two writers on + # an append-only file in git is a merge conflict waiting for a human — + # a dev-box tick never appends. + # + # A missing rollup means "nothing to append from that slice", never an + # error: this exits 0 whatever the checks managed to produce. + PYTHONPATH="$PWD" python -m heart.timings append \ + --ci-timing "$HEART_STATE_DIR/ci_timing.json" \ + --smoke-timings "$HEART_STATE_DIR/smoke_timings.json" + - name: Aggregate snapshot + compute readiness verdict run: | # Fold the per-repo sidecars into state.json, then compute the @@ -150,7 +175,7 @@ jobs: echo "_Published board: https://pyautolabs.github.io/PyAutoHeart/_" } >> "$GITHUB_STEP_SUMMARY" - - name: Update README badge + block (own repo only, main only) + - name: Commit the README block + today's timing record (own repo only, main only) if: github.ref == 'refs/heads/main' env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -175,14 +200,18 @@ jobs: text = "\n".join(lines) readme.write_text(text) PY - if ! git diff --quiet README.md; then + # `git status --porcelain` rather than `git diff --quiet`, because + # the record's first line for a repo creates an UNTRACKED file, which + # a diff of the working tree cannot see. One commit a day carries both + # the README block and the day's appended lines. + if [ -n "$(git status --porcelain README.md timings/)" ]; then git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - git add README.md - git commit -m "docs(heart): auto-update health dashboard block [skip ci]" + git add README.md timings/ + git commit -m "docs(heart): daily board block + timing record [skip ci]" git push else - echo "README health block unchanged — nothing to commit." + echo "README health block and timing record unchanged — nothing to commit." fi - name: Upload Pages artifact diff --git a/heart/checks/ci_timing.py b/heart/checks/ci_timing.py index f7c00b5a..c5a1b7fb 100644 --- a/heart/checks/ci_timing.py +++ b/heart/checks/ci_timing.py @@ -47,6 +47,11 @@ * **A failed fetch is not a quiet repo.** ``--fetch-error`` records the reason and writes empty ``workflows``/``events``; "we could not ask" must never render as "all quiet". +* **The history comes from the committed record first.** ``timings/gates.jsonl`` + (see ``heart/timings.py``) is durable; the previously published ``board.json`` + is the same artifact this render produces, so a Pages gap loses it. The board + stays as the fallback — first run, fresh clone, no record yet — and the + rolled-forward ``performance.history`` is written either way. Per-repo sidecar schema (``.ci_timing.json``):: @@ -479,10 +484,27 @@ def aggregate( today: str, ts: str, thresholds: dict[str, float] | None = None, + record_history: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: - """Fold the per-repo sidecars + the previous board into the global rollup.""" + """Fold the per-repo sidecars + the history into the global rollup. + + ``record_history`` is the COMMITTED record (``timings/gates.jsonl``, via + ``heart.timings.gates_history``) and is preferred whenever it is non-empty: + it is durable, whereas the previously published board is the same artifact + the render produces and a Pages gap loses it. The board stays as the + fallback for the very first run, a fresh clone, or a record that is not + there yet. + + Whichever history was used is also what ``roll_history`` rolls forward, so + ``board.json``'s ``performance.history`` keeps its shape either way — it + remains the fallback cache and the Brain board's sparkline input. + """ thr = dict(thresholds or DEFAULT_CI_TIMING_THRESHOLDS) - history_in = prev_history_of(prev_board) + history_in = ( + [e for e in record_history if isinstance(e, dict)] + if record_history + else prev_history_of(prev_board) + ) gates: list[dict[str, Any]] = [] events: list[dict[str, Any]] = [] @@ -631,6 +653,10 @@ def main(argv: list[str] | None = None) -> int: help="ISO date for the history entry (default: today, UTC)") ap.add_argument("--per-repo-dir", default="", help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)") + ap.add_argument("--record-dir", default="", + help="the committed timing record (default: HEART_HOME/timings); " + "its gates.jsonl is the preferred history source, the " + "previous board.json only the fallback") ap.add_argument("--fetch-error", default="", help="reason the runs fetch failed; recorded instead of a bogus quiet repo") ns = ap.parse_args(argv) @@ -640,12 +666,18 @@ def main(argv: list[str] | None = None) -> int: if ns.aggregate: sys.path.insert(0, str(HEART_HOME)) from heart import state as _state + from heart import timings as _timings per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR today = ns.today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + thr = load_thresholds() + record_dir = Path(ns.record_dir) if ns.record_dir else _timings.TIMINGS_DIR rollup = aggregate( read_sidecars(per_repo), read_prev_board(ns.prev_board), today, ts, - load_thresholds(), + thr, + record_history=_timings.gates_history( + record_dir / "gates.jsonl", int(thr.get("history_cap", 30)) + ), ) _write(Path(ns.out), rollup) print(summary_line(rollup)) diff --git a/heart/checks/ci_timing.sh b/heart/checks/ci_timing.sh index 34ca6e71..0ae71c8a 100644 --- a/heart/checks/ci_timing.sh +++ b/heart/checks/ci_timing.sh @@ -92,8 +92,12 @@ check_ci_timing_all() { local prev prev="$(_ci_timing_prev_board)" + # The committed record (timings/gates.jsonl) is the source of truth for the + # history; the previously published board is only the fallback for when it + # is not there yet (first run, fresh clone, a Pages-only consumer). PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_timing \ --aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \ + --record-dir "$HEART_HOME/timings" \ --out "$HEART_STATE_DIR/ci_timing.json" [[ -n "$prev" ]] && rm -f "$prev" diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 68ffc2aa..9e048f14 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -48,6 +48,11 @@ 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×. +* **The previous observation comes from the committed record first.** + ``timings/scripts/.jsonl`` (see ``heart/timings.py``) is durable and + keyed by ``(python, run_id)``; the published board is the same artifact this + render produces, so a Pages gap loses it. The board stays as the fallback, + and the ``performance.scripts.rows`` block is written either way. * **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. @@ -80,8 +85,9 @@ Global rollup schema (``smoke_timings.json``):: {"ts", - "repos": [{repo, python, run_id, run_url, head_branch, at, entries, - timed, total_s, error, slowest: [...]}], + "repos": [{repo, python, run_id, run_url, head_branch, head_sha, + env_profile, 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}], @@ -513,10 +519,19 @@ def aggregate( prev_board: Any, ts: str, thresholds: dict[str, float] | None = None, + record_prev_rows: dict[tuple[str, str, str], dict[str, Any]] | None = None, ) -> dict[str, Any]: - """Fold the per-repo sidecars + the previous board into the global rollup.""" + """Fold the per-repo sidecars + the previous observation into the rollup. + + ``record_prev_rows`` is the COMMITTED record (``timings/scripts/``, via + ``heart.timings.previous_script_rows``) in the same + ``(repo, python, entry) -> row`` shape ``prev_rows_of`` returns, and is + preferred whenever it is non-empty. The published board stays as the + fallback: it is the same artifact this render produces, so a Pages gap + costs the comparison, while the record does not. + """ thr = dict(thresholds or DEFAULT_SMOKE_TIMINGS_THRESHOLDS) - prev_rows = prev_rows_of(prev_board) + prev_rows = dict(record_prev_rows) if record_prev_rows else prev_rows_of(prev_board) top_n = int(thr.get("top_n", 5) or 5) repos: list[dict[str, Any]] = [] @@ -605,6 +620,10 @@ def _name_of(side: Any) -> str: "run_id": run_id, "run_url": run_url, "head_branch": str(leg.get("head_branch") or ""), + # Provenance the committed record stores per observation: which + # commit was measured, and under which environment profile. + "head_sha": str(leg.get("head_sha") or ""), + "env_profile": str(leg.get("env_profile") or ""), "at": at, "entries": len(entries), "timed": timed if timed is not None else len(leg_rows), @@ -757,6 +776,10 @@ def main(argv: list[str] | None = None) -> int: "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("--record-dir", default="", + help="the committed timing record (default: HEART_HOME/timings); " + "its scripts/ files are the preferred previous " + "observation, the previous board.json only the fallback") ap.add_argument("--fetch-error", default="", help="reason the artifacts listing fetch failed; recorded " "instead of a bogus quiet repo") @@ -780,11 +803,14 @@ def main(argv: list[str] | None = None) -> int: if ns.aggregate: sys.path.insert(0, str(HEART_HOME)) from heart import state as _state + from heart import timings as _timings per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR + record_dir = Path(ns.record_dir) if ns.record_dir else _timings.TIMINGS_DIR rollup = aggregate( read_sidecars(per_repo), read_prev_board(ns.prev_board), ts, load_thresholds(), + record_prev_rows=_timings.previous_script_rows(record_dir / "scripts"), ) _write(Path(ns.out), rollup) print(summary_line(rollup)) diff --git a/heart/checks/smoke_timings.sh b/heart/checks/smoke_timings.sh index 7eb8df3d..40f99b0b 100755 --- a/heart/checks/smoke_timings.sh +++ b/heart/checks/smoke_timings.sh @@ -142,8 +142,12 @@ check_smoke_timings_all() { local prev prev="$(_smoke_timings_prev_board)" + # The committed record (timings/scripts/.jsonl) is the source of truth + # for the previous observation; the previously published board is only the + # fallback for when it is not there yet. PYTHONPATH="$HEART_HOME" python3 -m heart.checks.smoke_timings \ --aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \ + --record-dir "$HEART_HOME/timings" \ --out "$HEART_STATE_DIR/smoke_timings.json" [[ -n "$prev" ]] && rm -f "$prev" diff --git a/heart/dashboard.py b/heart/dashboard.py index dc09f0f0..290e2721 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -892,8 +892,27 @@ def build_board( ) +def _record_lines(record: Any) -> tuple[str, str]: + """The two `record:` detail lines from the committed record's census. + + Empty strings when the census is absent — a snapshot taken before the + record existed must render byte-identically to how it always did, so the + caller appends nothing rather than a line saying "0 days". + """ + if not isinstance(record, dict) or not record: + return "", "" + days = _as_int(record.get("gates_days")) + obs = _as_int(record.get("scripts_observations")) + repos = _as_int(record.get("repos")) + return ( + f"record: timings/gates.jsonl — {days} days", + f"record: timings/scripts/ — {obs} observations across {repos} repos", + ) + + def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict], - errors: list, history: list[dict]) -> Section: + errors: list, history: list[dict], + record: Any = None) -> Section: """The CI wall-clock row: how long the gates a change must pass now take.""" timed = [g for g in gates if _as_int(g.get("runs_counted"))] warned = [g for g in gates if g.get("state") == "warn"] @@ -927,6 +946,11 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict], 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) + # 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) links = [ {"label": f"{e.get('repo')} {e.get('kind')}", "url": str(e.get("run_url")), @@ -948,7 +972,7 @@ def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict], def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict], slowed: list[dict], events: list[dict], - errors: list) -> Section: + errors: list, record: Any = None) -> 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 @@ -982,6 +1006,11 @@ def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict], 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}") + # Same as the gate row: how much durable history stands behind the + # run-to-run comparisons. Absent census adds no line at all. + scripts_line = _record_lines(record)[1] + if scripts_line: + details.append(scripts_line) links = [ {"label": f"{e.get('repo')} {e.get('entry')} TIMEOUT", @@ -1051,6 +1080,12 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non nr = nr if isinstance(nr, dict) else {} st = snapshot.get("smoke_timings") st = st if isinstance(st, dict) else {} + # The census of the committed timing record. It decorates the two timing + # rows with one detail line each and touches NOTHING else — in particular + # the `performance` block below is unchanged by it, so the Brain board and + # the next render's fallback read exactly what they always read. + record = snapshot.get("timings_record") + record = record if isinstance(record, dict) else {} if not ct and not nr and not st: return None @@ -1069,10 +1104,11 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non st_errors = list(st.get("errors") or []) if ct: - sections.append(_ci_timing_section(ct, gates, events, errors, history)) + sections.append(_ci_timing_section(ct, gates, events, errors, history, + record)) if st: sections.append(_smoke_timings_section(st, st_repos, st_rows, st_slowed, - st_events, st_errors)) + st_events, st_errors, record)) if nr: sections.append(_no_run_section(totals, rows, repo_rows)) diff --git a/heart/state.py b/heart/state.py index 6fe675ca..91c6e7c7 100644 --- a/heart/state.py +++ b/heart/state.py @@ -80,6 +80,11 @@ def aggregate() -> dict[str, Any]: "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", {}), + # The census of the COMMITTED timing record (timings/), written by + # `heart.timings append` in the daily cloud job. A snapshot taken + # before the record existed simply has no key, and the board renders + # exactly as it did — the census adds a detail line, never a row. + "timings_record": _read_json_or_default(HEART_STATE_DIR / "timings_record.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/heart/timings.py b/heart/timings.py new file mode 100644 index 00000000..e4698850 --- /dev/null +++ b/heart/timings.py @@ -0,0 +1,532 @@ +"""heart/timings.py — the permanent CI timing record, committed into this repo. + +``ci_timing`` measures the gates and ``smoke_timings`` measures the scripts +inside them, and both of them carried their own history in exactly one place: +the ``board.json`` the last run published to Pages. That is free and it is +idempotent, but it is also *the same artifact the render produces* — a Pages +publish gap, a rewritten board, a schema change, and the history is simply +gone. There is no second copy, and nothing can be recomputed after the fact: +the Actions REST window is a couple of weeks and an artifact expires in days. + +This module is the second copy, and it is the one that lasts: an append-only +record committed into PyAutoHeart's own repo beside the README block, one +commit a day, written by the daily cloud job and by nothing else. + +Layout:: + + timings/README.md # the schema + the rules (doctrine) + timings/gates.jsonl # one line per UTC date + timings/scripts/.jsonl # one line per (python leg, run id) + +Deliberate choices, each one a recorded lesson: + +* **Append-only, never rewritten.** Lines are only ever added. A wrong line is + superseded by a later one, never edited away — the record is evidence, and + evidence that can be quietly rewritten is not evidence. Consequently every + writer here appends; none of them opens a file for truncation. +* **Dedupe on identity, never on the day.** The gates file is keyed by + ``date``; the scripts files by ``(python, run_id)``. The distinction matters: + a quiet week produces the SAME smoke run for seven days running, and keying + the scripts record on the day would write seven copies of one measurement — + the ``script_timing`` "one value repeated seven times" defect, recorded once + and not to be re-derived. A re-run of the daily job on the same date is + likewise a no-op rather than a duplicate point in every sparkline. +* **Only measurements are recorded.** ``rows`` in the smoke rollup carries the + *timed* entries; an entry the runner skipped has ``seconds: null`` and was + never a measurement, so it is not in the record. The per-leg census + (``repos[].entries``) keeps the coverage visible beside the count. +* **A missing file is an empty record, never an error.** This is read and + written by an unattended job: bad input degrades to an honest empty/partial + record and exit 0. An unparseable line is skipped and *counted*, so the + census can say the record has a hole rather than pretending it does not. +* **Single writer.** Only the daily cloud job appends (the workflow's own + comment says so). A dev-box tick never does — two writers on an append-only + file in a git repo is a merge conflict waiting for a human. + +``gates.jsonl`` line:: + + {"date": "2026-09-05", "ts": "2026-09-05T05:03:00+00:00", + "gates": {"RepoA/Gate One": {"p50_s": 553.0, "pr_median_s": 601.0, + "max_s": 912.0, "queue_median_s": 12.0, + "runs": 14}}} + +``scripts/.jsonl`` line:: + + {"date": "2026-09-05", "at": "2026-09-04T10:00:00Z", "python": "3.12", + "run_id": 7, "run_url": "https://ci.invalid/runs/7", + "head_branch": "feat/x", "head_sha": "abc123", "env_profile": "smoke", + "entries": {"imaging/x.py": [12.5, "passed", 600.0]}} + +The entry triple is ``[seconds, status, cap_s]`` — positional on purpose: this +file grows by one line per leg per run forever, and the three keys repeated on +every entry would triple it for nothing a reader cannot infer from the schema. + +``timings/epochs.jsonl`` is RESERVED (``EPOCHS_FILE``) for a future labelled +epoch boundary — ``{"date", "label", "note"}``, e.g. "runners moved to 8-core" +— so a reader can tell a step change from a regression. Nothing here writes it +and the file deliberately does not exist yet. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import sys +from pathlib import Path +from typing import Any + +HEART_HOME = Path(__file__).resolve().parents[1] +TIMINGS_DIR = HEART_HOME / "timings" +GATES_FILE = TIMINGS_DIR / "gates.jsonl" +SCRIPTS_DIR = TIMINGS_DIR / "scripts" +# Named so the reservation is in the code, not only in the README. NOTHING +# writes this: an epoch boundary is a human's judgement about the world (a +# runner change, a cap change), not something a daily job can observe. +EPOCHS_FILE = TIMINGS_DIR / "epochs.jsonl" + +# The census key set, so a reader (and `show`) sees the same keys whether or +# not the record exists yet. +EMPTY_CENSUS = { + "gates_days": 0, + "gates_first": "", + "gates_last": "", + "scripts_observations": 0, + "repos": 0, + "unparseable": 0, +} + + +def scripts_file(repo: str, directory: Path | str = TIMINGS_DIR) -> Path: + """The per-repo scripts record path under ``directory``.""" + return Path(directory) / "scripts" / f"{repo}.jsonl" + + +# --- jsonl I/O --------------------------------------------------------------- +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) + return None + + +def _as_int(value: Any, default: int = 0) -> int: + if isinstance(value, bool) or value is None: + return default + if isinstance(value, (int, float)): + return int(value) + return default + + +def read_jsonl(path: Path | str) -> tuple[list[dict[str, Any]], int]: + """``(records, unparseable_count)``. A missing file is ``([], 0)``. + + A line that is not a JSON object is skipped and counted rather than raised + over: this is read inside an unattended job, and one corrupt line must cost + that line, not the record. The count travels into the census so the hole is + visible instead of silent. + """ + p = Path(path) + if not p.is_file(): + return [], 0 + try: + text = p.read_text() + except OSError: + return [], 0 + records: list[dict[str, Any]] = [] + skipped = 0 + for line in text.splitlines(): + if not line.strip(): + continue + try: + data = json.loads(line) + except ValueError: + skipped += 1 + continue + if isinstance(data, dict): + records.append(data) + else: + skipped += 1 + return records, skipped + + +def _dump(record: dict[str, Any]) -> str: + """One record → one compact, stable line. + + ``sort_keys`` so two writers of the same content produce the same bytes and + a diff shows only what changed; ``ensure_ascii=False`` so a UTF-8 path stays + readable in the file rather than becoming escapes. + """ + return json.dumps(record, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + + +def _append(path: Path | str, records: list[dict[str, Any]]) -> None: + """Append records to ``path`` (creating its directory). Never rewrites.""" + if not records: + return + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + with p.open("a", encoding="utf-8") as handle: + for record in records: + handle.write(_dump(record) + "\n") + + +# --- gates ------------------------------------------------------------------- +def gates_line_from_rollup( + rollup: Any, today: str, ts: str +) -> dict[str, Any] | None: + """One ``gates.jsonl`` line from a ``ci_timing.json`` rollup, or None. + + Only gates whose ``median_s`` is a number are recorded: a gate with no + completed runs in the window measured nothing, and a row of nulls would + make the record look like it has coverage it does not have. ``None`` when + that leaves nothing — an empty line is worse than no line. + """ + gates: dict[str, Any] = {} + if isinstance(rollup, dict): + for gate in rollup.get("gates") or []: + if not isinstance(gate, dict): + continue + median = _as_float(gate.get("median_s")) + if median is None: + continue + repo = str(gate.get("repo") or "") + workflow = str(gate.get("workflow") or "") + if not repo or not workflow: + continue + gates[f"{repo}/{workflow}"] = { + "p50_s": median, + "pr_median_s": _as_float(gate.get("pr_median_s")), + "max_s": _as_float(gate.get("max_s")), + "queue_median_s": _as_float(gate.get("queue_median_s")), + "runs": _as_int(gate.get("runs_counted")), + } + if not gates: + return None + return {"date": today, "ts": ts, "gates": gates} + + +def append_gates(path: Path | str, line: dict[str, Any] | None) -> bool: + """Append one dated gates line. ``False`` when that date is already there. + + Keyed by ``date``: the daily job re-run on the same day is a no-op rather + than a second point for the same day in every gate's sparkline. + """ + if not isinstance(line, dict) or not line.get("date"): + return False + existing, _ = read_jsonl(path) + date = str(line["date"]) + if any(str(rec.get("date") or "") == date for rec in existing): + return False + _append(path, [line]) + return True + + +def gates_history( + path: Path | str = GATES_FILE, cap: int = 30 +) -> list[dict[str, Any]]: + """The last ``cap`` gates lines, oldest first, in the *history* shape. + + ``{"date", "gates": {key: {"p50_s", "runs"}}}`` — exactly what + ``ci_timing.history_baseline`` and ``dashboard._gate_spark`` read. The extra + per-gate figures the record keeps (PR median, max, queue) are deliberately + dropped from this view: the baseline and the sparkline are about the p50, + and widening the shape here would change ``board.json``'s + ``performance.history`` for every consumer downstream. + """ + records, _ = read_jsonl(path) + out: list[dict[str, Any]] = [] + for record in records: + date = str(record.get("date") or "") + if not date: + continue + gates = record.get("gates") + if not isinstance(gates, dict): + continue + view = { + str(key): {"p50_s": _as_float(row.get("p50_s")), + "runs": _as_int(row.get("runs"))} + for key, row in gates.items() + if isinstance(row, dict) and _as_float(row.get("p50_s")) is not None + } + out.append({"date": date, "gates": view}) + return out[-int(cap):] if cap and int(cap) > 0 else out + + +# --- scripts ----------------------------------------------------------------- +def scripts_lines_from_rollup( + rollup: Any, today: str +) -> dict[str, list[dict[str, Any]]]: + """``{repo: [line, ...]}`` from a ``smoke_timings.json`` rollup. + + One line per ``(repo, python, run_id)``: the identity of a measurement. + ``repos`` carries the provenance (run, branch, sha, env profile) and + ``rows`` carries the timed entries, so the two are joined on that key. + + A leg with no ``run_id`` is skipped outright — without it the line has no + identity, so the dedupe could not tell one run from another and a quiet + week would record the same numbers over and over. + """ + out: dict[str, list[dict[str, Any]]] = {} + if not isinstance(rollup, dict): + return out + + entries_by_key: dict[tuple[str, str, str], dict[str, Any]] = {} + for row in rollup.get("rows") or []: + if not isinstance(row, dict): + continue + run_id = row.get("run_id") + if run_id is None or str(run_id) == "": + continue + entry = str(row.get("entry") or "") + seconds = _as_float(row.get("seconds")) + if not entry or seconds is None: + continue + key = (str(row.get("repo") or ""), str(row.get("python") or ""), + str(run_id)) + entries_by_key.setdefault(key, {})[entry] = [ + seconds, str(row.get("status") or ""), _as_float(row.get("cap_s")), + ] + + seen: set[tuple[str, str, str]] = set() + for leg in rollup.get("repos") or []: + if not isinstance(leg, dict): + continue + repo = str(leg.get("repo") or "") + run_id = leg.get("run_id") + if not repo or run_id is None or str(run_id) == "": + continue + python = str(leg.get("python") or "") + key = (repo, python, str(run_id)) + if key in seen: + continue + seen.add(key) + entries = entries_by_key.get(key, {}) + out.setdefault(repo, []).append({ + "date": today, + "at": str(leg.get("at") or ""), + "python": python, + "run_id": run_id, + "run_url": str(leg.get("run_url") or ""), + "head_branch": str(leg.get("head_branch") or ""), + # Absent from an older rollup: stored empty rather than omitted, so + # every line in the file has the same keys. + "head_sha": str(leg.get("head_sha") or ""), + "env_profile": str(leg.get("env_profile") or ""), + "entries": {name: entries[name] for name in sorted(entries)}, + }) + for repo in out: + out[repo].sort(key=lambda line: (str(line.get("python") or ""), + str(line.get("run_id") or ""))) + return out + + +def append_scripts(path: Path | str, lines: list[dict[str, Any]]) -> int: + """Append the scripts lines not already recorded. Returns how many landed. + + Keyed by ``(python, run_id)``, NOT by the day: the smoke artifacts only + change when a PR runs, so a quiet week hands the daily job the same run + seven times. Keying on the day would write seven identical observations and + make a flat week look like a week of measurements. + """ + existing, _ = read_jsonl(path) + seen = { + (str(rec.get("python") or ""), str(rec.get("run_id") or "")) + for rec in existing + } + fresh: list[dict[str, Any]] = [] + for line in lines or []: + if not isinstance(line, dict): + continue + key = (str(line.get("python") or ""), str(line.get("run_id") or "")) + if not key[1] or key in seen: + continue + seen.add(key) + fresh.append(line) + _append(path, fresh) + return len(fresh) + + +def previous_script_rows( + scripts_dir: Path | str = SCRIPTS_DIR, +) -> dict[tuple[str, str, str], dict[str, Any]]: + """``{(repo, python, entry): prev_row}`` — the last recorded observation. + + The shape is exactly what ``smoke_timings.classify_drift`` expects of a + previous row (``seconds``/``run_id``/``run_url``), so the record can stand + in for ``performance.scripts.rows`` off the published board. + + The *latest* line per python leg wins, and "latest" is file order: the file + is append-only, so the last line for a leg is the most recently recorded + one. Timed entries only — the record holds no untimed rows to begin with, + and a row with no seconds could not be compared anyway. + """ + out: dict[tuple[str, str, str], dict[str, Any]] = {} + root = Path(scripts_dir) + if not root.is_dir(): + return out + for path in sorted(root.glob("*.jsonl")): + repo = path.name[: -len(".jsonl")] + records, _ = read_jsonl(path) + latest: dict[str, dict[str, Any]] = {} + for record in records: + latest[str(record.get("python") or "")] = record + for python, record in latest.items(): + entries = record.get("entries") + if not isinstance(entries, dict): + continue + for entry, triple in entries.items(): + if not isinstance(triple, (list, tuple)) or not triple: + continue + seconds = _as_float(triple[0]) + if seconds is None: + continue + out[(repo, python, str(entry))] = { + "seconds": seconds, + "run_id": record.get("run_id"), + "run_url": str(record.get("run_url") or ""), + "status": str(triple[1]) if len(triple) > 1 else "", + "cap_s": _as_float(triple[2]) if len(triple) > 2 else None, + } + return out + + +# --- census ------------------------------------------------------------------ +def census(directory: Path | str = TIMINGS_DIR) -> dict[str, Any]: + """What the record holds — the one-screen answer, and the board's detail. + + ``unparseable`` is summed across every file so a corrupt line is reported + rather than silently dropped: the record is evidence, and a hole in it is + itself a finding. + """ + root = Path(directory) + out = dict(EMPTY_CENSUS) + gates, skipped = read_jsonl(root / "gates.jsonl") + dates = sorted(str(rec.get("date") or "") for rec in gates if rec.get("date")) + out["gates_days"] = len(dates) + out["gates_first"] = dates[0] if dates else "" + out["gates_last"] = dates[-1] if dates else "" + out["unparseable"] = skipped + + scripts_root = root / "scripts" + repos = 0 + observations = 0 + if scripts_root.is_dir(): + for path in sorted(scripts_root.glob("*.jsonl")): + records, repo_skipped = read_jsonl(path) + out["unparseable"] += repo_skipped + if records: + repos += 1 + observations += len(records) + out["repos"] = repos + out["scripts_observations"] = observations + return out + + +# --- I/O shell --------------------------------------------------------------- +def _read_rollup(path: str | Path | None) -> Any: + """One rollup JSON, or ``{}``. + + A missing or unreadable rollup means "nothing to append from that slice" — + the other slice still records. Never an error: the check that writes it + already recorded its own failure honestly. + """ + if not path: + return {} + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError): + return {} + + +def _default_census_out() -> Path: + from heart import state + + return state.HEART_STATE_DIR / "timings_record.json" + + +def _do_append(ns: argparse.Namespace) -> int: + from heart import state + + directory = Path(ns.dir) if ns.dir else TIMINGS_DIR + today = ns.today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + ts = ns.ts or datetime.datetime.now(datetime.timezone.utc).isoformat() + + gates_line = gates_line_from_rollup(_read_rollup(ns.ci_timing), today, ts) + gates_added = append_gates(directory / "gates.jsonl", gates_line) + skipped = 1 if (gates_line is not None and not gates_added) else 0 + + per_repo = scripts_lines_from_rollup(_read_rollup(ns.smoke_timings), today) + appended: dict[str, int] = {} + scripts_added = 0 + for repo in sorted(per_repo): + lines = per_repo[repo] + added = append_scripts(scripts_file(repo, directory), lines) + skipped += len(lines) - added + if added: + appended[repo] = added + scripts_added += added + + payload = dict(census(directory)) + payload["appended_today"] = {"gates": gates_added, "scripts": appended} + out_path = Path(ns.census_out) if ns.census_out else _default_census_out() + try: + state.atomic_write_json(out_path, payload) + except OSError: + # The census is a convenience for the render, never the record itself. + pass + + print( + f"timings: gates +{1 if gates_added else 0} line, " + f"scripts +{scripts_added} lines across {len(appended)} repos, " + f"{skipped} skipped (already recorded)" + ) + return 0 + + +def _do_show(ns: argparse.Namespace) -> int: + directory = Path(ns.dir) if ns.dir else TIMINGS_DIR + for key, value in census(directory).items(): + print(f"{key}: {value}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="heart.timings") + sub = ap.add_subparsers(dest="command", required=True) + + ap_append = sub.add_parser( + "append", help="append today's observations to the committed record" + ) + ap_append.add_argument("--ci-timing", default="", + help="the ci_timing.json rollup; missing => nothing " + "to append from that slice, never an error") + ap_append.add_argument("--smoke-timings", default="", + help="the smoke_timings.json rollup; missing => " + "nothing to append from that slice") + ap_append.add_argument("--today", default="", + help="ISO date for the gates line (default: today, UTC)") + ap_append.add_argument("--ts", default="", + help="ISO timestamp stamped on the gates line") + ap_append.add_argument("--dir", default="", + help=f"the record directory (default: {TIMINGS_DIR})") + ap_append.add_argument("--census-out", default="", + help="where the census JSON lands (default: " + "$HEART_STATE_DIR/timings_record.json)") + + ap_show = sub.add_parser("show", help="print the record's census") + ap_show.add_argument("--dir", default="", + help=f"the record directory (default: {TIMINGS_DIR})") + + ns = ap.parse_args(argv) + sys.path.insert(0, str(HEART_HOME)) + if ns.command == "append": + return _do_append(ns) + return _do_show(ns) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_ci_timing.py b/tests/test_ci_timing.py index 353714c8..8bbc4874 100644 --- a/tests/test_ci_timing.py +++ b/tests/test_ci_timing.py @@ -464,3 +464,89 @@ def test_main_treats_unparseable_stdin_as_fetch_error(tmp_path, monkeypatch, cap assert rc == 0 assert json.loads(out.read_text())["error"] capsys.readouterr() + + +# --- the committed record is the history source; the board is the fallback --- +# +# The published board.json is the same artifact this render produces, so a Pages +# gap loses it and nothing can recompute it. `timings/gates.jsonl` is the +# durable copy (see heart/timings.py) and it wins whenever it has anything. + +def _record_history(p50): + return [{"date": "2026-08-23", "gates": {f"{REPO}/Gate One": + {"p50_s": p50, "runs": 9}}}] + + +def _prev_board_history(p50): + return {"performance": {"history": [ + {"date": "2026-08-23", "gates": {f"{REPO}/Gate One": + {"p50_s": p50, "runs": 9}}}, + ]}} + + +def _one_gate_sidecar(median_s): + return { + "name": REPO, "group": "workspaces", "owner": "OwnerX", "error": "", + "ts": "T", + "workflows": {"Gate One": { + "median_s": median_s, "pr_median_s": None, "queue_median_s": None, + "max_s": median_s, "runs_counted": 5, "window_from": "", + "conclusions": {"success": 5}, "superseded": 0, + "actions_url": ACTIONS, + }}, + "events": [], + } + + +def test_aggregate_prefers_the_committed_record_over_the_previous_board(): + thr = {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30} + roll = ct.aggregate( + [_one_gate_sidecar(900.0)], + # The board would say the gate has always taken 900s — no drift. + _prev_board_history(900.0), "2026-08-24", "T", thr, + # The record says it took 300s yesterday — the drift is real. + record_history=_record_history(300.0), + ) + (gate,) = roll["gates"] + assert gate["baseline_s"] == 300.0 and gate["state"] == "warn" + + +def test_aggregate_falls_back_to_the_previous_board_when_the_record_is_empty(): + thr = {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30} + for record in (None, []): + roll = ct.aggregate([_one_gate_sidecar(900.0)], _prev_board_history(300.0), + "2026-08-24", "T", thr, record_history=record) + (gate,) = roll["gates"] + assert gate["baseline_s"] == 300.0 and gate["state"] == "warn" + + +def test_the_rolled_forward_history_keeps_its_shape_whichever_source_was_used(): + """board.json's `performance.history` is the fallback cache AND the Brain + board's sparkline input — the record must not change what it looks like.""" + thr = {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30} + roll = ct.aggregate([_one_gate_sidecar(900.0)], {}, "2026-08-24", "T", thr, + record_history=_record_history(300.0)) + assert [h["date"] for h in roll["history"]] == ["2026-08-23", "2026-08-24"] + assert roll["history"][-1]["gates"][f"{REPO}/Gate One"] == { + "p50_s": 900.0, "runs": 5, + } + + +def test_main_aggregate_reads_the_record_directory(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() + (per_repo / f"{REPO}.ci_timing.json").write_text(json.dumps(_one_gate_sidecar(900.0))) + + record = tmp_path / "timings" + record.mkdir() + (record / "gates.jsonl").write_text(json.dumps(_record_history(300.0)[0]) + "\n") + + out = tmp_path / "ci_timing.json" + assert ct.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--today", "2026-08-24", "--record-dir", str(record), + "--out", str(out)]) == 0 + (gate,) = json.loads(out.read_text())["gates"] + assert gate["baseline_s"] == 300.0 and gate["state"] == "warn" + capsys.readouterr() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 3b513b08..66b6ebcd 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1232,3 +1232,64 @@ def test_the_terminal_verdict_points_at_the_door_out_of_stale(): # the prompt hook's one-liner stays a one-liner quiet = "\n".join(dashboard.render_readiness_block(v, quiet=True)) assert "fix stale" not in quiet + + +# --- the committed timing record's census on the two ⏱ rows ------------------ +# +# The record (timings/gates.jsonl + timings/scripts/) is where the history now +# durably lives; the board says how much of it stands behind the numbers. It is +# a DETAIL LINE and nothing else: an older snapshot has no census and renders +# exactly as it always did, and the `performance` block never sees it. + +TIMINGS_CENSUS = { + "gates_days": 42, "gates_first": "2026-07-25", "gates_last": "2026-09-05", + "scripts_observations": 96, "repos": 3, "unparseable": 0, + "appended_today": {"gates": True, "scripts": {"RepoA": 1}}, +} + + +def _record_snapshot(**kw): + return make_snapshot(ci_timing=_ci_timing_slice(), no_run_census=_no_run_slice(), + smoke_timings=_smoke_timings_slice(), + timings_record=TIMINGS_CENSUS, **kw) + + +def test_the_record_census_renders_one_detail_line_under_each_timing_row(): + board = dashboard.build_board(_record_snapshot(), make_verdict(), now=FRESH_NOW) + assert _section(board, "ci_timing").details[-1] == ( + "record: timings/gates.jsonl — 42 days") + assert _section(board, "smoke_timings").details[-1] == ( + "record: timings/scripts/ — 96 observations across 3 repos") + + +def test_a_snapshot_without_the_census_renders_exactly_as_it_always_did(): + """Older snapshots (and a dev box that never appends) must be byte-identical + — the census adds a line, it never changes a row.""" + v = make_verdict() + without = _scripts_snapshot() + assert "timings_record" not in without + for fmt in ("term", "md", "html", "json"): + out = dashboard.render(without, v, fmt=fmt, now=FRESH_NOW) + assert "timings/gates.jsonl" not in out + assert "timings/scripts/" not in out + board = dashboard.build_board(without, v, now=FRESH_NOW) + assert not any(d.startswith("record:") for d in _section(board, "ci_timing").details) + assert not any(d.startswith("record:") + for d in _section(board, "smoke_timings").details) + # An empty census is "no record", not "a record of nothing". + empty = _scripts_snapshot() + empty["timings_record"] = {} + assert (dashboard.render(empty, v, fmt="md", now=FRESH_NOW) + == dashboard.render(without, v, fmt="md", now=FRESH_NOW)) + + +def test_the_census_never_touches_the_performance_block(): + """`performance` is the contract the Brain board and the next render's + fallback consume verbatim — the census is a render-side detail only.""" + v = make_verdict() + with_census = json.loads(dashboard.render(_record_snapshot(), v, fmt="json", + now=FRESH_NOW)) + without = json.loads(dashboard.render(_scripts_snapshot(), v, fmt="json", + now=FRESH_NOW)) + assert with_census["performance"] == without["performance"] + assert "timings_record" not in with_census["performance"] diff --git a/tests/test_heart_health_wiring.py b/tests/test_heart_health_wiring.py index 98790016..60c6b791 100644 --- a/tests/test_heart_health_wiring.py +++ b/tests/test_heart_health_wiring.py @@ -63,3 +63,52 @@ def test_the_snapshot_folds_in_the_smoke_timings_rollup(): 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 + + +# --- the permanent timing record is appended and committed ------------------- + +def _step_index(job, needle): + for i, step in enumerate(job["steps"]): + if needle in step.get("name", ""): + return i + raise AssertionError(f"no step named like {needle!r} in heart-health.yml") + + +def test_the_record_append_sits_between_the_checks_and_the_aggregate(): + """Ordering is the whole safety argument: the checks' aggregate passes have + already read the record for their baselines (and neither can be fooled by + today's own line), so appending here is safe — and it lets the render + census a record that already includes today.""" + _, job = _job() + checks = _step_index(job, "Run cloud-safe checks") + append = _step_index(job, "Append today's observations to the timing record") + aggregate = _step_index(job, "Aggregate snapshot + compute readiness verdict") + assert checks < append < aggregate + body = job["steps"][append]["run"] + assert "python -m heart.timings append" in body + assert '--ci-timing "$HEART_STATE_DIR/ci_timing.json"' in body + assert '--smoke-timings "$HEART_STATE_DIR/smoke_timings.json"' in body + + +def test_the_commit_step_carries_the_record_beside_the_readme_block(): + """A record nothing commits is a tempfile, not a record.""" + _, job = _job() + step = job["steps"][_step_index(job, "timing record (own repo only")] + body = step["run"] + assert "git add README.md timings/" in body + assert 'git status --porcelain README.md timings/' in body + assert "docs(heart): daily board block + timing record [skip ci]" in body + + +def test_the_two_checks_read_the_record_before_the_previous_board(): + """The published board is the fallback; the committed record is the source + of truth — a Pages gap must not lose the history any more.""" + for script in ("ci_timing.sh", "smoke_timings.sh"): + body = (CHECKS / script).read_text() + assert '--record-dir "$HEART_HOME/timings"' in body + + +def test_the_snapshot_folds_in_the_record_census(): + state_py = (Path(__file__).resolve().parent.parent / "heart" / "state.py").read_text() + assert '"timings_record": _read_json_or_default(' in state_py + assert '"timings_record.json"' in state_py diff --git a/tests/test_smoke_timings.py b/tests/test_smoke_timings.py index f0dabd6c..c5191b85 100644 --- a/tests/test_smoke_timings.py +++ b/tests/test_smoke_timings.py @@ -477,3 +477,89 @@ def test_summary_lines_are_honest_about_unavailability(monkeypatch): 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) + + +# --- the committed record is the previous observation; the board is fallback -- +# +# The published board.json is the same artifact this render produces, so a Pages +# gap loses it. `timings/scripts/.jsonl` is the durable copy (see +# heart/timings.py) and it wins whenever it has anything. + +def _record_rows(seconds, run_id=6): + return {(REPO, "3.12", "imaging/x.py"): { + "seconds": seconds, "run_id": run_id, "run_url": PREV_RUN_URL, + "status": "passed", "cap_s": 600.0, + }} + + +def test_aggregate_prefers_the_committed_record_over_the_previous_board(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], + # The board would say the script always took 30s — no drift. + _prev_board([_prev_row(30.0)]), "T", + {"slow_factor": 2.0, "min_delta_s": 5, "top_n": 5}, + # The record says it took 10s last run — the drift is real. + record_prev_rows=_record_rows(10.0), + ) + (row,) = roll["rows"] + assert row["state"] == "warn" and row["prev_s"] == 10.0 and row["ratio"] == 3.0 + + +def test_aggregate_falls_back_to_the_previous_board_when_the_record_is_empty(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") + for record in (None, {}): + roll = smt.aggregate([side], _prev_board([_prev_row(10.0)]), "T", + {"slow_factor": 2.0, "min_delta_s": 5, "top_n": 5}, + record_prev_rows=record) + (row,) = roll["rows"] + assert row["state"] == "warn" and row["prev_s"] == 10.0 + + +def test_the_repo_rows_carry_the_provenance_the_record_stores(tmp_path): + """head_sha + env_profile: which commit was measured, under which profile. + The sidecar leg has held both since phase 1; the rollup now passes them on + so `timings/scripts/.jsonl` can record them.""" + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/x.py", seconds=12.0)]), "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + assert side["legs"][0]["head_sha"] == "abc123" + assert side["legs"][0]["env_profile"] == "smoke" + (repo_row,) = smt.aggregate([side], {}, "T", + smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS)["repos"] + assert repo_row["head_sha"] == "abc123" + assert repo_row["env_profile"] == "smoke" + assert repo_row["head_branch"] == "feat/x" + + +def test_main_aggregate_reads_the_record_directory(tmp_path, monkeypatch, capsys): + import json as _json + + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + legs = [{"artifact": _selected(), "dir": _extracted(tmp_path, [ + _entry("imaging/x.py", seconds=30.0)]), "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + (per_repo / f"{REPO}.smoke_timings.json").write_text(_json.dumps(side)) + + scripts = tmp_path / "timings" / "scripts" + scripts.mkdir(parents=True) + (scripts / f"{REPO}.jsonl").write_text(_json.dumps({ + "date": "2026-09-04", "at": "", "python": "3.12", "run_id": 6, + "run_url": PREV_RUN_URL, "head_branch": "", "head_sha": "", + "env_profile": "smoke", "entries": {"imaging/x.py": [10.0, "passed", 600.0]}, + }) + "\n") + + out = tmp_path / "smoke_timings.json" + assert smt.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--record-dir", str(tmp_path / "timings"), + "--out", str(out)]) == 0 + (row,) = _json.loads(out.read_text())["rows"] + assert row["state"] == "warn" and row["prev_s"] == 10.0 and row["prev_run_id"] == 6 + capsys.readouterr() diff --git a/tests/test_timings.py b/tests/test_timings.py new file mode 100644 index 00000000..bb7f63ce --- /dev/null +++ b/tests/test_timings.py @@ -0,0 +1,339 @@ +"""tests/test_timings.py — the permanent, committed CI timing record. + +The record is the *durable* copy of what the two timing checks measure: the +published board.json is the same artifact the render produces, so a Pages gap +loses it, and nothing can recompute it afterwards. These tests pin the two +things that make it worth committing — it is append-only (a line is never +rewritten by a later run) and it dedupes on IDENTITY, never on the day, so a +quiet week cannot write seven copies of one run — plus the two read views the +checks consume. + +Fake repo/workflow/entry names throughout (the tenant firewall): the real ones +live in config/repos.yaml, which is the declared surface, never in test data. +""" + +from __future__ import annotations + +import json + +from heart import timings +from heart.checks import ci_timing, smoke_timings + +TS = "2026-09-05T05:03:00+00:00" +TODAY = "2026-09-05" +RUN_URL = "https://ci.invalid/OwnerX/RepoA/actions/runs/7" +GATE_URL = "https://ci.invalid/RepoA/actions" + + +def _ci_rollup(**kw): + """A ci_timing.json rollup: two gates, one of them unmeasured.""" + return { + "ts": TS, + "gates": [ + {"repo": "RepoA", "workflow": "Gate One", "median_s": 600.0, + "pr_median_s": 660.0, "queue_median_s": 12.0, "max_s": 900.0, + "runs_counted": 14, "state": "ok", "actions_url": GATE_URL}, + {"repo": "RepoB", "workflow": "Gate Two", "median_s": 45.0, + "pr_median_s": None, "queue_median_s": None, "max_s": 60.0, + "runs_counted": 4, "state": "ok", "actions_url": ""}, + # No completed runs in the window: measured nothing, recorded as + # nothing rather than as a row of nulls. + {"repo": "RepoC", "workflow": "Gate Three", "median_s": None, + "pr_median_s": None, "queue_median_s": None, "max_s": None, + "runs_counted": 0, "state": "ok", "actions_url": ""}, + ], + "history": [], + "events": [], + "errors": [], + **kw, + } + + +def _smoke_rollup(run_id=7, seconds=12.5): + """A smoke_timings.json rollup: one repo, one python leg, two entries.""" + return { + "ts": TS, + "repos": [ + {"repo": "RepoA", "python": "3.12", "run_id": run_id, + "run_url": RUN_URL, "head_branch": "feat/x", "head_sha": "abc123", + "env_profile": "smoke", "at": "2026-09-04T10:00:00Z", + "entries": 3, "timed": 2, "total_s": seconds + 4.0, "error": "", + "slowest": []}, + ], + "rows": [ + {"repo": "RepoA", "python": "3.12", "entry": "imaging/x.py", + "kind": "script", "status": "passed", "seconds": seconds, + "cap_s": 600.0, "exit_code": 0, "run_id": run_id, + "run_url": RUN_URL, "state": "ok"}, + {"repo": "RepoA", "python": "3.12", "entry": "imaging/y.py", + "kind": "script", "status": "passed", "seconds": 4.0, + "cap_s": 600.0, "exit_code": 0, "run_id": run_id, + "run_url": RUN_URL, "state": "ok"}, + ], + "slowed": [], + "events": [], + "errors": [], + "thresholds": {}, + } + + +# --- gates ------------------------------------------------------------------- +def test_gates_line_records_only_the_gates_that_measured_something(): + line = timings.gates_line_from_rollup(_ci_rollup(), TODAY, TS) + assert line["date"] == TODAY and line["ts"] == TS + assert set(line["gates"]) == {"RepoA/Gate One", "RepoB/Gate Two"} + assert line["gates"]["RepoA/Gate One"] == { + "p50_s": 600.0, "pr_median_s": 660.0, "max_s": 900.0, + "queue_median_s": 12.0, "runs": 14, + } + + +def test_a_rollup_with_no_measured_gate_yields_no_line(): + """An empty line is worse than no line — it would read as a quiet day.""" + assert timings.gates_line_from_rollup({"gates": []}, TODAY, TS) is None + assert timings.gates_line_from_rollup("not a rollup", TODAY, TS) is None + + +def test_the_gates_record_is_keyed_by_date(tmp_path): + path = tmp_path / "gates.jsonl" + line = timings.gates_line_from_rollup(_ci_rollup(), TODAY, TS) + assert timings.append_gates(path, line) is True + # Re-running the daily job on the same date is a no-op, not a second point + # for that day in every gate's sparkline. + assert timings.append_gates(path, line) is False + later = timings.gates_line_from_rollup(_ci_rollup(), "2026-09-06", TS) + assert timings.append_gates(path, later) is True + records, skipped = timings.read_jsonl(path) + assert [r["date"] for r in records] == [TODAY, "2026-09-06"] + assert skipped == 0 + + +def test_appending_never_rewrites_the_existing_bytes(tmp_path): + path = tmp_path / "gates.jsonl" + timings.append_gates(path, timings.gates_line_from_rollup(_ci_rollup(), TODAY, TS)) + before = path.read_bytes() + timings.append_gates(path, timings.gates_line_from_rollup(_ci_rollup(), "2026-09-06", TS)) + after = path.read_bytes() + assert after.startswith(before) # append-only, byte for byte + assert len(after) > len(before) + + +def test_every_record_is_one_newline_terminated_line_with_sorted_keys(tmp_path): + path = tmp_path / "gates.jsonl" + timings.append_gates(path, timings.gates_line_from_rollup(_ci_rollup(), TODAY, TS)) + text = path.read_text() + assert text.endswith("\n") + assert text.count("\n") == 1 + keys = list(json.loads(text).keys()) + assert keys == sorted(keys) + + +def test_a_missing_file_is_an_empty_record(tmp_path): + assert timings.read_jsonl(tmp_path / "nope.jsonl") == ([], 0) + assert timings.gates_history(tmp_path / "nope.jsonl", 30) == [] + assert timings.previous_script_rows(tmp_path / "nope") == {} + + +def test_an_unparseable_line_is_skipped_and_counted(tmp_path): + """A hole in the record is a finding, not something to hide.""" + path = tmp_path / "gates.jsonl" + path.write_text( + '{"date": "2026-09-04", "gates": {}}\n' + "{not json at all\n" + "\n" + "[1, 2, 3]\n" + '{"date": "2026-09-05", "gates": {}}\n' + ) + records, skipped = timings.read_jsonl(path) + assert [r["date"] for r in records] == ["2026-09-04", "2026-09-05"] + assert skipped == 2 + assert timings.census(tmp_path)["unparseable"] == 2 + + +# --- the read views the checks consume --------------------------------------- +def test_gates_history_is_exactly_what_the_baseline_and_the_spark_read(tmp_path): + from heart import dashboard + + path = tmp_path / "gates.jsonl" + for date, p50 in (("2026-09-02", 500.0), ("2026-09-03", 600.0), + ("2026-09-04", 700.0), (TODAY, 1800.0)): + timings.append_gates(path, { + "date": date, "ts": TS, + "gates": {"RepoA/Gate One": {"p50_s": p50, "pr_median_s": None, + "max_s": None, "queue_median_s": None, + "runs": 10}}, + }) + history = timings.gates_history(path, 30) + assert [h["date"] for h in history] == ["2026-09-02", "2026-09-03", + "2026-09-04", TODAY] + # The view is the p50 + coverage only; the extra recorded figures are + # dropped so board.json's performance.history keeps its shape. + assert history[0]["gates"]["RepoA/Gate One"] == {"p50_s": 500.0, "runs": 10} + # Today is excluded from its own baseline, so the median is of 500/600/700. + assert ci_timing.history_baseline(history, "RepoA/Gate One", TODAY) == 600.0 + assert dashboard._gate_spark(history, "RepoA/Gate One") == "▁▁▂█" + # `cap` keeps the last N, oldest first. + assert [h["date"] for h in timings.gates_history(path, 2)] == ["2026-09-04", TODAY] + + +def test_scripts_lines_are_one_per_repo_python_and_run(tmp_path): + lines = timings.scripts_lines_from_rollup(_smoke_rollup(), TODAY) + assert list(lines) == ["RepoA"] + (line,) = lines["RepoA"] + assert line["date"] == TODAY + assert line["python"] == "3.12" and line["run_id"] == 7 + assert line["run_url"] == RUN_URL and line["head_branch"] == "feat/x" + assert line["head_sha"] == "abc123" and line["env_profile"] == "smoke" + assert line["at"] == "2026-09-04T10:00:00Z" + # Entries sorted by path, each the positional [seconds, status, cap_s]. + assert list(line["entries"]) == ["imaging/x.py", "imaging/y.py"] + assert line["entries"]["imaging/x.py"] == [12.5, "passed", 600.0] + + +def test_a_leg_with_no_run_id_has_no_identity_and_is_not_recorded(): + rollup = _smoke_rollup() + rollup["repos"][0]["run_id"] = None + assert timings.scripts_lines_from_rollup(rollup, TODAY) == {} + + +def test_the_scripts_record_is_keyed_by_leg_and_run_never_by_the_day(tmp_path): + """A quiet week hands the job the SAME run seven times; keying on the day + would write seven copies of one measurement.""" + path = timings.scripts_file("RepoA", tmp_path) + lines = timings.scripts_lines_from_rollup(_smoke_rollup(), TODAY)["RepoA"] + assert timings.append_scripts(path, lines) == 1 + # Same run, a later day: nothing new was measured, so nothing is recorded. + again = timings.scripts_lines_from_rollup(_smoke_rollup(), "2026-09-06")["RepoA"] + assert timings.append_scripts(path, again) == 0 + # A NEW run of the same leg is a new measurement and does land. + fresh = timings.scripts_lines_from_rollup( + _smoke_rollup(run_id=8, seconds=40.0), "2026-09-06")["RepoA"] + assert timings.append_scripts(path, fresh) == 1 + records, _ = timings.read_jsonl(path) + assert [(r["run_id"], r["date"]) for r in records] == [(7, TODAY), (8, "2026-09-06")] + + +def test_previous_script_rows_takes_the_latest_line_per_leg_and_drives_drift(tmp_path): + scripts_dir = tmp_path / "scripts" + path = timings.scripts_file("RepoA", tmp_path) + for run_id, seconds in ((7, 12.5), (8, 40.0)): + timings.append_scripts(path, timings.scripts_lines_from_rollup( + _smoke_rollup(run_id=run_id, seconds=seconds), TODAY)["RepoA"]) + # A second python leg, so "latest per leg" is not "latest in the file". + other = timings.scripts_lines_from_rollup(_smoke_rollup(run_id=9, seconds=5.0), TODAY) + other["RepoA"][0]["python"] = "3.11" + timings.append_scripts(path, other["RepoA"]) + + prev = timings.previous_script_rows(scripts_dir) + assert prev[("RepoA", "3.12", "imaging/x.py")] == { + "seconds": 40.0, "run_id": 8, "run_url": RUN_URL, + "status": "passed", "cap_s": 600.0, + } + assert prev[("RepoA", "3.11", "imaging/x.py")]["seconds"] == 5.0 + + thr = {"slow_factor": 2.0, "min_delta_s": 5} + row = prev[("RepoA", "3.12", "imaging/x.py")] + assert smoke_timings.classify_drift(120.0, row, thr, run_id=9)[0] == "warn" + assert smoke_timings.classify_drift(41.0, row, thr, run_id=9)[0] == "ok" + # ...and a row from the SAME run is never compared against itself. + assert smoke_timings.classify_drift(120.0, row, thr, run_id=8) == ("ok", None, None) + + +def test_the_census_counts_days_observations_and_repos(tmp_path): + assert timings.census(tmp_path) == dict(timings.EMPTY_CENSUS) + timings.append_gates(tmp_path / "gates.jsonl", + timings.gates_line_from_rollup(_ci_rollup(), "2026-09-04", TS)) + timings.append_gates(tmp_path / "gates.jsonl", + timings.gates_line_from_rollup(_ci_rollup(), TODAY, TS)) + for repo in ("RepoA", "RepoB"): + lines = timings.scripts_lines_from_rollup(_smoke_rollup(), TODAY)["RepoA"] + for line in lines: + line["repo"] = repo + timings.append_scripts(timings.scripts_file(repo, tmp_path), lines) + assert timings.census(tmp_path) == { + "gates_days": 2, "gates_first": "2026-09-04", "gates_last": TODAY, + "scripts_observations": 2, "repos": 2, "unparseable": 0, + } + + +# --- the CLI ----------------------------------------------------------------- +def _write_rollups(tmp_path, *, run_id=7): + ci = tmp_path / "ci_timing.json" + smoke = tmp_path / "smoke_timings.json" + ci.write_text(json.dumps(_ci_rollup())) + smoke.write_text(json.dumps(_smoke_rollup(run_id=run_id))) + return ci, smoke + + +def test_main_append_writes_both_files_the_census_and_one_summary_line(tmp_path, capsys): + ci, smoke = _write_rollups(tmp_path) + record = tmp_path / "timings" + census_out = tmp_path / "timings_record.json" + argv = ["append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--today", TODAY, "--ts", TS, "--dir", str(record), + "--census-out", str(census_out)] + + assert timings.main(argv) == 0 + out = capsys.readouterr().out.strip() + assert out == ("timings: gates +1 line, scripts +1 lines across 1 repos, " + "0 skipped (already recorded)") + assert (record / "gates.jsonl").is_file() + assert timings.scripts_file("RepoA", record).is_file() + + census = json.loads(census_out.read_text()) + assert census["gates_days"] == 1 and census["scripts_observations"] == 1 + assert census["gates_first"] == TODAY and census["repos"] == 1 + assert census["appended_today"] == {"gates": True, "scripts": {"RepoA": 1}} + + # A second run over the SAME inputs appends nothing at all. + assert timings.main(argv) == 0 + out = capsys.readouterr().out.strip() + assert out == ("timings: gates +0 line, scripts +0 lines across 0 repos, " + "2 skipped (already recorded)") + assert len((record / "gates.jsonl").read_text().splitlines()) == 1 + assert len(timings.scripts_file("RepoA", record).read_text().splitlines()) == 1 + assert json.loads(census_out.read_text())["appended_today"] == { + "gates": False, "scripts": {}, + } + + +def test_main_append_survives_a_missing_rollup(tmp_path, capsys): + """A slice that produced no file means nothing to append from it — never an + error, and never a lost append from the OTHER slice.""" + _, smoke = _write_rollups(tmp_path) + record = tmp_path / "timings" + assert timings.main([ + "append", "--ci-timing", str(tmp_path / "gone.json"), + "--smoke-timings", str(smoke), "--today", TODAY, "--dir", str(record), + "--census-out", str(tmp_path / "census.json"), + ]) == 0 + assert "gates +0 line" in capsys.readouterr().out + assert not (record / "gates.jsonl").exists() + assert timings.scripts_file("RepoA", record).is_file() + + +def test_main_show_prints_the_census_one_key_per_line(tmp_path, capsys): + ci, smoke = _write_rollups(tmp_path) + record = tmp_path / "timings" + timings.main(["append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--today", TODAY, "--dir", str(record), + "--census-out", str(tmp_path / "census.json")]) + capsys.readouterr() + assert timings.main(["show", "--dir", str(record)]) == 0 + lines = capsys.readouterr().out.strip().splitlines() + assert lines[0] == "gates_days: 1" + assert "scripts_observations: 1" in lines + assert {ln.split(":")[0] for ln in lines} == set(timings.EMPTY_CENSUS) + + +def test_the_epoch_file_is_reserved_and_never_written(tmp_path): + """`epochs.jsonl` is a human's judgement about the world, not an + observation — the path is named so the reservation lives in the code.""" + assert timings.EPOCHS_FILE.name == "epochs.jsonl" + ci, smoke = _write_rollups(tmp_path) + record = tmp_path / "timings" + timings.main(["append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--today", TODAY, "--dir", str(record), + "--census-out", str(tmp_path / "census.json")]) + assert not (record / "epochs.jsonl").exists() + assert not timings.EPOCHS_FILE.exists() diff --git a/timings/README.md b/timings/README.md new file mode 100644 index 00000000..cba2d225 --- /dev/null +++ b/timings/README.md @@ -0,0 +1,144 @@ +# `timings/` — the permanent CI timing record + +This directory is PyAutoHeart's **append-only record of how long CI takes**. It +is written by exactly one thing — the daily `heart-health.yml` cloud job, which +commits it beside the README board block, one commit a day — and read by the +two timing checks as the first source for their baselines. + +It exists because the alternative did not last. `ci_timing` and `smoke_timings` +both carried their history in the `board.json` published to Pages by the +previous run: free, idempotent, and *the same artifact the render produces*. A +publish gap, a rewritten board or a schema change and the history is gone, and +nothing can recompute it — the Actions REST window is a couple of weeks and a +smoke-timings artifact expires in days. The board stays as the fallback; this +is the copy that lasts. + +The code is [`heart/timings.py`](../heart/timings.py); its module docstring +carries the same rules for a reader who arrives from the Python side. + +## The files + +``` +timings/README.md # this file — doctrine, not data +timings/gates.jsonl # one line per UTC date +timings/scripts/.jsonl # one line per (python leg, run id) +``` + +`gates.jsonl` and `timings/scripts/` are created by the first run that has +something to record; an empty file is not a record, so they are not committed +ahead of the data. + +### `gates.jsonl` — one line per date + +One JSON object per line, from `ci_timing.json`'s `gates`: + +```json +{"date":"2026-09-05","ts":"2026-09-05T05:03:00+00:00", + "gates":{"RepoA/Gate One":{"p50_s":553.0,"pr_median_s":601.0,"max_s":912.0, + "queue_median_s":12.0,"runs":14}}} +``` + +* The key is `/`, exactly the gate key the board uses. +* `p50_s` is the gate's `median_s` — the median over **success** runs — and + `runs` is `runs_counted`, the coverage behind it. Coverage travels beside + time, always: a gate that got faster by running less must not read as a gate + that got faster. +* Only gates whose `median_s` is a number are recorded. A gate with no + completed runs in the window measured nothing, and a row of nulls would make + the record look like it has coverage it does not have. + +### `scripts/.jsonl` — one line per leg per run + +One JSON object per line, from `smoke_timings.json`'s `repos` (the provenance) +joined to its `rows` (the timed entries): + +```json +{"date":"2026-09-05","at":"2026-09-04T10:00:00Z","python":"3.12","run_id":7, + "run_url":"https://ci.invalid/OwnerX/RepoA/actions/runs/7", + "head_branch":"feat/x","head_sha":"abc123","env_profile":"smoke", + "entries":{"imaging/x.py":[12.5,"passed",600.0]}} +``` + +* `entries` maps the entry path to the triple `[seconds, status, cap_s]`. + Positional on purpose: this file grows by one line per leg per run forever, + and repeating three key names on every entry would multiply it for nothing a + reader cannot get from this schema. Entries are sorted by path. +* **Untimed entries are not in the record.** The rollup's `rows` carries the + timed entries only; an entry the runner skipped has `seconds: null` and was + never a measurement. The per-leg census on the board (`repos[].entries` vs + `timed`) is where coverage stays visible — a `null` here would be a + fabricated zero-second row in a dataset whose whole purpose is timing. +* `head_sha` and `env_profile` are `""` when the rollup that produced the line + predates them, so every line in a file carries the same keys either way. + +## The two rules + +### 1. Append-only + +Lines are only ever **added**. A wrong line is superseded by a later one; it is +never edited and never deleted, and this directory is never hand-edited at all. +The record is evidence, and evidence that can be quietly rewritten is not +evidence. Every writer in `heart/timings.py` opens for append; none of them +truncates. + +### 2. Dedupe on identity, never on the day + +* `gates.jsonl` is keyed by **`date`** — appending is skipped when that date is + already present. Re-running the daily job is then a no-op rather than a + second point for the same day in every gate's sparkline. +* `scripts/.jsonl` is keyed by **`(python, run_id)`** — appending is + skipped when that leg of that run is already recorded. + +The second key is the load-bearing one. The smoke artifacts only change when a +PR runs, so a quiet week hands the daily job the *same run* seven days running. +Keyed on the day, that writes seven copies of one measurement — the +`script_timing` "one value repeated seven times" defect, recorded once and not +to be re-derived — and a flat week reads as a week of measurements. Keyed on +the run, a quiet week records nothing, which is the truth. + +## Reserved: `epochs.jsonl` + +`timings/epochs.jsonl` is **reserved** for a future labelled epoch boundary: + +```json +{"date":"2026-09-05","label":"runners moved to 8 cores","note":"..."} +``` + +A reader could then tell a step change in the world from a regression in the +code. Nothing writes it, and the file deliberately does not exist yet — +`heart/timings.py` names the path (`EPOCHS_FILE`) so the reservation lives in +the code as well as here. An epoch is a human's judgement about the world, not +something a daily job can observe. + +## Growth + +* `gates.jsonl`: ~1 line/day. A line is a few hundred bytes per tracked gate; + a year is a few hundred lines. +* `scripts/.jsonl`: **at most** one line per python leg per day, and in + practice far fewer — a line lands only when a new run produced a new + artifact. Two legs per repo is the current shape, so ≤ 2 lines/day/repo, and + a quiet repo contributes nothing at all. + +Yearly sharding (`gates-2026.jsonl`, `scripts/2026/.jsonl`) is the +obvious next step if a file ever gets unwieldy. **Not now**: at this growth +rate the whole record is comfortably under a megabyte for years, and sharding +early would buy a path-resolution rule and a reader that has to glob, in +exchange for nothing. + +## Reading it + +```bash +# The one-screen answer: days recorded, observations, repos, holes. +PYTHONPATH="$PWD" python -m heart.timings show + +# One gate's daily p50s. +jq -r '.date + " " + (.gates["RepoA/Gate One"].p50_s|tostring)' timings/gates.jsonl + +# One script's seconds across the recorded runs of a repo. +jq -r '[.run_id, .python, .entries["imaging/x.py"][0]] | @tsv' \ + timings/scripts/RepoA.jsonl +``` + +The daily job also writes the census to `$HEART_STATE_DIR/timings_record.json`, +which `state.aggregate()` folds into the snapshot as `timings_record` and the +board renders as one detail line under each of the two ⏱ timing rows.