From 388d6dd125327ccf83d09c0c3283b0ecef7eb69d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 20:50:44 -0600 Subject: [PATCH] pm-stack: gate Kaneo promotion on verified backup --- doc/pm-stack/COLD-RESTORE-RUNBOOK.md | 6 +- pm-stack/STORE-MIGRATION-PLAN-6816.md | 11 ++-- pm-stack/scripts/kaneo-cutover.sh | 49 +++++++++++++--- pm-stack/scripts/kaneo-cutover.test.sh | 72 +++++++++++++++++++++--- pm-stack/scripts/restore-point-check.py | 75 +++++++++++++++++++++++++ 5 files changed, 191 insertions(+), 22 deletions(-) create mode 100644 pm-stack/scripts/restore-point-check.py diff --git a/doc/pm-stack/COLD-RESTORE-RUNBOOK.md b/doc/pm-stack/COLD-RESTORE-RUNBOOK.md index 1c5cb9af15..c045fff014 100644 --- a/doc/pm-stack/COLD-RESTORE-RUNBOOK.md +++ b/doc/pm-stack/COLD-RESTORE-RUNBOOK.md @@ -15,7 +15,11 @@ A repeatable rehearsal driver lives at `pm-stack/scripts/restore-rehearsal.sh`. The cutover that precedes a post-cutover restore is gated by `pm-stack/scripts/kaneo-cutover.sh` (plan §4): promotion is refused unless `pm-stack/scripts/fence-check.sh` -reports FENCED and the target's table/row counts equal the source's. +reports FENCED, the target's table/row counts equal the source's, and the +latest backup record is a complete generation with verified local, R2, and +Drive copies finished within 36 hours (override only for a documented window +decision). Pass its path with `--backup-record-file`; the receipt records the +restore-point timestamp without exposing a DSN. Failover posture (Drew's #1258 rulings, 2026-11-03): all PM-stack state to Supabase `muse-dev2`, nothing laptop-only; **tested cold restore, no warm diff --git a/pm-stack/STORE-MIGRATION-PLAN-6816.md b/pm-stack/STORE-MIGRATION-PLAN-6816.md index 8ff2dc2254..dfee6a6a7b 100644 --- a/pm-stack/STORE-MIGRATION-PLAN-6816.md +++ b/pm-stack/STORE-MIGRATION-PLAN-6816.md @@ -94,10 +94,13 @@ two active writers" is mechanical instead of advisory: database, `pg_restore` it into the target, and require **schema parity** (same public table count). Row drift is reported, not failed — the final delta has not landed yet. -- `--mode promote` (step 5, the gate): refuses unless - `pm-stack/scripts/fence-check.sh` reports **FENCED** (fail closed on - anything unreadable) **and** the target's exact table count and row count - equal the source's. A refused promotion touches no store. Only a pass +- `--mode promote` (step 5, the gate): refuses unless the latest backup + record (`--backup-record-file`) describes a complete generation with a + valid archive identity and verified local, R2, and Drive copies, finished + no more than 36 hours ago by default (`--max-backup-age-hours` can set a + stricter window); `pm-stack/scripts/fence-check.sh` reports **FENCED** (fail + closed on anything unreadable) **and** the target's exact table count and row + count equal the source's. A refused promotion touches no store. Only a pass writes a cutover receipt (fence verdict, both counts, verdict line) with no DSN in it — the operator attaches it to the window record. diff --git a/pm-stack/scripts/kaneo-cutover.sh b/pm-stack/scripts/kaneo-cutover.sh index 11b598e328..866c7b373e 100755 --- a/pm-stack/scripts/kaneo-cutover.sh +++ b/pm-stack/scripts/kaneo-cutover.sh @@ -16,6 +16,8 @@ # anything unreadable); and # (b) final-delta parity: target table count AND exact row # count equal the source's. +# (c) a complete, verified backup generation finished within +# the accepted freshness window (default 36 hours). # Only then is a cutover receipt written and PROMOTE OK printed. # The script never rewrites the DSN itself: it gates the step # and records the evidence, so no configuration can promote @@ -41,6 +43,9 @@ # --fence-check PATH fence checker (default: sibling fence-check.sh) # --units-dir DIR passed to fence-check (fixture mode) # --containers-file FILE passed to fence-check (fixture mode) +# --backup-record-file FILE latest pm-dashboard-backup .last-run.json; +# required for promote +# --max-backup-age-hours N freshness bound for the backup (default 36) # --unreachable passed to fence-check: old host unreachable # -h, --help usage, exit 0 # @@ -58,6 +63,8 @@ RECEIPT="" PG_BIN_DIR="" FENCE_CHECK="$SCRIPT_DIR/fence-check.sh" FENCE_ARGS=() +BACKUP_RECORD_FILE="" +MAX_BACKUP_AGE_HOURS=36 # Exact counts for every public table, in one query: table count, then the # sum of per-table exact count(*). Exact (not pg_stat estimates) so the @@ -70,12 +77,14 @@ usage: kaneo-cutover.sh --mode presync|promote --source-dsn-file FILE --target-dsn-file FILE [--dump-file FILE] [--receipt FILE] [--pg-bin-dir DIR] [--fence-check PATH] [--units-dir DIR] - [--containers-file FILE] [--unreachable] [-h|--help] + [--containers-file FILE] [--unreachable] + [--backup-record-file FILE] + [--max-backup-age-hours N] [-h|--help] presync dump the source, restore into the target, verify schema parity. - promote require the old writer FENCED and exact table/row parity, then - write the cutover receipt. Exit: 0 pass, 2 usage, 3 not fenced, - 4 parity failure, 5 command failure. + promote require a fresh complete backup, the old writer FENCED, and exact + table/row parity, then write the cutover receipt. Exit: 0 pass, + 2 usage, 3 promotion refused, 4 parity failure, 5 command failure. USAGE } @@ -95,7 +104,7 @@ while [ "$#" -gt 0 ]; do FENCE_ARGS+=("--unreachable") shift ;; - --mode|--source-dsn-file|--target-dsn-file|--dump-file|--receipt|--pg-bin-dir|--fence-check|--units-dir|--containers-file) + --mode|--source-dsn-file|--target-dsn-file|--dump-file|--receipt|--pg-bin-dir|--fence-check|--units-dir|--containers-file|--backup-record-file|--max-backup-age-hours) opt="$1" [ "$#" -ge 2 ] || fail_usage "$opt requires a value" val="$2" @@ -108,12 +117,14 @@ while [ "$#" -gt 0 ]; do --receipt) RECEIPT="$val" ;; --pg-bin-dir) PG_BIN_DIR="$val" ;; --fence-check) FENCE_CHECK="$val" ;; + --backup-record-file) BACKUP_RECORD_FILE="$val" ;; + --max-backup-age-hours) MAX_BACKUP_AGE_HOURS="$val" ;; --units-dir) FENCE_ARGS+=("--units-dir" "$val") ;; --containers-file) FENCE_ARGS+=("--containers-file" "$val") ;; esac shift 2 ;; - --mode=*|--source-dsn-file=*|--target-dsn-file=*|--dump-file=*|--receipt=*|--pg-bin-dir=*|--fence-check=*|--units-dir=*|--containers-file=*) + --mode=*|--source-dsn-file=*|--target-dsn-file=*|--dump-file=*|--receipt=*|--pg-bin-dir=*|--fence-check=*|--units-dir=*|--containers-file=*|--backup-record-file=*|--max-backup-age-hours=*) opt="${1%%=*}" val="${1#*=}" [ -n "$val" ] || fail_usage "$opt requires a non-empty value" @@ -125,6 +136,8 @@ while [ "$#" -gt 0 ]; do --receipt) RECEIPT="$val" ;; --pg-bin-dir) PG_BIN_DIR="$val" ;; --fence-check) FENCE_CHECK="$val" ;; + --backup-record-file) BACKUP_RECORD_FILE="$val" ;; + --max-backup-age-hours) MAX_BACKUP_AGE_HOURS="$val" ;; --units-dir) FENCE_ARGS+=("--units-dir" "$val") ;; --containers-file) FENCE_ARGS+=("--containers-file" "$val") ;; esac @@ -152,6 +165,14 @@ esac if [ "$MODE" = "presync" ]; then [ -n "$DUMP_FILE" ] || fail_usage "--dump-file is required for presync" fi +if [ "$MODE" = "promote" ]; then + [ -n "$BACKUP_RECORD_FILE" ] || fail_usage "--backup-record-file is required for promote" + [ -r "$BACKUP_RECORD_FILE" ] || fail_usage "backup record file '$BACKUP_RECORD_FILE' is not readable" + case "$MAX_BACKUP_AGE_HOURS" in + ''|*[!0-9]*) fail_usage "--max-backup-age-hours must be a positive integer" ;; + 0) fail_usage "--max-backup-age-hours must be a positive integer" ;; + esac +fi if [ -n "$PG_BIN_DIR" ]; then [ -d "$PG_BIN_DIR" ] || fail_usage "--pg-bin-dir '$PG_BIN_DIR' is not a directory" @@ -241,6 +262,18 @@ if ! FENCE_OUT="$("$FENCE_CHECK" ${FENCE_ARGS[@]+"${FENCE_ARGS[@]}"} 2>&1)" || [ fi FENCE_LINE="$FENCE_OUT" +# Reject absent, incomplete, unverified, stale, or future-dated generations +# before querying either database. The collector and gate share the same +# local/R2/Drive definition of a complete backup restore point. +RESTORE_POINT_OUT="$(python3 -I "$SCRIPT_DIR/restore-point-check.py" \ + --record "$BACKUP_RECORD_FILE" --max-age-hours "$MAX_BACKUP_AGE_HOURS" 2>&1)" || { + RESTORE_POINT_LINE="REFUSED — $RESTORE_POINT_OUT" + write_receipt "REFUSED — promotion requires a fresh verified backup restore point" "- Restore point: $RESTORE_POINT_LINE" + echo "kaneo-cutover: REFUSED — promotion requires a fresh verified backup restore point; no database queried. $RESTORE_POINT_OUT" >&2 + exit 3 +} +RESTORE_POINT_LINE="$RESTORE_POINT_OUT" + SRC_COUNTS="$(counts_of source "$source_dsn")" || exit $? TGT_COUNTS="$(counts_of target "$target_dsn")" || exit $? if [ "$SRC_COUNTS" != "$TGT_COUNTS" ]; then @@ -249,8 +282,8 @@ if [ "$SRC_COUNTS" != "$TGT_COUNTS" ]; then exit 4 fi -write_receipt "PASS — fenced, and source and target both $SRC_COUNTS" -echo "kaneo-cutover: PROMOTE OK — $FENCE_OUT; source and target both $SRC_COUNTS" +write_receipt "PASS — fresh verified backup, fenced, and source and target both $SRC_COUNTS" "- Restore point: $RESTORE_POINT_LINE" +echo "kaneo-cutover: PROMOTE OK — $FENCE_OUT; $RESTORE_POINT_OUT; source and target both $SRC_COUNTS" if [ -z "$RECEIPT" ]; then printf '\n%s\n' "$RECEIPT_BODY" fi diff --git a/pm-stack/scripts/kaneo-cutover.test.sh b/pm-stack/scripts/kaneo-cutover.test.sh index c6c0c5cc26..8821c2ea68 100755 --- a/pm-stack/scripts/kaneo-cutover.test.sh +++ b/pm-stack/scripts/kaneo-cutover.test.sh @@ -41,6 +41,7 @@ while [ "$#" -gt 0 ]; do *) shift ;; esac done +printf 'psql\n' >>"$CUTOVER_FIXTURE_DIR/log" case "$dsn" in *source*) f="$CUTOVER_FIXTURE_DIR/counts-source.txt" ;; *target*) f="$CUTOVER_FIXTURE_DIR/counts-target.txt" ;; @@ -70,6 +71,18 @@ chmod +x "$TMP/bin/psql" "$TMP/bin/pg_dump" "$TMP/bin/pg_restore" printf 'source-db dsn\n' >"$TMP/source.dsn" printf 'target-db dsn\n' >"$TMP/target.dsn" +python3 -I - "$TMP/backup.json" <<'PY' +import json, sys +from datetime import datetime, timezone, timedelta +finished = datetime.now(timezone.utc) - timedelta(minutes=5) +json.dump({ + "date": finished.date().isoformat(), + "finishedAt": finished.isoformat(), + "result": "complete", + "archiveSha256": "a" * 64, + "destinations": {"local": "ok", "r2": "ok", "drive": "ok"}, +}, open(sys.argv[1], "w")) +PY # Fence fixtures: all writers stopped/inactive. mkdir -p "$TMP/units" @@ -89,12 +102,13 @@ log_is_empty() { [ ! -s "$TMP/fx/log" ]; } run() { "$BASH_BIN" "$DRIVER" "$@" 2>&1; } common=(--pg-bin-dir "$TMP/bin" --source-dsn-file "$TMP/source.dsn" --target-dsn-file "$TMP/target.dsn") +promote=(--backup-record-file "$TMP/backup.json") # 1. presync dumps then restores, and passes on schema parity. set_counts '45 90139' '45 0' reset_log if out="$(run --mode presync --dump-file "$TMP/k.dump" --receipt "$TMP/r1.md" "${common[@]}")"; then - if [ "$(cat "$TMP/fx/log" | tr '\n' ' ')" = "pg_dump pg_restore " ]; then + if [ "$(cat "$TMP/fx/log" | tr '\n' ' ')" = "pg_dump pg_restore psql psql " ]; then pass 'presync dumps then restores' else fail "presync dumps then restores (log: $(cat "$TMP/fx/log" | tr '\n' ' '))" @@ -124,7 +138,7 @@ fi # 3. promote refuses while a writer is running — and touches nothing. set_counts '45 90139' '45 90139' reset_log -if out="$(run --mode promote --receipt "$TMP/r3.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-kaneo-running.txt" "${common[@]}")"; then +if out="$(run --mode promote --receipt "$TMP/r3.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-kaneo-running.txt" "${promote[@]}" "${common[@]}")"; then fail "promote refuses while unfenced (exit 0, got: $out)" else if [ "$?" -eq 3 ] && log_is_empty && grep -q 'REFUSED' "$TMP/r3.md"; then @@ -137,7 +151,7 @@ fi # 4. promote refuses on final-delta row mismatch even when fenced. set_counts '45 90139' '45 89000' reset_log -if out="$(run --mode promote --receipt "$TMP/r4.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${common[@]}")"; then +if out="$(run --mode promote --receipt "$TMP/r4.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${promote[@]}" "${common[@]}")"; then fail "promote fails on row mismatch (exit 0, got: $out)" else if [ "$?" -eq 4 ] && grep -q 'FAIL — final-delta parity' "$TMP/r4.md"; then @@ -150,15 +164,15 @@ fi # 5. promote passes when fenced and counts match; receipt carries the fence. set_counts '45 90139' '45 90139' reset_log -if out="$(run --mode promote --receipt "$TMP/r5.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${common[@]}")"; then +if out="$(run --mode promote --receipt "$TMP/r5.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${promote[@]}" "${common[@]}")"; then case "$out" in *'PROMOTE OK'*FENCED*) pass 'promote passes when fenced and parity holds' ;; *) fail "promote passes when fenced and parity holds (got: $out)" ;; esac - if grep -q 'Fence: FENCED' "$TMP/r5.md" && grep -q '45 90139' "$TMP/r5.md"; then - pass 'promote receipt records the fence and the counts' + if grep -q 'Fence: FENCED' "$TMP/r5.md" && grep -q '45 90139' "$TMP/r5.md" && grep -q 'RESTORE POINT OK' "$TMP/r5.md"; then + pass 'promote receipt records the fence, backup restore point, and counts' else - fail 'promote receipt records the fence and the counts' + fail 'promote receipt records the fence, backup restore point, and counts' fi else fail "promote passes when fenced and parity holds (exit $?, got: $out)" @@ -167,14 +181,49 @@ fi # 6. An unreadable target is a command failure (exit 5), not a pass. set_counts '45 90139' '45 90139' rm -f "$TMP/fx/counts-target.txt" -if out="$(run --mode promote --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${common[@]}")"; then +if out="$(run --mode promote --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${promote[@]}" "${common[@]}")"; then fail "unreadable target exits 5 (exit 0, got: $out)" else [ "$?" -eq 5 ] && pass 'unreadable target exits 5' || fail "unreadable target exits 5 (got: $out)" fi printf '45 90139\n' >"$TMP/fx/counts-target.txt" -# 7. Contract (#3352): usage errors before any subprocess (exit 2). +# 7. Promotion requires a fresh, complete, off-machine verified restore point. +python3 -I - "$TMP/backup.json" <<'PY' +import json, sys +with open(sys.argv[1]) as f: record = json.load(f) +record["destinations"]["r2"] = "failed" +with open(sys.argv[1], "w") as f: json.dump(record, f) +PY +reset_log +if out="$(run --mode promote --receipt "$TMP/r6.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${promote[@]}" "${common[@]}")"; then + fail "promote refuses backup without verified R2 copy (exit 0, got: $out)" +else + [ "$?" -eq 3 ] && log_is_empty && grep -q 'restore point' "$TMP/r6.md" && pass 'promote refuses incomplete backup before database access' || fail "promote refuses incomplete backup before database access (got: $out)" +fi +python3 -I - "$TMP/backup.json" <<'PY' +import json, sys +from datetime import datetime, timezone, timedelta +with open(sys.argv[1]) as f: record = json.load(f) +record["destinations"]["r2"] = "ok" +record["finishedAt"] = (datetime.now(timezone.utc) - timedelta(hours=37)).isoformat() +with open(sys.argv[1], "w") as f: json.dump(record, f) +PY +reset_log +if out="$(run --mode promote --receipt "$TMP/r7.md" --units-dir "$TMP/units" --containers-file "$TMP/containers-clean.txt" "${promote[@]}" "${common[@]}")"; then + fail "promote refuses stale backup (exit 0, got: $out)" +else + [ "$?" -eq 3 ] && log_is_empty && grep -q 'restore point' "$TMP/r7.md" && pass 'promote refuses stale backup before database access' || fail "promote refuses stale backup before database access (got: $out)" +fi +python3 -I - "$TMP/backup.json" <<'PY' +import json, sys +from datetime import datetime, timezone, timedelta +with open(sys.argv[1]) as f: record = json.load(f) +record["finishedAt"] = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat() +with open(sys.argv[1], "w") as f: json.dump(record, f) +PY + +# 8. Contract (#3352): usage errors before any subprocess (exit 2). reset_log if run --bogus >/dev/null 2>&1; then fail 'unknown flag exits 2'; else [ "$?" -eq 2 ] && pass 'unknown flag exits 2' || fail 'unknown flag exits 2' @@ -187,6 +236,11 @@ if run --mode presync --source-dsn-file "$TMP/source.dsn" --target-dsn-file "$TM else [ "$?" -eq 2 ] && pass 'missing --dump-file for presync exits 2' || fail 'missing --dump-file for presync exits 2' fi +if run --mode promote --source-dsn-file "$TMP/source.dsn" --target-dsn-file "$TMP/target.dsn" >/dev/null 2>&1; then + fail 'missing backup record exits 2' +else + [ "$?" -eq 2 ] && pass 'missing backup record exits 2' || fail 'missing backup record exits 2' +fi if run --mode promote --source-dsn-file "$TMP/nope.dsn" --target-dsn-file "$TMP/target.dsn" >/dev/null 2>&1; then fail 'unreadable source DSN exits 2' else diff --git a/pm-stack/scripts/restore-point-check.py b/pm-stack/scripts/restore-point-check.py new file mode 100644 index 0000000000..65aa82b3da --- /dev/null +++ b/pm-stack/scripts/restore-point-check.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Fail closed unless a recent dashboard backup is a verified restore point. + +Oracle: host-health normalization in pm-stack/aggregator/src/host-health.ts +requires a complete generation, archive identity, and verified local/R2/Drive +copies. The cutover policy additionally bounds age to 36 hours by default. +""" + +import argparse +import json +import re +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + + +def parse_args(argv): + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--record", required=True) + parser.add_argument("--max-age-hours", type=int, default=36) + args = parser.parse_args(argv) + if args.max_age_hours <= 0: + parser.error("--max-age-hours must be a positive integer") + return args + + +def check_record(path: Path, max_age_hours: int, now: datetime) -> str: + try: + record = json.loads(path.read_text()) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ValueError("record is unreadable or invalid JSON") from exc + if not isinstance(record, dict): + raise ValueError("record is not an object") + if record.get("result") != "complete": + raise ValueError("latest generation is not complete") + if not isinstance(record.get("date"), str) or not record["date"]: + raise ValueError("generation date is missing") + digest = record.get("archiveSha256") + if not isinstance(digest, str) or re.fullmatch(r"[0-9a-fA-F]{64}", digest) is None: + raise ValueError("archive identity is missing or invalid") + destinations = record.get("destinations") + if not isinstance(destinations, dict) or any( + destinations.get(name) != "ok" for name in ("local", "r2", "drive") + ): + raise ValueError("local, R2, and Drive copies must all be verified") + finished = record.get("finishedAt") + if not isinstance(finished, str): + raise ValueError("finish time is missing") + try: + timestamp = datetime.fromisoformat(finished.replace("Z", "+00:00")) + except ValueError as exc: + raise ValueError("finish time is invalid") from exc + if timestamp.tzinfo is None: + raise ValueError("finish time must include a timezone") + age = now - timestamp.astimezone(timezone.utc) + if age < timedelta(0): + raise ValueError("finish time is in the future") + if age > timedelta(hours=max_age_hours): + raise ValueError(f"generation is older than {max_age_hours} hours") + return timestamp.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def main(argv=None): + args = parse_args(sys.argv[1:] if argv is None else argv) + try: + finished = check_record(Path(args.record), args.max_age_hours, datetime.now(timezone.utc)) + except ValueError as exc: + print(f"restore-point-check: unavailable restore point: {exc}", file=sys.stderr) + return 1 + print(f"RESTORE POINT OK: complete generation finished {finished}; local/R2/Drive verified") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())