From 40b902798137c187c1995a46faf863cb69fb9ff9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 22:27:18 +0000 Subject: [PATCH] feat(unit_timings): unit-test durations + import time live by CI ingestion (#206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lib-tests.yml — the reusable workflow every library's Tests gate calls — now emits a unit-timings- artifact (pytest --junitxml per-test durations plus a fresh-process import time), and the daily heart-health run ingests it with a new unit_timings check: the N slowest tests and the suite wall-clock per leg, import seconds per package, run-to-run drift against the committed timings/ record (both-gates for tests; the import_time median-window doctrine for imports), recorded as timings/unit/.jsonl. The existing Unit-test timing and Import timing board sections come alive from the same summaries the dev-box checks write, and workspace_testmode_timing is retired from the board as superseded by the per-script smoke timings. 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 | 61 +- .github/workflows/lib-tests.yml | 90 +- config/repos.yaml | 13 + heart/checks/import_time.py | 14 +- heart/checks/smoke_timings.py | 12 +- heart/checks/unit_test_timing.py | 13 +- heart/checks/unit_timings.py | 982 ++++++++++++++++++++++ heart/checks/unit_timings.sh | 136 +++ heart/checks/workspace_testmode_timing.py | 11 +- heart/dashboard.py | 121 ++- heart/state.py | 5 + heart/timings.py | 257 +++++- tests/test_dashboard.py | 143 ++++ tests/test_heart_health_wiring.py | 30 + tests/test_lib_tests_wiring.py | 110 +++ tests/test_timings.py | 174 +++- tests/test_unit_timings.py | 692 +++++++++++++++ tests/test_unit_timings_script.py | 132 +++ timings/README.md | 56 +- 19 files changed, 2981 insertions(+), 71 deletions(-) create mode 100644 heart/checks/unit_timings.py create mode 100755 heart/checks/unit_timings.sh create mode 100644 tests/test_lib_tests_wiring.py create mode 100644 tests/test_unit_timings.py create mode 100644 tests/test_unit_timings_script.py diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index f35d7132..25aca56c 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 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: +# It runs the six checks that need only the GitHub API (no local working tree) — +# CI status, open PRs, CI wall-clock timing, the NO_RUN census, the per-script +# smoke timings and the per-test unit 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 @@ -14,10 +14,12 @@ name: Heart Health # * 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. +# record (timings/gates.jsonl + timings/scripts/.jsonl + +# timings/unit/.jsonl). This job is the record's single writer; the +# 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 — and for unit_timings the record is the ONLY baseline, +# since the board never carried per-test rows. # 2. opens-or-updates a single "[heart-health]" tracking ISSUE when anything # is red/degraded and closes it when clean — the ALERTING channel (kept). # @@ -42,9 +44,10 @@ 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. +# actions: read → list and download workflow artifacts (smoke_timings, +# unit_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 @@ -90,33 +93,37 @@ jobs: - name: Install PyYAML run: pip install --quiet pyyaml - - name: Run cloud-safe checks (ci_status, open_prs, ci_timing, no_run_census, smoke_timings) + - name: Run cloud-safe checks (ci_status, open_prs, ci_timing, no_run_census, smoke_timings, unit_timings) env: # The repo-scoped GITHUB_TOKEN is enough for every check here except - # the artifact /zip downloads smoke_timings makes against OTHER repos: + # the artifact /zip downloads smoke_timings and unit_timings make + # against OTHER repos (workspaces and libraries respectively): # 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. + # fine-grained PAT (Actions: read on the workspace AND library 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: | - # 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. + # Six API-only checks: CI conclusions and open PRs (health), then CI + # wall-clock, the NO_RUN census, the per-script smoke timings and the + # per-test unit 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. unit_timings reads only the committed record — + # the board never carried per-test rows. `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 + bash heart/checks/unit_timings.sh exit 0 - name: Append today's observations to the timing record @@ -124,9 +131,10 @@ jobs: # 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. + # excludes today's date, and smoke_timings and unit_timings compare by + # run id and refuse 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 @@ -137,7 +145,8 @@ jobs: # 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" + --smoke-timings "$HEART_STATE_DIR/smoke_timings.json" \ + --unit-timings "$HEART_STATE_DIR/unit_timings.json" - name: Aggregate snapshot + compute readiness verdict run: | diff --git a/.github/workflows/lib-tests.yml b/.github/workflows/lib-tests.yml index a55c09fe..f3709938 100644 --- a/.github/workflows/lib-tests.yml +++ b/.github/workflows/lib-tests.yml @@ -17,6 +17,11 @@ name: Library Tests (reusable) # triggers it. Dependency-aware (conf→none, fit/array→conf, galaxy→conf+fit+array, # lens→all) so lightweight libs don't install the heavy stack. GitHub-hosted + # pip caching. +# +# The `unittest` job also publishes a `unit-timings-` artifact — pytest's +# junit XML (every test's duration) plus a fresh-process import time — which is +# the standing dataset the Heart's `unit_timings` check ingests daily into the +# board's Unit-test timing and Import timing rows (PyAutoHeart#206). on: workflow_call: @@ -94,6 +99,63 @@ jobs: pip install "./$r[${{ steps.map.outputs.extras }}]" done + # The cold import cost the developer loop actually pays: a FRESH process + # importing the package once, not the warm in-process cost a test session + # amortises over hundreds of tests. Measured here rather than inferred + # from the suite's wall-clock, which is dominated by the tests. + # + # `seconds: null` when the import failed or timed out — never a + # fabricated 0, which in a timing dataset would read as an instant import + # rather than as no measurement at all. The returncode travels with it so + # the ingest can say WHY there is no number. + # + # continue-on-error: this is a dataset, not a gate. A package that cannot + # be imported will fail the suite two steps down on its own merits; it + # must never be this step that reds six libraries' required check. + - name: Time a fresh-process import (unit-timings dataset) + continue-on-error: true + working-directory: ${{ steps.map.outputs.repo }} + env: + # The package name reaches Python through the ENVIRONMENT, never + # interpolated into the source: a `${{ }}` expansion inside the + # heredoc would be substituted before python ever parsed the line. + PKG: ${{ inputs.package }} + run: | + python - <<'PY' + import datetime, json, os, pathlib, subprocess, sys, time + + pkg = os.environ["PKG"] + seconds = None + returncode = None + start = time.perf_counter() + try: + proc = subprocess.run( + [sys.executable, "-c", f"import {pkg}"], + capture_output=True, timeout=600, + ) + except subprocess.TimeoutExpired: + # No number, and no returncode either: the process never finished. + pass + else: + returncode = proc.returncode + if proc.returncode == 0: + seconds = round(time.perf_counter() - start, 3) + else: + sys.stderr.write(proc.stderr.decode("utf-8", "replace")[-2000:]) + + out = pathlib.Path("test-results") + out.mkdir(parents=True, exist_ok=True) + (out / "import_time.json").write_text(json.dumps({ + "schema": "import_time/1", + "package": pkg, + "python": "%d.%d" % sys.version_info[:2], + "seconds": seconds, + "returncode": returncode, + "ts": datetime.datetime.now(datetime.timezone.utc).isoformat(), + }, sort_keys=True) + "\n") + print(f"import {pkg}: {seconds}s (returncode {returncode})") + PY + - name: Run tests run: | export JAX_ENABLE_X64=True @@ -102,7 +164,33 @@ jobs: export PYTHONPATH="$PYTHONPATH:$ROOT/$r" done pushd "${{ steps.map.outputs.repo }}" - pytest --cov ${{ inputs.package }} --cov-report xml:coverage.xml + # --junitxml is pytest's BUILT-IN machine-readable per-test record: + # one per test with `time` = setup+call+teardown. That is + # why not `--durations`, which is a console tail of the slowest N that + # has to be scraped out of a log that expires with the run. + pytest --cov ${{ inputs.package }} --cov-report xml:coverage.xml \ + --junitxml=test-results/junit.xml + + # The standing dataset the Heart's `unit_timings` check ingests: per-test + # durations from the junit XML plus the fresh-process import time above. + # In the job log that data evaporates with the log retention and is only + # recovered by hand-scraping; as an artifact it becomes a record the board + # can compare run to run, across every library at once. + # + # if: always() + if-no-files-found: ignore are both load-bearing, exactly + # as in smoke-tests.yml. A red suite still wrote its junit XML and those + # timings are worth keeping; a leg that died before the first write (a + # failed install) leaves no test-results/ at all, and an upload that + # failed closed would turn "we collected no timings" into "the PR is red", + # which is backwards. No retention-days: the dataset is the point, so it + # keeps the repo's full default artifact retention. + - name: Upload the unit timings (per-test durations + import time) + if: always() + uses: actions/upload-artifact@v4 + with: + name: unit-timings-${{ matrix.python-version }} + path: ${{ steps.map.outputs.repo }}/test-results/ + if-no-files-found: ignore - name: Upload coverage to Codecov if: always() diff --git a/config/repos.yaml b/config/repos.yaml index a0195c65..fe5514d8 100644 --- a/config/repos.yaml +++ b/config/repos.yaml @@ -264,6 +264,19 @@ thresholds: 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 + # Per-TEST and per-IMPORT drift from the libraries' own CI (heart/checks/unit_timings.py). + # Tests are 0.1-30 s, so the both-gates floor is 2 s. The import factors mirror + # the dev-box import_time doctrine so a ratio means the same thing from either + # vantage; the baseline is the median of the last `import_window` recorded runs + # and needs `import_min_samples` before it judges anything. Advisory. + unit_timings: + slow_factor: 2.0 + min_delta_s: 2 + top_n: 25 + import_yellow_factor: 1.5 + import_red_factor: 3.0 + import_window: 7 + import_min_samples: 3 worktree_drift: orphan_red: true # orphan WT with uncommitted work → red orphan_yellow: true # orphan WT (clean) → yellow diff --git a/heart/checks/import_time.py b/heart/checks/import_time.py index 6a5d89ce..71589de8 100644 --- a/heart/checks/import_time.py +++ b/heart/checks/import_time.py @@ -1,10 +1,16 @@ """heart/checks/import_time.py — measure PyAuto library import cost in a subprocess, track rolling per-package baselines, classify regressions. -OFF-TICK by design. Importing the science stack costs several seconds -(``import autolens`` ~3.6s warm, more cold), which does not fit the <30s -watch-loop tick budget (``docs/internals.md`` rule 3). Run this on a slower -cadence — a daily cron or on demand — and do **not** wire it into +Since #206 this surface is measured on the libraries' own CI (``lib-tests.yml`` +emits the ``unit-timings-`` artifact, whose ``import_time/1`` dataset is a +fresh-process import timed on the runner) and ingested daily by +``heart/checks/unit_timings.py``, which writes this same summary file; running +this module on a dev box remains an on-demand deep probe with the identical +output shape. + +Importing the science stack costs several seconds (``import autolens`` ~3.6s +warm, more cold), which does not fit the <30s watch-loop tick budget +(``docs/internals.md`` rule 3), so this module is never wired into ``heart/tick.sh``: python -m heart.checks.import_time diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 9e048f14..995b9b1f 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -188,7 +188,9 @@ def _as_int(value: Any) -> int | None: return int(num) if num is not None else None -def select_artifacts(listing: Any) -> list[dict[str, Any]]: +def select_artifacts( + listing: Any, pattern: re.Pattern[str] = ARTIFACT_RE +) -> list[dict[str, Any]]: """The newest non-expired ``smoke-timings-`` artifact per python leg. Accepts the REST ``{"artifacts": [...]}`` object the shell leg fetches and @@ -198,6 +200,12 @@ def select_artifacts(listing: Any) -> list[dict[str, Any]]: 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. + + ``pattern`` is the artifact-name rule, defaulting to this check's own. The + selection LOGIC — newest, non-expired, one per named leg, group 1 is the + python version — is identical for every per-leg timings artifact, so + ``unit_timings`` passes its own ``unit-timings-`` regex here rather than + growing a second copy of it that could drift. """ if isinstance(listing, dict): raw = listing.get("artifacts") or [] @@ -213,7 +221,7 @@ def select_artifacts(listing: Any) -> list[dict[str, Any]]: if not isinstance(art, dict): continue name = str(art.get("name") or "") - match = ARTIFACT_RE.match(name) + match = pattern.match(name) if not match: continue if art.get("expired"): diff --git a/heart/checks/unit_test_timing.py b/heart/checks/unit_test_timing.py index 15c7ecae..af6e949f 100644 --- a/heart/checks/unit_test_timing.py +++ b/heart/checks/unit_test_timing.py @@ -1,10 +1,15 @@ """heart/checks/unit_test_timing.py — track library unit-test durations, flag slow-test regressions. -OFF-TICK by design. Running the library suites costs minutes (test_autofit is -~1500 tests), which does not fit the <30s watch-loop budget (``docs/internals.md`` -rule 3). Run on a slower cadence — a daily/weekly cron or on demand — and do -**not** wire it into ``heart/tick.sh``: +Since #206 this surface is measured on the libraries' own CI (``lib-tests.yml`` +emits the ``unit-timings-`` artifact) and ingested daily by +``heart/checks/unit_timings.py``, which writes this same summary file; running +this module on a dev box remains an on-demand deep probe with the identical +output shape. + +Running the library suites costs minutes (test_autofit is ~1500 tests), which +does not fit the <30s watch-loop budget (``docs/internals.md`` rule 3), so this +module is never wired into ``heart/tick.sh``: python -m heart.checks.unit_test_timing HYGIENE_PYTHON=~/venv/PyAuto/bin/python python -m heart.checks.unit_test_timing diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py new file mode 100644 index 00000000..efcd21ab --- /dev/null +++ b/heart/checks/unit_timings.py @@ -0,0 +1,982 @@ +"""heart/checks/unit_timings.py — per-TEST and per-IMPORT timings from the +libraries' own CI (the unit half of the speed surface). + +``smoke_timings`` ingests what the workspace gates measure; this is its twin for +the LIBRARIES. Their required gate is the reusable ``lib-tests.yml``, which since +#206 writes two things per python leg and uploads them as ``unit-timings-``: + +* ``junit.xml`` — pytest's own machine-readable per-test record (``--junitxml``), + one ```` per test with ``time`` = setup+call+teardown. A console + ``--durations`` tail would have to be scraped out of a log that expires; +* ``import_time.json`` — a FRESH-process ``import ``, timed on the runner. + +Both surfaces already had a dev-box check (``unit_test_timing.py``, +``import_time.py``) whose numbers only ever existed on one developer's laptop. +This check ingests the CI dataset instead and writes *those same two summary +files*, so the board's "Unit-test timing" and "Import timing" rows come alive +without either section changing its shape (see ``legacy_summaries``). + +Two modes, same module (the smoke_timings 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/.unit_timings.json``. +* **aggregate** (``--aggregate``) — read every sidecar and write the global + rollup at ``$HEART_STATE_DIR/unit_timings.json``, plus the two legacy + summaries the existing board sections read. + +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: + +* **One selector, two callers.** ``smoke_timings.select_artifacts`` takes the + name pattern as an argument and this module passes ``ARTIFACT_RE``. The rule + (newest, non-expired, one per named leg) is the same rule; a second copy of it + here would be a second thing to keep true. +* **The committed record is the ONLY baseline.** ``smoke_timings`` falls back to + the previously published ``board.json``; this check does not, because the + board never carried unit rows and never will carry them before the record + does. ``timings/unit/.jsonl`` (see ``heart/timings.py``) is durable and + keyed by ``(python, run_id)``; with no record every test row is ``ok`` and + every import row is ``building``, which is the truth on day one. +* **Drift needs BOTH gates**, exactly as in ci_timing/smoke_timings, and by + literally the same function (``classify_test_drift`` IS + ``smoke_timings.classify_drift``). Unit tests run 0.1–30 s, so the absolute + floor in ``config/repos.yaml`` is 2 s rather than smoke's 5 s. +* **A run is never compared against itself.** Every row carries its ``run_id``; + a previous row from the SAME run yields ``ok`` with no ratio rather than a + reassuring 1.0×. +* **Imports are judged by the median window, not by the previous run.** That is + the ``import_time`` doctrine, kept so a ratio means the same thing from either + vantage: the baseline is ``median`` of the last ``import_window`` recorded + observations and nothing is judged before ``import_min_samples`` of them + (state ``building``). +* **``seconds: null`` is never zero.** An import that failed or timed out has no + number; the returncode travels with it so the board can say why. Counting it + as 0 s would put a fabricated instant import into a timing dataset. +* **Only the ``top_n`` slowest tests per leg are kept.** A 1500-test suite whole + would multiply the sidecar, the rollup and the committed record for rows + nothing renders; the suite totals keep the coverage visible beside them. +* **Drift is advisory.** Rows are ``ok`` or ``warn``, never ``fail``; the + readiness verdict and the badge are untouched — this is a dashboard leg. +* **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 rows. "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 (``.unit_timings.json``):: + + { + "name": "RepoA", "group": "libraries", "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 + "error": "", + "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, + "wall_s": 412.0}, + "slowest": [{"nodeid": "tests/foo/test_bar.py::test_x", + "seconds": 12.5}], + "import": {"package": "pkg_a", "seconds": 3.6, "returncode": 0}} + ] + } + +Global rollup schema (``unit_timings.json``):: + + {"ts", + "repos": [{repo, python, run_id, run_url, head_branch, head_sha, at, + tests, wall_s, import_s, package, error, suite, slowest}], + "tests": [{repo, python, nodeid, seconds, run_id, run_url, prev_s, + prev_run_id, ratio, delta_s, state, prompt}], + "imports": [{repo, package, python, seconds, run_id, run_url, baseline_s, + samples, ratio, state, prompt}], + "slowed_tests": [...], "slowed_imports": [...], + "errors": [{repo, error}], "thresholds": {...}} + +``repos[]`` carries ``suite`` and ``slowest`` whole so ``heart.timings`` can +build the committed record from the rollup alone, without re-reading a sidecar. + +Every actionable row — a slowed test, a slowed import — 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 statistics +import sys +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any + +# Reused, never duplicated: the both-gates drift rule and the artifact selector +# are one implementation with two callers. +from heart.checks.import_time import classify as _classify_ratio +from heart.checks.smoke_timings import classify_drift as classify_test_drift +from heart.checks.smoke_timings import select_artifacts as _select_artifacts + +HEART_HOME = Path(__file__).resolve().parents[2] +CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" + +# The libraries' Tests gate publishes one artifact per python leg. Nothing else +# in a library repo is named this way, and the workspaces' `smoke-timings-` +# deliberately does not match: a unit suite and a smoke script are different +# sizes of thing measured on different cadences. +ARTIFACT_RE = re.compile(r"^unit-timings-(\d+\.\d+)$") + +JUNIT_FILENAME = "junit.xml" +IMPORT_FILENAME = "import_time.json" +IMPORT_SCHEMA = "import_time/1" + +NO_DATASET_ERROR = "no unit-timings dataset in artifact" + +# Fallback when config/repos.yaml is unreadable; kept in sync with the YAML. +DEFAULT_UNIT_TIMINGS_THRESHOLDS = { + "slow_factor": 2.0, + "min_delta_s": 2, + "top_n": 25, + "import_yellow_factor": 1.5, + "import_red_factor": 3.0, + "import_window": 7, + "import_min_samples": 3, +} + +# The legacy "Unit-test timing" section says "(>3× baseline)" / "(>1.5×)" in its +# own summary wording, which it inherited from the dev-box check's rolling +# median. These two constants exist ONLY to keep that wording truthful when the +# section is fed from CI rows; the rows' own advisory `warn` state is the +# both-gates rule above, and nothing here changes it. +LEGACY_RED_FACTOR = 3.0 +LEGACY_YELLOW_FACTOR = 1.5 + +# What the ingested summaries put in the legacy `python` field: these numbers +# were measured on a CI runner, not by a `HYGIENE_PYTHON` on someone's laptop. +LEGACY_PYTHON = "ci" + + +# --- 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.unit_timings`` block, defaulted key by key.""" + out = dict(DEFAULT_UNIT_TIMINGS_THRESHOLDS) + block = (_load_config(config_path).get("thresholds") or {}).get("unit_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 ``unit-timings-`` artifact per python leg. + + A thin binding of ``smoke_timings.select_artifacts`` to this check's own + name pattern — same rule, one implementation. + """ + return _select_artifacts(listing, ARTIFACT_RE) + + +def junit_nodeid(classname: Any, name: Any) -> str: + """pytest's ``path::[Class::]test`` from a junit ``classname``/``name`` pair. + + junit has no node ids: pytest writes the DOTTED import path of the module + (plus the test class, when there is one) into ``classname`` and the test + name into ``name``. Reconstructing the node id is therefore a heuristic, and + it is kept deliberately simple — the first segment that starts with an + uppercase letter is taken as the test class, everything before it as the + module path: + + ``tests.foo.test_bar`` + ``test_x`` -> ``tests/foo/test_bar.py::test_x`` + ``tests.foo.test_bar.TestThing`` + ``test_x`` -> ``tests/foo/test_bar.py::TestThing::test_x`` + + When there is no module path to rebuild (a bare ``TestThing``, a plugin that + writes something else entirely) the dotted form is carried through verbatim + as ``classname::name`` rather than guessed at: an unrecognisable id that is + stable still compares correctly against itself run to run, which is all the + drift rule needs. + """ + classname = str(classname or "").strip() + name = str(name or "").strip() + if not classname: + return name + parts = [p for p in classname.split(".") if p] + module: list[str] = [] + classes: list[str] = [] + for index, part in enumerate(parts): + if part[:1].isupper(): + classes = parts[index:] + break + module.append(part) + if not module: + return f"{classname}::{name}" if name else classname + segments = ["/".join(module) + ".py", *classes] + if name: + segments.append(name) + return "::".join(segments) + + +def parse_junit(text: str) -> tuple[list[dict[str, Any]], dict[str, Any], str]: + """One ``junit.xml`` → ``(tests, suite, error)``. + + ``tests`` is ``[{"nodeid", "seconds"}]`` for every ```` carrying a + numeric ``time``; a testcase without one was never measured and is not a + zero-second test. ``suite`` sums the ```` attributes — a run can + emit more than one — into ``{tests, failures, errors, skipped, wall_s}``, so + the coverage behind the durations stays visible beside them. + + Malformed XML degrades to ``([], {}, "")``: this file is written by + another organ on a runner we do not control, and an unattended check must + never raise over it. + """ + if not isinstance(text, str) or not text.strip(): + return [], {}, f"{JUNIT_FILENAME} was empty" + try: + root = ET.fromstring(text) + except ET.ParseError: + return [], {}, f"{JUNIT_FILENAME} was not valid XML" + + suites = list(root.iter("testsuite")) + if not suites: + return [], {}, f"{JUNIT_FILENAME} carried no " + + suite: dict[str, Any] = {"tests": 0, "failures": 0, "errors": 0, + "skipped": 0, "wall_s": 0.0} + for element in suites: + for key in ("tests", "failures", "errors", "skipped"): + suite[key] += _as_int(element.get(key)) or 0 + suite["wall_s"] += _as_float(element.get("time")) or 0.0 + suite["wall_s"] = round(suite["wall_s"], 3) + + tests: list[dict[str, Any]] = [] + for case in root.iter("testcase"): + seconds = _as_float(case.get("time")) + if seconds is None: + continue + nodeid = junit_nodeid(case.get("classname"), case.get("name")) + if not nodeid: + continue + tests.append({"nodeid": nodeid, "seconds": round(seconds, 3)}) + return tests, suite, "" + + +def parse_import_time(text: str) -> tuple[dict[str, Any] | None, str]: + """One ``import_time.json`` → (row, "") or (None, reason). + + Normalised to exactly the five keys this check stores, every type coerced + defensively. ``seconds`` stays ``None`` when the import failed or timed out + — never 0.0 — and ``returncode`` travels with it so the board can say why + there is no number. + """ + try: + data = json.loads(text) + except (TypeError, ValueError): + return None, f"{IMPORT_FILENAME} was not valid JSON" + if not isinstance(data, dict): + return None, f"{IMPORT_FILENAME} was not an object" + if str(data.get("schema") or "") != IMPORT_SCHEMA: + return None, f"not an {IMPORT_SCHEMA} dataset" + return ( + { + "package": str(data.get("package") or ""), + "python": str(data.get("python") or ""), + "seconds": _as_float(data.get("seconds")), + "returncode": _as_int(data.get("returncode")), + "ts": str(data.get("ts") or ""), + }, + "", + ) + + +def read_downloaded_leg( + directory: Path | str, +) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, Any] | None, str, dict[str, str]]: + """One extracted artifact → ``(tests, suite, import_row, error, meta)``. + + The two halves are read independently ON PURPOSE. An install that died + before pytest ran leaves the import file and no junit; an import that + crashed leaves the junit and a null-seconds import row. Either half alone is + still data, and losing it because its sibling is missing would be a hole in + the record for no reason. Only when BOTH are absent is the artifact an + honest ``no unit-timings dataset``. + """ + root = Path(directory) + tests: list[dict[str, Any]] = [] + suite: dict[str, Any] = {} + import_row: dict[str, Any] | None = None + errors: list[str] = [] + + junit_paths = sorted(root.rglob(JUNIT_FILENAME)) + if junit_paths: + try: + text = junit_paths[0].read_text() + except OSError: + errors.append(f"{JUNIT_FILENAME} was unreadable") + else: + tests, suite, err = parse_junit(text) + if err: + errors.append(err) + + import_paths = sorted(root.rglob(IMPORT_FILENAME)) + if import_paths: + try: + text = import_paths[0].read_text() + except OSError: + errors.append(f"{IMPORT_FILENAME} was unreadable") + else: + import_row, err = parse_import_time(text) + if err: + errors.append(err) + + if not junit_paths and not import_paths: + return [], {}, None, NO_DATASET_ERROR, {} + meta = {"python": str((import_row or {}).get("python") or "")} + return tests, suite, import_row, "; ".join(errors), meta + + +# --- prompts (written by the producer; never re-derived by a renderer) ------- +def test_prompt(repo: str, nodeid: str, prev_s: Any, now_s: Any, + prev_run_url: str, run_url: str) -> str: + """The self-contained /hygiene prompt a slowed test copies.""" + prev = _as_float(prev_s) or 0.0 + now = _as_float(now_s) or 0.0 + return ( + f"/hygiene perf: {repo} {nodeid} {prev:.1f}s → {now:.1f}s " + f"between runs {prev_run_url} → {run_url}" + ) + + +def import_prompt(repo: str, package: str, python: str, baseline_s: Any, + now_s: Any, run_url: str) -> str: + """The self-contained /hygiene prompt a slowed import copies. + + ``repo`` is taken for symmetry with ``test_prompt`` (every caller has it) + and deliberately not repeated in the string: the package name identifies the + library unambiguously, and the run URL already names the repo. + """ + base = _as_float(baseline_s) or 0.0 + now = _as_float(now_s) or 0.0 + return ( + f"/hygiene perf: import {package} {base:.2f}s → {now:.2f}s " + f"(py{python}) — {run_url}" + ) + + +# --- per-repo sidecar -------------------------------------------------------- +def build_sidecar( + name: str, + group: str, + owner: str, + legs: list[dict[str, Any]], + ts: str, + error: str = "", + top_n: int = int(DEFAULT_UNIT_TIMINGS_THRESHOLDS["top_n"]), +) -> dict[str, Any]: + """Construct one repo's unit_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 tests. A single leg that failed to download keeps its + provenance (run, python, url) with its own ``error`` and no rows. + + Only the ``top_n`` slowest tests survive into the sidecar (sorted by seconds + descending, ties broken by node id so the file is stable): a 1500-test suite + whole would multiply every artifact downstream — the sidecar, the rollup and + the committed record — for rows nothing renders. ``suite`` keeps the + coverage behind them visible. + """ + 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 "") + tests: list[dict[str, Any]] = [] + suite: dict[str, Any] = {} + import_row: dict[str, Any] | None = None + meta: dict[str, str] = {} + if not leg_error: + directory = leg.get("dir") + if directory: + tests, suite, import_row, leg_error, meta = read_downloaded_leg(directory) + else: + leg_error = "artifact was not downloaded" + slowest = sorted(tests, key=lambda row: (-row["seconds"], row["nodeid"])) + 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 ""), + "error": leg_error, + "suite": suite, + "slowest": slowest[: max(int(top_n or 0), 0)], + "import": ( + { + "package": import_row["package"], + "seconds": import_row["seconds"], + "returncode": import_row["returncode"], + } + if import_row + else None + ), + } + ) + 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, + } + + +# --- classification ---------------------------------------------------------- +def classify_import( + seconds: Any, + history: list[Any] | None, + thresholds: dict[str, float], +) -> tuple[str, float | None, float | None, int]: + """``(state, baseline_s, ratio, samples)`` for one import measurement. + + The ``import_time`` doctrine, kept verbatim so a ratio means the same thing + from either vantage: the baseline is the MEDIAN of the recorded window + (never the single previous run — an import is a few seconds and jitters), + and nothing is judged until ``import_min_samples`` prior observations exist. + ``building`` is that honest "not yet" state, and it is also what a failed + import gets: with no number there is no verdict to give. + """ + samples = [ + value for value in (_as_float(v) for v in (history or [])) + if value is not None and value > 0 + ] + baseline = round(statistics.median(samples), 3) if samples else None + now = _as_float(seconds) + minimum = int(thresholds.get("import_min_samples", 3) or 0) + if now is None or now <= 0 or baseline is None or len(samples) < minimum: + return "building", baseline, None, len(samples) + ratio = round(now / baseline, 2) + state = _classify_ratio( + ratio, + float(thresholds.get("import_yellow_factor", 1.5)), + float(thresholds.get("import_red_factor", 3.0)), + ) + return state, baseline, ratio, len(samples) + + +# --- aggregate --------------------------------------------------------------- +def aggregate( + sidecars: list[dict[str, Any]], + ts: str, + thresholds: dict[str, float] | None = None, + record_prev_rows: dict[tuple[str, str, str], dict[str, Any]] | None = None, + record_import_history: dict[tuple[str, str, str], list[float]] | None = None, +) -> dict[str, Any]: + """Fold the per-repo sidecars + the committed record into the rollup. + + ``record_prev_rows`` is ``{(repo, python, nodeid): prev_row}`` and + ``record_import_history`` is ``{(repo, package, python): [seconds]}``, both + out of ``heart.timings`` (``timings/unit/.jsonl``). Unlike + ``smoke_timings`` there is no published-board fallback: the board never + carried these rows, so on the first run every test is ``ok`` and every + import is ``building`` — which is exactly what "no baseline yet" means. + """ + thr = dict(thresholds or DEFAULT_UNIT_TIMINGS_THRESHOLDS) + prev_rows = dict(record_prev_rows or {}) + history = dict(record_import_history or {}) + + repos: list[dict[str, Any]] = [] + tests: list[dict[str, Any]] = [] + imports: 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}"}) + + suite = leg.get("suite") if isinstance(leg.get("suite"), dict) else {} + slowest = [row for row in (leg.get("slowest") or []) + if isinstance(row, dict)] + + for row in slowest: + nodeid = str(row.get("nodeid") or "") + seconds = _as_float(row.get("seconds")) + if not nodeid or seconds is None: + continue + prev_row = prev_rows.get((repo, python, nodeid)) + state, ratio, delta = classify_test_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 "") + tests.append({ + "repo": repo, + "python": python, + "nodeid": nodeid, + "seconds": seconds, + "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": (test_prompt(repo, nodeid, prev_s, seconds, + prev_run_url, run_url) + if state == "warn" else None), + }) + + imported = leg.get("import") if isinstance(leg.get("import"), dict) else None + package = str((imported or {}).get("package") or "") + import_s = _as_float((imported or {}).get("seconds")) + if imported is not None and package: + state, baseline, ratio, samples = classify_import( + import_s, history.get((repo, package, python)), thr + ) + imports.append({ + "repo": repo, + "package": package, + "python": python, + "seconds": import_s, + "run_id": run_id, + "run_url": run_url, + "baseline_s": baseline, + "samples": samples, + "ratio": ratio, + "state": state, + "prompt": (import_prompt(repo, package, python, baseline, + import_s, run_url) + if state in ("yellow", "red") else None), + }) + + repos.append({ + "repo": repo, + "python": python, + "run_id": run_id, + "run_url": run_url, + "head_branch": str(leg.get("head_branch") or ""), + "head_sha": str(leg.get("head_sha") or ""), + "at": at, + "tests": _as_int(suite.get("tests")) or 0, + "wall_s": _as_float(suite.get("wall_s")) or 0.0, + "import_s": import_s, + "package": package, + "error": leg_error, + # Carried whole so `heart.timings` can build the committed + # record from the rollup alone, without re-reading a sidecar. + "suite": dict(suite), + "slowest": [{"nodeid": str(row.get("nodeid") or ""), + "seconds": _as_float(row.get("seconds"))} + for row in slowest], + }) + + repos.sort(key=lambda r: (str(r.get("repo") or ""), str(r.get("python") or ""))) + tests.sort(key=lambda r: (str(r.get("repo") or ""), str(r.get("python") or ""), + str(r.get("nodeid") or ""))) + imports.sort(key=lambda r: (str(r.get("repo") or ""), str(r.get("python") or ""), + str(r.get("package") or ""))) + return { + "ts": ts, + "repos": repos, + "tests": tests, + "imports": imports, + "slowed_tests": [r for r in tests if r.get("state") == "warn"], + "slowed_imports": [r for r in imports + if r.get("state") in ("yellow", "red")], + "errors": errors, + "thresholds": thr, + } + + +# --- the two legacy summaries the board sections already read ---------------- +def legacy_summaries( + rollup: dict[str, Any], thresholds: dict[str, float] | None = None +) -> tuple[dict[str, Any], dict[str, Any]]: + """``(unit_test_timing summary, import_time summary)`` from the rollup. + + EXACTLY the shapes ``unit_test_timing.run()`` and ``import_time.run()`` + return, key for key, because the board's two sections read those files and + this check is now their cloud source. Nothing in ``heart/dashboard.py``'s + state logic changes: the same summary, measured somewhere better. + + ``python`` is ``"ci"`` — these numbers came off a CI runner, not off a + ``HYGIENE_PYTHON`` on somebody's laptop, and the field is the honest place + to say so. + """ + thr = dict(thresholds or DEFAULT_UNIT_TIMINGS_THRESHOLDS) + rollup = rollup if isinstance(rollup, dict) else {} + repos = [r for r in (rollup.get("repos") or []) if isinstance(r, dict)] + test_rows = [r for r in (rollup.get("tests") or []) if isinstance(r, dict)] + import_rows = [r for r in (rollup.get("imports") or []) if isinstance(r, dict)] + errors = [e for e in (rollup.get("errors") or []) if isinstance(e, dict)] + + # --- unit tests --------------------------------------------------------- + measured = {str(r.get("repo") or "") for r in repos if not r.get("error")} + unavailable = sorted({str(e.get("repo") or "") for e in errors + if str(e.get("repo") or "")} - measured) + unit: dict[str, list[dict[str, Any]]] = {"red": [], "yellow": [], "green": []} + new_tests = 0 + for row in test_rows: + ratio = _as_float(row.get("ratio")) + if ratio is None or _as_float(row.get("prev_s")) is None: + new_tests += 1 + continue + entry = { + "repo": str(row.get("repo") or ""), + "test": str(row.get("nodeid") or ""), + "latest_seconds": round(_as_float(row.get("seconds")) or 0.0, 3), + "baseline_seconds": round(_as_float(row.get("prev_s")) or 0.0, 3), + "ratio": ratio, + # One recorded previous observation is the whole baseline here (the + # both-gates rule compares run to run), never a rolling window. + "samples": 1, + } + if ratio > LEGACY_RED_FACTOR: + unit["red"].append(entry) + elif ratio > LEGACY_YELLOW_FACTOR: + unit["yellow"].append(entry) + else: + unit["green"].append(entry) + + unit_summary = { + "python": LEGACY_PYTHON, + "repos_measured": len(measured), + "repos_unavailable": unavailable, + "new_tests_no_baseline": new_tests, + "red_count": len(unit["red"]), + "yellow_count": len(unit["yellow"]), + "green_count": len(unit["green"]), + "red": sorted(unit["red"], key=lambda x: -x["ratio"]), + "yellow": sorted(unit["yellow"], key=lambda x: -x["ratio"]), + } + + # --- imports ------------------------------------------------------------ + imports: dict[str, list[dict[str, Any]]] = {"red": [], "yellow": [], "green": []} + packages_measured = 0 + packages_unavailable: list[str] = [] + new_packages = 0 + for row in import_rows: + package = str(row.get("package") or "") + seconds = _as_float(row.get("seconds")) + if seconds is None: + # No number is not a slow import: it is an import that did not + # happen, and it says so in its own field rather than as a 0 s row. + if package not in packages_unavailable: + packages_unavailable.append(package) + continue + packages_measured += 1 + state = str(row.get("state") or "") + if state == "building": + new_packages += 1 + continue + entry = { + "package": package, + "latest_seconds": round(seconds, 3), + "baseline_seconds": round(_as_float(row.get("baseline_s")) or 0.0, 3), + "ratio": _as_float(row.get("ratio")) or 0.0, + "samples": _as_int(row.get("samples")) or 0, + } + # An unrecognised state degrades to green rather than vanishing: a row + # that measured something must show up in exactly one bucket. + imports.get(state, imports["green"]).append(entry) + + import_summary = { + "python": LEGACY_PYTHON, + "packages_measured": packages_measured, + "packages_unavailable": packages_unavailable, + "new_packages_no_baseline": new_packages, + "red_count": len(imports["red"]), + "yellow_count": len(imports["yellow"]), + "green_count": len(imports["green"]), + "red": sorted(imports["red"], key=lambda x: -x["ratio"]), + "yellow": sorted(imports["yellow"], key=lambda x: -x["ratio"]), + } + return unit_summary, import_summary + + +def read_sidecars(per_repo_dir: Path) -> list[dict[str, Any]]: + """Every ``*.unit_timings.json`` sidecar under ``per_repo_dir`` (I/O).""" + out: list[dict[str, Any]] = [] + for path in sorted(Path(per_repo_dir).glob("*.unit_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('unit_timings UNAVAILABLE')} " + f"{c_meta(str(sidecar['error']))}") + legs = [leg for leg in (sidecar.get("legs") or []) if isinstance(leg, dict)] + tracked = sum(len(leg.get("slowest") or []) 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'{tracked} test(s) tracked')}") + return (f"{glyph_ok()} {c_info(name)} {c_ok(f'{tracked} test(s) tracked')} " + 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, + ) + + legs = len(rollup.get("repos") or []) + tracked = len(rollup.get("tests") or []) + slowed = len(rollup.get("slowed_tests") or []) + imports = rollup.get("imports") or [] + red = len([r for r in imports if isinstance(r, dict) and r.get("state") == "red"]) + yellow = len([r for r in imports + if isinstance(r, dict) and r.get("state") == "yellow"]) + errors = len(rollup.get("errors") or []) + body = (f"{legs} suites, {tracked} tests tracked, {slowed} slowed, " + f"{len(imports)} imports ({red} red / {yellow} yellow)") + if errors: + body += f", {errors} unavailable" + bad = slowed or red or yellow or errors + glyph = glyph_warn() if bad else glyph_ok() + tint = c_warn if bad else c_ok + return (f"{glyph} {c_info('unit_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.unit_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 " + "and the two legacy summaries") + 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("--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 unit/ files are the ONLY baseline — with none, " + "every test is ok and every import is building") + ap.add_argument("--legacy-dir", default="", + help="where unit_test_timing.json and import_time.json are " + "written (default: $HEART_STATE_DIR)") + 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() + thresholds = load_thresholds() + + 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 + unit_dir = record_dir / "unit" + rollup = aggregate( + read_sidecars(per_repo), ts, thresholds, + record_prev_rows=_timings.previous_unit_rows(unit_dir), + record_import_history=_timings.import_history( + unit_dir, int(thresholds.get("import_window", 7) or 7) + ), + ) + _write(Path(ns.out), rollup) + # The two legacy summaries: the SAME files the dev-box checks write, so + # the board's existing sections come alive without changing shape. + legacy_dir = Path(ns.legacy_dir) if ns.legacy_dir else _state.HEART_STATE_DIR + unit_summary, import_summary = legacy_summaries(rollup, thresholds) + _write(legacy_dir / "unit_test_timing.json", unit_summary) + _write(legacy_dir / "import_time.json", import_summary) + 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, + top_n=int(thresholds.get("top_n", 25) or 25)) + _write(Path(ns.out), sidecar) + print(repo_summary_line(sidecar)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/checks/unit_timings.sh b/heart/checks/unit_timings.sh new file mode 100755 index 00000000..bd087cc2 --- /dev/null +++ b/heart/checks/unit_timings.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# heart/checks/unit_timings.sh — per-test + per-import CI timings (the unit leg). +# +# The twin of smoke_timings.sh, pointed at the LIBRARIES. For each polled +# library this lists the repo's artifacts via `gh api`, asks +# `heart.checks.unit_timings --plan` which of them are the Tests gate's +# `unit-timings-` legs, downloads and unzips those, and hands the extracted +# directories to the per-repo Python call, which parses the junit XML (per-test +# durations) and the `import_time/1` dataset inside and writes +# $HEART_PER_REPO_DIR/.unit_timings.json. A second, aggregate pass folds +# every sidecar into the global rollup at $HEART_STATE_DIR/unit_timings.json and +# writes the two LEGACY summaries the board's "Unit-test timing" and "Import +# timing" sections already read ($HEART_STATE_DIR/unit_test_timing.json and +# import_time.json) — the same files the dev-box checks write, so those rows +# come alive without either section changing shape. +# +# Only the `libraries` group is polled: a workspace runs no unit suite and +# publishes no `unit-timings-` artifact, and asking for one would manufacture +# a repo full of false "unavailable" rows. +# +# NO PREVIOUS-BOARD FETCH, deliberately, and this is the one structural +# difference from smoke_timings.sh: the committed record +# (timings/unit/.jsonl) is the ONLY baseline here. The published board +# never carried unit rows, so there is nothing to fall back to and nothing to +# fetch — with no record yet every test row is `ok` and every import is +# `building`, which is the truth on day one. +# +# 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 group whose required workflow is the libraries' Tests gate — the only +# repos that publish a `unit-timings-` artifact at all. +_UNIT_GROUPS="libraries" + +# `per_page=100` is one page of artifacts, newest first: comfortably more than +# the handful of live `unit-timings-*` legs, and the selector takes the newest +# non-expired one per name anyway. +_UNIT_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/$_UNIT_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.unit_timings \ + --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ + --fetch-error "$fetch_error" \ + --out "$HEART_PER_REPO_DIR/$name.unit_timings.json" + return 0 + fi + rm -f "$err" + + # The selection rule (newest non-expired artifact per python leg) lives in + # Python, never re-derived here. + local plan + plan="$(PYTHONPATH="$HEART_HOME" python3 -m heart.checks.unit_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 + # library 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.unit_timings \ + --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ + --listing "$listing" --downloads "$downloads" \ + --out "$HEART_PER_REPO_DIR/$name.unit_timings.json" + + rm -rf "$downloads" + rm -f "$listing" +} + +check_unit_timings_all() { + heart_state_dir + heart_log INFO "$(c_info "unit_timings: ingesting per-test unit-timings artifacts across the libraries")" + while read -r line; do + [[ -z "$line" ]] && continue + local owner_name group + owner_name="${line%% *}" + group="${line##* }" + case " $_UNIT_GROUPS " in + *" $group "*) ingest_one_repo "$owner_name" "$group" & ;; + *) continue ;; + esac + done < <(load_repos_yaml) + wait + + # The committed record (timings/unit/.jsonl) is the only baseline: + # previous test seconds per leg, and the import window whose median every + # import ratio is taken against. + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.unit_timings \ + --aggregate --ts "$(date -Iseconds)" \ + --record-dir "$HEART_HOME/timings" \ + --out "$HEART_STATE_DIR/unit_timings.json" + + heart_log OK "$(c_ok "unit_timings: done")" +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + check_unit_timings_all +fi diff --git a/heart/checks/workspace_testmode_timing.py b/heart/checks/workspace_testmode_timing.py index 0d6c5ccc..0587b6c5 100644 --- a/heart/checks/workspace_testmode_timing.py +++ b/heart/checks/workspace_testmode_timing.py @@ -6,9 +6,14 @@ scripts with ``PYAUTO_TEST_MODE=2`` + ``PYAUTO_WORKSPACE_SMALL_DATASETS=1`` — the developer-loop mode named in the original hygiene prompt — and times them. -OFF-TICK by design: running scripts costs seconds–minutes, which does not fit -the <30s watch-loop budget (``docs/internals.md`` rule 3). Run on a slower -cadence (daily cron / on demand), NOT from ``heart/tick.sh``: +Superseded on the board by the per-script smoke timings +(``heart/checks/smoke_timings.py``, #203): the smoke gates already run the +workspace scripts in TEST_MODE=2 with small datasets on every PR. Kept runnable +on demand; no longer a cloud-greyed board row (#206). + +Running scripts costs seconds–minutes, which does not fit the <30s watch-loop +budget (``docs/internals.md`` rule 3), so this module is never run from +``heart/tick.sh``: python -m heart.checks.workspace_testmode_timing diff --git a/heart/dashboard.py b/heart/dashboard.py index 290e2721..fa22d1d2 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -70,15 +70,22 @@ # Check families that only a local working tree can observe. On the cloud job # these are passed as ``unobserved`` so the board marks them honestly rather # than implying they are green. (Spec §2 "Cloud-safe caveat".) +# +# Three families LEFT this tuple in #206. `import_time` and `unit_test_timing` +# are now cloud-OBSERVED by ingestion: the libraries' own CI emits the +# `unit-timings-` artifact and `heart/checks/unit_timings.py` writes exactly +# these two summary files from it, so greying the rows on the cloud job would be +# a lie about data the job measured. `workspace_testmode_timing` is superseded +# on the board by the per-script Smoke scripts row (#203) — the smoke gates +# already run those scripts in TEST_MODE=2 on every PR — and is retired from the +# board rather than greyed: its section still renders if a dev-box snapshot +# carries the slice, but the cloud render no longer claims to be watching it. LOCAL_ONLY_FAMILIES = ( "repo_state", "worktree_drift", "script_timing", - "import_time", - "unit_test_timing", "profiling_drift", "test_run", - "workspace_testmode_timing", "version_skew", ) @@ -114,13 +121,14 @@ def _repo_owners() -> dict: # One line per local-only family on WHAT the dev box would observe — shown on # the grey rows so "not observed here" is a fact with a remedy, not a shrug. +# One line per LOCAL-ONLY family, exactly: the three that left +# LOCAL_ONLY_FAMILIES in #206 have no entry here either, because a watch line +# for a family that is never unobserved describes a grey row that can no longer +# render. UNOBS_WATCHES = { "worktree_drift": "task worktrees vs the active.md ledger (orphans, missing, dirty)", "script_timing": "workspace script runtimes vs their baselines", - "import_time": "library import costs vs their baselines", - "unit_test_timing": "the slowest unit tests vs their baselines", "profiling_drift": "pinned profiling results vs their baselines", - "workspace_testmode_timing": "TEST_MODE workspace script runtimes vs their baselines", "test_run": "the latest full workspace test-run verdict", "version_skew": "workspace version floors vs the newest releases", } @@ -346,6 +354,67 @@ def _dur(seconds: Any) -> str: return f"{int(round(seconds / 60))}m" +# How many ingested unit rows a section shows before it is a wall of text. Six +# is two python legs across three libraries — enough to see the shape, short +# enough to stay a detail block under a one-line summary. +UNIT_DETAIL_CAP = 6 + + +def _unit_suite_details(slice_: Any) -> list[str]: + """One line per ingested suite leg, slowest wall-clock first. + + Fed by ``heart/checks/unit_timings.py``'s rollup (#206). The legacy summary + above counts regressions; this says what was measured — how long each + library's suite takes on CI and what the slowest test in it is. Absent slice + => no lines at all, so a snapshot from before the ingest renders exactly as + it did. + """ + if not isinstance(slice_, dict): + return [] + legs = [leg for leg in (slice_.get("repos") or []) if isinstance(leg, dict)] + legs.sort(key=lambda leg: (-(_as_float(leg.get("wall_s")) or 0.0), + str(leg.get("repo") or ""), + str(leg.get("python") or ""))) + lines: list[str] = [] + for leg in legs[:UNIT_DETAIL_CAP]: + repo = str(leg.get("repo") or "?") + python = str(leg.get("python") or "?") + tests = _as_int(leg.get("tests")) + line = f"{repo} py{python}: {tests} tests {_dur(leg.get('wall_s'))}" + slowest = [row for row in (leg.get("slowest") or []) if isinstance(row, dict)] + if slowest: + top = slowest[0] + seconds = _as_float(top.get("seconds")) + nodeid = str(top.get("nodeid") or "?").split("::")[-1] + if seconds is not None: + line += f" slowest {nodeid} {seconds:.1f}s" + lines.append(line) + return lines + + +def _unit_import_details(slice_: Any) -> list[str]: + """One line per ingested import measurement (#206). + + A package whose import failed carries ``seconds: null`` — no number, so no + line: a fabricated 0.00s would be worse than the silence, and the row is + already counted as unavailable in the summary above. + """ + if not isinstance(slice_, dict): + return [] + lines: list[str] = [] + for row in (slice_.get("imports") or []): + if not isinstance(row, dict): + continue + seconds = _as_float(row.get("seconds")) + if seconds is None: + continue + lines.append(f"{row.get('package') or '?'} " + f"py{row.get('python') or '?'}: {seconds:.2f}s") + if len(lines) >= UNIT_DETAIL_CAP: + break + return lines + + def _gate_spark(history: Sequence[Any], key: str) -> str: """The sparkline of one gate's daily p50s, oldest first.""" values: list[float] = [] @@ -375,6 +444,16 @@ def _as_int(v: Any, default: int = 0) -> int: return default +def _as_float(v: Any, default: float | None = None) -> float | None: + """A float, or ``default``. ``bool`` is not a number here, nor is junk.""" + if isinstance(v, bool): + return default + try: + return float(v) + except (TypeError, ValueError): + return default + + def _parse_ts(ts: Any) -> datetime.datetime | None: try: t = datetime.datetime.fromisoformat(str(ts)) @@ -658,6 +737,11 @@ def build_board( f"{e['latest_seconds']:.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)" for e in (imp.get("red") or [])[:5] ] + # What was actually measured, when the CI ingest observed it: the + # summary above counts regressions, and a row that says only "3 + # imports within baseline" never says how long an import takes. + # Purely additive — the section's state logic is untouched. + details += _unit_import_details(snapshot.get("unit_timings")) sections.append(Section("import_time", "Import timing", st, summary, details)) # Unit-test timing (advisory; off-tick) ----------------------------------- @@ -682,6 +766,10 @@ def build_board( f"{e['latest_seconds']:.2f}s vs {e['baseline_seconds']:.2f}s ({e['ratio']}×)" for e in (ut.get("red") or [])[:5] ] + # The suites behind the summary, slowest wall-clock first: which + # library's suite costs what, and the single slowest test in it. + # Purely additive — the section's state logic is untouched. + details += _unit_suite_details(snapshot.get("unit_timings")) sections.append(Section("unit_test_timing", "Unit-test timing", st, summary, details)) # Profiling pinned-value drift ------------------------------------------- @@ -1073,6 +1161,7 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non 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. + `unit` (#206) is emitted on the same rule, for the same reason. """ ct = snapshot.get("ci_timing") ct = ct if isinstance(ct, dict) else {} @@ -1080,13 +1169,15 @@ 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 {} + ut = snapshot.get("unit_timings") + ut = ut if isinstance(ut, 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: + if not ct and not nr and not st and not ut: return None gates = [g for g in (ct.get("gates") or []) if isinstance(g, dict)] @@ -1150,6 +1241,22 @@ def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | Non "events": st_events, "errors": st_errors, } + if ut: + # The unit half (#206): suite legs, the slowest tests and the import + # measurements, each actionable row carrying its own prompt. Additive + # and observed-only, exactly as `scripts` — the Brain board reads it, + # and the baseline itself lives in the committed record, not here. + block["unit"] = { + "schema": 1, + "repos": [r for r in (ut.get("repos") or []) if isinstance(r, dict)], + "tests": [r for r in (ut.get("tests") or []) if isinstance(r, dict)], + "imports": [r for r in (ut.get("imports") or []) if isinstance(r, dict)], + "slowed_tests": [r for r in (ut.get("slowed_tests") or []) + if isinstance(r, dict)], + "slowed_imports": [r for r in (ut.get("slowed_imports") or []) + if isinstance(r, dict)], + "errors": list(ut.get("errors") or []), + } return block diff --git a/heart/state.py b/heart/state.py index 91c6e7c7..af9df358 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 unit half of the CI speed surface (#206): per-test durations and + # import seconds ingested from the libraries' own `unit-timings-` + # artifacts. The same check also writes the two legacy summaries read + # above as `import_time` and `unit_test_timing`. + "unit_timings": _read_json_or_default(HEART_STATE_DIR / "unit_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 diff --git a/heart/timings.py b/heart/timings.py index e4698850..05d327cb 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -17,6 +17,7 @@ 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) + timings/unit/.jsonl # one line per (python leg, run id) Deliberate choices, each one a recorded lesson: @@ -25,7 +26,7 @@ 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: + ``date``; the scripts and unit 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 @@ -61,6 +62,23 @@ 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. +``unit/.jsonl`` line (the libraries' own CI, via +``heart/checks/unit_timings.py``):: + + {"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", "package": "pkg_a", + "import_s": 3.6, + "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, + "wall_s": 412.0}, + "slowest": {"tests/foo/test_bar.py::test_x": 12.5}} + +Only the N SLOWEST tests are recorded, with the suite totals beside them: a +1500-test suite recorded whole would multiply this file forever for rows nothing +reads, while the totals keep the coverage visible. ``import_s`` is the +fresh-process cold import measured on the CI runner, and it is ``null`` — never +0.0 — when that import failed or timed out. + ``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 @@ -80,6 +98,7 @@ TIMINGS_DIR = HEART_HOME / "timings" GATES_FILE = TIMINGS_DIR / "gates.jsonl" SCRIPTS_DIR = TIMINGS_DIR / "scripts" +UNIT_DIR = TIMINGS_DIR / "unit" # 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. @@ -93,6 +112,8 @@ "gates_last": "", "scripts_observations": 0, "repos": 0, + "unit_observations": 0, + "unit_repos": 0, "unparseable": 0, } @@ -102,6 +123,11 @@ def scripts_file(repo: str, directory: Path | str = TIMINGS_DIR) -> Path: return Path(directory) / "scripts" / f"{repo}.jsonl" +def unit_file(repo: str, directory: Path | str = TIMINGS_DIR) -> Path: + """The per-repo unit-timings record path under ``directory``.""" + return Path(directory) / "unit" / 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.""" @@ -394,6 +420,179 @@ def previous_script_rows( return out +# --- unit tests + imports (the libraries' own CI) ---------------------------- +def unit_lines_from_rollup( + rollup: Any, today: str +) -> dict[str, list[dict[str, Any]]]: + """``{repo: [line, ...]}`` from a ``unit_timings.json`` rollup. + + One line per ``(repo, python, run_id)`` — the identity of a measurement, the + same key the scripts record uses and for the same reason: the libraries' + artifacts only change when a run happens, so a quiet week hands the daily + job the SAME run seven times. + + Everything the line needs is on the rollup's ``repos[]`` item (provenance, + the suite totals, the leg's slowest tests, the import seconds), so the + record can be built from the rollup alone without re-reading a sidecar. A + leg with no ``run_id`` has no identity and is skipped outright. + """ + out: dict[str, list[dict[str, Any]]] = {} + if not isinstance(rollup, dict): + return out + + 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) + + suite_in = leg.get("suite") if isinstance(leg.get("suite"), dict) else {} + suite = { + "tests": _as_int(suite_in.get("tests")), + "failures": _as_int(suite_in.get("failures")), + "errors": _as_int(suite_in.get("errors")), + "skipped": _as_int(suite_in.get("skipped")), + "wall_s": _as_float(suite_in.get("wall_s")), + } + slowest: dict[str, float] = {} + for row in leg.get("slowest") or []: + if not isinstance(row, dict): + continue + nodeid = str(row.get("nodeid") or "") + seconds = _as_float(row.get("seconds")) + if not nodeid or seconds is None: + continue + slowest[nodeid] = seconds + + 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 ""), + "head_sha": str(leg.get("head_sha") or ""), + "package": str(leg.get("package") or ""), + # `null`, never 0.0: an import that failed was not an instant one. + "import_s": _as_float(leg.get("import_s")), + "suite": suite, + "slowest": {name: slowest[name] for name in sorted(slowest)}, + }) + 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_unit(path: Path | str, lines: list[dict[str, Any]]) -> int: + """Append the unit lines not already recorded. Returns how many landed. + + Keyed by ``(python, run_id)``, NOT by the day — the scripts record's rule, + for the scripts record's reason: a quiet week would otherwise 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_unit_rows( + unit_dir: Path | str = UNIT_DIR, +) -> dict[tuple[str, str, str], dict[str, Any]]: + """``{(repo, python, nodeid): 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``), which is the same + function ``unit_timings`` classifies its test drift with. + + 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. Only the recorded (slowest) tests are in there to begin with — a test + that dropped out of the top N simply has no baseline next run, which is + honest: nothing was recorded about it. + """ + out: dict[tuple[str, str, str], dict[str, Any]] = {} + root = Path(unit_dir) + if not root.is_dir(): + return out + for path in sorted(root.glob("*.jsonl")): + repo = path.name[: -len(".jsonl")] + records, _ = read_jsonl(path) + latest: dict[str, dict[str, Any]] = {} + for record in records: + latest[str(record.get("python") or "")] = record + for python, record in latest.items(): + slowest = record.get("slowest") + if not isinstance(slowest, dict): + continue + for nodeid, value in slowest.items(): + seconds = _as_float(value) + if seconds is None: + continue + out[(repo, python, str(nodeid))] = { + "seconds": seconds, + "run_id": record.get("run_id"), + "run_url": str(record.get("run_url") or ""), + } + return out + + +def import_history( + unit_dir: Path | str = UNIT_DIR, window: int = 7 +) -> dict[tuple[str, str, str], list[float]]: + """``{(repo, package, python): [seconds, ...]}`` — oldest first, last N. + + The median of this window is the import baseline (``import_time``'s + doctrine, kept so a ratio means the same thing from either vantage). A + ``null`` observation — an import that failed or timed out — is skipped + rather than carried as a zero, which would drag the median toward a number + nothing ever measured. + """ + out: dict[tuple[str, str, str], list[float]] = {} + root = Path(unit_dir) + if not root.is_dir(): + return out + cap = int(window) if window and int(window) > 0 else 0 + for path in sorted(root.glob("*.jsonl")): + repo = path.name[: -len(".jsonl")] + records, _ = read_jsonl(path) + for record in records: + package = str(record.get("package") or "") + if not package: + continue + seconds = _as_float(record.get("import_s")) + if seconds is None: + continue + key = (repo, package, str(record.get("python") or "")) + out.setdefault(key, []).append(seconds) + if cap: + for key in out: + out[key] = out[key][-cap:] + 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. @@ -411,18 +610,21 @@ def census(directory: Path | str = TIMINGS_DIR) -> dict[str, Any]: 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 + def _count(sub: str) -> tuple[int, int]: + """(repos with at least one line, total lines) under ``root/``.""" + repos = observations = 0 + directory = root / sub + if directory.is_dir(): + for path in sorted(directory.glob("*.jsonl")): + records, repo_skipped = read_jsonl(path) + out["unparseable"] += repo_skipped + if records: + repos += 1 + observations += len(records) + return repos, observations + + out["repos"], out["scripts_observations"] = _count("scripts") + out["unit_repos"], out["unit_observations"] = _count("unit") return out @@ -470,8 +672,25 @@ def _do_append(ns: argparse.Namespace) -> int: appended[repo] = added scripts_added += added + per_repo_unit = unit_lines_from_rollup(_read_rollup(ns.unit_timings), today) + appended_unit: dict[str, int] = {} + unit_added = 0 + for repo in sorted(per_repo_unit): + lines = per_repo_unit[repo] + added = append_unit(unit_file(repo, directory), lines) + skipped += len(lines) - added + if added: + appended_unit[repo] = added + unit_added += added + payload = dict(census(directory)) payload["appended_today"] = {"gates": gates_added, "scripts": appended} + # The unit slice reports itself only when it was ASKED for, so an older + # invocation's payload and summary line read exactly as they always did. + # (The census above always carries the unit counts — the record has the + # slice whether or not this run was handed a rollup for it.) + if ns.unit_timings: + payload["appended_today"]["unit"] = appended_unit out_path = Path(ns.census_out) if ns.census_out else _default_census_out() try: state.atomic_write_json(out_path, payload) @@ -479,11 +698,13 @@ def _do_append(ns: argparse.Namespace) -> int: # The census is a convenience for the render, never the record itself. pass - print( + line = ( f"timings: gates +{1 if gates_added else 0} line, " - f"scripts +{scripts_added} lines across {len(appended)} repos, " - f"{skipped} skipped (already recorded)" + f"scripts +{scripts_added} lines across {len(appended)} repos" ) + if ns.unit_timings: + line += f", unit +{unit_added} lines across {len(appended_unit)} repos" + print(f"{line}, {skipped} skipped (already recorded)") return 0 @@ -507,6 +728,10 @@ def main(argv: list[str] | None = None) -> int: ap_append.add_argument("--smoke-timings", default="", help="the smoke_timings.json rollup; missing => " "nothing to append from that slice") + ap_append.add_argument("--unit-timings", default="", + help="the unit_timings.json rollup (per-test " + "durations + import seconds); 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="", diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 66b6ebcd..a941b8dc 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1293,3 +1293,146 @@ def test_the_census_never_touches_the_performance_block(): now=FRESH_NOW)) assert with_census["performance"] == without["performance"] assert "timings_record" not in with_census["performance"] + + +# --- the unit timings come from CI now (#206) ------------------------------- +# The libraries' own gate emits the `unit-timings-` artifact and +# `heart/checks/unit_timings.py` ingests it into the two summary files these +# sections already read — so two families left LOCAL_ONLY_FAMILIES, and a third +# (workspace_testmode_timing) was retired from the board as superseded by the +# per-script smoke row. Fake names throughout (the tenant firewall). + +UNIT_NODEID = "tests/foo/test_bar.py::test_x" +UNIT_RUN_URL = "https://ci.invalid/OwnerX/RepoA/actions/runs/7" + + +def _unit_timings_slice(*, imports=True): + return { + "ts": TS, + "repos": [ + {"repo": "RepoA", "python": "3.12", "run_id": 7, + "run_url": UNIT_RUN_URL, "head_branch": "main", "head_sha": "abc", + "at": TS, "tests": 1500, "wall_s": 412.0, "import_s": 3.6, + "package": "pkg_a", "error": "", + "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, + "wall_s": 412.0}, + "slowest": [{"nodeid": UNIT_NODEID, "seconds": 12.5}]}, + {"repo": "RepoB", "python": "3.12", "run_id": 8, + "run_url": UNIT_RUN_URL, "head_branch": "main", "head_sha": "def", + "at": TS, "tests": 200, "wall_s": 30.0, "import_s": 1.25, + "package": "pkg_b", "error": "", + "suite": {"tests": 200, "failures": 0, "errors": 0, "skipped": 0, + "wall_s": 30.0}, + "slowest": []}, + ], + "tests": [{"repo": "RepoA", "python": "3.12", "nodeid": UNIT_NODEID, + "seconds": 12.5, "run_id": 7, "run_url": UNIT_RUN_URL, + "prev_s": 4.0, "prev_run_id": 6, "ratio": 3.13, + "delta_s": 8.5, "state": "warn", "prompt": "/hygiene perf: x"}], + "imports": ([{"repo": "RepoA", "package": "pkg_a", "python": "3.12", + "seconds": 3.6, "run_id": 7, "run_url": UNIT_RUN_URL, + "baseline_s": 1.0, "samples": 3, "ratio": 3.6, + "state": "red", "prompt": "/hygiene perf: import"}, + {"repo": "RepoB", "package": "pkg_b", "python": "3.12", + "seconds": None, "run_id": 8, "run_url": UNIT_RUN_URL, + "baseline_s": None, "samples": 0, "ratio": None, + "state": "building", "prompt": None}] + if imports else []), + "slowed_tests": [], "slowed_imports": [], "errors": [], + "thresholds": {}, + } + + +def _legacy_unit(**kw): + summary = {"python": "ci", "repos_measured": 2, "repos_unavailable": [], + "new_tests_no_baseline": 0, "red_count": 0, "yellow_count": 0, + "green_count": 3, "red": [], "yellow": []} + summary.update(kw) + return summary + + +def _legacy_import(**kw): + summary = {"python": "ci", "packages_measured": 2, "packages_unavailable": [], + "new_packages_no_baseline": 0, "red_count": 0, "yellow_count": 0, + "green_count": 2, "red": [], "yellow": []} + summary.update(kw) + return summary + + +def test_the_ingested_families_are_no_longer_local_only(): + """They are measured on the libraries' CI and ingested daily (#206), so + greying them on the cloud render would be a lie about observed data; + workspace_testmode_timing is retired from the board as superseded (#203).""" + for family in ("import_time", "unit_test_timing", "workspace_testmode_timing"): + assert family not in dashboard.LOCAL_ONLY_FAMILIES + assert family not in dashboard.UNOBS_WATCHES + + +def test_a_cloud_render_with_no_slices_shows_no_rows_for_them(): + """No slice, no row — not a grey "not observed here" row either.""" + board = dashboard.build_board(make_snapshot(), make_verdict(), + unobserved=dashboard.LOCAL_ONLY_FAMILIES, + now=FRESH_NOW) + keys = [s.key for s in board.sections] + for family in ("import_time", "unit_test_timing", "workspace_testmode_timing"): + assert family not in keys + + +def test_the_ingested_sections_render_their_detail_lines_only_with_the_slice(): + plain = _section(dashboard.build_board( + make_snapshot(unit_test_timing=_legacy_unit(), import_time=_legacy_import()), + make_verdict(), now=FRESH_NOW), "unit_test_timing") + assert plain.details == [] + + board = dashboard.build_board( + make_snapshot(unit_test_timing=_legacy_unit(), import_time=_legacy_import(), + unit_timings=_unit_timings_slice()), + make_verdict(), now=FRESH_NOW) + unit = _section(board, "unit_test_timing") + # Worst wall-clock first, with the slowest test in the suite beside it. + assert unit.details == [ + "RepoA py3.12: 1500 tests 7m slowest test_x 12.5s", + "RepoB py3.12: 200 tests 30s", + ] + imports = _section(board, "import_time") + # A null-seconds import has no number, so it gets no line — never a 0.00s. + assert imports.details == ["pkg_a py3.12: 3.60s"] + # ...and neither section's state came from the new lines. + assert unit.state == dashboard.OK and imports.state == dashboard.OK + + +def test_board_json_carries_the_unit_block_only_when_observed(): + old = dashboard.build_board(_perf_snapshot(), make_verdict(), now=FRESH_NOW) + assert "unit" not in old.performance + + snap = make_snapshot(ci_timing=_ci_timing_slice(), no_run_census=_no_run_slice(), + unit_timings=_unit_timings_slice()) + new = dashboard.build_board(snap, make_verdict(), now=FRESH_NOW) + unit = new.performance["unit"] + assert unit["schema"] == 1 + assert unit["tests"][0]["prompt"] == "/hygiene perf: x" + assert unit["imports"][0]["state"] == "red" + assert len(unit["repos"]) == 2 + # The rest of the block is byte-identical: `unit` is purely additive. + assert json.dumps(old.performance, sort_keys=True) == json.dumps( + {k: v for k, v in new.performance.items() if k != "unit"}, sort_keys=True) + + +def test_unit_timings_alone_still_yields_a_performance_block(): + board = dashboard.build_board(make_snapshot(unit_timings=_unit_timings_slice()), + make_verdict(), now=FRESH_NOW) + assert board.performance["unit"]["repos"] + assert board.performance["gates"] == [] and board.performance["no_run"]["rows"] == [] + + +def test_malformed_unit_timings_slices_never_break_the_board(): + for snap in (make_snapshot(unit_timings="nope"), + make_snapshot(unit_timings=[]), + make_snapshot(unit_timings={"repos": None, "imports": "nope"}), + make_snapshot(unit_test_timing=_legacy_unit(), + import_time=_legacy_import(), + unit_timings={"repos": [None, "x", {"slowest": "no"}], + "imports": [None, "x", {}]})): + for fmt in ("term", "md", "html", "json"): + assert isinstance(dashboard.render(snap, make_verdict(), fmt=fmt, + now=FRESH_NOW), str) diff --git a/tests/test_heart_health_wiring.py b/tests/test_heart_health_wiring.py index 60c6b791..b7628b4a 100644 --- a/tests/test_heart_health_wiring.py +++ b/tests/test_heart_health_wiring.py @@ -112,3 +112,33 @@ 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 + + +# --- the unit-timings ingest is wired the same way (#206) -------------------- + +def test_the_cloud_step_runs_the_unit_timings_ingest(): + """The libraries' per-test artifact needs the same daily ingest the + workspaces' per-script one gets, or the two board rows go back to sleep.""" + _, job = _job() + assert "bash heart/checks/unit_timings.sh" in _cloud_step(job)["run"] + assert (CHECKS / "unit_timings.sh").is_file() + + +def test_the_append_step_records_the_unit_slice(): + _, job = _job() + body = job["steps"][_step_index(job, "Append today's observations")]["run"] + assert '--unit-timings "$HEART_STATE_DIR/unit_timings.json"' in body + + +def test_unit_timings_reads_the_record_and_never_a_previous_board(): + """The committed record is the ONLY baseline for this check: the published + board never carried per-test rows, so there is nothing to fall back to.""" + body = (CHECKS / "unit_timings.sh").read_text() + assert '--record-dir "$HEART_HOME/timings"' in body + assert "--prev-board" not in body + + +def test_the_snapshot_folds_in_the_unit_timings_rollup(): + state_py = (Path(__file__).resolve().parent.parent / "heart" / "state.py").read_text() + assert '"unit_timings": _read_json_or_default(' in state_py + assert '"unit_timings.json"' in state_py diff --git a/tests/test_lib_tests_wiring.py b/tests/test_lib_tests_wiring.py new file mode 100644 index 00000000..fb1a1738 --- /dev/null +++ b/tests/test_lib_tests_wiring.py @@ -0,0 +1,110 @@ +"""tests/test_lib_tests_wiring.py — the libraries' reusable gate stays wired. + +`lib-tests.yml` is referenced `@main` by six library repos, so a mistake in it +reds six required checks at once. These tests parse the YAML and pin the three +things #206 added to the `unittest` job — the fresh-process import timing, the +junit XML, and the `unit-timings-` artifact the Heart's `unit_timings` check +ingests — plus the two properties that keep the addition harmless: every new +step is non-fatal, and the pytest exit path is untouched apart from one flag. + +The `unittest-nojax` job is asserted UNCHANGED on purpose: it exists to prove +the jax-absent import path, it runs one python version, and a second dataset +from it would be a second channel measuring a different environment. + +PyYAML parses the bare `on:` key as boolean True, hence the `data[True]` reads +in the sibling wiring tests; nothing here needs the triggers. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +WORKFLOWS = Path(__file__).resolve().parent.parent / ".github" / "workflows" + +ARTIFACT_NAME = "unit-timings-${{ matrix.python-version }}" +IMPORT_STEP = "Time a fresh-process import" +UPLOAD_STEP = "Upload the unit timings" + + +def _jobs(): + return yaml.safe_load((WORKFLOWS / "lib-tests.yml").read_text())["jobs"] + + +def _steps(job_name): + return _jobs()[job_name]["steps"] + + +def _index(steps, needle): + for i, step in enumerate(steps): + if needle in step.get("name", ""): + return i + raise AssertionError(f"no step named like {needle!r} in lib-tests.yml") + + +def _step(steps, needle): + return steps[_index(steps, needle)] + + +def test_the_import_timing_step_runs_before_the_suite_and_cannot_red_the_gate(): + steps = _steps("unittest") + assert _index(steps, IMPORT_STEP) < _index(steps, "Run tests") + step = _step(steps, IMPORT_STEP) + # A dataset, not a gate: a package that cannot be imported fails the suite + # on its own merits two steps down. + assert step["continue-on-error"] is True + assert step["working-directory"] == "${{ steps.map.outputs.repo }}" + # The package name reaches Python through the environment, never + # interpolated into the heredoc's source. + assert step["env"]["PKG"] == "${{ inputs.package }}" + assert "${{ inputs.package }}" not in step["run"] + assert '"schema": "import_time/1"' in step["run"] + assert "test-results" in step["run"] + + +def test_the_suite_writes_pytest_s_own_junit_record(): + """--junitxml is the built-in per-test record; --durations is a console + tail that has to be scraped out of a log that expires with the run.""" + run = _step(_steps("unittest"), "Run tests")["run"] + assert "--junitxml=test-results/junit.xml" in run + # The exit path is untouched apart from that one flag. + assert "--cov ${{ inputs.package }} --cov-report xml:coverage.xml" in run + assert "continue-on-error" not in _step(_steps("unittest"), "Run tests") + + +def test_the_artifact_is_named_per_python_leg_and_never_fails_the_gate(): + steps = _steps("unittest") + step = _step(steps, UPLOAD_STEP) + assert step["if"] == "always()" # a red suite still has timings + assert step["uses"].startswith("actions/upload-artifact@") + assert step["with"]["name"] == ARTIFACT_NAME + assert step["with"]["path"] == "${{ steps.map.outputs.repo }}/test-results/" + # A leg that died before the first write must not red six libraries. + assert step["with"]["if-no-files-found"] == "ignore" + # No retention cap: the dataset is the point (smoke-tests.yml reasons the + # same way about its own timings artifact). + assert "retention-days" not in step["with"] + assert _index(steps, "Run tests") < _index(steps, UPLOAD_STEP) + + +def test_the_nojax_job_is_unchanged(): + """One dataset, one environment: the jax-absent leg proves imports work + without jax, and timing it would measure a different thing under the same + name.""" + steps = _steps("unittest-nojax") + names = [step.get("name", "") for step in steps] + assert not any(IMPORT_STEP in name or UPLOAD_STEP in name for name in names) + run = _step(steps, "Run tests (jax absent)")["run"] + assert "--junitxml" not in run + assert not any(str(step.get("uses", "")).startswith("actions/upload-artifact") + for step in steps) + + +def test_the_artifact_name_is_what_the_heart_check_selects(): + """One name, declared in two places that must agree — the emitter here and + the ingest's ARTIFACT_RE.""" + from heart.checks.unit_timings import ARTIFACT_RE + + assert ARTIFACT_RE.match("unit-timings-3.12") + assert ARTIFACT_NAME.startswith("unit-timings-") diff --git a/tests/test_timings.py b/tests/test_timings.py index bb7f63ce..0449fd01 100644 --- a/tests/test_timings.py +++ b/tests/test_timings.py @@ -250,9 +250,12 @@ def test_the_census_counts_days_observations_and_repos(tmp_path): for line in lines: line["repo"] = repo timings.append_scripts(timings.scripts_file(repo, tmp_path), lines) + # The two unit_* keys arrived with the unit-timings slice (#206): the + # census is the record's key set, and the record now holds three slices. assert timings.census(tmp_path) == { "gates_days": 2, "gates_first": "2026-09-04", "gates_last": TODAY, - "scripts_observations": 2, "repos": 2, "unparseable": 0, + "scripts_observations": 2, "repos": 2, + "unit_observations": 0, "unit_repos": 0, "unparseable": 0, } @@ -337,3 +340,172 @@ def test_the_epoch_file_is_reserved_and_never_written(tmp_path): "--census-out", str(tmp_path / "census.json")]) assert not (record / "epochs.jsonl").exists() assert not timings.EPOCHS_FILE.exists() + + +# --- the unit slice: per-test durations + the cold import (#206) -------------- +# +# Same two rules as the scripts record — append-only, keyed on (python, run_id) +# — over the libraries' own CI instead of the workspaces'. What is new here is +# WHAT is recorded: only the slowest N tests plus the suite totals (a 1500-test +# suite recorded whole would multiply the file for rows nothing reads), and the +# fresh-process import seconds, `null` when that import never succeeded. + +PACKAGE = "pkg_a" +NODEID = "tests/foo/test_bar.py::test_x" + + +def _unit_rollup(run_id=7, seconds=1.5, import_s=3.6, python="3.12"): + """A unit_timings.json rollup: one repo, one python leg, two slow tests.""" + return { + "ts": TS, + "repos": [ + {"repo": "RepoA", "python": python, "run_id": run_id, + "run_url": RUN_URL, "head_branch": "feat/x", "head_sha": "abc123", + "at": "2026-09-04T10:00:00Z", "tests": 1500, "wall_s": 412.0, + "import_s": import_s, "package": PACKAGE, "error": "", + "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, + "wall_s": 412.0}, + "slowest": [{"nodeid": NODEID, "seconds": seconds}, + {"nodeid": "tests/foo/test_bar.py::test_y", + "seconds": 0.5}]}, + ], + "tests": [], "imports": [], "slowed_tests": [], "slowed_imports": [], + "errors": [], "thresholds": {}, + } + + +def test_unit_lines_are_one_per_repo_python_and_run(): + lines = timings.unit_lines_from_rollup(_unit_rollup(), TODAY) + assert list(lines) == ["RepoA"] + (line,) = lines["RepoA"] + assert line["date"] == TODAY and line["python"] == "3.12" + assert line["run_id"] == 7 and line["run_url"] == RUN_URL + assert line["head_branch"] == "feat/x" and line["head_sha"] == "abc123" + assert line["at"] == "2026-09-04T10:00:00Z" + assert line["package"] == PACKAGE and line["import_s"] == 3.6 + assert line["suite"] == {"tests": 1500, "failures": 0, "errors": 0, + "skipped": 3, "wall_s": 412.0} + # Only the slowest tests, node id -> seconds, sorted by node id. + assert line["slowest"] == {NODEID: 1.5, + "tests/foo/test_bar.py::test_y": 0.5} + + +def test_a_unit_leg_with_no_run_id_has_no_identity_and_is_not_recorded(): + rollup = _unit_rollup() + rollup["repos"][0]["run_id"] = None + assert timings.unit_lines_from_rollup(rollup, TODAY) == {} + + +def test_a_failed_import_is_recorded_as_null_never_as_zero(): + (line,) = timings.unit_lines_from_rollup( + _unit_rollup(import_s=None), TODAY)["RepoA"] + assert line["import_s"] is None + + +def test_the_unit_record_is_keyed_by_leg_and_run_never_by_the_day(tmp_path): + path = timings.unit_file("RepoA", tmp_path) + lines = timings.unit_lines_from_rollup(_unit_rollup(), TODAY)["RepoA"] + assert timings.append_unit(path, lines) == 1 + # Same run, a later day: nothing new was measured, so nothing is recorded. + again = timings.unit_lines_from_rollup(_unit_rollup(), "2026-09-06")["RepoA"] + assert timings.append_unit(path, again) == 0 + fresh = timings.unit_lines_from_rollup( + _unit_rollup(run_id=8, seconds=9.0), "2026-09-06")["RepoA"] + assert timings.append_unit(path, fresh) == 1 + records, _ = timings.read_jsonl(path) + assert [(r["run_id"], r["date"]) for r in records] == [(7, TODAY), + (8, "2026-09-06")] + # Append-only, byte for byte. + assert path.read_text().count("\n") == 2 + + +def test_previous_unit_rows_takes_the_latest_line_per_leg_and_drives_drift(tmp_path): + unit_dir = tmp_path / "unit" + path = timings.unit_file("RepoA", tmp_path) + for run_id, seconds in ((7, 1.5), (8, 4.0)): + timings.append_unit(path, timings.unit_lines_from_rollup( + _unit_rollup(run_id=run_id, seconds=seconds), TODAY)["RepoA"]) + # A second python leg, so "latest per leg" is not "latest in the file". + timings.append_unit(path, timings.unit_lines_from_rollup( + _unit_rollup(run_id=9, seconds=0.5, python="3.13"), TODAY)["RepoA"]) + + prev = timings.previous_unit_rows(unit_dir) + assert prev[("RepoA", "3.12", NODEID)] == { + "seconds": 4.0, "run_id": 8, "run_url": RUN_URL} + assert prev[("RepoA", "3.13", NODEID)]["seconds"] == 0.5 + + thr = {"slow_factor": 2.0, "min_delta_s": 2} + row = prev[("RepoA", "3.12", NODEID)] + assert smoke_timings.classify_drift(12.0, row, thr, run_id=9)[0] == "warn" + assert smoke_timings.classify_drift(5.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(12.0, row, thr, run_id=8) == ( + "ok", None, None) + + +def test_import_history_is_oldest_first_window_capped_and_skips_nulls(tmp_path): + unit_dir = tmp_path / "unit" + path = timings.unit_file("RepoA", tmp_path) + for run_id, import_s in ((1, 1.0), (2, None), (3, 2.0), (4, 3.0), (5, 4.0)): + timings.append_unit(path, timings.unit_lines_from_rollup( + _unit_rollup(run_id=run_id, import_s=import_s), TODAY)["RepoA"]) + key = ("RepoA", PACKAGE, "3.12") + # A null was never a measurement: carrying it as 0.0 would drag the median + # toward a number nothing ever observed. + assert timings.import_history(unit_dir, 7)[key] == [1.0, 2.0, 3.0, 4.0] + assert timings.import_history(unit_dir, 2)[key] == [3.0, 4.0] + assert timings.import_history(tmp_path / "nope", 7) == {} + + +def test_the_census_counts_the_unit_slice_too(tmp_path): + assert timings.census(tmp_path)["unit_observations"] == 0 + for repo in ("RepoA", "RepoB"): + lines = timings.unit_lines_from_rollup(_unit_rollup(), TODAY)["RepoA"] + timings.append_unit(timings.unit_file(repo, tmp_path), lines) + census = timings.census(tmp_path) + assert census["unit_observations"] == 2 and census["unit_repos"] == 2 + # ...and the scripts figures stay their own. + assert census["scripts_observations"] == 0 and census["repos"] == 0 + + +def test_main_append_records_the_unit_slice_and_is_idempotent(tmp_path, capsys): + ci, smoke = _write_rollups(tmp_path) + unit = tmp_path / "unit_timings.json" + unit.write_text(json.dumps(_unit_rollup())) + record = tmp_path / "timings" + census_out = tmp_path / "census.json" + argv = ["append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--unit-timings", str(unit), "--today", TODAY, "--ts", TS, + "--dir", str(record), "--census-out", str(census_out)] + + assert timings.main(argv) == 0 + assert capsys.readouterr().out.strip() == ( + "timings: gates +1 line, scripts +1 lines across 1 repos, " + "unit +1 lines across 1 repos, 0 skipped (already recorded)") + assert timings.unit_file("RepoA", record).is_file() + census = json.loads(census_out.read_text()) + assert census["unit_observations"] == 1 and census["unit_repos"] == 1 + assert census["appended_today"]["unit"] == {"RepoA": 1} + + # A second run over the SAME inputs appends nothing at all. + assert timings.main(argv) == 0 + assert capsys.readouterr().out.strip() == ( + "timings: gates +0 line, scripts +0 lines across 0 repos, " + "unit +0 lines across 0 repos, 3 skipped (already recorded)") + assert len(timings.unit_file("RepoA", record).read_text().splitlines()) == 1 + assert json.loads(census_out.read_text())["appended_today"]["unit"] == {} + + +def test_a_run_without_the_unit_flag_reads_exactly_as_it_always_did(tmp_path, + capsys): + """The slice reports itself only when it was asked for, so an older + invocation's summary line and census payload are unchanged.""" + ci, smoke = _write_rollups(tmp_path) + census_out = tmp_path / "census.json" + assert timings.main([ + "append", "--ci-timing", str(ci), "--smoke-timings", str(smoke), + "--today", TODAY, "--dir", str(tmp_path / "timings"), + "--census-out", str(census_out), + ]) == 0 + assert "unit +" not in capsys.readouterr().out + assert "unit" not in json.loads(census_out.read_text())["appended_today"] diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py new file mode 100644 index 00000000..07c43000 --- /dev/null +++ b/tests/test_unit_timings.py @@ -0,0 +1,692 @@ +"""tests/test_unit_timings.py — per-test + per-import CI timings (#206). + +The unit twin of ``test_smoke_timings.py``: artifact selection, the two parses +(pytest's junit XML and the runner's ``import_time/1`` dataset), the drift rules +(both-gates for tests, the median window for imports) and the two LEGACY +summaries that make the board's existing "Unit-test timing" and "Import timing" +sections come alive without changing their shape. + +Fake repo/owner/package/test 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 import dashboard +from heart.checks import import_time as legacy_import +from heart.checks import unit_test_timing as legacy_unit +from heart.checks import unit_timings as ut + +REPO = "RepoA" +OWNER = "OwnerX" +PACKAGE = "pkg_a" +RUN_URL = f"https://github.com/{OWNER}/{REPO}/actions/runs/7" +PREV_RUN_URL = "https://ci.invalid/OwnerX/RepoA/actions/runs/6" +NODEID = "tests/foo/test_bar.py::test_x" + +THRESHOLDS = { + "slow_factor": 2.0, "min_delta_s": 2, "top_n": 25, + "import_yellow_factor": 1.5, "import_red_factor": 3.0, + "import_window": 7, "import_min_samples": 3, +} + + +# --- fixtures --------------------------------------------------------------- +def _artifact(name="unit-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, + "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,) = ut.select_artifacts([_artifact(**kw)]) + return picked + + +def _case(classname="tests.foo.test_bar", name="test_x", time="1.5"): + attrs = f'classname="{classname}" name="{name}"' + if time is not None: + attrs += f' time="{time}"' + return f"" + + +def _junit(cases=None, *, tests=2, failures=0, errors=0, skipped=1, time="41.0"): + cases = _case() if cases is None else cases + return ( + '' + f'{cases}' + ) + + +def _import_json(*, seconds=3.6, returncode=0, schema="import_time/1", + package=PACKAGE, python="3.12"): + return json.dumps({ + "schema": schema, "package": package, "python": python, + "seconds": seconds, "returncode": returncode, + "ts": "2026-09-01T09:55:00Z", + }) + + +def _extracted(tmp_path, *, sub="art", junit=..., imports=...): + """An extracted-artifact directory holding either/both dataset files.""" + d = tmp_path / sub + d.mkdir(parents=True, exist_ok=True) + if junit is ...: + junit = _junit() + if imports is ...: + imports = _import_json() + if junit is not None: + (d / "junit.xml").write_text(junit) + if imports is not None: + (d / "import_time.json").write_text(imports) + return d + + +def _legs(tmp_path, **kw): + return [{"artifact": _selected(), "dir": _extracted(tmp_path, **kw), "error": ""}] + + +def _sidecar(tmp_path, *, top_n=25, **kw): + return ut.build_sidecar(REPO, "libraries", OWNER, _legs(tmp_path, **kw), "T", + top_n=top_n) + + +def _prev_rows(seconds, run_id=6, nodeid=NODEID, python="3.12"): + return {(REPO, python, nodeid): {"seconds": seconds, "run_id": run_id, + "run_url": PREV_RUN_URL}} + + +def _cfg(tmp_path, **kw): + values = dict(THRESHOLDS) + values.update(kw) + body = "thresholds:\n unit_timings:\n" + "".join( + f" {key}: {value}\n" for key, value in values.items() + ) + cfg = tmp_path / "repos.yaml" + cfg.write_text(body) + return str(cfg) + + +# --- artifact selection ------------------------------------------------------ + +def test_selection_keeps_the_newest_unit_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("unit-timings-3.13", id_=3, created="2026-09-01T10:00:00Z"), + ]} + picked = ut.select_artifacts(listing) + assert [a["python"] for a in picked] == ["3.12", "3.13"] + 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" + + +def test_selection_ignores_the_smoke_and_weekly_artifact_names(): + """A smoke script and a unit test are different sizes of thing measured on + different cadences; mixing the channels would compare one to the other.""" + listing = {"artifacts": [ + _artifact("smoke-timings-3.12", id_=1), + _artifact("smoke-timings-scripts-ProjA-imaging", id_=2), + _artifact("unit-timings-scripts-ProjA", id_=3), + _artifact("unit-timings-3.12", id_=4), + ]} + assert [a["id"] for a in ut.select_artifacts(listing)] == [4] + + +def test_selection_skips_expired_artifacts_and_tolerates_garbage(): + listing = {"artifacts": [ + _artifact(id_=1, created="2026-09-02T10:00:00Z", expired=True), + _artifact(id_=2, created="2026-09-01T10:00:00Z"), + ]} + assert [a["id"] for a in ut.select_artifacts(listing)] == [2] + assert ut.select_artifacts(None) == [] + assert ut.select_artifacts({"artifacts": [None, "x", {}]}) == [] + + +# --- parsing pytest's junit XML --------------------------------------------- + +def test_a_module_classname_becomes_a_pytest_path_nodeid(): + tests, suite, err = ut.parse_junit(_junit()) + assert err == "" + assert tests == [{"nodeid": "tests/foo/test_bar.py::test_x", "seconds": 1.5}] + assert suite == {"tests": 2, "failures": 0, "errors": 0, "skipped": 1, + "wall_s": 41.0} + + +def test_a_class_in_the_middle_of_the_classname_stays_a_class_segment(): + tests, _, err = ut.parse_junit(_junit( + _case(classname="tests.foo.test_bar.TestThing"))) + assert err == "" and tests[0]["nodeid"] == ( + "tests/foo/test_bar.py::TestThing::test_x") + + +def test_an_unrecognisable_classname_is_carried_through_verbatim(): + """Stable beats guessed: an id that compares against itself run to run is + all the drift rule needs.""" + tests, _, _ = ut.parse_junit(_junit(_case(classname="TestThing"))) + assert tests[0]["nodeid"] == "TestThing::test_x" + tests, _, _ = ut.parse_junit(_junit(_case(classname=""))) + assert tests[0]["nodeid"] == "test_x" + + +def test_a_testcase_without_a_time_was_never_measured(): + tests, _, err = ut.parse_junit(_junit( + _case(name="test_x") + _case(name="test_y", time=None))) + assert err == "" and [t["nodeid"] for t in tests] == [ + "tests/foo/test_bar.py::test_x"] + + +def test_the_suite_totals_are_summed_over_every_testsuite(): + """A run can emit more than one ; the coverage is their sum.""" + doc = ( + "" + f'' + f"{_case(name='test_x')}" + f'' + f"{_case(name='test_y')}" + "" + ) + tests, suite, err = ut.parse_junit(doc) + assert err == "" + assert suite == {"tests": 5, "failures": 1, "errors": 2, "skipped": 1, + "wall_s": 15.0} + assert len(tests) == 2 + + +def test_malformed_junit_is_an_honest_error_never_a_raise(): + for text in ("") + assert tests == [] and suite == {} and "no " in err + + +# --- parsing the import_time/1 dataset -------------------------------------- + +def test_import_parse_rejects_a_foreign_schema_and_junk(): + row, err = ut.parse_import_time(_import_json(schema="import_time/2")) + assert row is None and "import_time/1" in err + row, err = ut.parse_import_time("not json") + assert row is None and "not valid JSON" in err + row, err = ut.parse_import_time("[]") + assert row is None and err + + +def test_a_failed_import_keeps_null_seconds_and_its_returncode(): + """Never 0.0: in a timing dataset that would read as an instant import.""" + row, err = ut.parse_import_time(_import_json(seconds=None, returncode=1)) + assert err == "" + assert row == {"package": PACKAGE, "python": "3.12", "seconds": None, + "returncode": 1, "ts": "2026-09-01T09:55:00Z"} + + +# --- reading one extracted artifact ----------------------------------------- + +def test_a_leg_with_only_the_junit_still_carries_its_tests(tmp_path): + """An import step that never wrote is not a reason to lose the suite.""" + tests, suite, row, err, meta = ut.read_downloaded_leg( + _extracted(tmp_path, imports=None)) + assert err == "" and row is None and meta["python"] == "" + assert tests and suite["tests"] == 2 + + +def test_a_leg_with_only_the_import_still_carries_it(tmp_path): + """An install that died before pytest ran still measured the import.""" + tests, suite, row, err, meta = ut.read_downloaded_leg( + _extracted(tmp_path, junit=None)) + assert err == "" and tests == [] and suite == {} + assert row["package"] == PACKAGE and meta["python"] == "3.12" + + +def test_a_leg_with_neither_is_an_honest_error(tmp_path): + empty = tmp_path / "empty" + empty.mkdir() + assert ut.read_downloaded_leg(empty) == ([], {}, None, ut.NO_DATASET_ERROR, {}) + + +def test_an_unparseable_half_is_reported_and_does_not_lose_the_other(tmp_path): + tests, _, row, err, _ = ut.read_downloaded_leg( + _extracted(tmp_path, junit="3× baseline)" / "(>1.5×)"; these constants exist + only so that wording stays true when the rows come from CI.""" + side = _sidecar(tmp_path, junit=_junit(_case(time="8.0"))) + roll = ut.aggregate([side], "T", THRESHOLDS, record_prev_rows=_prev_rows(2.0)) + unit, _ = ut.legacy_summaries(roll, THRESHOLDS) + assert unit["red_count"] == 1 and unit["yellow_count"] == 0 + (entry,) = unit["red"] + assert entry == {"repo": REPO, "test": NODEID, "latest_seconds": 8.0, + "baseline_seconds": 2.0, "ratio": 4.0, "samples": 1} + + side = _sidecar(tmp_path, sub="yellow", junit=_junit(_case(time="4.0"))) + roll = ut.aggregate([side], "T", THRESHOLDS, record_prev_rows=_prev_rows(2.0)) + unit, _ = ut.legacy_summaries(roll, THRESHOLDS) + assert unit["yellow_count"] == 1 and unit["red_count"] == 0 + + +def test_an_unavailable_repo_is_listed_never_counted_as_measured(tmp_path): + dead = ut.build_sidecar("RepoB", "libraries", OWNER, [], "T", error="boom") + roll = ut.aggregate([_sidecar(tmp_path), dead], "T", THRESHOLDS) + unit, _ = ut.legacy_summaries(roll, THRESHOLDS) + assert unit["repos_measured"] == 1 and unit["repos_unavailable"] == ["RepoB"] + + +def test_a_null_import_is_unavailable_not_a_fast_one(tmp_path): + side = _sidecar(tmp_path, imports=_import_json(seconds=None, returncode=1)) + _, imports = ut.legacy_summaries( + ut.aggregate([side], "T", THRESHOLDS), THRESHOLDS) + assert imports["packages_measured"] == 0 + assert imports["packages_unavailable"] == [PACKAGE] + assert imports["new_packages_no_baseline"] == 0 + + +def test_the_legacy_import_buckets_come_from_the_row_state(tmp_path): + roll = ut.aggregate([_sidecar(tmp_path)], "T", THRESHOLDS, + record_import_history={ + (REPO, PACKAGE, "3.12"): [1.0, 1.0, 1.0]}) + _, imports = ut.legacy_summaries(roll, THRESHOLDS) + assert imports["red_count"] == 1 and imports["packages_measured"] == 1 + assert imports["red"] == [{"package": PACKAGE, "latest_seconds": 3.6, + "baseline_seconds": 1.0, "ratio": 3.6, + "samples": 3}] + + +# --- ...and they drive the board's two existing sections -------------------- + +def _board(unit_summary=None, import_summary=None, unit_slice=None): + snapshot = {"ts": "2026-09-05T00:00:00+00:00", "repos": {}} + if unit_summary is not None: + snapshot["unit_test_timing"] = unit_summary + if import_summary is not None: + snapshot["import_time"] = import_summary + if unit_slice is not None: + snapshot["unit_timings"] = unit_slice + board = dashboard.build_board(snapshot, {"verdict": "green", "score": 100}) + return {section.key: section for section in board.sections} + + +def test_the_ingested_summaries_drive_the_board_ok_warn_and_fail(tmp_path): + green_roll = ut.aggregate([_sidecar(tmp_path)], "T", THRESHOLDS, + record_prev_rows=_prev_rows(1.4)) + unit, _ = ut.legacy_summaries(green_roll, THRESHOLDS) + assert _board(unit_summary=unit)["unit_test_timing"].state == dashboard.OK + + warn_roll = ut.aggregate([_sidecar(tmp_path, sub="w", + junit=_junit(_case(time="4.0")))], + "T", THRESHOLDS, record_prev_rows=_prev_rows(2.0)) + unit, _ = ut.legacy_summaries(warn_roll, THRESHOLDS) + assert _board(unit_summary=unit)["unit_test_timing"].state == dashboard.WARN + + fail_roll = ut.aggregate([_sidecar(tmp_path, sub="f", + junit=_junit(_case(time="8.0")))], + "T", THRESHOLDS, record_prev_rows=_prev_rows(2.0)) + unit, imports = ut.legacy_summaries(fail_roll, THRESHOLDS) + sections = _board(unit_summary=unit, import_summary=imports) + assert sections["unit_test_timing"].state == dashboard.FAIL + # The import summary of the same rollup measured its package and found + # nothing red: the two sections are fed from one rollup and judge apart. + assert sections["import_time"].state == dashboard.OK + + +# --- thresholds -------------------------------------------------------------- + +def test_thresholds_load_from_config(tmp_path): + assert ut.load_thresholds(_cfg(tmp_path, slow_factor=3.0, top_n=2))["top_n"] == 2 + assert (ut.load_thresholds(tmp_path / "absent.yaml") + == ut.DEFAULT_UNIT_TIMINGS_THRESHOLDS) + + +def test_real_config_declares_the_unit_timings_thresholds(): + """The shipped policy file must carry the block the check reads.""" + thr = ut.load_thresholds() + assert thr["slow_factor"] >= 1.0 and thr["min_delta_s"] >= 1 + assert thr["top_n"] >= 1 and thr["import_window"] >= 1 + assert thr["import_red_factor"] > thr["import_yellow_factor"] + + +# --- main wiring ------------------------------------------------------------- + +def test_plan_prints_the_ids_to_download(monkeypatch, capsys): + listing = json.dumps({"artifacts": [ + _artifact(id_=1), _artifact("unit-timings-3.13", id_=2), + _artifact("smoke-timings-3.12", id_=3), + ]}) + monkeypatch.setattr("sys.stdin", __import__("io").StringIO(listing)) + assert ut.main(["--plan"]) == 0 + assert capsys.readouterr().out.split("\n")[:2] == [ + "1 unit-timings-3.12", "2 unit-timings-3.13"] + + +def test_plan_says_nothing_on_garbage(monkeypatch, capsys): + monkeypatch.setattr("sys.stdin", __import__("io").StringIO("not json")) + assert ut.main(["--plan"]) == 0 + assert capsys.readouterr().out == "" + + +def test_main_writes_the_sidecar_then_the_rollup_and_both_legacy_files( + 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, sub="11", junit=_junit(_case(time="6.0"))) + + out = per_repo / f"{REPO}.unit_timings.json" + assert ut.main(["--name", REPO, "--group", "libraries", "--owner", OWNER, + "--ts", "T", "--listing", str(listing), + "--downloads", str(downloads), "--out", str(out)]) == 0 + side = json.loads(out.read_text()) + assert side["legs"][0]["slowest"][0]["seconds"] == 6.0 + assert "test(s) tracked" in capsys.readouterr().out + + # The record is the only baseline: one prior observation of the same test. + unit_dir = tmp_path / "timings" / "unit" + unit_dir.mkdir(parents=True) + (unit_dir / 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": "", + "package": PACKAGE, "import_s": 1.0, + "suite": {"tests": 2, "failures": 0, "errors": 0, "skipped": 0, + "wall_s": 40.0}, + "slowest": {NODEID: 2.0}, + }) + "\n") + + legacy = tmp_path / "legacy" + roll_path = tmp_path / "unit_timings.json" + assert ut.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--record-dir", str(tmp_path / "timings"), + "--legacy-dir", str(legacy), "--out", str(roll_path)]) == 0 + roll = json.loads(roll_path.read_text()) + (row,) = roll["tests"] + assert row["state"] == "warn" and row["prev_s"] == 2.0 and row["prev_run_id"] == 6 + assert "tests tracked" in capsys.readouterr().out + + unit = json.loads((legacy / "unit_test_timing.json").read_text()) + imports = json.loads((legacy / "import_time.json").read_text()) + assert set(unit) == LEGACY_UNIT_KEYS and set(imports) == LEGACY_IMPORT_KEYS + # 2.0s → 6.0s is exactly 3.0x: over the legacy section's ">1.5×" wording, + # not over its ">3× baseline" one. + assert unit["yellow_count"] == 1 and unit["red_count"] == 0 + # One recorded observation is below import_min_samples, so the import is + # still building rather than judged. + assert imports["new_packages_no_baseline"] == 1 + + +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}.unit_timings.json" + assert ut.main(["--name", REPO, "--group", "libraries", "--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}.unit_timings.json" + assert ut.main(["--name", REPO, "--group", "libraries", "--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 = ut.build_sidecar(REPO, "libraries", OWNER, [], "T", error="boom") + assert "UNAVAILABLE" in ut.repo_summary_line(dead) + roll = ut.aggregate([dead], "T", THRESHOLDS) + assert "1 unavailable" in ut.summary_line(roll) diff --git a/tests/test_unit_timings_script.py b/tests/test_unit_timings_script.py new file mode 100644 index 00000000..ee766789 --- /dev/null +++ b/tests/test_unit_timings_script.py @@ -0,0 +1,132 @@ +"""tests/test_unit_timings_script.py — the unit shell leg's failure paths. + +The sibling of `test_smoke_timings_script.py`, and it pins the same +load-bearing claim on the other check: ONE artifact's 403 must not cost the repo +its other python leg — the failure is written to `/.error` and +the loop continues. Driven the same way: 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 +from pathlib import Path + +import pytest + +from tests.test_smoke_timings_script import write_stub + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "heart" / "checks" / "unit_timings.sh" + +OWNER_NAME = "OwnerX/RepoA" +REPO = "RepoA" + +LISTING = { + "artifacts": [ + {"id": 1, "name": "unit-timings-3.12", "expired": False, + "created_at": "2026-09-01T10:00:00Z", + "workflow_run": {"id": 7, "head_branch": "feat/x", "head_sha": "abc123"}}, + {"id": 2, "name": "unit-timings-3.13", "expired": False, + "created_at": "2026-09-01T10:00:00Z", + "workflow_run": {"id": 7, "head_branch": "feat/x", "head_sha": "abc123"}}, + ] +} + +JUNIT = ( + '' + '' + '' + "" +) +IMPORT_JSON = {"schema": "import_time/1", "package": "pkg_a", "python": "3.12", + "seconds": 3.6, "returncode": 0, "ts": "2026-09-01T09:55:00Z"} + + +@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 / "junit.xml").write_text(JUNIT) + (tmp_path / "import_time.json").write_text(json.dumps(IMPORT_JSON)) + + 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 stub materialises what a successful extraction leaves behind: both + # halves of the dataset 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}/junit.xml" "$dest/junit.xml" + cp "{tmp_path}/import_time.json" "$dest/import_time.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, "libraries"], + capture_output=True, text=True, env={**os.environ, **env}, + ) + + +def _sidecar(env): + path = (Path(env["HEART_STATE_DIR"]) / "per-repo" / f"{REPO}.unit_timings.json") + return json.loads(path.read_text()) + + +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 = _sidecar(env) + assert side["name"] == REPO and side["error"] == "" + legs = {leg["python"]: leg for leg in side["legs"]} + assert set(legs) == {"3.12", "3.13"} + # The leg that downloaded is intact — both halves of the dataset... + assert legs["3.12"]["slowest"][0]["seconds"] == 12.5 + assert legs["3.12"]["suite"]["tests"] == 2 + assert legs["3.12"]["import"]["package"] == "pkg_a" + assert legs["3.12"]["error"] == "" + # ...and the 403 leg keeps its provenance with an honest error. + assert "403" in legs["3.13"]["error"] and legs["3.13"]["slowest"] == [] + assert legs["3.13"]["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 = _sidecar(env) + assert "502" in side["error"] and side["legs"] == [] diff --git a/timings/README.md b/timings/README.md index cba2d225..804f7c12 100644 --- a/timings/README.md +++ b/timings/README.md @@ -3,7 +3,8 @@ 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. +timing checks as the first source for their baselines (for `unit_timings` it is +the *only* source: the board never carried per-test rows). 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 @@ -21,12 +22,13 @@ carries the same rules for a reader who arrives from the Python side. ``` 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) +timings/scripts/.jsonl # one line per (python leg, run id) — smoke scripts +timings/unit/.jsonl # one line per (python leg, run id) — unit tests + import ``` -`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`, `timings/scripts/` and `timings/unit/` 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 @@ -71,6 +73,37 @@ joined to its `rows` (the timed entries): * `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. +### `unit/.jsonl` — one line per leg per run + +One JSON object per line, from `unit_timings.json`'s `repos` — the rollup the +libraries' own CI feeds through +[`heart/checks/unit_timings.py`](../heart/checks/unit_timings.py): + +```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","package":"pkg_a","import_s":3.62, + "suite":{"tests":1500,"failures":0,"errors":0,"skipped":3,"wall_s":412.0}, + "slowest":{"tests/foo/test_bar.py::test_x":12.5}} +``` + +* **Only the N slowest tests are recorded**, with the suite totals beside them. + A library suite is ~1500 tests; recorded whole, one line would carry 1500 + entries and this file would grow by a megabyte a week for rows nothing reads — + the board shows the slowest handful and the totals. `suite` is what keeps the + coverage visible next to them (a suite that got faster by running fewer tests + must not read as a suite that got faster), and `slowest` maps the pytest node + id to its seconds — the same positional-free shape the drift rule compares + run to run. `top_n` lives in `config/repos.yaml`, never here. +* **`import_s` is the fresh-process cold import** measured on the CI runner: a + new interpreter importing the package once, which is the cost the developer + loop actually pays — not the warm in-process cost a test session amortises. It + is `null`, never `0.0`, when that import failed or timed out; the import + baseline is the **median** of the last `import_window` non-null observations, + which is why a null is skipped rather than carried as a zero. +* A test that drops out of the slowest N simply has no baseline next run. That + is honest: nothing was recorded about it. + ## The two rules ### 1. Append-only @@ -86,8 +119,9 @@ truncates. * `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. +* `scripts/.jsonl` and `unit/.jsonl` are 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. @@ -118,6 +152,10 @@ something a daily job can observe. 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. +* `unit/.jsonl`: the same shape and the same cap — ≤ 2 lines/day/repo, + and only when a new run produced a new artifact. A line is larger than a + scripts line (the slowest N tests plus the suite totals) but bounded by + `top_n`, which is what keeps a 1500-test suite from setting the file size. Yearly sharding (`gates-2026.jsonl`, `scripts/2026/.jsonl`) is the obvious next step if a file ever gets unwieldy. **Not now**: at this growth @@ -137,6 +175,10 @@ jq -r '.date + " " + (.gates["RepoA/Gate One"].p50_s|tostring)' timings/gates.js # 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 + +# One library's suite wall-clock and cold import across the recorded runs. +jq -r '[.run_id, .python, .suite.wall_s, .import_s] | @tsv' \ + timings/unit/RepoA.jsonl ``` The daily job also writes the census to `$HEART_STATE_DIR/timings_record.json`,