From fc1c796be37d5018294f6a867a18daa7dead348e Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 08:11:38 -0600 Subject: [PATCH] =?UTF-8?q?github-backup:=20mirror=20contract=20remainder?= =?UTF-8?q?=20=E2=80=94=20validity=20is=20resolvability=20(#3238),=20missi?= =?UTF-8?q?ng-mirror=20alarm=20(#3270),=20atomic=20state=20(#3240),=20clos?= =?UTF-8?q?ing=20audit=20(#3283)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- infra/github-backup/README.md | 47 ++++ infra/github-backup/bin/clone_all.py | 12 +- infra/github-backup/bin/drain_queue.py | 12 +- infra/github-backup/bin/fetch_mirrors.py | 25 +- infra/github-backup/bin/ghb_common.py | 197 ++++++++++++- infra/github-backup/bin/manifest.py | 14 +- infra/github-backup/bin/reconcile.py | 21 +- infra/github-backup/docs/RUNBOOK.md | 8 + .../tests/test_clone_all_partial.py | 53 +++- .../tests/test_mirror_contract.py | 263 ++++++++++++++++++ .../tests/test_plan_state_shape.py | 10 +- .../tests/test_reconcile_clone_pass.py | 22 ++ .../tests/test_reconcile_retention.py | 25 +- 13 files changed, 668 insertions(+), 41 deletions(-) create mode 100644 infra/github-backup/tests/test_mirror_contract.py diff --git a/infra/github-backup/README.md b/infra/github-backup/README.md index 250f8523b2..b33e6993cc 100644 --- a/infra/github-backup/README.md +++ b/infra/github-backup/README.md @@ -50,6 +50,53 @@ reconcile-YYYY-MM-DD.md weekly sweep reports `config.json` → `app.bitwarden_secret_names`. Values never enter this repo, the backup tree, or chat. +## System contract — a mirror is what it can prove (design #3282) + +No surface of this system may report coverage, success, or health +that the underlying mirrors, records, or inventory do not support. +The seven rules, in operator language: + +1. **Validity is resolvability.** A mirror counts as present only + when it is bare AND its HEAD resolves to a commit + (`ghb_common.valid_mirror`). A bare directory with no refs is a + skeleton, not a backup. Planned repos are never legitimately + empty (zero-commit repos are excluded from the plan), so there + is no emptiness exception. +2. **Destinations have four states, each with a disposition.** + Absent → clone. Valid → skip (never deleted or re-cloned). + Skeleton (bare, unresolvable HEAD, zero refs) → remove and + clone; removal provably loses nothing. Debris (exists, not a + bare skeleton, not valid) → preserved and reported, never + silently deleted — it may hold the only copy of transferred + objects; `clone_all` fails loudly for that repo instead. +3. **Every attempt ends in a recorded outcome.** A per-repo fetch + never raises out of the run: a timeout, a failure, and a missing + mirror are all recorded (`ok` / `fail` / `missing`) in state, + `fetch.log`, and the run summary, by the one recorder path the + daily loop and the webhook drainer share. +4. **An event is acked only when its fetch landed.** The drainer + acks a planned repo's webhook event only on a recorded `ok`; on + `fail` / `missing` the event stays queued for the next drain and + the coalescing stamp advances only on `ok`. +5. **The alarm is a streak of unavailable days.** Failures, + timeouts, and missing mirrors all record the day against the + repo; a success clears the record. Three consecutive unavailable + days make the daily run exit non-zero — that exit code is the + alarm systemd watches. +6. **State is written atomically, loaded tolerantly, only through + `ghb_common`.** Generated state (`plan.json`, `state.json`, + `MANIFEST.json`, `FAMILIES.md`, reconcile reports) is written + via temp-file + fsync + `os.replace` with a last-good copy kept; + a torn file loads its last-good copy with a loud warning instead + of crashing every reader. The two `state.json` writers (daily + fetch, 5-minute drainer) hold the shared `state.lock` flock + across their whole read-modify-write cycle. +7. **A failed owner keeps its plan.** An owner whose inventory + fails (null `repositoryOwner`, SAML block, API error) is an + error, never an empty owner: reconcile retains that owner's + previously planned entries, marks them retained in the report, + and still exits non-zero. + ## Components | Path | What | diff --git a/infra/github-backup/bin/clone_all.py b/infra/github-backup/bin/clone_all.py index c75897beb6..3cd84b31f3 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, load_plan, report_problems, clone_status_record +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb, load_plan, report_problems, clone_status_record, is_skeleton_mirror PAR = 4 TIMEOUT = 5400 @@ -58,8 +58,14 @@ def dest_is_confirmed_partial(dest): worse than the wedge this fixes (Codex P1 on the #3233 PR). So: - a non-directory at the mirror path is a stray file — partial; + - a bare skeleton (bare, HEAD unresolvable, zero refs — #3238) + is partial: it is the state `clone --mirror` creates before + transport, holds no refs and no reachable objects by + construction, so clearing it loses nothing (design #3282 + rule 2's skeleton disposition); - git answering at all (rc 0) means a real repository lives there - — never partial, whatever valid_mirror made of it; + — never partial, whatever valid_mirror made of it (a bare repo + WITH refs reaches this branch and is preserved); - git saying 'not a git repository' is the killed-clone / junk shape — partial; - any other git failure is an inspection/policy error — NOT @@ -67,6 +73,8 @@ def dest_is_confirmed_partial(dest): """ if not os.path.isdir(dest): return True + if is_skeleton_mirror(dest): + return True r = subprocess.run( ["git", "-C", dest, "rev-parse", "--is-bare-repository"], capture_output=True, diff --git a/infra/github-backup/bin/drain_queue.py b/infra/github-backup/bin/drain_queue.py index c7b4c08eff..9b79eb11a4 100644 --- a/infra/github-backup/bin/drain_queue.py +++ b/infra/github-backup/bin/drain_queue.py @@ -45,7 +45,7 @@ from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from ghb_common import load_config, backup_root, load_plan, load_state, report_problems +from ghb_common import load_config, backup_root, load_plan, load_state, report_problems, save_json, state_lock import fetch_mirrors COALESCE_S = 15 * 60 @@ -213,6 +213,13 @@ def event_owner(ev): def main(): cfg = load_config() root = backup_root(cfg) + # #3240: same shared state lock as the daily fetch — see + # fetch_mirrors.main. The lock spans load -> modify -> save. + with state_lock(root): + return _main_locked(cfg, root) + + +def _main_locked(cfg, root): state_path = os.path.join(root, "state.json") state, problems = load_state(root) report_problems(problems) @@ -299,8 +306,7 @@ def log(line): failed.append( {"repo": repo, "result": res, "consecutive_failures": fs["count"]} ) - with open(state_path, "w") as f: - json.dump(state, f, indent=0) + save_json(state_path, state) if ack: ack_events(cfg, ack) print( diff --git a/infra/github-backup/bin/fetch_mirrors.py b/infra/github-backup/bin/fetch_mirrors.py index d599930bee..523c699b85 100644 --- a/infra/github-backup/bin/fetch_mirrors.py +++ b/infra/github-backup/bin/fetch_mirrors.py @@ -13,7 +13,7 @@ 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, load_plan, load_state, report_problems +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, load_plan, load_state, report_problems, save_json, state_lock import manifest as manifest_mod COALESCE_S = 12 * 3600 @@ -88,6 +88,18 @@ def _repo_state(state, repo): def fetch_repo(root, repo, state): path = mirror_path(root, repo) if not valid_mirror(path): + # #3270 / design #3282 rule 5: a missing mirror is an + # unavailable day, recorded exactly like a failure day. The + # missing path used to return before any state was touched, + # so a repo with NO backup at all could never trip the + # chronic alarm (3 consecutive days -> exit 1) that a merely + # failing fetch trips. Success clears the record via the + # same fail_days reset as the failure path. + st = _repo_state(state, repo) + today = time.strftime("%Y-%m-%d") + days = st.setdefault("fail_days", []) + record_failure_day(days, today) + st["last_error"] = "mirror missing or invalid on disk" return "missing" env = dict(os.environ, GIT_TERMINAL_PROMPT="0") try: @@ -127,6 +139,14 @@ def iter_plan_repos(root): def main(argv): cfg = load_config() root = backup_root(cfg) + # #3240: the whole load -> modify -> save cycle runs under the + # shared state lock so the daily fetch and the 5-minute drainer + # cannot interleave a lost update into state.json. + with state_lock(root): + return _main_locked(argv, root) + + +def _main_locked(argv, root): state_path = os.path.join(root, "state.json") state, problems = load_state(root) report_problems(problems) @@ -150,8 +170,7 @@ def main(argv): f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {repo} {res} " f"{(state.get(repo) or {}).get('last_error', '')}\n" ) - with open(state_path, "w") as f: - json.dump(state, f, indent=0) + save_json(state_path, state) manifest_mod.build(root) chronic = [ r diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py index 3955a4354b..89c962b56c 100644 --- a/infra/github-backup/bin/ghb_common.py +++ b/infra/github-backup/bin/ghb_common.py @@ -7,7 +7,12 @@ state (plan.json, MANIFEST.json, logs); all logic lives in the repo. """ -import json, os, subprocess, sys +import contextlib, json, os, shutil, subprocess, sys, tempfile + +try: + import fcntl +except ImportError: # non-Unix: the lock helper degrades to a no-op + fcntl = None HERE = os.path.dirname(os.path.abspath(__file__)) GB_DIR = os.path.dirname(HERE) @@ -33,10 +38,52 @@ def run(cmd, **kw): def valid_mirror(path): + """A mirror is valid only if it can prove it holds history (#3238). + + Design #3282 rule 1 — validity is resolvability: the destination + must be a bare repository AND its HEAD must resolve to a commit + (`rev-parse --verify -q HEAD`, the same call manifest.head_sha + makes). Bareness alone is true from the moment `git clone + --mirror` creates the destination skeleton, before any ref or + object has transferred, so a clone killed in that window used to + pass everywhere as a verified mirror while holding nothing. + + There is deliberately no emptiness exception: a planned repo is + never legitimately empty — build_plan excludes zero-commit repos + under the live config (skip_zero_commit_repos) — so an + unresolvable HEAD inside the plan is always a skeleton, never a + valid empty mirror. + """ if not os.path.isdir(path): return False r = run(["git", "-C", path, "rev-parse", "--is-bare-repository"]) - return r.returncode == 0 and r.stdout.strip() == "true" + if r.returncode != 0 or r.stdout.strip() != "true": + return False + h = run(["git", "-C", path, "rev-parse", "--verify", "-q", "HEAD"]) + return h.returncode == 0 and bool(h.stdout.strip()) + + +def is_skeleton_mirror(path): + """True for a bare skeleton: bare, HEAD unresolvable, zero refs. + + This is the destination state a `clone --mirror` creates before + transport and a killed clone leaves behind (#3238). By + construction it holds no refs and no reachable objects, so + removing it loses nothing — design #3282 rule 2's skeleton + disposition (remove and clone). A bare repository WITH refs is + never a skeleton, whatever its HEAD state: it may hold the only + copy of transferred objects and must be preserved. + """ + if not os.path.isdir(path): + return False + r = run(["git", "-C", path, "rev-parse", "--is-bare-repository"]) + if r.returncode != 0 or r.stdout.strip() != "true": + return False + h = run(["git", "-C", path, "rev-parse", "--verify", "-q", "HEAD"]) + if h.returncode == 0: + return False + refs = run(["git", "-C", path, "for-each-ref"]) + return refs.returncode == 0 and not refs.stdout.strip() def disk_kb(path): @@ -141,6 +188,128 @@ def inventory(owners): return out, errors +# ------------------------------------------- generated-state IO (#3240) +# Design #3282 rule 6: generated state (plan.json, state.json, +# MANIFEST.json, and the markdown reports built from them) is written +# atomically and loaded tolerantly, only through these helpers. A +# writer killed mid-dump (laptop sleep, reboot, driver timeout) must +# never leave a torn live file, and a pre-existing torn file must +# never wedge every reader at startup with a raw JSONDecodeError. + +LAST_GOOD_SUFFIX = ".last-good" + + +def _atomic_replace(path, text): + """Write `text` to `path` atomically: temp file in the SAME + directory, fsync, os.replace, directory fsync (best effort). A + reader only ever observes the previous complete file or the new + complete file — never a partial one.""" + directory = os.path.dirname(os.path.abspath(path)) + fd, tmp = tempfile.mkstemp( + dir=directory, prefix=".ghb-", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w") as f: + f.write(text) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp) + raise + with contextlib.suppress(OSError): + dir_fd = os.open(directory, os.O_RDONLY) + try: + os.fsync(dir_fd) + finally: + os.close(dir_fd) + + +def atomic_write_text(path, text): + """Atomically replace `path` with `text`, keeping the previous + complete version at `.last-good` for the tolerant loader.""" + if os.path.exists(path): + with contextlib.suppress(OSError): + with open(path) as f: + previous = f.read() + _atomic_replace(path + LAST_GOOD_SUFFIX, previous) + _atomic_replace(path, text) + + +def save_json(path, obj, **dump_kw): + """Serialize + atomically write a generated-state JSON file.""" + dump_kw.setdefault("indent", 0) + atomic_write_text(path, json.dumps(obj, **dump_kw)) + + +def load_json_tolerant(path, default, source): + """Load a generated-state JSON file tolerantly (#3240). + + Returns (value, problems). Missing file = (default, []). A torn + or unreadable live file falls back to the `.last-good` + copy kept by atomic_write_text; if that also fails, (default, + [problem]). Every fallback is a loud, named problem — corruption + is surfaced by the callers' report_problems, never silent and + never a startup traceback. + """ + if not os.path.exists(path): + return default, [] + try: + with open(path) as f: + return json.load(f), [] + except (OSError, ValueError) as e: + problems = [ + f"{source}: cannot load {os.path.basename(path)} " + f"({type(e).__name__}: {e}) — trying last-good copy" + ] + backup = path + LAST_GOOD_SUFFIX + if os.path.exists(backup): + try: + with open(backup) as f: + value = json.load(f) + problems.append( + f"{source}: {os.path.basename(path)} is torn; fell " + f"back to the last-good copy — the live file needs " + f"repair on the next successful write" + ) + return value, problems + except (OSError, ValueError) as e: + problems.append( + f"{source}: last-good copy also unusable " + f"({type(e).__name__}: {e})" + ) + problems.append( + f"{source}: {os.path.basename(path)} treated as empty" + ) + return default, problems + + +@contextlib.contextmanager +def state_lock(root): + """Shared flock for state.json read-modify-write (#3240). + + The daily fetch and the 5-minute drainer both load state.json, + modify it, and write it back; without a lock, one writer's + read-modify-write window silently drops the other's updates. + Hold this around the whole load -> modify -> save cycle. The + lock lives on a dedicated lockfile (never replaced), and + degrades to a no-op where fcntl is unavailable. + """ + if fcntl is None: + yield + return + os.makedirs(root, exist_ok=True) + fd = os.open(os.path.join(root, "state.lock"), os.O_CREAT | os.O_RDWR, 0o644) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + with contextlib.suppress(OSError): + fcntl.flock(fd, fcntl.LOCK_UN) + os.close(fd) + + # ------------------------------------------------------- plan/state files def _shape(value): return type(value).__name__ @@ -252,21 +421,25 @@ def validate_state(state, source="state.json"): def load_plan(root): - """Load + validate plan.json under `root` (missing file = empty).""" + """Load + validate plan.json under `root` (missing file = empty). + + Tolerant (#3240): a torn plan.json falls back to its last-good + copy (or empty) with named problems, never a JSONDecodeError at + startup.""" 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)) + raw, problems = load_json_tolerant(path, [], "plan.json") + entries, shape_problems = validate_plan(raw) + return entries, problems + shape_problems def load_state(root): - """Load + validate state.json under `root` (missing file = empty).""" + """Load + validate state.json under `root` (missing file = empty). + + Tolerant (#3240), same contract as load_plan.""" 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)) + raw, problems = load_json_tolerant(path, {}, "state.json") + clean, shape_problems = validate_state(raw) + return clean, problems + shape_problems def clone_status_record(line): diff --git a/infra/github-backup/bin/manifest.py b/infra/github-backup/bin/manifest.py index 9a7c3372ff..e4c94a145b 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, load_plan, load_state, report_problems +from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb, load_plan, load_state, report_problems, atomic_write_text, save_json def head_sha(path, branch=None): @@ -68,8 +68,11 @@ def build(root=None): "disk_kb": sum(e["disk_kb"] for e in entries.values()), }, } - with open(os.path.join(root, "MANIFEST.json"), "w") as f: - json.dump(manifest, f, indent=1, sort_keys=True) + # #3240: MANIFEST.json is the DR source of truth — atomic write + # via ghb_common, never a truncating open("w"). + save_json( + os.path.join(root, "MANIFEST.json"), manifest, indent=1, sort_keys=True + ) lines = [ "# Fork families (git alternates pool)", "", @@ -83,8 +86,9 @@ def build(root=None): for m in sorted(families[anchor]): lines.append(f"- {m}") lines.append("") - with open(os.path.join(root, "FAMILIES.md"), "w") as f: - f.write("\n".join(lines)) + # FAMILIES.md feeds cold-export decisions, so it gets the same + # atomic write as the JSON state (#3240 / #3283 disposition (a)). + atomic_write_text(os.path.join(root, "FAMILIES.md"), "\n".join(lines)) return manifest diff --git a/infra/github-backup/bin/reconcile.py b/infra/github-backup/bin/reconcile.py index f37a67d5fb..cb44f2e0b9 100644 --- a/infra/github-backup/bin/reconcile.py +++ b/infra/github-backup/bin/reconcile.py @@ -27,6 +27,10 @@ valid_mirror, mirror_path, clone_status_record, + load_plan, + report_problems, + save_json, + atomic_write_text, ) import manifest as manifest_mod @@ -80,9 +84,12 @@ def main(): plan, excluded, gaps, pending, skipped_empty = build_plan(repos, cfg) today = time.strftime("%Y-%m-%d") old_plan_path = os.path.join(root, "plan.json") - old_items = [] - if os.path.exists(old_plan_path): - old_items = json.load(open(old_plan_path)) + # #3240: the previous plan is loaded through the tolerant shared + # loader — a torn plan.json falls back to its last-good copy with + # named problems instead of killing the sweep at startup, and + # retention below still sees the last-known-good entries. + old_items, problems = load_plan(root) + report_problems(problems) old = [p["repo"] for p in old_items] # Last-known-good (#3229): an owner whose inventory FAILED (null # repositoryOwner, SAML-blocked, gh error, ...) keeps its previously @@ -106,8 +113,7 @@ def main(): added = sorted(set(new) - set(old)) removed = sorted(set(old) - set(new)) missing = [r for r in new if not valid_mirror(mirror_path(root, r))] - with open(old_plan_path, "w") as f: - json.dump(plan, f, indent=0) + save_json(old_plan_path, plan) lines = [ f"# github-backup reconcile {today}", "", @@ -191,8 +197,9 @@ def main(): ) lines.append("") report_path = os.path.join(root, f"reconcile-{today}.md") - with open(report_path, "w") as f: - f.write("\n".join(lines)) + # #3283 disposition (a): the dated reconcile report is generated + # state too — atomic write, same helper as FAMILIES.md. + atomic_write_text(report_path, "\n".join(lines)) print("\n".join(lines)) if clone_rc not in (None, 0): print("clone pass had failures; see clone-status.jsonl") diff --git a/infra/github-backup/docs/RUNBOOK.md b/infra/github-backup/docs/RUNBOOK.md index 065e9ec9b1..7d4bd17bc2 100644 --- a/infra/github-backup/docs/RUNBOOK.md +++ b/infra/github-backup/docs/RUNBOOK.md @@ -174,6 +174,14 @@ Config (this repo) + Bitwarden are the only inputs. §7 Option B rebuilds the entire tree; MANIFEST.json regenerates at the end. Exclusions and gaps in config.json reproduce exactly the intended non-coverage. +MANIFEST.json is trustworthy as the DR record because of the system +contract in `../README.md` ("a mirror is what it can prove", design +#3282): a mirror is only reported `mirrored` when its HEAD resolves, +every generated-state file is written atomically with a last-good +copy, and a failed owner's repos stay planned rather than silently +dropping out of the manifest. Read that section before treating any +status surface here as coverage. + ## 10. Health checks ```sh diff --git a/infra/github-backup/tests/test_clone_all_partial.py b/infra/github-backup/tests/test_clone_all_partial.py index 5157938ccf..9b27dd440d 100644 --- a/infra/github-backup/tests/test_clone_all_partial.py +++ b/infra/github-backup/tests/test_clone_all_partial.py @@ -10,7 +10,8 @@ Drives the real clone_all.main() against a temp backup root with a fake subprocess standing in for `git clone` (the fake mimics real git: cloning into a non-empty destination fails; otherwise it creates a -real bare mirror with git init --bare). valid_mirror stays real. +real bare mirror with one commit — since #3238 a zero-ref skeleton +is not a valid mirror). valid_mirror stays real. partial dest -> cleared, clone retried, ok + cleared_partial partial dest, clone @@ -42,6 +43,48 @@ REAL_RUN = subprocess.run REPO = "octo/widgets" +GIT_IDENTITY = { + **os.environ, + "GIT_AUTHOR_NAME": "ghb-test", + "GIT_AUTHOR_EMAIL": "ghb-test@example.invalid", + "GIT_COMMITTER_NAME": "ghb-test", + "GIT_COMMITTER_EMAIL": "ghb-test@example.invalid", +} + + +def make_bare_with_commit(dest): + """A REAL valid mirror: bare + one commit on refs/heads/main. + + Since #3238 a bare skeleton (git init --bare, zero refs) is not + a valid mirror — validity requires a resolvable HEAD — so test + fixtures that need a valid mirror must give it history. + """ + r = REAL_RUN(["git", "init", "--bare", dest], capture_output=True, text=True) + assert r.returncode == 0, r.stderr + tree = REAL_RUN( + ["git", "-C", dest, "mktree"], input="", capture_output=True, text=True + ) + assert tree.returncode == 0, tree.stderr + commit = REAL_RUN( + ["git", "-C", dest, "commit-tree", tree.stdout.strip(), "-m", "seed"], + capture_output=True, + text=True, + env=GIT_IDENTITY, + ) + assert commit.returncode == 0, commit.stderr + r = REAL_RUN( + ["git", "-C", dest, "update-ref", "refs/heads/main", commit.stdout.strip()], + capture_output=True, + text=True, + ) + assert r.returncode == 0, r.stderr + r = REAL_RUN( + ["git", "-C", dest, "symbolic-ref", "HEAD", "refs/heads/main"], + capture_output=True, + text=True, + ) + assert r.returncode == 0, r.stderr + class FakeSubprocess: """Stand-in for the subprocess module as clone_all sees it. @@ -86,8 +129,7 @@ def run(self, cmd, **kw): return subprocess.CompletedProcess( cmd, 1, "", "fatal: simulated clone failure" ) - r = REAL_RUN(["git", "init", "--bare", dest], capture_output=True, text=True) - assert r.returncode == 0, r.stderr + make_bare_with_commit(dest) return subprocess.CompletedProcess(cmd, 0, "", "") @@ -138,10 +180,7 @@ def seed_partial(self): def seed_valid_mirror(self): os.makedirs(os.path.dirname(self.dest), exist_ok=True) - r = REAL_RUN( - ["git", "init", "--bare", self.dest], capture_output=True, text=True - ) - assert r.returncode == 0, r.stderr + make_bare_with_commit(self.dest) with open(os.path.join(self.dest, "marker.txt"), "w") as f: f.write("do not touch") diff --git a/infra/github-backup/tests/test_mirror_contract.py b/infra/github-backup/tests/test_mirror_contract.py new file mode 100644 index 0000000000..7a24a10a26 --- /dev/null +++ b/infra/github-backup/tests/test_mirror_contract.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Regression tests for the #3282 mirror contract remainder: +#3238 (validity is resolvability), #3270 (missing mirrors reach the +chronic alarm), and #3240 (atomic writes, tolerant loads, shared +state lock). + +Oracles: +- #3238: the design's rule 1 — a mirror is valid iff it is bare AND + its HEAD resolves; a bare skeleton (the state `git clone --mirror` + creates before transport) holds zero refs by construction. +- #3270: the fetch docstring's alarm contract — 3 consecutive + unavailable days exit non-zero; missing is an unavailable day, + recorded through the same fail_days streak as failures (#3257). +- #3240: a reader never observes a partial file (temp + fsync + + os.replace), and a torn file falls back loudly (last-good copy or + empty), never a startup JSONDecodeError. + +Run: python3 infra/github-backup/tests/test_mirror_contract.py +""" + +import contextlib +import io +import json +import os +import subprocess +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 clone_all +import fetch_mirrors +import manifest as manifest_mod + + +def git(*args, cwd=None): + return subprocess.run( + ["git", *args], cwd=cwd, capture_output=True, text=True, check=True + ) + + +def make_complete_mirror(root): + """A small source repo + a real `git clone --mirror` of it.""" + src = os.path.join(root, "src") + os.makedirs(src) + git("init", "-b", "main", cwd=src) + git("config", "user.email", "t@example.invalid", cwd=src) + git("config", "user.name", "t", cwd=src) + with open(os.path.join(src, "f.txt"), "w") as f: + f.write("hello\n") + git("add", "f.txt", cwd=src) + git("commit", "-m", "one", cwd=src) + dest = os.path.join(root, "owner", "repo.git") + os.makedirs(os.path.dirname(dest)) + git("clone", "--mirror", src, dest) + return dest + + +def make_skeleton(root): + """The bare skeleton a killed mirror clone leaves (#3238).""" + dest = os.path.join(root, "owner", "repo.git") + os.makedirs(os.path.dirname(dest)) + git("init", "--bare", dest) + return dest + + +class ValidMirrorTests(unittest.TestCase): + def test_bare_skeleton_is_invalid(self): + with tempfile.TemporaryDirectory() as root: + dest = make_skeleton(root) + self.assertFalse(ghb_common.valid_mirror(dest)) + self.assertTrue(ghb_common.is_skeleton_mirror(dest)) + + def test_complete_mirror_is_valid(self): + with tempfile.TemporaryDirectory() as root: + dest = make_complete_mirror(root) + self.assertTrue(ghb_common.valid_mirror(dest)) + self.assertFalse(ghb_common.is_skeleton_mirror(dest)) + + def test_non_bare_and_missing_are_invalid(self): + with tempfile.TemporaryDirectory() as root: + self.assertFalse(ghb_common.valid_mirror(os.path.join(root, "nope"))) + plain = os.path.join(root, "plain") + os.makedirs(plain) + git("init", "-b", "main", cwd=plain) + self.assertFalse(ghb_common.valid_mirror(plain)) + self.assertFalse(ghb_common.is_skeleton_mirror(plain)) + + def test_skeleton_is_confirmed_partial_complete_is_not(self): + # clone_all may clear a skeleton and re-clone (#3238 + + # design rule 2); a complete mirror must never be cleared. + with tempfile.TemporaryDirectory() as root: + skeleton = make_skeleton(root) + self.assertTrue(clone_all.dest_is_confirmed_partial(skeleton)) + with tempfile.TemporaryDirectory() as root: + dest = make_complete_mirror(root) + self.assertFalse(clone_all.dest_is_confirmed_partial(dest)) + + def test_manifest_reports_skeleton_missing(self): + with tempfile.TemporaryDirectory() as root: + dest = make_skeleton(root) + plan = [{"repo": "owner/repo", "size_kb": 1}] + with open(os.path.join(root, "plan.json"), "w") as f: + json.dump(plan, f) + with ( + patch.object(manifest_mod, "load_config", return_value={}), + patch.object( + manifest_mod, + "mirror_path", + side_effect=lambda _r, _repo: dest, + ), + contextlib.redirect_stderr(io.StringIO()), + ): + m = manifest_mod.build(root) + self.assertEqual(m["mirrors"]["owner/repo"]["status"], "missing") + self.assertEqual(m["totals"], {"mirrored": 0, "missing": 1, "disk_kb": 0}) + + +class MissingAlarmTests(unittest.TestCase): + def run_fetch_repo(self, state, day, valid, outcome=None): + def fake_strftime(fmt): + if fmt == "%Y-%m-%d": + return day + return day + "T12:00:00+0000" + + patches = [ + patch.object(fetch_mirrors, "mirror_path", return_value="/mirror"), + patch.object(fetch_mirrors, "valid_mirror", return_value=valid), + patch.object(fetch_mirrors.time, "strftime", side_effect=fake_strftime), + ] + if outcome is not None: + patches.append( + patch.object( + fetch_mirrors.subprocess, + "run", + return_value=SimpleNamespace( + returncode=0 if outcome == "ok" else 1, + stdout="", + stderr="" if outcome == "ok" else "boom", + ), + ) + ) + with contextlib.ExitStack() as stack: + for p in patches: + stack.enter_context(p) + return fetch_mirrors.fetch_repo("/root", "owner/repo", state) + + def test_missing_days_accumulate_on_the_failure_streak(self): + state = {} + for day in ("2026-01-05", "2026-01-06", "2026-01-07"): + self.assertEqual( + self.run_fetch_repo(state, day, valid=False), "missing" + ) + self.assertEqual( + state["owner/repo"]["fail_days"], + ["2026-01-05", "2026-01-06", "2026-01-07"], + ) + self.assertIn("missing", state["owner/repo"]["last_error"]) + + def test_missing_streak_reaches_chronic_exit(self): + """End to end through main(): three missing days -> exit 1.""" + with tempfile.TemporaryDirectory() as root: + day = [None] + + def fake_strftime(fmt): + if fmt == "%Y-%m-%d": + return day[0] + return day[0] + "T12:00:00+0000" + + codes = [] + 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"), + patch.object(fetch_mirrors.time, "strftime", side_effect=fake_strftime), + contextlib.redirect_stdout(io.StringIO()), + ): + for d in ("2026-01-05", "2026-01-06", "2026-01-07"): + day[0] = d + codes.append( + fetch_mirrors.main(["fetch_mirrors.py", "owner/repo"]) + ) + self.assertEqual(codes, [0, 0, 1]) + + def test_return_to_ok_clears_the_missing_record(self): + state = {} + for day in ("2026-01-05", "2026-01-06"): + self.run_fetch_repo(state, day, valid=False) + res = self.run_fetch_repo(state, "2026-01-07", valid=True, outcome="ok") + self.assertEqual(res, "ok") + self.assertEqual(state["owner/repo"]["fail_days"], []) + + +class AtomicStateTests(unittest.TestCase): + def test_save_json_roundtrip_and_last_good(self): + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "state.json") + ghb_common.save_json(path, {"a/b": {"fail_days": []}}) + ghb_common.save_json(path, {"a/b": {"fail_days": ["2026-01-05"]}}) + with open(path) as f: + self.assertEqual(json.load(f), {"a/b": {"fail_days": ["2026-01-05"]}}) + with open(path + ghb_common.LAST_GOOD_SUFFIX) as f: + self.assertEqual(json.load(f), {"a/b": {"fail_days": []}}) + + def test_torn_file_falls_back_to_last_good_loudly(self): + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "state.json") + ghb_common.save_json(path, {"a/b": {"v": 1}}) + ghb_common.save_json(path, {"a/b": {"v": 2}}) + with open(path, "w") as f: + f.write('{"a/b": {"v": ') # torn mid-object + value, problems = ghb_common.load_json_tolerant(path, {}, "state.json") + self.assertEqual(value, {"a/b": {"v": 1}}) + self.assertTrue(any("torn" in p for p in problems)) + + def test_torn_file_without_last_good_is_empty_not_fatal(self): + with tempfile.TemporaryDirectory() as root: + with open(os.path.join(root, "state.json"), "w") as f: + f.write('{"a/b": ') + state, problems = ghb_common.load_state(root) + self.assertEqual(state, {}) + self.assertTrue(any("state.json" in p for p in problems)) + with open(os.path.join(root, "plan.json"), "w") as f: + f.write('[{"repo": "a/b"') + plan, problems = ghb_common.load_plan(root) + self.assertEqual(plan, []) + self.assertTrue(any("plan.json" in p for p in problems)) + + def test_failed_replace_leaves_previous_file_intact(self): + # A writer killed/replaced mid-dump never truncates the live + # file: the temp write is separate and the replace is atomic. + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "state.json") + ghb_common.save_json(path, {"v": 1}) + with patch.object( + ghb_common.os, "replace", side_effect=OSError("killed") + ): + with self.assertRaises(OSError): + ghb_common.save_json(path, {"v": 2}) + with open(path) as f: + self.assertEqual(json.load(f), {"v": 1}) + leftovers = [n for n in os.listdir(root) if n.endswith(".tmp")] + self.assertEqual(leftovers, []) + + def test_state_lock_is_reacquirable(self): + with tempfile.TemporaryDirectory() as root: + with ghb_common.state_lock(root): + self.assertTrue(os.path.exists(os.path.join(root, "state.lock"))) + with ghb_common.state_lock(root): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/github-backup/tests/test_plan_state_shape.py b/infra/github-backup/tests/test_plan_state_shape.py index 258a7475e2..334c14adf5 100644 --- a/infra/github-backup/tests/test_plan_state_shape.py +++ b/infra/github-backup/tests/test_plan_state_shape.py @@ -210,7 +210,15 @@ def test_main_survives_state_top_level_list(self): self.assertEqual(code, 0) self.assertIn("state.json", err) with open(os.path.join(root, "state.json")) as f: - self.assertEqual(json.load(f), {}) + saved = json.load(f) + # The wrong-shape top level is still dropped as a single + # named problem (the #6637 contract); the only entry in + # the saved state is the #3270 missing-day record for + # a/b — valid_mirror is patched False in run_main, so + # the repo is missing and its unavailable day is now + # recorded instead of leaving state untouched. + self.assertEqual(list(saved), ["a/b"]) + self.assertEqual(len(saved["a/b"]["fail_days"]), 1) def test_main_survives_string_state_entry_and_poison_plan(self): with tempfile.TemporaryDirectory() as root: diff --git a/infra/github-backup/tests/test_reconcile_clone_pass.py b/infra/github-backup/tests/test_reconcile_clone_pass.py index d890864d1c..d9a3c2fab6 100644 --- a/infra/github-backup/tests/test_reconcile_clone_pass.py +++ b/infra/github-backup/tests/test_reconcile_clone_pass.py @@ -27,9 +27,31 @@ def bare_mirror(root, repo): + """A REAL valid mirror: bare + one commit on refs/heads/main. + + Since #3238 a bare skeleton (zero refs) is NOT a valid mirror — + validity requires a resolvable HEAD — so a fixture mirror that + must count as present needs history. + """ path = os.path.join(root, repo + ".git") os.makedirs(os.path.dirname(path), exist_ok=True) subprocess.run(["git", "init", "--bare", "-q", path], check=True) + env = { + **os.environ, + "GIT_AUTHOR_NAME": "ghb-test", + "GIT_AUTHOR_EMAIL": "ghb-test@example.invalid", + "GIT_COMMITTER_NAME": "ghb-test", + "GIT_COMMITTER_EMAIL": "ghb-test@example.invalid", + } + tree = subprocess.run( + ["git", "-C", path, "mktree"], input="", capture_output=True, text=True, check=True + ).stdout.strip() + commit = subprocess.run( + ["git", "-C", path, "commit-tree", tree, "-m", "seed"], + capture_output=True, text=True, check=True, env=env, + ).stdout.strip() + subprocess.run(["git", "-C", path, "update-ref", "refs/heads/main", commit], check=True) + subprocess.run(["git", "-C", path, "symbolic-ref", "HEAD", "refs/heads/main"], check=True) def plan_item(repo, parent=None): diff --git a/infra/github-backup/tests/test_reconcile_retention.py b/infra/github-backup/tests/test_reconcile_retention.py index 3b4af93a3d..24b688a7d1 100644 --- a/infra/github-backup/tests/test_reconcile_retention.py +++ b/infra/github-backup/tests/test_reconcile_retention.py @@ -8,7 +8,8 @@ the plan as before. Drives the real reconcile.main() with inventory stubbed, against a -temp backup root holding real (empty) bare mirrors. +temp backup root holding real bare mirrors (one commit each — a +zero-ref skeleton is not a valid mirror since #3238). Run: python3 infra/github-backup/tests/test_reconcile_retention.py """ @@ -24,9 +25,31 @@ def bare_mirror(root, repo): + """A REAL valid mirror: bare + one commit on refs/heads/main. + + Since #3238 a bare skeleton (zero refs) is NOT a valid mirror — + validity requires a resolvable HEAD — so a fixture mirror that + must count as present needs history. + """ path = os.path.join(root, repo + ".git") os.makedirs(os.path.dirname(path), exist_ok=True) subprocess.run(["git", "init", "--bare", "-q", path], check=True) + env = { + **os.environ, + "GIT_AUTHOR_NAME": "ghb-test", + "GIT_AUTHOR_EMAIL": "ghb-test@example.invalid", + "GIT_COMMITTER_NAME": "ghb-test", + "GIT_COMMITTER_EMAIL": "ghb-test@example.invalid", + } + tree = subprocess.run( + ["git", "-C", path, "mktree"], input="", capture_output=True, text=True, check=True + ).stdout.strip() + commit = subprocess.run( + ["git", "-C", path, "commit-tree", tree, "-m", "seed"], + capture_output=True, text=True, check=True, env=env, + ).stdout.strip() + subprocess.run(["git", "-C", path, "update-ref", "refs/heads/main", commit], check=True) + subprocess.run(["git", "-C", path, "symbolic-ref", "HEAD", "refs/heads/main"], check=True) def plan_item(repo, parent=None):