|
| 1 | +"""Reusable canary state machine and GitHub issue updater for live probes. |
| 2 | +
|
| 3 | +IL-1 module: imports only stdlib and `autoskillit.core`. Provides the |
| 4 | +persistence + flake-guard primitives that live probe classes build on. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import os |
| 11 | +import subprocess |
| 12 | +import tempfile |
| 13 | +from dataclasses import asdict, dataclass |
| 14 | +from enum import StrEnum, unique |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +from autoskillit.core import atomic_write, get_logger, run_gh |
| 18 | + |
| 19 | +logger = get_logger(__name__) |
| 20 | + |
| 21 | +N_CONSECUTIVE_FLAKE_GUARD: int = 3 |
| 22 | + |
| 23 | + |
| 24 | +@unique |
| 25 | +class ErrorKind(StrEnum): |
| 26 | + NETWORK = "network" |
| 27 | + SCHEMA = "schema" |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class CanaryState: |
| 32 | + network_streak: int = 0 |
| 33 | + schema_streak: int = 0 |
| 34 | + last_issue_number: int | None = None |
| 35 | + |
| 36 | + @classmethod |
| 37 | + def load(cls, path: Path) -> CanaryState: |
| 38 | + try: |
| 39 | + raw = json.loads(path.read_text(encoding="utf-8")) |
| 40 | + except (FileNotFoundError, json.JSONDecodeError, OSError): |
| 41 | + return cls() |
| 42 | + if not isinstance(raw, dict): |
| 43 | + return cls() |
| 44 | + return cls( |
| 45 | + network_streak=raw.get("network_streak", 0), |
| 46 | + schema_streak=raw.get("schema_streak", 0), |
| 47 | + last_issue_number=raw.get("last_issue_number"), |
| 48 | + ) |
| 49 | + |
| 50 | + def save(self, path: Path) -> None: |
| 51 | + atomic_write(path, json.dumps(asdict(self), indent=2)) |
| 52 | + |
| 53 | + def record_failure(self, kind: ErrorKind) -> None: |
| 54 | + if kind is ErrorKind.NETWORK: |
| 55 | + self.network_streak += 1 |
| 56 | + elif kind is ErrorKind.SCHEMA: |
| 57 | + self.schema_streak += 1 |
| 58 | + else: |
| 59 | + raise ValueError(f"Unhandled ErrorKind: {kind!r}") |
| 60 | + |
| 61 | + def record_success(self) -> None: |
| 62 | + self.network_streak = 0 |
| 63 | + self.schema_streak = 0 |
| 64 | + |
| 65 | + def should_report(self, flake_guard: int = N_CONSECUTIVE_FLAKE_GUARD) -> bool: |
| 66 | + return self.network_streak >= flake_guard or self.schema_streak >= flake_guard |
| 67 | + |
| 68 | + |
| 69 | +def _run_gh_with_body_file(args: list[str], body: str) -> subprocess.CompletedProcess[str]: |
| 70 | + with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as f: |
| 71 | + f.write(body) |
| 72 | + body_path = f.name |
| 73 | + try: |
| 74 | + return run_gh([*args, "--body-file", body_path]) |
| 75 | + finally: |
| 76 | + try: |
| 77 | + os.unlink(body_path) |
| 78 | + except OSError: |
| 79 | + logger.debug("canary_body_file_unlink_failed", path=body_path) |
| 80 | + |
| 81 | + |
| 82 | +class CanaryIssueUpdater: |
| 83 | + def __init__(self, *, owner: str, repo: str) -> None: |
| 84 | + self._owner = owner |
| 85 | + self._repo = repo |
| 86 | + |
| 87 | + def ensure_issue(self, state: CanaryState, title: str, body: str) -> int: |
| 88 | + existing = self._find_existing(title) |
| 89 | + if existing is not None: |
| 90 | + result = _run_gh_with_body_file( |
| 91 | + [ |
| 92 | + "issue", |
| 93 | + "edit", |
| 94 | + str(existing), |
| 95 | + "--repo", |
| 96 | + f"{self._owner}/{self._repo}", |
| 97 | + ], |
| 98 | + body, |
| 99 | + ) |
| 100 | + if result.returncode != 0: |
| 101 | + logger.warning( |
| 102 | + "canary_issue_edit_failed", |
| 103 | + issue=existing, |
| 104 | + stderr=result.stderr, |
| 105 | + ) |
| 106 | + state.last_issue_number = existing |
| 107 | + return existing |
| 108 | + result = _run_gh_with_body_file( |
| 109 | + [ |
| 110 | + "issue", |
| 111 | + "create", |
| 112 | + "--repo", |
| 113 | + f"{self._owner}/{self._repo}", |
| 114 | + "--title", |
| 115 | + title, |
| 116 | + "--json", |
| 117 | + "number", |
| 118 | + ], |
| 119 | + body, |
| 120 | + ) |
| 121 | + if result.returncode != 0: |
| 122 | + msg = f"gh issue create failed: {result.stderr}" |
| 123 | + raise RuntimeError(msg) |
| 124 | + try: |
| 125 | + issue_number = json.loads(result.stdout)["number"] |
| 126 | + except (json.JSONDecodeError, KeyError) as exc: |
| 127 | + msg = f"gh issue create returned unexpected output: {result.stdout!r}" |
| 128 | + raise RuntimeError(msg) from exc |
| 129 | + state.last_issue_number = issue_number |
| 130 | + return issue_number |
| 131 | + |
| 132 | + def _find_existing(self, title: str) -> int | None: |
| 133 | + result = run_gh( |
| 134 | + [ |
| 135 | + "issue", |
| 136 | + "list", |
| 137 | + "--repo", |
| 138 | + f"{self._owner}/{self._repo}", |
| 139 | + "--search", |
| 140 | + title, |
| 141 | + "--state", |
| 142 | + "open", |
| 143 | + "--json", |
| 144 | + "number,title", |
| 145 | + "--limit", |
| 146 | + "10", |
| 147 | + ], |
| 148 | + ) |
| 149 | + if result.returncode != 0: |
| 150 | + logger.warning( |
| 151 | + "canary_find_existing_failed", |
| 152 | + returncode=result.returncode, |
| 153 | + stderr=result.stderr, |
| 154 | + ) |
| 155 | + return None |
| 156 | + try: |
| 157 | + issues = json.loads(result.stdout) |
| 158 | + except json.JSONDecodeError: |
| 159 | + return None |
| 160 | + if not isinstance(issues, list): |
| 161 | + return None |
| 162 | + for issue in issues: |
| 163 | + if issue.get("title") == title: |
| 164 | + number = issue.get("number") |
| 165 | + if isinstance(number, int): |
| 166 | + return number |
| 167 | + return None |
0 commit comments