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
18 changes: 11 additions & 7 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, load_plan, report_problems
from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb, load_plan, report_problems, clone_status_record

PAR = 4
TIMEOUT = 5400
Expand Down Expand Up @@ -92,12 +92,16 @@ def log_status(rec):
ok_prev = set()
if os.path.exists(status_path):
for line in open(status_path):
try:
r = json.loads(line)
if r.get("status") == "ok":
ok_prev.add(r["repo"])
except Exception:
pass
# Shared line contract: ghb_common.clone_status_record
# (#6606) — non-record lines are ignored, never crash.
r = clone_status_record(line)
if (
r is not None
and r.get("status") == "ok"
and isinstance(r.get("repo"), str)
and r["repo"]
):
ok_prev.add(r["repo"])

def clone_one(item, ref_ok):
repo = item["repo"]
Expand Down
24 changes: 24 additions & 0 deletions infra/github-backup/bin/ghb_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,30 @@ def load_state(root):
return validate_state(json.load(f))


def clone_status_record(line):
"""The clone-status.jsonl line contract — the ONE place it is stated
(#6606). Both readers of clone-status.jsonl (clone_all.py and
reconcile.py) go through this helper, so they cannot disagree:

each line is a JSON *object* (a status record like
{"repo": ..., "status": ...}). A line that does not parse as JSON,
and a line that parses as valid JSON of any other shape (number,
string, list, null, bool — a torn/interleaved append, a hand edit,
a future writer change), is NOT a record: this returns None and
the reader ignores the line exactly as it ignores unparseable
lines. Records are returned as-is; missing keys are the caller's
existing concern, and a caller that puts a field value into a set
must require the field's expected type (a record can still carry
a malformed field value, e.g. a list "repo" — both current
consumers require a string repo).
"""
try:
value = json.loads(line)
except Exception:
return None
return value if isinstance(value, dict) else None


def report_problems(problems):
"""Name every shape problem on stderr; returns the count."""
for problem in problems:
Expand Down
20 changes: 14 additions & 6 deletions infra/github-backup/bin/reconcile.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
build_plan,
valid_mirror,
mirror_path,
clone_status_record,
)
import manifest as manifest_mod

Expand All @@ -50,17 +51,22 @@ def depth(item):


def _clone_status_entries(root, offset):
"""Parse clone-status.jsonl entries appended after byte offset."""
"""Parse clone-status.jsonl entries appended after byte offset.

Per-line shape tolerance is the shared contract in
ghb_common.clone_status_record (#6606): unparseable lines and
valid-JSON non-object lines are both ignored, so a poison line
can never crash the failed-clone consumer below.
"""
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
record = clone_status_record(line)
if record is not None:
entries.append(record)
except OSError:
pass
return entries
Expand Down Expand Up @@ -159,7 +165,9 @@ def main():
{
e["repo"]
for e in _clone_status_entries(root, status_offset)
if e.get("status") == "fail" and e.get("repo")
if e.get("status") == "fail"
and isinstance(e.get("repo"), str)
and e.get("repo")
}
)
if clone_rc is None:
Expand Down
51 changes: 50 additions & 1 deletion infra/github-backup/tests/test_reconcile_clone_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def check(name, cond):
REAL_RUN = subprocess.run


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

clone_rc=None means the clone pass must not be invoked at all.
Expand All @@ -103,6 +103,8 @@ def fake_run(cmd, *args, **kwargs):
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 line in extra_lines:
f.write(line + "\n")
for repo in fail_repos:
f.write(json.dumps({"repo": repo, "status": "fail"}) + "\n")
if clone_rc == 0:
Expand Down Expand Up @@ -174,4 +176,51 @@ def fake_run(cmd, *args, **kwargs):
"clone pass: not run" in report,
)

# --- Scenario 4: failed clone pass with a poisoned status file (#6606) --
# Valid-JSON non-dict lines and an unparseable line land in
# clone-status.jsonl after the offset, before the real fail record.
# The failed-clone consumer must ignore them (shared contract:
# ghb_common.clone_status_record), still name the real failure in the
# dated report, and still exit 1 — no AttributeError traceback.
rc, report, calls = run_scenario(
clone_rc=1,
inventory_result=CLEAN,
with_mirror=False,
fail_repos=("good-owner/newrepo",),
extra_lines=("123", '"fail"', '["owner/bad"]', "null", "true", "{torn line"),
)
check("poisoned status file -> reconcile still exits 1", rc == 1)
check(
"poisoned status file -> report still names the real failing repo",
"## clone pass failures" in report and "good-owner/newrepo" in report,
)
check(
"poison shapes never surface as repos",
"owner/bad" not in report,
)

# Direct reader check: _clone_status_entries keeps only dict records;
# the consumer expression over them returns exactly the valid fails.
root = tempfile.mkdtemp(prefix="ghb-status-shape-test-")
with open(os.path.join(root, "clone-status.jsonl"), "w") as f:
f.write(json.dumps({"repo": "owner/bad", "status": "fail"}) + "\n")
f.write("{torn line\n")
for shape in ("123", '"x"', "[]", "null", "true"):
f.write(shape + "\n")
f.write(json.dumps({"repo": "owner/good", "status": "ok"}) + "\n")
f.write(json.dumps({"status": "fail"}) + "\n")
f.write(json.dumps({"repo": ["owner/bad2"], "status": "fail"}) + "\n")
entries = reconcile._clone_status_entries(root, 0)
check("reader keeps only dict records", all(isinstance(e, dict) for e in entries) and len(entries) == 4)
consumer = sorted(
{
e["repo"]
for e in entries
if e.get("status") == "fail"
and isinstance(e.get("repo"), str)
and e.get("repo")
}
)
check("consumer returns exactly the valid fail repos", consumer == ["owner/bad"])

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