Detect a mean shift with CUSUM
Why it matters Monitoring for model quality drift and error-rate spikes uses CUSUM-style detectors.
CUSUM watches a metric and raises an alarm when it drifts upward from its target.
Write cusum_alarm(x, target, k, h). Keep S = 0. For each t: S = max(0, S + x[t] - target - k). Return the first index t where S > h, or -1 if it never happens.
def cusum_alarm(x, target, k, h)Example
cusum_alarm([0, 0, 3, 3, 3], 0, 0.5, 4) gives S = 0, 0, 2.5, 5.0, so the alarm is at index 3.
Understand the idea
CUSUM is a running score that grows when a metric sits above its target and resets to zero when things look normal. A small slack k ignores ordinary noise, and an alarm fires when the score crosses a threshold h. Like a cricket scorer adding up extra runs conceded, but wiping the slate clean after a good over. Worked example: x = [1, 0, 3, 3, 2], target 1, k 0.5, h 2. Each step adds x - 1 - 0.5. t = 0: 0 + (-0.5), clamped to 0. t = 1: 0 + (-1.5), clamped to 0. t = 2: 0 + 1.5 = 1.5. t = 3: 1.5 + 1.5 = 3.0, which is above 2, so the alarm is at index 3. Rule: S starts at 0; for each t, S = max(0, S + x[t] - target - k); return the first t with S > h, or -1 if none. The clamp at zero matters: without it, a long run of low values builds a debt that delays the alarm on a real shift. Used in: detecting latency regressions, drift in model scores, and quality control.