Skip to content

feat: bring unit_test_timing + import_time live by ingesting lib-tests.yml artifacts #206

Closed

Description

@Jammy2211

Overview

Three Heart checks are built, tested and documented as "OFF-TICK, run on a daily cron" — and no cron exists anywhere: heart/checks/unit_test_timing.py (never run), heart/checks/import_time.py (ran once, 2026-07-11, autolens "unavailable"), heart/checks/workspace_testmode_timing.py (never run). Their board sections render "not observed here" every day.

The execution home, decided: ingestion, not a new cloud leg. Every library's Tests workflow (PyAutoNerves, PyAutoFit, PyAutoArray, PyAutoGalaxy, PyAutoLens, PyAutoCTI) is a thin caller of this repo's reusable .github/workflows/lib-tests.yml, which already installs the source stack and runs pytest on every push to main and every PR. One change there emits per-test durations (pytest's built-in --junitxml) and a fresh-process import time as a unit-timings-<py> artifact, and the daily heart-health.yml run ingests it exactly the way smoke_timings ingests the smoke artifacts (#203) and records it in the permanent timings/ record (#205). The two board sections come alive in their existing shape; the workspace_testmode_timing leg is retired as superseded — the smoke gates already run the workspace scripts in PYAUTO_TEST_MODE=2 with small datasets on every PR, and the Smoke scripts row (#203) is that measurement.

Phase 3 of the ci-timing-fast-tests epic (PyAutoMind/draft/feature/pyautoheart/ci_timing_fast_tests_epic.md; the Fable review there recorded ingestion-first as the default).

Plan

  • lib-tests.yml (unittest matrix job only): time a fresh-process import <package> before the suite and add --junitxml to the pytest call; upload both as unit-timings-<python-version> with if: always() / if-no-files-found: ignore, so a red suite still records and a broken emit never reds a gate.
  • New check heart/checks/unit_timings.{sh,py} in the smoke_timings shape: per library repo, newest non-expired unit-timings-<py> artifact per leg → parse junit.xml (stdlib xml.etree) and import_time.json → sidecar → aggregate rollup with drift against the record.
  • Extend the timings/ record with timings/unit/<repo>.jsonl (one line per python leg × run id: suite wall-clock, test count, the N slowest tests, import seconds) — same append-only, run-id-deduped rules as scripts/.
  • Write the rollup ALSO into the two existing summary shapes (unit_test_timing.json, import_time.json) so the existing "Unit-test timing" and "Import timing" sections light up unchanged; drop those two families (and workspace_testmode_timing) from LOCAL_ONLY_FAMILIES so the cloud render stops greying them out.
  • Wire the check into heart-health.yml's cloud step and heart.timings append; declared thresholds in config/repos.yaml; tests with fake names.
Detailed implementation plan

Affected Repositories

  • PyAutoHeart (primary, only). The libraries inherit through the reusable workflow — no per-library change.

Work Classification

Library (organ code) — no workspace follow-up.

Branch Survey

Repository Current Branch Dirty?
./PyAutoHeart main @ 7b4e109 clean

Branch: claude/ci-test-timing-epic-ke2lul (designated for the epic; restarted from the merged main; cloud session, no task worktree).

Implementation Steps

  1. .github/workflows/lib-tests.yml — unittest job only (the unittest-nojax leg is a correctness probe, not a timing surface):

    • New step after "Install", before "Run tests": "Time a fresh-process import" — continue-on-error: true; runs python - <<'PY' that spawns subprocess.run([sys.executable, "-c", "import <package>"]) once, timed with time.perf_counter(), and writes <repo>/test-results/import_time.json = {"schema": "import_time/1", "package", "python": "<major.minor>", "seconds": float|null, "returncode": int, "ts"} (a failed import records seconds: null and the returncode — honest, never a fabricated 0). Fresh process, so the number is the cold import cost the developer loop pays; the NUMBA_CACHE_DIR/MPLCONFIGDIR env the dev-box measurer sets is not needed on a runner.
    • "Run tests": append --junitxml=test-results/junit.xml (pytest built-in; the time attribute per <testcase> is setup+call+teardown — documented as "test duration").
    • New step "Upload the unit timings (per-test durations + import time)": if: always(), actions/upload-artifact@v4, name: unit-timings-${{ matrix.python-version }}, path: ${{ steps.map.outputs.repo }}/test-results/, if-no-files-found: ignore, no retention-days (the dataset is the point — same reasoning as smoke-tests.yml). Comment block in the file's voice: why junit and not --durations (machine-readable, every test, no parsing of a console tail), why a fresh process, why if: always().
    • Header comment updated. The workflow is referenced @main by every library, so a mistake here reds six gates at once: keep every new step non-fatal (continue-on-error / if: always()), never touch the pytest exit path, and validate with yaml.safe_load + a wiring test.
  2. heart/checks/unit_timings.py (stdlib only; PyYAML for config; mirror smoke_timings.py):

    • ARTIFACT_RE = re.compile(r"^unit-timings-(\d+\.\d+)$"); reuse smoke_timings.select_artifacts's logic by importing and parametrising it (add an optional pattern argument there, default unchanged) rather than duplicating.
    • parse_junit(text) -> (tests: list[{nodeid, seconds}], suite: {tests, failures, errors, skipped, time}, error) — xml.etree.ElementTree; nodeid = classname::name normalised to pytest's path::test form where classname is dotted (tests.foo.test_bar → tests/foo/test_bar.py::test_x; a class in the middle stays ::Class::test), a malformed file → error. parse_import_time(text) validates schema == "import_time/1".
    • read_downloaded_leg(dir) → (tests, suite, import_row, error, meta); junit may be absent when pytest never ran (install failed) — then the leg records the import row only, and vice versa.
    • build_sidecar(name, group, owner, legs, ts, error="") → <name>.unit_timings.json: {name, group, owner, error, ts, legs: [{python, artifact_id, run_id, run_url, head_branch, head_sha, at, error, suite: {tests, failures, errors, skipped, wall_s}, slowest: [{nodeid, seconds}] (top_n by seconds), import: {package, seconds, returncode}|null}]}. Only the slowest N are kept per leg (a 1500-test suite must not go into the board or the record whole); top_n from config.
    • aggregate(sidecars, prev_rows, ts, thresholds) → unit_timings.json: {ts, repos: [{repo, python, run_id, run_url, head_branch, at, tests, wall_s, import_s, error}], tests: [per slowest test: {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, thresholds}. Test drift: both gates (slow_factor AND min_delta_s) against the previous recorded observation of the same (repo, python, nodeid), run id must differ — ok|warn, advisory. Import drift: ratio of seconds to the median of the last baseline_window recorded observations for (repo, package, python) (the existing import_time doctrine), classified with the existing import_time.classify and its yellow_factor/red_factor (1.5 / 3.0), needing ≥ min_samples (3) recorded observations first — below that the row is building. Prompts: /hygiene perf: <repo> <nodeid> <prev>s → <now>s between runs <prev_run_url> → <run_url> and /hygiene perf: import <package> <baseline>s → <now>s (py<py>) — <run_url> (the hygiene conductor owns dev-loop cost; AGENTS.md:117-119 there names this promotion).
    • Also write the two legacy summaries so the existing dashboard sections render unchanged: unit_test_timing.json = {python: "ci", repos_measured, repos_unavailable, new_tests_no_baseline, red_count, yellow_count, green_count, red: [{repo, test, latest_seconds, baseline_seconds, ratio, samples}], yellow: [...]} where red is the tests over red_factor and yellow those over yellow_factor (ratio-only, matching the section's wording "(>3× baseline)/(>1.5×)"), computed from the same rows; import_time.json = {python: "ci", packages_measured, packages_unavailable, new_packages_no_baseline, red_count, yellow_count, green_count, red, yellow}. One producer, three files; the two legacy files are projections of the rollup (document this in the docstring; a dev-box run of the old checks still writes the same shapes).
    • CLI: --plan, per-repo (--name --group --owner --ts --listing --downloads [--fetch-error] --out), --aggregate [--record-dir] [--legacy-dir DIR] --ts --out (legacy dir = where unit_test_timing.json/import_time.json land, default $HEART_STATE_DIR). Coloured summary lines.
  3. heart/checks/unit_timings.sh — _UNIT_GROUPS="libraries"; otherwise a copy of smoke_timings.sh's loop with the new module name and _UNIT_ARTIFACTS_PATH; aggregate pass with --record-dir "$HEART_HOME/timings". No prev-board fallback is needed here (the record is the only baseline source; the board never carried these rows) — say so in the header.

  4. heart/timings.py — UNIT_DIR = TIMINGS_DIR / "unit", unit_file(repo); unit_lines_from_rollup(rollup, today) -> {repo: [line]} with line {"date", "at", "python", "run_id", "run_url", "head_branch", "head_sha", "package", "import_s": float|null, "suite": {"tests", "failures", "errors", "skipped", "wall_s"}, "slowest": {nodeid: seconds}}; append_unit(path, lines) -> int keyed (python, run_id); readers previous_unit_rows(unit_dir) -> {(repo, python, nodeid): {seconds, run_id, run_url}} (latest line per leg) and import_history(unit_dir, window) -> {(repo, package, python): [seconds, ...]} (last window observations, oldest first, non-null only); census() gains unit_observations and unit_repos; main append gains --unit-timings FILE. timings/README.md gains the unit/ section (schema, the same two rules, why only the N slowest are recorded).

  5. config/repos.yaml — declared block beside smoke_timings:

    unit_timings:
      slow_factor: 2.0      # test seconds / previous observation >= this, AND
      min_delta_s: 2        # ... at least this many seconds slower
      top_n: 25             # slowest tests kept per suite run (record + board)
      import_yellow_factor: 1.5   # import seconds / median of the window
      import_red_factor: 3.0
      import_window: 7            # recorded observations in the baseline
      import_min_samples: 3       # below this the import row is `building`

    Comment: tests are 0.1–30 s, so the floor is 2 s; import factors mirror the dev-box import_time doctrine so a number means the same thing from either vantage.

  6. heart/dashboard.py:

    • Remove import_time, unit_test_timing and workspace_testmode_timing from LOCAL_ONLY_FAMILIES and UNOBS_WATCHES (with a comment: the first two are now cloud-observed by ingestion; the third is superseded by the Smoke scripts row). Their sections keep rendering from the snapshot exactly as today (dev-box or cloud data alike); when the workspace_testmode_timing slice is absent no row renders — the family is retired from the board, not deleted from the codebase.
    • "Unit-test timing" section: add a detail line per repo leg "{repo} py{py}: {tests} tests {wall} slowest {nodeid} {s}" (cap 6) when snapshot["unit_timings"] is present, and "Import timing" gains "{package} py{py}: {s}s" per leg (cap 6). Both sections' state logic unchanged. state.aggregate() adds "unit_timings".
    • The performance block gains an additive "unit": {"schema": 1, "repos", "tests", "imports", "slowed_tests", "slowed_imports", "errors"} emitted only when the slice was observed (older snapshots byte-identical). The Brain board ignores unknown keys.
  7. .github/workflows/heart-health.yml — bash heart/checks/unit_timings.sh after smoke_timings.sh in the cloud step (comment + step name: six checks); heart.timings append gains --unit-timings "$HEART_STATE_DIR/unit_timings.json". The same HEART_TIMINGS_TOKEN || GITHUB_TOKEN applies (the artifacts live on the library repos — same cross-repo 403 risk, same remedy).

  8. Docstrings — unit_test_timing.py, import_time.py, workspace_testmode_timing.py: replace the "run on a daily cron" paragraphs with the truth: the first two are now measured on CI and ingested by unit_timings; the dev-box run stays an on-demand deep probe writing the same summary shape; the third is superseded by smoke_timings and stays on-demand only. docs/internals.md "Adding a new check" untouched.

  9. Tests (fake names): tests/test_unit_timings.py — junit parse (nodeid normalisation incl. a class, malformed → error, suite totals), import json parse (schema, null seconds), artifact selection via the shared selector with the new pattern (smoke names ignored), sidecar keeps only top_n, aggregate: test drift both gates + same run id never compared, import baseline needs min_samples then classifies yellow/red with the existing factors, legacy summaries carry the right counts and shapes (feed them to dashboard.build_board and assert the two sections render OK/WARN/FAIL accordingly), errors per repo/leg, --plan, main modes. tests/test_timings.py — unit lines, dedupe on (python, run_id), previous_unit_rows, import_history window, census keys, append --unit-timings. tests/test_dashboard.py — the three families are no longer in LOCAL_ONLY_FAMILIES; --cloud render with no slices shows no grey rows for them; the new detail lines appear only with the slice; performance.unit present only when observed. tests/test_heart_health_wiring.py — the check runs, the append passes --unit-timings. tests/test_workflow_wiring.py (or new) — lib-tests.yml: import step is continue-on-error, pytest line carries --junitxml, upload named unit-timings-${{ matrix.python-version }} with if: always() and if-no-files-found: ignore. Existing tests unmodified.

Key Files

  • .github/workflows/lib-tests.yml — the emit side (runs in every library's CI context; keep every new step non-fatal).
  • heart/checks/smoke_timings.{py,sh} — the ingest pattern (selector, download loop, sidecar/aggregate, prompts).
  • heart/timings.py + timings/README.md — the record to extend.
  • heart/checks/unit_test_timing.py, heart/checks/import_time.py — the legacy summary shapes and the classify doctrine to reuse; heart/dashboard.py:73-83, 640-735 — LOCAL_ONLY_FAMILIES and the two sections.

Out of scope

  • Measuring the unittest-nojax leg; per-dependency import breakdown inside the autolens job (each library measures its own package).
  • Deleting workspace_testmode_timing.py (retired from the board, kept runnable).
  • The hot-spot analysis itself (phase 9 reads what this records).

Original Prompt

Click to expand starting prompt
# Bring the dead timing legs live: unit_test_timing, import_time, workspace_testmode_timing

Type: feature
Target: PyAutoHeart
Repos:
- PyAutoHeart
Difficulty: medium
Autonomy: safe
Priority: high
Status: formalised
Consequence: judge
Review-minutes: 20
Unattended: ready
Epic: ci-timing-fast-tests
Phase: 3

Bring the dead timing legs live: unit_test_timing, import_time, workspace_testmode_timing on a real schedule.

Three Heart checks are built, tested, and documented as "OFF-TICK, run on a daily cron" —
but no cron exists anywhere (not in `tick.sh`, `daemon.sh`, `bin/`, nor any workflow):
`heart/checks/unit_test_timing.py` (pytest --durations over the 5 libraries; state dir has
0 files, never run), `heart/checks/import_time.py` (ran once 2026-07-11, only 4 packages,
autolens "unavailable"), `heart/checks/workspace_testmode_timing.py` (never run). The
dashboard sections for them exist (`heart/dashboard.py:626-672`) and render "not observed".

Decide the execution home and wire it: either a scheduled cloud job (these run local
suites — a dedicated workflow leg with the source-installed stack) or ingestion of CI
`pytest --durations` output from the libraries' own CI runs, whichever is cheaper to keep
honest. Fix the import_time coverage (all installed packages incl. autolens — recent work
already reduced autolens import time, so the check should now pass and become the
regression guard for it). Their observations join the phase-2 durable history and the
board sections come alive: unit-test run-time stats with slowest-test bottlenecks
highlighted, and import times per package — the "what generally drives run time" surface
the user asked for.

Activity

  1. Jammy2211 commented on Sep 5, 2026

    @Jammy2211
    ContributorAuthor

    Shipped

    PyAutoHeart#207 → cb1d500, merged 2026-09-05 (CI green on both matrix legs; suite 767 → 841).

    • lib-tests.yml (unittest job) now emits the unit-timings-<py> artifact: pytest --junitxml per-test durations plus a fresh-process import time. Every new step is non-fatal; the unittest-nojax job is unchanged.
    • heart/checks/unit_timings.{sh,py} — the sixth cloud-safe check: per library repo and leg, suite wall-clock, the 25 slowest tests, import seconds; both-gates drift for tests, the import_time median-window doctrine for imports (building until 3 recorded runs); /hygiene perf prompts.
    • The existing "Unit-test timing" and "Import timing" board sections render from the same summary shapes the dev-box checks write, and gain per-leg detail lines. import_time, unit_test_timing, workspace_testmode_timing left LOCAL_ONLY_FAMILIES; the last is retired from the board as superseded by the Smoke scripts row (feat(smoke_timings): ingest per-script smoke timings onto the ⏱ board #203).
    • timings/unit/<repo>.jsonl joins the permanent record; heart.timings append --unit-timings.

    Watch: the first Tests run on any library after this merge should carry the unit-timings-3.12/3.13 artifacts with the gate conclusion unaffected; the next heart-health run should show the two rows live (imports building for the first three runs). The cross-repo artifact 403 caveat from #203 applies to the library repos too — same HEART_TIMINGS_TOKEN remedy.

    Phase 3 of the ci-timing-fast-tests epic; phase 4 (the labeled LEGACY snapshot) is next, once a live run has seeded the record.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions