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
227 changes: 227 additions & 0 deletions heart/checks/required_workflow_drift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
"""heart/checks/required_workflow_drift.py — required workflows with no file.

``config/repos.yaml`` declares ``required_workflows`` per group, and
``heart/checks/ci_status.py``'s ``rollup()`` scores a repo over exactly those
workflows. A required workflow that has **no runs at all** is not scored as a
failure — it simply never satisfies ``all_green``, so the repo sits at
``{"conclusion": "", "status": "in_progress"}`` forever: able to go red, never
able to go green, and never CI-clean to the readiness gate.

On the dashboard that is indistinguishable from *a run is in flight*, which is
why it survives: one workspace repo sat in it from whenever it joined its group
until 2026-08-24, when a human noticed the asymmetry (a *red* required workflow
still reported failure correctly, so the repo could go red but never green).
This module makes that state nameable.

**What it can and cannot see.** The runs payload ``ci_status`` already fetches
cannot distinguish the two causes of "no runs" — a workflow file that does not
exist, and a workflow file that exists but has never run on ``main``. Only the
workflow *list* (``GET /repos/{owner}/{repo}/actions/workflows``) can, so that
is the one extra call this check makes: one per repo in a group that has
``required_workflows``, in parallel, the same cheap metadata read (and the same
shape) as the two ``ci_status.sh`` already makes per repo.

Matching is on each workflow's ``name`` field, never its filename. ``name`` is
what ``ci_status`` matches runs against, so a filename-based check could pass
while the roll-up still starves.

Classification: a missing file is **YELLOW**, and a *configuration* finding
rather than red CI — the repo's code is fine, its gate is not wired up; colouring
it red misattributes the fault. Same monitoring-not-gating stance as
``manifest_drift``, whose shape this mirrors.

Degradation is honest, never a hollow green: no ``gh`` (the web/mobile session)
or a failed fetch reports ``available: false`` / a per-repo ``error``, the same
distinction ``ci_status.sh`` draws between "no runs" and "the query broke".

The result lands at ``$HEART_STATE_DIR/required_workflow_drift.json``.
"""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any

HEART_HOME = Path(__file__).resolve().parents[2]
CONFIG_PATH = HEART_HOME / "config" / "repos.yaml"
HEART_STATE_DIR = Path(
os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart"
)

# Seconds any single workflow-list fetch may take. The repos are scanned in
# parallel, so the worst case this adds to a tick is one timeout rather than one
# per repo — but it is capped anyway so a stalled network can never eat the
# <30s tick budget. Same reasoning as ci_status.sh's ls-remote bound.
FETCH_TIMEOUT_S = int(os.environ.get("HEART_WORKFLOW_LIST_TIMEOUT", "10"))

# Parallel fetches. Matches the order of the repo count (17 today across the
# four groups that gate), so in practice every repo is in flight at once.
MAX_WORKERS = 8


def polled_repos(config_path: Path | str = CONFIG_PATH) -> list[dict[str, str]]:
"""Return ``{owner, name, group}`` for every repo in ``repos:``.

Groups are returned as declared; the caller decides which of them gate.
"""
import yaml

cfg = yaml.safe_load(Path(config_path).read_text()) or {}
out: list[dict[str, str]] = []
for group, entries in (cfg.get("repos") or {}).items():
for repo in entries or []:
if isinstance(repo, dict) and repo.get("name") and repo.get("owner"):
out.append(
{
"owner": str(repo["owner"]),
"name": str(repo["name"]),
"group": str(group),
}
)
return out


def gating_repos(config_path: Path | str = CONFIG_PATH) -> list[dict[str, Any]]:
"""Polled repos whose group declares ``required_workflows``, with that list.

A group with no required workflows is *advisory* — ``rollup()`` reports its
newest run rather than gating on a set — so there is nothing here to be
missing, and nothing to fetch for it.
"""
sys.path.insert(0, str(HEART_HOME))
from heart.checks.ci_status import load_required_workflows

required = load_required_workflows(config_path)
rows = []
for repo in polled_repos(config_path):
want = required.get(repo["group"])
if want:
rows.append({**repo, "required": list(want)})
return rows


def fetch_workflow_names(owner_name: str) -> tuple[list[str] | None, str]:
"""Return this repo's workflow ``name`` fields, or ``(None, error)``.

``per_page=100`` rather than ``--paginate``: no PyAuto repo is near 100
workflow files, and an unpaginated single call keeps this one cheap metadata
read per repo — the cost argument the whole check rests on.
"""
proc = subprocess.run(
[
"gh",
"api",
f"repos/{owner_name}/actions/workflows?per_page=100",
"--jq",
".workflows[].name",
],
capture_output=True,
text=True,
timeout=FETCH_TIMEOUT_S,
)
if proc.returncode != 0:
# Collapse gh's stderr to one line so it fits the sidecar and the log.
err = " ".join((proc.stderr or "").split())[:200]
return None, err or f"gh api exited {proc.returncode}"
return [line for line in proc.stdout.splitlines() if line.strip()], ""


