diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py index 21fa4103b7..f3c32ee8f3 100644 --- a/infra/github-backup/bin/ghb_common.py +++ b/infra/github-backup/bin/ghb_common.py @@ -111,12 +111,21 @@ def disk_kb(path): """ +# Hard page bound for inventory_owner (#6840): at 100 repos per page +# this still admits 100,000 repos under one owner — far above any real +# owner's page count — while guaranteeing the loop terminates even if +# a server invents a fresh advancing cursor on every page forever. +MAX_INVENTORY_PAGES = 1000 + + def inventory_owner(owner): """All repos visible to the gh token under one owner, via GraphQL.""" repos = [] after = None seen_cursors = set() + pages = 0 while True: + pages += 1 variables = {"login": owner} if after: variables["after"] = after @@ -155,12 +164,28 @@ def inventory_owner(owner): f"gh api graphql for {owner}: malformed repositories " f"connection (nodes/pageInfo missing)" ) - for n in conn["nodes"]: + for i, n in enumerate(conn["nodes"]): + if not ( + isinstance(n, dict) + and isinstance(n.get("nameWithOwner"), str) + and n["nameWithOwner"] + ): + # A malformed node is a poison entry (#6637 discipline, + # #6840): name it and skip it — a raw TypeError/KeyError + # from the subscript would fail the owner's whole + # inventory over one bad repo record. + print( + f"github-backup: inventory for {owner}: page {pages} " + f"node {i} is not an object with a non-empty string " + f"'nameWithOwner' (got {_shape(n)}) \u2014 skipped", + file=sys.stderr, + ) + continue repos.append( { "repo": n["nameWithOwner"], - "fork": bool(n["isFork"]), - "archived": bool(n["isArchived"]), + "fork": bool(n.get("isFork")), + "archived": bool(n.get("isArchived")), "size_kb": n.get("diskUsage") or 0, "parent": (n.get("parent") or {}).get("nameWithOwner"), "branch": (n.get("defaultBranchRef") or {}).get("name"), @@ -172,6 +197,12 @@ def inventory_owner(owner): } ) if conn["pageInfo"]["hasNextPage"]: + if pages >= MAX_INVENTORY_PAGES: + raise RuntimeError( + f"gh api graphql for {owner}: pagination exceeded " + f"{MAX_INVENTORY_PAGES} pages with hasNextPage still " + f"true; refusing to page unboundedly" + ) next_after = conn["pageInfo"]["endCursor"] if ( not isinstance(next_after, str) diff --git a/infra/github-backup/tests/test_inventory_owner.py b/infra/github-backup/tests/test_inventory_owner.py index 34e7539825..c7c4331cfe 100644 --- a/infra/github-backup/tests/test_inventory_owner.py +++ b/infra/github-backup/tests/test_inventory_owner.py @@ -204,4 +204,90 @@ def check(name, cond): ghb_common.run = saved_run + +# ------------------------------------------------------------ #6840 shapes +# Oracle: ghb_common.run stubbed with canned GraphQL pages (the same +# oracle as every case above); the expected outcomes are the #6840 +# acceptance criteria — a malformed node is named and skipped, never a +# raw TypeError/KeyError that fails the owner's whole inventory, and a +# server inventing a fresh advancing cursor forever hits the hard +# page bound (MAX_INVENTORY_PAGES, shrunk to 3 here) as a named +# owner-level RuntimeError. +def shape_stub_factory(case): + def stub(cmd, **kw): + good = node("some-owner/repo1") + if case == "null-node": + return R(0, payload([None, good])) + if case == "missing-field-node": + bad = node("some-owner/bad") + del bad["nameWithOwner"] + return R(0, payload([bad, good])) + if case == "nonstring-field-node": + bad = node("some-owner/bad") + bad["nameWithOwner"] = 42 + return R(0, payload([bad, good])) + raise AssertionError(f"unknown node shape case: {case}") + + return stub + + +for case in ["null-node", "missing-field-node", "nonstring-field-node"]: + ghb_common.run = shape_stub_factory(case) + repos, errors = ghb_common.inventory(["some-owner"]) + check( + f"{case}: good repo still inventoried", + [r["repo"] for r in repos.values()] == ["some-owner/repo1"], + ) + check(f"{case}: no owner error (node skipped, not fatal)", errors == {}) + ghb_common.run = shape_stub_factory(case) + direct = ghb_common.inventory_owner("some-owner") + check( + f"{case}: inventory_owner returns only the good repo", + [r["repo"] for r in direct] == ["some-owner/repo1"], + ) + +page_calls = [] + + +def advancing_cursor_stub(cmd, **kw): + page_calls.append(cmd) + return R( + 0, + payload( + [node("some-owner/repo1")], + has_next=True, + cursor=f"cur{len(page_calls)}", + ), + ) + + +saved_max_pages = ghb_common.MAX_INVENTORY_PAGES +ghb_common.MAX_INVENTORY_PAGES = 3 +try: + ghb_common.run = advancing_cursor_stub + try: + ghb_common.inventory_owner("some-owner") + bound_raised = False + bound_message = "" + except RuntimeError as e: + bound_raised = True + bound_message = str(e) + check("page-bound: inventory_owner raises RuntimeError", bound_raised) + check( + "page-bound: exception names owner and the bound", + "some-owner" in bound_message and "3" in bound_message, + ) + check("page-bound: transport calls stop at the bound", len(page_calls) == 3) + page_calls.clear() + repos, errors = ghb_common.inventory(["some-owner"]) + check("page-bound: no repos returned for failed owner", repos == {}) + check( + "page-bound: owner-level error recorded", + "some-owner" in errors and bool(errors["some-owner"]), + ) + check("page-bound: inventory transport calls bounded", len(page_calls) == 3) +finally: + ghb_common.MAX_INVENTORY_PAGES = saved_max_pages + ghb_common.run = saved_run + print(f"\n{sum(1 for _, ok in PASS if ok)}/{len(PASS)} checks passed")