diff --git a/.github/workflows/lib-tests.yml b/.github/workflows/lib-tests.yml index f3709938..34b0d75f 100644 --- a/.github/workflows/lib-tests.yml +++ b/.github/workflows/lib-tests.yml @@ -22,6 +22,21 @@ name: Library Tests (reusable) # 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). +# +# TWO CACHES ride the `unittest` job, both added as non-fatal steps and both +# keyed on a manual epoch salt (PYAUTO_CACHE_EPOCH) so they can be invalidated +# together, exactly as smoke-tests.yml does it: the JAX persistent compilation +# cache, per (runner OS x python leg x jaxlib), and the numba on-disk function +# cache, per (runner OS x full python version). numba stamps every entry with +# its source file's (mtime, size) — which a fresh clone and a fresh pip install +# both change — so a `Stamp source mtimes from content` step rewrites every +# .py's mtime as a hash of its CONTENT: identical content hits, changed content +# misses, and the numba key therefore needs no library-commit component and can +# safely carry a prefix fallback. Both caches are measured before and after the +# run into `test-results/cache_state.json`, the sidecar that rides the +# unit-timings artifact, so every unit-timing row the Heart ingests can say +# whether the leg ran hot or cold instead of reading a cache landing as a +# speedup and its first invalidation as a regression. on: workflow_call: @@ -34,6 +49,11 @@ on: jobs: unittest: runs-on: ubuntu-latest + # The manual salt carried by every cache key below. Bump it to invalidate + # every cache at once — a runner-image change, a cache-format change — in + # one edit instead of hand-editing each key and hoping none was missed. + env: + PYAUTO_CACHE_EPOCH: "1" strategy: fail-fast: false matrix: @@ -99,6 +119,148 @@ jobs: pip install "./$r[${{ steps.map.outputs.extras }}]" done + - name: Resolve cache keys + # Two components, each one a thing that MUST invalidate a cache: + # jaxlib — a cached compilation is a jaxlib-specific artefact, so a + # jaxlib bump must never read the previous wheel's entries; + # pyfull — the FULL python version, because numba keys every cache + # entry on the directory its source was found in and the + # site-packages path carries the patch version. + # No chain hash here, unlike smoke-tests.yml: this workflow has no + # dataset cache, and the content-stamp two steps down makes a library + # commit invalidate exactly the numba entries it changed. + # Non-fatal like every step the caches added: an unresolvable key + # degrades to a cache miss, never to a red gate. + id: keys + continue-on-error: true + run: | + jaxlib="$(python -c 'import jaxlib; print(jaxlib.__version__)' 2>/dev/null || echo nojax)" + pyfull="$(python -c 'import sys; print(sys.version.split()[0])')" + { + echo "jaxlib=${jaxlib:-nojax}" + echo "pyfull=$pyfull" + } >> "$GITHUB_OUTPUT" + + - name: Restore the JAX compile cache + # The run-id suffix makes every save a fresh SUPERSET of what was + # restored (the accumulating-cache pattern): the exact key never hits, + # the restore-keys prefix takes the newest previous entry, and the save + # writes the merged directory back under a new key. Traced code that + # changed simply misses its own entries and recompiles them, so this + # cache needs no invalidation rule of its own. And a PR run reads the + # default branch's caches under GitHub's cache scoping — which is + # exactly what a contributor wants: a first push that is already warm. + uses: actions/cache/restore@v4 + id: jax-cache + continue-on-error: true + with: + path: ${{ github.workspace }}/.pyauto_jax_cache + key: pyauto-jax-${{ runner.os }}-py${{ matrix.python-version }}-jaxlib${{ steps.keys.outputs.jaxlib }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + restore-keys: | + pyauto-jax-${{ runner.os }}-py${{ matrix.python-version }}-jaxlib${{ steps.keys.outputs.jaxlib }}-e${{ env.PYAUTO_CACHE_EPOCH }}- + + - name: Restore the numba cache + # Same accumulating pattern as the compile cache above, and the prefix + # fallback is SAFE for the reason the stamp step below exists: a numba + # entry carries its source file's (mtime, size), the stamp makes that + # mtime a function of the file's content, so a changed file misses its + # own entry however old the restored directory is. That is why this key + # names no library commit — and a numba version bump invalidates its own + # index format on its own terms. + uses: actions/cache/restore@v4 + id: numba-cache + continue-on-error: true + with: + path: ${{ github.workspace }}/.numba_cache + key: pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + restore-keys: | + pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}- + + - name: Stamp source mtimes from content + # numba stamps every cache entry with its source file's + # (st_mtime, st_size) and stores it under a directory named for the + # source's own directory. A fresh clone and a fresh `pip install` both + # give every .py a brand-new mtime, so a restored cache would miss + # EVERY entry it holds — the cache would cost upload time and buy + # nothing. This step rewrites each mtime as a function of the file's + # CONTENT, so an unchanged file stamps identically on every runner and + # a changed one stamps differently: exactly the invalidation numba + # wants, expressed in the one field it already checks. + # + # Non-fatal like the rest: a file we could not stat or touch costs one + # cache entry, never the gate. + id: stamp + continue-on-error: true + env: + # Via env, never interpolated into the script body — the same house + # rule the key resolver above and the recorder below follow. + STAMP_DIRS: ${{ steps.map.outputs.repo }} ${{ steps.map.outputs.deps }} + run: | + python - <<'PY' + import hashlib + import importlib.util + import os + import pathlib + + # The cloned checkouts first: `Run tests` puts them on PYTHONPATH, so + # they are the copies the suite actually imports. + roots = [pathlib.Path(d) for d in os.environ.get("STAMP_DIRS", "").split()] + # ...and the INSTALLED copies beside them, which is what a leg with no + # matching branch imports. `find_spec` on a top-level name resolves it + # WITHOUT importing it, so a package that is not installed here simply + # drops out instead of raising. + for pkg in ("autonerves", "autofit", "autoarray", "autogalaxy", + "autolens", "autocti", "autoreduce"): + try: + spec = importlib.util.find_spec(pkg) + except (ImportError, ValueError): + continue + if spec is None: + continue + roots.extend(pathlib.Path(p) + for p in (spec.submodule_search_locations or [])) + + stamped = 0 + for root in roots: + if not root.is_dir(): + continue + for path in root.rglob("*.py"): + try: + digest = hashlib.sha1(path.read_bytes()).digest() + mtime = 1_000_000_000 + int.from_bytes(digest[:4], "big") + os.utime(path, (mtime, mtime)) + except OSError: + continue + stamped += 1 + print(f"stamped {stamped} source files under {len(roots)} roots") + PY + + - name: Measure the caches before the run + # The "before" half of the sidecar: what a restore actually put on disk, + # as against what the run leaves behind. A missing path measures as + # zero rather than failing — a cold cache is a measurement, not a fault. + id: cache-before + continue-on-error: true + env: + JAX_PATH: ${{ github.workspace }}/.pyauto_jax_cache + NUMBA_PATH: ${{ github.workspace }}/.numba_cache + run: | + measure() { + mb="$(du -sm "$1" 2>/dev/null | cut -f1)" + n="$(find "$1" -type f 2>/dev/null | wc -l)" + echo "${mb:-0} ${n:-0}" + } + set -- $(measure "$JAX_PATH") + jax_mb="$1"; jax_n="$2" + set -- $(measure "$NUMBA_PATH") + numba_mb="$1"; numba_n="$2" + { + echo "jax_mb=$jax_mb" + echo "jax_n=$jax_n" + echo "numba_mb=$numba_mb" + echo "numba_n=$numba_n" + } >> "$GITHUB_OUTPUT" + # 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 @@ -157,6 +319,14 @@ jobs: PY - name: Run tests + env: + # autonerves defaults the JAX cache to ~/.cache/pyauto_jax when it is + # unset; an explicit workspace path is the one the cache steps above + # and below can name. NUMBA_CACHE_DIR likewise moves numba's on-disk + # function cache out of the source trees (where it would be neither + # restorable nor saveable) into the one directory those steps cache. + JAX_COMPILATION_CACHE_DIR: ${{ github.workspace }}/.pyauto_jax_cache + NUMBA_CACHE_DIR: ${{ github.workspace }}/.numba_cache run: | export JAX_ENABLE_X64=True ROOT="$(pwd)" @@ -171,6 +341,110 @@ jobs: pytest --cov ${{ inputs.package }} --cov-report xml:coverage.xml \ --junitxml=test-results/junit.xml + - name: Record cache state (rides the unit-timings artifact) + # This file is the unit of measurement for the whole cache story: every + # unit-timing row the Heart ingests from the artifact below can then say + # whether that leg ran hot or cold. Without it a timing dataset reads a + # cache landing as a speedup and its invalidation as a regression, and + # neither is a change anybody made. + # + # if: always() — a red run's cache state is exactly as interesting as a + # green one's, and the artifact is uploaded either way. + # + # Two sections, not smoke-tests.yml's three: there is no dataset cache + # in this workflow, so there is nothing honest to say under `datasets`. + id: cache-state + if: always() + continue-on-error: true + env: + EPOCH: ${{ env.PYAUTO_CACHE_EPOCH }} + OUT_DIR: ${{ steps.map.outputs.repo }}/test-results + JAX_PATH: ${{ github.workspace }}/.pyauto_jax_cache + JAX_KEY_RESTORED: ${{ steps.jax-cache.outputs.cache-matched-key }} + JAX_EXACT: ${{ steps.jax-cache.outputs.cache-hit }} + JAX_MB_BEFORE: ${{ steps.cache-before.outputs.jax_mb }} + JAX_N_BEFORE: ${{ steps.cache-before.outputs.jax_n }} + NUMBA_PATH: ${{ github.workspace }}/.numba_cache + NUMBA_KEY_RESTORED: ${{ steps.numba-cache.outputs.cache-matched-key }} + NUMBA_EXACT: ${{ steps.numba-cache.outputs.cache-hit }} + NUMBA_MB_BEFORE: ${{ steps.cache-before.outputs.numba_mb }} + NUMBA_N_BEFORE: ${{ steps.cache-before.outputs.numba_n }} + run: | + python - <<'PY' + import json + import os + import subprocess + from pathlib import Path + + + def as_int(text): + try: + return int(str(text).strip()) + except (TypeError, ValueError): + return 0 + + + def measure(path): + """(size in MiB, file count) for a path that may not exist.""" + if not path or not os.path.isdir(path): + return 0, 0 + proc = subprocess.run(["du", "-sm", path], capture_output=True, + text=True) + head = proc.stdout.split() + size = as_int(head[0]) if head else 0 + return size, sum(len(files) for _r, _d, files in os.walk(path)) + + + def section(path, key, exact, mb_before, n_before): + mb_after, n_after = measure(path) + mb_before, n_before = as_int(mb_before), as_int(n_before) + return { + "path": path, + # A restored key at all is a hit; the EXACT key is the + # accumulating pattern's never-case, kept separate so a + # reader is not left guessing which one "hit" meant. + "restored_key": key, + "hit": bool(key), + "exact": exact == "true", + "size_mb_before": mb_before, + "size_mb_after": mb_after, + "entries_before": n_before, + "entries_after": n_after, + }, (mb_after != mb_before or n_after != n_before) + + + env = os.environ.get + jax, jax_changed = section( + env("JAX_PATH", ""), env("JAX_KEY_RESTORED", ""), + env("JAX_EXACT", ""), env("JAX_MB_BEFORE", ""), + env("JAX_N_BEFORE", ""), + ) + numba, numba_changed = section( + env("NUMBA_PATH", ""), env("NUMBA_KEY_RESTORED", ""), + env("NUMBA_EXACT", ""), env("NUMBA_MB_BEFORE", ""), + env("NUMBA_N_BEFORE", ""), + ) + payload = { + "schema": "cache_state/1", + "epoch": env("EPOCH", ""), + "jax": jax, + "numba": numba, + } + out = Path(env("OUT_DIR", "test-results")) + out.mkdir(parents=True, exist_ok=True) + (out / "cache_state.json").write_text( + json.dumps(payload, sort_keys=True, indent=2) + "\n") + print(json.dumps(payload, sort_keys=True)) + + github_output = env("GITHUB_OUTPUT") + if github_output: + with open(github_output, "a", encoding="utf-8") as handle: + handle.write("jax_changed=%s\n" + % ("true" if jax_changed else "false")) + handle.write("numba_changed=%s\n" + % ("true" if numba_changed else "false")) + PY + # 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 @@ -199,6 +473,29 @@ jobs: files: ${{ steps.map.outputs.repo }}/coverage.xml fail_ci_if_error: false + - name: Save the JAX compile cache + # Saved even on a RED run: a compilation-cache entry is complete or + # absent, never half-written, so the compiling a failing run did is + # still worth keeping for the next attempt. The `jax_changed` guard is + # the no-op case — an unchanged cache is not re-uploaded under a new key. + if: always() && steps.cache-state.outputs.jax_changed == 'true' + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/.pyauto_jax_cache + key: pyauto-jax-${{ runner.os }}-py${{ matrix.python-version }}-jaxlib${{ steps.keys.outputs.jaxlib }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + + - name: Save the numba cache + # Saved on a red run for the same reason: a numba cache entry is an + # index line plus a complete compiled artefact, or it is absent. Same + # no-op guard as above. + if: always() && steps.cache-state.outputs.numba_changed == 'true' + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/.numba_cache + key: pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + - name: Slack on failure if: ${{ failure() }} uses: slackapi/slack-github-action@v1.21.0 diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml index b8a96a0f..e8e9ab54 100644 --- a/.github/workflows/smoke-tests.yml +++ b/.github/workflows/smoke-tests.yml @@ -36,20 +36,40 @@ name: Smoke Tests (reusable) # # The workflow filename is intentionally stable for downstream callers. # -# TWO CACHES ride this workflow, both added as non-fatal steps and both keyed +# THREE CACHES ride this workflow, all added as non-fatal steps and all keyed # on a manual epoch salt (PYAUTO_CACHE_EPOCH) so all of them can be invalidated # at once. The JAX persistent compilation cache is restored and saved per # (runner OS x python leg x jaxlib): the runner copies the job env into every # script subprocess, so every script's JAX writes to and reads from the one -# directory named below. The workspace's simulated `dataset/` tree is restored +# directory named below. The numba on-disk function cache is restored and saved +# per (runner OS x full python version); numba stamps every entry with its +# source file's (mtime, size) — which a fresh `pip install` changes — so a +# `Stamp source mtimes from content` step rewrites every installed .py's mtime +# as a hash of its CONTENT, and identical content then hits while changed +# content misses. The workspace's simulated `dataset/` tree is restored # and saved per (simulator-script hash x dependency-chain SHAs), with NO # broader fallback — a different simulator or library commit must miss rather -# than restore FITS this run would not have written. Both are measured before -# and after the run into `test-results/cache_state.json`, the sidecar that -# rides the smoke-timings artifact: every per-script timing row the Heart +# than restore FITS this run would not have written. All three are measured +# before and after the run into `test-results/cache_state.json`, the sidecar +# that rides the smoke-timings artifact: every per-script timing row the Heart # ingests can then say whether that script ran hot or cold, instead of reading # a first cache hit as a 4x speedup and its first invalidation as a 4x # regression. +# +# A FOURTH cache, and the same rules: pip's own wheel cache under ~/.cache/pip. +# It is what the FIXED overhead of this gate is made of. Measured over the six +# most recent smoke runs of one `_test` workspace (12 legs), the seconds spent +# before the first script runs are 104 s mean = 22.6% of the job, and inside +# that: install 83.6 s (80%), the dependency-chain clone 16.5 s (16%), +# everything else ~4 s. So the clones below are `--depth 1` and the wheels the +# install downloads are cached across runs. The PyAuto libraries themselves +# stay SOURCE installs from those clones — the wheels being cached are the +# third-party ones underneath them (jax, numpy, scipy, matplotlib, astropy). +# +# That overhead is now DATA, not a thing to re-measure by hand: `setup_s` in +# the sidecar is job start -> first script, stamped by the two `Mark ...` steps +# below and differenced by the recorder. `null` when either mark is missing — +# an unknown, never a fabricated zero. on: workflow_call: @@ -150,23 +170,51 @@ jobs: matrix: python-version: ${{ fromJSON(inputs.python-versions) }} steps: + # The first half of `setup_s`: the wall clock at the top of the job, + # before anything this workflow does. Differenced against the second mark + # (immediately before the runner) by the recorder below, so how long this + # gate spends getting ready is a measured field in the sidecar rather + # than something a human re-derives from the Actions UI every time. + # + # Non-fatal and env-free, like the other measurement steps: a mark we + # could not write costs one `null` in the sidecar, never the gate. + - name: Mark job start + continue-on-error: true + shell: bash + run: date +%s > "$RUNNER_TEMP/job_start" + - name: Checkout workspace (repo under test, at the PR ref) uses: actions/checkout@v4 with: path: workspace - name: Clone dependency chain + PyAutoHands (matching branch if it exists) + # DEPTH 1, on the clone and on the matching-branch fetch alike: nothing + # downstream reads this history. The libraries are `pip install`ed from + # these trees by the workspace's own epilogue, their version comes from + # `setup.py`'s VERSION env default rather than from `git describe`, and + # the only other reader is `Resolve cache keys`, whose + # `git -C "$dep" rev-parse HEAD` answers on a shallow clone exactly as + # it does on a full one. + # + # The matching-branch fallback is UNCHANGED in meaning — a library PR + # must still be tested against its workspace — but a shallow clone is + # single-branch, so there is no `origin/$BRANCH` for `git checkout` to + # DWIM from and `checkout "$BRANCH"` fails with `did not match any + # file(s) known to git`. `--depth 1` fetch + `checkout -B "$BRANCH" + # FETCH_HEAD` is the sequence that works, verified against a scratch + # shallow clone. shell: bash run: | set -e BRANCH="${{ github.head_ref || github.ref_name }}" OWNER="${{ github.repository_owner }}" for dep in ${{ inputs.chain }} PyAutoHands; do - git clone "https://github.com/$OWNER/$dep" "$dep" + git clone --depth 1 "https://github.com/$OWNER/$dep" "$dep" if git -C "$dep" ls-remote --exit-code --heads origin "$BRANCH" >/dev/null 2>&1; then echo "Branch $BRANCH exists in $dep — checking it out" - git -C "$dep" fetch origin "$BRANCH" - git -C "$dep" checkout "$BRANCH" + git -C "$dep" fetch --depth 1 origin "$BRANCH" + git -C "$dep" checkout -B "$BRANCH" FETCH_HEAD fi done @@ -175,6 +223,46 @@ jobs: with: python-version: ${{ matrix.python-version }} + - name: Restore the pip wheel cache + # The biggest single piece of this gate's fixed cost: the install step + # below is ~84 s per leg and almost all of it is PyPI download + + # wheel-build for the third-party stack under the PyAuto libraries + # (jax, numpy, scipy, matplotlib, astropy...). `~/.cache/pip` is where + # pip keeps those, so restoring it turns most of that step into a local + # copy. The PyAuto libraries themselves are unaffected: the epilogue + # `pip install ./`s them from the clones above, which pip does not + # cache, so a source install stays a source install. + # + # `actions/cache@v4` rather than `setup-python`'s own `cache: pip`, for + # three reasons, all of them properties this file already holds: + # 1. NON-FATAL. Eleven required checks ride this workflow and every + # cache step here is `continue-on-error: true`. A `cache:` inside + # setup-python cannot be, and a `cache-dependency-path` that + # matches NO file is a hard error in that action ("No file in ... + # matched to [...]") — while the chain is a caller-supplied input, + # so the set of files that will exist is not this file's to know. + # 2. The EPOCH SALT. Every cache here is keyed on + # PYAUTO_CACHE_EPOCH so all of them invalidate in one edit; + # setup-python's key is its own and cannot carry it. + # 3. One key shape, read the same way as the other three. + # + # Keyed on the CONTENT of the dependency declarations (the libraries + # ship their dependencies in `pyproject.toml`, not in a requirements + # file — the globs below name both shapes plus any the workspace + # carries), so a dependency change misses and everything else hits. + # `hashFiles()` returns "" when nothing matches, which is a constant + # key rather than an error; the prefix fallback then carries the run. + # This step is AFTER the clone above, so the chain's files exist when + # the expression resolves. + uses: actions/cache@v4 + id: pip-cache + continue-on-error: true + with: + path: ~/.cache/pip + key: pyauto-pip-${{ runner.os }}-py${{ matrix.python-version }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ hashFiles('*/pyproject.toml', '*/setup.py', 'workspace/requirements*.txt', 'workspace/**/requirements*.txt') }} + restore-keys: | + pyauto-pip-${{ runner.os }}-py${{ matrix.python-version }}-e${{ env.PYAUTO_CACHE_EPOCH }}- + # arcticpy is a stack-level system dependency with a fiddly, easy-to-drift # build recipe — it belongs to Heart, not to each workspace's epilogue. # Gated the same way lib-tests.yml gates its own arcticpy step, so every @@ -193,9 +281,12 @@ jobs: bash workspace/.github/scripts/smoke_install.sh - name: Resolve cache keys - # Three components, each one a thing that MUST invalidate a cache: + # Four components, each one a thing that MUST invalidate a cache: # jaxlib — a cached compilation is a jaxlib-specific artefact, so a # jaxlib bump must never read the previous wheel's entries; + # pyfull — the FULL python version, because numba keys every cache + # entry on the directory its source was found in and the + # site-packages path carries the patch version; # chain — the dependency-chain commit SHAs, because a library commit # can change what a simulator writes into dataset/; # sims — the hash of every simulator script in the workspace, @@ -213,9 +304,11 @@ jobs: SIMS_HASH: ${{ hashFiles('workspace/**/simulator*.py', 'workspace/**/simulator/**', 'workspace/**/simulators/**') }} run: | jaxlib="$(python -c 'import jaxlib; print(jaxlib.__version__)' 2>/dev/null || echo nojax)" + pyfull="$(python -c 'import sys; print(sys.version.split()[0])')" chain="$(for dep in $CHAIN; do git -C "$dep" rev-parse HEAD; done | sha256sum | cut -c1-16)" { echo "jaxlib=${jaxlib:-nojax}" + echo "pyfull=$pyfull" echo "chain=$chain" echo "sims=$SIMS_HASH" } >> "$GITHUB_OUTPUT" @@ -259,6 +352,23 @@ jobs: restore-keys: | pyauto-datasets-${{ runner.os }}-e${{ env.PYAUTO_CACHE_EPOCH }}-sim${{ steps.keys.outputs.sims }}-chain${{ steps.keys.outputs.chain }}- + - name: Restore the numba cache + # Same accumulating pattern as the compile cache above, and the prefix + # fallback is SAFE for the reason the stamp step below exists: a numba + # entry carries its source file's (mtime, size), the stamp makes that + # mtime a function of the file's content, so a changed file misses its + # own entry however old the restored directory is. That is why this key + # names no library commit — and a numba version bump invalidates its own + # index format on its own terms. + uses: actions/cache/restore@v4 + id: numba-cache + continue-on-error: true + with: + path: ${{ github.workspace }}/.numba_cache + key: pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + restore-keys: | + pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}- + - name: Measure the caches before the run # The "before" half of the sidecar: what a restore actually put on disk, # as against what the run leaves behind. A missing path measures as @@ -267,6 +377,7 @@ jobs: continue-on-error: true env: JAX_PATH: ${{ github.workspace }}/.pyauto_jax_cache + NUMBA_PATH: ${{ github.workspace }}/.numba_cache DS_PATH: workspace/dataset run: | measure() { @@ -276,17 +387,86 @@ jobs: } set -- $(measure "$JAX_PATH") jax_mb="$1"; jax_n="$2" + set -- $(measure "$NUMBA_PATH") + numba_mb="$1"; numba_n="$2" set -- $(measure "$DS_PATH") ds_mb="$1"; ds_n="$2" { echo "jax_mb=$jax_mb" echo "jax_n=$jax_n" + echo "numba_mb=$numba_mb" + echo "numba_n=$numba_n" echo "ds_mb=$ds_mb" echo "ds_n=$ds_n" } >> "$GITHUB_OUTPUT" + - name: Stamp source mtimes from content + # numba stamps every cache entry with its source file's + # (st_mtime, st_size) and stores it under a directory named for the + # source's own directory. The workspace's own `smoke_install.sh` does a + # `pip install ./` per library, which gives every installed .py a + # brand-new mtime, so a restored numba cache would miss EVERY entry it + # holds — it would cost upload time and buy nothing. This step rewrites + # each mtime as a function of the file's CONTENT, so an unchanged file + # stamps identically on every runner and a changed one stamps + # differently: exactly the invalidation numba wants, expressed in the + # one field it already checks. + # + # Non-fatal like the rest: a file we could not stat or touch costs one + # cache entry, never the gate. + id: stamp + continue-on-error: true + env: + # Nothing here but the installed packages, found below: the chain is + # `pip install`ed by the workspace's epilogue and the runner's own + # PYTHONPATH names only PyAutoHands, so the clones are not what the + # scripts import. Via env, never interpolated into the script body — + # the same house rule the key resolver and the recorder follow. + STAMP_DIRS: "" + run: | + python - <<'PY' + import hashlib + import importlib.util + import os + import pathlib + + roots = [pathlib.Path(d) for d in os.environ.get("STAMP_DIRS", "").split()] + # The INSTALLED copies, which is what every script imports. + # `find_spec` on a top-level name resolves it WITHOUT importing it, so + # a package this workspace does not install simply drops out instead + # of raising. + for pkg in ("autonerves", "autofit", "autoarray", "autogalaxy", + "autolens", "autocti", "autoreduce"): + try: + spec = importlib.util.find_spec(pkg) + except (ImportError, ValueError): + continue + if spec is None: + continue + roots.extend(pathlib.Path(p) + for p in (spec.submodule_search_locations or [])) + + stamped = 0 + for root in roots: + if not root.is_dir(): + continue + for path in root.rglob("*.py"): + try: + digest = hashlib.sha1(path.read_bytes()).digest() + mtime = 1_000_000_000 + int.from_bytes(digest[:4], "big") + os.utime(path, (mtime, mtime)) + except OSError: + continue + stamped += 1 + print(f"stamped {stamped} source files under {len(roots)} roots") + PY + - name: Prepare cache dirs - run: mkdir -p /tmp/numba_cache /tmp/matplotlib + # numba's directory is no longer among these: it is the restored and + # saved cache above, under the workspace, and the cache action creates + # it. Matplotlib's stays — it is scratch, wanted only so the backend + # does not try to write into a read-only home. + run: mkdir -p /tmp/matplotlib - name: Validate env profiles (strict — PyAutoHands#161 step 5) # Binding PR-time config gate for every workspace that carries a smoke @@ -315,6 +495,16 @@ jobs: echo "No config/build/profile_smoke.yaml — profile validation skipped." fi + # The second half of `setup_s`. Placed IMMEDIATELY before the runner and + # nowhere else: the runner step's own command is the one thing in this + # workflow that must stay byte-identical (a workspace owns its runner), + # so the mark cannot live inside it and every step between the two marks + # is honestly part of the setup being measured. + - name: Mark scripts start + continue-on-error: true + shell: bash + run: date +%s > "$RUNNER_TEMP/scripts_start" + - name: Run the workspace runner (the smoke runner by default) env: JAX_ENABLE_X64: "True" @@ -324,7 +514,11 @@ jobs: # This runner is the other surface that executes workspace scripts # under JAX, so it needs the same treatment. JAX_TRACEBACK_FILTERING: "off" - NUMBA_CACHE_DIR: /tmp/numba_cache + # The restored-and-saved directory, not a per-run temporary: the + # runner copies this job env into every script subprocess, so all + # of them share the one numba cache the steps above and below + # carry between runs. + NUMBA_CACHE_DIR: ${{ github.workspace }}/.numba_cache MPLCONFIGDIR: /tmp/matplotlib PYTHONPATH: ${{ github.workspace }}/PyAutoHands/autohands # autonerves defaults this to ~/.cache/pyauto_jax when it is unset; an @@ -358,6 +552,11 @@ jobs: # # if: always() — a red run's cache state is exactly as interesting as a # green one's, and the artifact is uploaded either way. + # + # It also carries `setup_s`: the seconds from job start to the first + # script, differenced from the two `Mark ...` marks. The marks are + # non-fatal, so either may be absent; `null` then says so, because a + # fabricated 0 would read as a gate with no fixed cost at all. id: cache-state if: always() continue-on-error: true @@ -368,6 +567,11 @@ jobs: JAX_EXACT: ${{ steps.jax-cache.outputs.cache-hit }} JAX_MB_BEFORE: ${{ steps.cache-before.outputs.jax_mb }} JAX_N_BEFORE: ${{ steps.cache-before.outputs.jax_n }} + NUMBA_PATH: ${{ github.workspace }}/.numba_cache + NUMBA_KEY_RESTORED: ${{ steps.numba-cache.outputs.cache-matched-key }} + NUMBA_EXACT: ${{ steps.numba-cache.outputs.cache-hit }} + NUMBA_MB_BEFORE: ${{ steps.cache-before.outputs.numba_mb }} + NUMBA_N_BEFORE: ${{ steps.cache-before.outputs.numba_n }} DS_PATH: workspace/dataset DS_KEY_RESTORED: ${{ steps.dataset-cache.outputs.cache-matched-key }} DS_EXACT: ${{ steps.dataset-cache.outputs.cache-hit }} @@ -417,22 +621,55 @@ jobs: }, (mb_after != mb_before or n_after != n_before) + def setup_seconds(): + """Job start -> first script, in whole seconds, or None. + + Both marks are written by non-fatal steps, so a missing or + unreadable one is an unknown rather than a zero. A negative or + absurd difference is discarded for the same reason: it would be + a clock we do not trust, not a measurement. + """ + temp = os.environ.get("RUNNER_TEMP") or "" + if not temp: + return None + stamps = [] + for name in ("job_start", "scripts_start"): + try: + stamps.append(int(Path(temp, name).read_text().strip())) + except (OSError, TypeError, ValueError): + return None + delta = stamps[1] - stamps[0] + return delta if delta >= 0 else None + + env = os.environ.get jax, jax_changed = section( env("JAX_PATH", ""), env("JAX_KEY_RESTORED", ""), env("JAX_EXACT", ""), env("JAX_MB_BEFORE", ""), env("JAX_N_BEFORE", ""), ) + numba, numba_changed = section( + env("NUMBA_PATH", ""), env("NUMBA_KEY_RESTORED", ""), + env("NUMBA_EXACT", ""), env("NUMBA_MB_BEFORE", ""), + env("NUMBA_N_BEFORE", ""), + ) datasets, ds_changed = section( env("DS_PATH", ""), env("DS_KEY_RESTORED", ""), env("DS_EXACT", ""), env("DS_MB_BEFORE", ""), env("DS_N_BEFORE", ""), ) + # The schema string does not move: a `numba` section is ADDITIVE, and + # an ingest that predates it reads the two sections it knows and the + # absence of the third honestly (see heart/checks/smoke_timings.py). payload = { "schema": "cache_state/1", "epoch": env("EPOCH", ""), "jax": jax, + "numba": numba, "datasets": datasets, + # Additive like `numba` was: the schema string does not move, and + # an ingest that predates this field reads its absence honestly. + "setup_s": setup_seconds(), } out = Path("workspace/test-results") out.mkdir(parents=True, exist_ok=True) @@ -445,6 +682,8 @@ jobs: with open(github_output, "a", encoding="utf-8") as handle: handle.write("jax_changed=%s\n" % ("true" if jax_changed else "false")) + handle.write("numba_changed=%s\n" + % ("true" if numba_changed else "false")) handle.write("ds_changed=%s\n" % ("true" if ds_changed else "false")) PY @@ -496,6 +735,17 @@ jobs: path: ${{ github.workspace }}/.pyauto_jax_cache key: pyauto-jax-${{ runner.os }}-py${{ matrix.python-version }}-jaxlib${{ steps.keys.outputs.jaxlib }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + - name: Save the numba cache + # Saved on a red run for the same reason as the compile cache: a numba + # cache entry is an index line plus a complete compiled artefact, or it + # is absent. Same no-op guard as above. + if: always() && steps.cache-state.outputs.numba_changed == 'true' + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: ${{ github.workspace }}/.numba_cache + key: pyauto-numba-${{ runner.os }}-py${{ steps.keys.outputs.pyfull }}-e${{ env.PYAUTO_CACHE_EPOCH }}-${{ github.run_id }} + - name: Save simulated datasets # ONLY on a green run, unlike the compile cache above: a simulator # killed mid-write leaves a truncated FITS on disk, `should_simulate` diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 445a8086..3cbbd9a7 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -54,12 +54,29 @@ render produces, so a Pages gap loses it. The board stays as the fallback, and the ``performance.scripts.rows`` block is written either way. * **Drift is never classified across two known but different cache states.** - The smoke workflow restores a JAX compile cache and the simulated datasets, - and writes ``cache_state.json`` beside the timings dataset in the same - artifact. A cold run against a hot baseline is a recompile and a hot run - against a cold one is the cache landing; neither is a change anybody made, so - both yield ``ok`` with no ratio. An ``unknown`` on either side — every - artifact older than the sidecar — compares exactly as it always did. + The smoke workflow restores a JAX compile cache, a numba function cache and + the simulated datasets, and writes ``cache_state.json`` beside the timings + dataset in the same artifact. A cold run against a hot baseline is a + recompile and a hot run against a cold one is the cache landing; neither is a + change anybody made, so both yield ``ok`` with no ratio. An ``unknown`` on + either side — every artifact older than the sidecar — compares exactly as it + always did. + + The sidecar carries one section per cache (``jax``, ``numba``, ``datasets``), + each ``{"hit", "exact", "restored_key", "size_mb_before/after", + "entries_before/after"}``, plus the ``epoch`` salt those keys were built + with and ``setup_s`` — the seconds from job start to the first script, i.e. + this gate's FIXED overhead (checkout, dependency-chain clone, python setup, + install), measured by the workflow's two mark steps and differenced by its + recorder. It rides here rather than in the timings dataset because it is a + property of the leg, not of any script in it, and because it is the number + the cache work is judged on. ``null``/absent is ``None``, never 0. ``jax`` and ``datasets`` have been written on every run since the + sidecar existed, so a MISSING section of either is a miss; ``numba`` was + added later, so a missing ``numba`` section is ``unknown`` — an older + emitter, not a run that restored nothing. Which cache a comparison turns on + is the consumer's business: the script rows compare on ``jax`` alone + (``classify_drift``'s ``prev_cache_key``), the unit rows on jax and numba + combined (``heart.timings.unit_cache_state``). * **Drift is advisory.** Rows are ``ok`` or ``warn``, never ``fail``; only TIMEOUT entries are hard rows. The readiness verdict is untouched — this is a dashboard leg, not a gate. @@ -80,7 +97,8 @@ "head_branch": "feat/x", "head_sha": "abc...", "at": "2026-09-01T10:00:00Z", # the artifact's created_at "env_profile": "smoke", "error": "", - "cache": {"jax": "hit", "datasets": "miss", "epoch": "1"}, + "cache": {"jax": "hit", "datasets": "miss", "numba": "hit", + "epoch": "1"}, "entries": [{"entry": "imaging/x.py", "kind": "script", "status": "passed", "seconds": 12.5, "cap_s": 600.0, "exit_code": 0}], @@ -134,10 +152,13 @@ TIMINGS_FILENAME = "smoke_timings.json" TIMINGS_SCHEMA = "smoke_timings/1" -# The cache-state sidecar the smoke workflow writes beside the timings dataset -# and uploads in the same artifact: whether this leg ran with a restored JAX -# compile cache and a restored dataset tree, or cold. A run that recompiled -# everything is not a slower run, it is a differently-conditioned one. +# The cache-state sidecar BOTH reusable workflows write beside their timings +# dataset and upload in the same artifact: whether this leg ran with a restored +# JAX compile cache, a restored numba function cache and (in the smoke gate) a +# restored dataset tree, or cold. A run that recompiled everything is not a +# slower run, it is a differently-conditioned one. The schema string is +# unchanged by the numba section: it is purely additive, and an older sidecar +# without it stays readable. CACHE_STATE_FILENAME = "cache_state.json" CACHE_STATE_SCHEMA = "cache_state/1" @@ -321,15 +342,45 @@ def parse_timings(text: str) -> tuple[dict[str, Any] | None, str]: ) +def _setup_seconds(value: Any) -> float | None: + """A sidecar's ``setup_s`` as a float, or ``None`` for every other reading. + + Written by another organ on a runner we do not control, so the same + defensive shape as everything else here: a bool, a string, a NaN, a + negative difference or an absent field are all "we do not know how long + this leg spent getting ready", which is exactly what ``None`` says. + """ + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + seconds = float(value) + if seconds != seconds or seconds in (float("inf"), float("-inf")): + return None + return seconds if seconds >= 0 else None + + def parse_cache_state(text: str) -> tuple[dict[str, Any] | None, str]: """One ``cache_state.json`` → (state, "") or (None, reason). The same defensive shape as ``parse_timings``: the file is written by another organ on a runner we do not control, so a surprising value degrades to a miss rather than raising out of an unattended check. A section is a - ``hit`` exactly when it says so — an absent or malformed section is a miss, - because the workflow writes both sections on every run and their absence is - not evidence that anything was restored. + ``hit`` exactly when it says so — an absent or malformed ``jax`` or + ``datasets`` section is a miss, because the workflows have written both on + every run since the sidecar existed and their absence is not evidence that + anything was restored. + + ``numba`` is the exception, and deliberately so: it was added to the + schema later, so a sidecar without it is an OLDER EMITTER rather than a run + that restored nothing, and the honest reading of its absence is + ``unknown``. Reading it as a miss would date-stamp every pre-numba artifact + as cold and quietly suppress the drift comparisons those legs can still + make. + + ``setup_s`` follows the same additive rule and the same honesty: a float + when the emitter measured the gate's fixed overhead, ``None`` when it did + not (an older emitter, a mark step that could not write) or when the value + is not a finite non-negative number. Never 0 — a gate with no fixed cost is + not a thing that happens, so a fabricated zero would be a claim. """ try: data = json.loads(text) @@ -348,27 +399,49 @@ def _section(key: str) -> tuple[str, str]: jax_state, jax_key = _section("jax") ds_state, ds_key = _section("datasets") + numba_block = data.get("numba") + if isinstance(numba_block, dict): + numba_state = "hit" if numba_block.get("hit") else "miss" + numba_key = str(numba_block.get("restored_key") or "") + else: + # Additive section, absent from every sidecar written before it: not a + # miss, which would be a claim about a cache the emitter never had. + numba_state, numba_key = UNKNOWN_CACHE_STATE, "" return ( { "jax": jax_state, "datasets": ds_state, + "numba": numba_state, + "setup_s": _setup_seconds(data.get("setup_s")), # The manual salt in force. A bump means every key changed at once, # so a miss on both sides is expected rather than a finding. "epoch": str(data.get("epoch") or ""), "jax_restored_key": jax_key, "datasets_restored_key": ds_key, + "numba_restored_key": numba_key, }, "", ) -def cache_view(cache: Any) -> dict[str, str]: - """A cache state normalised to the three keys every consumer carries. +def cache_view(cache: Any) -> dict[str, Any]: + """A cache state normalised to the five keys every consumer carries. Anything that is not one of the two known states reads ``unknown``: a leg - from before the sidecar existed, a truncated file, a future schema. The - epoch rides along because a comparison across an epoch bump is comparing - two different worlds, and the reader needs to be able to see that. + from before the sidecar existed, a truncated file, a future schema, a + ``numba`` section the emitter did not write. The epoch rides along because + a comparison across an epoch bump is comparing two different worlds, and + the reader needs to be able to see that. + + ``datasets`` is carried for every leg including the libraries', whose + workflow has no dataset cache at all: it is the sidecar's own reading, and + the unit consumers simply do not read that key (see + ``heart.timings.unit_cache_state``). + + ``setup_s`` rides the same block for the same reason the states do — it is + a property of the leg, taken at the same moment, by the same emitter — and + is ``None`` wherever it is absent or unreadable. It is the only non-string + value here, so a consumer that renders this block reads it by name. """ src = cache if isinstance(cache, dict) else {} @@ -377,10 +450,11 @@ def _state(key: str) -> str: return value if value in CACHE_STATES else UNKNOWN_CACHE_STATE return {"jax": _state("jax"), "datasets": _state("datasets"), - "epoch": str(src.get("epoch") or "")} + "numba": _state("numba"), "epoch": str(src.get("epoch") or ""), + "setup_s": _setup_seconds(src.get("setup_s"))} -def read_cache_state(directory: Path | str) -> dict[str, str]: +def read_cache_state(directory: Path | str) -> dict[str, Any]: """The first parseable ``cache_state.json`` under one extracted artifact. Sorted path order, first file that parses wins — the same rule the timings @@ -607,6 +681,7 @@ def classify_drift( thresholds: dict[str, float], run_id: Any = None, cache: Any = None, + prev_cache_key: str = "cache_jax", ) -> tuple[str, float | None, float | None]: """(state, ratio, delta_s) — ``warn`` needs BOTH gates, else ``ok``. @@ -616,13 +691,23 @@ def classify_drift( comparing a run against itself would report a reassuring 1.0× that means nothing. Never ``fail`` — a slowed script is advisory by construction. - ``cache`` is THIS run's JAX cache state (``"hit"``/``"miss"``/``"unknown"``) - and is compared against the previous row's ``cache_jax``. Two KNOWN and - DIFFERENT states are not a comparison: a cold run against a hot baseline is - a recompile, and a hot run against a cold one is the cache landing. Neither - is a change anybody made, and reporting either as drift would cry wolf on - exactly the runs where the cache is doing its job. An unknown on either - side compares as it always did — every artifact older than the sidecar. + ``cache`` is THIS run's cache state (``"hit"``/``"miss"``/``"unknown"``) + and is compared against the previous row's, read under ``prev_cache_key``. + Two KNOWN and DIFFERENT states are not a comparison: a cold run against a + hot baseline is a recompile, and a hot run against a cold one is the cache + landing. Neither is a change anybody made, and reporting either as drift + would cry wolf on exactly the runs where the cache is doing its job. An + unknown on either side compares as it always did — every artifact older + than the sidecar. + + ``prev_cache_key`` exists because the two callers turn on different + states and must say so in the row rather than in a comment. A script row's + baseline records the JAX cache alone under ``cache_jax`` (the default, + unchanged); a unit row's records jax and numba COMBINED under + ``cache_state``, and calling that field ``cache_jax`` would name it after + half of what it means. One parameter is the smaller honest change: the + alternative — writing the combined state into a field called ``cache_jax`` + — would make every reader of the record wrong. """ now = _as_float(seconds) if not isinstance(prev_row, dict): @@ -634,7 +719,7 @@ def classify_drift( if run_id is not None and prev_run is not None and prev_run == run_id: return "ok", None, None now_cache = str(cache or "") - prev_cache = str(prev_row.get("cache_jax") or "") + prev_cache = str(prev_row.get(prev_cache_key) or "") if (now_cache in CACHE_STATES and prev_cache in CACHE_STATES and now_cache != prev_cache): return "ok", None, None diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py index d0141703..50a00465 100644 --- a/heart/checks/unit_timings.py +++ b/heart/checks/unit_timings.py @@ -45,6 +45,15 @@ 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. +* **Nor across two known but different cache states.** ``lib-tests.yml`` + restores a JAX compile cache and a numba function cache and writes the same + ``cache_state.json`` sidecar the smoke gate writes, in the same artifact. A + leg is ``hit`` only when it had BOTH and ``miss`` only when it had NEITHER + (``heart.timings.unit_cache_state``); every mixture is ``unknown`` and + compares as it always did. The combined state rides the record — and + therefore the previous row — under ``cache_state``, which is why + ``classify_drift`` is called with ``prev_cache_key="cache_state"`` rather + than its scripts-side default of ``cache_jax``. * **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×. @@ -78,6 +87,8 @@ "head_branch": "feat/x", "head_sha": "abc...", "at": "2026-09-01T10:00:00Z", # the artifact's created_at "error": "", + "cache": {"jax": "hit", "datasets": "miss", "numba": "hit", + "epoch": "1"}, "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, "wall_s": 412.0}, "slowest": [{"nodeid": "tests/foo/test_bar.py::test_x", @@ -90,7 +101,8 @@ {"ts", "repos": [{repo, python, run_id, run_url, head_branch, head_sha, at, - tests, wall_s, import_s, package, error, suite, slowest}], + tests, wall_s, import_s, package, error, cache, 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, @@ -98,8 +110,9 @@ "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. +``repos[]`` carries ``suite``, ``slowest`` and ``cache`` 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 @@ -121,8 +134,13 @@ # 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 cache_view, read_cache_state from heart.checks.smoke_timings import classify_drift as classify_test_drift from heart.checks.smoke_timings import select_artifacts as _select_artifacts +# `heart.timings` imports nothing from `heart`, so this direction is the one +# with no cycle: the record owns the rule for combining the two cache states +# because the record is what writes it into every previous row. +from heart.timings import unit_cache_state HEART_HOME = Path(__file__).resolve().parents[2] CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" @@ -333,7 +351,7 @@ def parse_import_time(text: str) -> tuple[dict[str, Any] | None, str]: def read_downloaded_leg( directory: Path | str, -) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, Any] | None, str, dict[str, str]]: +) -> tuple[list[dict[str, Any]], dict[str, Any], dict[str, Any] | None, str, dict[str, Any]]: """One extracted artifact → ``(tests, suite, import_row, error, meta)``. The two halves are read independently ON PURPOSE. An install that died @@ -341,7 +359,14 @@ def read_downloaded_leg( 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``. + honest ``no unit-timings dataset`` — and that verdict is taken BEFORE the + cache sidecar is looked at, because a sidecar without a dataset beside it + is cache state for a measurement that does not exist. + + ``meta["cache"]`` is the leg's cache state, read from the same + ``cache_state.json`` sidecar the smoke gate writes and by the same reader — + ``unknown`` throughout when no sidecar rode along, which is every artifact + older than it. """ root = Path(directory) tests: list[dict[str, Any]] = [] @@ -373,7 +398,8 @@ def read_downloaded_leg( if not junit_paths and not import_paths: return [], {}, None, NO_DATASET_ERROR, {} - meta = {"python": str((import_row or {}).get("python") or "")} + meta = {"python": str((import_row or {}).get("python") or ""), + "cache": read_cache_state(root)} return tests, suite, import_row, "; ".join(errors), meta @@ -454,7 +480,7 @@ def build_sidecar( tests: list[dict[str, Any]] = [] suite: dict[str, Any] = {} import_row: dict[str, Any] | None = None - meta: dict[str, str] = {} + meta: dict[str, Any] = {} if not leg_error: directory = leg.get("dir") if directory: @@ -472,6 +498,9 @@ def build_sidecar( "head_sha": str(art.get("head_sha") or ""), "at": str(art.get("created_at") or ""), "error": leg_error, + # A leg whose download failed has no sidecar either: "unknown" + # on every side, never a fabricated miss. + "cache": meta.get("cache") or cache_view(None), "suite": suite, "slowest": slowest[: max(int(top_n or 0), 0)], "import": ( @@ -573,6 +602,10 @@ def _name_of(side: Any) -> str: run_url = str(leg.get("run_url") or "") at = str(leg.get("at") or "") leg_error = str(leg.get("error") or "") + leg_cache = cache_view(leg.get("cache")) + # jax AND numba, combined: a suite is comparable to its baseline + # only when both ran the same way (see `unit_cache_state`). + leg_cache_state = unit_cache_state(leg_cache) if leg_error: # Provenance survives: which run we could not read, and why. errors.append({"repo": repo, "error": f"{python or '?'}: {leg_error}"}) @@ -588,7 +621,8 @@ def _name_of(side: Any) -> str: continue prev_row = prev_rows.get((repo, python, nodeid)) state, ratio, delta = classify_test_drift( - seconds, prev_row, thr, run_id=run_id + seconds, prev_row, thr, run_id=run_id, + cache=leg_cache_state, prev_cache_key="cache_state", ) prev_s = _as_float((prev_row or {}).get("seconds")) prev_run_id = (prev_row or {}).get("run_id") @@ -648,6 +682,7 @@ def _name_of(side: Any) -> str: "error": leg_error, # Carried whole so `heart.timings` can build the committed # record from the rollup alone, without re-reading a sidecar. + "cache": leg_cache, "suite": dict(suite), "slowest": [{"nodeid": str(row.get("nodeid") or ""), "seconds": _as_float(row.get("seconds"))} diff --git a/heart/dashboard.py b/heart/dashboard.py index aac21f48..92610bca 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -360,6 +360,46 @@ def _dur(seconds: Any) -> str: UNIT_DETAIL_CAP = 6 +def _setup_seconds(cache): + """A leg's measured setup seconds out of its cache block, or ``None``. + + The block is read straight off the published board or a fresh snapshot, so + it may be anything at all: only a finite non-negative number is a + measurement, and everything else — absent, a string, a bool — is the + honest unknown that renders nothing. + """ + src = cache if isinstance(cache, dict) else {} + value = src.get("setup_s") + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + seconds = float(value) + if seconds != seconds or seconds in (float("inf"), float("-inf")): + return None + return seconds if seconds >= 0 else None + + +def _cache_bracket(cache: Any, jax_label: str = "jax") -> str: + """`` [jax hit, numba miss]`` for the states that are KNOWN, else ``""``. + + Hot or cold, said on the line the numbers are on: a leg that ran with a + restored compile cache is not comparable to one that recompiled, and a + reader looking at a jump needs that beside the seconds rather than a click + away. Only known states are named — a leg from before the cache-state + sidecar existed, or from before the numba cache was added, renders exactly + as it always did. + + ``jax_label`` is the scripts row's ``jax cache`` wording, kept verbatim so + that row is unchanged for every leg whose numba state is unknown. + """ + src = cache if isinstance(cache, dict) else {} + parts = [] + for key, label in (("jax", jax_label), ("numba", "numba")): + value = str(src.get(key) or "") + if value in ("hit", "miss"): + parts.append(f"{label} {value}") + return f" [{', '.join(parts)}]" if parts else "" + + def _unit_suite_details(slice_: Any) -> list[str]: """One line per ingested suite leg, slowest wall-clock first. @@ -380,7 +420,11 @@ def _unit_suite_details(slice_: Any) -> list[str]: 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'))}" + # Same bracket as the scripts row, in the shorter wording a unit line + # can afford: `RepoA py3.12 [jax hit, numba miss]: 1500 tests 6m52s`. + bracket = _cache_bracket(leg.get("cache")) + line = (f"{repo} py{python}{bracket}: " + f"{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] @@ -1102,14 +1146,21 @@ def _smoke_timings_section(st: dict, repos: list[dict], rows: list[dict], # Coverage beside time, always: a leg that got faster by running less # must not read as a leg that got faster. tail = f"({_as_int(r.get('timed'))} scripts, {_dur(r.get('total_s'))} total)" - # Hot or cold, said on the line the numbers are on: a leg that ran with - # a restored JAX compile cache is not comparable to one that recompiled, - # and a reader looking at a jump needs that beside the seconds rather - # than a click away. Said only when it is KNOWN — a leg from before the - # cache-state sidecar existed renders exactly as it always did. - cache = r.get("cache") if isinstance(r.get("cache"), dict) else {} - jax = str(cache.get("jax") or "") - bracket = f" [jax cache {jax}]" if jax in ("hit", "miss") else "" + # The fixed overhead the scripts are not responsible for: checkout, + # dependency-chain clone, python setup, install. It sits after the + # coverage tail because it is not part of it — a leg whose total fell + # while its setup rose has not got faster. Rendered ONLY when the + # sidecar measured it; a leg from an emitter that did not (every + # artifact from before the marks existed) reads exactly as it always + # did, with no line about a number nobody took. + setup_s = _setup_seconds(r.get("cache")) + if setup_s is not None: + tail = f"{tail} · setup {_as_int(setup_s)}s" + # Hot or cold, said on the line the numbers are on. `[jax cache hit]` + # for a leg whose numba state is unknown — every artifact from before + # that cache existed, rendering exactly as it always did — and + # `[jax cache hit, numba hit]` once the sidecar carries both. + bracket = _cache_bracket(r.get("cache"), jax_label="jax cache") prefix = f"{r.get('repo')} py{r.get('python') or '?'}{bracket}:" details.append(f"{prefix} {head} {tail}" if head else f"{prefix} {tail}") # Same as the gate row: how much durable history stands behind the diff --git a/heart/timings.py b/heart/timings.py index 8788a67f..413bee21 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -70,6 +70,7 @@ "run_id": 7, "run_url": "https://ci.invalid/runs/7", "head_branch": "feat/x", "head_sha": "abc123", "package": "pkg_a", "import_s": 3.6, + "cache": {"jax": "hit", "numba": "miss"}, "suite": {"tests": 1500, "failures": 0, "errors": 0, "skipped": 3, "wall_s": 412.0}, "slowest": {"tests/foo/test_bar.py::test_x": 12.5}} @@ -78,7 +79,11 @@ 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. +0.0 — when that import failed or timed out. ``cache`` is what the leg ran +UNDER: the libraries' gate restores a JAX compile cache and a numba function +cache, and a suite that recompiled everything is not a slower suite, it is a +differently-conditioned one. Both read ``unknown`` for a rollup older than the +sidecar. There is no ``datasets`` key here — that cache is the workspaces'. ``epochs.jsonl`` line:: @@ -397,23 +402,75 @@ def gates_history( _CACHE_STATES = ("hit", "miss") -def _cache_pair(cache: Any) -> dict[str, str]: - """``{"jax", "datasets"}`` out of a rollup leg's cache block. +# Which caches each record says a measurement was taken under. The scripts +# gate restores three; the libraries' gate restores two and has no dataset +# cache at all, so recording a `datasets` key on a unit line would be a field +# that could only ever say "unknown". +SCRIPTS_CACHE_KEYS = ("jax", "datasets", "numba") +UNIT_CACHE_KEYS = ("jax", "numba") - Two keys, not three: the epoch is a property of the *keys* the workflow - used, not of the measurement, and the record's job is to say what the - measurement was taken under. Anything that is not one of the two known - states records ``unknown`` — a rollup from before the sidecar existed, a - leg the download failed on — never a fabricated miss. + +def _cache_states(cache: Any, keys: tuple[str, ...] = SCRIPTS_CACHE_KEYS + ) -> dict[str, str]: + """The named cache states out of a rollup leg's cache block. + + The epoch is deliberately NOT among them: it is a property of the *keys* + the workflow used, not of the measurement, and the record's job is to say + what the measurement was taken under. Anything that is not one of the two + known states records ``unknown`` — a rollup from before the sidecar + existed, a section an older emitter never wrote, a leg the download failed + on — never a fabricated miss. """ src = cache if isinstance(cache, dict) else {} out = {} - for key in ("jax", "datasets"): + for key in keys: value = str(src.get(key) or "") out[key] = value if value in _CACHE_STATES else UNKNOWN_CACHE_STATE return out +def _setup_seconds(cache: Any) -> float | None: + """The leg's ``setup_s`` out of its cache block, or ``None``. + + The sidecar reader (``heart.checks.smoke_timings.cache_view``) has already + coerced this; the same normalisation is repeated here for the same reason + ``_cache_states`` repeats its own — this module reads rollups it did not + necessarily produce, including ones written before the field existed, and + must never raise or fabricate on one. + """ + src = cache if isinstance(cache, dict) else {} + value = src.get("setup_s") + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + seconds = float(value) + if seconds != seconds or seconds in (float("inf"), float("-inf")): + return None + return seconds if seconds >= 0 else None + + +def unit_cache_state(cache: Any) -> str: + """The ONE state a unit leg's drift comparison turns on. + + A library suite is conditioned by two caches at once, and a comparison is + only safe when both sides ran the same way. So: ``hit`` when the leg had + both, ``miss`` when it had neither, and ``unknown`` for every mixture and + for every leg where either state is itself unknown. That last case is the + point — half-hot against half-cold is not a comparison anybody can read, + and ``unknown`` compares exactly as it did before the sidecar existed + rather than suppressing the row. + + Lives here, beside the record that writes ``cache_state`` into every + previous unit row, rather than in ``heart.checks.unit_timings`` which + imports it: this module imports nothing from ``heart``, so the dependency + only ever points one way and there is no cycle to unpick. + """ + states = _cache_states(cache, UNIT_CACHE_KEYS) + jax, numba = states["jax"], states["numba"] + if jax == numba and jax in _CACHE_STATES: + return jax + return UNKNOWN_CACHE_STATE + + def scripts_lines_from_rollup( rollup: Any, today: str ) -> dict[str, list[dict[str, Any]]]: @@ -477,8 +534,16 @@ def scripts_lines_from_rollup( # because a measurement taken with a restored compile cache and one # taken without it are not the same measurement — and a baseline # that cannot say which it was is a baseline nothing can use. - # "unknown" on both sides for a rollup that predates the sidecar. - "cache": _cache_pair(leg.get("cache")), + # "unknown" on every side for a rollup that predates the sidecar. + "cache": _cache_states(leg.get("cache")), + # The leg's FIXED overhead: job start -> first script, out of the + # same sidecar. Recorded beside `cache` and not inside it because + # `cache` says what the measurement was taken UNDER and every value + # in it is a state string; this is a measurement of its own, of the + # part of the gate no script is responsible for. `null` when the + # rollup does not know — never 0, which would claim the gate spent + # no time getting ready. + "setup_s": _setup_seconds(leg.get("cache")), "entries": {name: entries[name] for name in sorted(entries)}, }) for repo in out: @@ -564,7 +629,7 @@ def previous_script_rows( # `classify_drift` can refuse a comparison across two known # but different states. A line recorded before the field # existed reads "unknown" and compares as it always did. - "cache_jax": _cache_pair(record.get("cache"))["jax"], + "cache_jax": _cache_states(record.get("cache"))["jax"], } return out @@ -581,9 +646,9 @@ def unit_lines_from_rollup( 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. + the suite totals, the leg's slowest tests, the import seconds, the cache + state), 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): @@ -632,6 +697,12 @@ def unit_lines_from_rollup( "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")), + # What the suite ran UNDER. Recorded beside the seconds because a + # suite measured with a restored compile cache and a restored numba + # cache is not the same measurement as one that compiled from cold, + # and a baseline that cannot say which it was is a baseline nothing + # can use. "unknown" on both for a rollup that predates the sidecar. + "cache": _cache_states(leg.get("cache"), UNIT_CACHE_KEYS), "suite": suite, "slowest": {name: slowest[name] for name in sorted(slowest)}, }) @@ -673,8 +744,12 @@ def previous_unit_rows( """``{(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. + previous row (``seconds``/``run_id``/``run_url``/``cache_state``), which is + the same function ``unit_timings`` classifies its test drift with — it + reads the cache field by name, and this one is called ``cache_state`` + rather than the scripts record's ``cache_jax`` because it is jax and numba + combined and naming it after half of what it means would mislead every + reader of the record. 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 @@ -710,6 +785,11 @@ def previous_unit_rows( "seconds": seconds, "run_id": record.get("run_id"), "run_url": str(record.get("run_url") or ""), + # The state this baseline was measured under, so + # `classify_drift` can refuse a comparison across two known + # but different ones. A line recorded before the field + # existed reads "unknown" and compares as it always did. + "cache_state": unit_cache_state(record.get("cache")), } return out diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 23eb3117..5ae6fbb7 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1509,11 +1509,11 @@ def test_a_half_written_epoch_is_no_epoch_at_all(): # same repo can differ by the whole cost of recompiling. A reader looking at a # jump needs that beside the seconds, not a click away. -def _cached_scripts_snapshot(jax="hit", **kw): +def _cached_scripts_snapshot(jax="hit", numba="unknown", **kw): slice_ = _smoke_timings_slice(**kw) if jax is not None: slice_["repos"][0]["cache"] = {"jax": jax, "datasets": "miss", - "epoch": "1"} + "numba": numba, "epoch": "1"} return make_snapshot(ci_timing=_ci_timing_slice(), no_run_census=_no_run_slice(), smoke_timings=slice_) @@ -1529,6 +1529,23 @@ def test_a_known_cache_state_is_bracketed_on_the_per_repo_line(): " (2 scripts, 35s total)") +def test_a_known_numba_state_joins_the_same_bracket(): + """The gate restores two caches, so the line says both — and stays exactly + `[jax cache hit]` for a leg whose numba state is unknown, which is every + artifact from before that cache existed.""" + sec = _section(dashboard.build_board( + _cached_scripts_snapshot("hit", numba="miss"), make_verdict(), + now=FRESH_NOW), "smoke_timings") + assert sec.details[0].startswith("RepoA py3.12 [jax cache hit, numba miss]:") + sec = _section(dashboard.build_board( + _cached_scripts_snapshot("miss", numba="hit"), make_verdict(), + now=FRESH_NOW), "smoke_timings") + assert sec.details[0].startswith("RepoA py3.12 [jax cache miss, numba hit]:") + # Everything after the prefix is untouched. + assert sec.details[0].endswith("imaging/x.py 30s · imaging/y.py 5s" + " (2 scripts, 35s total)") + + def test_an_unknown_or_absent_cache_state_leaves_the_line_unchanged(): """A leg from before the cache-state sidecar existed renders exactly as it always did — no bracket, and certainly no claim that it ran cold.""" @@ -1548,5 +1565,89 @@ def test_the_scripts_block_inherits_the_cache_state_with_no_renderer_change(): d = json.loads(dashboard.render(_cached_scripts_snapshot("hit"), make_verdict(), fmt="json", now=FRESH_NOW)) assert d["performance"]["scripts"]["repos"][0]["cache"] == { - "jax": "hit", "datasets": "miss", "epoch": "1"} + "jax": "hit", "datasets": "miss", "numba": "unknown", "epoch": "1"} assert d["schema_version"] == dashboard.SCHEMA_VERSION # purely additive + + +# --- the fixed overhead, on the same line as the numbers -------------------- +# A fifth of every `_test` leg is spent before the first script runs. A reader +# looking at a leg's total needs that beside it, not in a different artifact. + +def _setup_scripts_snapshot(setup_s): + slice_ = _smoke_timings_slice() + slice_["repos"][0]["cache"] = {"jax": "unknown", "datasets": "unknown", + "numba": "unknown", "epoch": "", + "setup_s": setup_s} + return make_snapshot(ci_timing=_ci_timing_slice(), + no_run_census=_no_run_slice(), smoke_timings=slice_) + + +def _scripts_line(snapshot): + return _section(dashboard.build_board(snapshot, make_verdict(), + now=FRESH_NOW), "smoke_timings").details[0] + + +def test_a_measured_setup_is_appended_after_the_coverage_tail(): + """After the tail and not inside it: a leg that got faster by running fewer + scripts and a leg that got faster by installing quicker are different + events, and the line has to keep them apart.""" + assert _scripts_line(_setup_scripts_snapshot(104)) == ( + "RepoA py3.12: imaging/x.py 30s · imaging/y.py 5s" + " (2 scripts, 35s total) · setup 104s") + # Whole seconds on the line whatever the sidecar carried — the same + # `_as_int` truncation every other count on this board goes through. + assert _scripts_line(_setup_scripts_snapshot(103.6)).endswith("· setup 103s") + # And the cache bracket, when there is one, is unaffected by the addition. + line = _scripts_line(_cached_scripts_snapshot("hit")) + assert line.startswith("RepoA py3.12 [jax cache hit]:") + + +def test_an_unmeasured_setup_leaves_the_line_exactly_as_it_was(): + """Every artifact from before the mark steps existed. The unknown case is + pinned by the cache-state tests above too; this says the setup work did not + move it.""" + unchanged = ("RepoA py3.12: imaging/x.py 30s · imaging/y.py 5s" + " (2 scripts, 35s total)") + for value in (None, "104", True, -5, float("nan")): + assert _scripts_line(_setup_scripts_snapshot(value)) == unchanged, value + # No cache block at all — a leg the download failed on, or an older board. + assert _scripts_line(_cached_scripts_snapshot(None)) == unchanged + + +# --- the same bracket, on the unit suite line -------------------------------- +# The libraries' gate restores a JAX compile cache and a numba function cache +# too, so a suite's wall-clock is only readable beside what it ran under. + +def _unit_cached_snapshot(cache): + slice_ = _unit_timings_slice() + if cache is not None: + slice_["repos"][0]["cache"] = cache + return make_snapshot(unit_test_timing=_legacy_unit(), + import_time=_legacy_import(), unit_timings=slice_) + + +def _unit_line(cache): + board = dashboard.build_board(_unit_cached_snapshot(cache), make_verdict(), + now=FRESH_NOW) + return _section(board, "unit_test_timing").details[0] + + +def test_a_known_unit_cache_state_is_bracketed_on_the_suite_line(): + """Same format as the scripts row, in the shorter wording a unit line can + afford — and the numbers after it are untouched.""" + assert _unit_line({"jax": "hit", "numba": "miss", "epoch": "1"}) == ( + "RepoA py3.12 [jax hit, numba miss]: 1500 tests 7m slowest test_x 12.5s") + assert _unit_line({"jax": "miss", "numba": "miss", "epoch": "1"}) == ( + "RepoA py3.12 [jax miss, numba miss]: 1500 tests 7m slowest test_x 12.5s") + # One known half is still worth saying; the unknown half is simply absent. + assert _unit_line({"jax": "hit", "numba": "unknown"}) == ( + "RepoA py3.12 [jax hit]: 1500 tests 7m slowest test_x 12.5s") + + +def test_an_unknown_or_absent_unit_cache_state_leaves_the_line_unchanged(): + """A leg from before the sidecar existed renders exactly as it always did — + no bracket, and certainly no claim that it ran cold.""" + unchanged = "RepoA py3.12: 1500 tests 7m slowest test_x 12.5s" + for cache in (None, {}, {"jax": "unknown", "numba": "unknown"}, + {"jax": "warm", "numba": None}, "nonsense"): + assert _unit_line(cache) == unchanged diff --git a/tests/test_lib_tests_wiring.py b/tests/test_lib_tests_wiring.py index fb1a1738..7c2ae821 100644 --- a/tests/test_lib_tests_wiring.py +++ b/tests/test_lib_tests_wiring.py @@ -7,6 +7,16 @@ 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. +They also pin the TWO CACHES the job gained — a JAX compile cache and a numba +function cache, with `smoke-tests.yml`'s discipline (one epoch salt, the +accumulating run-id key, a single prefix fallback, a `cache_state.json` sidecar +riding the existing artifact, saves gated on a measured change) — and the one +thing that makes the numba half work at all: the source mtimes are stamped from +CONTENT, because numba keys every cache entry on its source file's +`(mtime, size)` and a fresh clone or a fresh `pip install` changes every mtime. +That stamp is what makes the prefix fallback safe and lets the numba key name +no library commit. + 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. @@ -27,6 +37,19 @@ IMPORT_STEP = "Time a fresh-process import" UPLOAD_STEP = "Upload the unit timings" +INSTALL_STEP = "Install (deps + package from source" +KEYS_STEP = "Resolve cache keys" +JAX_RESTORE_STEP = "Restore the JAX compile cache" +NUMBA_RESTORE_STEP = "Restore the numba cache" +STAMP_STEP = "Stamp source mtimes from content" +BEFORE_STEP = "Measure the caches before the run" +RECORD_STEP = "Record cache state" +JAX_SAVE_STEP = "Save the JAX compile cache" +NUMBA_SAVE_STEP = "Save the numba cache" + +NEW_STEPS = (KEYS_STEP, JAX_RESTORE_STEP, NUMBA_RESTORE_STEP, STAMP_STEP, + BEFORE_STEP, RECORD_STEP, JAX_SAVE_STEP, NUMBA_SAVE_STEP) + def _jobs(): return yaml.safe_load((WORKFLOWS / "lib-tests.yml").read_text())["jobs"] @@ -108,3 +131,184 @@ def test_the_artifact_name_is_what_the_heart_check_selects(): assert ARTIFACT_RE.match("unit-timings-3.12") assert ARTIFACT_NAME.startswith("unit-timings-") + + +# --- the two caches --------------------------------------------------------- + +def test_the_epoch_salt_is_declared_once_at_the_job_level(): + """One knob invalidates every cache below it — a runner-image change, a + cache-format change — instead of an edit per key with one of them missed. + Declared on `unittest` alone: the no-jax leg caches nothing.""" + jobs = _jobs() + assert jobs["unittest"]["env"]["PYAUTO_CACHE_EPOCH"] == "1" + assert "env" not in jobs["unittest-nojax"] + + +def test_the_cache_steps_sit_in_order_between_the_install_and_the_upload(): + steps = _steps("unittest") + order = [_index(steps, name) for name in + (INSTALL_STEP, KEYS_STEP, JAX_RESTORE_STEP, NUMBA_RESTORE_STEP, + STAMP_STEP, BEFORE_STEP, "Run tests", RECORD_STEP, UPLOAD_STEP)] + assert order == sorted(order) + # The saves come after the state they are gated on, and the notifier stays + # last so a failure is still announced. + assert _index(steps, RECORD_STEP) < _index(steps, JAX_SAVE_STEP) + assert _index(steps, RECORD_STEP) < _index(steps, NUMBA_SAVE_STEP) + assert _index(steps, NUMBA_SAVE_STEP) < _index(steps, "Slack on failure") + assert _index(steps, "Slack on failure") == len(steps) - 1 + + +def test_every_step_the_caches_added_is_non_fatal(): + """Six required checks ride this file: a cache miss, a cache-service outage + or a `du` that failed must cost a warm run, never a green gate.""" + steps = _steps("unittest") + for name in NEW_STEPS: + assert _step(steps, name)["continue-on-error"] is True, name + + +def test_the_key_resolver_publishes_the_two_components_the_keys_need(): + step = _step(_steps("unittest"), KEYS_STEP) + assert step["id"] == "keys" + run = step["run"] + assert "jaxlib=" in run and "pyfull=" in run + # A jaxlib that will not import is a key component, not a failure. + assert "nojax" in run + # The full version, patch included: numba's entries hash the site-packages + # path, which carries it. + assert "sys.version.split()[0]" in run + # No chain hash here — there is no dataset cache in this workflow. + assert "sims" not in run and "chain" not in run + + +def test_the_jax_key_is_per_python_leg_per_jaxlib_and_carries_the_salt(): + """A compiled executable is jaxlib-specific and the interpreter's minor + version is part of what produced it: neither may read the other's entries.""" + step = _step(_steps("unittest"), JAX_RESTORE_STEP) + assert step["uses"].startswith("actions/cache/restore@") + assert step["id"] == "jax-cache" + assert step["with"]["path"] == "${{ github.workspace }}/.pyauto_jax_cache" + key = step["with"]["key"] + for component in ("${{ runner.os }}", "${{ matrix.python-version }}", + "${{ steps.keys.outputs.jaxlib }}", + "${{ env.PYAUTO_CACHE_EPOCH }}", "${{ github.run_id }}"): + assert component in key, component + _assert_one_prefix_fallback(step) + + +def test_the_numba_key_is_per_full_python_version_and_carries_the_salt(): + """numba keys every cache entry on the directory its source was found in, + and the site-packages path carries the PATCH version — so 3.12.3 and 3.12.7 + are different caches, not one.""" + step = _step(_steps("unittest"), NUMBA_RESTORE_STEP) + assert step["uses"].startswith("actions/cache/restore@") + assert step["id"] == "numba-cache" + assert step["with"]["path"] == "${{ github.workspace }}/.numba_cache" + key = step["with"]["key"] + for component in ("${{ runner.os }}", "${{ steps.keys.outputs.pyfull }}", + "${{ env.PYAUTO_CACHE_EPOCH }}", "${{ github.run_id }}"): + assert component in key, component + _assert_one_prefix_fallback(step) + + +def _assert_one_prefix_fallback(step): + """The accumulating-cache pattern: the exact key (run id) never hits, the + single prefix always does, and each save is a superset of what was + restored. Exactly one fallback — a second, broader line would be a claim + nobody made about what may be read.""" + key = step["with"]["key"] + fallbacks = [line for line in step["with"]["restore-keys"].split("\n") + if line.strip()] + assert len(fallbacks) == 1 + (fallback,) = fallbacks + assert key.startswith(fallback) + assert "${{ github.run_id }}" not in fallback + assert fallback.endswith("-e${{ env.PYAUTO_CACHE_EPOCH }}-") + + +def test_the_stamp_step_makes_the_numba_fallback_safe(): + """numba stamps every entry with its source's (mtime, size), and a fresh + clone or a fresh `pip install` changes every mtime — so without this the + restored cache would miss every entry it holds, and with it a changed file + misses its own entry however old the restored directory is. That is what + lets the key above carry a prefix fallback and name no library commit.""" + step = _step(_steps("unittest"), STAMP_STEP) + run = step["run"] + # The roots reach the script through the environment, never spliced into + # the heredoc's source (the import-timing step records the lesson). + assert step["env"]["STAMP_DIRS"] == \ + "${{ steps.map.outputs.repo }} ${{ steps.map.outputs.deps }}" + assert "${{" not in run + # A content hash, not a clock reading. + assert "sha1" in run and "os.utime" in run + # The installed copies too, resolved WITHOUT importing them. + assert "find_spec" in run and "submodule_search_locations" in run + + +def test_the_suite_runs_under_both_cache_dirs_and_is_otherwise_untouched(): + step = _step(_steps("unittest"), "Run tests") + for name in ("JAX_COMPILATION_CACHE_DIR", "NUMBA_CACHE_DIR"): + assert step["env"][name].startswith("${{ github.workspace }}/"), name + # The command itself is untouched — the env block is the whole change. + assert "export JAX_ENABLE_X64=True" in step["run"] + assert "--junitxml=test-results/junit.xml" in step["run"] + + +def test_the_record_step_runs_on_a_red_run_too_and_writes_the_sidecar(): + """A red run's cache state is exactly as interesting as a green one's — and + the artifact it rides in is uploaded either way.""" + from heart.checks.smoke_timings import CACHE_STATE_FILENAME, CACHE_STATE_SCHEMA + + step = _step(_steps("unittest"), RECORD_STEP) + assert step["if"] == "always()" + assert step["id"] == "cache-state" + run = step["run"] + # One filename and one schema string, declared in two places that must + # agree — the emitter here and the ingest in the check. + assert CACHE_STATE_FILENAME in run + assert f'"schema": "{CACHE_STATE_SCHEMA}"' in run + # Two sections, no `datasets`: there is no dataset cache in this workflow, + # so there would be nothing honest to say under it. + assert '"jax": jax' in run and '"numba": numba' in run + assert '"datasets"' not in run + assert '"epoch"' in run + # It writes beside the timings the upload step already collects. + assert step["env"]["OUT_DIR"] == "${{ steps.map.outputs.repo }}/test-results" + # Every input reaches Python through the environment, never spliced into + # the heredoc's source. + for key in ("EPOCH", "OUT_DIR", + "JAX_PATH", "JAX_KEY_RESTORED", "JAX_EXACT", "JAX_MB_BEFORE", + "JAX_N_BEFORE", "NUMBA_PATH", "NUMBA_KEY_RESTORED", + "NUMBA_EXACT", "NUMBA_MB_BEFORE", "NUMBA_N_BEFORE"): + assert key in step["env"], key + assert "${{" not in run + assert step["env"]["JAX_KEY_RESTORED"] == \ + "${{ steps.jax-cache.outputs.cache-matched-key }}" + assert step["env"]["NUMBA_EXACT"] == \ + "${{ steps.numba-cache.outputs.cache-hit }}" + assert "jax_changed" in run and "numba_changed" in run + + +def test_both_saves_run_on_a_red_run_and_mirror_their_restores(): + """A compile-cache entry — jax or numba — is complete or absent, never + half-written, so a failing run's compiling is still worth keeping. There is + no dataset here whose truncation would have to be guarded against.""" + steps = _steps("unittest") + jax = _step(steps, JAX_SAVE_STEP) + numba = _step(steps, NUMBA_SAVE_STEP) + assert jax["if"] == "always() && steps.cache-state.outputs.jax_changed == 'true'" + assert numba["if"] == \ + "always() && steps.cache-state.outputs.numba_changed == 'true'" + for step, restore in ((jax, JAX_RESTORE_STEP), (numba, NUMBA_RESTORE_STEP)): + assert step["uses"].startswith("actions/cache/save@") + source = _step(steps, restore)["with"] + assert step["with"]["path"] == source["path"] + assert step["with"]["key"] == source["key"] + + +def test_the_nojax_job_gained_no_cache_step(): + """It exists to prove the jax-absent import path on one python version. A + cache there would key on a jaxlib that is deliberately not installed, and + the epoch salt it would need is not even declared on the job.""" + names = [step.get("name", "") for step in _steps("unittest-nojax")] + for name in NEW_STEPS: + assert not any(name in candidate for candidate in names), name diff --git a/tests/test_smoke_tests_wiring.py b/tests/test_smoke_tests_wiring.py index ca6eddd1..5f0fdc41 100644 --- a/tests/test_smoke_tests_wiring.py +++ b/tests/test_smoke_tests_wiring.py @@ -2,20 +2,21 @@ `smoke-tests.yml` is referenced `@main` by eleven workspace repos, so a mistake in it reds eleven required checks at once. These tests parse the YAML and pin -what the cache work added — a JAX compile cache and a simulated-dataset cache -restored and saved across runs, plus the `cache_state.json` sidecar that rides -the timings artifact — together with the three properties that keep the -addition harmless: +what the cache work added — a JAX compile cache, a numba function cache and a +simulated-dataset cache restored and saved across runs, plus the +`cache_state.json` sidecar that rides the timings artifact — together with the +three properties that keep the addition harmless: * **every new step is non-fatal** (`continue-on-error: true`), so a cache service outage degrades a run to cold rather than to red; * **the runner's command is untouched** — the step gained one environment variable and nothing else; * **the dataset cache has exactly one fallback key.** That is the correctness - property of the pair: the JAX cache may read anything compiled for the same - jaxlib, but a dataset restored under a different simulator or a different - library commit is not the dataset this run would have written, so a broader - fallback would be silent corruption of the thing being measured. + property of the set: the JAX cache may read anything compiled for the same + jaxlib and the numba cache anything stamped from the same source content + (see the stamp step), but a dataset restored under a different simulator or a + different library commit is not the dataset this run would have written, so a + broader fallback would be silent corruption of the thing being measured. Fake names only, as in the sibling wiring tests: nothing here names a repo, an owner or a package — the workflow file is the declared surface, the callers are @@ -40,13 +41,18 @@ KEYS_STEP = "Resolve cache keys" JAX_RESTORE_STEP = "Restore the JAX compile cache" DS_RESTORE_STEP = "Restore simulated datasets" +NUMBA_RESTORE_STEP = "Restore the numba cache" BEFORE_STEP = "Measure the caches before the run" +STAMP_STEP = "Stamp source mtimes from content" RECORD_STEP = "Record cache state" JAX_SAVE_STEP = "Save the JAX compile cache" +NUMBA_SAVE_STEP = "Save the numba cache" DS_SAVE_STEP = "Save simulated datasets" +PREPARE_STEP = "Prepare cache dirs" -NEW_STEPS = (KEYS_STEP, JAX_RESTORE_STEP, DS_RESTORE_STEP, BEFORE_STEP, - RECORD_STEP, JAX_SAVE_STEP, DS_SAVE_STEP) +NEW_STEPS = (KEYS_STEP, JAX_RESTORE_STEP, DS_RESTORE_STEP, NUMBA_RESTORE_STEP, + BEFORE_STEP, STAMP_STEP, RECORD_STEP, JAX_SAVE_STEP, + NUMBA_SAVE_STEP, DS_SAVE_STEP) def _job(): @@ -77,9 +83,14 @@ def test_the_epoch_salt_is_declared_once_at_the_job_level(): assert _job()["env"]["PYAUTO_CACHE_EPOCH"] == "1" -def test_the_runner_step_names_the_compile_cache_dir_and_is_otherwise_untouched(): +def test_the_runner_step_names_both_cache_dirs_and_is_otherwise_untouched(): step = _step(_steps(), RUNNER_STEP) cache_dir = step["env"]["JAX_COMPILATION_CACHE_DIR"] + # numba's directory moved out of /tmp: a per-run temporary is neither + # restorable nor saveable, so it bought nothing across runs. + numba_dir = step["env"]["NUMBA_CACHE_DIR"] + assert numba_dir.startswith("${{ github.workspace }}/") + assert not numba_dir.startswith("/tmp") # An explicit path under the workspace: the default is a home-directory # cache the cache steps could not name, and the runner copies this job env # into every script subprocess, so all of them share the one directory. @@ -95,10 +106,12 @@ def test_the_cache_steps_sit_between_the_install_and_the_upload_in_order(): steps = _steps() order = [_index(steps, name) for name in (INSTALL_STEP, KEYS_STEP, JAX_RESTORE_STEP, DS_RESTORE_STEP, - BEFORE_STEP, RUNNER_STEP, RECORD_STEP, UPLOAD_STEP)] + NUMBA_RESTORE_STEP, BEFORE_STEP, STAMP_STEP, PREPARE_STEP, + RUNNER_STEP, RECORD_STEP, UPLOAD_STEP)] assert order == sorted(order) # The saves come after the state they are gated on, and before the notifier. assert _index(steps, RECORD_STEP) < _index(steps, JAX_SAVE_STEP) + assert _index(steps, RECORD_STEP) < _index(steps, NUMBA_SAVE_STEP) assert _index(steps, RECORD_STEP) < _index(steps, DS_SAVE_STEP) assert _index(steps, DS_SAVE_STEP) < _index(steps, "Slack notify") @@ -123,7 +136,7 @@ def test_the_key_resolver_takes_its_inputs_through_the_environment(): # reads a plain variable back. assert step["env"]["SIMS_HASH"].startswith("${{ hashFiles(") assert "hashFiles" not in step["run"] - for output in ("jaxlib=", "chain=", "sims=$SIMS_HASH"): + for output in ("jaxlib=", "pyfull=", "chain=", "sims=$SIMS_HASH"): assert output in step["run"] # A jaxlib that will not import is a key component, not a failure. assert "nojax" in step["run"] @@ -148,6 +161,46 @@ def test_the_jax_key_is_per_python_leg_per_jaxlib_and_carries_the_salt(): assert fallback.endswith("-e${{ env.PYAUTO_CACHE_EPOCH }}-") +def test_the_numba_key_is_per_full_python_version_and_carries_the_salt(): + """numba keys every cache entry on the directory its source was found in, + and the site-packages path carries the PATCH version — so 3.12.3 and 3.12.7 + are different caches, not one.""" + step = _step(_steps(), NUMBA_RESTORE_STEP) + assert step["uses"].startswith("actions/cache/restore@") + assert step["id"] == "numba-cache" + assert step["with"]["path"] == "${{ github.workspace }}/.numba_cache" + key = step["with"]["key"] + for component in ("${{ runner.os }}", "${{ steps.keys.outputs.pyfull }}", + "${{ env.PYAUTO_CACHE_EPOCH }}", "${{ github.run_id }}"): + assert component in key, component + (fallback,) = [line for line in step["with"]["restore-keys"].split("\n") + if line.strip()] + assert key.startswith(fallback) + assert "${{ github.run_id }}" not in fallback + assert fallback.endswith("-e${{ env.PYAUTO_CACHE_EPOCH }}-") + + +def test_the_stamp_step_makes_the_numba_fallback_safe(): + """numba stamps every entry with its source's (mtime, size), and a fresh + `pip install` changes every mtime — so without this the restored cache + would miss every entry it holds, and with it a changed file misses its own + entry however old the restored directory is. That is what lets the key + above carry a prefix fallback and name no library commit.""" + step = _step(_steps(), STAMP_STEP) + run = step["run"] + # Roots reach the script through the environment, never spliced into the + # heredoc's source — the house rule the key resolver follows too. + assert "STAMP_DIRS" in step["env"] + assert "${{" not in run + # The stamp is a content hash, not a clock reading. + assert "sha1" in run and "os.utime" in run + # `find_spec` resolves an installed package WITHOUT importing it. + assert "find_spec" in run and "submodule_search_locations" in run + # It has to run before anything writes a numba entry. + steps = _steps() + assert _index(steps, STAMP_STEP) < _index(steps, RUNNER_STEP) + + def test_the_dataset_key_has_exactly_one_fallback_and_no_broader_one(): """Correctness over hit rate: a different simulator or a different library commit MUST miss, because the FITS it would restore are not the FITS this @@ -184,13 +237,21 @@ def test_the_record_step_runs_on_a_red_run_too_and_writes_the_sidecar(): # Every input reaches Python through the environment, never spliced into # the heredoc's source. for key in ("EPOCH", "JAX_KEY_RESTORED", "JAX_EXACT", "DS_KEY_RESTORED", - "DS_EXACT", "JAX_MB_BEFORE", "DS_N_BEFORE"): + "DS_EXACT", "JAX_MB_BEFORE", "DS_N_BEFORE", + "NUMBA_PATH", "NUMBA_KEY_RESTORED", "NUMBA_EXACT", + "NUMBA_MB_BEFORE", "NUMBA_N_BEFORE"): assert key in step["env"], key assert "${{" not in run assert step["env"]["JAX_KEY_RESTORED"] == \ "${{ steps.jax-cache.outputs.cache-matched-key }}" assert step["env"]["DS_EXACT"] == "${{ steps.dataset-cache.outputs.cache-hit }}" + assert step["env"]["NUMBA_KEY_RESTORED"] == \ + "${{ steps.numba-cache.outputs.cache-matched-key }}" assert "jax_changed" in run and "ds_changed" in run + assert "numba_changed" in run + # The numba section is ADDITIVE: the schema string does not move, so an + # ingest that predates it still reads the sidecar. + assert '"numba": numba' in run def test_the_saves_differ_on_exactly_one_thing_a_red_run(): @@ -199,13 +260,19 @@ def test_the_saves_differ_on_exactly_one_thing_a_red_run(): `should_simulate` would happily keep, so datasets save only when green.""" steps = _steps() jax = _step(steps, JAX_SAVE_STEP) + numba = _step(steps, NUMBA_SAVE_STEP) datasets = _step(steps, DS_SAVE_STEP) assert jax["if"].startswith("always()") + # A numba entry is an index line plus a complete artefact, or it is absent: + # the compile cache's rule, not the dataset's. + assert numba["if"].startswith("always()") assert datasets["if"].startswith("success()") # An unchanged cache is not re-uploaded under a new key. assert "steps.cache-state.outputs.jax_changed == 'true'" in jax["if"] + assert "steps.cache-state.outputs.numba_changed == 'true'" in numba["if"] assert "steps.cache-state.outputs.ds_changed == 'true'" in datasets["if"] - for step, restore in ((jax, JAX_RESTORE_STEP), (datasets, DS_RESTORE_STEP)): + for step, restore in ((jax, JAX_RESTORE_STEP), (numba, NUMBA_RESTORE_STEP), + (datasets, DS_RESTORE_STEP)): assert step["uses"].startswith("actions/cache/save@") source = _step(steps, restore)["with"] assert step["with"]["path"] == source["path"] @@ -230,3 +297,133 @@ def test_the_sidecar_name_and_schema_are_what_the_heart_check_reads(): run = _step(_steps(), RECORD_STEP)["run"] assert CACHE_STATE_FILENAME in run assert f'"schema": "{CACHE_STATE_SCHEMA}"' in run + + +# --- the fixed overhead: what the gate spends before the first script ------- +# Measured over six runs of one `_test` workspace (12 legs): 104 s mean from +# job start to the first script, 22.6% of the job, of which the install is +# ~84 s and the dependency-chain clone ~16.5 s. These tests pin the three +# things done about it — shallow clones, a pip wheel cache, and the marks that +# make the overhead a measured field instead of a hand-scraped one. + +PIP_CACHE_STEP = "Restore the pip wheel cache" +CLONE_STEP = "Clone dependency chain" +JOB_MARK_STEP = "Mark job start" +SCRIPTS_MARK_STEP = "Mark scripts start" + +OVERHEAD_STEPS = (JOB_MARK_STEP, PIP_CACHE_STEP, SCRIPTS_MARK_STEP) + + +def test_the_chain_is_cloned_shallow_on_both_the_clone_and_the_fallback(): + """Nothing downstream reads this history: the libraries are installed from + the trees, and the only other reader is `rev-parse HEAD`, which answers on + a shallow clone. So both network legs are depth 1 — a full clone in the + fallback would hand back every byte the shallow clone saved.""" + run = _step(_steps(), CLONE_STEP)["run"] + assert "git clone --depth 1 " in run + assert "git clone \"https" not in run + assert 'fetch --depth 1 origin "$BRANCH"' in run + # A shallow clone is single-branch, so there is no `origin/$BRANCH` for + # `git checkout` to DWIM from — FETCH_HEAD is what the fetch above leaves. + assert 'checkout -B "$BRANCH" FETCH_HEAD' in run + + +def test_the_matching_branch_fallback_survives_the_shallow_clone(): + """The reason this step exists at all: a library PR must still be tested + against its workspace. Depth is an optimisation; this is the semantics.""" + run = _step(_steps(), CLONE_STEP)["run"] + assert 'ls-remote --exit-code --heads origin "$BRANCH"' in run + assert "PyAutoHands" in run # cloned in the same loop, same depth + # Still env-not-interpolation for the branch and the owner, and the chain + # still reaches the loop as the caller-supplied text it is. + assert 'BRANCH="${{ github.head_ref || github.ref_name }}"' in run + assert 'OWNER="${{ github.repository_owner }}"' in run + + +def test_the_pip_cache_is_a_fourth_cache_under_the_same_rules(): + """Non-fatal, salted with the same epoch, one prefix fallback: the three + properties every cache in this file already holds. `setup-python`'s own + `cache:` can hold none of them — it cannot be `continue-on-error`, it + cannot carry the salt, and a `cache-dependency-path` matching no file is a + hard error in an action that eleven required checks ride.""" + steps = _steps() + step = _step(steps, PIP_CACHE_STEP) + assert step["uses"].startswith("actions/cache@") + assert step["id"] == "pip-cache" + assert step["continue-on-error"] is True + assert step["with"]["path"] == "~/.cache/pip" + key = step["with"]["key"] + for component in ("${{ runner.os }}", "${{ matrix.python-version }}", + "${{ env.PYAUTO_CACHE_EPOCH }}", "hashFiles("): + assert component in key, component + (fallback,) = [line for line in step["with"]["restore-keys"].split("\n") + if line.strip()] + assert key.startswith(fallback) + assert "hashFiles(" not in fallback + assert fallback.endswith("-e${{ env.PYAUTO_CACHE_EPOCH }}-") + # setup-python is left alone: no `cache:` of its own to race this one. + assert "cache" not in _step(steps, "Set up Python")["with"] + + +def test_the_pip_key_hashes_the_dependency_declarations_it_can_see(): + """The libraries ship their dependencies in `pyproject.toml`, not in a + requirements file, and the workspace may carry either or neither. All the + shapes are named; `hashFiles()` returns "" for the ones that match nothing, + which is a constant key rather than the error `setup-python` would raise.""" + key = _step(_steps(), PIP_CACHE_STEP)["with"]["key"] + for pattern in ("*/pyproject.toml", "*/setup.py", + "workspace/requirements*.txt"): + assert pattern in key, pattern + # The globs only resolve if the chain is already on disk: this step must + # come after the clone, and before the install whose downloads it caches. + steps = _steps() + assert _index(steps, CLONE_STEP) < _index(steps, PIP_CACHE_STEP) + assert _index(steps, PIP_CACHE_STEP) < _index(steps, INSTALL_STEP) + + +def test_the_two_marks_bracket_exactly_the_setup(): + """`setup_s` is only honest if the first mark is the first thing the job + does and the second is the last thing before the scripts.""" + steps = _steps() + assert _index(steps, JOB_MARK_STEP) == 0 + assert _index(steps, SCRIPTS_MARK_STEP) + 1 == _index(steps, RUNNER_STEP) + for name, stamp in ((JOB_MARK_STEP, "job_start"), + (SCRIPTS_MARK_STEP, "scripts_start")): + step = _step(steps, name) + run = step["run"] + assert "date +%s" in run and stamp in run + assert "$RUNNER_TEMP" in run + # Env-free and expression-free: nothing here to interpolate. + assert "env" not in step + assert "${{" not in run + + +def test_every_step_the_overhead_work_added_is_non_fatal(): + """Same rule as the caches: a mark we could not write or a cache service + outage costs a measurement, never one of eleven required checks.""" + steps = _steps() + for name in OVERHEAD_STEPS: + assert _step(steps, name)["continue-on-error"] is True, name + + +def test_the_recorder_carries_setup_s_and_stays_expression_free(): + """The overhead becomes DATA in the sidecar the Heart already ingests, + rather than a number scraped out of the Actions UI by hand.""" + step = _step(_steps(), RECORD_STEP) + run = step["run"] + assert '"setup_s": setup_seconds()' in run + assert "job_start" in run and "scripts_start" in run + # Read from the runner's own environment, not spliced in — the house rule. + assert 'os.environ.get("RUNNER_TEMP")' in run + assert "${{" not in run + # Absent or unreadable marks are None, never a fabricated zero. + assert "return None" in run + + +def test_the_runner_command_is_still_byte_identical_and_still_fatal(): + """The one thing in this workflow that must not move: a workspace owns its + runner. The second mark is a step BEFORE it, not an edit to it.""" + step = _step(_steps(), RUNNER_STEP) + assert 'python "$RUNNER" $RUNNER_ARGS' in step["run"] + assert "date +%s" not in step["run"] + assert "continue-on-error" not in step diff --git a/tests/test_smoke_timings.py b/tests/test_smoke_timings.py index eae74b2a..2fce9a5f 100644 --- a/tests/test_smoke_timings.py +++ b/tests/test_smoke_timings.py @@ -627,13 +627,21 @@ def _line(date, python, run_id, seconds): # --- the cache-state sidecar (hot or cold) ---------------------------------- -# The smoke workflow restores a JAX compile cache and the simulated datasets -# between runs and writes `cache_state.json` beside the timings dataset. A run -# that recompiled everything is not a slower run, it is a differently -# conditioned one, and the comparison has to be able to tell them apart. +# The smoke workflow restores a JAX compile cache, a numba function cache and +# the simulated datasets between runs and writes `cache_state.json` beside the +# timings dataset; the libraries' workflow writes the same sidecar with the jax +# and numba sections only. A run that recompiled everything is not a slower +# run, it is a differently conditioned one, and the comparison has to be able +# to tell them apart. -def _cache_state(*, jax_hit=True, ds_hit=False, epoch="1", - schema="cache_state/1", jax_key="pyauto-jax-...-e1-"): +# Sentinel for "the emitter did not write this key at all", which is a +# different thing from having written null. +_ABSENT = object() + + +def _cache_state(*, jax_hit=True, ds_hit=False, numba_hit=True, epoch="1", + schema="cache_state/1", jax_key="pyauto-jax-...-e1-", + setup_s=104): return json.dumps({ "schema": schema, "epoch": epoch, @@ -645,9 +653,27 @@ def _cache_state(*, jax_hit=True, ds_hit=False, epoch="1", "pyauto-datasets-...-" if ds_hit else "", "hit": ds_hit, "exact": False, "size_mb_before": 0, "size_mb_after": 90, "entries_before": 0, "entries_after": 12}, + "numba": {"path": "/w/.numba_cache", "restored_key": + "pyauto-numba-...-" if numba_hit else "", "hit": numba_hit, + "exact": False, "size_mb_before": 3, "size_mb_after": 9, + "entries_before": 30, "entries_after": 61}, + # The gate's fixed overhead, measured by the workflow's two mark steps. + **({} if setup_s is _ABSENT else {"setup_s": setup_s}), }) +def _cache_state_without_setup(**kw): + """A sidecar from the emitter that predates the setup_s field.""" + return _cache_state(setup_s=_ABSENT, **kw) + + +def _cache_state_without_numba(**kw): + """A sidecar from the emitter that predates the numba cache.""" + payload = json.loads(_cache_state(**kw)) + payload.pop("numba") + return json.dumps(payload) + + def _with_cache(directory, **kw): """Drop a cache_state.json beside an already-extracted dataset.""" (directory / smt.CACHE_STATE_FILENAME).write_text(_cache_state(**kw)) @@ -655,12 +681,19 @@ def _with_cache(directory, **kw): def test_cache_state_parses_hit_and_miss_per_section(): - state, err = smt.parse_cache_state(_cache_state(jax_hit=True, ds_hit=False)) + state, err = smt.parse_cache_state( + _cache_state(jax_hit=True, ds_hit=False, numba_hit=True)) assert err == "" assert state["jax"] == "hit" and state["datasets"] == "miss" + assert state["numba"] == "hit" assert state["epoch"] == "1" assert state["jax_restored_key"].startswith("pyauto-jax-") assert state["datasets_restored_key"] == "" + assert state["numba_restored_key"].startswith("pyauto-numba-") + + cold, err = smt.parse_cache_state(_cache_state(numba_hit=False)) + assert err == "" and cold["numba"] == "miss" + assert cold["numba_restored_key"] == "" def test_cache_state_rejects_a_foreign_or_broken_sidecar(): @@ -672,17 +705,83 @@ def test_cache_state_rejects_a_foreign_or_broken_sidecar(): def test_a_missing_section_is_a_miss_not_a_hit(): - """The workflow writes both sections every run, so an absent one is not - evidence that anything was restored.""" + """Both workflows have written `jax` and `datasets` on every run since the + sidecar existed, so an absent one is not evidence that anything was + restored.""" state, err = smt.parse_cache_state(json.dumps({"schema": "cache_state/1"})) assert err == "" and state["jax"] == "miss" and state["datasets"] == "miss" +def test_a_missing_numba_section_is_unknown_not_a_miss(): + """`numba` is ADDITIVE to the schema. A sidecar without it is an older + EMITTER, not a run that restored nothing — reading it as a miss would + date-stamp every earlier artifact cold and suppress its comparisons.""" + state, err = smt.parse_cache_state(_cache_state_without_numba(jax_hit=True)) + assert err == "" + # The two original sections are untouched by the addition. + assert state["jax"] == "hit" and state["datasets"] == "miss" + assert state["numba"] == "unknown" + assert state["numba_restored_key"] == "" + # A section that is present but not an object is no section at all. + payload = json.loads(_cache_state()) + payload["numba"] = "yes" + state, err = smt.parse_cache_state(json.dumps(payload)) + assert err == "" and state["numba"] == "unknown" + + +def test_the_cache_view_carries_the_numba_state_beside_the_other_two(): + view = smt.cache_view({"jax": "hit", "datasets": "miss", "numba": "miss", + "epoch": "1"}) + assert view == {"jax": "hit", "datasets": "miss", "numba": "miss", + "epoch": "1", "setup_s": None} + # Anything that is not one of the two known states reads unknown, numba + # included — and no sidecar at all is unknown on every side. + assert smt.cache_view({"jax": "hit", "numba": "warm"})["numba"] == "unknown" + assert smt.cache_view(None) == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown", "epoch": "", + "setup_s": None} + + +def test_the_sidecar_carries_the_gates_fixed_overhead(): + """`setup_s` is job start -> first script: checkout, chain clone, python + setup, install. It is the number the cache work is judged on, so it rides + the sidecar rather than being scraped out of the Actions UI by hand.""" + state, err = smt.parse_cache_state(_cache_state(setup_s=104)) + assert err == "" and state["setup_s"] == 104.0 + assert smt.cache_view(state)["setup_s"] == 104.0 + # A leg that spent no measurable time is a real reading, not an absence. + state, _ = smt.parse_cache_state(_cache_state(setup_s=0)) + assert state["setup_s"] == 0.0 + + +def test_a_sidecar_without_setup_s_is_none_never_a_zero(): + """Additive like `numba` was: a sidecar without the field is an OLDER + EMITTER, and a gate that spent no time getting ready is not a thing that + happens — so its absence must not render as a measurement of 0 s.""" + state, err = smt.parse_cache_state(_cache_state_without_setup()) + assert err == "" and state["setup_s"] is None + assert smt.cache_view(state)["setup_s"] is None + # The cache states of that older sidecar are read exactly as before. + assert state["jax"] == "hit" and state["numba"] == "hit" + + +def test_an_unreadable_setup_s_is_none_rather_than_an_exception(): + """Written by another organ on a runner we do not control: every surprise + degrades to the honest unknown.""" + for value in (None, "104", True, -5, float("nan"), float("inf"), {}): + state, err = smt.parse_cache_state(_cache_state(setup_s=value)) + assert err == "", value + assert state["setup_s"] is None, value + assert smt.cache_view({"setup_s": "104"})["setup_s"] is None + assert smt.cache_view(None)["setup_s"] is None + + def test_a_leg_carries_its_cache_state_when_the_sidecar_rode_along(tmp_path): directory = _with_cache(_extracted(tmp_path, [_entry()])) entries, err, meta = smt.read_downloaded_leg(directory) assert err == "" and entries - assert meta["cache"] == {"jax": "hit", "datasets": "miss", "epoch": "1"} + assert meta["cache"] == {"jax": "hit", "datasets": "miss", + "numba": "hit", "epoch": "1", "setup_s": 104.0} def test_a_leg_without_the_sidecar_is_unknown_never_a_miss(tmp_path): @@ -690,7 +789,9 @@ def test_a_leg_without_the_sidecar_is_unknown_never_a_miss(tmp_path): distinguishable from "nothing was restored".""" entries, err, meta = smt.read_downloaded_leg(_extracted(tmp_path, [_entry()])) assert err == "" and meta["cache"] == {"jax": "unknown", - "datasets": "unknown", "epoch": ""} + "datasets": "unknown", + "numba": "unknown", "epoch": "", + "setup_s": None} def test_an_unparseable_sidecar_reads_unknown_and_loses_no_timings(tmp_path): @@ -706,7 +807,8 @@ def test_the_sidecar_leg_and_the_rollup_carry_the_cache_state(tmp_path): "error": ""}] side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") (leg,) = side["legs"] - assert leg["cache"] == {"jax": "hit", "datasets": "miss", "epoch": "1"} + assert leg["cache"] == {"jax": "hit", "datasets": "miss", + "numba": "hit", "epoch": "1", "setup_s": 104.0} roll = smt.aggregate([side], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) assert roll["repos"][0]["cache"] == leg["cache"] @@ -719,7 +821,8 @@ def test_a_failed_leg_has_no_cache_state_either(tmp_path): {"artifact": _selected(), "dir": None, "error": "HTTP 403"}, ], "T") (leg,) = side["legs"] - assert leg["cache"] == {"jax": "unknown", "datasets": "unknown", "epoch": ""} + assert leg["cache"] == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown", "epoch": "", "setup_s": None} def test_drift_is_never_classified_across_two_known_cache_states(): @@ -748,6 +851,25 @@ def test_drift_is_classified_normally_for_equal_or_unknown_cache_states(): thr, run_id=7)[0] == "warn" +def test_the_drift_rule_can_be_told_which_field_the_baseline_keeps_it_in(): + """The scripts rows compare on the JAX cache alone (`cache_jax`, the + default); the unit rows compare on jax and numba COMBINED and keep that + under `cache_state`, because calling a combined state `cache_jax` would + name it after half of what it means.""" + thr = {"slow_factor": 2.0, "min_delta_s": 5} + unit_prev = dict(_prev_row(10.0), cache_state="hit") + assert smt.classify_drift(30.0, unit_prev, thr, run_id=7, cache="miss", + prev_cache_key="cache_state") == ("ok", None, None) + # Read under the DEFAULT key that row does not carry, the same pair + # compares normally — which is the point of naming the field explicitly. + assert smt.classify_drift(30.0, unit_prev, thr, run_id=7, + cache="miss")[0] == "warn" + # Equal states compare normally under either name. + same = dict(_prev_row(10.0), cache_state="miss") + assert smt.classify_drift(30.0, same, thr, run_id=7, cache="miss", + prev_cache_key="cache_state")[0] == "warn" + + def test_the_board_fallback_carries_the_cache_state_through(tmp_path): """The published board is the other source of a previous row, so the state a baseline was measured under has to survive that path too.""" diff --git a/tests/test_timings.py b/tests/test_timings.py index 0d1a7a7d..e1de056d 100644 --- a/tests/test_timings.py +++ b/tests/test_timings.py @@ -437,7 +437,10 @@ def test_previous_unit_rows_takes_the_latest_line_per_leg_and_drives_drift(tmp_p prev = timings.previous_unit_rows(unit_dir) assert prev[("RepoA", "3.12", NODEID)] == { - "seconds": 4.0, "run_id": 8, "run_url": RUN_URL} + "seconds": 4.0, "run_id": 8, "run_url": RUN_URL, + # A rollup with no cache block: unknown, and it compares as it always + # did (below). + "cache_state": "unknown"} assert prev[("RepoA", "3.13", NODEID)]["seconds"] == 0.5 thr = {"slow_factor": 2.0, "min_delta_s": 2} @@ -796,28 +799,144 @@ def test_the_committed_record_carries_the_legacy_and_fast_tests_boundaries(): # scratch are not the same measurement. The record stores which it was, because # a baseline that cannot say is a baseline nothing can compare against. -def _cached_rollup(jax="hit", datasets="miss", **kw): +def _cached_rollup(jax="hit", datasets="miss", numba="hit", **kw): rollup = _smoke_rollup(**kw) - rollup["repos"][0]["cache"] = {"jax": jax, "datasets": datasets, "epoch": "1"} + rollup["repos"][0]["cache"] = {"jax": jax, "datasets": datasets, + "numba": numba, "epoch": "1"} return rollup def test_the_scripts_line_records_the_cache_state_beside_the_seconds(): (line,) = timings.scripts_lines_from_rollup(_cached_rollup(), TODAY)["RepoA"] - # Two keys, not three: the epoch is a property of the workflow's keys, not - # of the measurement. - assert line["cache"] == {"jax": "hit", "datasets": "miss"} + # One key per cache the smoke gate restores, and no epoch: that is a + # property of the workflow's keys, not of the measurement. + assert line["cache"] == {"jax": "hit", "datasets": "miss", "numba": "hit"} def test_a_rollup_from_before_the_sidecar_records_unknown_not_a_miss(): """Every rollup older than the cache work. "We do not know" must stay distinguishable from "nothing was restored".""" (line,) = timings.scripts_lines_from_rollup(_smoke_rollup(), TODAY)["RepoA"] - assert line["cache"] == {"jax": "unknown", "datasets": "unknown"} + assert line["cache"] == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown"} junk = _smoke_rollup() junk["repos"][0]["cache"] = {"jax": "warm", "datasets": None} (line,) = timings.scripts_lines_from_rollup(junk, TODAY)["RepoA"] - assert line["cache"] == {"jax": "unknown", "datasets": "unknown"} + assert line["cache"] == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown"} + + +# --- the gate's fixed overhead, recorded beside the seconds ----------------- +# A fifth of every `_test` leg is spent before the first script runs. The +# record carries it so a leg whose total fell while its setup rose cannot read +# as a leg that got faster. + +def test_the_scripts_line_records_the_setup_seconds_beside_the_cache(): + rollup = _cached_rollup() + rollup["repos"][0]["cache"]["setup_s"] = 104.0 + (line,) = timings.scripts_lines_from_rollup(rollup, TODAY)["RepoA"] + assert line["setup_s"] == 104.0 + # Beside `cache`, not inside it: `cache` says what the measurement was + # taken UNDER and every value in it is a state string; this is a + # measurement of its own, of the part no script is responsible for. + assert "setup_s" not in line["cache"] + + +def test_a_line_whose_rollup_never_measured_the_setup_records_null(): + """Every rollup older than the mark steps, and every leg whose marks did + not survive. A fabricated 0 would claim a gate with no fixed cost.""" + (line,) = timings.scripts_lines_from_rollup(_smoke_rollup(), TODAY)["RepoA"] + assert line["setup_s"] is None + for junk in ("104", True, -5, float("nan"), None): + rollup = _cached_rollup() + rollup["repos"][0]["cache"]["setup_s"] = junk + (line,) = timings.scripts_lines_from_rollup(rollup, TODAY)["RepoA"] + assert line["setup_s"] is None, junk + # Zero is a reading, not an absence. + rollup = _cached_rollup() + rollup["repos"][0]["cache"]["setup_s"] = 0 + (line,) = timings.scripts_lines_from_rollup(rollup, TODAY)["RepoA"] + assert line["setup_s"] == 0.0 + + +# --- the unit record: jax and numba, combined -------------------------------- +# A library suite is conditioned by two caches at once, so a comparison is only +# safe when both sides ran the same way — and the combined state has its own +# field name because it means something different from the scripts record's +# `cache_jax`. + +def _unit_cached_rollup(jax="hit", numba="hit", **kw): + rollup = _unit_rollup(**kw) + rollup["repos"][0]["cache"] = {"jax": jax, "datasets": "miss", + "numba": numba, "epoch": "1"} + return rollup + + +def test_the_unit_line_records_the_two_caches_it_was_measured_under(): + (line,) = timings.unit_lines_from_rollup(_unit_cached_rollup(numba="miss"), + TODAY)["RepoA"] + # Two keys, not the scripts record's three: the libraries' gate has no + # dataset cache, so a `datasets` field here could only say "unknown". + assert line["cache"] == {"jax": "hit", "numba": "miss"} + + +def test_a_unit_rollup_from_before_the_sidecar_records_unknown_on_both(): + (line,) = timings.unit_lines_from_rollup(_unit_rollup(), TODAY)["RepoA"] + assert line["cache"] == {"jax": "unknown", "numba": "unknown"} + junk = _unit_rollup() + junk["repos"][0]["cache"] = {"jax": "warm", "numba": None} + (line,) = timings.unit_lines_from_rollup(junk, TODAY)["RepoA"] + assert line["cache"] == {"jax": "unknown", "numba": "unknown"} + + +def test_the_combined_unit_cache_state_is_hit_only_when_both_were(): + """Half-hot against half-cold is not a comparison anybody can read, so + every mixture is unknown and compares exactly as it always did.""" + state = timings.unit_cache_state + assert state({"jax": "hit", "numba": "hit"}) == "hit" + assert state({"jax": "miss", "numba": "miss"}) == "miss" + for mixed in ({"jax": "hit", "numba": "miss"}, + {"jax": "miss", "numba": "hit"}, + {"jax": "hit", "numba": "unknown"}, + {"jax": "unknown", "numba": "hit"}, + {"jax": "hit"}, {}, None, "nonsense"): + assert state(mixed) == "unknown", mixed + + +def test_previous_unit_rows_hands_the_combined_state_to_the_drift_rule(tmp_path): + unit_dir = tmp_path / "unit" + path = timings.unit_file("RepoA", tmp_path) + timings.append_unit(path, timings.unit_lines_from_rollup( + _unit_cached_rollup(seconds=4.0), TODAY)["RepoA"]) + row = timings.previous_unit_rows(unit_dir)[("RepoA", "3.12", NODEID)] + # Named for what it is — jax AND numba — not for half of it. + assert row["cache_state"] == "hit" and "cache_jax" not in row + + thr = {"slow_factor": 2.0, "min_delta_s": 2} + # 4s → 12s is a 3x, and it is not reported: the baseline ran hot. + assert smoke_timings.classify_drift( + 12.0, row, thr, run_id=9, cache="miss", + prev_cache_key="cache_state") == ("ok", None, None) + assert smoke_timings.classify_drift( + 12.0, row, thr, run_id=9, cache="hit", + prev_cache_key="cache_state")[0] == "warn" + + +def test_a_legacy_unit_line_reads_unknown_and_compares_as_it_always_did(tmp_path): + """The record is append-only and full of lines written before this field + existed; they must keep comparing exactly as they did.""" + unit_dir = tmp_path / "unit" + path = timings.unit_file("RepoA", tmp_path) + (line,) = timings.unit_lines_from_rollup(_unit_cached_rollup(seconds=4.0), + TODAY)["RepoA"] + line.pop("cache") + timings.append_unit(path, [line]) + row = timings.previous_unit_rows(unit_dir)[("RepoA", "3.12", NODEID)] + assert row["cache_state"] == "unknown" + thr = {"slow_factor": 2.0, "min_delta_s": 2} + assert smoke_timings.classify_drift( + 12.0, row, thr, run_id=9, cache="hit", + prev_cache_key="cache_state")[0] == "warn" def test_previous_script_rows_hands_the_cache_state_to_the_drift_rule(tmp_path): diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index 8b824c89..fee45ff0 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -15,8 +15,9 @@ import json -from heart import dashboard +from heart import dashboard, timings from heart.checks import import_time as legacy_import +from heart.checks import smoke_timings as smt from heart.checks import unit_test_timing as legacy_unit from heart.checks import unit_timings as ut @@ -76,10 +77,32 @@ def _import_json(*, seconds=3.6, returncode=0, schema="import_time/1", }) -def _extracted(tmp_path, *, sub="art", junit=..., imports=...): +def _cache_state(*, jax_hit=True, numba_hit=False, epoch="1"): + """The sidecar `lib-tests.yml` writes: jax and numba, no datasets section. + + The libraries' gate has no dataset cache, so it writes no `datasets` + section — and the reader must not turn that into a claim about one. + """ + return json.dumps({ + "schema": smt.CACHE_STATE_SCHEMA, + "epoch": epoch, + "jax": {"path": "/w/.pyauto_jax_cache", "hit": jax_hit, + "restored_key": "pyauto-jax-...-e1-" if jax_hit else "", + "exact": False, "size_mb_before": 40, "size_mb_after": 55, + "entries_before": 120, "entries_after": 180}, + "numba": {"path": "/w/.numba_cache", "hit": numba_hit, + "restored_key": "pyauto-numba-...-e1-" if numba_hit else "", + "exact": False, "size_mb_before": 3, "size_mb_after": 9, + "entries_before": 30, "entries_after": 61}, + }) + + +def _extracted(tmp_path, *, sub="art", junit=..., imports=..., cache=None): """An extracted-artifact directory holding either/both dataset files.""" d = tmp_path / sub d.mkdir(parents=True, exist_ok=True) + if cache is not None: + (d / smt.CACHE_STATE_FILENAME).write_text(cache) if junit is ...: junit = _junit() if imports is ...: @@ -750,3 +773,93 @@ def _line(date, run_id, seconds, import_s): assert json.loads( (legacy / "import_time.json").read_text())["new_packages_no_baseline"] == 1 capsys.readouterr() + + +# --- the cache state a suite was measured under ------------------------------ +# `lib-tests.yml` restores a JAX compile cache and a numba function cache and +# writes the same `cache_state.json` sidecar the smoke gate writes, in the same +# artifact. A suite that recompiled everything is not a slower suite, it is a +# differently conditioned one. + +def test_a_leg_carries_its_cache_state_when_the_sidecar_rode_along(tmp_path): + tests, suite, imported, err, meta = ut.read_downloaded_leg( + _extracted(tmp_path, cache=_cache_state(jax_hit=True, numba_hit=False))) + # The datasets read is the sidecar's own — the libraries' gate has no such + # cache, and the unit consumers do not read that key. + assert err == "" and tests and imported is not None + assert meta["cache"]["jax"] == "hit" and meta["cache"]["numba"] == "miss" + assert meta["cache"]["epoch"] == "1" + + +def test_a_leg_without_the_sidecar_is_unknown_never_a_miss(tmp_path): + """Every artifact older than the sidecar. "We do not know" must stay + distinguishable from "nothing was restored".""" + *_, meta = ut.read_downloaded_leg(_extracted(tmp_path)) + assert meta["cache"] == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown", "epoch": "", + "setup_s": None} + + +def test_a_leg_with_neither_dataset_is_still_the_no_dataset_error(tmp_path): + """A sidecar with no timings beside it is cache state for a measurement + that does not exist: the leg's verdict is unchanged by the addition.""" + directory = _extracted(tmp_path, junit=None, imports=None, + cache=_cache_state()) + tests, suite, imported, err, meta = ut.read_downloaded_leg(directory) + assert err == ut.NO_DATASET_ERROR + assert tests == [] and suite == {} and imported is None and meta == {} + + +def test_the_sidecar_leg_and_the_rollup_carry_the_cache_state(tmp_path): + side = _sidecar(tmp_path, cache=_cache_state(jax_hit=True, numba_hit=True)) + (leg,) = side["legs"] + assert leg["cache"]["jax"] == "hit" and leg["cache"]["numba"] == "hit" + roll = ut.aggregate([side], "T", THRESHOLDS) + assert roll["repos"][0]["cache"] == leg["cache"] + + +def test_a_failed_leg_has_no_cache_state_either(tmp_path): + side = ut.build_sidecar(REPO, "libraries", OWNER, [ + {"artifact": _selected(), "dir": None, "error": "HTTP 403"}, + ], "T") + (leg,) = side["legs"] + assert leg["cache"] == {"jax": "unknown", "datasets": "unknown", + "numba": "unknown", "epoch": "", "setup_s": None} + + +def test_the_combined_state_is_hit_only_when_both_caches_were(): + """The truth table the unit drift rule turns on: half-hot against half-cold + is not a comparison anybody can read.""" + assert timings.unit_cache_state({"jax": "hit", "numba": "hit"}) == "hit" + assert timings.unit_cache_state({"jax": "miss", "numba": "miss"}) == "miss" + for mixed in ({"jax": "hit", "numba": "miss"}, + {"jax": "miss", "numba": "hit"}, + {"jax": "hit", "numba": "unknown"}, + {"jax": "hit"}, {}, None): + assert timings.unit_cache_state(mixed) == "unknown", mixed + + +def test_drift_is_never_classified_across_two_known_cache_states(tmp_path): + """A cold suite against a hot baseline is a recompile; a hot one against a + cold baseline is the cache landing. Neither is a change anybody made.""" + side = _sidecar(tmp_path, + junit=_junit(_case(time="12.0")), + cache=_cache_state(jax_hit=False, numba_hit=False)) + hot_prev = {(REPO, "3.12", NODEID): { + "seconds": 1.5, "run_id": 6, "run_url": PREV_RUN_URL, + "cache_state": "hit"}} + (row,) = ut.aggregate([side], "T", THRESHOLDS, + record_prev_rows=hot_prev)["tests"] + # 1.5s → 12.0s is an 8x, and it is not reported: the baseline ran hot. + assert row["state"] == "ok" and row["ratio"] is None + + # Two cold runs are comparable, and so is a baseline of unknown state. + cold_prev = {(REPO, "3.12", NODEID): { + "seconds": 1.5, "run_id": 6, "run_url": PREV_RUN_URL, + "cache_state": "miss"}} + (row,) = ut.aggregate([side], "T", THRESHOLDS, + record_prev_rows=cold_prev)["tests"] + assert row["state"] == "warn" and row["ratio"] == 8.0 + (row,) = ut.aggregate([side], "T", THRESHOLDS, + record_prev_rows=_prev_rows(1.5))["tests"] + assert row["state"] == "warn" diff --git a/timings/README.md b/timings/README.md index 5ee0851d..134c2c3f 100644 --- a/timings/README.md +++ b/timings/README.md @@ -63,7 +63,7 @@ joined to its `rows` (the timed entries): {"date":"2026-09-05","at":"2026-09-04T10:00:00Z","python":"3.12","run_id":7, "run_url":"https://ci.invalid/OwnerX/RepoA/actions/runs/7", "head_branch":"feat/x","head_sha":"abc123","env_profile":"smoke", - "cache":{"jax":"hit","datasets":"miss"}, + "cache":{"jax":"hit","datasets":"miss","numba":"hit"},"setup_s":104, "entries":{"imaging/x.py":[12.5,"passed",600.0]}} ``` @@ -79,13 +79,15 @@ 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. * **`cache` is the condition the measurement was taken under**, not a - measurement of its own: `jax` and `datasets` are each `hit`, `miss` or - `unknown`, read from the `cache_state.json` sidecar the smoke workflow + measurement of its own: `jax`, `datasets` and `numba` are each `hit`, `miss` + or `unknown`, read from the `cache_state.json` sidecar the smoke workflow uploads beside the timings dataset. The CI job restores a JAX compilation - cache and the workspace's simulated `dataset/` tree between runs, so two - otherwise identical legs can differ by the whole cost of recompiling or - re-simulating. A line recorded before the sidecar existed reads `unknown` on - both sides — the honest absence, never a fabricated `miss`. + cache, a numba function cache and the workspace's simulated `dataset/` tree + between runs, so two otherwise identical legs can differ by the whole cost of + recompiling or re-simulating. A line recorded before the sidecar existed + reads `unknown` on every side — the honest absence, never a fabricated + `miss` — and so does `numba` on a line recorded before that cache was + added. From this follows the one rule the comparison obeys: @@ -96,6 +98,20 @@ joined to its `rows` (the timed entries): > crying wolf on exactly the runs where the cache is doing its job. An > `unknown` on either side compares exactly as it did before the field > existed. +* **`setup_s` is the gate's FIXED overhead**, in seconds: job start to the + first script — checkout, dependency-chain clone, python setup, install — + read from the same `cache_state.json` sidecar, which gets it by differencing + two `date +%s` marks the smoke workflow writes at the top of the job and + immediately before the runner. It sits beside `cache` rather than inside it + because `cache` says what a measurement was taken *under* and every value in + it is a state string; this is a measurement of its own, of the part of the + gate no script is responsible for. It is what makes a leg whose `total_s` + fell while its install got slower readable as what it is. + + `null` for every line recorded before the marks existed, and for every leg + where either mark did not survive — **never 0**, which would claim a gate + that spent no time getting ready. The board renders it as `· setup 104s` + after the coverage tail, and only when it is known. ### `unit/.jsonl` — one line per leg per run @@ -107,10 +123,21 @@ libraries' own CI feeds through {"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, + "cache":{"jax":"hit","numba":"miss"}, "suite":{"tests":1500,"failures":0,"errors":0,"skipped":3,"wall_s":412.0}, "slowest":{"tests/foo/test_bar.py::test_x":12.5}} ``` +* **`cache` is the condition this suite was measured under**, exactly as on a + scripts line, and for the same reason. Two keys, not three: the libraries' + gate restores a JAX compilation cache and a numba function cache, and it has + no dataset cache at all, so a `datasets` key here could only ever say + `unknown`. The drift rule turns on the two COMBINED — `hit` when the leg had + both, `miss` when it had neither, `unknown` for every mixture — carried into + the previous row as `cache_state` (`heart.timings.unit_cache_state`), which + is a different field name from the scripts record's `cache_jax` because it + means a different thing. + * **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 — diff --git a/timings/unit_import_census_2026-09.md b/timings/unit_import_census_2026-09.md index e53b6585..8a30f1f9 100644 --- a/timings/unit_import_census_2026-09.md +++ b/timings/unit_import_census_2026-09.md @@ -433,6 +433,15 @@ quadrature node. | `lib-tests.yml` | has **no** JAX cache, **no** numba cache, and no `NUMBA_CACHE_DIR`. It sets `JAX_ENABLE_X64=True` and runs `pytest --cov --cov-report xml --junitxml=…` serially | | phase 8 diagnosis | cold numba was "the whole of the 86 s → 18 s step" on a pixelization script; the same class, on the other workflow | +**2026-09-06 correction:** `smoke-tests.yml` cached the JAX compile cache and the +simulated datasets only; numba was at `/tmp/numba_cache` with no restore and no save, so +every run recompiled it. PyAutoHeart#215 adds the numba cache to **both** workflows — +`lib-tests.yml` gains a JAX compile cache and a numba cache with `smoke-tests.yml`'s +discipline, `smoke-tests.yml` gains the numba half it never had — plus the mtime +content-stamp that makes it hit: numba stamps each entry with its source's +`(st_mtime, st_size)`, which a fresh clone or a fresh `pip install` changes, so without +the stamp a restored numba cache would miss every entry it holds. + ### 5.4 `model.info` / `replace_promise` — agreed, and already fixed Recorded here because it is the model case of the three sides agreeing. Phase 8 measured