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
52 changes: 49 additions & 3 deletions scripts/fleet/repo-universe/check_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -192,19 +208,44 @@ 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.

Returns (new_state, report_lines, had_error). Pure apart from the
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:
Expand All @@ -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"]}
Expand Down Expand Up @@ -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"
Expand Down
85 changes: 85 additions & 0 deletions scripts/fleet/repo-universe/test_check_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading