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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 35 additions & 26 deletions .github/workflows/heart-health.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,22 @@ 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
# * step summary — fmt="md" into $GITHUB_STEP_SUMMARY (zero hosting)
# * README — a shields verdict badge + an auto-updated
# <!-- heart:begin -->…<!-- heart:end --> md block
# and commits, beside that block, the day's lines of the PERMANENT timing
# record (timings/gates.jsonl + timings/scripts/<repo>.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/<repo>.jsonl +
# timings/unit/<repo>.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).
#
Expand All @@ -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
Expand Down Expand Up @@ -90,43 +93,48 @@ 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
run: |
# ORDERING: after the checks, before the render. The checks' aggregate
# passes have already READ the record for their baselines, and neither
# can be fooled by today's own line — ci_timing's `history_baseline`
# excludes today's date, and smoke_timings compares by run id and
# refuses to compare a run against itself. So appending here is safe,
# and it lets the render census a record that already includes today.
# 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
Expand All @@ -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: |
Expand Down
90 changes: 89 additions & 1 deletion .github/workflows/lib-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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-<py>` 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:
Expand Down Expand Up @@ -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
Expand All @@ -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 <testcase> 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()
Expand Down
13 changes: 13 additions & 0 deletions config/repos.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 10 additions & 4 deletions heart/checks/import_time.py
Original file line number Diff line number Diff line change
@@ -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-<py>`` 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
Expand Down
12 changes: 10 additions & 2 deletions heart/checks/smoke_timings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-<py>`` artifact per python leg.

Accepts the REST ``{"artifacts": [...]}`` object the shell leg fetches and
Expand All @@ -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-<py>`` regex here rather than
growing a second copy of it that could drift.
"""
if isinstance(listing, dict):
raw = listing.get("artifacts") or []
Expand All @@ -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"):
Expand Down
13 changes: 9 additions & 4 deletions heart/checks/unit_test_timing.py
Original file line number Diff line number Diff line change
@@ -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-<py>`` 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
Expand Down
Loading
Loading