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
36 changes: 33 additions & 3 deletions infra/github-backup/bin/ghb_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ def _shape(value):
return type(value).__name__


# Plan fields every consumer treats as a repo name / branch name (or
# null): clone_all hashes "reference" into its scheduler state and
# passes "branch" to manifest's head_sha string concatenation;
# manifest groups families by "reference", sorts the anchors, and
# copies "parent" into MANIFEST.json. All three must be strings or
# null — any other JSON shape is poison (#6834).
_PLAN_STRING_FIELDS = ("reference", "branch", "parent")


def validate_plan(plan, source="plan.json"):
"""Split a loaded plan.json into (valid entries, named problems).

Expand All @@ -154,6 +163,17 @@ def validate_plan(plan, source="plan.json"):
poison entry (#6637): it is reported by index and skipped, never
allowed to crash the run for every other repo. A non-list top
level invalidates the whole file as a single named problem.

The consumed string fields ("reference", "branch", "parent")
are validated per entry (#6834): a value that is neither a string
nor null/absent is reported by entry and field and neutralized
to None — a list/dict reference is unhashable in clone_all's
scheduler and manifest's family grouping, a numeric reference
crashes manifest's mixed-type anchor sort (or writes a bogus
FAMILIES anchor), and a non-string branch crashes head_sha for a
present mirror. The entry itself is kept: its repo is fine, only
the poisoned field is dropped. Entries are copied, never mutated
in place.
"""
if not isinstance(plan, list):
return [], [
Expand All @@ -162,13 +182,23 @@ def validate_plan(plan, source="plan.json"):
]
entries, problems = [], []
for i, item in enumerate(plan):
if isinstance(item, dict) and isinstance(item.get("repo"), str):
entries.append(item)
else:
if not (isinstance(item, dict) and isinstance(item.get("repo"), str)):
problems.append(
f"{source}: entry {i} is not an object with a string "
f"'repo' (got {_shape(item)}) — skipped"
)
continue
entry = dict(item)
for field in _PLAN_STRING_FIELDS:
value = entry.get(field)
if value is not None and not isinstance(value, str):
problems.append(
f"{source}: entry {i} ({entry['repo']}) field "
f"'{field}' is {_shape(value)}, expected a string "
f"or null — set to null"
)
entry[field] = None
entries.append(entry)
return entries, problems


Expand Down
26 changes: 26 additions & 0 deletions infra/github-backup/tests/test_clone_all_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,38 @@ def test_reference_outside_plan_does_not_deadlock_or_get_used():
h.cleanup()


def test_wrong_shape_reference_does_not_crash_scheduler():
# Issue #6834: a list/dict reference is unhashable in the
# scheduler's state.get(ref) and an int reference can never match
# a repo name — pre-fix the whole clone run died before DONE.
# validate_plan now neutralizes them to None: full clones, run
# completes, no --reference flag is passed for the poisoned rows.
h = Harness(
[
{"repo": "o/anchor"},
{"repo": "o/member", "reference": ["o/anchor"]},
{"repo": "o/other", "reference": 123},
]
)
try:
assert h.run() == 0
assert "--reference" not in h.command("o/member")
assert "--reference" not in h.command("o/other")
records = {record["repo"]: record for record in h.records()}
assert len(records) == 3
assert all(r["status"] == "ok" for r in records.values())
assert records["o/member"]["reference_used"] is None
finally:
h.cleanup()


if __name__ == "__main__":
tests = [
test_slow_anchor_is_used_as_reference,
test_failed_anchor_uses_full_clone_fallback,
test_reference_cycle_uses_no_inflight_fallback,
test_reference_outside_plan_does_not_deadlock_or_get_used,
test_wrong_shape_reference_does_not_crash_scheduler,
]
for test in tests:
test()
Expand Down
97 changes: 97 additions & 0 deletions infra/github-backup/tests/test_plan_state_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,52 @@ def test_plan_entry_string_repo_value_required(self):
self.assertEqual(entries, [])
self.assertEqual(len(problems), 2)

def test_wrong_shape_reference_is_named_and_neutralized(self):
# Issue #6834: a list/dict reference is unhashable in
# clone_all's scheduler and manifest's family grouping; an
# int reference crashes manifest's mixed-type anchor sort.
for bad in (["a/b"], {"repo": "a/b"}, 123, True):
entries, problems = ghb_common.validate_plan(
[{"repo": "a/b", "reference": bad}]
)
self.assertEqual(len(entries), 1)
self.assertIsNone(entries[0]["reference"])
self.assertEqual(len(problems), 1)
self.assertIn("entry 0", problems[0])
self.assertIn("'reference'", problems[0])

