diff --git a/flake.nix b/flake.nix index ea05ad5e..eebce3d1 100644 --- a/flake.nix +++ b/flake.nix @@ -657,6 +657,24 @@ touch $out ''; + # cf-route-monitor (devbox route-to-api.anthropic.com probe + episode + # alerting, bead workstation-dkts.2). Hermetic: curl/ip are stubs. + # Pinned assertion count; see users/dev/test-cf-route-monitor.sh. + cf-route-monitor-tests = devboxPkgs.runCommand "cf-route-monitor-tests" { + nativeBuildInputs = [ devboxPkgs.bash devboxPkgs.coreutils devboxPkgs.gnugrep + devboxPkgs.gawk devboxPkgs.jq devboxPkgs.gnused + devboxPkgs.findutils ]; + } '' + cd ${self} + bash users/dev/test-cf-route-monitor.sh 2>&1 | tee "$TMPDIR/cfr.txt" + grep -q '^ALL PASS (93 assertions)' "$TMPDIR/cfr.txt" || { + echo "GATE FAILURE: cf-route-monitor suite did not reach ALL PASS (93 assertions)." >&2 + echo "If you added assertions, bump the pinned count here deliberately." >&2 + exit 1 + } + touch $out + ''; + # Failover reconciler (devbox em-ci-failover, bead eternal-machinery-0oycj.5). # Pinned assertion count; see hosts/devbox/test-em-ci-failover.sh. em-ci-failover-tests = devboxPkgs.runCommand "em-ci-failover-tests" { diff --git a/users/dev/cf-route-monitor.nix b/users/dev/cf-route-monitor.nix new file mode 100644 index 00000000..02b0fa8e --- /dev/null +++ b/users/dev/cf-route-monitor.nix @@ -0,0 +1,49 @@ +# cf-route-monitor (devbox only): detect and record outages on devbox's route +# to api.anthropic.com (Cloudflare-fronted), bead workstation-dkts.2. +# +# On 2026-12-02 the route went dark in 20-70 s clusters while served from +# Cloudflare's Moscow colo (DME). This is DETECTION ONLY: a user timer probes +# /cdn-cgi/trace every 30 s over v4 (and v6 once a v6 route exists), logs one +# JSON line per run to ~/.local/state/cf-route-monitor/log.jsonl, and sends a +# pigeon alert when 2 consecutive probes fail (and again after 10 consecutive +# successes). The warning alert is the trigger for the manual upstreamProxy +# stopgap (runbook: bd show workstation-dkts.3). +# +# An outage is not a unit failure: the script exits 0 on failed probes, so +# there is deliberately no OnFailure unit. Alert delivery is retried on every +# run until it succeeds. The script and its state machine are in +# cf-route-monitor.sh; tests in test-cf-route-monitor.sh +# (checks.cf-route-monitor-tests). +# +# Budget: at most one request per 30 s per family to api.anthropic.com, no +# credentials. TimeoutStartSec=40s fits v4 (10 s) + v6 (10 s) + alert (12 s). Runs cannot +# overlap (a oneshot is not restarted while active), so this is safe. +{ pkgs, lib, isDevbox, ... }: + +lib.mkIf isDevbox { + systemd.user.services.cf-route-monitor = { + Unit.Description = "cf-route-monitor: probe the route to api.anthropic.com, log, alert on outages"; + Service = { + Type = "oneshot"; + ExecStart = "${pkgs.bash}/bin/bash ${./cf-route-monitor.sh}"; + Environment = [ + "HOME=%h" + "PATH=${lib.makeBinPath [ pkgs.curl pkgs.jq pkgs.iproute2 pkgs.coreutils pkgs.gawk pkgs.gnused ]}" + ]; + TimeoutStartSec = "40s"; + MemoryMax = "128M"; + MemorySwapMax = "0"; + Nice = 10; + }; + }; + + systemd.user.timers.cf-route-monitor = { + Unit.Description = "cf-route-monitor every 30 s"; + Timer = { + OnBootSec = "2min"; + OnUnitActiveSec = "30s"; + AccuracySec = "1s"; + }; + Install.WantedBy = [ "timers.target" ]; + }; +} diff --git a/users/dev/cf-route-monitor.sh b/users/dev/cf-route-monitor.sh new file mode 100755 index 00000000..7138aff1 --- /dev/null +++ b/users/dev/cf-route-monitor.sh @@ -0,0 +1,200 @@ +#!/usr/bin/env bash +# cf-route-monitor: detect and record outages on this host's route to +# api.anthropic.com (Cloudflare-fronted). Detection only; see +# users/dev/cf-route-monitor.nix and bead workstation-dkts.2. +# +# One run (the timer fires every 30 s): +# 1. probe /cdn-cgi/trace over IPv4 (and IPv6 when a v6 route exists) +# 2. append one JSON line to $STATE_DIR/log.jsonl (rotated at 20 MiB) +# 3. advance the episode state machine in $STATE_DIR/state.json +# 4. deliver any queued alert (kept and retried on every run until sent) +# +# Exit 0 always -- an outage is not a unit failure -- except on internal +# errors (missing tool, unwritable state dir). +# +# Test seams (all env): STATE_DIR, CF_ROUTE_PROBE_URL, CF_ROUTE_ALERT_URL, +# CF_ROUTE_TOKEN_FILE, CF_ROUTE_NOW (ISO-8601 UTC timestamp). +set -u + +STATE_DIR=${STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/cf-route-monitor} +PROBE_URL=${CF_ROUTE_PROBE_URL:-https://api.anthropic.com/cdn-cgi/trace} +ALERT_URL=${CF_ROUTE_ALERT_URL:-http://127.0.0.1:4731/alert} +TOKEN_FILE=${CF_ROUTE_TOKEN_FILE:-/run/secrets/pigeon_daemon_auth_token} +V6_PROBE_ADDR=2607:6bc0::10 +ROTATE_BYTES=$((20 * 1024 * 1024)) + +log() { printf '[cf-route-monitor] %s\n' "$*" >&2; } +die() { log "internal error: $*"; exit 1; } + +for tool in curl jq date mktemp awk; do + command -v "$tool" >/dev/null 2>&1 || die "$tool not found in PATH" +done +mkdir -p "$STATE_DIR" 2>/dev/null || die "cannot create $STATE_DIR" +[ -w "$STATE_DIR" ] || die "$STATE_DIR is not writable" + +LOG=$STATE_DIR/log.jsonl +STATE=$STATE_DIR/state.json +# Temp files are removed on any exit, including a SIGTERM from the unit's +# TimeoutStartSec (a plain EXIT trap does not run on an unhandled TERM). +TMPFILES=() +cleanup() { [ "${#TMPFILES[@]}" -gt 0 ] && rm -f "${TMPFILES[@]}"; return 0; } +trap cleanup EXIT +trap 'exit 143' TERM INT +TS=${CF_ROUTE_NOW:-$(date -u +%Y-%m-%dT%H:%M:%SZ)} + +# probe FAMILY(4|6): print one JSON object {ok,connect_ms,total_ms,colo,curl_rc,http}. +# connect_ms excludes DNS (time_connect - time_namelookup); it is null when +# the connect never completed (time_connect is 0). +probe() { + local fam=$1 body out rc nl tc tt http colo + body=$(mktemp "$STATE_DIR/body.XXXXXX") || die "mktemp failed" + TMPFILES+=("$body") + # --noproxy: always measure the direct route, even if a proxy is ever put + # into the user manager's environment (the upstreamProxy stopgap must not + # make this monitor report "recovered"). + out=$(curl "-$fam" -sS --noproxy '*' -o "$body" --connect-timeout 5 -m 10 \ + -w '%{time_namelookup} %{time_connect} %{time_total} %{http_code}' \ + "$PROBE_URL") + rc=$? + nl=0 tc=0 tt=0 http=0 + read -r nl tc tt http <<<"$out" || true + colo="" + if [ "$rc" -eq 0 ]; then + colo=$(sed -n 's/^colo=//p' "$body" | head -n 1) + fi + rm -f "$body" + jq -nc \ + --argjson rc "$rc" \ + --arg nl "${nl:-0}" --arg tc "${tc:-0}" --arg tt "${tt:-0}" \ + --arg http "${http:-0}" --arg colo "$colo" ' + ($nl | tonumber? // 0) as $nl + | ($tc | tonumber? // 0) as $tc + | ($tt | tonumber? // 0) as $tt + | ($http | tonumber? // 0) as $http + | { + ok: ($rc == 0 and $http == 200), + connect_ms: (if $tc > 0 then ((($tc - $nl) * 1000) | round) else null end), + total_ms: (($tt * 1000) | round), + colo: $colo, + curl_rc: $rc, + http: $http + }' +} + +V4=$(probe 4) || exit 1 +V6=null +if command -v ip >/dev/null 2>&1 && ip -6 route get "$V6_PROBE_ADDR" >/dev/null 2>&1; then + V6=$(probe 6) || exit 1 +fi + +# Rotate, then append. +if [ -f "$LOG" ]; then + size=$(wc -c <"$LOG" | tr -d ' ') + if [ "${size:-0}" -gt "$ROTATE_BYTES" ]; then + mv -f "$LOG" "$LOG.1" || log "rotation failed" + fi +fi +jq -nc --arg ts "$TS" --argjson v4 "$V4" --argjson v6 "$V6" \ + '{ts: $ts, v4: $v4, v6: $v6}' >>"$LOG" || die "cannot append to $LOG" + +# --- episode state machine (v4 only) --------------------------------------- +DEFAULT_STATE='{ + "consecutive_fail": 0, "consecutive_ok": 0, + "in_episode": false, "episode_start": null, "episode_fail_count": 0, + "colos_seen": [], "last_ok_colo": null, "first_fail_ts": null, "last_ts": null, + "alert_pending": null +}' +if [ -f "$STATE" ] && jq -e 'type == "object"' "$STATE" >/dev/null 2>&1; then + OLD=$(cat "$STATE") +else + [ -f "$STATE" ] && log "state.json unreadable; starting fresh" + OLD=$DEFAULT_STATE +fi + +# shellcheck disable=SC2016 # jq program, not shell +STEP=' +def dur($s): + ($s | floor) as $s + | if $s < 60 then "\($s)s" + elif $s < 3600 then "\($s / 60 | floor)m\($s % 60)s" + else "\($s / 3600 | floor)h\(($s % 3600) / 60 | floor)m" end; +# Counters older than 5 minutes (reboot, suspended timer) do not carry over: +# one failure before a gap plus one after is not "2 consecutive". An open +# episode is kept; it closes after 10 OKs as usual. +(($defaults + .) + | if (.last_ts != null) and ((($ts | fromdateiso8601) - (.last_ts | fromdateiso8601)) > 300) + then .consecutive_fail = 0 | .consecutive_ok = 0 | .first_fail_ts = null + else . end + | .last_ts = $ts) as $st +| if $v4.ok then + ($st + | .consecutive_ok += 1 | .consecutive_fail = 0 | .first_fail_ts = null + | if $v4.colo != "" then .last_ok_colo = $v4.colo else . end + | if .in_episode and $v4.colo != "" and ((.colos_seen | index($v4.colo)) == null) + then .colos_seen += [$v4.colo] else . end + | if .in_episode and .consecutive_ok >= 10 then + (if (.alert_pending != null and .alert_pending.kind == "start") + then " (start alert was not delivered)" else "" end) as $note + | .alert_pending = { + severity: "info", kind: "recovered", + text: ("devbox: api.anthropic.com route recovered; episode \(.episode_start)-\($ts) (\(dur(($ts | fromdateiso8601) - (.episode_start | fromdateiso8601)))), \(.episode_fail_count) failed probes, colos seen: \(if (.colos_seen | length) > 0 then (.colos_seen | join(", ")) else "none" end)" + $note) + } + | .in_episode = false | .episode_start = null + | .episode_fail_count = 0 | .colos_seen = [] + else . end) + else + ($st + | .consecutive_fail += 1 | .consecutive_ok = 0 + | if .consecutive_fail == 1 then .first_fail_ts = $ts else . end + | if .in_episode then .episode_fail_count += 1 + elif .consecutive_fail >= 2 then + .in_episode = true + | .episode_start = (.first_fail_ts // $ts) + | .episode_fail_count = .consecutive_fail + | .colos_seen = [] + | .alert_pending = { + severity: "warning", kind: "start", + text: ("devbox: api.anthropic.com unreachable (2 consecutive failed connects; colo before failure: \(.last_ok_colo // "unknown")). Runbook: bd show workstation-dkts.3") + } + else . end) + end' +NEW=$(jq -c --argjson defaults "$DEFAULT_STATE" --argjson v4 "$V4" --arg ts "$TS" "$STEP" <<<"$OLD") \ + || die "state machine failed" + +write_state() { + local tmp + tmp=$(mktemp "$STATE_DIR/state.XXXXXX") || die "mktemp failed" + TMPFILES+=("$tmp") + printf '%s\n' "$1" >"$tmp" && mv -f "$tmp" "$STATE" || die "cannot write $STATE" +} +write_state "$NEW" + +# --- alert delivery ----------------------------------------------------------- +# POST {text,severity} to pigeon. Kept in alert_pending until delivered. +# -m 12 is above pigeon's own /alert budget (10 s: a 5 s Cloudflare-Worker leg, +# then the direct fallback). The Worker leg is exactly what stalls during this +# outage, so a client timeout (curl 28) means "outcome unknown" -- pigeon may +# still deliver. Then back off 5 minutes instead of re-posting every run; +# any other failure (refused, HTTP error) retries on the next run. +if jq -e '.alert_pending != null' <<<"$NEW" >/dev/null; then + now_s=$(date -u -d "$TS" +%s) + next_s=$(jq -r '.alert_pending.next_try_s // 0' <<<"$NEW") + if [ "$now_s" -ge "$next_s" ]; then + body=$(jq -c '.alert_pending | {text, severity}' <<<"$NEW") + token=$(cat "$TOKEN_FILE" 2>/dev/null || true) + auth=() + [ -n "$token" ] && auth=(-H "Authorization: Bearer $token") + curl -fsS -m 12 "${auth[@]}" -H 'Content-Type: application/json' \ + -d "$body" "$ALERT_URL" >/dev/null + arc=$? + if [ "$arc" -eq 0 ]; then + write_state "$(jq -c '.alert_pending = null' <<<"$NEW")" + elif [ "$arc" -eq 28 ]; then + log "alert outcome unknown (curl timeout); retry after 5 min: $body" + write_state "$(jq -c --argjson n "$((now_s + 300))" '.alert_pending.next_try_s = $n' <<<"$NEW")" + else + log "alert not delivered (curl $arc; will retry next run): $body" + fi + fi +fi +exit 0 diff --git a/users/dev/home.nix b/users/dev/home.nix index 947a89b4..883f2ac3 100644 --- a/users/dev/home.nix +++ b/users/dev/home.nix @@ -12,6 +12,7 @@ ./em-drift-detector.nix ./quota-telemetry.nix ./reading-archive.nix + ./cf-route-monitor.nix ./em-test-postgres.nix ./em-scratch-db-gc.nix ./tec-codex-bot.nix diff --git a/users/dev/test-cf-route-monitor.sh b/users/dev/test-cf-route-monitor.sh new file mode 100644 index 00000000..03f8963c --- /dev/null +++ b/users/dev/test-cf-route-monitor.sh @@ -0,0 +1,335 @@ +#!/usr/bin/env bash +# Hermetic tests for users/dev/cf-route-monitor.sh (bead workstation-dkts.2). +# curl and ip are stubs on PATH; no network, no pigeon, no real clock. +# Run: bash users/dev/test-cf-route-monitor.sh +# Pinned in flake.nix as checks.cf-route-monitor-tests ("ALL PASS (N assertions)"). +set -u + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +SCRIPT=${CF_ROUTE_MONITOR_BIN:-$HERE/cf-route-monitor.sh} + +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +STUB=$T/stub +mkdir -p "$STUB/bin" + +pass=0 +fail=0 +ok() { pass=$((pass + 1)); } +bad() { fail=$((fail + 1)); echo "FAIL: $1" >&2; } +eq() { # eq DESC EXPECTED ACTUAL + if [ "$2" = "$3" ]; then ok; else bad "$1: expected [$2] got [$3]"; fi +} + +# --- stubs -------------------------------------------------------------------- +# curl stub. Probe calls (URL contains cdn-cgi) read $STUB/v4 or $STUB/v6, one +# line "RC|NAMELOOKUP CONNECT TOTAL HTTP|COLO"; alert calls (URL ends /alert) +# append the -d body (and any Authorization header) to $STUB/alerts.log and +# succeed unless $STUB/alert_fail exists. Every call is counted per kind. +cat >"$STUB/bin/curl" <<'STUBEOF' +#!/usr/bin/env bash +out="" ; data="" ; fam="" ; url="" ; auth="" ; noproxy=0 +while [ $# -gt 0 ]; do + case "$1" in + -4) fam=4 ;; -6) fam=6 ;; + --noproxy) [ "$2" = '*' ] && noproxy=1; shift ;; + -o) out=$2; shift ;; + -d) data=$2; shift ;; + -H) case "$2" in Authorization:*) auth=$2 ;; esac; shift ;; + -w|-m|--connect-timeout) shift ;; + -*) ;; + *) url=$1 ;; + esac + shift +done +case "$url" in + */alert) + echo x >>"$STUB/alert_calls" + if [ -e "$STUB/alert_timeout" ]; then exit 28; fi + if [ -e "$STUB/alert_fail" ]; then exit 22; fi + printf '%s\n' "$data" >>"$STUB/alerts.log" + [ -n "$auth" ] && printf '%s\n' "$auth" >>"$STUB/auth.log" + exit 0 ;; + *cdn-cgi*) + echo "$fam" >>"$STUB/probe_calls" + [ "$noproxy" = 1 ] || echo "$fam" >>"$STUB/proxied_probes" + IFS='|' read -r rc timing colo <"$STUB/v$fam" + if [ -n "$out" ]; then + if [ "$rc" = 0 ]; then printf 'fl=1\nip=1.2.3.4\ncolo=%s\nhttp=2\n' "$colo" >"$out"; else : >"$out"; fi + fi + printf '%s' "$timing" + exit "$rc" ;; +esac +exit 99 +STUBEOF +cat >"$STUB/bin/ip" <<'STUBEOF' +#!/usr/bin/env bash +# ip -6 route get ADDR +[ -e "$STUB/has_v6" ] +STUBEOF +# No /usr/bin/env in the nix sandbox: point the stubs at this bash. +sed -i "1s|.*|#!$BASH|" "$STUB/bin/curl" "$STUB/bin/ip" +chmod +x "$STUB/bin/curl" "$STUB/bin/ip" + +export STUB +export CF_ROUTE_ALERT_URL=http://127.0.0.1:4731/alert +export CF_ROUTE_PROBE_URL=https://api.anthropic.com/cdn-cgi/trace +export CF_ROUTE_TOKEN_FILE=$T/no-token +export STATE_DIR=$T/state + +OK_V4='0|0.010000 0.050000 0.120000 200|AMS' +FAIL_V4='28|0.010000 0.000000 10.000000 000|' + +# run_once TS V4SPEC [V6SPEC] +run_once() { + local ts=$1 + echo "$2" >"$STUB/v4" + [ -n "${3:-}" ] && echo "$3" >"$STUB/v6" + CF_ROUTE_NOW=$ts PATH="$STUB/bin:$PATH" bash "$SCRIPT" 2>>"$T/stderr" + LAST_RC=$? +} +reset() { rm -rf "$STATE_DIR" "$STUB/alerts.log" "$STUB/alert_calls" "$STUB/probe_calls" "$STUB/alert_fail" "$STUB/alert_timeout" "$STUB/proxied_probes" "$STUB/has_v6" "$STUB/auth.log"; } +alerts() { [ -f "$STUB/alerts.log" ] && wc -l <"$STUB/alerts.log" | tr -d ' ' || echo 0; } +alert_calls() { [ -f "$STUB/alert_calls" ] && wc -l <"$STUB/alert_calls" | tr -d ' ' || echo 0; } +last_log() { tail -n 1 "$STATE_DIR/log.jsonl"; } +st() { jq -r "$1" "$STATE_DIR/state.json"; } + +# --- 1. one healthy probe ------------------------------------------------------- +reset +run_once 2026-12-02T10:00:00Z "$OK_V4" +eq "healthy run exits 0" 0 "$LAST_RC" +eq "log has one line" 1 "$(wc -l <"$STATE_DIR/log.jsonl" | tr -d ' ')" +eq "log ts" 2026-12-02T10:00:00Z "$(last_log | jq -r .ts)" +eq "v4 ok" true "$(last_log | jq -r .v4.ok)" +eq "v4 connect_ms excludes DNS" 40 "$(last_log | jq -r .v4.connect_ms)" +eq "v4 total_ms" 120 "$(last_log | jq -r .v4.total_ms)" +eq "v4 colo" AMS "$(last_log | jq -r .v4.colo)" +eq "v4 curl_rc" 0 "$(last_log | jq -r .v4.curl_rc)" +eq "v4 http" 200 "$(last_log | jq -r .v4.http)" +eq "v6 null without a v6 route" null "$(last_log | jq -c .v6)" +eq "v6 never probed without a route" "4" "$(tr -d '\n' <"$STUB/probe_calls")" +eq "healthy: no alert" 0 "$(alerts)" +eq "last_ok_colo kept" AMS "$(st .last_ok_colo)" + +# --- 2. failure shapes ---------------------------------------------------------- +run_once 2026-12-02T10:00:30Z "$FAIL_V4" +eq "failed probe exits 0" 0 "$LAST_RC" +eq "fail: ok false" false "$(last_log | jq -r .v4.ok)" +eq "fail: curl_rc recorded" 28 "$(last_log | jq -r .v4.curl_rc)" +eq "fail: colo empty" "" "$(last_log | jq -r .v4.colo)" +eq "fail: connect_ms null when never connected" null "$(last_log | jq -c .v4.connect_ms)" +eq "one failure: no alert" 0 "$(alerts)" +eq "one failure: not in episode" false "$(st .in_episode)" + +reset +run_once 2026-12-02T10:00:00Z '0|0.010000 0.050000 0.120000 503|' +eq "http 503 is not ok" false "$(last_log | jq -r .v4.ok)" +eq "http 503 recorded" 503 "$(last_log | jq -r .v4.http)" +eq "http 503 curl_rc 0" 0 "$(last_log | jq -r .v4.curl_rc)" + +# --- 3. a lone failure between oks never opens an episode ---------------------------- +reset +run_once 2026-12-02T10:00:00Z "$OK_V4" +run_once 2026-12-02T10:00:30Z "$FAIL_V4" +run_once 2026-12-02T10:01:00Z "$OK_V4" +run_once 2026-12-02T10:01:30Z "$FAIL_V4" +eq "non-consecutive failures: no alert" 0 "$(alerts)" +eq "non-consecutive failures: no episode" false "$(st .in_episode)" +eq "consecutive_fail restarts at 1" 1 "$(st .consecutive_fail)" + +# --- 4. episode opens on 2 consecutive failures, once -------------------------------- +reset +run_once 2026-12-02T10:00:00Z "$OK_V4" +run_once 2026-12-02T10:00:30Z "$FAIL_V4" +run_once 2026-12-02T10:01:00Z "$FAIL_V4" +eq "two failures: one alert" 1 "$(alerts)" +eq "two failures: in episode" true "$(st .in_episode)" +eq "episode_start is the FIRST failure" 2026-12-02T10:00:30Z "$(st .episode_start)" +eq "alert severity warning" warning "$(jq -r .severity "$STUB/alerts.log")" +eq "alert body has only text+severity" "severity,text" "$(jq -r 'keys | join(",")' "$STUB/alerts.log")" +want='devbox: api.anthropic.com unreachable (2 consecutive failed connects; colo before failure: AMS). Runbook: bd show workstation-dkts.3' +eq "alert text" "$want" "$(jq -r .text "$STUB/alerts.log")" +eq "delivered alert cleared from state" null "$(st .alert_pending)" +run_once 2026-12-02T10:01:30Z "$FAIL_V4" +run_once 2026-12-02T10:02:00Z "$FAIL_V4" +eq "more failures: still one alert" 1 "$(alerts)" +eq "episode fail count" 4 "$(st .episode_fail_count)" + +# --- 5. recovery needs 10 consecutive oks -------------------------------------------- +for i in 0 1 2 3 4 5 6 7 8; do + run_once "2026-12-02T10:0$((3 + i / 2)):$((i % 2 * 3))0Z" "0|0.01 0.05 0.12 200|DME" +done +eq "9 oks: still in episode" true "$(st .in_episode)" +eq "9 oks: no recovery alert yet" 1 "$(alerts)" +run_once 2026-12-02T10:07:30Z '0|0.01 0.05 0.12 200|FRA' +eq "10th ok: recovered" false "$(st .in_episode)" +eq "recovery alert sent" 2 "$(alerts)" +eq "recovery severity info" info "$(tail -n 1 "$STUB/alerts.log" | jq -r .severity)" +want='devbox: api.anthropic.com route recovered; episode 2026-12-02T10:00:30Z-2026-12-02T10:07:30Z (7m0s), 4 failed probes, colos seen: DME, FRA' +eq "recovery text" "$want" "$(tail -n 1 "$STUB/alerts.log" | jq -r .text)" +eq "episode fields reset" "0 0" "$(st '"\(.episode_fail_count) \(.colos_seen | length)"')" + +# A failure inside the recovery window restarts the ok count (stays in episode). +reset +run_once 2026-12-02T11:00:00Z "$FAIL_V4" +run_once 2026-12-02T11:00:30Z "$FAIL_V4" +for i in 1 2 3 4 5 6 7 8 9; do run_once 2026-12-02T11:01:00Z "$OK_V4"; done +run_once 2026-12-02T11:05:00Z "$FAIL_V4" +for i in 1 2 3 4 5 6 7 8 9; do run_once 2026-12-02T11:06:00Z "$OK_V4"; done +eq "fail resets ok streak: still in episode" true "$(st .in_episode)" +eq "fail resets ok streak: only the start alert" 1 "$(alerts)" +eq "failure with no earlier ok: colo before failure unknown" "unknown" \ + "$(head -n 1 "$STUB/alerts.log" | jq -r '.text | capture("colo before failure: (?[^)]*)\\)").c')" + +# --- 6. undelivered alerts are retried until sent ------------------------------------ +reset +touch "$STUB/alert_fail" +run_once 2026-12-02T12:00:00Z "$OK_V4" +run_once 2026-12-02T12:00:30Z "$FAIL_V4" +run_once 2026-12-02T12:01:00Z "$FAIL_V4" +eq "undelivered: exit 0" 0 "$LAST_RC" +eq "undelivered: kept pending" warning "$(st .alert_pending.severity)" +eq "undelivered: one attempt so far" 1 "$(alert_calls)" +run_once 2026-12-02T12:01:30Z "$FAIL_V4" +eq "undelivered: retried on next run" 2 "$(alert_calls)" +eq "undelivered: still pending" warning "$(st .alert_pending.severity)" +rm "$STUB/alert_fail" +run_once 2026-12-02T12:02:00Z "$FAIL_V4" +eq "retry delivered" 1 "$(alerts)" +eq "delivered text is the original start alert" "warning" "$(jq -r .severity "$STUB/alerts.log")" +eq "pending cleared after delivery" null "$(st .alert_pending)" +run_once 2026-12-02T12:02:30Z "$FAIL_V4" +eq "no resend after delivery" 1 "$(alerts)" + +# --- 7. newer alert replaces an undelivered older one -------------------------------- +reset +touch "$STUB/alert_fail" +run_once 2026-12-02T13:00:00Z "$OK_V4" +run_once 2026-12-02T13:00:30Z "$FAIL_V4" +run_once 2026-12-02T13:01:00Z "$FAIL_V4" +for i in 1 2 3 4 5 6 7 8 9 10; do run_once 2026-12-02T13:05:00Z "$OK_V4"; done +eq "replaced: pending is the recovery" info "$(st .alert_pending.severity)" +want='devbox: api.anthropic.com route recovered; episode 2026-12-02T13:00:30Z-2026-12-02T13:05:00Z (4m30s), 2 failed probes, colos seen: AMS (start alert was not delivered)' +eq "replaced: recovery notes undelivered start" "$want" "$(st .alert_pending.text)" +rm "$STUB/alert_fail" +run_once 2026-12-02T13:05:30Z "$OK_V4" +eq "replaced: only the recovery is ever sent" 1 "$(alerts)" +eq "replaced: delivered one is the recovery" info "$(jq -r .severity "$STUB/alerts.log")" + +# A delivered start alert yields a plain recovery text (no note). +reset +run_once 2026-12-02T14:00:00Z "$FAIL_V4" +run_once 2026-12-02T14:00:30Z "$FAIL_V4" +touch "$STUB/alert_fail" +for i in 1 2 3 4 5 6 7 8 9 10; do run_once 2026-12-02T14:01:00Z "$OK_V4"; done +eq "delivered start: recovery has no note" 0 \ + "$(st .alert_pending.text | grep -c 'not delivered')" + +# --- 8. bearer token -------------------------------------------------------------------- +reset +echo s3cret >"$T/token" +CF_ROUTE_TOKEN_FILE=$T/token run_once 2026-12-02T15:00:00Z "$FAIL_V4" +CF_ROUTE_TOKEN_FILE=$T/token run_once 2026-12-02T15:00:30Z "$FAIL_V4" +eq "alert carries the bearer token" "Authorization: Bearer s3cret" "$(cat "$STUB/auth.log")" +eq "token never lands in the log or state" 0 "$(cat "$STATE_DIR"/* | grep -c s3cret)" + +# --- 9. v6 only with a v6 route --------------------------------------------------------- +reset +touch "$STUB/has_v6" +run_once 2026-12-02T16:00:00Z "$OK_V4" '0|0.001000 0.021000 0.050000 200|LHR' +eq "v6 probed when routable" "4 6" "$(tr '\n' ' ' <"$STUB/probe_calls" | sed 's/ $//')" +eq "v6 ok" true "$(last_log | jq -r .v6.ok)" +eq "v6 connect_ms" 20 "$(last_log | jq -r .v6.connect_ms)" +eq "v6 colo" LHR "$(last_log | jq -r .v6.colo)" +run_once 2026-12-02T16:00:30Z "$OK_V4" '28|0.001000 0.000000 10.000000 000|' +eq "v6 failure recorded" false "$(last_log | jq -r .v6.ok)" +run_once 2026-12-02T16:01:00Z "$OK_V4" '28|0.001000 0.000000 10.000000 000|' +eq "v6 failures never open an episode" false "$(st .in_episode)" +eq "v6 failures never alert" 0 "$(alerts)" + +# --- 10. rotation ------------------------------------------------------------------------- +reset +mkdir -p "$STATE_DIR" +truncate -s 21M "$STATE_DIR/log.jsonl" +echo old >"$STATE_DIR/log.jsonl.1" +run_once 2026-12-02T17:00:00Z "$OK_V4" +eq "rotated: .1 holds the big log" 22020 "$(( $(stat -c %s "$STATE_DIR/log.jsonl.1") / 1000 ))" +eq "rotated: old .1 overwritten" 0 "$(grep -c '^old$' "$STATE_DIR/log.jsonl.1")" +eq "rotated: fresh log has one line" 1 "$(wc -l <"$STATE_DIR/log.jsonl" | tr -d ' ')" +run_once 2026-12-02T17:00:30Z "$OK_V4" +eq "no rotation under the limit" 2 "$(wc -l <"$STATE_DIR/log.jsonl" | tr -d ' ')" + +# --- 11. robustness ----------------------------------------------------------------------- +reset +mkdir -p "$STATE_DIR" +echo 'not json{' >"$STATE_DIR/state.json" +run_once 2026-12-02T18:00:00Z "$FAIL_V4" +eq "corrupt state: recovers, exit 0" 0 "$LAST_RC" +eq "corrupt state: restarted counters" 1 "$(st .consecutive_fail)" + +reset +echo file >"$T/afile" +STATE_DIR=$T/afile/sub run_once 2026-12-02T18:00:00Z "$OK_V4" +eq "unwritable state dir: exit 1" 1 "$LAST_RC" + +reset +mkdir -p "$STATE_DIR" +# Real clock when CF_ROUTE_NOW is unset. +echo "$OK_V4" >"$STUB/v4" +PATH="$STUB/bin:$PATH" bash "$SCRIPT" 2>>"$T/stderr" +eq "real timestamp is ISO UTC" 1 "$(last_log | jq -r '.ts | test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") | if . then 1 else 0 end')" +eq "no body temp files left behind" 0 "$(find "$STATE_DIR" -name 'body.*' | wc -l | tr -d ' ')" + +# --- 12. probes always bypass any proxy ------------------------------------------------ +reset +touch "$STUB/has_v6" +run_once 2026-12-02T19:00:00Z "$OK_V4" "$OK_V4" +eq "both probes ran" 2 "$(wc -l <"$STUB/probe_calls" | tr -d ' ')" +eq "no probe without --noproxy '*'" 0 "$( [ -f "$STUB/proxied_probes" ] && wc -l <"$STUB/proxied_probes" | tr -d ' ' || echo 0)" + +# --- 13. stale counters do not carry over a gap ----------------------------------------- +reset +run_once 2026-12-02T20:00:00Z "$OK_V4" +run_once 2026-12-02T20:00:30Z "$FAIL_V4" +# Six minutes later (reboot): one more failure is NOT "2 consecutive". +run_once 2026-12-02T20:06:30Z "$FAIL_V4" +eq "gap: no episode from a stale failure" false "$(st .in_episode)" +eq "gap: counter restarted" 1 "$(st .consecutive_fail)" +eq "gap: first_fail_ts is the post-gap failure" 2026-12-02T20:06:30Z "$(st .first_fail_ts)" +eq "gap: no alert" 0 "$(alerts)" +run_once 2026-12-02T20:07:00Z "$FAIL_V4" +eq "gap: episode starts at the post-gap failure" 2026-12-02T20:06:30Z "$(st .episode_start)" +# An open episode survives a gap and still needs 10 OKs to close. +run_once 2026-12-02T20:20:00Z "$OK_V4" +eq "gap: open episode kept" true "$(st .in_episode)" + +# --- 14. alert timeout = outcome unknown: back off 5 minutes -------------------------- +reset +touch "$STUB/alert_timeout" +run_once 2026-12-02T21:00:00Z "$FAIL_V4" +run_once 2026-12-02T21:00:30Z "$FAIL_V4" +eq "timeout: one attempt" 1 "$(alert_calls)" +eq "timeout: still pending" warning "$(st .alert_pending.severity)" +eq "timeout: next try in 5 min" "$(( $(date -u -d 2026-12-02T21:00:30Z +%s) + 300 ))" "$(st .alert_pending.next_try_s)" +run_once 2026-12-02T21:01:00Z "$FAIL_V4" +run_once 2026-12-02T21:04:00Z "$FAIL_V4" +eq "timeout: no re-post inside the backoff" 1 "$(alert_calls)" +rm "$STUB/alert_timeout" +run_once 2026-12-02T21:05:30Z "$FAIL_V4" +eq "timeout: retried after the backoff" 2 "$(alert_calls)" +eq "timeout: delivered, pending cleared" null "$(st .alert_pending)" +# A plain failure (refused) still retries on the very next run. +reset +touch "$STUB/alert_fail" +run_once 2026-12-02T22:00:00Z "$FAIL_V4" +run_once 2026-12-02T22:00:30Z "$FAIL_V4" +run_once 2026-12-02T22:01:00Z "$FAIL_V4" +eq "refused: retried next run (no backoff)" 2 "$(alert_calls)" +eq "refused: no next_try_s" null "$(st .alert_pending.next_try_s)" + +if [ "$fail" -eq 0 ]; then + echo "ALL PASS ($pass assertions)" +else + echo "FAILED: $fail of $((pass + fail)) assertions" >&2 + exit 1 +fi