From af9e3781a9e6bcc9075f14979c796ea97a6e7b22 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 12:43:48 +0000 Subject: [PATCH 1/3] feat(runner): Stage 3 one-retry and quarantine skip (PyAutoHeart#344) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Human ruling, M1 gate 2026-11-12. Both are opt-in flags of run_python.py that only Heart's Stage 3 (workspace-validation.yml, mode=release) passes: - --retry-failed: a FAILED script is re-run once. A pass on the retry is PASSED with `flaky`, `attempts: 2` and the first error kept — recorded, not hidden; a second failure stays FAILED. A TIMEOUT is not retried. - --quarantine FILE: the ACTIVE entries Heart resolved for the workspace (heart.quarantine skip-list). A matching script is SKIPPED, recorded with its bug ref, never run. Expiry, bug-ref and the 3-entry cap are Heart's. - aggregate_results carries `flaky` and `quarantined` lists into report.json and its markdown; `ready` is unchanged. - The per-run JSON stays byte-compatible when neither is used. Co-Authored-By: Claude Opus 5.5 --- autohands/aggregate_results.py | 19 +++++ autohands/build_util.py | 49 ++++++++++++- autohands/result_collector.py | 27 +++++++ autohands/run_python.py | 30 ++++++++ tests/test_stage3_retry_quarantine.py | 102 ++++++++++++++++++++++++++ 5 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 tests/test_stage3_retry_quarantine.py diff --git a/autohands/aggregate_results.py b/autohands/aggregate_results.py index d4e53c69..50abe486 100644 --- a/autohands/aggregate_results.py +++ b/autohands/aggregate_results.py @@ -189,6 +189,10 @@ def aggregate(results_dir: Path) -> dict: f["classification"] = classify_failure(f) skipped = [r for r in all_results if r.get("status") == "skipped"] + # Stage 3 (PyAutoHeart#344): passed on the one retry, and skipped by the + # expiring quarantine — both carried through so Heart records them. + flaky = [r for r in all_results if r.get("flaky")] + quarantined = [r for r in all_results if r.get("quarantined")] # Top-N slowest scripts across the whole run, regardless of status — # useful for spotting timing regressions before they cross the timeout. @@ -238,6 +242,8 @@ def aggregate(results_dir: Path) -> dict: "failures": [_clean_result(f) for f in failures], "failure_pr_correlations": pr_correlations, "skipped": [_clean_result(s) for s in skipped], + "flaky": [_clean_result(r) for r in flaky], + "quarantined": [_clean_result(r) for r in quarantined], "pr_changes": pr_changes, "runs": [{k: v for k, v in run.items() if k != "results"} for run in runs], } @@ -283,6 +289,19 @@ def generate_markdown(report: dict) -> str: lines.append(" • ".join(meta_parts)) lines.append("") + # Stage 3's retry and quarantine (PyAutoHeart#344) — at the top: a flaky + # pass and a quarantined skip are both things a reader must see. + for key, title in (("flaky", "## Flaky — failed, then passed on the one retry"), + ("quarantined", "## Quarantined — skipped, not run")): + entries = report.get(key) or [] + if entries: + lines.append(title) + lines.append("") + for e in entries: + note = (e.get("first_error") or "") if key == "flaky" else (e.get("skip_reason") or "") + lines.append(f"- `{e.get('project', '')}` `{e.get('file', '')}` {note}".rstrip()) + lines.append("") + # Slow-skipped and needs-fix scripts — surface at the top so they # can't be missed def _render_tagged_section(title: str, intro: str, entries: list) -> None: diff --git a/autohands/build_util.py b/autohands/build_util.py index 09a8c353..187f8385 100644 --- a/autohands/build_util.py +++ b/autohands/build_util.py @@ -1497,7 +1497,9 @@ def files_from_list(directory: str, list_path) -> List[Path]: return files -def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_reasons=None, env_config=None, files=None): +def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_reasons=None, + env_config=None, files=None, retry_failed=False, + quarantine=None): """ Run the scripts under ``directory``, honouring ``no_run_list``. @@ -1516,8 +1518,22 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea Measured before this was settled: honouring ``no_run`` over the workspaces' allowlists would have dropped 13 scripts across four repos, every one of which runs today. + + ``retry_failed`` and ``quarantine`` are Stage 3's (release validation, + PyAutoHeart#344; the human ruling of 2026-11-12) and need a ``report``: + + * ``retry_failed`` re-runs a FAILED script once. A pass on the retry is + recorded PASSED with ``flaky`` set and the first error kept — recorded, + not hidden; a second failure stays FAILED (``attempts`` 2). A TIMEOUT is + not retried: it already spent its whole cap, and slowness is not flake. + * ``quarantine`` is the list of ACTIVE entries Heart resolved for this + workspace (``{"script", "bug", "expires"}``; Heart owns the expiry, the + bug-ref and the 3-entry rules). A matching script is SKIPPED with the + entry's bug ref, never run — the gate it would have failed is reported by + Heart as YELLOW, never GREEN. """ no_run_list = no_run_list or [] + quarantine = [q for q in (quarantine or []) if isinstance(q, dict) and q.get("script")] # Infrastructure files — always skip, never report infra_skip = ["__init__", "README"] no_run_list.extend(infra_skip) @@ -1532,6 +1548,18 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea for file in files: if file.stem in infra_skip: continue + q = next((q for q in quarantine if should_skip(file, [str(q["script"])])), None) + if q is not None: + print(f" {file} ... QUARANTINED ({q.get('bug')}, until {q.get('expires')})") + if report is not None: + from result_collector import ScriptResult, Status + report.results.append(ScriptResult( + file=str(file), + status=Status.SKIPPED, + skip_reason=f"quarantined: {q.get('bug')} (expires {q.get('expires')})", + quarantined=str(q.get("bug")), + )) + continue # The allowlist is the policy when there is one: no_run.yaml governs # OTHER runs (the release mega-run, notebook generation), not this one. if not files_are_allowlist and should_skip(file, no_run_list): @@ -1566,3 +1594,22 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea env = build_env_for_script(file, env_config) extra_args = args_for_script(file, env_config) execute_script(str(file), report=report, env=env, extra_args=extra_args) + if retry_failed and report is not None: + _retry_once(file, report, env, extra_args) + + +def _retry_once(file, report, env, extra_args) -> None: + """Stage 3's one retry of a FAILED script (see execute_scripts_in_folder).""" + from result_collector import Status + first = report.results[-1] if report.results else None + if first is None or first.file != str(file) or first.status != Status.FAILED: + return + print(" failed; retrying once (Stage 3)...") + report.results.pop() + execute_script(str(file), report=report, env=env, extra_args=extra_args) + second = report.results[-1] + second.attempts = 2 + if second.status == Status.PASSED: + second.flaky = True + tail = (first.traceback or "").strip().splitlines()[-1:] or [first.error_message or ""] + second.first_error = tail[0] diff --git a/autohands/result_collector.py b/autohands/result_collector.py index 86a68d5b..3518abd8 100644 --- a/autohands/result_collector.py +++ b/autohands/result_collector.py @@ -65,6 +65,15 @@ class ScriptResult: # killed, so there is no exit code the script chose) and for entries that # never ran. exit_code: Optional[int] = None + # Stage 3's one retry (PyAutoHeart#344): how many times the entry ran, and + # whether it failed first and passed on the retry — FLAKY, recorded, never + # hidden. ``first_error`` keeps the first attempt's failure. + attempts: int = 1 + flaky: bool = False + first_error: Optional[str] = None + # Set when the entry was skipped by Heart's expiring Stage 3 quarantine: + # the bug-task ref the quarantine entry names. + quarantined: Optional[str] = None @property def was_timed(self) -> bool: @@ -116,6 +125,16 @@ def to_dict(self): d["traceback"] = "\n".join(lines[-100:]) if self.skip_reason is not None: d["skip_reason"] = self.skip_reason + # Emitted only when set, so a run without retries or quarantine keeps + # the per-run JSON byte-compatible. + if self.attempts > 1: + d["attempts"] = self.attempts + if self.flaky: + d["flaky"] = True + if self.first_error is not None: + d["first_error"] = self.first_error + if self.quarantined is not None: + d["quarantined"] = self.quarantined return d @@ -201,6 +220,14 @@ def to_markdown(self) -> str: lines.append("```") lines.append("") + flaky = [r for r in self.results if r.flaky] + if flaky: + lines.append("## Flaky (failed, then passed on the one retry)") + lines.append("") + for r in flaky: + lines.append(f"- `{r.file}` — first attempt: {r.first_error or 'failed'}") + lines.append("") + skipped = [r for r in self.results if r.status == Status.SKIPPED] if skipped: lines.append("## Skipped") diff --git a/autohands/run_python.py b/autohands/run_python.py index 7cdc5b21..7e0f5210 100644 --- a/autohands/run_python.py +++ b/autohands/run_python.py @@ -35,6 +35,25 @@ ), ) +parser.add_argument( + "--retry-failed", + action="store_true", + help=( + "Stage 3 only (PyAutoHeart#344): re-run a FAILED script once; a pass on " + "the retry is recorded as flaky. Needs --report-dir." + ), +) +parser.add_argument( + "--quarantine", + type=str, + default=None, + help=( + "Stage 3 only: a JSON file of the ACTIVE quarantine entries Heart " + "resolved for this workspace (`python -m heart.quarantine skip-list`). " + "A matching script is skipped and recorded as quarantined." + ), +) + args = parser.parse_args() project = args.project @@ -113,6 +132,15 @@ print(f"ERROR: {e}", file=sys.stderr) sys.exit(1) + quarantine = None + if args.quarantine: + import json + # A named file that is missing or unreadable is a configuration error: + # running the quarantined script instead would be safe, but silently + # ignoring the flag would hide that the policy never arrived. + with open(args.quarantine) as fh: + quarantine = json.load(fh).get("entries", []) + build_util.execute_scripts_in_folder( no_run_list=no_run_list, directory=directory, @@ -120,6 +148,8 @@ skip_reasons=skip_reasons, env_config=env_config, files=files, + retry_failed=args.retry_failed and report is not None, + quarantine=quarantine, ) if report is not None: diff --git a/tests/test_stage3_retry_quarantine.py b/tests/test_stage3_retry_quarantine.py new file mode 100644 index 00000000..a8d16a46 --- /dev/null +++ b/tests/test_stage3_retry_quarantine.py @@ -0,0 +1,102 @@ +""" +Stage 3's one script retry and the quarantine skip (PyAutoHeart#344). + +Human ruling, 2026-11-12: a Stage 3 script that fails is re-run once; a pass +on the retry is recorded as flaky, not hidden; a second failure stays red. A +quarantined script (an ACTIVE entry Heart resolved: bug ref, expiry) is +skipped and recorded, never run. Heart owns the expiry / bug-ref / 3-entry +rules and the YELLOW; these tests pin the runner's half. +""" + +import json +import sys +from pathlib import Path + +import pytest + +PROJECT_ROOT = Path(__file__).parent.parent +AUTOHANDS_DIR = PROJECT_ROOT / "autohands" +sys.path.insert(0, str(AUTOHANDS_DIR)) + +import aggregate_results # noqa: E402 +from build_util import execute_scripts_in_folder # noqa: E402 +from result_collector import RunReport, Status # noqa: E402 + +# Fails on its first run, passes on every later one (a marker file records +# that it ran) — a flake. +FLAKY = """ +from pathlib import Path +marker = Path(__file__).with_suffix(".ran") +if not marker.exists(): + marker.write_text("1") + raise SystemExit("first attempt: transient failure") +""" +BROKEN = 'raise RuntimeError("really broken")\n' + + +@pytest.fixture +def workspace(tmp_path, monkeypatch): + scripts = tmp_path / "scripts" + scripts.mkdir() + (scripts / "flaky.py").write_text(FLAKY) + (scripts / "broken.py").write_text(BROKEN) + (scripts / "fine.py").write_text("") + monkeypatch.chdir(tmp_path) + return tmp_path + + +def _run(**kw): + report = RunReport(project="demo", directory="scripts", run_type="script") + execute_scripts_in_folder(directory="scripts", report=report, **kw) + return {Path(r.file).name: r for r in report.results}, report + + +def test_witness_344_retry_pass_is_recorded_as_flaky(workspace): + results, report = _run(retry_failed=True) + r = results["flaky.py"] + assert r.status == Status.PASSED + assert r.flaky is True and r.attempts == 2 + assert "transient failure" in r.first_error + d = r.to_dict() + assert d["flaky"] is True and d["attempts"] == 2 and "first_error" in d + assert "## Flaky" in report.to_markdown() + # One entry per script: the first attempt is replaced, not double-counted. + assert len(report.results) == 3 + + +def test_witness_344_retry_fail_is_recorded_red(workspace): + results, report = _run(retry_failed=True) + r = results["broken.py"] + assert r.status == Status.FAILED and r.attempts == 2 and r.flaky is False + assert report.has_failures + + +def test_without_the_flag_nothing_is_retried(workspace): + results, _ = _run() + assert results["flaky.py"].status == Status.FAILED + assert results["flaky.py"].attempts == 1 + # A passing entry carries none of the new keys: the per-run JSON is unchanged. + assert set(results["fine.py"].to_dict()) == {"file", "status", "duration_seconds"} + + +def test_a_quarantined_script_is_skipped_and_recorded_not_run(workspace): + q = [{"script": "scripts/broken.py", "bug": "PyAutoDemo#7", "expires": "2026-11-19"}] + results, report = _run(retry_failed=True, quarantine=q) + r = results["broken.py"] + assert r.status == Status.SKIPPED and r.quarantined == "PyAutoDemo#7" + assert "quarantined: PyAutoDemo#7" in r.skip_reason + assert not report.has_failures + + +def test_aggregate_carries_flaky_and_quarantined(workspace, tmp_path, monkeypatch): + monkeypatch.setattr(aggregate_results, "fetch_merged_prs", lambda: []) # no network + q = [{"script": "scripts/broken.py", "bug": "PyAutoDemo#7", "expires": "2026-11-19"}] + _, report = _run(retry_failed=True, quarantine=q) + out = tmp_path / "results" + report.write(out) + agg = aggregate_results.aggregate(out) + assert agg["ready"] is True + assert [Path(e["file"]).name for e in agg["flaky"]] == ["flaky.py"] + assert [e["quarantined"] for e in agg["quarantined"]] == ["PyAutoDemo#7"] + md = aggregate_results.generate_markdown(agg) + assert "Flaky" in md and "Quarantined" in md From 9e17e201e058d4a14b4de81ac65e45ee86168d22 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 13:12:17 +0000 Subject: [PATCH 2/3] fix(runner): exact quarantine match, clean output before retry, record the entry (PyAutoHeart#344 review) - Quarantine entries match the exact workspace-relative path, never a substring (`scripts/imaging/fit.py` no longer skips `scripts/multi_imaging/fit.py`). - Before the one retry, files the failed attempt wrote under `output/` (mtime at or after its start) are removed, so a script that failed after its search completed cannot resume from the finished output and pass. Earlier scripts' output is untouched. - A quarantined skip records its entry (`quarantine_entry`: workspace, script, bug, expires) so Heart can judge what the rehearsal skipped. Co-Authored-By: Claude Opus 5.5 --- autohands/build_util.py | 62 ++++++++++++++++++++++++--- autohands/result_collector.py | 6 +++ autohands/run_python.py | 4 +- tests/test_stage3_retry_quarantine.py | 49 +++++++++++++++++++++ 4 files changed, 115 insertions(+), 6 deletions(-) diff --git a/autohands/build_util.py b/autohands/build_util.py index 187f8385..29d97a1d 100644 --- a/autohands/build_util.py +++ b/autohands/build_util.py @@ -1548,7 +1548,7 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea for file in files: if file.stem in infra_skip: continue - q = next((q for q in quarantine if should_skip(file, [str(q["script"])])), None) + q = _quarantine_match(file, quarantine) if q is not None: print(f" {file} ... QUARANTINED ({q.get('bug')}, until {q.get('expires')})") if report is not None: @@ -1558,6 +1558,8 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea status=Status.SKIPPED, skip_reason=f"quarantined: {q.get('bug')} (expires {q.get('expires')})", quarantined=str(q.get("bug")), + quarantine_entry={k: q.get(k) for k in + ("workspace", "script", "bug", "expires")}, )) continue # The allowlist is the policy when there is one: no_run.yaml governs @@ -1593,18 +1595,68 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea from env_config import build_env_for_script, args_for_script env = build_env_for_script(file, env_config) extra_args = args_for_script(file, env_config) + started = time.time() execute_script(str(file), report=report, env=env, extra_args=extra_args) if retry_failed and report is not None: - _retry_once(file, report, env, extra_args) + _retry_once(file, report, env, extra_args, started) + + +def _quarantine_match(file, quarantine): + """The quarantine entry naming exactly this script, or None. + + Matched on the EXACT workspace-relative path (the runner's cwd is the + workspace root), never as a substring: an entry for ``scripts/imaging/fit.py`` + must not also skip ``scripts/multi_imaging/fit.py``.""" + from pathlib import PurePosixPath + from result_collector import workspace_relative + rel = PurePosixPath(Path(workspace_relative(str(file))).as_posix()) + for q in quarantine: + if PurePosixPath(str(q["script"])) == rel: + return q + return None + + +#: Where workspace scripts write (autonerves' default ``output_path`` is +#: ``/output``; the runner's cwd is the workspace root). +OUTPUT_DIRNAME = "output" + + +def clean_output_written_since(started: float, root=None) -> int: + """Delete every file under ``/output`` written or modified at or after + ``started`` (the failed attempt's start), and the directories it leaves + empty. Returns the number of files removed. + + That is exactly what the failed attempt produced: a model-fit search that + completed before the script failed leaves its finished samples there, and + a retry would RESUME from them and pass without re-running the search. + Output written by earlier scripts (older mtimes) is left alone.""" + out = Path(root or Path.cwd()) / OUTPUT_DIRNAME + if not out.is_dir(): + return 0 + removed = 0 + for f in sorted(out.rglob("*"), key=lambda p: len(p.parts), reverse=True): + try: + if f.is_file() or f.is_symlink(): + if f.lstat().st_mtime >= started: + f.unlink() + removed += 1 + elif f.is_dir() and not any(f.iterdir()): + f.rmdir() + except OSError: + pass + return removed -def _retry_once(file, report, env, extra_args) -> None: - """Stage 3's one retry of a FAILED script (see execute_scripts_in_folder).""" +def _retry_once(file, report, env, extra_args, started: float = 0.0) -> None: + """Stage 3's one retry of a FAILED script (see execute_scripts_in_folder). + The failed attempt's output is removed first, so the retry runs from + scratch and cannot resume a search the first attempt finished.""" from result_collector import Status first = report.results[-1] if report.results else None if first is None or first.file != str(file) or first.status != Status.FAILED: return - print(" failed; retrying once (Stage 3)...") + removed = clean_output_written_since(started) + print(f" failed; removed {removed} output file(s) it wrote; retrying once (Stage 3)...") report.results.pop() execute_script(str(file), report=report, env=env, extra_args=extra_args) second = report.results[-1] diff --git a/autohands/result_collector.py b/autohands/result_collector.py index 3518abd8..75cf7516 100644 --- a/autohands/result_collector.py +++ b/autohands/result_collector.py @@ -74,6 +74,10 @@ class ScriptResult: # Set when the entry was skipped by Heart's expiring Stage 3 quarantine: # the bug-task ref the quarantine entry names. quarantined: Optional[str] = None + # The quarantine entry that skipped it ({"workspace", "script", "bug", + # "expires"}), so Heart can tell whether that entry is still active when + # it reads a rehearsal that never ran the script. + quarantine_entry: Optional[dict] = None @property def was_timed(self) -> bool: @@ -135,6 +139,8 @@ def to_dict(self): d["first_error"] = self.first_error if self.quarantined is not None: d["quarantined"] = self.quarantined + if self.quarantine_entry is not None: + d["quarantine_entry"] = dict(self.quarantine_entry) return d diff --git a/autohands/run_python.py b/autohands/run_python.py index 7e0f5210..ef13c067 100644 --- a/autohands/run_python.py +++ b/autohands/run_python.py @@ -139,7 +139,9 @@ # running the quarantined script instead would be safe, but silently # ignoring the flag would hide that the policy never arrived. with open(args.quarantine) as fh: - quarantine = json.load(fh).get("entries", []) + q_doc = json.load(fh) + quarantine = [{**e, "workspace": e.get("workspace") or q_doc.get("workspace")} + for e in q_doc.get("entries", []) if isinstance(e, dict)] build_util.execute_scripts_in_folder( no_run_list=no_run_list, diff --git a/tests/test_stage3_retry_quarantine.py b/tests/test_stage3_retry_quarantine.py index a8d16a46..70831898 100644 --- a/tests/test_stage3_retry_quarantine.py +++ b/tests/test_stage3_retry_quarantine.py @@ -100,3 +100,52 @@ def test_aggregate_carries_flaky_and_quarantined(workspace, tmp_path, monkeypatc assert [e["quarantined"] for e in agg["quarantined"]] == ["PyAutoDemo#7"] md = aggregate_results.generate_markdown(agg) assert "Flaky" in md and "Quarantined" in md + + +# --- review fixes ------------------------------------------------------------- + +# Writes a "finished search" into output/ and then fails; on a later run it +# would RESUME from that output and pass without searching again. +RESUMES = """ +from pathlib import Path +done = Path("output/build/demo/search_finished") +if done.exists(): + raise SystemExit(0) # resumed from the finished output: a false pass +done.parent.mkdir(parents=True, exist_ok=True) +done.write_text("samples") +raise RuntimeError("failed after the search completed") +""" + + +def test_retry_cleans_the_failed_attempts_output_so_it_cannot_resume(workspace): + (workspace / "scripts" / "resumes.py").write_text(RESUMES) + keep = workspace / "output" / "build" / "earlier" / "result.json" + keep.parent.mkdir(parents=True) + keep.write_text("from an earlier script") + import os + os.utime(keep, (1, 1)) # written long before this run + results, _ = _run(retry_failed=True) + r = results["resumes.py"] + assert r.status == Status.FAILED and r.attempts == 2 and r.flaky is False + assert keep.exists() # other scripts' output is untouched + + +def test_quarantine_matches_the_exact_workspace_relative_path(workspace): + sub = workspace / "scripts" / "multi_imaging" + sub.mkdir() + (sub / "broken.py").write_text(BROKEN) + (workspace / "scripts" / "imaging").mkdir() + (workspace / "scripts" / "imaging" / "broken.py").write_text(BROKEN) + q = [{"script": "scripts/imaging/broken.py", "bug": "PyAutoDemo#7", + "expires": "2026-11-19", "workspace": "demo_workspace"}] + report = RunReport(project="demo", directory="scripts", run_type="script") + execute_scripts_in_folder(directory="scripts", report=report, quarantine=q) + by_rel = {str(Path(r.file).relative_to(workspace)): r for r in report.results} + skipped = by_rel["scripts/imaging/broken.py"] + assert skipped.status == Status.SKIPPED + assert skipped.to_dict()["quarantine_entry"] == { + "workspace": "demo_workspace", "script": "scripts/imaging/broken.py", + "bug": "PyAutoDemo#7", "expires": "2026-11-19"} + # Neither the substring-sharing sibling nor the same-named top-level script. + assert by_rel["scripts/multi_imaging/broken.py"].status == Status.FAILED + assert by_rel["scripts/broken.py"].status == Status.FAILED From e5e8e521a4eadbb806b2a1c2a9756e5032d576e8 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 13:17:19 +0000 Subject: [PATCH 3/3] fix(runner): retry clean removes only paths the failed attempt created (PyAutoHeart#344 review) The mtime-based clean deleted any output file touched during the failed attempt. A script resuming an earlier script's search restores that zip with fresh mtimes and rewrites it, so the clean deleted the earlier script's output and later scripts re-ran or failed: a false red. Now the runner snapshots the paths under output/ before each attempt (only when the retry is on), and before the retry deletes only paths that were not in that snapshot. The attempt's own new search output still goes; the earlier zip survives even though it was rewritten. Co-Authored-By: Claude Opus 5.5 --- autohands/build_util.py | 50 +++++++++++++++++---------- tests/test_stage3_retry_quarantine.py | 38 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 19 deletions(-) diff --git a/autohands/build_util.py b/autohands/build_util.py index 29d97a1d..dfbe3fce 100644 --- a/autohands/build_util.py +++ b/autohands/build_util.py @@ -1595,10 +1595,10 @@ def execute_scripts_in_folder(directory, no_run_list=None, report=None, skip_rea from env_config import build_env_for_script, args_for_script env = build_env_for_script(file, env_config) extra_args = args_for_script(file, env_config) - started = time.time() + before = output_snapshot() if retry_failed and report is not None else None execute_script(str(file), report=report, env=env, extra_args=extra_args) - if retry_failed and report is not None: - _retry_once(file, report, env, extra_args, started) + if before is not None: + _retry_once(file, report, env, extra_args, before) def _quarantine_match(file, quarantine): @@ -1621,25 +1621,37 @@ def _quarantine_match(file, quarantine): OUTPUT_DIRNAME = "output" -def clean_output_written_since(started: float, root=None) -> int: - """Delete every file under ``/output`` written or modified at or after - ``started`` (the failed attempt's start), and the directories it leaves - empty. Returns the number of files removed. - - That is exactly what the failed attempt produced: a model-fit search that - completed before the script failed leaves its finished samples there, and - a retry would RESUME from them and pass without re-running the search. - Output written by earlier scripts (older mtimes) is left alone.""" +def output_snapshot(root=None) -> frozenset: + """Every path under ``/output`` that exists now — taken before an + attempt, so the retry's clean can tell the attempt's own output apart.""" + out = Path(root or Path.cwd()) / OUTPUT_DIRNAME + return frozenset(out.rglob("*")) if out.is_dir() else frozenset() + + +def clean_output_new_since(before, root=None) -> int: + """Delete every path under ``/output`` that was NOT in ``before`` (the + snapshot taken before the failed attempt). Returns the number of files + removed. + + New paths are exactly the failed attempt's own output: a model-fit search + that completed before the script failed leaves its finished samples there, + and a retry would RESUME from them and pass without re-running the search. + A path that already existed is kept even if the attempt rewrote it — a + script resuming an earlier script's search restores that search's zip + with fresh mtimes and rewrites the zip, and deleting it would make later + scripts re-run or fail: a false red. (What the attempt unzipped from it is + new, so it goes; the zip it came from stays.)""" out = Path(root or Path.cwd()) / OUTPUT_DIRNAME if not out.is_dir(): return 0 removed = 0 for f in sorted(out.rglob("*"), key=lambda p: len(p.parts), reverse=True): + if f in before: + continue try: - if f.is_file() or f.is_symlink(): - if f.lstat().st_mtime >= started: - f.unlink() - removed += 1 + if f.is_symlink() or f.is_file(): + f.unlink() + removed += 1 elif f.is_dir() and not any(f.iterdir()): f.rmdir() except OSError: @@ -1647,7 +1659,7 @@ def clean_output_written_since(started: float, root=None) -> int: return removed -def _retry_once(file, report, env, extra_args, started: float = 0.0) -> None: +def _retry_once(file, report, env, extra_args, before: frozenset = frozenset()) -> None: """Stage 3's one retry of a FAILED script (see execute_scripts_in_folder). The failed attempt's output is removed first, so the retry runs from scratch and cannot resume a search the first attempt finished.""" @@ -1655,8 +1667,8 @@ def _retry_once(file, report, env, extra_args, started: float = 0.0) -> None: first = report.results[-1] if report.results else None if first is None or first.file != str(file) or first.status != Status.FAILED: return - removed = clean_output_written_since(started) - print(f" failed; removed {removed} output file(s) it wrote; retrying once (Stage 3)...") + removed = clean_output_new_since(before) + print(f" failed; removed {removed} new output file(s) it wrote; retrying once (Stage 3)...") report.results.pop() execute_script(str(file), report=report, env=env, extra_args=extra_args) second = report.results[-1] diff --git a/tests/test_stage3_retry_quarantine.py b/tests/test_stage3_retry_quarantine.py index 70831898..cdb87b9b 100644 --- a/tests/test_stage3_retry_quarantine.py +++ b/tests/test_stage3_retry_quarantine.py @@ -149,3 +149,41 @@ def test_quarantine_matches_the_exact_workspace_relative_path(workspace): # Neither the substring-sharing sibling nor the same-named top-level script. assert by_rel["scripts/multi_imaging/broken.py"].status == Status.FAILED assert by_rel["scripts/broken.py"].status == Status.FAILED + + +# Resumes an EARLIER script's search (its zip pre-exists): restores it (fresh +# mtimes on the unzipped files), rewrites the zip, writes its own new search +# output, then fails. +RESUMES_EARLIER = """ +import zipfile +from pathlib import Path +z = Path("output/build/earlier/search.zip") +with zipfile.ZipFile(z) as zf: + zf.extractall(z.with_suffix("")) +with zipfile.ZipFile(z, "w") as zf: + zf.writestr("samples.csv", "rewritten") +own = Path("output/build/failing/search/samples.csv") +own.parent.mkdir(parents=True, exist_ok=True) +own.write_text("own new search") +raise RuntimeError("failed after its own search") +""" + + +def test_retry_clean_keeps_an_earlier_scripts_rewritten_zip(workspace): + import os + import zipfile + from build_util import clean_output_new_since, output_snapshot + z = workspace / "output" / "build" / "earlier" / "search.zip" + z.parent.mkdir(parents=True) + with zipfile.ZipFile(z, "w") as zf: + zf.writestr("samples.csv", "earlier search") + os.utime(z, (1, 1)) + before = output_snapshot() + (workspace / "scripts" / "resumes_earlier.py").write_text(RESUMES_EARLIER) + import subprocess + subprocess.run([sys.executable, "scripts/resumes_earlier.py"], cwd=workspace) + assert z.stat().st_mtime > 1 # rewritten by the attempt + assert clean_output_new_since(before) >= 2 + assert z.exists() # the earlier output survives + assert not (workspace / "output" / "build" / "earlier" / "search").exists() + assert not (workspace / "output" / "build" / "failing").exists()