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
79 changes: 78 additions & 1 deletion nixos/home/laptop-backups-watchdog.sh
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,37 @@
# max-age-hours (default 26, a little over one daily period; the
# module option services.laptop-backups.watchdog
# .maxAgeHours feeds this argument).
# jobs comma-separated subset of dashboard,repo-archive,state,opencode-db,cold-store
# jobs comma-separated subset of
# dashboard,repo-archive,state,opencode-db,cold-store,mesh
# (default dashboard,repo-archive). The module passes only the jobs
# whose enable flag is on: a disabled job has no
# record and no timer, so requiring them would fail
# the watchdog forever in a supported configuration.
# Test hooks: LAPTOP_BACKUPS_RECORD overrides the record path and
# `systemctl` is resolved via PATH, so the suite can stub both.
#
# mesh (code#13463): restore verification, not just backup freshness.
# The mesh rotation writes one JSON record per leg x store pair to
# $HOME/backups/mesh/restore-verification/<leg>.<store>.json:
# {"leg":"class-a","store":"r2","verified_at":"2026-11-20T12:00:00Z",
# "result":"ok","detail":"restored 12 dbs to /var/tmp/scratch; row counts match manifest"}
# Every declared leg x store pair must have a record whose result is
# ok and whose verification is no older than a quarter (the rotation's
# coverage promise, design §9: every combination at least quarterly),
# so a stalled rotation or a failed restore is named by leg and store.
MAX_AGE_HOURS="${1:-26}"
JOBS="${2:-dashboard,repo-archive}"
want_job() { case ",$JOBS," in *",$1,"*) return 0 ;; *) return 1 ;; esac }
RECORD="${LAPTOP_BACKUPS_RECORD:-$HOME/backups/dashboard/.last-run.json}"
MANIFEST="${COLD_STORE_MANIFEST:-$HOME/.config/cold-store/manifest.sqlite}"
# mesh restore-verification records (code#13463). Legs and stores are
# the design's topology (§2); a new leg adds its name here and to the
# rotation. A quarter is 91 days ~= 2184h; 2200h is a little over,
# matching the daily threshold's slack.
MESH_RECORDS="${LAPTOP_BACKUPS_MESH_RECORDS:-$HOME/backups/mesh/restore-verification}"
MESH_MAX_AGE_HOURS="${LAPTOP_BACKUPS_MESH_MAX_AGE_HOURS:-2200}"
MESH_LEGS="${LAPTOP_BACKUPS_MESH_LEGS:-class-a,class-b,replicate,class-d,class-e,embeds}"
MESH_STORES="${LAPTOP_BACKUPS_MESH_STORES:-r2,laptop,drive}"
NOW_EPOCH="$(date +%s)"
MAX_AGE_SEC=$((MAX_AGE_HOURS * 3600))
# A timestamp further in the future than this tolerance cannot be a
Expand Down Expand Up @@ -321,6 +340,64 @@ PYEOF
fi
fi

# --- (g) mesh restore-verification records (code#13463) ----------------------
# Backup-verified is not restore-verified (design §9). The rotation
# records each leg x store restore on its own schedule; this check
# reads those records only. A record that is missing, unreadable,
# failed, or older than a quarter names the leg and the store, so a
# stalled rotation cannot pass as a healthy mesh.
if want_job mesh; then
if [ ! -d "$MESH_RECORDS" ]; then
complain "mesh restore verification: no records directory at $MESH_RECORDS"
else
IFS=',' read -r -a mesh_legs <<<"$MESH_LEGS"
IFS=',' read -r -a mesh_stores <<<"$MESH_STORES"
for leg in "${mesh_legs[@]}"; do
[ -n "$leg" ] || continue
for store in "${mesh_stores[@]}"; do
[ -n "$store" ] || continue
mesh_record="$MESH_RECORDS/$leg.$store.json"
if [ ! -f "$mesh_record" ]; then
complain "mesh restore verification: leg=$leg store=$store: no record at $mesh_record (never verified)"
continue
fi
mesh_verdict="$(
RECORD="$mesh_record" LEG="$leg" STORE="$store" NOW_EPOCH="$NOW_EPOCH" \
MESH_MAX_AGE_SEC=$((MESH_MAX_AGE_HOURS * 3600)) SKEW_TOLERANCE_SEC="$SKEW_TOLERANCE_SEC" \
python3 - <<'PYEOF' 2>/dev/null
import json, os
from datetime import datetime, timezone
try:
rec = json.load(open(os.environ["RECORD"]))
verified = datetime.strptime(rec["verified_at"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
except Exception:
print("unreadable")
raise SystemExit
if rec.get("leg") != os.environ["LEG"] or rec.get("store") != os.environ["STORE"]:
print(f"record identifies leg={rec.get('leg')} store={rec.get('store')} but is filed as leg={os.environ['LEG']} store={os.environ['STORE']}")
raise SystemExit
if rec.get("result") != "ok":
print(f"last verification failed result={rec.get('result')} verified_at={rec.get('verified_at')} detail={rec.get('detail')}")
raise SystemExit
age = int(os.environ["NOW_EPOCH"]) - int(verified.timestamp())
if age < -int(os.environ["SKEW_TOLERANCE_SEC"]):
print(f"future verified_at={rec.get('verified_at')} is {-age}s ahead of now (skew tolerance {os.environ['SKEW_TOLERANCE_SEC']}s)")
elif age > int(os.environ["MESH_MAX_AGE_SEC"]):
print(f"stale verified_at={rec.get('verified_at')} age_days={age // 86400} (quarterly threshold {int(os.environ['MESH_MAX_AGE_SEC']) // 86400}d)")
else:
print("ok")
PYEOF
)"
case "$mesh_verdict" in
ok) ;;
unreadable | "") complain "mesh restore verification: leg=$leg store=$store: record at $mesh_record is unreadable" ;;
*) complain "mesh restore verification: leg=$leg store=$store: $mesh_verdict" ;;
esac
done
done
fi
fi

