From 6fa0aa40a97f58f025706a5787a9126b2890ddc6 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:54:18 -0600 Subject: [PATCH] fix(repo-universe): wrong-shape fetch/state JSON becomes per-repo ERRORs (#6652) check_issues only turned failures raised as FetchError into report ERROR lines; valid-JSON wrong-shape inputs (scalar issue items, non-list fixture entries, malformed persisted state) crashed the whole run with TypeError/AttributeError and re-crashed daily. normalize_issue, the fixture fetcher and the gh fetcher now raise FetchError for wrong shapes; run_check reports malformed per-repo state entries per-repo (state untouched) and raises a named load error for top-level state shape failures, which main maps to a single named exit-2 error. Seven regression tests cover the named shapes. --- scripts/fleet/repo-universe/check_issues.py | 52 +++++++++++- .../fleet/repo-universe/test_check_issues.py | 85 +++++++++++++++++++ 2 files changed, 134 insertions(+), 3 deletions(-) diff --git a/scripts/fleet/repo-universe/check_issues.py b/scripts/fleet/repo-universe/check_issues.py index ad1a073390..7bf833ad12 100755 --- a/scripts/fleet/repo-universe/check_issues.py +++ b/scripts/fleet/repo-universe/check_issues.py @@ -107,7 +107,15 @@ def parse_inventory(text: str) -> list[str]: def normalize_issue(raw: dict) -> dict | None: - """Project an API issue onto the persisted fields; None for PRs.""" + """Project an API issue onto the persisted fields; None for PRs. + + A non-object item is a failed fetch (#6652): valid JSON with the + wrong shape must surface as FetchError — the per-repo ERROR the + header contract promises — never as a TypeError / AttributeError + that aborts the whole run. + """ + if not isinstance(raw, dict): + raise FetchError(f"issue entry is not a JSON object: {raw!r:.80}") if "pull_request" in raw: return None return {field: raw.get(field) for field in ISSUE_FIELDS} @@ -135,6 +143,9 @@ def fetch_issues_gh(repo: str) -> list[dict]: # stream; gh emits a single merged array for JSON endpoints. if isinstance(pages, dict): pages = [pages] + if not isinstance(pages, list): + raise FetchError(f"unexpected gh api output for {repo}: " + "not a JSON array of issues") issues = [] for item in pages: normalized = normalize_issue(item) @@ -148,11 +159,16 @@ def load_fixture(path: Path) -> dict: def fetch_issues_fixture(repo: str, fixture: dict) -> list[dict]: + if not isinstance(fixture, dict): + raise FetchError("fixture is not a JSON object mapping " + "repos to issue lists") entry = fixture.get(repo) if entry is None: raise FetchError(f"repo {repo} absent from fixture") if isinstance(entry, dict) and "error" in entry: raise FetchError(str(entry["error"])) + if not isinstance(entry, list): + raise FetchError(f"fixture entry for {repo} is not a list of issues") issues = [] for item in entry: normalized = normalize_issue(item) @@ -192,6 +208,19 @@ def diff_repo(prior: dict | None, current: list[dict]) -> dict: "reopened": reopened, "changed": changed} +def _valid_prior_entry(entry) -> bool: + """Shape-check one persisted per-repo state entry (#6652). + + A wrong-shape persisted entry (an int, a list, an issues mapping + whose values are not objects) is reported per-repo by run_check + instead of crashing diff_repo's subscripts for every repo. + """ + if not isinstance(entry, dict): + return False + issues = entry.get("issues") + return isinstance(issues, dict) and all( + isinstance(v, dict) for v in issues.values()) + def run_check(inventory_text: str, state: dict, fetch, now: str) -> tuple[dict, list[str], bool]: """Run one check over all watched repos. @@ -199,12 +228,24 @@ def run_check(inventory_text: str, state: dict, fetch, now: str) -> tuple[dict, injected `fetch` callable, so tests drive it with fixtures. """ repos = parse_inventory(inventory_text) + if not isinstance(state, dict): + raise FetchError("persisted state is not a JSON object") prior_repos = state.get("repos", {}) + if not isinstance(prior_repos, dict): + raise FetchError("persisted state 'repos' is not a JSON object") new_repos = dict(prior_repos) lines = [f"# Repo-universe issue check — {now}", ""] had_error = False total_delta = 0 for repo in repos: + prior_entry = prior_repos.get(repo) + if prior_entry is not None and not _valid_prior_entry(prior_entry): + had_error = True + lines.append(f"## {repo}") + lines.append("- ERROR: persisted state entry is malformed; " + "repo skipped, state left untouched") + lines.append("") + continue try: issues = fetch(repo) except FetchError as exc: @@ -213,7 +254,6 @@ def run_check(inventory_text: str, state: dict, fetch, now: str) -> tuple[dict, lines.append(f"- ERROR: fetch failed: {exc}") lines.append("") continue - prior_entry = prior_repos.get(repo) result = diff_repo(prior_entry["issues"] if prior_entry else None, issues) entry = {"watermark": max((i["updated_at"] or "" for i in issues), default=None), "issues": result["state"]} @@ -268,7 +308,13 @@ def main(argv: list[str] | None = None) -> int: else: fetch = fetch_issues_gh - new_state, lines, had_error = run_check(inventory_text, state, fetch, now) + try: + new_state, lines, had_error = run_check(inventory_text, state, fetch, now) + except FetchError as exc: + # A single named load error for state-level shape failures + # (#6652): no traceback, no report, no state write. + print(f"error: {exc}; no report or state written", file=sys.stderr) + return 2 date = now[:10] report_path = state_dir / f"report-{date}.md" diff --git a/scripts/fleet/repo-universe/test_check_issues.py b/scripts/fleet/repo-universe/test_check_issues.py index 7da8b2e8fd..3b716e27ca 100755 --- a/scripts/fleet/repo-universe/test_check_issues.py +++ b/scripts/fleet/repo-universe/test_check_issues.py @@ -239,5 +239,90 @@ def test_create_edit_close_lifecycle(self): self.assertIn("- closed: #42", "\n".join(lines)) +class WrongShapeTests(unittest.TestCase): + """Valid JSON with the wrong shape becomes per-repo ERRORs (#6652). + + Each case here crashed the checker with an unhandled TypeError / + AttributeError before the fix — one poison entry took down every + repo's delta for the run, and persisted poison re-crashed daily. + """ + + def fixture_fetch(self, fixture): + return lambda repo: check_issues.fetch_issues_fixture(repo, fixture) + + def test_fixture_entry_object_without_error_is_a_fetch_error(self): + fixture = {"dezren39/hatch-personal": {"number": 1}, + "developing-today/code": [issue(9)]} + state, lines, had_error = check_issues.run_check( + INVENTORY, {"version": 1, "repos": {}}, self.fixture_fetch(fixture), NOW1) + self.assertTrue(had_error) + report = "\n".join(lines) + self.assertIn("- ERROR: fetch failed:", report) + # The healthy repo was still checked and baselined. + self.assertIn("baseline: 1 issues recorded", report) + self.assertNotIn("dezren39/hatch-personal", state["repos"]) + + def test_fixture_entry_list_with_scalar_item_is_a_fetch_error(self): + fixture = {"dezren39/hatch-personal": [123], + "developing-today/code": []} + _, lines, had_error = check_issues.run_check( + INVENTORY, {"version": 1, "repos": {}}, self.fixture_fetch(fixture), NOW1) + self.assertTrue(had_error) + self.assertIn("not a JSON object", "\n".join(lines)) + + def test_fixture_top_level_list_is_a_fetch_error(self): + with self.assertRaises(check_issues.FetchError): + check_issues.fetch_issues_fixture("dezren39/hatch-personal", [1, 2]) + + def test_state_top_level_list_is_a_named_load_error(self): + with self.assertRaises(check_issues.FetchError): + check_issues.run_check(INVENTORY, [], fetch_from({}), NOW1) + with self.assertRaises(check_issues.FetchError): + check_issues.run_check(INVENTORY, {"repos": []}, fetch_from({}), NOW1) + + def test_per_repo_state_entry_int_is_reported_and_preserved(self): + good = {"dezren39/hatch-personal": [issue(1)], + "developing-today/code": [issue(9)]} + prior = {"version": 1, "repos": {"dezren39/hatch-personal": 123}} + state, lines, had_error = check_issues.run_check( + INVENTORY, prior, fetch_from(good), NOW2) + self.assertTrue(had_error) + self.assertIn("- ERROR: persisted state entry is malformed", + "\n".join(lines)) + self.assertEqual(state["repos"]["dezren39/hatch-personal"], 123) + # The healthy repo still advanced. + self.assertIn("9", state["repos"]["developing-today/code"]["issues"]) + + def test_persisted_issue_entry_int_is_reported_and_preserved(self): + good = {"dezren39/hatch-personal": [issue(1)], + "developing-today/code": []} + prior = {"version": 1, "repos": { + "dezren39/hatch-personal": { + "watermark": None, "issues": {"1": 123}}}} + state, lines, had_error = check_issues.run_check( + INVENTORY, prior, fetch_from(good), NOW2) + self.assertTrue(had_error) + self.assertIn("- ERROR: persisted state entry is malformed", + "\n".join(lines)) + self.assertEqual( + state["repos"]["dezren39/hatch-personal"]["issues"]["1"], 123) + + def test_main_with_wrong_shape_state_file_exits_named_error(self): + import tempfile + with tempfile.TemporaryDirectory() as td: + td = Path(td) + inventory = td / "inv.yaml" + inventory.write_text(INVENTORY) + state_dir = td / "state" + state_dir.mkdir() + (state_dir / "state.json").write_text("[1, 2, 3]") + argv = ["--inventory", str(inventory), "--state-dir", str(state_dir), + "--fixture", str(td / "fixture.json"), "--now", NOW1] + (td / "fixture.json").write_text(json.dumps({})) + self.assertEqual(check_issues.main(argv), 2) + # No report written, poison state file untouched. + self.assertFalse(list(state_dir.glob("report-*.md"))) + self.assertEqual((state_dir / "state.json").read_text(), "[1, 2, 3]") + if __name__ == "__main__": unittest.main()