From d6f0766f22f261d6020de88535488918a66dacd1 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 12:34:10 +0000 Subject: [PATCH 1/3] feat(readiness): repos Heart does not poll are gate-deferred, not STALE (#343) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Human ruling, M2 gate 2026-11-13: profiling, inference, assistants, visualization, Scientist, Broca and Cortex are not Heart-gated; their PR checks decide. - config/repos.yaml: `not_heart_gated:` (16 names resolved from the body map); every name must be unpolled and in `excluded:` (loader refuses otherwise). pyautolabs.github.io stays out: no CI. - `readiness --dev`: a touched repo on the list is gate-deferred — listed in `gate_deferred`, shown as "not Heart-gated: PR checks decide", never STALE or blocking. An all-deferred scope does not judge the snapshot age. - Witness test: a branch touching a not-Heart-gated repo reads GREEN, gate-deferred and shown, when the in-scope polled repos are green. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 ++- REFERENCE.md | 6 +++- config/repos.yaml | 30 ++++++++++++++++++ heart/readiness.py | 69 +++++++++++++++++++++++++++++++++++------ tests/test_dev_ship.py | 51 ++++++++++++++++++++++++++++++ tests/test_readiness.py | 25 +++++++++++++++ 6 files changed, 174 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5e04c663..2a604748 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,9 @@ yellow/red (`heart/readiness.py` docstring is the canonical definition). Releases still require GREEN. A development ship asks the scoped gate, `pyauto-heart readiness --dev --repos A,B --json`: only CI on `main` of the touched repos and their dependants blocks, every other reason is shown, a -feed older than 6 h is STALE, and STALE never passes (PyAutoHeart#340). It +feed older than 6 h is STALE, and STALE never passes (PyAutoHeart#340); a +touched repo on `not_heart_gated:` is gate-deferred, its PR checks decide +(PyAutoHeart#343). It judges the dev box's local `~/.pyauto-heart/state.json`; the event triggers refresh the published cloud feed, not that file. diff --git a/REFERENCE.md b/REFERENCE.md index 1f0891c5..c531ec97 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -128,7 +128,11 @@ it: only CI on `main` of the touched repos and of their dependants (the carried in `shown_reasons`. In-scope `main` CI is read for a repo of any group (organs and developer workspaces included); a run with no conclusion yet is STALE. A touched repo Heart does not poll is STALE ("not polled by -Heart"); a name `config/repos.yaml` never mentions is a usage error. Evidence +Heart") — unless it is on `config/repos.yaml`'s `not_heart_gated:` list +(PyAutoHeart#343, ruling 2026-11-13): then it is *gate-deferred*, listed in +`gate_deferred`, shown as "not Heart-gated: PR checks decide", and never STALE +or blocking; the merge paths require at least one completed PR check, all +green. A name `config/repos.yaml` never mentions is a usage error. Evidence older than 6 h (`--max-feed-age-hours`, positive, at most 6), of unknown age, or dated more than 5 min ahead, is STALE; each CI sidecar is aged by its own `ts`, the snapshot by its aggregation `ts`. Only GREEN passes diff --git a/config/repos.yaml b/config/repos.yaml index a1ef0e12..0adf9912 100644 --- a/config/repos.yaml +++ b/config/repos.yaml @@ -284,6 +284,36 @@ excluded: - z_vault # archived material - scripts # utility scripts (not a checkout) +# Not Heart-gated (human ruling, M2 gate 2026-11-13, PyAutoHeart#343). Repos +# Heart does not poll whose PR checks are the gate: a development ship touching +# one reads gate-deferred — not STALE, not blocking, shown as "not Heart-gated: +# PR checks decide" — and the merge paths (the /prm judgement and the batch +# watcher's close-out) require at least one completed check on the PR head, +# all of them green. A repo with no CI therefore stays a human merge. Every +# name here must also be in `excluded:` (a polled repo is judged by its main +# CI, never deferred). Categories ruled: profiling, inference, assistants, +# visualization, Scientist, Broca, Cortex — resolved to names from the body +# map (PyAutoMind/repos.yaml). Deliberately NOT here: pyautolabs.github.io +# (no CI), PyAutoDNA, PyAutoGut, PyAutoReduce, ECLIPSE_lens_catalogue, +# autoreduce_workspace — those still read STALE ("not polled by Heart"). +not_heart_gated: + - autolens_profiling + - autofit_profiling + - autolens_inference + - autofit_inference + - autocti_assistant + - autofit_assistant + - autogalaxy_assistant + - autolens_assistant + - euclid_assistant + - autolens_visualization + - autogalaxy_visualization + - autofit_visualization + - autocti_visualization + - PyAutoScientist + - PyAutoBroca + - PyAutoCortex + # Regenerated artifacts that perpetually show as dirty in `git status`. # A porcelain path matching any of these globs (or any untracked directory) # is counted as "generated noise" — informational, NOT actionable — and is diff --git a/heart/readiness.py b/heart/readiness.py index dad5bd2d..6a5d4be1 100644 --- a/heart/readiness.py +++ b/heart/readiness.py @@ -84,6 +84,14 @@ release-gated ones; a run with no conclusion yet is STALE. A touched repo Heart does not poll is STALE ("not polled by Heart"); a name the policy file never mentions is a usage error. +- *Not Heart-gated* (human ruling 2026-11-13, PyAutoHeart#343). A touched + repo on ``config/repos.yaml``'s ``not_heart_gated`` list (unpolled repos + whose PR checks are the gate: profiling, inference, assistants, + visualization, Scientist, Broca, Cortex) is *gate-deferred*: not STALE, not + blocking, listed in ``gate_deferred`` and shown as "not Heart-gated: PR + checks decide". The merge paths enforce the rest — at least one completed + check on the PR head, all green. When every touched repo is deferred, Heart + holds no evidence the verdict uses, so the snapshot's age is not judged. - *Feed age.* Evidence older than ``DEV_MAX_FEED_AGE_HOURS`` (6 h, also the ceiling a caller may set), of unknown age, or dated more than 5 min in the future, is STALE: re-check, or park. Each in-scope CI sidecar is aged by its @@ -889,6 +897,9 @@ def load_verdict() -> dict[str, Any]: #: ``main`` of one named repo (``repository_reasons[].key``). DEV_ENFORCED_KEYS = frozenset({"lib_ci", "ws_ci", "lib_ci_unavailable", "lib_unknown"}) +#: The shown reason for a gate-deferred repo (PyAutoHeart#343). +GATE_DEFERRED_REASON = "not Heart-gated: PR checks decide" + def load_dependencies(config_path: Path | str = CONFIG_PATH) -> dict[str, list[str]]: """``dependencies:`` from the policy file — library -> libraries it imports. @@ -938,6 +949,25 @@ def load_known_repo_names(config_path: Path | str = CONFIG_PATH) -> list[str]: return sorted(names) +def load_not_heart_gated(config_path: Path | str = CONFIG_PATH) -> list[str]: + """``not_heart_gated:`` — unpolled repos whose PR checks are the gate + (PyAutoHeart#343). Strict: a name that Heart polls cannot also be deferred + (its main CI is the evidence), and every name must be in ``excluded:`` — + a misfiled name raises rather than silently ungating a polled repo.""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + raw = cfg.get("not_heart_gated") or [] + if not isinstance(raw, list): + raise ValueError(f"not_heart_gated must be a list in {config_path}") + names = [str(x) for x in raw] + polled = set(load_repo_groups(config_path)) + excluded = {str(x) for x in cfg.get("excluded") or [] if isinstance(x, str)} + bad = [n for n in names if n in polled or n not in excluded] + if bad: + raise ValueError("not_heart_gated names must be unpolled repos listed in " + f"excluded: {', '.join(bad)} ({config_path})") + return names + + def load_release_scope_workflows(config_path: Path | str = CONFIG_PATH) -> frozenset[str]: """``dev_ship.release_scope_workflows`` — workflow names that never count as a repo's own ``main`` CI at a development ship. Absent ⇒ none (every @@ -978,6 +1008,7 @@ def dev_scope( dependencies: dict[str, list[str]], known: Sequence[str] = (), universe: Sequence[str] | None = None, + not_gated: Sequence[str] = (), ) -> dict[str, list[str]]: """The repos a development ship answers for. @@ -987,8 +1018,10 @@ def dev_scope( it is listed under ``not_polled`` — Heart holds no evidence about it, so ``dev_ship`` reads it STALE, never green. With ``universe`` (every name the policy file mentions), a name outside it raises ``ValueError``: a typo is a - usage error, not a repo.""" - pool = (*(universe or ()), *known, *dependencies, + usage error, not a repo. A touched repo in ``not_gated`` (and not polled) + is ``gate_deferred``: Heart does not judge it, its PR checks do, so it is + neither ``not_polled`` nor ``enforced``.""" + pool = (*(universe or ()), *known, *not_gated, *dependencies, *(u for ups in dependencies.values() for u in ups)) canon = {n.lower(): n for n in pool} touched: list[str] = [] @@ -1003,13 +1036,17 @@ def dev_scope( unknown = [t for t in touched if t.lower() not in {n.lower() for n in pool}] if unknown: raise ValueError("not a repo named in config/repos.yaml: " + ", ".join(unknown)) - dependants = sorted(dependants_of(touched, dependencies) - set(touched)) known_l = {n.lower() for n in known} + deferred_l = {n.lower() for n in not_gated} - known_l + deferred = [t for t in touched if t.lower() in deferred_l] + judged = [t for t in touched if t not in deferred] + dependants = sorted(dependants_of(judged, dependencies) - set(touched)) return { "touched": touched, "dependants": dependants, - "enforced": [*touched, *dependants], - "not_polled": [t for t in touched if known and t.lower() not in known_l], + "enforced": [*judged, *dependants], + "not_polled": [t for t in judged if known and t.lower() not in known_l], + "gate_deferred": deferred, } @@ -1172,6 +1209,7 @@ def dev_ship( universe: Sequence[str] | None = None, release_scope: Sequence[str] | None = None, ci_workflows: dict[str, list[str]] | None = None, + not_gated: Sequence[str] | None = None, source: str | None = None, ) -> dict[str, Any]: """The development-ship verdict for a branch touching ``repos``. @@ -1180,7 +1218,9 @@ def dev_ship( pass; RED is red CI on ``main`` in scope; STALE is in-scope CI evidence missing, unfinished or aged, a touched repo Heart does not poll, or a snapshot older than ``max_age_hours`` (or of unknown age) — re-check, or - park. An in-scope RED outranks staleness: the last known result was + park. A touched repo on the ``not_heart_gated`` list is gate-deferred: + listed and shown, never STALE or blocking (PyAutoHeart#343); its PR + checks decide at merge. An in-scope RED outranks staleness: the last known result was adverse, exactly as the release tiers treat it. Raises ``ValueError`` for a name the policy file never mentions or an invalid maximum age.""" snapshot = snapshot or {} @@ -1194,8 +1234,13 @@ def dev_ship( groups = groups if groups is not None else load_repo_groups() if universe is None and groups_given is None: universe = load_known_repo_names() # live policy: a typo is a usage error - scope = dev_scope(repos, deps, known=list(groups), universe=universe) + ng = (list(not_gated) if not_gated is not None + else load_not_heart_gated() if groups_given is None else []) + scope = dev_scope(repos, deps, known=list(groups), universe=universe, not_gated=ng) red, stale, shown = split_dev_reasons(full, scope["enforced"]) + for name in scope["gate_deferred"]: + shown.append({"severity": "deferred", + "text": f"{name}: {GATE_DEFERRED_REASON}"}) if not scope["touched"]: stale.append("no touched repos stated — the dev-ship scope is unknown") @@ -1213,10 +1258,13 @@ def dev_ship( shown += ci_shown age = feed_age_hours(snapshot.get("ts"), now) - if age is None: + # Every touched repo deferred: no Heart evidence enters the verdict, so the + # snapshot's age cannot make it stale (its age is still reported). + heart_judged = bool(scope["enforced"]) or not scope["touched"] + if heart_judged and age is None: stale.append("Heart snapshot age unknown (no ts, or dated in the future) " "— re-check, or park") - elif age > max_age_hours: + elif heart_judged and age > max_age_hours: stale.append(f"Heart snapshot {age:.1f} h old, over the {max_age_hours:g} h " "maximum — re-check, or park") @@ -1229,6 +1277,7 @@ def dev_ship( "stale": "re-check (refresh the evidence, then ask again), or park", "green": ""}[verdict], "scope": scope, + "gate_deferred": list(scope["gate_deferred"]), "red_reasons": red, "yellow_reasons": [], "stale_reasons": stale, @@ -1252,6 +1301,8 @@ def render_dev(verdict: dict[str, Any]) -> list[str]: head = ", ".join(scope.get("touched") or []) or "?" if scope.get("dependants"): head += f" (+ dependants {', '.join(scope['dependants'])})" + if scope.get("gate_deferred"): + head += f" (gate-deferred {', '.join(scope['gate_deferred'])})" age = verdict.get("feed_age_hours") lines = [c_bold(f"DEV SHIP {head}"), f" {glyph()} {colour(v.upper())} " diff --git a/tests/test_dev_ship.py b/tests/test_dev_ship.py index 2b059d9c..26a550b0 100644 --- a/tests/test_dev_ship.py +++ b/tests/test_dev_ship.py @@ -514,3 +514,54 @@ def test_release_scope_workflows_in_an_organ_never_count_as_its_own_ci(): for e in ci["workflows"].values(): e["on_head"] = False assert dev(snap, [ORGAN], release_scope=["Release Integrate"])["verdict"] == "green" + + +# --- not Heart-gated: gate-deferred (PyAutoHeart#343, ruling 2026-11-13) ----- + +DEFERRED = "bench_profiling" # an unpolled repo whose PR checks are the gate +UNIVERSE_NG = [*UNIVERSE, DEFERRED] + + +def test_witness_343_not_heart_gated_repo_reads_green_gate_deferred_and_shown(): + """Witness: a branch touching a not-Heart-gated repo reads GREEN, + gate-deferred and shown, when the in-scope polled repos are green.""" + v = dev(snapshot(), [DEFERRED, MID], universe=UNIVERSE_NG, not_gated=[DEFERRED]) + assert v["verdict"] == "green" and v["pass"] is True + assert v["gate_deferred"] == [DEFERRED] + assert v["scope"]["gate_deferred"] == [DEFERRED] + assert v["scope"]["not_polled"] == [] + assert DEFERRED not in v["scope"]["enforced"] + assert v["stale_reasons"] == [] and v["red_reasons"] == [] + assert {"severity": "deferred", + "text": f"{DEFERRED}: not Heart-gated: PR checks decide"} in v["shown_reasons"] + text = "\n".join(readiness.render_dev(v)) + assert f"gate-deferred {DEFERRED}" in text and "PR checks decide" in text + + +def test_gate_deferred_never_hides_an_in_scope_red_or_stale(): + v = dev(snapshot(**{MID: _lib("failure")}), [DEFERRED, MID], + universe=UNIVERSE_NG, not_gated=[DEFERRED]) + assert v["verdict"] == "red" and v["gate_deferred"] == [DEFERRED] + v = dev(snapshot(), [DEFERRED, "UnpolledLib"], universe=UNIVERSE_NG, not_gated=[DEFERRED]) + assert v["verdict"] == "stale" + assert "not polled by Heart: UnpolledLib" in v["stale_reasons"] + + +def test_without_the_list_an_unpolled_repo_still_reads_stale(): + v = dev(snapshot(), [DEFERRED], universe=UNIVERSE_NG) + assert v["verdict"] == "stale" and v["gate_deferred"] == [] + assert f"not polled by Heart: {DEFERRED}" in v["stale_reasons"] + + +def test_a_polled_repo_on_the_list_is_still_judged_by_its_main_ci(): + v = dev(snapshot(**{MID: _lib("failure")}), [MID], not_gated=[MID]) + assert v["verdict"] == "red" and v["gate_deferred"] == [] + + +def test_an_all_deferred_scope_does_not_judge_the_snapshot_age(): + old = dict(snapshot(), ts="2026-11-01T00:00:00+00:00") + v = dev(old, [DEFERRED], universe=UNIVERSE_NG, not_gated=[DEFERRED]) + assert v["verdict"] == "green" and v["feed_age_hours"] > 6 + # One Heart-judged repo in scope brings the age back into the verdict. + assert dev(old, [DEFERRED, MID], universe=UNIVERSE_NG, + not_gated=[DEFERRED])["verdict"] == "stale" diff --git a/tests/test_readiness.py b/tests/test_readiness.py index 60ab7af0..d2e6f96f 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -1327,3 +1327,28 @@ def test_live_every_polled_advisory_repo_declares_its_ci_workflows(): assert advisory == set(ciw) rs = readiness.load_release_scope_workflows() assert not any(set(w) & rs for w in ciw.values()) + + +def test_live_not_heart_gated_names_are_unpolled_excluded_repos(): + """PyAutoHeart#343: the ruled categories resolved to names; every one is + unpolled and in `excluded:`, and the list is a strict subset of it (a + repo with no CI stays out — the merge guard would park it anyway).""" + import yaml + excluded = set(yaml.safe_load(readiness.CONFIG_PATH.read_text())["excluded"]) + ng = readiness.load_not_heart_gated() + assert len(ng) >= 7 and set(ng) < excluded + assert not set(ng) & set(readiness.load_repo_groups()) + v = readiness.dev_ship(make_snapshot(), [ng[0]]) + assert v["gate_deferred"] == [ng[0]] + assert not any("not polled" in r for r in v["stale_reasons"]) + + +def test_not_heart_gated_refuses_a_polled_or_unexcluded_name(tmp_path): + cfg = tmp_path / "repos.yaml" + cfg.write_text("repos:\n libraries:\n - {name: LibA, owner: o}\n" + "excluded: [Bench]\nnot_heart_gated: [LibA]\n") + with pytest.raises(ValueError, match="LibA"): + readiness.load_not_heart_gated(cfg) + cfg.write_text("repos: {}\nexcluded: [Bench]\nnot_heart_gated: [Other]\n") + with pytest.raises(ValueError, match="Other"): + readiness.load_not_heart_gated(cfg) From c704320b06163ac76c56c67a9225c13a56b2b5b3 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 12:43:48 +0000 Subject: [PATCH 2/3] feat(stage3): one script retry + expiring quarantine, YELLOW while active (#344) Human ruling, M1 gate 2026-11-12. - config/stage3_quarantine.yaml (repo-tracked, schema in its header) and heart/quarantine.py, its one reader: an entry names workspace, script, a filed bug task (Repo#N / Owner/Repo#N / issue URL), filed date and an expiry at most 7 days later; at most 3 active (a fourth is refused); workspace scripts only. `check` exits 1 on a refused entry; `skip-list` gives Stage 3 the ACTIVE entries for one workspace. - readiness: an active entry is YELLOW with the list (`stage3_quarantine`); an expired or refused entry, or an unreadable file, is RED. Quarantine never turns RED into GREEN. A pass on the retry is carried as `stage3_flaky` (shown, not a tier). - validate: the stage report, fold and validation_report carry `flaky` and `quarantined`. - workspace-validation.yml (mode=release): resolve the quarantine per workspace and pass --retry-failed / --quarantine to the Hands runner (only when the runner has them, so merge order cannot break Stage 3). - Witness tests: retry pass recorded flaky; retry fail red; quarantined YELLOW; missing bug ref refused; expired entry red again; fourth entry refused. Tests read no live quarantine (conftest). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/workspace-validation.yml | 37 +++- config/stage3_quarantine.yaml | 28 +++ docs/release_validation.md | 22 ++ heart/quarantine.py | 226 +++++++++++++++++++++ heart/readiness.py | 36 +++- heart/validate.py | 23 +++ tests/conftest.py | 13 ++ tests/test_stage3_quarantine.py | 187 +++++++++++++++++ tests/test_workflow_wiring.py | 16 ++ 9 files changed, 584 insertions(+), 4 deletions(-) create mode 100644 config/stage3_quarantine.yaml create mode 100644 heart/quarantine.py create mode 100644 tests/test_stage3_quarantine.py diff --git a/.github/workflows/workspace-validation.yml b/.github/workflows/workspace-validation.yml index 2de6b495..6a5d2aac 100644 --- a/.github/workflows/workspace-validation.yml +++ b/.github/workflows/workspace-validation.yml @@ -395,6 +395,26 @@ jobs: python3 "$(pwd)/../PyAutoHands/autohands/run_python.py" \ "$SHARD_PROJECT" "$@" \ --report-dir test-results + - name: "Checkout PyAutoHeart (Stage 3 quarantine) [mode=release]" + if: needs.find_scripts.outputs.mode == 'release' + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoHeart + path: PyAutoHeart + - name: "Resolve the Stage 3 quarantine for this workspace [mode=release]" + # PyAutoHeart#344 (human ruling 2026-11-12): Heart owns the quarantine + # (config/stage3_quarantine.yaml) and its rules — filed bug task, at most + # 7 days, at most 3 active. Only the ACTIVE entries for this workspace + # reach the runner; an expired or refused entry is not skipped, so its + # script runs again. Readiness shows YELLOW while any entry is active. + if: needs.find_scripts.outputs.mode == 'release' + env: + WS_REPO: ${{ steps.ws.outputs.repo }} + run: | + python3 -m pip install -q "PyYAML>=6.0" + PYTHONPATH="$GITHUB_WORKSPACE/PyAutoHeart" python3 -m heart.quarantine skip-list \ + --workspace "$WS_REPO" --out "$GITHUB_WORKSPACE/stage3_quarantine.json" + cat "$GITHUB_WORKSPACE/stage3_quarantine.json" - name: "Run Python scripts [mode=release, wheels, release profile, no source on PYTHONPATH]" if: needs.find_scripts.outputs.mode == 'release' env: @@ -448,10 +468,23 @@ jobs: else set -- "scripts/$SHARD_DIRECTORY" fi - python3 "$(pwd)/../PyAutoHands/autohands/run_python.py" \ + # Stage 3's one retry and quarantine (PyAutoHeart#344): a FAILED + # script is re-run once and a pass on the retry is recorded as flaky; + # a quarantined script is skipped and recorded. Release mode only. + # Passed only to a PyAutoHands runner that has them (merge order): + # without them nothing is skipped or retried — the fail-closed side. + RUNNER="$(pwd)/../PyAutoHands/autohands/run_python.py" + stage3=() + if grep -q -- "--retry-failed" "$RUNNER"; then + stage3=(--retry-failed --quarantine "$GITHUB_WORKSPACE/stage3_quarantine.json") + else + echo "::warning::PyAutoHands runner has no Stage 3 retry/quarantine yet — neither applied" + fi + python3 "$RUNNER" \ "$SHARD_PROJECT" "$@" \ --report-dir test-results \ - --env-config "$ENV_CONFIG" + --env-config "$ENV_CONFIG" \ + "${stage3[@]}" - name: Upload script results # The name's leg suffix is the shard's directory, or `ordered` for an # ordered entry (script_matrix.py --ordered), whose directory is "." — diff --git a/config/stage3_quarantine.yaml b/config/stage3_quarantine.yaml new file mode 100644 index 00000000..129cd8b9 --- /dev/null +++ b/config/stage3_quarantine.yaml @@ -0,0 +1,28 @@ +# Stage 3 script quarantine (PyAutoHeart#344; human ruling, M1 gate 2026-11-12). +# +# A failing release-validation (Stage 3) workspace script may be set aside so +# one script does not hold the release RED — under this doctrine, enforced by +# heart/quarantine.py (the one reader): +# +# - an entry needs a FILED bug task (`bug`), or it is refused; +# - it expires at most 7 days after `filed`; an EXPIRED entry fails the gate +# again (readiness RED) and Stage 3 runs the script again — remove the +# entry once the bug is fixed; +# - at most 3 entries are active at once; a fourth is refused; +# - while any entry is active, readiness is YELLOW with the list — never +# GREEN: the script is skipped, the release decision stays the human's; +# - workspace scripts only: never unit tests or install checks. +# +# Schema of one entry (all required unless marked optional): +# +# - workspace: autolens_workspace_test # a polled Stage 3 workspace (config/repos.yaml) +# script: scripts/interferometer/model_fit.py # .py path inside that workspace +# bug: PyAutoLens#123 # filed bug task: Repo#N, Owner/Repo#N or issue URL +# filed: 2026-11-13 # YYYY-MM-DD +# expires: 2026-11-20 # YYYY-MM-DD, after filed, at most filed + 7 days +# owner: someone # optional — who is fixing it +# reason: one line # optional +# +# Check the file: `python3 -m heart.quarantine check` (exit 1 on a refused entry). + +entries: [] diff --git a/docs/release_validation.md b/docs/release_validation.md index bb6599a0..a92ef044 100644 --- a/docs/release_validation.md +++ b/docs/release_validation.md @@ -195,6 +195,28 @@ dispatching the `release-integrate.yml` channel), an ingested rehearsal-only report still (correctly) gates YELLOW: the source was built and TestPyPI-installed, but not yet exercised at release fidelity. `mode: release` is what supplies the `integrate` stage that flips this to GREEN-eligible. + +## One retry and the expiring quarantine (PyAutoHeart#344) + +Human ruling, M1 gate 2026-11-12. In Stage 3 (`mode: release` only): + +- **One retry.** A script that FAILS is re-run once (`run_python.py + --retry-failed`). A pass on the retry is recorded as **flaky** — `flaky`, + `attempts: 2` and the first error in the per-run JSON, the `flaky` list of + `report.json`, the stage report and `validation_report.json`, and + `stage3_flaky` in the readiness verdict — never hidden. A second failure + stays FAILED (RED). A TIMEOUT is not retried: it already spent its cap. +- **Quarantine.** `config/stage3_quarantine.yaml` (schema in its header; one + reader, `heart/quarantine.py`). An entry names the workspace, the script, a + filed bug task, the filed date and an expiry at most 7 days later; at most 3 + are active. Stage 3 resolves the ACTIVE entries per workspace + (`python -m heart.quarantine skip-list`) and the runner skips those scripts, + recorded as quarantined. Readiness is **YELLOW** while any entry is active, + with the list; an **expired** entry is RED and its script runs again; a + refused entry (no bug ref, over 7 days, a fourth active, not a workspace + script) is RED and not skipped. Quarantine never turns RED into GREEN, and + release approval is unchanged: the nightly still ships on GREEN only. + # Bounded investigation of a failed wheel run `release-diagnostic.yml` investigates the saved `rectangular_rtu.py` timeout diff --git a/heart/quarantine.py b/heart/quarantine.py new file mode 100644 index 00000000..3f61fe68 --- /dev/null +++ b/heart/quarantine.py @@ -0,0 +1,226 @@ +"""heart/quarantine.py — the expiring Stage 3 script quarantine (PyAutoHeart#344). + +Human ruling, M1 gate 2026-11-12: a failing Stage 3 (release-validation) +workspace script may be set aside, so one script does not hold the release +RED, under this doctrine: + +- an entry needs a **filed bug task** (``bug``: an issue ref); +- it **expires** at most 7 days after it was filed; +- at most **3** entries are active at once; +- while any entry is active, readiness shows **YELLOW** with the list; +- an **expired** entry fails the gate again (RED), and its script runs again; +- quarantine never turns RED into GREEN: the script is only skipped, and the + verdict it leaves is YELLOW at best. Release approval is unchanged. + +Workspace scripts only — never unit tests or install checks: ``workspace`` +must be a polled release-surface workspace and ``script`` a ``.py`` path +inside it. + +The file is ``config/stage3_quarantine.yaml`` (schema in its header). This +module is the one reader: ``classify`` sorts entries into active / expired / +refused, ``readiness`` turns that into YELLOW / RED reasons, and the +``skip-list`` CLI hands Stage 3 (``workspace-validation.yml``, mode=release) +the ACTIVE entries for one workspace, which PyAutoHands' runner skips and +records. Pure stdlib + PyYAML: Stage 3 runs it with nothing else installed. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import re +import sys +from pathlib import Path +from typing import Any + +import yaml + +HEART_HOME = Path(__file__).resolve().parents[1] +QUARANTINE_PATH = HEART_HOME / "config" / "stage3_quarantine.yaml" +REPOS_PATH = HEART_HOME / "config" / "repos.yaml" + +#: The ruling's numbers. +MAX_ACTIVE = 3 +MAX_DAYS = 7 + +#: Groups in ``config/repos.yaml`` whose scripts Stage 3 runs. +STAGE3_GROUPS = ("workspaces", "workspaces_test", "howto", "pipelines") + +#: A filed bug task: ``Repo#N``, ``Owner/Repo#N`` or a GitHub issue URL. +BUG_REF = re.compile( + r"^(?:[\w.-]+/)?[\w.-]+#\d+$|^https://github\.com/[\w.-]+/[\w.-]+/issues/\d+$") + + +def stage3_workspaces(repos_path: Path | str = REPOS_PATH) -> list[str]: + """The workspaces whose scripts Stage 3 runs (the only quarantinable ones).""" + cfg = yaml.safe_load(Path(repos_path).read_text()) or {} + groups = cfg.get("repos") or {} + return sorted(r["name"] for g in STAGE3_GROUPS for r in groups.get(g) or [] + if isinstance(r, dict) and r.get("name")) + + +def load(path: Path | str | None = None) -> list[Any]: + """The raw ``entries:`` list (default: ``QUARANTINE_PATH``). A missing file + is no quarantine; a file whose ``entries`` is not a list raises — a + malformed policy is never "empty".""" + p = Path(path if path is not None else QUARANTINE_PATH) + if not p.exists(): + return [] + cfg = yaml.safe_load(p.read_text()) or {} + entries = cfg.get("entries") + if entries is None: + return [] + if not isinstance(entries, list): + raise ValueError(f"{p}: entries must be a list") + return entries + + +def _date(v: Any) -> datetime.date | None: + if isinstance(v, datetime.datetime): + return v.date() + if isinstance(v, datetime.date): + return v + try: + return datetime.date.fromisoformat(str(v).strip()) + except ValueError: + return None + + +def _label(e: Any) -> str: + if not isinstance(e, dict): + return repr(e) + return f"{e.get('workspace', '?')}/{e.get('script', '?')}" + + +def _schema_error(e: Any, workspaces: set[str], today: datetime.date) -> str | None: + """Why an entry is refused on its own merits, or None.""" + if not isinstance(e, dict): + return "not a mapping" + bug = str(e.get("bug") or "").strip() + if not bug: + return "no bug-task ref (a quarantine needs a filed bug task)" + if not BUG_REF.match(bug): + return f"bug ref {bug!r} is not an issue ref (Repo#N, Owner/Repo#N or issue URL)" + ws = str(e.get("workspace") or "") + if ws not in workspaces: + return (f"workspace {ws!r} is not a Stage 3 workspace " + "(scripts only — never unit tests or install checks)") + script = str(e.get("script") or "") + if not script.endswith(".py") or script.startswith("/") or ".." in script.split("/") \ + or "/" not in script: + return f"script {script!r} is not a .py path inside the workspace" + filed, expires = _date(e.get("filed")), _date(e.get("expires")) + if filed is None: + return "no valid filed date (YYYY-MM-DD)" + if expires is None: + return "no valid expires date (YYYY-MM-DD)" + if filed > today: + return f"filed {filed.isoformat()} is in the future" + if expires <= filed: + return "expires is not after filed" + if (expires - filed).days > MAX_DAYS: + return f"expires {(expires - filed).days} days after filed (at most {MAX_DAYS})" + return None + + +def classify( + entries: list[Any], + today: datetime.date, + workspaces: list[str] | set[str] | None = None, +) -> dict[str, list[dict[str, Any]]]: + """Sort entries into ``active`` / ``expired`` / ``refused``. + + Each row is ``{"label", "entry", "why"}`` (``why`` on refused/expired). + Refused: a schema error (no bug ref, a non-workspace target, a window over + 7 days...), or a valid live entry beyond the first ``MAX_ACTIVE`` by + ``filed`` date (file order breaks ties) — the fourth entry is refused, the + three before it stand. Expired: ``today`` is after ``expires`` (an entry is + live through its expiry day). A refused or expired entry is never skipped + by Stage 3.""" + ws = set(workspaces) if workspaces is not None else set(stage3_workspaces()) + active: list[dict[str, Any]] = [] + expired: list[dict[str, Any]] = [] + refused: list[dict[str, Any]] = [] + live: list[tuple[datetime.date, int, dict[str, Any]]] = [] + for i, e in enumerate(entries): + why = _schema_error(e, ws, today) + if why: + refused.append({"label": _label(e), "entry": e, "why": why}) + continue + expires = _date(e["expires"]) + if today > expires: + expired.append({"label": _label(e), "entry": e, + "why": f"expired {expires.isoformat()}"}) + continue + live.append((_date(e["filed"]), i, e)) + for n, (_, _, e) in enumerate(sorted(live, key=lambda t: (t[0], t[1]))): + row = {"label": _label(e), "entry": e} + if n < MAX_ACTIVE: + active.append(row) + else: + refused.append({**row, "why": f"{MAX_ACTIVE} entries already active"}) + return {"active": active, "expired": expired, "refused": refused} + + +def readiness_reasons( + entries: list[Any], today: datetime.date, workspaces: list[str] | set[str] | None = None, +) -> tuple[list[str], list[str]]: + """``(red, yellow)`` reason sentences for the readiness verdict.""" + c = classify(entries, today, workspaces) + red = [f"Stage 3 quarantine EXPIRED: {r['label']} ({r['entry'].get('bug')}, " + f"{r['why']}) — the script gates again" for r in c["expired"]] + red += [f"Stage 3 quarantine entry refused: {r['label']} — {r['why']}" + for r in c["refused"]] + yellow = [f"Stage 3 quarantine active ({len(c['active'])}/{MAX_ACTIVE}): {r['label']} " + f"({r['entry'].get('bug')}, expires {_date(r['entry']['expires'])})" + for r in c["active"]] + return red, yellow + + +def skip_list(workspace: str, entries: list[Any], today: datetime.date, + workspaces: list[str] | set[str] | None = None) -> dict[str, Any]: + """The ACTIVE entries for one workspace, as PyAutoHands' runner reads them + (``run_python.py --quarantine``): ``script`` is the workspace-relative + path pattern, matched as a path substring.""" + c = classify(entries, today, workspaces) + return {"workspace": workspace, "date": today.isoformat(), "entries": [ + {"script": str(r["entry"]["script"]), "bug": str(r["entry"]["bug"]), + "expires": str(_date(r["entry"]["expires"]))} + for r in c["active"] if r["entry"].get("workspace") == workspace]} + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="python -m heart.quarantine") + sub = ap.add_subparsers(dest="cmd", required=True) + chk = sub.add_parser("check", help="validate the file; exit 1 on a refused entry") + chk.add_argument("--file", default=None) + sk = sub.add_parser("skip-list", help="the ACTIVE entries for one workspace, as JSON") + sk.add_argument("--workspace", required=True) + sk.add_argument("--file", default=None) + sk.add_argument("--out", default="-") + for p in (chk, sk): + p.add_argument("--date", default=None, help="judge as of YYYY-MM-DD (default today, UTC)") + ns = ap.parse_args(argv) + today = (datetime.date.fromisoformat(ns.date) if ns.date + else datetime.datetime.now(datetime.timezone.utc).date()) + entries = load(ns.file) + if ns.cmd == "check": + c = classify(entries, today) + for r in c["active"]: + print(f"active {r['label']} ({r['entry'].get('bug')})") + for r in c["expired"]: + print(f"EXPIRED {r['label']} — {r['why']} (gates RED until removed)") + for r in c["refused"]: + print(f"REFUSED {r['label']} — {r['why']}") + return 1 if c["refused"] else 0 + out = json.dumps(skip_list(ns.workspace, entries, today), indent=2) + if ns.out == "-": + print(out) + else: + Path(ns.out).write_text(out + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/readiness.py b/heart/readiness.py index 6a5d4be1..85ab01d1 100644 --- a/heart/readiness.py +++ b/heart/readiness.py @@ -22,7 +22,9 @@ gate fails closed on evidence it cannot classify. Also RED: the release push credential (``heart/checks/token_push.py``, the ``pyautolabs-bot`` App's ``git push --dry-run``) was refused by any library; a missing, partial or - older-than-48 h proof is STALE. + older-than-48 h proof is STALE. Also RED: an expired or refused Stage 3 + quarantine entry (``heart/quarantine.py``, PyAutoHeart#344); an ACTIVE one + is YELLOW with the list — a quarantined script is skipped, never green. - **YELLOW** (caution) for soft signals: workspace-validation not passing (the workspace scripts/notebooks carry standing debt, so this is advisory — never a hard block), script-timing regressions, stale open PRs, stale parked scripts, a @@ -130,6 +132,7 @@ import yaml +from heart import quarantine as _quarantine from heart import state, validate from heart.checks.ci_status import FAILURE_CONCLUSIONS, load_required_workflows from heart.checks.test_run import counts_measured as tr_counts_measured @@ -191,6 +194,9 @@ "token_push_refused": (40, 40), "token_push_unknown": (10, 10), "token_push_stale": (10, 10), + "quarantine_active": (5, 15), + "quarantine_expired": (40, 40), + "quarantine_refused": (40, 40), } @@ -284,8 +290,12 @@ def compute( libraries: Sequence[str] | None = None, required_workflows: dict[str, list[str]] | None = None, profile: str = "default", + quarantine: list[Any] | None = None, ) -> dict[str, Any]: - """Pure verdict function. Never raises on missing/partial data.""" + """Pure verdict function. Never raises on missing/partial data. + + ``quarantine`` is the Stage 3 quarantine's raw entries (default: the + repo-tracked ``config/stage3_quarantine.yaml``, PyAutoHeart#344).""" snapshot = snapshot or {} libs = list(libraries) if libraries is not None else load_release_gate_names() req_wf = required_workflows if required_workflows is not None else load_required_workflows() @@ -721,6 +731,26 @@ def scope_local(msg: str, key: str) -> None: else: add_stale("no release validation for current source", "validation_absent") + # --- Stage 3 quarantine (PyAutoHeart#344; ruling 2026-11-12) --- + # An ACTIVE entry is YELLOW with the list: its script was skipped, and a + # skipped script can never make the verdict GREEN. An EXPIRED or refused + # entry is RED — the script gates again. A file that cannot be read is RED + # too: an unreadable policy is never an empty one. + try: + q_entries = quarantine if quarantine is not None else _quarantine.load() + q_red, q_yellow = _quarantine.readiness_reasons(q_entries, ref.date()) + except (OSError, ValueError, yaml.YAMLError) as exc: + q_red, q_yellow = [f"Stage 3 quarantine file unreadable: {exc}"], [] + for t in q_red: + red.append(t) + hit("quarantine_expired" if "EXPIRED" in t else "quarantine_refused") + for t in q_yellow: + yellow.append(t) + hit("quarantine_active") + # A pass on Stage 3's one retry is recorded as flaky (shown, not a tier). + stage3_flaky = [f for f in ((vr or {}).get("flaky") or []) if isinstance(f, dict)] \ + if isinstance(vr, dict) else [] + # --- release push credential (RED on a refused push, STALE if unproven) --- # heart/checks/token_push.py: the pyautolabs-bot App's `git push --dry-run` # to each release library. A refusal means the release's tag push would @@ -838,6 +868,8 @@ def scope_local(msg: str, key: str) -> None: # flat lists above are the contract every existing consumer reads. "stale_details": [{"text": t, "key": k} for t, k in zip(stale, stale_keys)], "na_reasons": na, + "stage3_quarantine": q_yellow, + "stage3_flaky": stage3_flaky, "validation_ahead": validation_ahead, "validation_note": ( "release validation covers the rehearsed commits; main is ahead by " diff --git a/heart/validate.py b/heart/validate.py index c38bae85..fc02255a 100644 --- a/heart/validate.py +++ b/heart/validate.py @@ -234,6 +234,11 @@ def __init__(self) -> None: self.totals: dict[str, int] = {k: 0 for k in _COUNT_KEYS} self.per_project: dict[str, dict[str, int]] = {} self.failures: list[dict[str, Any]] = [] + # Stage 3's one retry and quarantine (PyAutoHeart#344): scripts that + # passed only on the retry, and scripts skipped by an active entry. + # Recorded, never a pass/fail input. + self.flaky: list[dict[str, Any]] = [] + self.quarantined: list[dict[str, Any]] = [] self.run_urls: dict[str, str] = {} # The verify_install sidecar a stage artifact carried, if any. Kept out # of validation_report.json (it is not part of that schema) — `run()` @@ -306,9 +311,16 @@ def add_stage(self, data: dict[str, Any]) -> None: for f in data.get("failures", []) or []: if isinstance(f, dict): self.failures.append(f) + self._add_stage3_notes(data) self.add_commit_shas(data.get("commit_shas")) self.add_verify_install(data.get("verify_install")) + def _add_stage3_notes(self, data: dict[str, Any]) -> None: + for key, target in (("flaky", self.flaky), ("quarantined", self.quarantined)): + for f in data.get(key) or []: + if isinstance(f, dict): + target.append(f) + def add_verify_install(self, sidecar: Any) -> None: """Keep the newest verify_install block seen across ingested artifacts. @@ -375,6 +387,7 @@ def add_report(self, data: dict[str, Any]) -> None: for f in data.get("failures", []) or []: if isinstance(f, dict): self.failures.append(f) + self._add_stage3_notes(data) for k, v in (data.get("run_urls") or {}).items(): self.run_urls.setdefault(str(k), str(v)) # --- the base's own verdict -------------------------------------- @@ -650,6 +663,8 @@ def _distill(acc: _Accumulator, now: datetime.datetime | None = None) -> dict[st "totals": acc.totals, "per_project": acc.per_project, "failures": acc.failures, + "flaky": acc.flaky, + "quarantined": acc.quarantined, "run_urls": acc.run_urls, "ts": _now_iso(now), } @@ -797,6 +812,14 @@ def to_stage_report( report["summary"] = summary report["per_project"] = per_project report["failures"] = failures + # Stage 3's retry and quarantine (PyAutoHeart#344), in the stage report's + # own vocabulary: a flaky pass keeps its first error; a quarantined skip + # keeps the bug ref of the entry that skipped it. + for key, extra in (("flaky", "first_error"), ("quarantined", "quarantined")): + rows = aggregate.get(key) + report[key] = [{"project": r.get("project"), "script": r.get("file"), + extra: r.get(extra)} + for r in (rows if isinstance(rows, list) else []) if isinstance(r, dict)] vi = normalize_verify_install(verify_install) if vi is not None: report["verify_install"] = vi diff --git a/tests/conftest.py b/tests/conftest.py index 7fc695ed..bc148c47 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,3 +14,16 @@ import tempfile os.environ["HEART_STATE_DIR"] = tempfile.mkdtemp(prefix="pyauto-heart-test-state-") + + +import pytest # noqa: E402 + + +@pytest.fixture(autouse=True) +def _no_live_stage3_quarantine(monkeypatch, tmp_path_factory): + """Readiness reads the repo-tracked Stage 3 quarantine by default. A real + entry filed on main must not turn every verdict test YELLOW, so the suite + reads an absent file unless a test passes entries (PyAutoHeart#344).""" + from heart import quarantine + monkeypatch.setattr(quarantine, "QUARANTINE_PATH", + tmp_path_factory.getbasetemp() / "no_stage3_quarantine.yaml") diff --git a/tests/test_stage3_quarantine.py b/tests/test_stage3_quarantine.py new file mode 100644 index 00000000..0e06f4da --- /dev/null +++ b/tests/test_stage3_quarantine.py @@ -0,0 +1,187 @@ +"""tests/test_stage3_quarantine.py — Stage 3 retry + expiring quarantine +(PyAutoHeart#344; human ruling, M1 gate 2026-11-12). + +A quarantine entry needs a filed bug task, expires at most 7 days after it was +filed, at most 3 are active, readiness is YELLOW while any is active, an +expired entry is RED again, and quarantine never turns a RED into GREEN. A pass +on Stage 3's one retry is recorded as flaky; a retry that fails stays red. + +Workspace names here are drawn from the live config (the tenant firewall keeps +instance facts out of test files); the snapshot comes from test_readiness. +""" + +from __future__ import annotations + +import datetime +import json + +import pytest + +from heart import quarantine, readiness, validate +from tests.test_readiness import LIBS, make_snapshot + +TODAY = datetime.date(2026, 6, 1) # make_snapshot()'s ts date +WS = quarantine.stage3_workspaces()[0] + + +def entry(n=1, filed="2026-05-30", expires="2026-06-05", bug="DemoLib#12", **kw): + e = {"workspace": WS, "script": f"scripts/demo/s{n}.py", "bug": bug, + "filed": filed, "expires": expires} + e.update(kw) + return e + + +def compute(snap=None, entries=()): + return readiness.compute(snap or make_snapshot(), libraries=LIBS, quarantine=list(entries)) + + +# --- the Witness ------------------------------------------------------------ + +def test_witness_344_retry_pass_recorded_as_flaky(): + """A Stage 3 report whose script passed on the retry: the validation + report records it as flaky (with the first error), the stage still passes, + and readiness carries it in `stage3_flaky` without changing the tier.""" + agg = {"ready": True, "summary": {"passed": 3}, + "per_project": {WS: {"passed": 3}}, "failures": [], + "flaky": [{"project": WS, "file": "scripts/demo/s1.py", + "status": "passed", "flaky": True, "attempts": 2, + "first_error": "ConnectionError: transient"}]} + stage = validate.to_stage_report(agg, profile="release") + assert stage["status"] == "pass" + assert stage["flaky"] == [{"project": WS, "script": "scripts/demo/s1.py", + "first_error": "ConnectionError: transient"}] + acc = validate._Accumulator() + acc.add_stage(stage) + report = validate._distill(acc) + assert report["flaky"] == stage["flaky"] + snap = make_snapshot() + snap["validation_report"]["flaky"] = stage["flaky"] + v = compute(snap) + assert v["verdict"] == "green" and v["stage3_flaky"] == stage["flaky"] + + +def test_witness_344_retry_fail_recorded_red(): + """The retry failed too: the stage fails and readiness is RED.""" + agg = {"ready": False, "summary": {"passed": 2, "failed": 1}, + "per_project": {WS: {"passed": 2, "failed": 1}}, + "failures": [{"project": WS, "file": "scripts/demo/s1.py", + "status": "failed", "attempts": 2}]} + stage = validate.to_stage_report(agg, profile="release") + assert stage["status"] == "fail" and stage["flaky"] == [] + snap = make_snapshot(validation_report={**make_snapshot()["validation_report"], + "validation_outcome": "fail", + "release_ready": False}) + v = compute(snap) + assert v["verdict"] == "red" + assert any("release validation FAILED" in r for r in v["red_reasons"]) + + +def test_witness_344_quarantined_reads_yellow_never_green(): + v = compute(entries=[entry()]) + assert v["verdict"] == "yellow" + assert v["red_reasons"] == [] + assert v["yellow_reasons"] == [ + f"Stage 3 quarantine active (1/3): {WS}/scripts/demo/s1.py " + "(DemoLib#12, expires 2026-06-05)"] + assert v["stage3_quarantine"] == v["yellow_reasons"] + + +def test_witness_344_missing_bug_ref_is_refused(): + for bad in (entry(bug=""), {k: v for k, v in entry().items() if k != "bug"}): + c = quarantine.classify([bad], TODAY, [WS]) + assert c["active"] == [] and len(c["refused"]) == 1 + assert "no bug-task ref" in c["refused"][0]["why"] + v = compute(entries=[entry(bug="")]) + assert v["verdict"] == "red" + assert any("quarantine entry refused" in r and "bug-task" in r for r in v["red_reasons"]) + # Refused means not skipped: Stage 3 runs the script. + assert quarantine.skip_list(WS, [entry(bug="")], TODAY, [WS])["entries"] == [] + + +def test_witness_344_expired_entry_is_red_again(): + old = entry(filed="2026-05-20", expires="2026-05-27") + c = quarantine.classify([old], TODAY, [WS]) + assert c["active"] == [] and len(c["expired"]) == 1 + v = compute(entries=[old]) + assert v["verdict"] == "red" + assert any("quarantine EXPIRED" in r and "gates again" in r for r in v["red_reasons"]) + # ... and Stage 3 no longer skips it. + assert quarantine.skip_list(WS, [old], TODAY, [WS])["entries"] == [] + # An entry is live through its expiry day. + assert quarantine.classify([entry(expires="2026-06-01")], TODAY, [WS])["active"] + + +def test_witness_344_fourth_entry_is_refused(): + four = [entry(1, filed="2026-05-28", expires="2026-06-04"), + entry(2, filed="2026-05-29", expires="2026-06-05"), + entry(3, filed="2026-05-30", expires="2026-06-06"), + entry(4, filed="2026-05-31", expires="2026-06-07")] + c = quarantine.classify(four, TODAY, [WS]) + assert [r["label"] for r in c["active"]] == [f"{WS}/scripts/demo/s{n}.py" for n in (1, 2, 3)] + assert [(r["label"], r["why"]) for r in c["refused"]] == [ + (f"{WS}/scripts/demo/s4.py", "3 entries already active")] + v = compute(entries=four) + assert v["verdict"] == "red" + assert len([r for r in v["yellow_reasons"] if "quarantine active (3/3)" in r]) == 3 + assert [e["script"] for e in quarantine.skip_list(WS, four, TODAY, [WS])["entries"]] == \ + [f"scripts/demo/s{n}.py" for n in (1, 2, 3)] + + +# --- the doctrine around it --------------------------------------------------- + +def test_quarantine_never_turns_red_to_green(): + """Another red reason stays red with an active quarantine beside it.""" + snap = make_snapshot() + snap["repos"][LIBS[0]]["ci_status"]["conclusion"] = "failure" + v = compute(snap, entries=[entry()]) + assert v["verdict"] == "red" + assert any("quarantine active" in r for r in v["yellow_reasons"]) + + +@pytest.mark.parametrize("bad,why", [ + (dict(expires="2026-06-07", filed="2026-05-30"), "at most 7"), + (dict(expires="2026-05-30", filed="2026-05-30"), "not after filed"), + (dict(filed="2026-06-02", expires="2026-06-05"), "in the future"), + (dict(workspace="PyAutoDemoLib"), "never unit tests or install checks"), + (dict(script="test_thing.txt"), "not a .py path"), + (dict(script="../escape/x.py"), "not a .py path"), + (dict(bug="see slack"), "not an issue ref"), + (dict(filed="yesterday"), "filed date"), +]) +def test_schema_refusals(bad, why): + c = quarantine.classify([entry(**bad)], TODAY, [WS]) + assert c["active"] == [] and why in c["refused"][0]["why"] + + +def test_bug_ref_forms_accepted(): + for bug in ("DemoLib#3", "DemoOrg/DemoLib#3", "https://github.com/DemoOrg/DemoLib/issues/3"): + assert quarantine.classify([entry(bug=bug)], TODAY, [WS])["active"] + + +def test_skip_list_cli_and_check_exit_codes(tmp_path, capsys): + f = tmp_path / "q.yaml" + f.write_text(json.dumps({"entries": [entry()]})) # JSON is valid YAML + out = tmp_path / "skip.json" + assert quarantine.main(["skip-list", "--workspace", WS, "--file", str(f), + "--date", "2026-06-01", "--out", str(out)]) == 0 + assert json.loads(out.read_text())["entries"] == [ + {"script": "scripts/demo/s1.py", "bug": "DemoLib#12", "expires": "2026-06-05"}] + assert quarantine.main(["check", "--file", str(f), "--date", "2026-06-01"]) == 0 + f.write_text(json.dumps({"entries": [entry(bug="")]})) + assert quarantine.main(["check", "--file", str(f), "--date", "2026-06-01"]) == 1 + + +def test_an_unreadable_quarantine_file_is_red(tmp_path, monkeypatch): + f = tmp_path / "q.yaml" + f.write_text("entries: {not: a list}\n") + monkeypatch.setattr(quarantine, "QUARANTINE_PATH", f) + v = readiness.compute(make_snapshot(), libraries=LIBS) + assert v["verdict"] == "red" + assert any("quarantine file unreadable" in r for r in v["red_reasons"]) + + +def test_live_quarantine_file_passes_its_own_check(): + """The repo-tracked file is valid (Heart Tests reds on a refused entry).""" + entries = quarantine.load(quarantine.HEART_HOME / "config" / "stage3_quarantine.yaml") + today = datetime.datetime.now(datetime.timezone.utc).date() + assert quarantine.classify(entries, today)["refused"] == [] diff --git a/tests/test_workflow_wiring.py b/tests/test_workflow_wiring.py index 8721a95a..3525dc90 100644 --- a/tests/test_workflow_wiring.py +++ b/tests/test_workflow_wiring.py @@ -571,3 +571,19 @@ def test_download_gate_is_a_no_op_without_scripts_and_honours_workspace_dir(tmp_ (other / "bad.py").write_text("from urllib.request import urlretrieve\nurlretrieve('u', 'p')\n") res = _run_discard(step, tmp_path, env={"WORKSPACE_DIR": "elsewhere"}) assert res.returncode == 1 and "scripts/bad.py:2" in res.stdout + + +def test_stage3_release_leg_resolves_the_quarantine_and_retries_once(): + """PyAutoHeart#344: only mode=release resolves Heart's quarantine for the + shard's workspace and asks the runner for its one retry; the smoke leg + (the PR/continuous channel) gets neither.""" + job = _load("workspace-validation.yml")["jobs"]["run_scripts"] + resolve = _step(job, "Resolve the Stage 3 quarantine") + assert resolve["if"] == "needs.find_scripts.outputs.mode == 'release'" + assert "heart.quarantine skip-list" in resolve["run"] + assert "steps.ws.outputs.repo" in resolve["env"]["WS_REPO"] + release = _step(job, "Run Python scripts [mode=release") + assert "--retry-failed" in release["run"] + assert '--quarantine "$GITHUB_WORKSPACE/stage3_quarantine.json"' in release["run"] + smoke = _step(job, "Run Python scripts [mode=smoke") + assert "--retry-failed" not in smoke["run"] and "--quarantine" not in smoke["run"] From 95b74180c9e2544229b9406ec5756c4d5aad2c49 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 13:12:17 +0000 Subject: [PATCH 3/3] fix(readiness): a quarantine skip never reads GREEN; flaky passes are shown (#344 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - MUST-FIX: readiness now judges the ingested rehearsal's own `quarantined` list, not only the live file. Each skipped script is at least YELLOW, named; RED when its entry is no longer active (removed or expired) — only a fresh rehearsal that ran the script clears it. The stage report carries the `quarantine_entry` that skipped each script. - Flaky passes become `flaky_reasons` ("flaky: passed on retry — ..."), rendered in the readiness block and shown at a dev ship; not a tier. Co-Authored-By: Claude Opus 5.5 --- heart/dashboard.py | 5 +++ heart/readiness.py | 32 +++++++++++++++-- heart/validate.py | 5 +-- tests/test_stage3_quarantine.py | 63 +++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 4 deletions(-) diff --git a/heart/dashboard.py b/heart/dashboard.py index f33d98ce..4348c830 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -1906,6 +1906,11 @@ def render_readiness_block(verdict: dict[str, Any], *, quiet: bool = False) -> l if shown < limit: for s in stales[: limit - shown]: lines.append(" " + c_info(f"? {s}")) + # Stage 3 passes that needed the one retry (PyAutoHeart#344): not a tier, + # but always on the board — recorded, never hidden. + if not quiet: + for f in verdict.get("flaky_reasons") or []: + lines.append(" " + c_meta(f"~ {f}")) # A terminal reading STALE gets the door out of it, not just the diagnosis: # `fix stale` prints each gap's command and the one plan that clears them # all. Suppressed in quiet mode — that line is a shell prompt, not a board. diff --git a/heart/readiness.py b/heart/readiness.py index 85ab01d1..fd60b40c 100644 --- a/heart/readiness.py +++ b/heart/readiness.py @@ -739,17 +739,44 @@ def scope_local(msg: str, key: str) -> None: try: q_entries = quarantine if quarantine is not None else _quarantine.load() q_red, q_yellow = _quarantine.readiness_reasons(q_entries, ref.date()) + q_active = _quarantine.classify(q_entries, ref.date())["active"] except (OSError, ValueError, yaml.YAMLError) as exc: q_red, q_yellow = [f"Stage 3 quarantine file unreadable: {exc}"], [] + q_active = [] + # What the ingested rehearsal ACTUALLY skipped. The live file alone is not + # enough: once an entry is removed or expires, a rehearsal that never ran + # its script would read GREEN (and M2.4 ancestry keeps it fresh). Each + # skipped script is at least YELLOW; RED when its entry is no longer active + # — only a fresh rehearsal that ran the script clears it. + live = {(str(r["entry"].get("workspace")), str(r["entry"].get("script"))) + for r in q_active} + vr_q = (vr.get("quarantined") if isinstance(vr, dict) else None) or [] + for row in (r for r in vr_q if isinstance(r, dict)): + e = row.get("quarantine_entry") if isinstance(row.get("quarantine_entry"), dict) else {} + key = (str(e.get("workspace")), str(e.get("script"))) + label = (f"{key[0]}/{key[1]}" if e.get("script") + else f"{row.get('project')}: {row.get('script')}") + if key in live: + q_yellow.append(f"Stage 3 rehearsal skipped {label} (quarantined, " + f"{row.get('quarantined') or e.get('bug')})") + else: + q_red.append(f"Stage 3 rehearsal skipped {label}, but its quarantine " + "is no longer active — re-run the rehearsal so it runs") for t in q_red: red.append(t) - hit("quarantine_expired" if "EXPIRED" in t else "quarantine_refused") + hit("quarantine_expired" if ("EXPIRED" in t or "no longer active" in t) + else "quarantine_refused") for t in q_yellow: yellow.append(t) hit("quarantine_active") # A pass on Stage 3's one retry is recorded as flaky (shown, not a tier). stage3_flaky = [f for f in ((vr or {}).get("flaky") or []) if isinstance(f, dict)] \ if isinstance(vr, dict) else [] + # Shown on every surface, never a tier: the retry is the ruling's, and a + # flaky pass is a pass — but a human reading the verdict must see it. + flaky_reasons = [f"flaky: passed on retry — {f.get('project')}: {f.get('script')}" + + (f" (first: {f.get('first_error')})" if f.get("first_error") else "") + for f in stage3_flaky] # --- release push credential (RED on a refused push, STALE if unproven) --- # heart/checks/token_push.py: the pyautolabs-bot App's `git push --dry-run` @@ -870,6 +897,7 @@ def scope_local(msg: str, key: str) -> None: "na_reasons": na, "stage3_quarantine": q_yellow, "stage3_flaky": stage3_flaky, + "flaky_reasons": flaky_reasons, "validation_ahead": validation_ahead, "validation_note": ( "release validation covers the rehearsed commits; main is ahead by " @@ -1102,7 +1130,7 @@ def split_dev_reasons( shown = [ {"severity": sev, "text": str(t)} for sev, key in (("red", "red_reasons"), ("yellow", "yellow_reasons"), - ("stale", "stale_reasons")) + ("stale", "stale_reasons"), ("flaky", "flaky_reasons")) for t in verdict.get(key) or [] if str(t) not in taken ] diff --git a/heart/validate.py b/heart/validate.py index fc02255a..b073526f 100644 --- a/heart/validate.py +++ b/heart/validate.py @@ -815,10 +815,11 @@ def to_stage_report( # Stage 3's retry and quarantine (PyAutoHeart#344), in the stage report's # own vocabulary: a flaky pass keeps its first error; a quarantined skip # keeps the bug ref of the entry that skipped it. - for key, extra in (("flaky", "first_error"), ("quarantined", "quarantined")): + for key, extras in (("flaky", ("first_error",)), + ("quarantined", ("quarantined", "quarantine_entry"))): rows = aggregate.get(key) report[key] = [{"project": r.get("project"), "script": r.get("file"), - extra: r.get(extra)} + **{x: r.get(x) for x in extras}} for r in (rows if isinstance(rows, list) else []) if isinstance(r, dict)] vi = normalize_verify_install(verify_install) if vi is not None: diff --git a/tests/test_stage3_quarantine.py b/tests/test_stage3_quarantine.py index 0e06f4da..eab3d62a 100644 --- a/tests/test_stage3_quarantine.py +++ b/tests/test_stage3_quarantine.py @@ -185,3 +185,66 @@ def test_live_quarantine_file_passes_its_own_check(): entries = quarantine.load(quarantine.HEART_HOME / "config" / "stage3_quarantine.yaml") today = datetime.datetime.now(datetime.timezone.utc).date() assert quarantine.classify(entries, today)["refused"] == [] + + +# --- review fixes --------------------------------------------------------------- + +def _skipped_row(e): + return {"project": "demo", "script": f"/runner/workspace/{e['script']}", + "quarantined": e["bug"], + "quarantine_entry": {k: e[k] for k in ("workspace", "script", "bug", "expires")}} + + +def _snap_skipped(e): + snap = make_snapshot() + snap["validation_report"]["quarantined"] = [_skipped_row(e)] + return snap + + +def test_a_rehearsal_that_skipped_a_script_never_reads_green_once_the_entry_is_gone(): + """Review MUST-FIX: the report's own `quarantined` list is judged. With the + entry removed (or expired) the rehearsal never ran the script: RED, until a + fresh rehearsal runs it.""" + e = entry() + v = compute(_snap_skipped(e), entries=[]) # entry removed + assert v["verdict"] == "red" + assert any(f"skipped {WS}/scripts/demo/s1.py, but its quarantine is no longer active" + in r for r in v["red_reasons"]) + expired = entry(filed="2026-05-20", expires="2026-05-27") + v = compute(_snap_skipped(expired), entries=[expired]) # entry expired + assert v["verdict"] == "red" + assert any("no longer active" in r for r in v["red_reasons"]) + + +def test_a_rehearsal_skip_under_a_live_entry_is_yellow_and_named(): + e = entry() + v = compute(_snap_skipped(e), entries=[e]) + assert v["verdict"] == "yellow" + assert f"Stage 3 rehearsal skipped {WS}/scripts/demo/s1.py (quarantined, DemoLib#12)" \ + in v["yellow_reasons"] + + +def test_the_stage_report_carries_the_entry_that_skipped_the_script(): + e = entry() + agg = {"ready": True, "summary": {"passed": 1, "skipped": 1}, "failures": [], + "quarantined": [{"project": "demo", "file": "/w/" + e["script"], + "status": "skipped", "quarantined": e["bug"], + "quarantine_entry": _skipped_row(e)["quarantine_entry"]}]} + stage = validate.to_stage_report(agg, profile="release") + assert stage["quarantined"][0]["quarantine_entry"]["workspace"] == WS + + +def test_flaky_passes_are_shown_in_the_verdict_and_rendered(): + """Review item 2: a flaky pass reaches the human, not only the JSON.""" + snap = make_snapshot() + snap["validation_report"]["flaky"] = [{"project": "demo", "script": "scripts/demo/s1.py", + "first_error": "ConnectionError: transient"}] + v = compute(snap) + assert v["verdict"] == "green" + assert v["flaky_reasons"] == ["flaky: passed on retry — demo: scripts/demo/s1.py " + "(first: ConnectionError: transient)"] + text = "\n".join(readiness.render_block(v)) + assert "flaky: passed on retry" in text + d = readiness.dev_ship(snap, [LIBS[0]], libraries=LIBS, now=datetime.datetime( + 2026, 6, 1, 1, tzinfo=datetime.timezone.utc)) + assert any(r["severity"] == "flaky" for r in d["shown_reasons"])