:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(alerts): make detector moving-average smoothing causal (#76434)
posthog[bot]1c4bc70d063a
diff --git a/posthog/tasks/alerts/detectors/preprocessing.py b/posthog/tasks/alerts/detectors/preprocessing.pyindex a821b95a8777..acbeefa5165f 100644--- a/posthog/tasks/alerts/detectors/preprocessing.py+++ b/posthog/tasks/alerts/detectors/preprocessing.py@@ -51,14 +51,19 @@ def first_difference(data: np.ndarray) -> np.ndarray:def moving_average(data: np.ndarray, window: int) -> np.ndarray:"""Simple moving average smoothing.- Uses 'same' mode to preserve array length.++ Trailing (causal) window: index i averages data[i - window + 1 : i + 1], padding+ only on the left. A centered window would average the most recent point against+ padding replicated from itself, then need `window - 1` more real points to arrive+ before that point's smoothed value stabilizes - each new point silently changes+ the smoothed value of points already reported, and shifts an anomaly's peak score+ onto a later, unrelated point instead of the one where the deviation happened."""if len(data) < window:return datakernel = np.ones(window) / window- # Use 'same' mode but handle edges by padding- padded = np.pad(data, (window // 2, window - 1 - window // 2), mode="edge")+ padded = np.pad(data, (window - 1, 0), mode="edge")smoothed = np.convolve(padded, kernel, mode="valid")return smootheddiff --git a/posthog/tasks/alerts/detectors/test/test_detectors.py b/posthog/tasks/alerts/detectors/test/test_detectors.pyindex e1f27d111dd5..9e3df13738f0 100644--- a/posthog/tasks/alerts/detectors/test/test_detectors.py+++ b/posthog/tasks/alerts/detectors/test/test_detectors.py@@ -8,6 +8,7 @@ from parameterized import parameterizedfrom posthog.tasks.alerts.detector import _compute_min_samples_for_detectorfrom posthog.tasks.alerts.detectors.base import DetectionResultfrom posthog.tasks.alerts.detectors.ensemble import EnsembleDetector+from posthog.tasks.alerts.detectors.preprocessing import moving_averagefrom posthog.tasks.alerts.detectors.pyod_detectors.copod import COPODDetectorfrom posthog.tasks.alerts.detectors.pyod_detectors.ecod import ECODDetectorfrom posthog.tasks.alerts.detectors.pyod_detectors.hbos import HBOSDetector@@ -290,6 +291,40 @@ class TestStatisticalDetectors:assert result.score is not None+class TestMovingAverageSmoothing:+ def test_smoothed_value_is_stable_once_computed(self) -> None:+ # moving_average recomputes over the whole series on every call, since each+ # detector check re-preprocesses the full historical window it fetches. A+ # centered window pads the newest point with a replica of itself, so its+ # smoothed value is provisional and silently changes once real future points+ # arrive - a look-ahead bug for anything scored incrementally. Causal+ # (trailing) smoothing must give a point the same smoothed value regardless+ # of how much data arrives after it.+ data = np.array([20.0, 19.0, 21.0, 2.0, 21.0, 20.0, 19.0, 21.0])+ first_look = moving_average(data[:4], window=3)[-1]+ later_look = moving_average(data, window=3)[3]+ assert first_look == later_look++ def test_anomaly_attributed_to_the_drop_not_the_rebound(self) -> None:+ # Regression for a live gateway-volume alert: with the old centered,+ # edge-padded moving_average, a single-point cliff scored as non-anomalous+ # at the bucket where it happened (score 0.0) and only crossed the threshold+ # two buckets later, once the cliff was fully interior to the window and the+ # recovery had entered it too - attributing the anomaly to a normal-looking+ # rebound point instead of the actual drop.+ baseline = [20, 19, 21] * 11+ data = np.array(baseline, dtype=float)+ cliff_index = len(data) - 6+ data[cliff_index] = 2.0+ data[cliff_index + 1] = 21.0++ detector = ZScoreDetector({"threshold": 0.9, "window": 10, "preprocessing": {"smooth_n": 3, "diffs_n": 1}})+ result = detector.detect_batch(data)++ assert cliff_index in result.triggered_indices+ assert cliff_index + 2 not in result.triggered_indices++class TestPyODDetectors:@parameterized.expand(PYOD_DETECTORS_FOR_ANOMALY_TEST)def test_detect_anomaly(self, _name: str, detector: Any) -> None: