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
5 changes: 3 additions & 2 deletions infra/github-backup/bin/clone_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
59 changes: 52 additions & 7 deletions infra/github-backup/bin/fetch_mirrors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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):
Expand All @@ -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"] = []
Expand All @@ -81,15 +119,17 @@ 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]


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)
Expand All @@ -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

Expand Down
105 changes: 105 additions & 0 deletions infra/github-backup/bin/ghb_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,111 @@ 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.

Bookkeeping keys written by the webhook drainer are state too,
under their own shapes: "drain_last::<repo>" is a numeric
timestamp and "drain_fail::<repo>" 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 {}, [
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 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)}, "
f"expected an object — dropped"
Comment on lines +196 to +209

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve webhook-drainer timestamps when validating state

When the webhook drainer has successfully fetched a repository, state.json legitimately contains a numeric drain_last::<repo> timestamp, written by drain_queue.py:251–259 and used to enforce its 15-minute coalescing window. This validator treats those timestamps as malformed entries and drops them. Because fetch_mirrors.main() writes the sanitized state back to disk, every daily fetch erases the drainer's coalescing metadata, allowing the next webhook drain to fetch repositories again inside that window. Preserve and validate these bookkeeping entries separately from per-repository objects.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e06082 — thank you, this was a real catch. validate_state now validates the drainer's bookkeeping keys under their own shapes and preserves them: drain_last::<repo> must be a number (bool excluded) and drain_fail::<repo> stays on the object path; a wrong-shaped drain_last:: is named and dropped instead of silently kept. Two regression tests added (test_drain_bookkeeping_entries_are_preserved, test_drain_last_with_wrong_shape_is_named_and_dropped); full github-backup suite green, including test_drain_queue.py 82/82.

)
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).
Expand Down
10 changes: 5 additions & 5 deletions infra/github-backup/bin/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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:
Expand Down
Loading
Loading