From fe93a68dd0656dc7b47bf309027987c95abd0379 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 30 Jul 2026 14:40:03 +0100 Subject: [PATCH] fix: never print counts nobody measured; ingest the run's report artifact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 2026-07-30 live bug: readiness said 'workspace validation not passing (0 failed, cloud#30516167217)' while that run had 2 failed + 1 timeout — ready came from the cloud run conclusion, the counts from a local run_logs/latest/report.json that does not exist for cloud runs, and every consumer printed the zero-filled placeholders as fact (PyAutoHeart#119). - test_run.py: summaries carry an explicit counts_measured flag; _from_report extracts compact failing_scripts (no tracebacks); new _cloud_report() downloads the run's workspace-validation-report artifact; run() takes a cloud_report_fetcher injected only by the tick entrypoint (run() itself stays no-network/side-effect-free), promotes artifact counts when no local report exists, and records cloud_report_run_id; main() caches the artifact per run id via the previously persisted sidecar and stops printing fabricated counts in its own CLI line. - readiness.py: measured -> 'not passing (2 failed, 1 timeout, cloud#…: , +N more)'; unmeasured -> 'failing (…; counts not ingested — see run)'; legacy cloud-shaped sidecars treated as unmeasured. - dashboard.py: same guard (no 0p/0f/0s placeholders); failing scripts in the section details. Verified live: the tick now writes 585p/2f/91s @ cloud#30516167217 with the three failing scripts, and compute() emits the honest reason above. Suite: 316 passed. Co-Authored-By: Claude Fable 5 --- heart/checks/test_run.py | 144 ++++++++++++++++++++++++++++++++++++--- heart/dashboard.py | 21 ++++-- heart/readiness.py | 33 +++++++-- tests/test_dashboard.py | 32 +++++++++ tests/test_readiness.py | 38 +++++++++++ tests/test_test_run.py | 134 ++++++++++++++++++++++++++++++++++++ 6 files changed, 383 insertions(+), 19 deletions(-) diff --git a/heart/checks/test_run.py b/heart/checks/test_run.py index 086d749b..5197aff2 100644 --- a/heart/checks/test_run.py +++ b/heart/checks/test_run.py @@ -16,6 +16,13 @@ per-job ``*__script.json`` ``summary`` blocks, set ``ready`` to ``None`` (the verdict treats that as "unknown", a yellow — never a silent green), and mark the parked-script counts unknown. + +When the verdict comes from a cloud run and no local report exists, the run's +own ``workspace-validation-report`` artifact supplies the real counts and +failing-script names (fetched once per run id by the tick entrypoint). A +summary must never carry counts nobody measured: ``counts_measured`` says +whether the passed/failed/skipped/timeout keys are real, and every consumer +(readiness, dashboard, this module's own CLI line) checks it before printing. """ from __future__ import annotations @@ -25,8 +32,9 @@ import os import subprocess import sys +import tempfile from pathlib import Path -from typing import Any +from typing import Any, Callable # Reuse the same root/latest resolution as script_timing.py. HEART_HOME = Path(__file__).resolve().parents[2] @@ -45,6 +53,10 @@ # comes from a local `autohands run_all` when one is present. VALIDATION_REPO = os.environ.get("GITHUB_REPOSITORY", "PyAutoLabs/PyAutoHeart") VALIDATION_WORKFLOW = "workspace-validation.yml" +# The aggregated per-run report the workflow's `analyze` job uploads; it holds +# 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" # 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 @@ -143,6 +155,24 @@ def _from_report(report: dict[str, Any]) -> dict[str, Any]: "age_days": entry.get("age_days"), } ) + # Compact failing-script names (the report's `failures` entries also carry + # full tracebacks — those stay in the report, never in the sidecar). + failing = [] + for entry in report.get("failures", []) or []: + if not isinstance(entry, dict): + continue + path = str(entry.get("file") or "") + directory = str(entry.get("directory") or "").strip("/") + name = path.rsplit("/", 1)[-1] + failing.append( + { + "project": entry.get("project"), + "script": f"{directory}/{name}" if directory else path.lstrip("/"), + "status": entry.get("status"), + } + ) + if len(failing) >= 10: + break return { "ready": report.get("ready"), "passed": summary.get("passed", 0), @@ -153,6 +183,8 @@ def _from_report(report: dict[str, Any]) -> dict[str, Any]: "run_label": report.get("run_label", ""), "parked_stale_count": len(parked), "parked_stale": parked, + "failing_scripts": failing, + "counts_measured": True, # The surface this report measured (projects/shards/run_types/env # profile). Carried through so the leg's history is comparable at all: # a count is only a trend against the same denominator (#83 §5.3). @@ -189,11 +221,57 @@ def _from_per_job(results_dir: Path) -> dict[str, Any]: "run_label": results_dir.resolve().name, "parked_stale_count": 0, "parked_stale": [], + "failing_scripts": [], + "counts_measured": True, "source": "per-job", } -def run(results_dir: Path | None = None, fetch_cloud: bool | None = None) -> dict[str, Any]: +def _cloud_report(run_id: Any) -> dict[str, Any] | None: + """Download run_id's aggregated report artifact and parse its report.json. + + Never raises; None if gh is unavailable, the artifact expired, or the JSON + is malformed. The artifact is a few kB — cheap, but still network: callers + cache per run_id (see main()) so the <30s tick pays at most one download + per new validation run.""" + 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", REPORT_ARTIFACT, "-D", td], + capture_output=True, text=True, timeout=60, + ) + if res.returncode != 0: + return None + report = _read_json(Path(td) / "report.json") + except Exception: + return None + return report if isinstance(report, dict) else None + + +def counts_measured(summary: dict[str, Any]) -> bool: + """True if the summary's counts came from an actual report. + + Legacy sidecars predate the explicit flag: the cloud-only shape (source + "cloud" with a synthesised ``cloud#`` run_label and no local report) + is exactly the shape whose zeros were fabricated — everything else parsed + a real report. Consumers (readiness, dashboard) must never print counts + for which this is False.""" + if "counts_measured" in summary: + return bool(summary["counts_measured"]) + return not ( + summary.get("source") == "cloud" + and str(summary.get("run_label", "")).startswith("cloud#") + ) + + +def run( + results_dir: Path | None = None, + fetch_cloud: bool | None = None, + cloud_report_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 # path — always disabled the cloud fetch, leaving the leg on stale local @@ -226,11 +304,32 @@ def run(results_dir: Path | None = None, fetch_cloud: bool | None = None) -> dic cloud = _server_verdict() if fetch_cloud else None if cloud is not None: local_ready = summary.get("ready") if summary else None + had_local = bool(summary) if not summary: + # No local report: these zeros are placeholders, not measurements — + # counts_measured stays False unless the run's own artifact report + # supplies real counts below. summary = { "passed": 0, "failed": 0, "skipped": 0, "timeout": 0, "per_project": {}, "parked_stale_count": 0, "parked_stale": [], + "failing_scripts": [], "counts_measured": False, } + # 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"]) + if isinstance(cs, dict): + counts = { + k: int(cs.get(k, 0) or 0) + for k in ("passed", "failed", "skipped", "timeout") + } + summary["cloud_counts"] = counts + summary["failing_scripts"] = list(cs.get("failing_scripts") or [])[:10] + summary["cloud_report_run_id"] = cloud["run_id"] + if not had_local: + summary.update(counts) + summary["counts_measured"] = True summary["cloud_ready"] = cloud["ready"] if local_ready is None: summary["ready"] = cloud["ready"] @@ -252,9 +351,28 @@ def run(results_dir: Path | None = None, fetch_cloud: bool | None = None) -> dic def main(argv: list[str]) -> int: results_dir = Path(argv[1]) if len(argv) > 1 else TEST_RESULTS_LATEST + + # Per-run-id cache over the previously persisted sidecar: the tick fires + # every <30s but a new validation run appears ~twice a day, so the artifact + # is downloaded once per run and replayed from state thereafter. + prev = _read_json(HEART_STATE_DIR / "test_run.json") + + def _cached_cloud_counts(run_id: Any) -> dict[str, Any] | None: + if ( + isinstance(prev, dict) + and prev.get("cloud_report_run_id") == run_id + and isinstance(prev.get("cloud_counts"), dict) + ): + return { + **prev["cloud_counts"], + "failing_scripts": prev.get("failing_scripts") or [], + } + report = _cloud_report(run_id) + return _from_report(report) if isinstance(report, dict) else None + # 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) + summary = run(results_dir, fetch_cloud=True, cloud_report_fetcher=_cached_cloud_counts) sys.path.insert(0, str(HEART_HOME)) from heart import state @@ -271,19 +389,27 @@ def main(argv: list[str]) -> int: ready = summary.get("ready") failed = summary.get("failed", 0) - if ready is False or failed: + measured = counts_measured(summary) + if ready is False or (failed and measured): glyph = glyph_fail() - label = c_fail(f"NOT ready ({failed} failed)") + label = c_fail( + f"NOT ready ({failed} failed)" + if measured + else "NOT ready (counts not ingested — see run)" + ) elif ready is True: glyph = glyph_ok() label = c_ok("ready") else: glyph = glyph_warn() label = c_warn("ready unknown") - extra = c_meta( - f" {summary.get('passed', 0)}p/{failed}f/{summary.get('skipped', 0)}s" - f" @ {summary.get('run_label', '?')}" - ) + if measured: + extra = c_meta( + f" {summary.get('passed', 0)}p/{failed}f/{summary.get('skipped', 0)}s" + f" @ {summary.get('run_label', '?')}" + ) + else: + extra = c_meta(f" @ {summary.get('run_label', '?')}") print(f"{glyph} {c_info('test_run')} {label}{extra}") return 0 diff --git a/heart/dashboard.py b/heart/dashboard.py index 2a2f4f03..c49e6e1e 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -37,6 +37,7 @@ from dataclasses import dataclass, field from typing import Any, Iterable, Sequence +from heart.checks.test_run import counts_measured as tr_counts_measured from heart.heart_color import ( c_bold, c_dim, c_fail, c_info, c_meta, c_ok, c_warn, glyph_fail, glyph_info, glyph_ok, glyph_warn, @@ -480,17 +481,27 @@ def build_board( tr = snapshot.get("test_run") or {} if tr: ready = tr.get("ready") - counts = ( - f"{_as_int(tr.get('passed'))}p / {_as_int(tr.get('failed'))}f / " - f"{_as_int(tr.get('skipped'))}s @ {tr.get('run_label', '?')}" - ) - if ready is False or _as_int(tr.get("failed")): + measured = tr_counts_measured(tr) + if measured: + counts = ( + f"{_as_int(tr.get('passed'))}p / {_as_int(tr.get('failed'))}f / " + f"{_as_int(tr.get('skipped'))}s @ {tr.get('run_label', '?')}" + ) + else: + # Conclusion-only verdict: never render fabricated zeros. + counts = f"counts not ingested @ {tr.get('run_label', '?')}" + if ready is False or (measured and _as_int(tr.get("failed"))): st, summary = FAIL, f"NOT ready — {counts}" elif ready is True: st, summary = OK, f"ready — {counts}" else: st, summary = WARN, f"ready unknown — {counts}" details = [] + for s in (tr.get("failing_scripts") or [])[:3]: + if isinstance(s, dict): + details.append( + f"✗ {s.get('project')} {s.get('script')} ({s.get('status')})" + ) stale_n = _as_int(tr.get("parked_stale_count")) if stale_n: details.append(f"{stale_n} stale parked script(s)") diff --git a/heart/readiness.py b/heart/readiness.py index 322630ed..45afb863 100644 --- a/heart/readiness.py +++ b/heart/readiness.py @@ -85,6 +85,7 @@ from heart import state from heart.checks.ci_status import FAILURE_CONCLUSIONS, load_required_workflows +from heart.checks.test_run import counts_measured as tr_counts_measured from heart.heart_color import ( c_bold, c_fail, c_info, c_meta, c_ok, c_warn, glyph_fail, glyph_ok, glyph_warn, @@ -323,11 +324,33 @@ def scope_local(msg: str, key: str) -> None: if ready is False: # Workspace scripts/notebooks carry standing debt; failing validation # is advisory (YELLOW), not a release blocker. Real blockers are the - # library CI / install / version-skew gates above. - yellow.append( - f"workspace validation not passing " - f"({_as_int(test_run.get('failed', 0))} failed, {test_run.get('run_label', '?')})" - ) + # library CI / install / version-skew gates above. The reason may + # only state counts somebody measured (a local report or the run's + # ingested artifact) — a conclusion-only verdict says so instead of + # asserting "0 failed". + label = test_run.get("run_label", "?") + if tr_counts_measured(test_run): + failed = _as_int(test_run.get("failed", 0)) + timeout = _as_int(test_run.get("timeout", 0)) + msg = f"workspace validation not passing ({failed} failed" + if timeout: + msg += f", {timeout} timeout" + msg += f", {label}" + scripts = [ + s for s in (test_run.get("failing_scripts") or []) + if isinstance(s, dict) + ] + if scripts: + msg += ": " + ", ".join( + f"{s.get('project')} {s.get('script')}" for s in scripts[:3] + ) + if len(scripts) > 3: + msg += f", +{len(scripts) - 3} more" + yellow.append(msg + ")") + else: + yellow.append( + f"workspace validation failing ({label}; counts not ingested — see run)" + ) hit("test_failing") elif ready is True: # Passing-but-expired evidence is a freshness gap, not a warning — diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 26c885c5..b9be2694 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -164,6 +164,38 @@ def test_find_links_install_pass_is_warned_as_development_only(): assert "development-only (find-links" in section.summary +def test_test_run_cloud_conclusion_only_hides_fabricated_zeros(): + # The legacy cloud-only sidecar shape: red conclusion, no count evidence. + snap = make_snapshot(test_run={ + "ready": False, "passed": 0, "failed": 0, "skipped": 0, + "source": "cloud", "run_label": "cloud#30516167217"}) + + board = dashboard.build_board(snap, make_verdict("yellow", 70), now=FRESH_NOW) + section = next(s for s in board.sections if s.key == "test_run") + + assert section.state == dashboard.FAIL + assert "0p" not in section.summary + assert "counts not ingested" in section.summary + assert "cloud#30516167217" in section.summary + + +def test_test_run_failing_scripts_listed_in_details(): + snap = make_snapshot(test_run={ + "ready": False, "passed": 585, "failed": 2, "skipped": 91, + "counts_measured": True, "run_label": "cloud#1", + "failing_scripts": [ + {"project": "autogalaxy", "script": "scripts/interferometer/start_here.py", + "status": "failed"}, + ]}) + + board = dashboard.build_board(snap, make_verdict("yellow", 70), now=FRESH_NOW) + section = next(s for s in board.sections if s.key == "test_run") + + assert "585p" in section.summary and "2f" in section.summary + assert any("autogalaxy scripts/interferometer/start_here.py" in d + for d in section.details) + + def test_release_install_pass_names_the_index(): snap = make_snapshot(verify_install={ "ready": True, diff --git a/tests/test_readiness.py b/tests/test_readiness.py index 3e801270..24b12d1f 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -109,6 +109,44 @@ def test_test_run_failing_is_yellow_not_red(): assert v["score"] == 85 +def test_test_run_cloud_conclusion_only_never_fabricates_zero_failed(): + # The 2026-07-30 live bug: cloud red, no local report → the old reason + # asserted "0 failed". A conclusion-only verdict must say so instead. + v = compute(make_snapshot(test_run={ + "ready": False, "failed": 0, "source": "cloud", + "run_label": "cloud#30516167217"})) + assert v["verdict"] == "yellow" + assert not any("0 failed" in r for r in v["yellow_reasons"]) + assert any("counts not ingested" in r and "cloud#30516167217" in r + for r in v["yellow_reasons"]) + + +def test_test_run_explicit_unmeasured_flag_respected(): + v = compute(make_snapshot(test_run={ + "ready": False, "failed": 0, "counts_measured": False, + "run_label": "cloud#5"})) + assert any("counts not ingested" in r for r in v["yellow_reasons"]) + + +def test_test_run_failing_reason_names_scripts(): + v = compute(make_snapshot(test_run={ + "ready": False, "failed": 2, "timeout": 1, "run_label": "cloud#1", + "counts_measured": True, + "failing_scripts": [ + {"project": "autogalaxy", "script": "scripts/interferometer/start_here.py", + "status": "failed"}, + {"project": "autolens", "script": "scripts/interferometer/start_here.py", + "status": "failed"}, + {"project": "autolens", "script": "scripts/group/start_here.py", + "status": "timeout"}, + {"project": "autofit", "script": "scripts/x.py", "status": "failed"}, + ]})) + r = next(r for r in v["yellow_reasons"] if "workspace validation" in r) + assert "2 failed" in r and "1 timeout" in r + assert "autogalaxy scripts/interferometer/start_here.py" in r + assert "+1 more" in r + + def test_version_skew_unsatisfiable_floor_is_red(): snap = make_snapshot(version_skew={"workspaces": [ {"workspace": "autolens_workspace", "library": "PyAutoLens", diff --git a/tests/test_test_run.py b/tests/test_test_run.py index c865f8a7..bb1fdc9d 100644 --- a/tests/test_test_run.py +++ b/tests/test_test_run.py @@ -189,6 +189,7 @@ def test_main_consults_the_server_verdict(monkeypatch, tmp_path): from pathlib import Path monkeypatch.setattr(tr, "_server_verdict", lambda: { "ready": False, "ts": "2026-07-16T00:00:00Z", "run_id": 3, "url": "U"}) + monkeypatch.setattr(tr, "_cloud_report", lambda rid: None) # hermetic (tmp_path / "report.json").write_text(json.dumps({ "ready": True, "run_label": "local", "summary": {"passed": 5}})) assert tr.main(["test_run", str(tmp_path)]) == 0 @@ -253,3 +254,136 @@ def test_surface_absent_from_old_report_is_none_not_a_crash(tmp_path): "ready": True, "run_label": "old", "summary": {"passed": 1}})) out = tr.run(results_dir=tmp_path) assert out["surface"] is None + + +# --- honest counts + artifact ingest (PyAutoHeart#119) -------------------------- +# A summary may only carry counts somebody measured; when the verdict is a bare +# cloud conclusion, the run's own report artifact supplies the real counts and +# failing-script names (fetched by the tick entrypoint, cached per run id). + + +def test_cloud_red_no_local_report_counts_from_artifact(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 7, "url": "U"}) + fetched = [] + + def fetcher(run_id): + fetched.append(run_id) + return {"passed": 585, "failed": 2, "skipped": 91, "timeout": 1, + "failing_scripts": [{"project": "autogalaxy", + "script": "scripts/interferometer/start_here.py", + "status": "failed"}]} + + out = tr.run(results_dir=tmp_path, fetch_cloud=True, cloud_report_fetcher=fetcher) + assert fetched == [7] + assert out["ready"] is False + assert out["passed"] == 585 and out["failed"] == 2 and out["timeout"] == 1 + assert out["counts_measured"] is True + assert out["cloud_counts"]["failed"] == 2 + assert out["cloud_report_run_id"] == 7 + assert out["failing_scripts"][0]["script"].endswith("start_here.py") + + +def test_cloud_red_fetcher_fails_counts_not_measured(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 7, "url": "U"}) + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: None) + assert out["ready"] is False + assert out["counts_measured"] is False + assert "cloud_counts" not in out + + +def test_local_report_counts_stay_authoritative_artifact_enriches(monkeypatch, tmp_path): + (tmp_path / "report.json").write_text(json.dumps({ + "ready": False, "run_label": "local", "summary": {"passed": 5, "failed": 3}})) + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 8, "url": "U"}) + out = tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: { + "passed": 1, "failed": 1, "skipped": 0, "timeout": 0, + "failing_scripts": []}) + assert out["failed"] == 3 # the local surface keeps its counts + assert out["cloud_counts"]["failed"] == 1 # the cloud surface is carried alongside + assert out["counts_measured"] is True + + +def test_run_without_fetcher_marks_counts_unmeasured(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 9, "url": "U"}) + out = tr.run(results_dir=tmp_path, fetch_cloud=True) + assert out["counts_measured"] is False + + +def test_fetcher_skipped_while_cloud_run_in_progress(monkeypatch, tmp_path): + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": None, "ts": "t", "run_id": 10, "url": "U"}) + calls = [] + tr.run(results_dir=tmp_path, fetch_cloud=True, + cloud_report_fetcher=lambda rid: calls.append(rid)) + assert calls == [] + + +def test_from_report_extracts_failing_scripts_without_tracebacks(): + report = {"ready": False, "summary": {"failed": 1}, + "failures": [{"file": "/abs/workspace/scripts/interferometer/start_here.py", + "directory": "scripts/interferometer", + "project": "autolens", "status": "failed", + "traceback": "thousands of characters"}]} + out = tr._from_report(report) + assert out["failing_scripts"] == [{"project": "autolens", + "script": "scripts/interferometer/start_here.py", + "status": "failed"}] + assert out["counts_measured"] is True + + +def test_counts_measured_legacy_shapes(): + # legacy cloud-only sidecar (the fabricated-zero shape) → not measured + assert tr.counts_measured({"source": "cloud", "run_label": "cloud#1"}) is False + # legacy local-report sidecar → measured + assert tr.counts_measured({"source": "report", "run_label": "2026-05-29"}) is True + # cloud source but a local run_label (local report present) → measured + assert tr.counts_measured({"source": "cloud", "run_label": "local"}) is True + # the explicit flag always wins + assert tr.counts_measured( + {"source": "cloud", "run_label": "cloud#1", "counts_measured": True}) is True + + +def test_main_caches_artifact_per_run_id(monkeypatch, tmp_path): + """A sidecar already holding this run id's counts → no re-download.""" + 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({ + "cloud_report_run_id": 21, + "cloud_counts": {"passed": 7, "failed": 2, "skipped": 0, "timeout": 0}, + "failing_scripts": [{"project": "p", "script": "s.py", "status": "failed"}], + })) + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 21, "url": "U"}) + monkeypatch.setattr(tr, "_cloud_report", + lambda rid: (_ for _ in ()).throw(AssertionError("downloaded"))) + assert tr.main(["test_run", str(tmp_path)]) == 0 + written = json.loads((state_dir / "test_run.json").read_text()) + assert written["failed"] == 2 and written["counts_measured"] is True + assert written["failing_scripts"][0]["script"] == "s.py" + + +def test_main_downloads_artifact_for_new_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").unlink(missing_ok=True) + monkeypatch.setattr(tr, "_server_verdict", lambda: { + "ready": False, "ts": "t", "run_id": 22, "url": "U"}) + monkeypatch.setattr(tr, "_cloud_report", lambda rid: { + "ready": False, "summary": {"passed": 3, "failed": 1}, + "failures": [{"file": "x/scripts/a/b.py", "directory": "scripts/a", + "project": "autolens", "status": "failed"}]}) + assert tr.main(["test_run", str(tmp_path)]) == 0 + written = json.loads((state_dir / "test_run.json").read_text()) + 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"