Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions autohands/aggregate_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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],
}
Expand Down Expand Up @@ -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:
Expand Down
113 changes: 112 additions & 1 deletion autohands/build_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

Expand All @@ -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)
Expand All @@ -1532,6 +1548,20 @@ 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 = _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:
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")),
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
# OTHER runs (the release mega-run, notebook generation), not this one.
if not files_are_allowlist and should_skip(file, no_run_list):
Expand Down Expand Up @@ -1565,4 +1595,85 @@ 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)
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 before is not None:
_retry_once(file, report, env, extra_args, before)


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
#: ``<cwd>/output``; the runner's cwd is the workspace root).
OUTPUT_DIRNAME = "output"


def output_snapshot(root=None) -> frozenset:
"""Every path under ``<root>/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 ``<root>/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_symlink() or f.is_file():
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, 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."""
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
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]
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]
33 changes: 33 additions & 0 deletions autohands/result_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ 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
# 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:
Expand Down Expand Up @@ -116,6 +129,18 @@ 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
if self.quarantine_entry is not None:
d["quarantine_entry"] = dict(self.quarantine_entry)
return d


Expand Down Expand Up @@ -201,6 +226,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")
Expand Down
32 changes: 32 additions & 0 deletions autohands/run_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -113,13 +132,26 @@
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:
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,
directory=directory,
report=report,
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:
Expand Down
Loading
Loading