From 54e99b2c3cf9d8164d9c21f6476a26d17011759f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 00:32:09 +0000 Subject: [PATCH] feat(smoke-tests): JAX compile + simulated-dataset caches across runs; cache state on every timing row (#210) The reusable smoke workflow now restores and saves the JAX persistent compilation cache (keyed on runner OS x Python leg x jaxlib x a manual epoch salt) and the workspace's simulated datasets (keyed on the simulator-script hash x the dependency-chain SHAs x the salt, no broader fallback), both as non-fatal steps, and writes test-results/cache_state.json so every per-script row the Heart ingests says whether it ran hot or cold. smoke_timings, the timings/ record and the board carry that state additively, and drift is never classified across two different known cache states. Readiness verdict and badge untouched; the runner command is unchanged. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0151gQm9fk3XGLi5f18Urdba --- .github/workflows/smoke-tests.yml | 243 ++++++++++++++++++++++++++++++ heart/checks/smoke_timings.py | 149 +++++++++++++++++- heart/dashboard.py | 10 +- heart/timings.py | 37 ++++- tests/test_dashboard.py | 48 ++++++ tests/test_smoke_tests_wiring.py | 232 ++++++++++++++++++++++++++++ tests/test_smoke_timings.py | 142 +++++++++++++++++ tests/test_timings.py | 63 +++++++- timings/README.md | 19 +++ 9 files changed, 932 insertions(+), 11 deletions(-) create mode 100644 tests/test_smoke_tests_wiring.py diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml index 71123fd7..b8a96a0f 100644 --- a/.github/workflows/smoke-tests.yml +++ b/.github/workflows/smoke-tests.yml @@ -35,6 +35,21 @@ name: Smoke Tests (reusable) # organism reuse this workflow without modification. # # The workflow filename is intentionally stable for downstream callers. +# +# TWO CACHES ride this workflow, both added as non-fatal steps and both 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 +# 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 +# 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. on: workflow_call: @@ -125,6 +140,11 @@ jobs: needs: changes if: needs.changes.outputs.docs_only != 'true' 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: @@ -172,6 +192,99 @@ jobs: pip install pyyaml bash workspace/.github/scripts/smoke_install.sh + - name: Resolve cache keys + # Three 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; + # 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, + # because an edit to one changes the datasets it produces. + # Non-fatal like every step this workflow gained: an unresolvable key + # degrades to a cache miss, never to a red gate. + id: keys + continue-on-error: true + env: + # Via env, never interpolated into the script body — the clone step + # above records why: `chain` is caller-supplied text. + CHAIN: ${{ inputs.chain }} + # hashFiles() is an expression, not a shell command, so it resolves + # here and the script reads it back as a plain variable. + SIMS_HASH: ${{ hashFiles('workspace/**/simulator*.py', 'workspace/**/simulator/**', 'workspace/**/simulators/**') }} + run: | + jaxlib="$(python -c 'import jaxlib; print(jaxlib.__version__)' 2>/dev/null || echo nojax)" + chain="$(for dep in $CHAIN; do git -C "$dep" rev-parse HEAD; done | sha256sum | cut -c1-16)" + { + echo "jaxlib=${jaxlib:-nojax}" + echo "chain=$chain" + echo "sims=$SIMS_HASH" + } >> "$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 simulated datasets + # ONE fallback line and no broader one, deliberately: a different + # simulator script or a different library commit MUST miss, because the + # FITS it would restore are not the FITS this run would have written. + # Correctness over hit rate. + # + # Not keyed on the python leg: simulated FITS do not depend on the + # interpreter's minor version, so both legs share one entry. + # + # Restoring is safe whatever lands here — `should_simulate` keeps a + # restored dataset only while its resolution regime matches the one in + # force, and deletes and re-simulates it when it does not. + uses: actions/cache/restore@v4 + id: dataset-cache + continue-on-error: true + with: + path: workspace/dataset + key: pyauto-datasets-${{ runner.os }}-e${{ env.PYAUTO_CACHE_EPOCH }}-sim${{ steps.keys.outputs.sims }}-chain${{ steps.keys.outputs.chain }}-${{ github.run_id }} + restore-keys: | + pyauto-datasets-${{ runner.os }}-e${{ env.PYAUTO_CACHE_EPOCH }}-sim${{ steps.keys.outputs.sims }}-chain${{ steps.keys.outputs.chain }}- + + - 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 + DS_PATH: workspace/dataset + 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 "$DS_PATH") + ds_mb="$1"; ds_n="$2" + { + echo "jax_mb=$jax_mb" + echo "jax_n=$jax_n" + echo "ds_mb=$ds_mb" + echo "ds_n=$ds_n" + } >> "$GITHUB_OUTPUT" + - name: Prepare cache dirs run: mkdir -p /tmp/numba_cache /tmp/matplotlib @@ -214,6 +327,12 @@ jobs: NUMBA_CACHE_DIR: /tmp/numba_cache MPLCONFIGDIR: /tmp/matplotlib PYTHONPATH: ${{ github.workspace }}/PyAutoHands/autohands + # autonerves defaults this to ~/.cache/pyauto_jax when it is unset; an + # explicit workspace path is the one the cache steps above and below + # can name. The runner copies this job env into every script + # subprocess, so each script's JAX writes to and reads from the same + # compilation cache instead of one per-process temporary. + JAX_COMPILATION_CACHE_DIR: ${{ github.workspace }}/.pyauto_jax_cache # Via env, never interpolated into the script body: these inputs reach # here from a caller's workflow_dispatch, and `${{ }}` inside `run:` # would splice their text straight into the shell. @@ -230,6 +349,106 @@ jobs: fi python "$RUNNER" $RUNNER_ARGS + - name: Record cache state (rides the smoke-timings artifact) + # This file is the unit of measurement for the whole cache story: every + # per-script timing row the Heart ingests from the artifact below can + # then say whether that script ran hot or cold. Without it a timing + # dataset reads a cache landing as a 4x speedup and its invalidation as + # a 4x 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. + id: cache-state + if: always() + continue-on-error: true + env: + EPOCH: ${{ env.PYAUTO_CACHE_EPOCH }} + 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 }} + DS_PATH: workspace/dataset + DS_KEY_RESTORED: ${{ steps.dataset-cache.outputs.cache-matched-key }} + DS_EXACT: ${{ steps.dataset-cache.outputs.cache-hit }} + DS_MB_BEFORE: ${{ steps.cache-before.outputs.ds_mb }} + DS_N_BEFORE: ${{ steps.cache-before.outputs.ds_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", ""), + ) + datasets, ds_changed = section( + env("DS_PATH", ""), env("DS_KEY_RESTORED", ""), + env("DS_EXACT", ""), env("DS_MB_BEFORE", ""), + env("DS_N_BEFORE", ""), + ) + payload = { + "schema": "cache_state/1", + "epoch": env("EPOCH", ""), + "jax": jax, + "datasets": datasets, + } + out = Path("workspace/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("ds_changed=%s\n" + % ("true" if ds_changed else "false")) + PY + - name: Upload the smoke report dir (per-script timings) # PyAutoHands#264. The runner writes a consolidated smoke_timings.json # into its report dir on every report write — one row per executed @@ -265,6 +484,30 @@ jobs: workspace/**/smoke_timings.json if-no-files-found: ignore + - 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 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` + # would keep it (its regime matches), and caching it would poison every + # later run that restored it. Same no-op guard as above. + if: success() && steps.cache-state.outputs.ds_changed == 'true' + continue-on-error: true + uses: actions/cache/save@v4 + with: + path: workspace/dataset + key: pyauto-datasets-${{ runner.os }}-e${{ env.PYAUTO_CACHE_EPOCH }}-sim${{ steps.keys.outputs.sims }}-chain${{ steps.keys.outputs.chain }}-${{ github.run_id }} + - name: Slack notify on failure if: ${{ failure() }} uses: slackapi/slack-github-action@v1.21.0 diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 08ad49ae..445a8086 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -53,6 +53,13 @@ keyed by ``(python, run_id)``; the published board is the same artifact this render produces, so a Pages gap loses it. The board stays as the fallback, and the ``performance.scripts.rows`` block is written either way. +* **Drift is 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. * **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. @@ -73,6 +80,7 @@ "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"}, "entries": [{"entry": "imaging/x.py", "kind": "script", "status": "passed", "seconds": 12.5, "cap_s": 600.0, "exit_code": 0}], @@ -86,11 +94,11 @@ {"ts", "repos": [{repo, python, run_id, run_url, head_branch, head_sha, - env_profile, at, entries, timed, total_s, error, + env_profile, cache, at, entries, timed, total_s, error, slowest: [...]}], "rows": [{repo, python, entry, kind, status, seconds, cap_s, exit_code, - run_id, run_url, prev_s, prev_run_id, ratio, delta_s, state, - prompt}], + run_id, run_url, prev_s, prev_run_id, cache_jax, + prev_cache_jax, ratio, delta_s, state, prompt}], "slowed": [...], "events": [...], "errors": [{repo, error}], "thresholds": {...}} @@ -126,6 +134,19 @@ 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. +CACHE_STATE_FILENAME = "cache_state.json" +CACHE_STATE_SCHEMA = "cache_state/1" + +# What every consumer sees when no sidecar rode along: not "miss", which would +# be a claim, but "unknown", which is the honest absence. Older artifacts +# predate the sidecar entirely and must keep comparing exactly as they did. +UNKNOWN_CACHE_STATE = "unknown" +CACHE_STATES = ("hit", "miss") + # Statuses the producer emits; counted per leg so the coverage behind a total # stays visible next to it. TRACKED_STATUSES = ("passed", "failed", "skipped", "timeout") @@ -300,7 +321,85 @@ def parse_timings(text: str) -> tuple[dict[str, Any] | None, str]: ) -def read_downloaded_leg(directory: Path | str) -> tuple[list[dict[str, Any]], str, dict[str, str]]: +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. + """ + try: + data = json.loads(text) + except (TypeError, ValueError): + return None, f"{CACHE_STATE_FILENAME} was not valid JSON" + if not isinstance(data, dict): + return None, f"{CACHE_STATE_FILENAME} was not an object" + if str(data.get("schema") or "") != CACHE_STATE_SCHEMA: + return None, f"not a {CACHE_STATE_SCHEMA} sidecar" + + def _section(key: str) -> tuple[str, str]: + block = data.get(key) + block = block if isinstance(block, dict) else {} + return ("hit" if block.get("hit") else "miss", + str(block.get("restored_key") or "")) + + jax_state, jax_key = _section("jax") + ds_state, ds_key = _section("datasets") + return ( + { + "jax": jax_state, + "datasets": ds_state, + # 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, + }, + "", + ) + + +def cache_view(cache: Any) -> dict[str, str]: + """A cache state normalised to the three 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. + """ + src = cache if isinstance(cache, dict) else {} + + def _state(key: str) -> str: + value = str(src.get(key) or "") + return value if value in CACHE_STATES else UNKNOWN_CACHE_STATE + + return {"jax": _state("jax"), "datasets": _state("datasets"), + "epoch": str(src.get("epoch") or "")} + + +def read_cache_state(directory: Path | str) -> dict[str, str]: + """The first parseable ``cache_state.json`` under one extracted artifact. + + Sorted path order, first file that parses wins — the same rule the timings + datasets merge under, so an artifact carrying several report dirs resolves + deterministically. No sidecar at all is ``unknown``, never a miss. + """ + for path in sorted(Path(directory).rglob(CACHE_STATE_FILENAME)): + try: + text = path.read_text() + except OSError: + continue + state, err = parse_cache_state(text) + if state is None or err: + continue + return cache_view(state) + return cache_view(None) + + +def read_downloaded_leg(directory: Path | str) -> tuple[list[dict[str, Any]], str, dict[str, Any]]: """Every ``smoke_timings.json`` under one extracted artifact → (entries, error, meta). An artifact may hold more than one dataset (a report dir per project, the @@ -313,10 +412,14 @@ def read_downloaded_leg(directory: Path | str) -> tuple[list[dict[str, Any]], st unreadable get the SAME honest error: what we have is no usable dataset either way, and the leg keeps its provenance so the board can say which run it could not read. + + ``meta["cache"]`` is the leg's cache state, read from the ``cache_state.json`` + sidecar the workflow uploads in the same artifact — ``unknown`` on both + sides when no sidecar rode along, which is every artifact older than it. """ root = Path(directory) entries: dict[str, dict[str, Any]] = {} - meta: dict[str, str] = {} + meta: dict[str, Any] = {} for path in sorted(root.rglob(TIMINGS_FILENAME)): try: text = path.read_text() @@ -335,6 +438,7 @@ def read_downloaded_leg(directory: Path | str) -> tuple[list[dict[str, Any]], st entries.setdefault(entry["entry"], entry) if not entries and not meta: return [], NO_DATASET_ERROR, {} + meta["cache"] = read_cache_state(root) return [entries[key] for key in sorted(entries)], "", meta @@ -425,7 +529,7 @@ def build_sidecar( ) leg_error = str(leg.get("error") or "") entries: list[dict[str, Any]] = [] - meta: dict[str, str] = {} + meta: dict[str, Any] = {} if not leg_error: directory = leg.get("dir") if directory: @@ -444,6 +548,9 @@ def build_sidecar( "head_sha": str(art.get("head_sha") or ""), "at": str(art.get("created_at") or ""), "env_profile": meta.get("env_profile", ""), + # Whether this leg ran hot or cold. A leg we could not read has + # no cache state either — "unknown", not a fabricated miss. + "cache": cache_view(meta.get("cache")), "error": leg_error, "entries": entries, "counts": counts, @@ -465,6 +572,9 @@ def prev_rows_of(prev_board: Any) -> dict[tuple[str, str, str], dict[str, Any]]: Anything unexpected (a 404 page, an older board with no scripts block, a rows list of nulls) degrades to no previous observation: a publish gap costs a comparison, never a render. + + The row is carried WHOLE, so ``cache_jax`` reaches ``classify_drift`` with + it on this fallback path exactly as it does on the committed-record path. """ out: dict[tuple[str, str, str], dict[str, Any]] = {} if not isinstance(prev_board, dict): @@ -496,6 +606,7 @@ def classify_drift( prev_row: Any, thresholds: dict[str, float], run_id: Any = None, + cache: Any = None, ) -> tuple[str, float | None, float | None]: """(state, ratio, delta_s) — ``warn`` needs BOTH gates, else ``ok``. @@ -504,6 +615,14 @@ def classify_drift( render, so a second render of the same day sees the same run's rows, and 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. """ now = _as_float(seconds) if not isinstance(prev_row, dict): @@ -514,6 +633,11 @@ def classify_drift( prev_run = prev_row.get("run_id") 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 "") + if (now_cache in CACHE_STATES and prev_cache in CACHE_STATES + and now_cache != prev_cache): + return "ok", None, None ratio = round(now / prev, 2) delta = round(now - prev, 1) if (ratio >= float(thresholds.get("slow_factor", 2.0)) @@ -568,6 +692,7 @@ 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")) if leg_error: # Provenance survives: which run we could not read, and why. errors.append({"repo": repo, "error": f"{python or '?'}: {leg_error}"}) @@ -595,7 +720,10 @@ def _name_of(side: Any) -> str: # `null` means the entry never ran. Not a zero-second row. continue prev_row = prev_rows.get((repo, python, name)) - state, ratio, delta = classify_drift(seconds, prev_row, thr, run_id=run_id) + state, ratio, delta = classify_drift( + seconds, prev_row, thr, run_id=run_id, + cache=leg_cache["jax"], + ) prev_s = _as_float((prev_row or {}).get("seconds")) prev_run_id = (prev_row or {}).get("run_id") prev_run_url = str((prev_row or {}).get("run_url") or "") @@ -612,6 +740,12 @@ def _name_of(side: Any) -> str: "run_url": run_url, "prev_s": prev_s, "prev_run_id": prev_run_id, + # Both sides of the cache comparison ride the row, so the + # next render reads back the state its baseline was + # measured under instead of re-deriving it. + "cache_jax": leg_cache["jax"], + "prev_cache_jax": str((prev_row or {}).get("cache_jax") + or UNKNOWN_CACHE_STATE), "ratio": ratio, "delta_s": delta, "state": state, @@ -632,6 +766,7 @@ def _name_of(side: Any) -> str: # commit was measured, and under which environment profile. "head_sha": str(leg.get("head_sha") or ""), "env_profile": str(leg.get("env_profile") or ""), + "cache": leg_cache, "at": at, "entries": len(entries), "timed": timed if timed is not None else len(leg_rows), diff --git a/heart/dashboard.py b/heart/dashboard.py index c1c90149..aac21f48 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -1102,7 +1102,15 @@ 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)" - prefix = f"{r.get('repo')} py{r.get('python') or '?'}:" + # 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 "" + 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 # run-to-run comparisons. Absent census adds no line at all. diff --git a/heart/timings.py b/heart/timings.py index 9cfff6dd..8788a67f 100644 --- a/heart/timings.py +++ b/heart/timings.py @@ -393,6 +393,27 @@ def gates_history( # --- scripts ----------------------------------------------------------------- +UNKNOWN_CACHE_STATE = "unknown" +_CACHE_STATES = ("hit", "miss") + + +def _cache_pair(cache: Any) -> dict[str, str]: + """``{"jax", "datasets"}`` out of a rollup leg's cache block. + + 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. + """ + src = cache if isinstance(cache, dict) else {} + out = {} + for key in ("jax", "datasets"): + value = str(src.get(key) or "") + out[key] = value if value in _CACHE_STATES else UNKNOWN_CACHE_STATE + return out + + def scripts_lines_from_rollup( rollup: Any, today: str ) -> dict[str, list[dict[str, Any]]]: @@ -452,6 +473,12 @@ def scripts_lines_from_rollup( # every line in the file has the same keys. "head_sha": str(leg.get("head_sha") or ""), "env_profile": str(leg.get("env_profile") or ""), + # Whether the leg ran hot or cold. Recorded beside the seconds + # 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")), "entries": {name: entries[name] for name in sorted(entries)}, }) for repo in out: @@ -492,8 +519,9 @@ def previous_script_rows( """``{(repo, python, entry): prev_row}`` — the last recorded observation. The shape is exactly what ``smoke_timings.classify_drift`` expects of a - previous row (``seconds``/``run_id``/``run_url``), so the record can stand - in for ``performance.scripts.rows`` off the published board. + previous row (``seconds``/``run_id``/``run_url``/``cache_jax``), so the + record can stand in for ``performance.scripts.rows`` off the published + board. The *latest* line per python leg wins, and "latest" is file order: the file is append-only, so the last line for a leg is the most recently recorded @@ -532,6 +560,11 @@ def previous_script_rows( "run_url": str(record.get("run_url") or ""), "status": str(triple[1]) if len(triple) > 1 else "", "cap_s": _as_float(triple[2]) if len(triple) > 2 else None, + # The cache state this baseline was measured under, so + # `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"], } return out diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index c66eb513..23eb3117 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1502,3 +1502,51 @@ def test_a_half_written_epoch_is_no_epoch_at_all(): timings_record=census), v, now=FRESH_NOW) assert "epoch" not in _section(board, "ci_timing").details[-1] + + +# --- hot or cold, on the line the numbers are on ---------------------------- +# The smoke gate restores a JAX compile cache between runs, so two legs of the +# 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): + slice_ = _smoke_timings_slice(**kw) + if jax is not None: + slice_["repos"][0]["cache"] = {"jax": jax, "datasets": "miss", + "epoch": "1"} + return make_snapshot(ci_timing=_ci_timing_slice(), + no_run_census=_no_run_slice(), smoke_timings=slice_) + + +def test_a_known_cache_state_is_bracketed_on_the_per_repo_line(): + for state in ("hit", "miss"): + sec = _section(dashboard.build_board(_cached_scripts_snapshot(state), + make_verdict(), now=FRESH_NOW), + "smoke_timings") + assert sec.details[0].startswith(f"RepoA py3.12 [jax cache {state}]:") + # 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.""" + unchanged = ("RepoA py3.12: imaging/x.py 30s · imaging/y.py 5s" + " (2 scripts, 35s total)") + for snap in (_cached_scripts_snapshot(None), + _cached_scripts_snapshot("unknown"), + _cached_scripts_snapshot("warm")): + sec = _section(dashboard.build_board(snap, make_verdict(), now=FRESH_NOW), + "smoke_timings") + assert sec.details[0] == unchanged + + +def test_the_scripts_block_inherits_the_cache_state_with_no_renderer_change(): + """`performance.scripts` carries the repos verbatim, so the Brain board and + the next render's fallback read the field without this file knowing it.""" + 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"} + assert d["schema_version"] == dashboard.SCHEMA_VERSION # purely additive diff --git a/tests/test_smoke_tests_wiring.py b/tests/test_smoke_tests_wiring.py new file mode 100644 index 00000000..ca6eddd1 --- /dev/null +++ b/tests/test_smoke_tests_wiring.py @@ -0,0 +1,232 @@ +"""tests/test_smoke_tests_wiring.py — the workspaces' reusable gate stays wired. + +`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: + +* **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. + +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 +not. + +PyYAML parses the bare `on:` key as boolean True, hence the `data[True]` reads +in the sibling wiring tests; nothing here needs the triggers. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +WORKFLOWS = Path(__file__).resolve().parent.parent / ".github" / "workflows" + +INSTALL_STEP = "Install (base + the workspace's own epilogue)" +RUNNER_STEP = "Run the workspace runner" +UPLOAD_STEP = "Upload the smoke report dir" + +KEYS_STEP = "Resolve cache keys" +JAX_RESTORE_STEP = "Restore the JAX compile cache" +DS_RESTORE_STEP = "Restore simulated datasets" +BEFORE_STEP = "Measure the caches before the run" +RECORD_STEP = "Record cache state" +JAX_SAVE_STEP = "Save the JAX compile cache" +DS_SAVE_STEP = "Save simulated datasets" + +NEW_STEPS = (KEYS_STEP, JAX_RESTORE_STEP, DS_RESTORE_STEP, BEFORE_STEP, + RECORD_STEP, JAX_SAVE_STEP, DS_SAVE_STEP) + + +def _job(): + data = yaml.safe_load((WORKFLOWS / "smoke-tests.yml").read_text()) + return data["jobs"]["smoke"] + + +def _steps(): + return _job()["steps"] + + +def _index(steps, needle): + for i, step in enumerate(steps): + if needle in step.get("name", ""): + return i + raise AssertionError(f"no step named like {needle!r} in smoke-tests.yml") + + +def _step(steps, needle): + return steps[_index(steps, needle)] + + +# --- the salt and the cache directory --------------------------------------- + +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.""" + assert _job()["env"]["PYAUTO_CACHE_EPOCH"] == "1" + + +def test_the_runner_step_names_the_compile_cache_dir_and_is_otherwise_untouched(): + step = _step(_steps(), RUNNER_STEP) + cache_dir = step["env"]["JAX_COMPILATION_CACHE_DIR"] + # 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. + assert cache_dir.startswith("${{ github.workspace }}/") + # The command itself is untouched — one env key is the whole change. + assert 'python "$RUNNER" $RUNNER_ARGS' in step["run"] + assert "continue-on-error" not in step + + +# --- placement, and non-fatality -------------------------------------------- + +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)] + 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, DS_SAVE_STEP) + assert _index(steps, DS_SAVE_STEP) < _index(steps, "Slack notify") + + +def test_every_step_the_caches_added_is_non_fatal(): + """Eleven 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() + for name in NEW_STEPS: + assert _step(steps, name)["continue-on-error"] is True, name + + +# --- the keys ---------------------------------------------------------------- + +def test_the_key_resolver_takes_its_inputs_through_the_environment(): + step = _step(_steps(), KEYS_STEP) + # The chain is caller-supplied text; interpolating it into `run:` would + # splice it straight into the shell (the clone step records the lesson). + assert step["env"]["CHAIN"] == "${{ inputs.chain }}" + assert "${{ inputs.chain }}" not in step["run"] + # hashFiles() is an expression, so it resolves in `env:` and the script + # 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"): + assert output in step["run"] + # A jaxlib that will not import is a key component, not a failure. + assert "nojax" in step["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(), JAX_RESTORE_STEP) + assert step["uses"].startswith("actions/cache/restore@") + assert step["id"] == "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 + # The accumulating-cache pattern: the exact key (run id) never hits, the + # prefix always does, and each save is a superset of what was restored. + (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_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 + run would have written.""" + step = _step(_steps(), DS_RESTORE_STEP) + assert step["uses"].startswith("actions/cache/restore@") + assert step["id"] == "dataset-cache" + assert step["with"]["path"] == "workspace/dataset" + key = step["with"]["key"] + for component in ("${{ steps.keys.outputs.sims }}", + "${{ steps.keys.outputs.chain }}", + "${{ env.PYAUTO_CACHE_EPOCH }}"): + assert component in key, component + # Not keyed on the python leg: simulated FITS do not depend on the + # interpreter's minor version, so both legs share one entry. + assert "${{ matrix.python-version }}" not in key + fallbacks = [line for line in step["with"]["restore-keys"].split("\n") if line.strip()] + assert len(fallbacks) == 1 + assert fallbacks[0].endswith("-chain${{ steps.keys.outputs.chain }}-") + assert key.startswith(fallbacks[0]) + + +# --- the sidecar and the saves ---------------------------------------------- + +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 timings artifact it rides in is uploaded either way.""" + step = _step(_steps(), RECORD_STEP) + assert step["if"] == "always()" + assert step["id"] == "cache-state" + run = step["run"] + assert '"schema": "cache_state/1"' in run + assert "workspace/test-results" in run and "cache_state.json" in run + # 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"): + 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 "jax_changed" in run and "ds_changed" in run + + +def test_the_saves_differ_on_exactly_one_thing_a_red_run(): + """A compile-cache entry is complete or absent, so a red run's compiling is + still worth keeping. A killed simulator leaves a truncated FITS that + `should_simulate` would happily keep, so datasets save only when green.""" + steps = _steps() + jax = _step(steps, JAX_SAVE_STEP) + datasets = _step(steps, DS_SAVE_STEP) + assert jax["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.ds_changed == 'true'" in datasets["if"] + for step, restore in ((jax, JAX_RESTORE_STEP), (datasets, DS_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_upload_step_is_untouched_by_the_cache_work(): + """The sidecar rides the artifact that already exists — a second upload + would be a second channel for one measurement.""" + step = _step(_steps(), UPLOAD_STEP) + assert step["if"] == "always()" + assert step["with"]["if-no-files-found"] == "ignore" + assert "workspace/test-results/" in step["with"]["path"] + assert "retention-days" not in step["with"] + + +def test_the_sidecar_name_and_schema_are_what_the_heart_check_reads(): + """One filename and one schema string, declared in two places that must + agree — the emitter in the workflow and the ingest in the check.""" + from heart.checks.smoke_timings import CACHE_STATE_FILENAME, CACHE_STATE_SCHEMA + + run = _step(_steps(), RECORD_STEP)["run"] + assert CACHE_STATE_FILENAME in run + assert f'"schema": "{CACHE_STATE_SCHEMA}"' in run diff --git a/tests/test_smoke_timings.py b/tests/test_smoke_timings.py index 0b828f6e..eae74b2a 100644 --- a/tests/test_smoke_timings.py +++ b/tests/test_smoke_timings.py @@ -624,3 +624,145 @@ def _line(date, python, run_id, seconds): assert rows["3.12"]["prev_s"] is None and rows["3.12"]["state"] == "ok" assert rows["3.13"]["prev_s"] == 28.0 and rows["3.13"]["prev_run_id"] == 6 capsys.readouterr() + + +# --- 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. + +def _cache_state(*, jax_hit=True, ds_hit=False, epoch="1", + schema="cache_state/1", jax_key="pyauto-jax-...-e1-"): + return json.dumps({ + "schema": schema, + "epoch": epoch, + "jax": {"path": "/w/.pyauto_jax_cache", "restored_key": + jax_key if jax_hit else "", "hit": jax_hit, "exact": False, + "size_mb_before": 40, "size_mb_after": 55, + "entries_before": 120, "entries_after": 180}, + "datasets": {"path": "workspace/dataset", "restored_key": + "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}, + }) + + +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)) + return directory + + +def test_cache_state_parses_hit_and_miss_per_section(): + state, err = smt.parse_cache_state(_cache_state(jax_hit=True, ds_hit=False)) + assert err == "" + assert state["jax"] == "hit" and state["datasets"] == "miss" + assert state["epoch"] == "1" + assert state["jax_restored_key"].startswith("pyauto-jax-") + assert state["datasets_restored_key"] == "" + + +def test_cache_state_rejects_a_foreign_or_broken_sidecar(): + """Written by another organ on a runner we do not control: a surprise + degrades to no state, never to an exception out of an unattended check.""" + for text in ("{", "[]", '"nope"', _cache_state(schema="cache_state/0")): + state, err = smt.parse_cache_state(text) + assert state is None and err + + +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.""" + 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_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"} + + +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".""" + entries, err, meta = smt.read_downloaded_leg(_extracted(tmp_path, [_entry()])) + assert err == "" and meta["cache"] == {"jax": "unknown", + "datasets": "unknown", "epoch": ""} + + +def test_an_unparseable_sidecar_reads_unknown_and_loses_no_timings(tmp_path): + directory = _extracted(tmp_path, [_entry()]) + (directory / smt.CACHE_STATE_FILENAME).write_text("{ not json") + entries, err, meta = smt.read_downloaded_leg(directory) + assert entries and err == "" and meta["cache"]["jax"] == "unknown" + + +def test_the_sidecar_leg_and_the_rollup_carry_the_cache_state(tmp_path): + legs = [{"artifact": _selected(), + "dir": _with_cache(_extracted(tmp_path, [_entry(seconds=12.0)])), + "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + (leg,) = side["legs"] + assert leg["cache"] == {"jax": "hit", "datasets": "miss", "epoch": "1"} + + roll = smt.aggregate([side], {}, "T", smt.DEFAULT_SMOKE_TIMINGS_THRESHOLDS) + assert roll["repos"][0]["cache"] == leg["cache"] + (row,) = roll["rows"] + assert row["cache_jax"] == "hit" and row["prev_cache_jax"] == "unknown" + + +def test_a_failed_leg_has_no_cache_state_either(tmp_path): + side = smt.build_sidecar(REPO, "workspaces", OWNER, [ + {"artifact": _selected(), "dir": None, "error": "HTTP 403"}, + ], "T") + (leg,) = side["legs"] + assert leg["cache"] == {"jax": "unknown", "datasets": "unknown", "epoch": ""} + + +def test_drift_is_never_classified_across_two_known_cache_states(): + """A cold run against a hot baseline is a recompile; a hot run against a + cold one is the cache landing. Neither is a change anybody made.""" + thr = {"slow_factor": 2.0, "min_delta_s": 5} + hot = dict(_prev_row(10.0), cache_jax="hit") + assert smt.classify_drift(30.0, hot, thr, run_id=7, cache="miss") == ( + "ok", None, None) + cold = dict(_prev_row(30.0), cache_jax="miss") + assert smt.classify_drift(10.0, cold, thr, run_id=7, cache="hit") == ( + "ok", None, None) + + +def test_drift_is_classified_normally_for_equal_or_unknown_cache_states(): + """Two cold runs are comparable, and an unknown on either side compares + exactly as it did before the sidecar existed.""" + thr = {"slow_factor": 2.0, "min_delta_s": 5} + same = dict(_prev_row(10.0), cache_jax="miss") + assert smt.classify_drift(30.0, same, thr, run_id=7, cache="miss")[0] == "warn" + unknown_prev = dict(_prev_row(10.0), cache_jax="unknown") + assert smt.classify_drift(30.0, unknown_prev, thr, run_id=7, cache="hit")[0] == "warn" + assert smt.classify_drift(30.0, _prev_row(10.0), thr, run_id=7, + cache="hit")[0] == "warn" + assert smt.classify_drift(30.0, dict(_prev_row(10.0), cache_jax="hit"), + thr, run_id=7)[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.""" + rows = smt.prev_rows_of(_prev_board([dict(_prev_row(), cache_jax="hit")])) + assert rows[(REPO, "3.12", "imaging/x.py")]["cache_jax"] == "hit" + + legs = [{"artifact": _selected(), + "dir": _with_cache(_extracted(tmp_path, [_entry(seconds=30.0)]), + jax_hit=False), + "error": ""}] + side = smt.build_sidecar(REPO, "workspaces", OWNER, legs, "T") + roll = smt.aggregate([side], _prev_board([dict(_prev_row(10.0), cache_jax="hit")]), + "T", {"slow_factor": 2.0, "min_delta_s": 5, "top_n": 5}) + (row,) = roll["rows"] + # 10s → 30s is a 3x, and it is not reported: the baseline ran hot. + assert row["cache_jax"] == "miss" and row["prev_cache_jax"] == "hit" + assert row["state"] == "ok" and row["ratio"] is None + assert roll["slowed"] == [] diff --git a/tests/test_timings.py b/tests/test_timings.py index 6df81ce1..5fe549eb 100644 --- a/tests/test_timings.py +++ b/tests/test_timings.py @@ -227,7 +227,7 @@ def test_previous_script_rows_takes_the_latest_line_per_leg_and_drives_drift(tmp prev = timings.previous_script_rows(scripts_dir) assert prev[("RepoA", "3.12", "imaging/x.py")] == { "seconds": 40.0, "run_id": 8, "run_url": RUN_URL, - "status": "passed", "cap_s": 600.0, + "status": "passed", "cap_s": 600.0, "cache_jax": "unknown", } assert prev[("RepoA", "3.11", "imaging/x.py")]["seconds"] == 5.0 @@ -785,3 +785,64 @@ def test_the_committed_record_carries_exactly_the_legacy_boundary(): assert epochs[0]["date"] == "2026-09-05" and epochs[0]["label"] == "legacy" assert epochs[0]["note"] assert len(timings.EPOCHS_FILE.read_text().splitlines()) == 1 + + +# --- the cache state a measurement was taken under -------------------------- +# A leg that ran with a restored JAX compile cache and one that recompiled from +# 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): + rollup = _smoke_rollup(**kw) + rollup["repos"][0]["cache"] = {"jax": jax, "datasets": datasets, "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"} + + +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"} + 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"} + + +def test_previous_script_rows_hands_the_cache_state_to_the_drift_rule(tmp_path): + scripts_dir = tmp_path / "scripts" + path = timings.scripts_file("RepoA", tmp_path) + timings.append_scripts(path, timings.scripts_lines_from_rollup( + _cached_rollup(jax="hit", seconds=10.0), TODAY)["RepoA"]) + prev = timings.previous_script_rows(scripts_dir) + row = prev[("RepoA", "3.12", "imaging/x.py")] + assert row["cache_jax"] == "hit" + # 10s → 30s is a 3x, and it is not reported: the baseline ran hot. + thr = {"slow_factor": 2.0, "min_delta_s": 5} + assert smoke_timings.classify_drift(30.0, row, thr, run_id=9, + cache="miss") == ("ok", None, None) + assert smoke_timings.classify_drift(30.0, row, thr, run_id=9, + cache="hit")[0] == "warn" + + +def test_a_legacy_record_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.""" + scripts_dir = tmp_path / "scripts" + path = timings.scripts_file("RepoA", tmp_path) + (line,) = timings.scripts_lines_from_rollup(_smoke_rollup(seconds=10.0), + TODAY)["RepoA"] + line.pop("cache") + timings.append_scripts(path, [line]) + row = timings.previous_script_rows(scripts_dir)[("RepoA", "3.12", "imaging/x.py")] + assert row["cache_jax"] == "unknown" + thr = {"slow_factor": 2.0, "min_delta_s": 5} + assert smoke_timings.classify_drift(30.0, row, thr, run_id=9, + cache="hit")[0] == "warn" diff --git a/timings/README.md b/timings/README.md index c876e3ae..5ee0851d 100644 --- a/timings/README.md +++ b/timings/README.md @@ -63,6 +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"}, "entries":{"imaging/x.py":[12.5,"passed",600.0]}} ``` @@ -77,6 +78,24 @@ joined to its `rows` (the timed entries): fabricated zero-second row in a dataset whose whole purpose is timing. * `head_sha` and `env_profile` are `""` when the rollup that produced the line predates them, so every line in a file carries the same keys either way. +* **`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 + 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`. + + From this follows the one rule the comparison obeys: + + > **Drift is never classified across two known but different jax cache + > states.** A cold run against a hot baseline is a recompile; a hot run + > against a cold one is the cache landing. Neither is a change anybody made, + > so `smoke_timings.classify_drift` returns `ok` with no ratio rather than + > 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. ### `unit/.jsonl` — one line per leg per run