def test_wrong_shape_branch_and_parent_are_neutralized(self):
# A non-string branch crashes manifest head_sha for a present
# mirror; parent is copied into MANIFEST.json verbatim.
entries, problems = ghb_common.validate_plan(
[{"repo": "a/b", "branch": 7, "parent": ["x/y"]},
{"repo": "c/d", "branch": ["main"], "parent": {"x": 1}}]
)
self.assertEqual(len(entries), 2)
for entry in entries:
self.assertIsNone(entry["branch"])
self.assertIsNone(entry["parent"])
self.assertEqual(len(problems), 4)
self.assertIn("'branch'", problems[0])
self.assertIn("'parent'", problems[1])

def test_string_and_null_fields_pass_unchanged(self):
plan = [
{"repo": "a/b", "reference": "c/d", "branch": "main",
"parent": "x/y"},
{"repo": "c/d", "reference": None, "branch": None,
"parent": None},
{"repo": "e/f"},
]
entries, problems = ghb_common.validate_plan(plan)
self.assertEqual(entries, plan)
self.assertEqual(problems, [])

def test_validate_plan_does_not_mutate_input(self):
plan = [{"repo": "a/b", "reference": ["c/d"]}]
ghb_common.validate_plan(plan)
self.assertEqual(plan[0]["reference"], ["c/d"])

def test_plan_top_level_object_is_single_named_problem(self):
entries, problems = ghb_common.validate_plan({"repo": "a/b"})
self.assertEqual(entries, [])
Expand Down Expand Up @@ -253,6 +299,57 @@ def test_build_with_poison_state_entries(self):
self.assertIn("a/b", err)
self.assertIn("c/d", err)

def test_build_with_wrong_shape_reference_branch_parent(self):
# Issue #6834: pre-fix the int reference wrote a bogus
# "## anchor: 123" family (or crashed the mixed-type sort
# next to a string anchor) and the list reference raised an
# unhashable TypeError in families.setdefault.
with tempfile.TemporaryDirectory() as root:
manifest, err = self.run_build(
root,
[
{"repo": "a/b", "reference": 123},
{"repo": "c/d", "reference": "a/b"},
{"repo": "e/f", "reference": ["a/b"]},
{"repo": "g/h", "branch": ["main"], "parent": {"x": 1}},
],
{},
)
self.assertEqual(
sorted(manifest["mirrors"]), ["a/b", "c/d", "e/f", "g/h"]
)
self.assertIsNone(manifest["mirrors"]["a/b"]["reference"])
self.assertIsNone(manifest["mirrors"]["e/f"]["reference"])
self.assertIsNone(manifest["mirrors"]["g/h"]["default_branch"])
self.assertIsNone(manifest["mirrors"]["g/h"]["parent"])
with open(os.path.join(root, "FAMILIES.md")) as f:
families = f.read()
self.assertIn("## anchor: a/b", families)
self.assertNotIn("123", families)
for field in ("'reference'", "'branch'", "'parent'"):
self.assertIn(field, err)

def test_build_with_wrong_shape_branch_and_present_mirror(self):
# head_sha concatenates "refs/heads/" + branch — only reached
# for present mirrors, so patch valid_mirror on.
with tempfile.TemporaryDirectory() as root:
write_json(
root, "plan.json", [{"repo": "a/b", "branch": ["main"]}]
)
write_json(root, "state.json", {})
with (
patch.object(manifest_mod, "load_config", return_value={}),
patch.object(manifest_mod, "valid_mirror", return_value=True),
patch.object(manifest_mod, "disk_kb", return_value=0),
contextlib.redirect_stderr(io.StringIO()) as err,
):
manifest_mod.build(root)
with open(os.path.join(root, "MANIFEST.json")) as f:
manifest = json.load(f)
self.assertIsNone(manifest["mirrors"]["a/b"]["head"])
self.assertIsNone(manifest["mirrors"]["a/b"]["default_branch"])
self.assertIn("'branch'", err.getvalue())

def test_build_with_state_top_level_list(self):
with tempfile.TemporaryDirectory() as root:
manifest, err = self.run_build(root, [{"repo": "a/b"}], [])
Expand Down
Loading