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
18 changes: 18 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand Down
49 changes: 49 additions & 0 deletions users/dev/cf-route-monitor.nix
Original file line number Diff line number Diff line change
@@ -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" ];
};
}
200 changes: 200 additions & 0 deletions users/dev/cf-route-monitor.sh
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions users/dev/home.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading