feat(status): detect when a check region silently stops answering

checkProxyFallback: true is correct — a probe outage must not be published
as a service outage. But it makes the probe outage itself invisible:
monitor.ts:399-410 falls back to a local re-check, checkLocation keeps the
local colo, and nothing anywhere says the configured region has stopped
answering. A Durable Object that never comes back degrades a two-region
page to a one-region page in total silence.

Adds the missing comparison: configured region vs. the region the run
actually came from, persisted as state.probeOkAt (a timestamp, not a run
counter — the state is only written on change or after the write cooldown).
After 15 consecutive runs from outside the configured region the worker logs
every run and notifies once; once more on recovery. Nothing new on the public
page: "our probe moved" is an operations fact, not user-relevant status.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
pull/216/head
Test User 2026-07-31 02:30:12 +02:00
parent a21be253cb
commit c080da7bc8
5 changed files with 392 additions and 2 deletions

View File

@ -0,0 +1,188 @@
/**
* Red/green proof for the probe-drift detection (worker/src/probe.ts).
*
* npx tsx scripts/check-probe-drift.ts
*
* Three cases side by side, all driving the REAL `doMonitor` fallback branch
* (worker/src/monitor.ts:397-407) against the REAL `website_enam` monitor from
* uptime.config.ts — the Durable Object is replaced, nothing else is:
*
* A) PERMANENTLY DEAD PROXY — the stub throws from run 4 on. Detection MUST
* fire, exactly once, after PROBE_DRIFT_RUNS dead runs.
* B) SINGLE BLIP — one run out of 40 throws. Detection MUST NOT fire, or the
* silence has only been traded for alarm fatigue.
* C) CONTROL for the design choice — same dead proxy as A, but the cron
* worker happens to run inside the target region. The naive "map the
* recorded colo back to a region" test is blind here; this one is not.
*
* Exits non-zero if any expectation is violated.
*/
import { doMonitor } from '../worker/src/monitor'
import { evaluateProbe, PROBE_DRIFT_RUNS, PROBE_DRIFT_SECONDS } from '../worker/src/probe'
import { workerConfig } from '../uptime.config'
import { codeToCountry } from '../util/iata'
import type { MonitorStateCompacted, MonitorTarget } from '../types/config'
const monitor = workerConfig.monitors.find((m) => m.id === 'website_enam') as MonitorTarget
if (!monitor?.checkProxy) throw new Error('website_enam or its checkProxy is gone')
const LOCAL_COLO = 'LHR' // the cron colo, as measured live on 2026-07-31
const PROBE_COLO = 'EWR' // what the enam Durable Object answered live
/** Env whose Durable Object namespace is dead on the runs the predicate picks. */
function envWithDeadRuns(isDead: (n: number) => boolean, run: { n: number }): any {
return {
REMOTE_CHECKER_DO: {
idFromName(_name: string) {
if (isDead(run.n)) {
throw new Error('Network connection lost.') // what a dead DO looks like
}
return 'id'
},
get(_id: any, _opts: any) {
return {
async getLocationAndStatus() {
return { location: PROBE_COLO, status: { ping: 24, up: true, err: '' } }
},
async kill() {},
}
},
},
}
}
async function scenario(
label: string,
isDead: (n: number) => boolean,
totalRuns: number,
localColo: string = LOCAL_COLO
) {
const state: MonitorStateCompacted = {
lastUpdate: 0,
overallUp: 0,
overallDown: 0,
incident: {},
latency: {},
}
const run = { n: 0 }
const t0 = 1785457187 // live `updatedAt` from status.openshopgraph.org
const alerts: string[] = []
const locs: string[] = []
let firstDegradedRun: number | null = null
let fallbackRuns = 0
let deadRunsBeforeDetection = 0
let naiveLooksCorrect = 0
let allUp = true
// Count how often the real fallback branch logged, as evidence that the
// production code path — not a stand-in — produced these results.
const realLog = console.log
let fallbackLogLines = 0
console.log = (...args: any[]) => {
if (String(args[0]).startsWith('Falling back to local check')) fallbackLogLines++
}
for (let n = 1; n <= totalRuns; n++) {
run.n = n
const now = t0 + n * 60 // cron is every minute
const result = await doMonitor(monitor, localColo, envWithDeadRuns(isDead, run))
const verdict = evaluateProbe(state, monitor.id, result.fromConfiguredRegion, now)
locs.push(result.location)
// The naive alternative: reconstruct the region from the recorded colo, the
// only thing the pre-change state knows. "enam" == a United States colo.
if (codeToCountry(result.location).startsWith('United States')) naiveLooksCorrect++
allUp &&= result.status.up
if (!result.fromConfiguredRegion) fallbackRuns++
if (verdict.degraded && firstDegradedRun === null) {
firstDegradedRun = n
deadRunsBeforeDetection = fallbackRuns
}
if (verdict.crossed) alerts.push(`run ${n}: DRIFT (stale ${verdict.staleFor}s)`)
if (verdict.recovered) alerts.push(`run ${n}: RECOVERED`)
}
console.log = realLog
const uniqueLocs = locs.filter((l, i) => locs.indexOf(l) === i)
console.log(`\n=== ${label} ===`)
console.log(
` runs : ${totalRuns} (cron 1/min), threshold ${PROBE_DRIFT_RUNS} runs / ${PROBE_DRIFT_SECONDS}s`
)
console.log(` real fallback branch : taken ${fallbackLogLines}/${totalRuns} runs (monitor.ts:395)`)
console.log(` page showed location : ${uniqueLocs.join(', ')}`)
console.log(` monitor stayed UP : ${allUp}`)
console.log(` first degraded run : ${firstDegradedRun ?? 'never'}`)
console.log(` dead runs at detect : ${firstDegradedRun ? deadRunsBeforeDetection : '-'}`)
console.log(` alerts : ${alerts.length ? alerts.join(' | ') : 'none'}`)
console.log(
` naive geo test says OK: ${naiveLooksCorrect}/${totalRuns} runs looked like the configured region`
)
return {
alerts,
firstDegradedRun,
uniqueLocs,
allUp,
fallbackRuns,
deadRunsBeforeDetection,
naiveLooksCorrect,
}
}
async function main() {
let ok = true
const check = (cond: boolean, msg: string) => {
console.log(` ${cond ? 'PASS' : 'FAIL'} ${msg}`)
ok &&= cond
}
// ---------------------------------------------------------------- A: dead --
// Healthy for 3 runs, then the Durable Object never answers again.
const dead = await scenario('A) Durable Object permanently dead from run 4', (n) => n >= 4, 40)
check(dead.allUp, 'monitor stays UP throughout — the fallback keeps the page honest, as designed')
check(
dead.uniqueLocs.join() === `${PROBE_COLO},${LOCAL_COLO}`,
`page showed ${PROBE_COLO} then silently ${LOCAL_COLO} forever, with no other signal (the bug)`
)
check(
dead.deadRunsBeforeDetection === PROBE_DRIFT_RUNS,
`detection fires after exactly ${PROBE_DRIFT_RUNS} dead runs, got ${dead.deadRunsBeforeDetection}`
)
check(dead.alerts.length === 1, `exactly one alert over 40 runs, got ${dead.alerts.length}`)
// ---------------------------------------------------------------- B: blip --
const blip = await scenario(
'B) single dropped run (run 5), probe otherwise healthy',
(n) => n === 5,
40
)
check(blip.fallbackRuns === 1, `exactly one fallback run, got ${blip.fallbackRuns}`)
check(blip.firstDegradedRun === null, `single blip never degrades, got ${blip.firstDegradedRun}`)
check(blip.alerts.length === 0, `single blip raises no alert, got ${blip.alerts.length}`)
check(
blip.uniqueLocs.includes(PROBE_COLO) && blip.uniqueLocs.includes(LOCAL_COLO),
'blip run really took the fallback branch'
)
// ------------------------------------------------- C: control for the design
// Same permanently dead probe, but the CRON worker happens to be scheduled in
// IAD — inside enam, the very region being checked. The naive "map the colo
// back to a region" test sees United States on every run and stays silent.
const blind = await scenario(
'C) control — dead probe, but the cron worker sits in the target region (IAD)',
(n) => n >= 4,
40,
'IAD'
)
check(
blind.naiveLooksCorrect === 40,
`naive geo test is blind here: it saw the configured region on ${blind.naiveLooksCorrect}/40 runs`
)
check(
blind.alerts.length === 1 && blind.deadRunsBeforeDetection === PROBE_DRIFT_RUNS,
'the implemented detection still fires — it asks the proxy, not the map'
)
console.log(`\n${ok ? 'GREEN' : 'RED'}`)
if (!ok) process.exitCode = 1
}
main()

