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
1 change: 1 addition & 0 deletions infra/github-backup/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,4 @@ reconcile-YYYY-MM-DD.md weekly sweep reports
| `worker/` | Cloudflare Worker webhook receiver (wrangler) |
| `systemd/` | laptop user units + timers + installer |
| `docs/RUNBOOK.md` | copy-paste operations: install, add org, upgrade, DR |
| `tests/` | regression tests (plain python3, no deps) |
118 changes: 101 additions & 17 deletions infra/github-backup/bin/drain_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,32 @@
clone attempt through the normal plan if the repo is already planned.
Secrets come from the environment; the systemd unit sources them from
Bitwarden by name (see config.json app.bitwarden_secret_names).

Ack discipline (#3219): an event is acked — i.e. deleted from the Worker
queue — only once the drainer has made the mirror reflect it:

- planned repo, fetch attempted: ack iff fetch_repo returned "ok".
On "fail"/"missing" the event STAYS QUEUED for the next drain tick,
the failure is appended to fetch.log (same leading format as the
daily pass), and the coalesce stamp is NOT advanced.
- planned repo inside its coalesce window: the event stays queued
(not acked); a drain after the window passes fetches and acks it.
- unplanned repo: acked + a fetch.log note (mirror creation is the
weekly reconcile's decision).
- consecutive drain failures are counted per repo
(state key drain_fail::<repo>); at CHRONIC_DRAIN_FAILURES the failure
is logged loudly (DRAIN-CHRONIC) and the run exits non-zero so
systemd surfaces it — the event is still kept, never silently dropped.
"""
import json, os, sys, time, urllib.request
from datetime import datetime, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ghb_common import load_config, backup_root
import fetch_mirrors

COALESCE_S = 15 * 60
CHRONIC_DRAIN_FAILURES = 5


def worker_req(path, payload=None):
Expand All @@ -37,6 +55,29 @@ def worker_req(path, payload=None):
return json.loads(r.read() or b"{}")


def event_age_s(ev, now):
"""Age of a queued event in seconds, or None if its ts is unusable.

The Worker stamps ts with `new Date().toISOString()`; accept epoch
numbers too so a format change degrades to 'unknown', not a crash.
"""
ts = ev.get("ts")
if isinstance(ts, (int, float)):
return max(0, int(now - ts))
if isinstance(ts, str):
try:
t = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%fZ") \
.replace(tzinfo=timezone.utc).timestamp()
return max(0, int(now - t))
except ValueError:
try:
t = datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
return max(0, int(now - t))
except ValueError:
return None
return None


def main():
cfg = load_config()
root = backup_root(cfg)
Expand All @@ -48,33 +89,76 @@ def main():
print("queue empty")
return 0
now = time.time()
to_fetch, ack = [], []
stamp = time.strftime("%Y-%m-%dT%H:%M:%S%z")
log_path = os.path.join(root, "fetch.log")
plan_path = os.path.join(root, "plan.json")
planned = {p["repo"] for p in json.load(open(plan_path))} \
if os.path.exists(plan_path) else set()

def log(line):
with open(log_path, "a") as f:
f.write(line + "\n")

# Group events by repo; events without a repo carry nothing the
# drainer can act on, so they are acked immediately.
by_repo, ack = {}, []
for ev in events:
repo = ev.get("repo")
ack.append(ev["id"])
if not repo:
ack.append(ev["id"])
continue
by_repo.setdefault(repo, []).append(ev)

fetched, failed, unplanned, pending = [], [], [], []
for repo in sorted(by_repo):
evs = by_repo[repo]
ids = [e["id"] for e in evs]
ages = [a for a in (event_age_s(e, now) for e in evs) if a is not None]
age_note = f"oldest event age {max(ages)}s" if ages else "event age unknown"
if repo not in planned:
log(f"{stamp} {repo} webhook event for unplanned repo — "
f"left for weekly reconcile")
ack.extend(ids)
unplanned.append(repo)
continue
key = f"drain_last::{repo}"
if now - state.get(key, 0) < COALESCE_S:
# Inside the coalesce window: keep the event queued. A drain
# after the window passes will fetch (and then ack) it.
pending.append(repo)
continue
state[key] = now
if repo not in to_fetch:
to_fetch.append(repo)
fetched = []
for repo in to_fetch:
plan_path = os.path.join(root, "plan.json")
planned = {p["repo"] for p in json.load(open(plan_path))} if os.path.exists(plan_path) else set()
if repo in planned:
fetch_mirrors.fetch_repo(root, repo, state)
res = fetch_mirrors.fetch_repo(root, repo, state)
if res == "ok":
state[key] = now
state.pop(f"drain_fail::{repo}", None)
ack.extend(ids)
fetched.append(repo)
else:
with open(os.path.join(root, "fetch.log"), "a") as f:
f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {repo} "
f"webhook event for unplanned repo — left for weekly reconcile\n")
continue
fkey = f"drain_fail::{repo}"
fs = state.setdefault(fkey, {"count": 0, "first": now})
fs["count"] += 1
fs["last"] = now
err = (state.get(repo) or {}).get("last_error", "")
log(f"{stamp} {repo} {res} {err} (drain: {age_note}, "
f"consecutive drain failures {fs['count']})")
if fs["count"] >= CHRONIC_DRAIN_FAILURES:
log(f"{stamp} {repo} DRAIN-CHRONIC {fs['count']} consecutive "
f"drain failures — event(s) kept queued, needs attention")
failed.append({"repo": repo, "result": res,
"consecutive_failures": fs["count"]})
Comment on lines +147 to +148

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 Allow queue polling to progress past retained failed events

If the queue contains 500 older events for unavailable planned mirrors, retaining those events now prevents later events for healthy repositories from being processed. The Worker in infra/github-backup/worker/src/index.js:55–61 returns only the first 500 entries and neither follows nor exposes a pagination cursor, so every drain retries the same failed batch until recovery or expiration of the seven-day TTL. I reproduced this with 500 missing-mirror events followed by one healthy-repository event: repeated drains never attempted the healthy repository. Preserve failed events, but add pagination or another mechanism that allows polling to advance past them.

Useful? React with 👍 / 👎.

with open(state_path, "w") as f:
json.dump(state, f, indent=0)
worker_req(cfg["worker"]["queue_poll_path"] + "/ack", {"ids": ack})
print(json.dumps({"events": len(events), "fetched": fetched}))
if ack:
worker_req(cfg["worker"]["queue_poll_path"] + "/ack", {"ids": ack})
print(json.dumps({"events": len(events), "fetched": fetched,
"failed": failed, "unplanned": unplanned,
"coalesced_pending": pending, "acked": len(ack)}))
chronic = [f["repo"] for f in failed
if f["consecutive_failures"] >= CHRONIC_DRAIN_FAILURES]
if chronic:
print(f"drain: chronic failures (events kept queued): {chronic}",
file=sys.stderr)
return 1
return 0


Expand Down
173 changes: 173 additions & 0 deletions infra/github-backup/tests/test_drain_queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""test_drain_queue.py — regression tests for #3219 ack discipline.

Drives the real drain_queue.main() with a stub Worker and a stub
fetch_mirrors.fetch_repo, against a temp backup root:

success -> event acked, coalesce stamp set
fetch "fail" -> event NOT acked, fetch.log line written, no stamp
fetch "missing" -> event NOT acked, fetch.log line written, no stamp
unplanned repo -> event acked + fetch.log note (behavior preserved)
inside coalesce -> event NOT acked, no fetch attempted
chronic failures -> run exits non-zero, DRAIN-CHRONIC logged, still queued

Run: python3 infra/github-backup/tests/test_drain_queue.py
"""
import json, os, sys, tempfile, time
from datetime import datetime, timedelta, timezone

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

import drain_queue
import fetch_mirrors


def iso_age(seconds):
t = datetime.now(timezone.utc) - timedelta(seconds=seconds)
return t.strftime("%Y-%m-%dT%H:%M:%S.") + f"{t.microsecond // 1000:03d}Z"


class Harness:
"""One drain run against a stub Worker + stub fetch."""

def __init__(self, events, planned, fetch_results, initial_state=None):
self.root = tempfile.mkdtemp(prefix="ghb-drain-test-")
with open(os.path.join(self.root, "plan.json"), "w") as f:
json.dump([{"repo": r} for r in planned], f)
if initial_state is not None:
with open(os.path.join(self.root, "state.json"), "w") as f:
json.dump(initial_state, f)
self.events = events
self.fetch_results = fetch_results # repo -> "ok"|"fail"|"missing"
self.fetch_calls = []
self.ack_calls = []
self._saved = (drain_queue.worker_req, drain_queue.load_config,
drain_queue.backup_root, fetch_mirrors.fetch_repo)
drain_queue.worker_req = self._worker_req
drain_queue.load_config = lambda: {"worker": {"queue_poll_path": "/queue"}}
drain_queue.backup_root = lambda cfg=None: self.root
fetch_mirrors.fetch_repo = self._fetch_repo

def _worker_req(self, path, payload=None):
if path.endswith("/ack"):
self.ack_calls.append(payload["ids"])
return {}
return {"events": self.events}

def _fetch_repo(self, root, repo, state):
self.fetch_calls.append(repo)
res = self.fetch_results[repo]
st = state.setdefault(repo, {})
if res == "ok":
st["last_fetch"] = time.time()
st["fail_days"] = []
elif res == "fail":
st["last_error"] = "stub fetch boom"
return res

def run(self):
try:
return drain_queue.main()
finally:
(drain_queue.worker_req, drain_queue.load_config,
drain_queue.backup_root,
fetch_mirrors.fetch_repo) = self._saved

def acked_ids(self):
return [i for call in self.ack_calls for i in call]

def state(self):
with open(os.path.join(self.root, "state.json")) as f:
return json.load(f)

def fetch_log(self):
p = os.path.join(self.root, "fetch.log")
return open(p).read() if os.path.exists(p) else ""


def ev(eid, repo, age=60):
return {"id": eid, "repo": repo, "event": "push", "ts": iso_age(age)}


PASS = []


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


# 1. success -> acked + stamped
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "ok"})
check("success: exit 0", h.run() == 0)
check("success: event acked", h.acked_ids() == ["e1"])
check("success: coalesce stamp set", "drain_last::owner/repo" in h.state())
check("success: no fetch.log", h.fetch_log() == "")

