From 3c8af48f5d648e2334771c54e1cb6792f456c071 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:35:48 -0600 Subject: [PATCH 1/3] =?UTF-8?q?fix(github-backup):=20validate=20plan/state?= =?UTF-8?q?=20shape=20at=20load=20=E2=80=94=20poison=20entries=20named=20a?= =?UTF-8?q?nd=20skipped,=20never=20fatal=20(#6637)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- infra/github-backup/bin/clone_all.py | 5 +- infra/github-backup/bin/fetch_mirrors.py | 59 +++++- infra/github-backup/bin/ghb_common.py | 90 ++++++++ infra/github-backup/bin/manifest.py | 10 +- .../tests/test_plan_state_shape.py | 198 ++++++++++++++++++ 5 files changed, 348 insertions(+), 14 deletions(-) create mode 100644 infra/github-backup/tests/test_plan_state_shape.py diff --git a/infra/github-backup/bin/clone_all.py b/infra/github-backup/bin/clone_all.py index f8661a1d54..6c443c3a72 100644 --- a/infra/github-backup/bin/clone_all.py +++ b/infra/github-backup/bin/clone_all.py @@ -12,7 +12,7 @@ from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb, load_plan, report_problems PAR = 4 TIMEOUT = 5400 @@ -80,7 +80,8 @@ def dest_is_confirmed_partial(dest): def main(): cfg = load_config() root = backup_root(cfg) - plan = json.load(open(os.path.join(root, "plan.json"))) + plan, problems = load_plan(root) + report_problems(problems) status_path = os.path.join(root, "clone-status.jsonl") def log_status(rec): diff --git a/infra/github-backup/bin/fetch_mirrors.py b/infra/github-backup/bin/fetch_mirrors.py index f197134bfe..d599930bee 100644 --- a/infra/github-backup/bin/fetch_mirrors.py +++ b/infra/github-backup/bin/fetch_mirrors.py @@ -13,14 +13,23 @@ from datetime import date, timedelta sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from ghb_common import load_config, backup_root, mirror_path, valid_mirror +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, load_plan, load_state, report_problems import manifest as manifest_mod COALESCE_S = 12 * 3600 def record_failure_day(days, today): - """Keep only the trailing consecutive calendar-day failure streak.""" + """Keep only the trailing consecutive calendar-day failure streak. + + A non-list `days` is a malformed state entry (#6637): fail as a + single named error instead of escaping as a raw TypeError/KeyError + from the streak walk or the in-place writes below. + """ + if not isinstance(days, list): + raise ValueError( + f"fail_days must be a list of ISO dates, got {type(days).__name__}" + ) today_date = date.fromisoformat(today) start = len(days) - 1 try: @@ -47,6 +56,35 @@ def record_failure_day(days, today): days[:] = [today] +def _repo_state(state, repo): + """The per-repo state dict, sanitized (#6637). + + A pre-existing non-dict entry (or a non-list fail_days) is poison + from a wrong-shape state.json: report it, replace it with a clean + entry, and let the fetch for this repo — and every other repo — + proceed. + """ + st = state.get(repo) + if not isinstance(st, dict): + if repo in state: + print( + f"github-backup: state entry for {repo!r} is " + f"{type(st).__name__}, expected an object — replaced", + file=sys.stderr, + ) + st = {} + state[repo] = st + days = st.get("fail_days") + if days is not None and not isinstance(days, list): + print( + f"github-backup: 'fail_days' for {repo!r} is " + f"{type(days).__name__}, expected a list — reset to []", + file=sys.stderr, + ) + st["fail_days"] = [] + return st + + def fetch_repo(root, repo, state): path = mirror_path(root, repo) if not valid_mirror(path): @@ -61,14 +99,14 @@ def fetch_repo(root, repo, state): env=env, ) except subprocess.TimeoutExpired as e: - st = state.setdefault(repo, {}) + st = _repo_state(state, repo) today = time.strftime("%Y-%m-%d") days = st.setdefault("fail_days", []) record_failure_day(days, today) st["last_error"] = f"fetch timed out after {e.timeout} seconds" return "fail" now = time.time() - st = state.setdefault(repo, {}) + st = _repo_state(state, repo) if r.returncode == 0: st["last_fetch"] = now st["fail_days"] = [] @@ -81,7 +119,8 @@ def fetch_repo(root, repo, state): def iter_plan_repos(root): - plan = json.load(open(os.path.join(root, "plan.json"))) + plan, problems = load_plan(root) + report_problems(problems) return [p["repo"] for p in plan] @@ -89,7 +128,8 @@ def main(argv): cfg = load_config() root = backup_root(cfg) state_path = os.path.join(root, "state.json") - state = json.load(open(state_path)) if os.path.exists(state_path) else {} + state, problems = load_state(root) + report_problems(problems) log_path = os.path.join(root, "fetch.log") only = argv[1:] repos = only if only else iter_plan_repos(root) @@ -113,7 +153,12 @@ def main(argv): with open(state_path, "w") as f: json.dump(state, f, indent=0) manifest_mod.build(root) - chronic = [r for r in repos if len((state.get(r) or {}).get("fail_days", [])) >= 3] + chronic = [ + r + for r in repos + if isinstance((state.get(r) or {}).get("fail_days"), list) + and len(state[r]["fail_days"]) >= 3 + ] print(json.dumps({"results": results, "chronic_failures": chronic})) return 1 if chronic else 0 diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py index df61d6af35..c06c6a59d7 100644 --- a/infra/github-backup/bin/ghb_common.py +++ b/infra/github-backup/bin/ghb_common.py @@ -141,6 +141,96 @@ def inventory(owners): return out, errors +# ------------------------------------------------------- plan/state files +def _shape(value): + return type(value).__name__ + + +def validate_plan(plan, source="plan.json"): + """Split a loaded plan.json into (valid entries, named problems). + + A plan entry is valid only as an object with a string "repo" — + every consumer subscripts entry["repo"], so any other shape is a + 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. + """ + if not isinstance(plan, list): + return [], [ + f"{source}: top level is {_shape(plan)}, expected a list of " + f"objects — whole file treated as empty" + ] + entries, problems = [], [] + for i, item in enumerate(plan): + if isinstance(item, dict) and isinstance(item.get("repo"), str): + entries.append(item) + else: + problems.append( + f"{source}: entry {i} is not an object with a string " + f"'repo' (got {_shape(item)}) — skipped" + ) + return entries, problems + + +def validate_state(state, source="state.json"): + """Split a loaded state.json into (clean state, named problems). + + Per-repo entries must be objects; a wrong-shape entry is dropped + by name (#6637) so one poison entry cannot wedge every repo, and + a non-list "fail_days" inside an entry is reset to [] under the + same rule. A non-object top level invalidates the whole file as + a single named problem. + """ + if not isinstance(state, dict): + return {}, [ + f"{source}: top level is {_shape(state)}, expected an " + f"object — whole file treated as empty" + ] + clean, problems = {}, [] + for repo, entry in state.items(): + if not isinstance(entry, dict): + problems.append( + f"{source}: entry for {repo!r} is {_shape(entry)}, " + f"expected an object — dropped" + ) + continue + entry = dict(entry) + days = entry.get("fail_days") + if days is not None and not isinstance(days, list): + problems.append( + f"{source}: 'fail_days' for {repo!r} is {_shape(days)}, " + f"expected a list — reset to []" + ) + entry["fail_days"] = [] + clean[repo] = entry + return clean, problems + + +def load_plan(root): + """Load + validate plan.json under `root` (missing file = empty).""" + path = os.path.join(root, "plan.json") + if not os.path.exists(path): + return [], [] + with open(path) as f: + return validate_plan(json.load(f)) + + +def load_state(root): + """Load + validate state.json under `root` (missing file = empty).""" + path = os.path.join(root, "state.json") + if not os.path.exists(path): + return {}, [] + with open(path) as f: + return validate_state(json.load(f)) + + +def report_problems(problems): + """Name every shape problem on stderr; returns the count.""" + for problem in problems: + print(f"github-backup: {problem}", file=sys.stderr) + return len(problems) + + # ---------------------------------------------------------------- plan def build_plan(repos, cfg): """Apply config tier rules. Returns (plan, excluded, gaps, pending_review). diff --git a/infra/github-backup/bin/manifest.py b/infra/github-backup/bin/manifest.py index f6bcba028b..9a7c3372ff 100644 --- a/infra/github-backup/bin/manifest.py +++ b/infra/github-backup/bin/manifest.py @@ -9,7 +9,7 @@ import json, os, subprocess, sys, time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb, load_plan, load_state, report_problems def head_sha(path, branch=None): @@ -32,10 +32,10 @@ def last_fetch(path, state): def build(root=None): cfg = load_config() root = root or backup_root(cfg) - plan_path = os.path.join(root, "plan.json") - plan = json.load(open(plan_path)) if os.path.exists(plan_path) else [] - state_path = os.path.join(root, "state.json") - state = json.load(open(state_path)) if os.path.exists(state_path) else {} + plan, problems = load_plan(root) + report_problems(problems) + state, problems = load_state(root) + report_problems(problems) entries = {} families = {} for item in plan: diff --git a/infra/github-backup/tests/test_plan_state_shape.py b/infra/github-backup/tests/test_plan_state_shape.py new file mode 100644 index 0000000000..919bbb0d2c --- /dev/null +++ b/infra/github-backup/tests/test_plan_state_shape.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Regression tests for plan/state wrong-shape crashes (#6637). + +A plan.json / state.json that is valid JSON but the wrong shape used +to crash fetch_mirrors (and its sibling consumers manifest.py and +clone_all.py) with raw TypeError / KeyError / AttributeError +tracebacks, wedging the whole run for every repo until a human +repaired the file. The fix validates shape at load in ghb_common: +bad entries are reported by name and skipped; a wrong-shape top +level is a single named problem; valid behaviour is unchanged. + +Oracle: the in-tree contract from clone_all.py's clone-status.jsonl +reader and #6606 — bad entries are skipped with a note, never fatal +to the whole run. + +Run: python3 infra/github-backup/tests/test_plan_state_shape.py +""" + +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +BIN = os.path.abspath( + os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bin") +) +sys.path.insert(0, BIN) + +import ghb_common +import fetch_mirrors +import manifest as manifest_mod + + +def write_json(root, name, value): + with open(os.path.join(root, name), "w") as f: + json.dump(value, f) + + +class ValidatePlanTests(unittest.TestCase): + def test_valid_plan_passes_through(self): + plan = [{"repo": "a/b", "size_kb": 1}, {"repo": "c/d"}] + entries, problems = ghb_common.validate_plan(plan) + self.assertEqual(entries, plan) + self.assertEqual(problems, []) + + def test_plan_entry_int_is_named_and_skipped(self): + entries, problems = ghb_common.validate_plan([{"repo": "a/b"}, 123]) + self.assertEqual([e["repo"] for e in entries], ["a/b"]) + self.assertEqual(len(problems), 1) + self.assertIn("entry 1", problems[0]) + + def test_plan_entry_missing_repo_is_named_and_skipped(self): + entries, problems = ghb_common.validate_plan([{"name": "x"}]) + self.assertEqual(entries, []) + self.assertIn("entry 0", problems[0]) + + def test_plan_entry_string_repo_value_required(self): + entries, problems = ghb_common.validate_plan([{"repo": 42}, "a/b"]) + self.assertEqual(entries, []) + self.assertEqual(len(problems), 2) + + def test_plan_top_level_object_is_single_named_problem(self): + entries, problems = ghb_common.validate_plan({"repo": "a/b"}) + self.assertEqual(entries, []) + self.assertEqual(len(problems), 1) + self.assertIn("top level", problems[0]) + + +class ValidateStateTests(unittest.TestCase): + def test_state_entry_string_is_named_and_dropped(self): + clean, problems = ghb_common.validate_state( + {"a/b": {"last_fetch": 1}, "c/d": "oops"} + ) + self.assertEqual(clean, {"a/b": {"last_fetch": 1}}) + self.assertEqual(len(problems), 1) + self.assertIn("c/d", problems[0]) + + def test_state_top_level_list_is_single_named_problem(self): + clean, problems = ghb_common.validate_state([1, 2]) + self.assertEqual(clean, {}) + self.assertIn("top level", problems[0]) + + def test_non_list_fail_days_is_reset_with_problem(self): + clean, problems = ghb_common.validate_state( + {"a/b": {"fail_days": "2026-01-01"}} + ) + self.assertEqual(clean["a/b"]["fail_days"], []) + self.assertIn("fail_days", problems[0]) + + +class FetchMirrorsShapeTests(unittest.TestCase): + def test_iter_plan_repos_skips_poison_entries(self): + with tempfile.TemporaryDirectory() as root: + write_json( + root, + "plan.json", + [{"repo": "a/b"}, 123, {"name": "x"}, {"repo": "c/d"}], + ) + with contextlib.redirect_stderr(io.StringIO()) as err: + repos = fetch_mirrors.iter_plan_repos(root) + self.assertEqual(repos, ["a/b", "c/d"]) + self.assertIn("entry 1", err.getvalue()) + self.assertIn("entry 2", err.getvalue()) + + def test_record_failure_day_rejects_non_list_days(self): + for bad in ["2026-01-01", 123, {"2026-01-01": True}]: + with self.assertRaises(ValueError) as cm: + fetch_mirrors.record_failure_day(bad, "2026-01-02") + self.assertIn("fail_days", str(cm.exception)) + + def test_record_failure_day_list_behaviour_unchanged(self): + days = ["2026-01-01"] + fetch_mirrors.record_failure_day(days, "2026-01-02") + self.assertEqual(days, ["2026-01-01", "2026-01-02"]) + + def run_main(self, root, plan, state): + write_json(root, "plan.json", plan) + write_json(root, "state.json", state) + with ( + patch.object(fetch_mirrors, "load_config", return_value={}), + patch.object(fetch_mirrors, "backup_root", return_value=root), + patch.object(fetch_mirrors, "mirror_path", return_value="/mirror"), + patch.object(fetch_mirrors, "valid_mirror", return_value=False), + patch.object(fetch_mirrors.manifest_mod, "build"), + contextlib.redirect_stdout(io.StringIO()), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + code = fetch_mirrors.main(["fetch_mirrors.py"]) + return code, err.getvalue() + + def test_main_survives_state_top_level_list(self): + with tempfile.TemporaryDirectory() as root: + code, err = self.run_main(root, [{"repo": "a/b"}], [1, 2]) + self.assertEqual(code, 0) + self.assertIn("state.json", err) + with open(os.path.join(root, "state.json")) as f: + self.assertEqual(json.load(f), {}) + + def test_main_survives_string_state_entry_and_poison_plan(self): + with tempfile.TemporaryDirectory() as root: + code, err = self.run_main( + root, + [{"repo": "a/b"}, 123], + {"a/b": "oops"}, + ) + self.assertEqual(code, 0) + self.assertIn("a/b", err) # poison state entry named + self.assertIn("entry 1", err) # poison plan entry named + + def test_fetch_repo_sanitizes_poison_state_entry(self): + state = {"a/b": {"fail_days": "2026-01-01"}} + with ( + patch.object(fetch_mirrors, "mirror_path", return_value="/mirror"), + patch.object(fetch_mirrors, "valid_mirror", return_value=True), + patch.object( + fetch_mirrors.subprocess, + "run", + return_value=SimpleNamespace( + returncode=1, stdout="", stderr="boom" + ), + ), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + result = fetch_mirrors.fetch_repo("/root", "a/b", state) + self.assertEqual(result, "fail") + self.assertIsInstance(state["a/b"]["fail_days"], list) + self.assertEqual(len(state["a/b"]["fail_days"]), 1) # today recorded + self.assertIn("fail_days", err.getvalue()) + + +class ManifestShapeTests(unittest.TestCase): + def test_build_regenerates_with_poison_entries_skipped(self): + with tempfile.TemporaryDirectory() as root: + write_json( + root, + "plan.json", + [{"repo": "a/b", "size_kb": 3}, 123, {"name": "x"}], + ) + write_json(root, "state.json", {"a/b": "oops", "c/d": 7}) + with ( + patch.object(manifest_mod, "load_config", return_value={}), + 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.assertEqual(list(manifest["mirrors"]), ["a/b"]) + self.assertIn("entry 1", err.getvalue()) + self.assertIn("c/d", err.getvalue()) + + +if __name__ == "__main__": + unittest.main() From 2e06082eeea6dd7a21f282579711bc8b111c97c9 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:42:01 -0600 Subject: [PATCH 2/3] fix(github-backup): preserve drainer bookkeeping entries in state validation (#6637, Codex P2 on #6696) --- infra/github-backup/bin/ghb_common.py | 15 ++++++++++++ .../tests/test_plan_state_shape.py | 24 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py index c06c6a59d7..351592b4d0 100644 --- a/infra/github-backup/bin/ghb_common.py +++ b/infra/github-backup/bin/ghb_common.py @@ -180,6 +180,12 @@ def validate_state(state, source="state.json"): a non-list "fail_days" inside an entry is reset to [] under the same rule. A non-object top level invalidates the whole file as a single named problem. + + Bookkeeping keys written by the webhook drainer are state too, + under their own shapes: "drain_last::" is a numeric + timestamp and "drain_fail::" is an object. They are + validated under those shapes and preserved — dropping them + would erase the drainer's coalescing window every daily fetch. """ if not isinstance(state, dict): return {}, [ @@ -188,6 +194,15 @@ def validate_state(state, source="state.json"): ] clean, problems = {}, [] for repo, entry in state.items(): + if repo.startswith("drain_last::"): + if isinstance(entry, (int, float)) and not isinstance(entry, bool): + clean[repo] = entry + else: + problems.append( + f"{source}: entry for {repo!r} is {_shape(entry)}, " + f"expected a number — dropped" + ) + continue if not isinstance(entry, dict): problems.append( f"{source}: entry for {repo!r} is {_shape(entry)}, " diff --git a/infra/github-backup/tests/test_plan_state_shape.py b/infra/github-backup/tests/test_plan_state_shape.py index 919bbb0d2c..97d705f27c 100644 --- a/infra/github-backup/tests/test_plan_state_shape.py +++ b/infra/github-backup/tests/test_plan_state_shape.py @@ -85,6 +85,30 @@ def test_state_top_level_list_is_single_named_problem(self): self.assertEqual(clean, {}) self.assertIn("top level", problems[0]) + def test_drain_bookkeeping_entries_are_preserved(self): + # drain_queue.py keeps its coalescing state in the same file: + # drain_last:: is a numeric timestamp, drain_fail:: + # an object. Validation must not drop them (Codex review, PR + # #6696) — fetch_mirrors.main() writes the state back. + clean, problems = ghb_common.validate_state( + { + "a/b": {"last_fetch": 1}, + "drain_last::a/b": 1760000000.5, + "drain_fail::a/b": {"count": 2, "first": 1, "last": 2}, + } + ) + self.assertEqual(problems, []) + self.assertEqual(clean["drain_last::a/b"], 1760000000.5) + self.assertEqual(clean["drain_fail::a/b"]["count"], 2) + + def test_drain_last_with_wrong_shape_is_named_and_dropped(self): + clean, problems = ghb_common.validate_state( + {"drain_last::a/b": "soon", "drain_last::c/d": True} + ) + self.assertEqual(clean, {}) + self.assertEqual(len(problems), 2) + self.assertIn("drain_last::a/b", problems[0]) + def test_non_list_fail_days_is_reset_with_problem(self): clean, problems = ghb_common.validate_state( {"a/b": {"fail_days": "2026-01-01"}} From 23bd4659cb85125c663954c9c3f2ec0211f1ab01 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:47:17 -0600 Subject: [PATCH 3/3] test(github-backup): property tests for plan/state shape validators (#6637, Codex P1 on #6696) --- .../tests/test_plan_state_shape.py | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) diff --git a/infra/github-backup/tests/test_plan_state_shape.py b/infra/github-backup/tests/test_plan_state_shape.py index 97d705f27c..59e0a3ee5d 100644 --- a/infra/github-backup/tests/test_plan_state_shape.py +++ b/infra/github-backup/tests/test_plan_state_shape.py @@ -20,6 +20,7 @@ import io import json import os +import random import sys import tempfile import unittest @@ -218,5 +219,170 @@ def test_build_regenerates_with_poison_entries_skipped(self): self.assertIn("c/d", err.getvalue()) +class ShapePropertyTests(unittest.TestCase): + """Property tests for the validators (testing doctrine: parsers + and validators carry invariants, and a generator hammers them). + + Stdlib-only: a seeded `random.Random` generates arbitrary + JSON-shaped values. Oracles are independent restatements of the + shape contract, not the implementation: + + - plan oracle: an entry is valid iff it is a dict whose "repo" + is a string; the valid entries, in order, are exactly the + accepted ones, and every invalid entry yields one problem. + - state oracle: a top-level value is valid iff per-repo values + are dicts (with fail_days absent or a list), drain_last:: + values are non-bool numbers, and drain_fail:: values are + dicts; valid inputs survive validation unchanged, validation + is idempotent, and a poison entry never changes the verdict + on its siblings. + """ + + SEED = 6637 + CASES = 2000 + + def gen_value(self, rng, depth=0): + kinds = ["dict", "list", "str", "int", "float", "bool", "none"] + if depth >= 3: + kinds = ["str", "int", "bool", "none"] + kind = rng.choice(kinds) + if kind == "dict": + keys = rng.sample( + ["repo", "size_kb", "fail_days", "last_fetch", "x"], + rng.randint(0, 3), + ) + return {k: self.gen_value(rng, depth + 1) for k in keys} + if kind == "list": + return [self.gen_value(rng, depth + 1) for _ in range(rng.randint(0, 3))] + if kind == "str": + return rng.choice(["a/b", "c/d", "true", "", "2026-01-01"]) + if kind == "int": + return rng.randint(-5, 10**6) + if kind == "float": + return rng.uniform(-5, 10**6) + if kind == "bool": + return rng.choice([True, False]) + return None + + def gen_plan(self, rng): + if rng.random() < 0.1: + return self.gen_value(rng) + plan = [] + for _ in range(rng.randint(0, 6)): + r = rng.random() + if r < 0.45: + plan.append({"repo": rng.choice(["a/b", "c/d", "e/f"])}) + elif r < 0.6: + entry = {"repo": rng.choice(["a/b", "c/d"])} + entry["size_kb"] = rng.randint(0, 100) + plan.append(entry) + else: + plan.append(self.gen_value(rng)) + return plan + + @staticmethod + def plan_oracle(plan): + if not isinstance(plan, list): + return [], 1 + valid = [ + e + for e in plan + if isinstance(e, dict) and isinstance(e.get("repo"), str) + ] + return valid, len(plan) - len(valid) + + def test_plan_invariants_over_generated_inputs(self): + rng = random.Random(self.SEED) + for _ in range(self.CASES): + plan = self.gen_plan(rng) + # Round-trip through JSON: the validators only ever see + # json.load output. + plan = json.loads(json.dumps(plan)) + entries, problems = ghb_common.validate_plan(plan) + want_entries, want_problems = self.plan_oracle(plan) + self.assertEqual(entries, want_entries) + self.assertEqual(len(problems), want_problems) + for e in entries: + self.assertIsInstance(e["repo"], str) + + @staticmethod + def state_oracle(state): + if not isinstance(state, dict): + return {}, 1 + clean, problems = {}, 0 + for key, value in state.items(): + if key.startswith("drain_last::"): + if isinstance(value, (int, float)) and not isinstance(value, bool): + clean[key] = value + else: + problems += 1 + continue + if not isinstance(value, dict): + problems += 1 + continue + entry = dict(value) + days = entry.get("fail_days") + if days is not None and not isinstance(days, list): + entry["fail_days"] = [] + problems += 1 + clean[key] = entry + return clean, problems + + def gen_state(self, rng): + if rng.random() < 0.1: + return self.gen_value(rng) + state = {} + for _ in range(rng.randint(0, 5)): + r = rng.random() + if r < 0.4: + state[rng.choice(["a/b", "c/d"])] = { + "last_fetch": rng.randint(0, 10**6), + "fail_days": ["2026-01-01"], + } + elif r < 0.55: + state[f"drain_last::{rng.choice(['a/b', 'c/d'])}"] = rng.uniform( + 0, 10**6 + ) + elif r < 0.65: + state[f"drain_fail::{rng.choice(['a/b', 'c/d'])}"] = { + "count": rng.randint(0, 5), + "first": 1, + "last": 2, + } + else: + key = rng.choice( + ["a/b", "c/d", "drain_last::a/b", "drain_fail::c/d", "zz"] + ) + state[key] = self.gen_value(rng) + return state + + def test_state_invariants_over_generated_inputs(self): + rng = random.Random(self.SEED + 1) + for _ in range(self.CASES): + state = json.loads(json.dumps(self.gen_state(rng))) + clean, problems = ghb_common.validate_state(state) + want_clean, want_problems = self.state_oracle(state) + self.assertEqual(clean, want_clean) + self.assertEqual(len(problems), want_problems) + # Idempotence: a validated state validates clean. + again, again_problems = ghb_common.validate_state(clean) + self.assertEqual(again, clean) + self.assertEqual(again_problems, []) + + def test_poison_entry_never_changes_sibling_verdicts(self): + rng = random.Random(self.SEED + 2) + poisons = [123, "oops", [1], None, True, {"name": "x"}, {"repo": 7}] + for _ in range(500): + plan = self.gen_plan(rng) + if not isinstance(plan, list): + continue + plan = json.loads(json.dumps(plan)) + base_entries, base_problems = ghb_common.validate_plan(plan) + poisoned = plan + [rng.choice(poisons)] + entries, problems = ghb_common.validate_plan(poisoned) + self.assertEqual(entries, base_entries) + self.assertEqual(len(problems), len(base_problems) + 1) + + if __name__ == "__main__": unittest.main()