def check_one(repo: dict[str, Any]) -> dict[str, Any]:
"""Resolve one repo's required-vs-present workflow names."""
owner_name = f"{repo['owner']}/{repo['name']}"
try:
names, error = fetch_workflow_names(owner_name)
except subprocess.TimeoutExpired:
names, error = None, f"timed out after {FETCH_TIMEOUT_S}s"
except OSError as exc: # gh vanished between the probe and the call
names, error = None, str(exc)[:200]

row: dict[str, Any] = {
"name": repo["name"],
"group": repo["group"],
"required": list(repo["required"]),
"error": error,
}
if names is None:
row["present"] = []
row["missing"] = []
return row
present = sorted(set(names))
row["present"] = present
row["missing"] = [wf for wf in repo["required"] if wf not in set(names)]
return row


def run(config_path: Path | str = CONFIG_PATH) -> dict[str, Any]:
"""Check every gating repo, write the sidecar, return the result."""
if shutil.which("gh") is None:
result: dict[str, Any] = {
"available": False,
"reason": "gh not installed (web/mobile session)",
"repos": [],
"missing_count": 0,
}
else:
repos = gating_repos(config_path)
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
rows = list(pool.map(check_one, repos))
rows.sort(key=lambda r: (r["group"], r["name"]))
result = {
"available": True,
"checked": len(rows),
"repos": rows,
"missing_count": sum(len(r["missing"]) for r in rows),
"error_count": sum(1 for r in rows if r["error"]),
}

sys.path.insert(0, str(HEART_HOME))
from heart import state

state.atomic_write_json(
HEART_STATE_DIR / "required_workflow_drift.json", result
)
return result


def main(argv: list[str]) -> int:
result = run()
sys.path.insert(0, str(HEART_HOME))
from heart.heart_color import (
c_info,
c_meta,
c_ok,
c_warn,
glyph_ok,
glyph_warn,
)

label = c_info("required_workflow_drift")
if not result["available"]:
print(f"{glyph_warn()} {label} {c_meta('skipped: ' + str(result.get('reason', '')))}")
return 0

missing = result["missing_count"]
checked = result["checked"]
errors = result["error_count"]
suffix = c_meta(f"({checked} gating repos" + (f", {errors} unreadable)" if errors else ")"))
if missing:
worst = [
f"{r['name']}: {', '.join(r['missing'])}"
for r in result["repos"]
if r["missing"]
]
print(f"{glyph_warn()} {label} {c_warn(f'{missing} required workflow(s) with no file')} {suffix}")
for line in worst:
print(f" {c_meta(line)}")
else:
print(f"{glyph_ok()} {label} {c_ok('every required workflow has a file')} {suffix}")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))
34 changes: 34 additions & 0 deletions heart/readiness.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@
"skew_pypi_bad": (25, 50),
"skew_pypi_floor_yanked": (8, 24),
"skew_pypi_unknown": (10, 30),
"required_workflow_drift": (20, 40),
"required_workflow_unknown": (10, 30),
"install_not_ready": (40, 40),
"install_non_release": (10, 10),
"install_stale": (10, 10),
Expand Down Expand Up @@ -461,6 +463,38 @@ def scope_local(msg: str, key: str) -> None:
)
hit("manifest_drift")

# --- required-workflow drift (YELLOW — a gate that is not wired up) ---
#
# A required workflow with no file never satisfies ci_status.rollup()'s
# all_green, so the repo reads `in_progress` forever — indistinguishable
# from a run in flight, which is why this state survives unnoticed. It is a
# *configuration* finding, not red CI: the repo's code is fine, its gate is
# missing, and colouring it red would misattribute the fault.
wf_drift = snapshot.get("required_workflow_drift")
if isinstance(wf_drift, dict) and wf_drift.get("available"):
for row in wf_drift.get("repos") or []:
if not isinstance(row, dict):
continue
for wf in row.get("missing") or []:
yellow.append(
f"{row.get('name')}: required workflow '{wf}' has no workflow "
f"file — CI can never roll up green"
)
hit("required_workflow_drift")
# A repo whose workflow list could not be read is an unknown, never an
# implied pass: without it a missing gate would hide behind the error.
unreadable = [
str(row.get("name"))
for row in wf_drift.get("repos") or []
if isinstance(row, dict) and row.get("error")
]
if unreadable:
add_stale(
"required workflows unverified (workflow list unreadable): "
+ ", ".join(sorted(unreadable)),
"required_workflow_unknown",
)

# --- install verification (deep check: RED on fail, YELLOW if stale/unrun) ---
#
# The sidecar arrives either from a local `verify_install --report-json` run
Expand Down
1 change: 1 addition & 0 deletions heart/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def aggregate() -> dict[str, Any]:
"version_skew": _read_json_or_default(HEART_STATE_DIR / "version_skew.json", {}),
"version_skew_pypi": _read_json_or_default(HEART_STATE_DIR / "version_skew_pypi.json", {}),
"manifest_drift": _read_json_or_default(HEART_STATE_DIR / "manifest_drift.json", {}),
"required_workflow_drift": _read_json_or_default(HEART_STATE_DIR / "required_workflow_drift.json", {}),
"verify_install": _read_json_or_default(HEART_STATE_DIR / "verify_install.json", {}),
"url_check": _read_json_or_default(HEART_STATE_DIR / "url_check.json", {}),
"validation_report": _read_json_or_default(HEART_STATE_DIR / "validation_report.json", {}),
Expand Down
6 changes: 6 additions & 0 deletions heart/tick.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ PYTHONPATH="$HEART_HOME" python3 -m heart.checks.release_run || heart_log WARN "
# Python: workspace-vs-library version skew (cheap file reads; no heavy imports).
PYTHONPATH="$HEART_HOME" python3 -m heart.checks.version_skew || heart_log WARN "$(c_warn 'version_skew failed')"

# Python: required-workflow drift — a required workflow with no file never
# satisfies ci_status's all_green, so the repo reads `in_progress` forever.
# One extra cheap `gh api` metadata read per gating repo, fetched in parallel;
# skips itself entirely when `gh` is absent (web/mobile session).
PYTHONPATH="$HEART_HOME" python3 -m heart.checks.required_workflow_drift || heart_log WARN "$(c_warn 'required_workflow_drift failed')"

# Python: body-map identity drift — PyAutoMind/repos.yaml vs Heart/Build/labels
# repo lists and every checkout's origin (delegates to repos_sync.py --check).
if [[ -f "$PYAUTO_ROOT/PyAutoMind/scripts/repos_sync.py" ]]; then
Expand Down
51 changes: 51 additions & 0 deletions tests/test_readiness.py
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,57 @@ def test_manifest_drift_unavailable_stays_green():
assert v["verdict"] == "green"


def _wf_drift(**overrides):
row = {
"name": "autolens_workspace",
"group": "workspaces",
"required": ["Smoke Tests", "Navigator Check"],
"present": ["Smoke Tests"],
"missing": ["Navigator Check"],
"error": "",
}
row.update(overrides)
return {"available": True, "checked": 1, "repos": [row],
"missing_count": len(row["missing"]),
"error_count": 1 if row["error"] else 0}


def test_missing_required_workflow_is_yellow_not_red():
"""A gate that is not wired up is a configuration finding, not red CI."""
v = compute(make_snapshot(required_workflow_drift=_wf_drift()))
assert v["verdict"] == "yellow"
assert v["red_reasons"] == []
assert any(
"autolens_workspace" in r and "Navigator Check" in r
for r in v["yellow_reasons"]
)


def test_required_workflows_all_present_stays_green():
v = compute(make_snapshot(required_workflow_drift=_wf_drift(
present=["Smoke Tests", "Navigator Check"], missing=[])))
assert v["verdict"] == "green"


def test_required_workflow_drift_unavailable_stays_green():
"""No `gh` (the web/mobile session) is a skip, not a finding."""
v = compute(make_snapshot(required_workflow_drift={
"available": False, "reason": "gh not installed", "repos": [],
"missing_count": 0}))
assert v["verdict"] == "green"


def test_unreadable_workflow_list_is_stale_not_an_implied_pass():
"""Without this, a missing gate would hide behind a failed fetch."""
v = compute(make_snapshot(required_workflow_drift=_wf_drift(
present=[], missing=[], error="HTTP 403")))
assert v["verdict"] == "stale"
assert any("required workflows unverified" in r for r in v["stale_reasons"])
assert any(
d["key"] == "required_workflow_unknown" for d in v["stale_details"]
)


# ---------------------------------------------------------------------------
# release-ci profile (the scheduled-nightly gate — design §5 in
# PyAutoHands/docs/nightly_release_design.md). The driver assembles a snapshot
Expand Down
Loading
Loading