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
76 changes: 67 additions & 9 deletions infra/github-backup/bin/reconcile.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
plan.json + MANIFEST.json.

Webhooks (the App + Worker) are the freshness layer; this sweep is what
guarantees nothing is missed. Exit code is non-zero only on owner-level
inventory failure, so the timer unit surfaces it.
guarantees nothing is missed. Exit code is non-zero on owner-level
inventory failure or a failed clone pass (#3300), so the timer unit
surfaces either.
"""

import json, os, subprocess, sys, time
Expand Down Expand Up @@ -48,6 +49,23 @@ def depth(item):
return sorted(plan, key=lambda it: (depth(it), it["repo"]))


def _clone_status_entries(root, offset):
"""Parse clone-status.jsonl entries appended after byte offset."""
path = os.path.join(root, "clone-status.jsonl")
entries = []
try:
with open(path) as f:
f.seek(offset)
for line in f:
try:
entries.append(json.loads(line))
except Exception:
pass
except OSError:
pass
return entries


def main():
cfg = load_config()
root = backup_root(cfg)
Expand Down Expand Up @@ -117,11 +135,16 @@ def main():
if pending:
lines.append("## pending Drew review (giant forks, NOT cloned)")
lines += [f"- {p['repo']} — {p['reason']}" for p in pending] + [""]
report_path = os.path.join(root, f"reconcile-{today}.md")
with open(report_path, "w") as f:
f.write("\n".join(lines))
print("\n".join(lines))
# Clone pass (#3300): run BEFORE the report is written so its
# outcome lands in the dated report, and propagate a non-zero exit
# instead of dropping clone_all's verdict on the floor.
clone_rc = None
clone_failures = []
if missing:
status_path = os.path.join(root, "clone-status.jsonl")
status_offset = (
os.path.getsize(status_path) if os.path.exists(status_path) else 0
)
r = subprocess.run(
[
sys.executable,
Expand All @@ -130,10 +153,45 @@ def main():
),
]
)
if r.returncode != 0:
print("clone pass had failures; see clone-status.jsonl")
clone_rc = r.returncode
if clone_rc != 0:
clone_failures = sorted(
{
e["repo"]
for e in _clone_status_entries(root, status_offset)
if e.get("status") == "fail" and e.get("repo")
}
)
if clone_rc is None:
lines.append("- clone pass: not run (no mirrors missing)")
elif clone_rc == 0:
lines.append(
f"- clone pass: succeeded ({len(missing)} mirrors attempted)"
)
else:
lines.append(
f"- clone pass: FAILED (clone_all exit {clone_rc}; "
f"{len(missing)} mirrors attempted)"
)
lines.append("")
if clone_rc not in (None, 0):
lines.append("## clone pass failures")
if clone_failures:
lines += [f"- {r}" for r in clone_failures]
else:
lines.append(
"- no per-repo failures recorded in clone-status.jsonl; "
"see clone_all output"
)
lines.append("")
report_path = os.path.join(root, f"reconcile-{today}.md")
with open(report_path, "w") as f:
f.write("\n".join(lines))
print("\n".join(lines))
if clone_rc not in (None, 0):
print("clone pass had failures; see clone-status.jsonl")
manifest_mod.build(root)
return 1 if errors else 0
return 1 if errors or clone_rc not in (None, 0) else 0


if __name__ == "__main__":
Expand Down
181 changes: 181 additions & 0 deletions infra/github-backup/tests/test_reconcile_clone_pass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""test_reconcile_clone_pass.py — regression test for #3300.

reconcile.py used to discard clone_all.py's non-zero exit and write its
dated report before the clone pass, so a failed mirror creation was
reported as success. Now:

- clone_all rc=1 -> reconcile exits 1 and the dated report records the
clone failure, naming the failing repos from clone-status.jsonl.
- clone_all rc=0 -> reconcile exits 0 and the report records success.
- inventory-error control -> still exits non-zero, clone pass not run.

Drives the real reconcile.main() with inventory and the clone_all
subprocess stubbed, against a temp backup root.

Run: python3 infra/github-backup/tests/test_reconcile_clone_pass.py
"""

import glob, json, os, subprocess, sys, tempfile

BIN = os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bin")
)
sys.path.insert(0, BIN)

import reconcile


def bare_mirror(root, repo):
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)