View File

@ -152,4 +152,23 @@ export type MonitorStateCompacted = {
time: string // Hex encoded Uint32Array
}
>
// Probe health per monitor — unix seconds of the most recent run whose check
// actually came back from the monitor's CONFIGURED region (`checkProxy`).
//
// Why this exists: with `checkProxyFallback: true` a probe outage is silent.
// monitor.ts falls back to a local re-check, `checkLocation` keeps the local
// colo, and the page stays honest — it names the place it really measured.
// Nothing anywhere says the configured region has stopped answering, so a
// permanently dead Durable Object degrades a two-region page to a one-region
// page without a single signal. This field is that signal.
//
// A timestamp, deliberately not a run counter: the state is only written when
// something changed or after `kvWriteCooldownMinutes` (index.ts:239-249), so
// an increment-per-run counter would silently lose the runs in between. A
// timestamp is idempotent and survives skipped writes.
//
// Optional: states written before this change simply don't have it, and the
// clock starts on the first run after the deploy.
probeOkAt?: Record<string, number> // monitor id -> unix seconds
}

View File

@ -2,8 +2,14 @@ import { DurableObject } from 'cloudflare:workers'
import { MonitorTarget } from '../../types/config'
import { workerConfig } from '../../uptime.config'
import { doMonitor, getStatus } from './monitor'
import { formatAndNotify, getWorkerLocation } from './util'
import { formatAndNotify, getWorkerLocation, webhookNotify } from './util'
import { CompactedMonitorStateWrapper, getFromStore, setToStore } from './store'
import {
evaluateProbe,
formatProbeDriftNotification,
formatProbeRecoveryNotification,
PROBE_DRIFT_RUNS,
} from './probe'
import pLimit from 'p-limit'
export interface Env {
@ -26,7 +32,12 @@ const Worker = {
// Parallel check multiple monitors
// Max concurrent connection is 6 limited by Cloudflare Workers, we use 5 here to be safe
type CheckResult = { id: string; location: string; status: { ping: number; up: boolean; err: string } }
type CheckResult = {
id: string
location: string
status: { ping: number; up: boolean; err: string }
fromConfiguredRegion: boolean
}
let checkQueue: Promise<CheckResult>[] = []
let checkResult: Record<string, CheckResult> = {};
const limit = pLimit(5);
@ -194,6 +205,47 @@ const Worker = {
}
}
// --- probe drift: is this monitor still measuring from its own region? --
// Independent of up/down on purpose. A monitor can be perfectly green and
// still have stopped being the second vantage point it is named after.
const probe = evaluateProbe(
state.data,
monitor.id,
checkResult[monitor.id].fromConfiguredRegion,
currentTimeSecond
)
if (monitor.checkProxy && probe.degraded) {
// Logged every run while degraded: `wrangler tail` is the channel that
// works even with no webhook configured.
console.log(
`[probe-drift] ${monitor.id}: configured region ${monitor.checkProxy} has not ` +
`answered for ${probe.staleFor}s (>= ${PROBE_DRIFT_RUNS} runs); measuring from ` +
`${checkLocation} instead`
)
}
if (monitor.checkProxy && (probe.crossed || probe.recovered)) {
// Notified once per transition, not per run — the point of N is to not
// trade silence for alarm fatigue.
const message = probe.crossed
? formatProbeDriftNotification(
monitor.name,
monitor.checkProxy,
checkLocation,
probe.staleFor
)
: formatProbeRecoveryNotification(monitor.name, monitor.checkProxy)
console.log(message)
if (workerConfig.notification?.webhook) {
try {
await webhookNotify(workerConfig.notification.webhook, message)
} catch (e) {
console.log('Error sending probe drift notification: ' + e)
}
}
// Force the state write so `probeOkAt` and the alert cannot drift apart.
statusChanged = true
}
// append to latency data
state.appendLatency(monitor.id, {
loc: checkLocation,

View File

@ -358,6 +358,12 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
let checkLocation = defaultLocation
let status
// Did this run actually measure from the region the monitor is configured for?
// A monitor without `checkProxy` is configured for "wherever the cron runs",
// so the local colo IS its configured region and it is true by definition.
// With a `checkProxy` it only becomes true when the proxy really answered.
let fromConfiguredRegion = monitor.checkProxy === undefined
if (monitor.checkProxy) {
// Initiate a check using proxy (Geo-specific monitoring)
try {
@ -389,9 +395,14 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
}
checkLocation = resp.location
status = resp.status
fromConfiguredRegion = true
} catch (err) {
console.log(`[${monitor.id}] Error calling proxy: ${err}`)
if (monitor.checkProxyFallback) {
// `fromConfiguredRegion` stays false: the target was measured, but NOT
// from `monitor.checkProxy`. `checkLocation` keeps `defaultLocation`,
// i.e. the local colo — which is the honest answer for the page and at
// the same time the whole reason this branch is invisible.
console.log('Falling back to local check...')
status = await getStatus(monitor)
} else {
@ -410,5 +421,6 @@ export async function doMonitor(monitor: MonitorTarget, defaultLocation: string,
location: checkLocation,
status,
id: monitor.id,
fromConfiguredRegion,
}
}

119
worker/src/probe.ts Normal file
View File

@ -0,0 +1,119 @@
import { MonitorStateCompacted } from '../../types/config'
/**
* Detection for the silent self-healing described in uptime.config.ts:80-85.
*
* `checkProxyFallback: true` is the right setting — a probe outage must not be
* published as a service outage. But it makes the probe outage itself invisible:
* monitor.ts falls back to a local re-check, the page reports the local colo
* (truthfully), and nothing states that the configured region has stopped
* answering. A Durable Object that never comes back therefore turns a
* two-region page into a one-region page in complete silence.
*
* This module is the missing comparison: configured region (`checkProxy`)
* against the region the run actually came from (`fromConfiguredRegion`,
* monitor.ts).
*
* WHY NOT COMPARE THE COLO GEOGRAPHICALLY. The obvious reading of "target
* region vs actual region" is to map the recorded colo (e.g. "EWR") to a
* region and compare it against the hint ("enam"). That test is strictly
* weaker and would have a real blind spot: `checkLocation` on the fallback
* path is the CRON worker's colo, and the cron worker can be scheduled
* anywhere — including inside the very region being checked. A dead enam probe
* whose fallback happens to run in a US colo would look perfect. (Measured
* 2026-07-31: cron colo LHR, probe colo EWR — today it would happen to show,
* tomorrow it need not.) It would also need a ~200-entry country->region table
* whose gaps produce false positives. The proxy call either answered or it did
* not; that is the exact signal, so it is the one used here.
*/
// Consecutive runs from outside the configured region before this is a finding.
// Cron is `* * * * *` (deploy.tf:64-69), so N runs ~ N minutes.
//
// WHY 15:
// * Noise floor: a Durable Object relocation or cold start costs one or two
// runs. N=1 or N=3 would page for every blip — new alarm fatigue, which is
// worse than the silence it replaces.
// * Not the service grace period: `notification.gracePeriod` is 3 because a
// user-visible outage is urgent. A probe that moved is an operations fact,
// not a user-visible outage; it may be found 15 minutes later.
// * Above the write cooldown: state is written at most every
// `kvWriteCooldownMinutes` (3). At 5x that, a skipped state write can never
// manufacture a streak.
export const PROBE_DRIFT_RUNS = 15
export const PROBE_DRIFT_SECONDS = PROBE_DRIFT_RUNS * 60
export type ProbeVerdict = {
/** Seconds since the configured region last answered for this monitor. */
staleFor: number
/** Currently measuring from outside the configured region for >= N runs. */
degraded: boolean
/** This run is the one that crossed the threshold (fire the alert once). */
crossed: boolean
/** The configured region answered again after a degraded stretch. */
recovered: boolean
}
/**
* Folds one check result into `state.probeOkAt` and returns the verdict.
* Mutates `state.probeOkAt` — that is the point, the field has to be persisted.
*
* @param monitorId id of the monitor just checked
* @param fromConfiguredRegion did the run come from `monitor.checkProxy`?
* @param now unix seconds of this run
*/
export function evaluateProbe(
state: MonitorStateCompacted,
monitorId: string,
fromConfiguredRegion: boolean,
now: number
): ProbeVerdict {
const probeOkAt = (state.probeOkAt ??= {})
// First time we see this monitor (fresh state, or first run after deploy):
// start the clock now, so a monitor cannot be born already degraded.
const previousOkAt = probeOkAt[monitorId] ?? now
const staleFor = Math.max(0, now - previousOkAt)
if (fromConfiguredRegion) {
probeOkAt[monitorId] = now
return {
staleFor: 0,
degraded: false,
crossed: false,
recovered: staleFor >= PROBE_DRIFT_SECONDS,
}
}
probeOkAt[monitorId] = previousOkAt
return {
staleFor,
degraded: staleFor >= PROBE_DRIFT_SECONDS,
// Fire once, on the run that crosses. The +-30s window is the idiom already
// used for the grace period in index.ts:129-137 and absorbs clock drift;
// with a 60s cron exactly one run falls inside it.
crossed: staleFor >= PROBE_DRIFT_SECONDS - 30 && staleFor < PROBE_DRIFT_SECONDS + 30,
recovered: false,
}
}
export function formatProbeDriftNotification(
monitorName: string,
configuredRegion: string,
measuredFrom: string,
staleFor: number
): string {
return (
`\u{1F4CD} ${monitorName}: check region "${configuredRegion}" has not answered for ` +
`${Math.round(staleFor / 60)} minutes. Checks are falling back to ${measuredFrom}, ` +
`so this monitor is no longer an independent vantage point. ` +
`Service status itself is unaffected.`
)
}
export function formatProbeRecoveryNotification(
monitorName: string,
configuredRegion: string
): string {
return `\u{2705} ${monitorName}: check region "${configuredRegion}" is answering again.`
}