# 2. fetch fail -> NOT acked, logged with age, no stamp, failure counted
h = Harness([ev("e1", "owner/repo", age=600)], ["owner/repo"],
{"owner/repo": "fail"})
check("fail: exit 0 (not yet chronic)", h.run() == 0)
check("fail: event NOT acked", h.acked_ids() == [])
log = h.fetch_log()
check("fail: fetch.log line", "owner/repo fail" in log and "stub fetch boom" in log)
check("fail: event age in log", "oldest event age" in log)
check("fail: no coalesce stamp", "drain_last::owner/repo" not in h.state())
check("fail: failure counted",
h.state()["drain_fail::owner/repo"]["count"] == 1)

# 3. missing mirror -> NOT acked, logged
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "missing"})
check("missing: exit 0", h.run() == 0)
check("missing: event NOT acked", h.acked_ids() == [])
check("missing: fetch.log line", "owner/repo missing" in h.fetch_log())
check("missing: no coalesce stamp", "drain_last::owner/repo" not in h.state())

# 4. unplanned repo -> acked + noted, no fetch attempted
h = Harness([ev("e1", "other/repo")], ["owner/repo"], {})
check("unplanned: exit 0", h.run() == 0)
check("unplanned: event acked", h.acked_ids() == ["e1"])
check("unplanned: fetch.log note", "unplanned repo" in h.fetch_log())
check("unplanned: no fetch attempted", h.fetch_calls == [])