def plan_item(repo, parent=None):
return {
"repo": repo,
"reference": None,
"size_kb": 10,
"fork": False,
"parent": parent,
"branch": "main",
"head": "abc123",
"private": None,
}


def inv_repo(repo):
return {
"repo": repo,
"fork": False,
"archived": False,
"size_kb": 10,
"parent": None,
"branch": "main",
"head": "abc123",
"pushed_at": "2026-11-01T00:00:00Z",
"empty": False,
}


CFG = {
"owners": ["good-owner"],
"tier_rules": {
"include_nonforks": True,
"skip_zero_commit_repos": True,
"fork_max_size_mb": 500,
},
"exclusions": [],
"gaps": [],
}

PASS = []


def check(name, cond):
PASS.append((name, bool(cond)))
print(("PASS " if cond else "FAIL ") + name)
assert cond, name


REAL_RUN = subprocess.run


def run_scenario(clone_rc, inventory_result, with_mirror, fail_repos=()):
"""Run reconcile.main() in a fresh temp root with stubs installed.

clone_rc=None means the clone pass must not be invoked at all.
Returns (rc, report_text).
"""
root = tempfile.mkdtemp(prefix="ghb-clone-pass-test-")
item = plan_item("good-owner/newrepo")
with open(os.path.join(root, "plan.json"), "w") as f:
json.dump([item], f)
if with_mirror:
bare_mirror(root, item["repo"])

calls = []

def fake_run(cmd, *args, **kwargs):
if any(str(c).endswith("clone_all.py") for c in cmd):
calls.append(cmd)
assert clone_rc is not None, "clone pass ran unexpectedly"
# Simulate clone_all appending per-repo status records.
with open(os.path.join(root, "clone-status.jsonl"), "a") as f:
for repo in fail_repos:
f.write(json.dumps({"repo": repo, "status": "fail"}) + "\n")
if clone_rc == 0:
f.write(
json.dumps({"repo": item["repo"], "status": "ok"}) + "\n"
)
return subprocess.CompletedProcess(cmd, clone_rc)
return REAL_RUN(cmd, *args, **kwargs)

saved = (
reconcile.load_config,
reconcile.backup_root,
reconcile.inventory,
subprocess.run,
)
reconcile.load_config = lambda: CFG
reconcile.backup_root = lambda cfg=None: root
reconcile.inventory = lambda owners: inventory_result
subprocess.run = fake_run
try:
rc = reconcile.main()
finally:
(
reconcile.load_config,
reconcile.backup_root,
reconcile.inventory,
subprocess.run,
) = saved

reports = glob.glob(os.path.join(root, "reconcile-*.md"))
assert len(reports) == 1, f"expected one report, got {reports}"
report = open(reports[0]).read()
return rc, report, calls


CLEAN = ({"good-owner/newrepo": inv_repo("good-owner/newrepo")}, {})

# --- Scenario 1: clone pass fails -------------------------------------
rc, report, calls = run_scenario(
clone_rc=1,
inventory_result=CLEAN,
with_mirror=False,
fail_repos=("good-owner/newrepo",),
)
check("clone rc=1 -> reconcile exits 1", rc == 1)
check("clone pass was invoked once", len(calls) == 1)
check(
"report records the clone failure",
"clone pass: FAILED" in report and "clone_all exit 1" in report,
)
check(
"report names the failing repo",
"## clone pass failures" in report and "good-owner/newrepo" in report,
)

# --- Scenario 2: clone pass succeeds ----------------------------------
rc, report, calls = run_scenario(
clone_rc=0, inventory_result=CLEAN, with_mirror=False
)
check("clone rc=0 + clean inventory -> reconcile exits 0", rc == 0)
check("report records clone success", "clone pass: succeeded" in report)

# --- Scenario 3: inventory-error control ------------------------------
rc, report, calls = run_scenario(
clone_rc=None,
inventory_result=({}, {"good-owner": "gh api graphql: owner gone"}),
with_mirror=True,
)
check("inventory error -> reconcile still exits non-zero", rc == 1)
check("clone pass not run when nothing is missing", len(calls) == 0)
check(
"report notes clone pass not run",
"clone pass: not run" in report,
)

print(f"\n{sum(1 for _, ok in PASS if ok)}/{len(PASS)} checks passed")