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
47 changes: 47 additions & 0 deletions infra/github-backup/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
12 changes: 10 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, 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
Expand Down Expand Up @@ -58,15 +58,23 @@ 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
confirmed partial, and the caller preserves the destination.
"""
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,
Expand Down
12 changes: 9 additions & 3 deletions infra/github-backup/bin/drain_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
25 changes: 22 additions & 3 deletions infra/github-backup/bin/fetch_mirrors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
Loading
Loading