# 5. inside coalesce window -> NOT acked, no fetch; window passed -> fetched
now = time.time()
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "ok"},
initial_state={"drain_last::owner/repo": now})
check("coalesce: exit 0", h.run() == 0)
check("coalesce: event NOT acked yet", h.acked_ids() == [])
check("coalesce: no fetch attempted", h.fetch_calls == [])
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "ok"},
initial_state={"drain_last::owner/repo": now - drain_queue.COALESCE_S - 1})
check("coalesce-expired: exit 0", h.run() == 0)
check("coalesce-expired: fetched + acked",
h.fetch_calls == ["owner/repo"] and h.acked_ids() == ["e1"])

# 6. chronic: threshold-th consecutive failure -> exit 1, loud log, still queued
n = drain_queue.CHRONIC_DRAIN_FAILURES
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "fail"},
initial_state={"drain_fail::owner/repo": {"count": n - 1, "first": now}})
check("chronic: exit non-zero", h.run() == 1)
check("chronic: event still NOT acked", h.acked_ids() == [])
check("chronic: DRAIN-CHRONIC logged", "DRAIN-CHRONIC" in h.fetch_log())
check("chronic: count advanced", h.state()["drain_fail::owner/repo"]["count"] == n)

# 7. recovery: success clears the failure counter
h = Harness([ev("e1", "owner/repo")], ["owner/repo"], {"owner/repo": "ok"},
initial_state={"drain_fail::owner/repo": {"count": 3, "first": now}})
check("recovery: exit 0", h.run() == 0)
check("recovery: acked", h.acked_ids() == ["e1"])
check("recovery: failure counter cleared",
"drain_fail::owner/repo" not in h.state())

# 8. mixed batch: one ok, one fail, one unplanned -> only ok+unplanned acked
h = Harness([ev("e1", "a/ok"), ev("e2", "b/bad"), ev("e3", "c/new")],
["a/ok", "b/bad"], {"a/ok": "ok", "b/bad": "fail"})
check("mixed: exit 0", h.run() == 0)
check("mixed: acked = ok + unplanned only",
sorted(h.acked_ids()) == ["e1", "e3"])

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