if [ "$violations" -gt 0 ]; then
echo "laptop-backups-watchdog: $violations violation(s)" >&2
exit 1
Expand Down
49 changes: 49 additions & 0 deletions nixos/home/laptop-backups-watchdog.test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ run_watchdog_jobs() { # $1 jobs list
PATH="$BIN:$PATH" bash "$SCRIPT" 26 "$1" >"$TMP_ROOT/out.log" 2>&1
RC=$?
}
run_watchdog_mesh() { # mesh records are independently fixture-controlled
HOME="$HOME_DIR" LAPTOP_BACKUPS_RECORD="$RECORD" WATCHDOG_STUB_TRIGGERS="$TRIG" \
LAPTOP_BACKUPS_MESH_RECORDS="$MESH_RECORDS" \
PATH="$BIN:$PATH" bash "$SCRIPT" 26 mesh >"$TMP_ROOT/out.log" 2>&1
RC=$?
}

expect_ok() {
if [[ $RC -eq 0 ]]; then
Expand Down Expand Up @@ -334,6 +340,49 @@ set_cs_result failure
run_watchdog
expect_ok cs-not-in-default-jobs

# --- mesh restore-verification rotation (code#13463) ------------------------
# One record per leg x store pair is required. Fresh successful records
# cover all combinations; the record format is the rotation's durable
# evidence, not a status file synthesized by the watchdog.
MESH_RECORDS="$TMP_ROOT/mesh"
mkdir -p "$MESH_RECORDS"
write_mesh_record() { # $1 leg, $2 store, $3 result, $4 verification time
python3 - "$1" "$2" "$3" "$(iso_ago "$4")" "$MESH_RECORDS" <<'PYEOF'
import json, os, sys
leg, store, result, verified_at, root = sys.argv[1:]
with open(os.path.join(root, f"{leg}.{store}.json"), "w") as fh:
json.dump({"leg": leg, "store": store, "result": result,
"verified_at": verified_at, "detail": "scratch restore row counts match"}, fh)
PYEOF
}
for leg in class-a class-b replicate class-d class-e embeds; do
for store in r2 laptop drive; do
write_mesh_record "$leg" "$store" ok "10 days ago"
done
done
run_watchdog_mesh
expect_ok mesh-rotation-fresh

# Deliberately stalled leg: one leg/store record is older than the
# quarterly rotation bound and must be named rather than hidden by other
# fresh combinations.
write_mesh_record class-a laptop ok "100 days ago"
run_watchdog_mesh
expect_named_failure mesh-stalled-leg class-a
if grep -q 'store=laptop' "$TMP_ROOT/out.log"; then
echo "ok: mesh-stalled-leg: output names store=laptop"
else fail "mesh-stalled-leg: output does not name store=laptop: $(cat "$TMP_ROOT/out.log")"; fi

# A failed restore result is a failure even when its record is fresh.
write_mesh_record class-a laptop failed "1 hour ago"
run_watchdog_mesh
expect_named_failure mesh-failed-restore class-a

# Missing per-pair evidence catches an unstarted rotation.
rm -f "$MESH_RECORDS/embeds.drive.json"
run_watchdog_mesh
expect_named_failure mesh-missing-record 'leg=embeds store=drive'

if ((failures > 0)); then
echo "laptop-backups-watchdog tests: $failures failure(s)" >&2
exit 1
Expand Down
17 changes: 17 additions & 0 deletions nixos/home/laptop-backups.nix
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@
# last-trigger time ONLY: its script (~/tools/repo-archive-
# backup.sh) and its restic credentials live outside this repo, so
# no run record is required of it.
# With watchdog.meshEnable (code#13463), it also reads the backup
# mesh's restore-verification records: one per leg x store pair
# under ~/backups/mesh/restore-verification, each successful and no
# older than watchdog.meshMaxAgeHours (a quarter), so a stalled
# rotation is named by leg and store.
#
# Pruning discipline: each job prunes only the dated directories it
# created itself. The sandbox's backup job writes into its own tree under
Expand Down Expand Up @@ -120,6 +125,7 @@ let
++ (lib.optional cfg.state.enable "state")
++ (lib.optional cfg.opencodeDb.enable "opencode-db")
++ (lib.optional cfg.coldStoreNightly.enable "cold-store")
++ (lib.optional cfg.watchdog.meshEnable "mesh")
);
watchdogWanted = cfg.watchdog.enable && watchdogJobs != "";
servicePath = lib.makeBinPath [
Expand Down Expand Up @@ -273,6 +279,16 @@ in
default = "*-*-* 06,12,18:30:00";
description = "Times of day the watchdog runs (systemd calendar).";
};
meshEnable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Also report the backup mesh's restore-verification rotation records (code#13463): every leg x store pair under ~/backups/mesh/restore-verification must have a successful record no older than a quarter. Off until the rotation runners exist; enabling it before then fails naming every unverified pair, which is the intended reading.";
};
meshMaxAgeHours = lib.mkOption {
type = lib.types.ints.positive;
default = 2200;
description = "Maximum age (hours) of a leg x store restore-verification record before the watchdog names it (default 2200h, a little over a quarter).";
};
};
};

Expand Down Expand Up @@ -387,6 +403,7 @@ in
Environment = [
"PATH=${servicePath}:${home}/tools/bin:/run/current-system/sw/bin"
"LAPTOP_BACKUPS_OFFSITE_CHECK=1"
"LAPTOP_BACKUPS_MESH_MAX_AGE_HOURS=${toString cfg.watchdog.meshMaxAgeHours}"
];
};
};
Expand Down