diff --git a/.github/scripts/smoke_sha_gate.py b/.github/scripts/smoke_sha_gate.py new file mode 100644 index 00000000..ee22e7e2 --- /dev/null +++ b/.github/scripts/smoke_sha_gate.py @@ -0,0 +1,239 @@ +"""Decide whether tonight's workspace smoke sweep runs, and record its SHAs. + +The first job of workspace-smoke.yml (main only) and of +workspace-smoke-pinned.yml (bisect runs) runs this. It resolves the commit +every repo the sweep covers will be tested at (the `main` head, or the +SHA/ref the pinned entry's `commit_shas` input names), compares that map with +the record of the last successful run, and writes: + + shas.json the record, uploaded as the `workspace-smoke-shas` + artifact of EVERY run (swept or skipped); + $GITHUB_OUTPUT sweep=true|false and commit_shas=; + $GITHUB_STEP_SUMMARY one headline plus a table of the tested SHAs. + +The sweep is skipped only when all of these hold: nothing was pinned, the +dispatch did not set force, the latest completed run on main concluded +success (a red run at the same SHAs must be swept again, not masked by an +older green one), a previous record exists and is readable, every covered +repo's SHA equals that record's, and the last full sweep is younger than +FULL_SWEEP_MAX_AGE_DAYS (so a dependency that moved on PyPI without any +`main` moving is still caught within a week, as before). Anything else runs +the sweep. A previous record that expired or predates this script counts as +"no record": run the sweep. + +Heart's test_run leg reads the record: a skipped run carries `swept: false` +and the id of the full sweep it re-attests (`full_sweep_run_id`), so Heart +takes the counts from that run and never reports the skip as a fresh sweep. + +Environment (all optional except where the workflow sets them): + PINS JSON {repo: sha-or-ref}; default "{}" (pinned entry only) + FORCE "true" sweeps even when nothing moved + LAST_RUN_ID, LAST_RUN_CONCLUSION latest completed run on main (not this one) + PREVIOUS_RECORD path to the last successful run's shas.json + PREVIOUS_RUN_ID that run's id + RUN_ID, RUN_URL, EVENT this run's identity +Stdlib only: it runs on the bare runner python3 before any setup step. +""" + +from __future__ import annotations + +import datetime +import json +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Callable + +FULL_SWEEP_MAX_AGE_DAYS = 7 +SCHEMA = 1 +_SHA = re.compile(r"[0-9a-f]{40}") +# The body the sweep runs. It is the one source of truth for which repos the +# sweep covers: load_covered() reads them from its checkout steps, so this +# script names no repo itself (the organ tenant firewall keeps instance facts +# out of Heart's Python). +BODY = Path(".github/workflows/workspace-validation.yml") + + +def load_covered(body: Path = BODY) -> tuple[str, ...]: + """Libraries then workspaces the body checks out, in order. + + Libraries: the words of the body's `for lib in ...; do` clone loops (all + loops must agree). Workspaces: the values of find_scripts' `declare -A WS` + map. Raises if either is missing, so a reshaped body fails the gate loudly + instead of silently covering nothing.""" + text = body.read_text() + loops = {tuple(m.split()) for m in re.findall(r"for lib in ([\w ]+); do", text)} + if len(loops) != 1: + raise ValueError(f"{body}: expected one library list, found {sorted(loops)}") + ws_map = re.search(r"declare -A WS=\((.*?)\)\n", text, re.S) + workspaces = tuple(re.findall(r"\]=(\w+)", ws_map.group(1))) if ws_map else () + if not workspaces: + raise ValueError(f"{body}: no workspace map (declare -A WS) found") + return loops.pop() + workspaces + + +def owner() -> str: + """The GitHub owner of the covered repos: this repository's owner.""" + return os.environ.get("OWNER") or os.environ["GITHUB_REPOSITORY_OWNER"] + + +def ls_remote(repo: str, ref: str) -> str: + """The commit `ref` names in /, or "" if none.""" + out = subprocess.run( + ["git", "ls-remote", f"https://github.com/{owner()}/{repo}", ref], + capture_output=True, text=True, timeout=60, check=True, + ).stdout + for line in out.splitlines(): + sha, _, name = line.partition("\t") + if name in (ref, f"refs/heads/{ref}", f"refs/tags/{ref}"): + return sha + return "" # short SHAs and unknown refs: resolve() reports them + + +def parse_pins(raw: str | None, covered: tuple[str, ...]) -> dict[str, str]: + """The dispatch input as a {repo: ref} dict; rejects unknown repos.""" + pins = json.loads(raw or "{}") or {} + if not isinstance(pins, dict): + raise ValueError("commit_shas must be a JSON object {repo: sha}") + unknown = sorted(set(pins) - set(covered)) + if unknown: + raise ValueError( + f"commit_shas names repos the sweep does not cover: {unknown}; " + f"covered: {list(covered)}" + ) + return {k: str(v).strip() for k, v in pins.items() if str(v).strip()} + + +def resolve( + pins: dict[str, str], + covered: tuple[str, ...], + lookup: Callable[[str, str], str] = ls_remote, +) -> dict[str, str]: + """Full 40-hex SHA for every covered repo: the pin if given, else main.""" + shas = {} + for repo in covered: + ref = pins.get(repo, "refs/heads/main") + sha = ref.lower() if _SHA.fullmatch(ref.lower()) else lookup(repo, ref) + if not _SHA.fullmatch(sha or ""): + raise ValueError(f"{repo}: cannot resolve {ref!r} to a commit") + shas[repo] = sha + return shas + + +def _age_days(ts: str | None, now: datetime.datetime) -> float | None: + try: + then = datetime.datetime.fromisoformat(str(ts).replace("Z", "+00:00")) + except ValueError: + return None + return (now - then).total_seconds() / 86400 + + +def decide( + shas: dict[str, str], + pins: dict[str, str], + previous: dict | None, + previous_run_id: str, + now: datetime.datetime, + force: bool = False, + last_run: tuple[str, str] | None = None, +) -> tuple[bool, str, dict]: + """(sweep, reason, record) for this run. + + last_run is (id, conclusion) of the latest completed run on main, or None + when there is none.""" + stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ") + full_id, full_ts = None, None + if pins: + sweep, reason = True, f"pinned by dispatch: {', '.join(sorted(pins))}" + elif force: + sweep, reason = True, "forced by dispatch" + elif last_run and last_run[1] != "success": + sweep, reason = True, f"last run {last_run[0]} concluded {last_run[1] or 'unknown'}" + elif not isinstance(previous, dict) or not isinstance(previous.get("commit_shas"), dict): + sweep = True + reason = ( + f"no SHA record from the last successful run ({previous_run_id or 'none'}); " + "running the sweep" + ) + else: + full_id = previous.get("full_sweep_run_id") or previous_run_id + full_ts = previous.get("full_sweep_created_at") + moved = sorted(r for r in shas if previous["commit_shas"].get(r) != shas[r]) + age = _age_days(full_ts, now) + if moved: + sweep, reason = True, f"main moved since run {previous_run_id}: {', '.join(moved)}" + elif age is None or age >= FULL_SWEEP_MAX_AGE_DAYS: + sweep = True + reason = ( + f"no main moved, but the last full sweep (run {full_id}) is " + f"{'of unknown age' if age is None else f'{age:.1f} days old'}; " + f"a full sweep runs at least every {FULL_SWEEP_MAX_AGE_DAYS} days" + ) + else: + sweep, reason = False, f"no main moved since run {full_id}" + run_id = os.environ.get("RUN_ID", "") + record = { + "schema": SCHEMA, + "run_id": run_id, + "run_url": os.environ.get("RUN_URL", ""), + "event": os.environ.get("EVENT", ""), + "created_at": stamp, + "swept": sweep, + "reason": reason, + "full_sweep_run_id": run_id if sweep else full_id, + "full_sweep_created_at": stamp if sweep else full_ts, + "previous_run_id": previous_run_id or None, + "pinned": pins, + "commit_shas": shas, + } + return sweep, reason, record + + +def summary_markdown(record: dict) -> str: + head = ( + f"**Workspace sweep running:** {record['reason']}." + if record["swept"] + else f"**Workspace sweep skipped: {record['reason']}.** " + f"These SHAs passed the full sweep in run {record['full_sweep_run_id']}." + ) + rows = [ + f"| {repo} | `{sha}` | {'pinned' if repo in record['pinned'] else 'main'} |" + for repo, sha in record["commit_shas"].items() + ] + return "\n".join( + [head, "", "| repo | commit | source |", "|---|---|---|", *rows, ""] + ) + + +def main() -> int: + covered = load_covered() + pins = parse_pins(os.environ.get("PINS"), covered) + previous = None + prev_path = os.environ.get("PREVIOUS_RECORD", "") + if prev_path and Path(prev_path).is_file(): + try: + previous = json.loads(Path(prev_path).read_text()) + except ValueError: + previous = None + shas = resolve(pins, covered) + last_id = os.environ.get("LAST_RUN_ID", "") + sweep, reason, record = decide( + shas, pins, previous, os.environ.get("PREVIOUS_RUN_ID", ""), + datetime.datetime.now(datetime.timezone.utc), + force=os.environ.get("FORCE", "").lower() == "true", + last_run=(last_id, os.environ.get("LAST_RUN_CONCLUSION", "")) if last_id else None, + ) + Path("shas.json").write_text(json.dumps(record, indent=2) + "\n") + compact = json.dumps(shas, separators=(",", ":")) + with open(os.environ.get("GITHUB_OUTPUT", os.devnull), "a") as fh: + fh.write(f"sweep={'true' if sweep else 'false'}\ncommit_shas={compact}\n") + with open(os.environ.get("GITHUB_STEP_SUMMARY", os.devnull), "a") as fh: + fh.write(summary_markdown(record)) + print(reason) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/workspace-smoke-pinned.yml b/.github/workflows/workspace-smoke-pinned.yml new file mode 100644 index 00000000..85a77c3d --- /dev/null +++ b/.github/workflows/workspace-smoke-pinned.yml @@ -0,0 +1,63 @@ +name: Workspace Smoke (pinned) + +# Bisect runs of the workspace smoke sweep at pinned commits (M3.7d, +# PyAutoHeart#354). Same body as workspace-smoke.yml (workspace-validation.yml, +# mode smoke), but its own entry, so its runs never enter the smoke channel's +# history: Heart's test_run leg and the nightly gate read workspace-smoke.yml +# only, and a pinned run that passes on an old SHA must not read as "main is +# green". +# +# gh workflow run workspace-smoke-pinned.yml -f commit_shas='{"PyAutoGalaxy":""}' +# +# commit_shas is a JSON {repo: full-sha | branch | tag}; repos it does not name +# use main, and a repo the sweep does not cover is rejected. The gate script +# (.github/scripts/smoke_sha_gate.py) resolves every repo to a full SHA, and +# the run records them in the `workspace-smoke-shas` artifact and its summary, +# exactly as the nightly entry does. A pinned run always sweeps. + +on: + workflow_dispatch: + inputs: + commit_shas: + description: 'JSON {repo: sha-or-ref} to pin, e.g. {"PyAutoGalaxy":""}; unlisted repos use main' + type: string + required: true + +permissions: + contents: read + +jobs: + gate: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + commit_shas: ${{ steps.decide.outputs.commit_shas }} + steps: + - name: Checkout PyAutoHeart (gate script) + uses: actions/checkout@v4 + with: + sparse-checkout: .github # the gate script and the body it reads the covered repos from + - name: Resolve the pinned SHAs + id: decide + env: + PINS: ${{ inputs.commit_shas }} + OWNER: ${{ github.repository_owner }} + RUN_ID: ${{ github.run_id }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + EVENT: ${{ github.event_name }} + run: | + python3 -c 'import json,os,sys; json.loads(os.environ["PINS"]) or sys.exit("::error::commit_shas pins nothing; use workspace-smoke.yml to test main")' + python3 .github/scripts/smoke_sha_gate.py + - name: Upload the SHA record + uses: actions/upload-artifact@v4 + with: + name: workspace-smoke-shas + path: shas.json + if-no-files-found: error + + smoke: + needs: gate + uses: ./.github/workflows/workspace-validation.yml + with: + mode: smoke + commit_shas: ${{ needs.gate.outputs.commit_shas }} diff --git a/.github/workflows/workspace-smoke.yml b/.github/workflows/workspace-smoke.yml index c422377b..9cf6723c 100644 --- a/.github/workflows/workspace-smoke.yml +++ b/.github/workflows/workspace-smoke.yml @@ -2,22 +2,106 @@ name: Workspace Smoke # The CONTINUOUS workspace-readiness channel: every workspace's scripts and # generated notebooks against the current source `main` of the 5 libraries, -# weekly and on demand. Thin entry over the shared body +# nightly and on demand. Thin entry over the shared body # (workspace-validation.yml, workflow_call-only) — the split gives each # meaning its own run history, so Heart's test_run leg # (`gh run list --workflow workspace-smoke.yml`) can never confuse a failed -# release rehearsal (release-integrate.yml) with the smoke verdict. +# release rehearsal (release-integrate.yml) with the smoke verdict. For the +# same reason this entry only ever tests `main`: bisect runs pinned to other +# SHAs have their own entry, workspace-smoke-pinned.yml, so a pinned run that +# passes on an old SHA can never read as "main is green". +# +# Nightly, but only when something moved (M3.7d, PyAutoHeart#354). The `gate` +# job (.github/scripts/smoke_sha_gate.py) resolves the commit of every library +# and workspace the sweep covers and compares it with the record of the last +# successful run on main. When no `main` moved, the latest completed run +# concluded success and the last full sweep is under 7 days old, the sweep is +# skipped: the run ends in about a minute, concludes success and its summary +# says "no main moved since run ". Otherwise the sweep runs at exactly the +# SHAs the gate resolved, so every job tests the same commits even if a `main` +# moves mid-run. A plain dispatch follows the same rule; dispatch with +# `-f force=true` to sweep regardless. +# +# Every run, swept or skipped, uploads the `workspace-smoke-shas` artifact +# (shas.json: the SHAs tested, whether it swept, and the full sweep it +# re-attests) and prints the same table in its summary. Read it with +# gh run download --repo PyAutoLabs/PyAutoHeart -n workspace-smoke-shas +# +# Bisecting: use workspace-smoke-pinned.yml, not this entry. on: schedule: - - cron: "0 3 * * 1" # Mondays 03:00 UTC + - cron: "0 3 * * *" # nightly 03:00 UTC (the old Monday run is one of these) workflow_dispatch: + inputs: + force: + description: "Sweep even when no main moved since the last successful run" + type: boolean + default: false permissions: contents: read + actions: read # the gate lists runs and downloads the last run's SHA record jobs: + gate: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + sweep: ${{ steps.decide.outputs.sweep }} + commit_shas: ${{ steps.decide.outputs.commit_shas }} + steps: + - name: Checkout PyAutoHeart (gate script) + uses: actions/checkout@v4 + with: + sparse-checkout: .github # the gate script and the body it reads the covered repos from + - name: Fetch the last successful run's SHA record + id: previous + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + # Fail-open to "run the sweep": no previous run, an expired artifact or + # a run from before this gate all leave previous/ empty. The latest + # completed run (this one is still in progress, so never listed) feeds + # the "last run concluded failure → sweep again" rule. + run: | + last=$(gh run list --repo "$REPO" --workflow workspace-smoke.yml --branch main \ + --status completed --limit 5 --json databaseId,conclusion \ + --jq "[.[] | select(.databaseId != $RUN_ID)][0] // empty | \"\(.databaseId) \(.conclusion)\"" || true) + echo "last_id=${last%% *}" >> "$GITHUB_OUTPUT" + echo "last_conclusion=${last#* }" >> "$GITHUB_OUTPUT" + id=$(gh run list --repo "$REPO" --workflow workspace-smoke.yml --branch main \ + --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty' || true) + echo "run_id=$id" >> "$GITHUB_OUTPUT" + if [ -n "$id" ]; then + gh run download "$id" --repo "$REPO" -n workspace-smoke-shas -D previous \ + || echo "::notice::run $id has no workspace-smoke-shas artifact; the sweep will run" + fi + - name: Resolve SHAs and decide + id: decide + env: + FORCE: ${{ inputs.force && 'true' || 'false' }} + LAST_RUN_ID: ${{ steps.previous.outputs.last_id }} + LAST_RUN_CONCLUSION: ${{ steps.previous.outputs.last_conclusion }} + PREVIOUS_RECORD: previous/shas.json + PREVIOUS_RUN_ID: ${{ steps.previous.outputs.run_id }} + OWNER: ${{ github.repository_owner }} + RUN_ID: ${{ github.run_id }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + EVENT: ${{ github.event_name }} + run: python3 .github/scripts/smoke_sha_gate.py + - name: Upload the SHA record + uses: actions/upload-artifact@v4 + with: + name: workspace-smoke-shas + path: shas.json + if-no-files-found: error + smoke: + needs: gate + if: needs.gate.outputs.sweep == 'true' uses: ./.github/workflows/workspace-validation.yml with: mode: smoke + commit_shas: ${{ needs.gate.outputs.commit_shas }} diff --git a/.github/workflows/workspace-validation.yml b/.github/workflows/workspace-validation.yml index 6a5d2aac..4d0b22c1 100644 --- a/.github/workflows/workspace-validation.yml +++ b/.github/workflows/workspace-validation.yml @@ -7,7 +7,7 @@ name: Workspace Validation # Runs every workspace's scripts AND generated notebooks against the # CURRENT source `main` of the 5 libraries (source-shadowed via PYTHONPATH, # under the `smoke` env profile — config/build/profile_smoke.yaml). -# This is the continuous readiness signal / weekly sweep; +# This is the continuous readiness signal / nightly sweep; # `test_run`/`readiness` read the smoke channel's conclusion. # # mode=release (entry: release-integrate.yml — Brain Release Agent dispatch @@ -37,7 +37,8 @@ name: Workspace Validation # Triggers: workflow_call ONLY — this file is the shared body behind two thin # entry workflows, one per meaning: # -# workspace-smoke.yml schedule + bare dispatch → mode=smoke +# workspace-smoke.yml nightly schedule + dispatch, main only → mode=smoke +# workspace-smoke-pinned.yml dispatch with commit_shas (bisect) → mode=smoke # release-integrate.yml dispatch + workflow_call → mode=release # # The split exists because `gh run list --workflow ` cannot filter on @@ -94,24 +95,42 @@ jobs: outputs: matrix: ${{ steps.script_matrix.outputs.matrix }} mode: ${{ steps.mode.outputs.mode }} + refs: ${{ steps.mode.outputs.refs }} steps: # Resolved once here (rather than read from `inputs.mode` directly in # every downstream `if:`) so every mode check routes through one job # output; the entry workflows always pass mode explicitly, and a bare # input still resolves to plain "smoke", never an empty string. + # + # refs is the {repo: sha} map every smoke checkout below pins to (both + # smoke entries' gate job passes the SHAs it resolved; a repo missing from + # the map uses main). mode=release ignores commit_shas for checkouts — + # there it only labels the report — so refs is always {} in that mode. - name: Resolve mode id: mode env: MODE_INPUT: ${{ inputs.mode }} - run: echo "mode=${MODE_INPUT:-smoke}" >> "$GITHUB_OUTPUT" + COMMIT_SHAS: ${{ inputs.commit_shas }} + run: | + mode="${MODE_INPUT:-smoke}" + echo "mode=$mode" >> "$GITHUB_OUTPUT" + [ "$mode" = smoke ] || COMMIT_SHAS="{}" + printf 'refs=%s\n' "$(python3 -c 'import json,os; print(json.dumps(json.loads(os.environ["COMMIT_SHAS"] or "{}"), separators=(",", ":")))')" >> "$GITHUB_OUTPUT" - name: Checkout PyAutoHands (run primitives) uses: actions/checkout@v4 with: repository: PyAutoLabs/PyAutoHands path: PyAutoHands - name: Clone workspaces (paths match script_matrix project names) + env: + REFS: ${{ steps.mode.outputs.refs }} run: | set -e + clone_at() { # repo dest: at REFS[repo] if pinned, else main + ref=$(python3 -c 'import json,os,sys; print(json.loads(os.environ.get("REFS") or "{}").get(sys.argv[1], ""))' "$1") + if [ -z "$ref" ]; then git clone --depth 1 "https://github.com/PyAutoLabs/$1" "$2"; return; fi + git init -q "$2" && git -C "$2" fetch -q --depth 1 "https://github.com/PyAutoLabs/$1" "$ref" && git -C "$2" checkout -q FETCH_HEAD + } declare -A WS=( [autofit]=autofit_workspace [autogalaxy]=autogalaxy_workspace [autolens]=autolens_workspace [autofit_test]=autofit_workspace_test [autogalaxy_test]=autogalaxy_workspace_test @@ -120,7 +139,7 @@ jobs: [euclid]=euclid_strong_lens_modeling_pipeline ) for proj in "${!WS[@]}"; do - git clone --depth 1 "https://github.com/PyAutoLabs/${WS[$proj]}" "$proj" + clone_at "${WS[$proj]}" "$proj" done - name: Make script matrix id: script_matrix @@ -177,7 +196,7 @@ jobs: uses: actions/checkout@v4 with: repository: PyAutoLabs/${{ matrix.project.workspace }} - ref: main + ref: ${{ fromJSON(needs.find_scripts.outputs.refs)[matrix.project.workspace] || 'main' }} path: workspace - name: Set up Python uses: actions/setup-python@v5 @@ -233,7 +252,7 @@ jobs: uses: actions/checkout@v4 with: repository: PyAutoLabs/${{ steps.ws.outputs.repo }} - ref: main + ref: ${{ fromJSON(needs.find_scripts.outputs.refs)[steps.ws.outputs.repo] || 'main' }} path: workspace - name: Discard result files the workspace checkout carries # A workspace repo must never ship its own test-results/ — but one did: @@ -270,12 +289,19 @@ jobs: ) [ "$found" -eq 0 ] && echo "no stale result files under $ws" exit 0 - - name: "Checkout libraries (current main; source-shadowed via PYTHONPATH) [mode=smoke]" + - name: "Checkout libraries (main or the pinned SHA; source-shadowed via PYTHONPATH) [mode=smoke]" if: needs.find_scripts.outputs.mode == 'smoke' + env: + REFS: ${{ needs.find_scripts.outputs.refs }} run: | set -e + clone_at() { # repo dest: at REFS[repo] if pinned, else main + ref=$(python3 -c 'import json,os,sys; print(json.loads(os.environ.get("REFS") or "{}").get(sys.argv[1], ""))' "$1") + if [ -z "$ref" ]; then git clone --depth 1 "https://github.com/PyAutoLabs/$1" "$2"; return; fi + git init -q "$2" && git -C "$2" fetch -q --depth 1 "https://github.com/PyAutoLabs/$1" "$ref" && git -C "$2" checkout -q FETCH_HEAD + } for lib in PyAutoNerves PyAutoArray PyAutoFit PyAutoGalaxy PyAutoLens; do - git clone --depth 1 "https://github.com/PyAutoLabs/$lib" "libs/$lib" + clone_at "$lib" "libs/$lib" done - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 @@ -583,7 +609,7 @@ jobs: uses: actions/checkout@v4 with: repository: PyAutoLabs/${{ steps.ws.outputs.repo }} - ref: main + ref: ${{ fromJSON(needs.find_scripts.outputs.refs)[steps.ws.outputs.repo] || 'main' }} path: workspace - name: Discard result files the workspace checkout carries if: steps.gate.outputs.run == 'true' @@ -623,10 +649,17 @@ jobs: exit 0 - name: Checkout libraries (source-shadowed via PYTHONPATH) if: steps.gate.outputs.run == 'true' + env: + REFS: ${{ needs.find_scripts.outputs.refs }} run: | set -e + clone_at() { # repo dest: at REFS[repo] if pinned, else main + ref=$(python3 -c 'import json,os,sys; print(json.loads(os.environ.get("REFS") or "{}").get(sys.argv[1], ""))' "$1") + if [ -z "$ref" ]; then git clone --depth 1 "https://github.com/PyAutoLabs/$1" "$2"; return; fi + git init -q "$2" && git -C "$2" fetch -q --depth 1 "https://github.com/PyAutoLabs/$1" "$ref" && git -C "$2" checkout -q FETCH_HEAD + } for lib in PyAutoNerves PyAutoArray PyAutoFit PyAutoGalaxy PyAutoLens; do - git clone --depth 1 "https://github.com/PyAutoLabs/$lib" "libs/$lib" + clone_at "$lib" "libs/$lib" done - name: Download generated notebooks if: steps.gate.outputs.run == 'true' diff --git a/REFERENCE.md b/REFERENCE.md index c531ec97..2c048bc3 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -197,7 +197,15 @@ workspace repos are not gated, and no other skill blocks on it. workflows the libraries and workspaces call; Heart owns the definitions. - **workspace-smoke.yml** → **workspace-validation.yml** (workflow_call body) — scripts + notebooks against the libraries' current `main`; the run history - `test_run` + `readiness` consume. The release rehearsal has its own entry, + `test_run` + `readiness` consume. Nightly at 03:00 UTC: a `gate` job skips + the sweep when no library or workspace `main` moved since the last successful + run, the latest run on `main` concluded success, and the last full sweep is + under 7 days old; `-f force=true` sweeps regardless. Every run uploads the + SHAs it tested as the `workspace-smoke-shas` artifact; `test_run` reads only + runs on `main` and treats a skipped night as a re-attestation of the full + sweep it names. Bisect runs at pinned commits use their own entry, + **workspace-smoke-pinned.yml** (`-f commit_shas='{"":""}'`), so + they never enter the smoke channel's history. The release rehearsal has its own entry, **release-integrate.yml**, so a failed rehearsal never overwrites the smoke verdict (see `docs/release_validation.md`). - **heart-tests.yml** — Heart's own pytest suite; **url-check.yml** — weekly diff --git a/docs/release_validation.md b/docs/release_validation.md index a92ef044..c6b560ae 100644 --- a/docs/release_validation.md +++ b/docs/release_validation.md @@ -9,7 +9,8 @@ M2 shipped the report schema, `pyauto-heart validate --ingest`, and the readiness hard gate. **M3 wires the acceptance criteria below into the shared `workspace-validation.yml` body** via a `mode: release` input. The two modes now have separate entry workflows (one run history per meaning): -`workspace-smoke.yml` (the continuous smoke channel) and +`workspace-smoke.yml` (the continuous smoke channel: nightly, skipped when no +`main` moved; bisect runs at pinned SHAs go through `workspace-smoke-pinned.yml`) and `release-integrate.yml` (this release-fidelity channel): - The `release` env profile lives in each workspace/`*_workspace_test` repo as diff --git a/heart/checks/test_run.py b/heart/checks/test_run.py index 5af358b8..8f9ceb00 100644 --- a/heart/checks/test_run.py +++ b/heart/checks/test_run.py @@ -64,6 +64,15 @@ # the real counts and per-script failures for a cloud run — the only place they # exist when there is no local run_logs/. REPORT_ARTIFACT = "workspace-validation-report" +# The SHA record every workspace-smoke run uploads from its gate job +# (.github/scripts/smoke_sha_gate.py, PyAutoHeart#354). A run that skipped the +# sweep because no `main` moved carries ``swept: false`` and the id of the full +# sweep it re-attests; run() takes the counts from that sweep and labels the +# verdict as a re-attestation, never as a fresh sweep. The skip run's own +# createdAt stays the evidence timestamp: the code on main is still exactly +# what that sweep passed, and the gate forces a full sweep at least every 7 +# days, so readiness' TEST_STALE_DAYS age rule needs no change. +SHA_ARTIFACT = "workspace-smoke-shas" # Agent/MCP-supplied conclusion drop point. On a mobile/cloud session there is no # `gh` (and no local report.json); Brain queries the run conclusion via its MCP @@ -116,11 +125,13 @@ def _cloud_verdict() -> dict[str, Any] | None: """Latest cloud workspace-validation run via `gh`: {ready, ts, run_id, url}. ready is True/False on a completed run, None while in progress. Never raises; - returns None if gh is unavailable or no run exists.""" + returns None if gh is unavailable or no run exists. Only runs on main + count: a dispatch from a feature branch (run 43034177136 was one) tests + that branch's workflow, not the smoke channel.""" try: out = subprocess.run( ["gh", "run", "list", "--repo", VALIDATION_REPO, - "--workflow", VALIDATION_WORKFLOW, "--limit", "1", + "--workflow", VALIDATION_WORKFLOW, "--branch", "main", "--limit", "1", "--json", "conclusion,status,createdAt,databaseId,url"], capture_output=True, text=True, timeout=30, ) @@ -260,6 +271,28 @@ def _cloud_report(run_id: Any) -> dict[str, Any] | None: return report if isinstance(report, dict) else None +def _cloud_sha_record(run_id: Any) -> dict[str, Any] | None: + """Download run_id's ``workspace-smoke-shas`` record (shas.json). + + Never raises; None if gh is unavailable, the run predates the gate, the + artifact expired, or the JSON is malformed. Cached per run id by main().""" + if not run_id: + return None + try: + with tempfile.TemporaryDirectory() as td: + res = subprocess.run( + ["gh", "run", "download", str(run_id), "--repo", VALIDATION_REPO, + "-n", SHA_ARTIFACT, "-D", td], + capture_output=True, text=True, timeout=60, + ) + if res.returncode != 0: + return None + record = _read_json(Path(td) / "shas.json") + except Exception: + return None + return record if isinstance(record, dict) else None + + def counts_measured(summary: dict[str, Any]) -> bool: """True if the summary's counts came from an actual report. @@ -280,6 +313,7 @@ def run( results_dir: Path | None = None, fetch_cloud: bool | None = None, cloud_report_fetcher: Callable[[Any], dict[str, Any] | None] | None = None, + cloud_sha_fetcher: Callable[[Any], dict[str, Any] | None] | None = None, ) -> dict[str, Any]: # fetch_cloud is decided by the CALLER, never inferred: the old # `results_dir is None` inference meant main() — the tick and the mobile @@ -323,11 +357,31 @@ def run( "per_project": {}, "parked_stale_count": 0, "parked_stale": [], "failing_scripts": [], "counts_measured": False, } + # The run's SHA record (PyAutoHeart#354): what it tested and, for a + # night that skipped the sweep, which full sweep it re-attests. The + # report counts then come from that sweep, since the skip run has none. + report_run_id = cloud["run_id"] + attested = None + if cloud_sha_fetcher is not None and cloud["ready"] is not None: + record = cloud_sha_fetcher(cloud["run_id"]) + if isinstance(record, dict): + summary["sha_record"] = record + summary["sha_record_run_id"] = cloud["run_id"] + if isinstance(record.get("commit_shas"), dict): + summary["commit_shas"] = record["commit_shas"] + if record.get("pinned"): + summary["pinned"] = record["pinned"] + if record.get("swept") is False and record.get("full_sweep_run_id"): + attested = record["full_sweep_run_id"] + report_run_id = attested + summary["sweep_skipped"] = True + summary["full_sweep_run_id"] = attested + summary["full_sweep_ts"] = record.get("full_sweep_created_at") # Enrich from the run's own aggregated report artifact (counts + the # failing script names). The fetcher is injected by the tick/CLI # entrypoint only — run() itself stays no-network by default. if cloud_report_fetcher is not None and cloud["ready"] is not None: - cs = cloud_report_fetcher(cloud["run_id"]) + cs = cloud_report_fetcher(report_run_id) if isinstance(cs, dict): counts = { k: int(cs.get(k, 0) or 0) @@ -335,7 +389,7 @@ def run( } summary["cloud_counts"] = counts summary["failing_scripts"] = list(cs.get("failing_scripts") or [])[:10] - summary["cloud_report_run_id"] = cloud["run_id"] + summary["cloud_report_run_id"] = report_run_id if not had_local: summary.update(counts) summary["counts_measured"] = True @@ -351,6 +405,10 @@ def run( f"local ready={local_ready} vs cloud ready={cloud['ready']}" ) summary["ts"] = cloud["ts"] + if attested is not None and not had_local: + summary["run_label"] = ( + f"cloud#{attested} (re-attested by #{cloud['run_id']}: no main moved)" + ) summary["run_label"] = summary.get("run_label") or f"cloud#{cloud['run_id']}" summary["cloud_url"] = cloud["url"] summary["source"] = "cloud" @@ -379,9 +437,22 @@ def _cached_cloud_counts(run_id: Any) -> dict[str, Any] | None: report = _cloud_report(run_id) return _from_report(report) if isinstance(report, dict) else None + def _cached_sha_record(run_id: Any) -> dict[str, Any] | None: + if ( + isinstance(prev, dict) + and prev.get("sha_record_run_id") == run_id + and isinstance(prev.get("sha_record"), dict) + ): + return prev["sha_record"] + return _cloud_sha_record(run_id) + # The tick/CLI is the real path: always consult the server verdict here, # explicitly — this is the entrypoint the old inference silently disabled. - summary = run(results_dir, fetch_cloud=True, cloud_report_fetcher=_cached_cloud_counts) + summary = run( + results_dir, fetch_cloud=True, + cloud_report_fetcher=_cached_cloud_counts, + cloud_sha_fetcher=_cached_sha_record, + ) sys.path.insert(0, str(HEART_HOME)) from heart import state diff --git a/tests/test_smoke_sha_gate.py b/tests/test_smoke_sha_gate.py new file mode 100644 index 00000000..48cdd36d --- /dev/null +++ b/tests/test_smoke_sha_gate.py @@ -0,0 +1,339 @@ +"""tests/test_smoke_sha_gate.py — the nightly workspace-smoke gate (PyAutoHeart#354). + +.github/scripts/smoke_sha_gate.py decides whether the nightly sweep runs and +records the SHAs every run tested. These tests cover the decision, the record +Heart's test_run leg reads, and the wiring in workspace-smoke.yml and +workspace-validation.yml. No network: ls-remote is injected. +""" + +from __future__ import annotations + +import datetime +import importlib.util +import json +import re +from pathlib import Path + +import pytest +import yaml + +from heart.checks import test_run + +ROOT = Path(__file__).resolve().parents[1] +WORKFLOWS = ROOT / ".github" / "workflows" +spec = importlib.util.spec_from_file_location( + "smoke_sha_gate", ROOT / ".github/scripts/smoke_sha_gate.py" +) +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + +NOW = datetime.datetime(2026, 11, 20, 3, 0, 5, tzinfo=datetime.timezone.utc) +# Placeholder repos: the decision logic never needs a real name (and the organ +# tenant firewall keeps real ones out of Heart's Python). +COVERED = ("LibA", "LibB", "ws_a", "ws_b") + + +def _shas(char="a"): + return {repo: char * 40 for repo in COVERED} + + +def _previous(shas, full_id="100", full_ts="2026-11-18T03:00:00Z", swept=True): + return {"commit_shas": shas, "swept": swept, + "full_sweep_run_id": full_id, "full_sweep_created_at": full_ts} + + +# --- decision --------------------------------------------------------------- + +def test_nothing_moved_skips_and_names_the_full_sweep(): + sweep, reason, record = gate.decide(_shas(), {}, _previous(_shas()), "100", NOW) + assert sweep is False + assert reason == "no main moved since run 100" + assert record["swept"] is False + assert record["full_sweep_run_id"] == "100" + assert record["full_sweep_created_at"] == "2026-11-18T03:00:00Z" + assert record["commit_shas"] == _shas() + + +def test_a_skip_after_a_skip_still_attests_the_original_full_sweep(): + previous = _previous(_shas(), full_id="100", swept=False) + sweep, reason, record = gate.decide(_shas(), {}, previous, "101", NOW) + assert sweep is False and reason == "no main moved since run 100" + assert record["full_sweep_run_id"] == "100" and record["previous_run_id"] == "101" + + +def test_one_moved_main_runs_the_sweep_and_names_it(): + now = _shas() + now["LibB"] = "b" * 40 + sweep, reason, record = gate.decide(now, {}, _previous(_shas()), "100", NOW) + assert sweep is True and reason.endswith(": LibB") + assert record["full_sweep_run_id"] == record["run_id"] + + +def test_a_full_sweep_runs_at_least_weekly_even_when_nothing_moved(): + old = _previous(_shas(), full_ts="2026-11-13T03:00:00Z") # 7 days before NOW + sweep, reason, _ = gate.decide(_shas(), {}, old, "100", NOW) + assert sweep is True and "7.0 days old" in reason + + +@pytest.mark.parametrize("previous", [None, {}, {"commit_shas": "junk"}]) +def test_no_readable_record_runs_the_sweep(previous): + sweep, reason, _ = gate.decide(_shas(), {}, previous, "100", NOW) + assert sweep is True and "no SHA record" in reason + + +def test_a_pinned_dispatch_never_skips(): + pins = {"LibB": "a" * 40} + sweep, reason, record = gate.decide(_shas(), pins, _previous(_shas()), "100", NOW) + assert sweep is True and reason.startswith("pinned by dispatch") + assert record["pinned"] == pins + + +def test_force_sweeps_even_when_nothing_moved(): + sweep, reason, record = gate.decide(_shas(), {}, _previous(_shas()), "100", NOW, force=True) + assert sweep is True and reason == "forced by dispatch" + assert record["full_sweep_run_id"] == record["run_id"] + + +@pytest.mark.parametrize("conclusion", ["failure", "cancelled", "timed_out", ""]) +def test_a_red_latest_run_is_swept_again_not_masked_by_an_older_green(conclusion): + """Run 100 passed; run 101 failed at the same SHAs (a flake or a PyPI + move). Nothing moved since 100, but the night must sweep, not skip.""" + sweep, reason, _ = gate.decide(_shas(), {}, _previous(_shas()), "100", NOW, + last_run=("101", conclusion)) + assert sweep is True + assert reason == f"last run 101 concluded {conclusion or 'unknown'}" + + +def test_a_green_latest_run_still_allows_the_skip(): + sweep, reason, _ = gate.decide(_shas(), {}, _previous(_shas()), "100", NOW, + last_run=("100", "success")) + assert sweep is False and reason == "no main moved since run 100" + + +def test_the_summary_carries_the_headline_and_every_sha(): + _, _, record = gate.decide(_shas(), {}, _previous(_shas()), "100", NOW) + text = gate.summary_markdown(record) + assert "no main moved since run 100" in text + for repo in COVERED: + assert f"| {repo} | `{'a' * 40}` | main |" in text + + +# --- resolving pins --------------------------------------------------------- + +def test_resolve_uses_main_unless_pinned_and_resolves_refs(): + calls = [] + + def lookup(repo, ref): + calls.append((repo, ref)) + return ("c" if ref == "feature/x" else "d") * 40 + + shas = gate.resolve({"LibA": "E" * 40, "LibB": "feature/x"}, COVERED, lookup) + assert shas["LibA"] == "e" * 40 # full SHA: taken as given + assert shas["LibB"] == "c" * 40 # branch: resolved + assert shas["ws_a"] == "d" * 40 # unpinned: main + assert ("LibA", "E" * 40) not in calls + assert ("ws_a", "refs/heads/main") in calls + + +def test_resolve_rejects_an_unresolvable_ref(): + with pytest.raises(ValueError, match="cannot resolve"): + gate.resolve({"LibA": "abc123"}, COVERED, lambda repo, ref: "") + + +def test_pins_must_name_covered_repos(): + with pytest.raises(ValueError, match="does not cover"): + gate.parse_pins('{"LibC": "abc"}', COVERED) + assert gate.parse_pins("", COVERED) == {} + assert gate.parse_pins('{"LibB": " %s "}' % ("a" * 40), COVERED) == {"LibB": "a" * 40} + + +def test_main_writes_record_outputs_and_summary(tmp_path, monkeypatch): + prev = tmp_path / "prev.json" + prev.write_text(json.dumps(_previous(_shas()))) + out, summ = tmp_path / "out", tmp_path / "summary" + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(gate, "load_covered", lambda body=None: COVERED) + monkeypatch.setattr(gate, "resolve", lambda pins, covered, lookup=None: _shas()) + for k, v in {"PINS": "", "PREVIOUS_RECORD": str(prev), "PREVIOUS_RUN_ID": "100", + "RUN_ID": "200", "GITHUB_OUTPUT": str(out), + "GITHUB_STEP_SUMMARY": str(summ)}.items(): + monkeypatch.setenv(k, v) + assert gate.main() == 0 + record = json.loads((tmp_path / "shas.json").read_text()) + assert record["run_id"] == "200" and record["swept"] is False + lines = out.read_text().splitlines() + assert "sweep=false" in lines + assert json.loads(lines[1].split("=", 1)[1]) == _shas() + assert "no main moved since run 100" in summ.read_text() + + +@pytest.mark.parametrize("env, reason", [ + ({"FORCE": "true"}, "forced by dispatch"), + ({"FORCE": "false", "LAST_RUN_ID": "101", "LAST_RUN_CONCLUSION": "failure"}, + "last run 101 concluded failure"), + ({"FORCE": "false", "LAST_RUN_ID": "", "LAST_RUN_CONCLUSION": ""}, + "no main moved since run 100"), +]) +def test_main_reads_force_and_the_latest_run_from_the_environment(tmp_path, monkeypatch, env, reason): + prev = tmp_path / "prev.json" + prev.write_text(json.dumps(_previous(_shas()))) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(gate, "load_covered", lambda body=None: COVERED) + monkeypatch.setattr(gate, "resolve", lambda pins, covered, lookup=None: _shas()) + for k, v in {"PINS": "", "PREVIOUS_RECORD": str(prev), "PREVIOUS_RUN_ID": "100", + "RUN_ID": "200", "GITHUB_OUTPUT": str(tmp_path / "o"), + "GITHUB_STEP_SUMMARY": str(tmp_path / "s"), **env}.items(): + monkeypatch.setenv(k, v) + assert gate.main() == 0 + assert json.loads((tmp_path / "shas.json").read_text())["reason"] == reason + + +# --- wiring ----------------------------------------------------------------- + +def _load(name): + return yaml.safe_load((WORKFLOWS / name).read_text()) + + +def _body_covered(): + return gate.load_covered(WORKFLOWS / "workspace-validation.yml") + + +def test_covered_repos_are_read_from_the_body_and_agree_with_every_checkout(): + """The body is the one source of truth for the covered repos. Every + workspace checkout in it must name a covered repo, and every library loop + must list the same libraries (load_covered raises otherwise).""" + covered = _body_covered() + assert len(covered) == len(set(covered)) and covered + body = _load("workspace-validation.yml") + notebook_ws = {p["workspace"] for p in + body["jobs"]["generate_notebooks"]["strategy"]["matrix"]["project"]} + assert notebook_ws <= set(covered) + for job in ("run_scripts", "run_notebooks"): + route = next(s["run"] for s in body["jobs"][job]["steps"] if s.get("id") == "ws") + assert set(re.findall(r"repo=(\w+)", route)) <= set(covered), job + loops = re.findall(r"for lib in ([\w ]+); do", + (WORKFLOWS / "workspace-validation.yml").read_text()) + assert loops and all(tuple(l.split()) == covered[:len(l.split())] for l in loops) + + +def test_load_covered_fails_loudly_on_a_reshaped_body(tmp_path): + body = tmp_path / "body.yml" + body.write_text("for lib in LibA LibB; do\n") + with pytest.raises(ValueError, match="no workspace map"): + gate.load_covered(body) + body.write_text("for lib in LibA; do\nfor lib in LibB; do\ndeclare -A WS=(\n [a]=ws_a\n)\n") + with pytest.raises(ValueError, match="one library list"): + gate.load_covered(body) + body.write_text("for lib in LibA LibB; do\ndeclare -A WS=(\n [a]=ws_a [b]=ws_b\n)\n") + assert gate.load_covered(body) == COVERED + + +def test_smoke_entry_gates_the_sweep_and_passes_the_shas(): + data = _load("workspace-smoke.yml") + triggers = data.get("on", data.get(True)) + assert triggers["schedule"] == [{"cron": "0 3 * * *"}] + # The smoke channel only ever tests main: no pin input, only force. + inputs = triggers["workflow_dispatch"]["inputs"] + assert set(inputs) == {"force"} + assert inputs["force"]["type"] == "boolean" and inputs["force"]["default"] is False + decide = next(s for s in data["jobs"]["gate"]["steps"] if s.get("id") == "decide") + assert "PINS" not in decide["env"] + assert decide["env"]["FORCE"] == "${{ inputs.force && 'true' || 'false' }}" + assert {"LAST_RUN_ID", "LAST_RUN_CONCLUSION"} <= set(decide["env"]) + jobs = data["jobs"] + smoke = jobs["smoke"] + assert smoke["needs"] == "gate" + assert smoke["if"] == "needs.gate.outputs.sweep == 'true'" + assert smoke["with"]["commit_shas"] == "${{ needs.gate.outputs.commit_shas }}" + upload = next(s for s in jobs["gate"]["steps"] + if str(s.get("uses", "")).startswith("actions/upload-artifact")) + assert upload["with"]["name"] == test_run.SHA_ARTIFACT + assert upload["with"]["path"] == "shas.json" + assert data["permissions"]["actions"] == "read" + + +def test_pinned_entry_has_its_own_history_and_always_sweeps(): + data = _load("workspace-smoke-pinned.yml") + triggers = data.get("on", data.get(True)) + assert set(triggers) == {"workflow_dispatch"} + assert triggers["workflow_dispatch"]["inputs"]["commit_shas"]["required"] is True + jobs = data["jobs"] + decide = next(s for s in jobs["gate"]["steps"] if s.get("id") == "decide") + assert decide["env"]["PINS"] == "${{ inputs.commit_shas }}" + smoke = jobs["smoke"] + assert smoke["needs"] == "gate" and "if" not in smoke + assert smoke["uses"].endswith("workspace-validation.yml") + assert smoke["with"] == {"mode": "smoke", + "commit_shas": "${{ needs.gate.outputs.commit_shas }}"} + upload = next(s for s in jobs["gate"]["steps"] + if str(s.get("uses", "")).startswith("actions/upload-artifact")) + assert upload["with"]["name"] == test_run.SHA_ARTIFACT + + +def test_body_pins_every_smoke_checkout_to_the_resolved_refs(): + body = _load("workspace-validation.yml") + jobs = body["jobs"] + assert jobs["find_scripts"]["outputs"]["refs"] == "${{ steps.mode.outputs.refs }}" + for job in ("generate_notebooks", "run_scripts", "run_notebooks"): + refs = [s["with"]["ref"] for s in jobs[job]["steps"] + if s.get("name") == "Checkout workspace"] + assert refs and all("needs.find_scripts.outputs.refs" in r for r in refs), job + text = (WORKFLOWS / "workspace-validation.yml").read_text() + assert not re.search(r'git clone --depth 1 "https://github\.com/[^/]+/\$lib"', text) + + +def test_resolve_mode_keeps_release_checkouts_on_main(tmp_path): + import os + import subprocess + step = next(s for s in _load("workspace-validation.yml")["jobs"]["find_scripts"]["steps"] + if s.get("id") == "mode") + for mode, expected in [("smoke", {"LibA": "a" * 40}), ("release", {})]: + out = tmp_path / f"out-{mode}" + subprocess.run(["bash", "-ec", step["run"]], check=True, env={ + **os.environ, "MODE_INPUT": mode, "GITHUB_OUTPUT": str(out), + "COMMIT_SHAS": json.dumps({"LibA": "a" * 40}, indent=2)}) + lines = dict(l.split("=", 1) for l in out.read_text().splitlines()) + assert lines["mode"] == mode and json.loads(lines["refs"]) == expected + + +def test_library_clone_step_checks_out_the_pinned_sha(tmp_path): + """Run the body's library-clone shell verbatim against local repos (git's + url.insteadOf redirects github.com): the pinned library lands on its pin, + the rest on main.""" + import os + import subprocess + + def git(*args, cwd): + return subprocess.run(["git", *args], cwd=cwd, check=True, + capture_output=True, text=True).stdout.strip() + + origin = tmp_path / "origin" + first = {} + step = next(s for s in _load("workspace-validation.yml")["jobs"]["run_scripts"]["steps"] + if str(s.get("name", "")).startswith("Checkout libraries")) + libraries = re.search(r"for lib in ([\w ]+); do", step["run"]).group(1).split() + url_prefix = re.search(r'git clone --depth 1 "(https://github\.com/[^/"$]+/)\$1"', + step["run"]).group(1) + pinned = libraries[0] + for lib in libraries: + repo = origin / lib + repo.mkdir(parents=True) + git("init", "-q", "-b", "main", cwd=repo) + for n in (1, 2): + (repo / "f").write_text(str(n)) + git("add", "f", cwd=repo) + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", str(n), cwd=repo) + if n == 1: + first[lib] = git("rev-parse", "HEAD", cwd=repo) + work = tmp_path / "work" + work.mkdir() + env = {**os.environ, "REFS": json.dumps({pinned: first[pinned]}), + "GIT_CONFIG_COUNT": "2", + "GIT_CONFIG_KEY_0": f"url.file://{origin}/.insteadOf", + "GIT_CONFIG_VALUE_0": url_prefix, + "GIT_CONFIG_KEY_1": "uploadpack.allowAnySHA1InWant", + "GIT_CONFIG_VALUE_1": "true"} + subprocess.run(["bash", "-ec", step["run"]], cwd=work, env=env, check=True, + capture_output=True, text=True) + for lib in libraries: + assert (work / "libs" / lib / "f").read_text() == ("1" if lib == pinned else "2") diff --git a/tests/test_test_run.py b/tests/test_test_run.py index bb1fdc9d..722aea5f 100644 --- a/tests/test_test_run.py +++ b/tests/test_test_run.py @@ -4,9 +4,18 @@ import json +import pytest + from heart.checks import test_run as tr +@pytest.fixture(autouse=True) +def _no_live_sha_record(monkeypatch): + """main() now also fetches the run's SHA record; never reach `gh` from + the suite. Tests that need a record pass cloud_sha_fetcher or re-patch.""" + monkeypatch.setattr(tr, "_cloud_sha_record", lambda rid: None) + + def test_from_report_extracts_ready_counts_and_stale_parked(): report = { "ready": False, @@ -79,6 +88,19 @@ def test_cloud_verdict_parses_completed_run(monkeypatch): assert v["ready"] is True and v["run_id"] == 42 and v["ts"] == "2026-06-23T00:00:00Z" +def test_cloud_verdict_reads_only_runs_on_main(monkeypatch): + """A dispatch from a feature branch (run 43034177136 was one) is not the + smoke verdict.""" + import types + seen = [] + monkeypatch.setattr(tr.subprocess, "run", lambda argv, **k: ( + seen.append(argv), types.SimpleNamespace(stdout="[]"))[1]) + tr._cloud_verdict() + argv = seen[0] + assert argv[argv.index("--branch") + 1] == "main" + assert argv[argv.index("--workflow") + 1] == "workspace-smoke.yml" + + def test_cloud_verdict_in_progress_is_unknown(monkeypatch): import types monkeypatch.setattr(tr.subprocess, "run", lambda *a, **k: types.SimpleNamespace( @@ -387,3 +409,112 @@ def test_main_downloads_artifact_for_new_run_id(monkeypatch, tmp_path): assert written["failed"] == 1 and written["counts_measured"] is True assert written["cloud_report_run_id"] == 22 assert written["failing_scripts"][0]["script"] == "scripts/a/b.py" + + +# --- skipped nights (PyAutoHeart#354) ---------------------------------------- +# +# workspace-smoke.yml skips the sweep when no main moved; the skip run concludes +# success and its SHA record names the full sweep it re-attests. + +SKIP_RECORD = { + "schema": 1, "run_id": 31, "swept": False, + "reason": "no main moved since run 30", + "full_sweep_run_id": 30, "full_sweep_created_at": "2026-11-18T03:00:05Z", + "pinned": {}, "commit_shas": {"LibA": "a" * 40}, +} + + +def _green_skip_verdict(monkeypatch): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": True, "ts": "2026-11-19T03:00:04Z", "run_id": 31, "url": "U31"}) + + +def test_skipped_night_takes_counts_from_the_attested_sweep(monkeypatch, tmp_path): + _green_skip_verdict(monkeypatch) + fetched = [] + + def report(rid): + fetched.append(rid) + return {"passed": 120, "failed": 0, "skipped": 4, "timeout": 0} + + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=report, + cloud_sha_fetcher=lambda rid: SKIP_RECORD) + assert fetched == [30] # the full sweep's report, not the skip run's + assert out["ready"] is True and out["counts_measured"] is True + assert out["passed"] == 120 and out["cloud_report_run_id"] == 30 + assert out["sweep_skipped"] is True and out["full_sweep_run_id"] == 30 + assert out["full_sweep_ts"] == "2026-11-18T03:00:05Z" + # Labelled as a re-attestation, never as a fresh sweep of run 31. + assert out["run_label"] == "cloud#30 (re-attested by #31: no main moved)" + assert out["commit_shas"] == {"LibA": "a" * 40} + + +def test_skipped_night_keeps_the_evidence_fresh(monkeypatch, tmp_path): + """The skip run's own timestamp is the evidence ts, so readiness' age rule + (TEST_STALE_DAYS) does not age a quiet week into STALE.""" + _green_skip_verdict(monkeypatch) + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: None, + cloud_sha_fetcher=lambda rid: SKIP_RECORD) + assert out["ts"] == "2026-11-19T03:00:04Z" + import datetime + from heart import readiness + # A day after the skip: the age rule measures from the skip run. + ref = datetime.datetime(2026, 11, 20, 3, tzinfo=datetime.timezone.utc) + assert readiness._age_days(out["ts"], ref) < 1.01 + assert readiness._age_days(out["full_sweep_ts"], ref) > 1.9 + + +def test_full_sweep_record_changes_nothing_but_carries_the_shas(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": True, "ts": "t", "run_id": 30, "url": "U30"}) + record = {**SKIP_RECORD, "run_id": 30, "swept": True, "full_sweep_run_id": 30} + fetched = [] + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: fetched.append(rid), + cloud_sha_fetcher=lambda rid: record) + assert fetched == [30] + assert "sweep_skipped" not in out and out["run_label"] == "cloud#30" + assert out["commit_shas"] == record["commit_shas"] + + +def test_missing_sha_record_behaves_as_before(monkeypatch, tmp_path): + """Runs from before the gate, or an expired artifact: unchanged behaviour.""" + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": True, "ts": "t", "run_id": 29, "url": "U"}) + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: None, + cloud_sha_fetcher=lambda rid: None) + assert out["run_label"] == "cloud#29" and "sweep_skipped" not in out + assert "commit_shas" not in out + + +def test_pinned_run_is_marked(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 32, "url": "U"}) + record = {**SKIP_RECORD, "run_id": 32, "swept": True, "full_sweep_run_id": 32, + "pinned": {"LibA": "b" * 40}} + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_sha_fetcher=lambda rid: record) + assert out["pinned"] == {"LibA": "b" * 40} + + +def test_main_caches_the_sha_record_per_run_id(monkeypatch, tmp_path): + import os + from pathlib import Path + state_dir = Path(os.environ["HEART_STATE_DIR"]) + state_dir.mkdir(parents=True, exist_ok=True) + (state_dir / "test_run.json").write_text(json.dumps({ + "sha_record_run_id": 31, "sha_record": SKIP_RECORD, + "cloud_report_run_id": 30, + "cloud_counts": {"passed": 9, "failed": 0, "skipped": 0, "timeout": 0}, + })) + _green_skip_verdict(monkeypatch) + boom = lambda rid: (_ for _ in ()).throw(AssertionError("downloaded")) # noqa: E731 + monkeypatch.setattr(tr, "_cloud_sha_record", boom) + monkeypatch.setattr(tr, "_cloud_report", boom) + assert tr.main(["test_run", str(tmp_path)]) == 0 + written = json.loads((state_dir / "test_run.json").read_text()) + assert written["sweep_skipped"] is True and written["passed"] == 9 + assert written["run_label"].startswith("cloud#30 (re-attested by #31") diff --git a/tests/test_workflow_wiring.py b/tests/test_workflow_wiring.py index 3525dc90..d4ccdbf4 100644 --- a/tests/test_workflow_wiring.py +++ b/tests/test_workflow_wiring.py @@ -38,9 +38,24 @@ def test_smoke_entry_owns_the_schedule_and_calls_body_in_smoke_mode(): data = _load("workspace-smoke.yml") triggers = _triggers(data) assert set(triggers) == {"schedule", "workflow_dispatch"} - (job,) = data["jobs"].values() + # A `gate` job decides whether the nightly sweep runs (PyAutoHeart#354, + # tested in test_smoke_sha_gate.py); the sweep itself is the one job + # calling the body. + assert set(data["jobs"]) == {"gate", "smoke"} + job = data["jobs"]["smoke"] + assert job["uses"].endswith("workspace-validation.yml") + assert job["with"]["mode"] == "smoke" + + +def test_pinned_entry_is_dispatch_only_and_calls_body_in_smoke_mode(): + """Bisect runs at pinned SHAs get their own run history (PyAutoHeart#354) + so they can never become the smoke channel's latest run.""" + data = _load("workspace-smoke-pinned.yml") + assert set(_triggers(data)) == {"workflow_dispatch"} + job = data["jobs"]["smoke"] assert job["uses"].endswith("workspace-validation.yml") assert job["with"]["mode"] == "smoke" + assert VALIDATION_WORKFLOW != "workspace-smoke-pinned.yml" def test_release_entry_has_no_mode_input_and_calls_body_in_release_mode():