: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): realign zscore/iqr detector indices after differencing (#76177)
posthog[bot]e086deae940a
diff --git a/posthog/tasks/alerts/detector.py b/posthog/tasks/alerts/detector.pyindex ab2cf2ae7f14..cd4d36eb9ea6 100644--- a/posthog/tasks/alerts/detector.py+++ b/posthog/tasks/alerts/detector.py@@ -101,12 +101,19 @@ def _compute_min_samples_for_detector(detector_config: dict[str, Any]) -> int:# Use the configured window, falling back to the defaultwindow = detector_config.get("window") or DETECTOR_DEFAULT_WINDOW- # Account for preprocessing that consumes usable data points+ # Statistical detectors exclude training_offset_n trailing points from the fit (default 1);+ # a caller-configured larger offset needs the same headroom here as detect()/detect_batch()+ # apply, or every check silently falls short of _validate_data's minimum and never fires.+ offset = max(detector_config.get("training_offset_n") or 1, 1)++ # Account for preprocessing that consumes usable data points. diffs_n only ever runs a single+ # first-difference pass regardless of its configured magnitude (preprocess_data treats it as a+ # boolean), so only one synthetic leading point is ever introduced.preprocessing = detector_config.get("preprocessing") or {}lags_n = preprocessing.get("lags_n") or 0- diffs_n = preprocessing.get("diffs_n") or 0+ diffs_n = 1 if preprocessing.get("diffs_n") else 0- samples_needed = window + 1 + lags_n + diffs_n+ samples_needed = window + offset + lags_n + diffs_n# Never go below the per-detector minimum guardreturn max(samples_needed, guard)diff --git a/posthog/tasks/alerts/detectors/base.py b/posthog/tasks/alerts/detectors/base.pyindex 8007d90c626d..c90ba14686c8 100644--- a/posthog/tasks/alerts/detectors/base.py+++ b/posthog/tasks/alerts/detectors/base.py@@ -31,7 +31,7 @@ class BaseDetector(ABC):def __init__(self, config: dict[str, Any]):self.config = config- self.preprocessing_config = config.get("preprocessing", {})+ self.preprocessing_config = config.get("preprocessing") or {}self.training_offset: int = config.get("training_offset_n", self.DEFAULT_TRAINING_OFFSET)@abstractmethoddiff --git a/posthog/tasks/alerts/detectors/statistical/iqr.py b/posthog/tasks/alerts/detectors/statistical/iqr.pyindex 451a6a3cec97..1fa63e6323e0 100644--- a/posthog/tasks/alerts/detectors/statistical/iqr.py+++ b/posthog/tasks/alerts/detectors/statistical/iqr.py@@ -56,14 +56,26 @@ class IQRDetector(BaseDetector):threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)multiplier = self.config.get("multiplier", 1.5)window = self.config.get("window", 30)+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0+ offset = max(self.training_offset, 1)- if not self._validate_data(data, min_length=window + 1):+ if not self._validate_data(data, min_length=window + offset + diffs_n):return DetectionResult(is_anomaly=False)+ original_length = len(data)data = self.preprocess(data)values = data if data.ndim == 1 else data[:, 0]-- window_data = values[-(window + 1) : -1]+ # Differencing prepends synthetic (zero-valued) points to keep the array+ # length unchanged - drop them so the training window only ever sees+ # genuine differenced values.+ values = values[diffs_n:]++ # Honor training_offset to exclude points closest to the one being+ # scored, so a live check agrees with detect_batch().+ window_data = values[-(window + offset) : -offset]q1 = np.percentile(window_data, 25)q3 = np.percentile(window_data, 75)iqr = q3 - q1@@ -91,7 +103,7 @@ class IQRDetector(BaseDetector):return DetectionResult(is_anomaly=is_anomaly,score=prob,- triggered_indices=[len(values) - 1] if is_anomaly else [],+ triggered_indices=[original_length - 1] if is_anomaly else [],all_scores=[prob],metadata={"q1": float(q1),@@ -108,18 +120,26 @@ class IQRDetector(BaseDetector):threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)multiplier = self.config.get("multiplier", 1.5)window = self.config.get("window", 30)+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0+ offset = max(self.training_offset, 1)- if not self._validate_data(data, min_length=window + 1):+ if not self._validate_data(data, min_length=window + offset + diffs_n):return DetectionResult(is_anomaly=False)data = self.preprocess(data)values = data if data.ndim == 1 else data[:, 0]+ # Keep indices aligned with the original series: scores/triggers below+ # are shifted back by diffs_n before being returned.+ values = values[diffs_n:]triggered = []- scores: list[float | None] = [None] * window+ scores: list[float | None] = [None] * (diffs_n + window + offset - 1)- for i in range(window, len(values)):- window_data = values[i - window : i]+ for i in range(window + offset - 1, len(values)):+ window_data = values[i - window - offset + 1 : i - offset + 1]q1 = np.percentile(window_data, 25)q3 = np.percentile(window_data, 75)iqr = q3 - q1@@ -147,7 +167,7 @@ class IQRDetector(BaseDetector):prob = _iqr_distance_to_probability(raw_distance, window_distances)scores.append(prob)if prob > threshold:- triggered.append(i)+ triggered.append(i + diffs_n)return DetectionResult(is_anomaly=len(triggered) > 0,diff --git a/posthog/tasks/alerts/detectors/statistical/mad.py b/posthog/tasks/alerts/detectors/statistical/mad.pyindex 65040d18908b..b50cd278b50e 100644--- a/posthog/tasks/alerts/detectors/statistical/mad.py+++ b/posthog/tasks/alerts/detectors/statistical/mad.py@@ -29,7 +29,10 @@ class MADDetector(BaseDetector):def detect(self, data: np.ndarray) -> DetectionResult:threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)window = self.config.get("window", 30)- diffs_n = self.preprocessing_config.get("diffs_n", 0) or 0+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0offset = max(self.training_offset, 1)if not self._validate_data(data, min_length=window + offset + diffs_n):@@ -72,7 +75,10 @@ class MADDetector(BaseDetector):def detect_batch(self, data: np.ndarray) -> DetectionResult:threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)window = self.config.get("window", 30)- diffs_n = self.preprocessing_config.get("diffs_n", 0) or 0+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0offset = max(self.training_offset, 1)if not self._validate_data(data, min_length=window + offset + diffs_n):diff --git a/posthog/tasks/alerts/detectors/statistical/zscore.py b/posthog/tasks/alerts/detectors/statistical/zscore.pyindex f7ec3cc37751..2a5e1cfdfd04 100644--- a/posthog/tasks/alerts/detectors/statistical/zscore.py+++ b/posthog/tasks/alerts/detectors/statistical/zscore.py@@ -43,15 +43,27 @@ class ZScoreDetector(BaseDetector):"""Check if the most recent point is an anomaly based on z-score."""threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)window = self.config.get("window", 30)+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0+ offset = max(self.training_offset, 1)- if not self._validate_data(data, min_length=window + 1):+ if not self._validate_data(data, min_length=window + offset + diffs_n):return DetectionResult(is_anomaly=False)+ original_length = len(data)data = self.preprocess(data)values = data if data.ndim == 1 else data[:, 0]-- # Use rolling window for mean/std (exclude current point)- window_data = values[-(window + 1) : -1]+ # Differencing prepends synthetic (zero-valued) points to keep the array+ # length unchanged - drop them so the training window only ever sees+ # genuine differenced values.+ values = values[diffs_n:]++ # Use rolling window for mean/std, honoring training_offset to exclude+ # points closest to the one being scored, so a live check agrees with+ # detect_batch().+ window_data = values[-(window + offset) : -offset]mean = np.mean(window_data)std = np.std(window_data)@@ -62,7 +74,7 @@ class ZScoreDetector(BaseDetector):return DetectionResult(is_anomaly=is_anomaly,score=1.0 if is_anomaly else 0.0,- triggered_indices=[len(values) - 1] if is_anomaly else [],+ triggered_indices=[original_length - 1] if is_anomaly else [],all_scores=[1.0 if is_anomaly else 0.0],metadata={"mean": float(mean), "std": 0.0, "value": float(current_value), "raw_zscore": None},)@@ -74,7 +86,7 @@ class ZScoreDetector(BaseDetector):return DetectionResult(is_anomaly=prob > threshold,score=prob,- triggered_indices=[len(values) - 1] if prob > threshold else [],+ triggered_indices=[original_length - 1] if prob > threshold else [],all_scores=[prob],metadata={"mean": float(mean),@@ -88,18 +100,26 @@ class ZScoreDetector(BaseDetector):"""Check all points for z-score anomalies."""threshold = self.config.get("threshold", self.DEFAULT_THRESHOLD)window = self.config.get("window", 30)+ # preprocess() only ever runs a single first-difference pass when diffs_n is truthy+ # (it's a boolean toggle, not a pass count), so exactly one synthetic leading point+ # is introduced regardless of the configured magnitude.+ diffs_n = 1 if self.preprocessing_config.get("diffs_n") else 0+ offset = max(self.training_offset, 1)- if not self._validate_data(data, min_length=window + 1):+ if not self._validate_data(data, min_length=window + offset + diffs_n):return DetectionResult(is_anomaly=False)data = self.preprocess(data)values = data if data.ndim == 1 else data[:, 0]+ # Keep indices aligned with the original series: scores/triggers below+ # are shifted back by diffs_n before being returned.+ values = values[diffs_n:]triggered = []- scores: list[float | None] = [None] * window+ scores: list[float | None] = [None] * (diffs_n + window + offset - 1)- for i in range(window, len(values)):- window_data = values[i - window : i]+ for i in range(window + offset - 1, len(values)):+ window_data = values[i - window - offset + 1 : i - offset + 1]mean = np.mean(window_data)std = np.std(window_data)@@ -108,7 +128,7 @@ class ZScoreDetector(BaseDetector):if std == 0:if abs(current_val - mean) > 0:scores.append(1.0)- triggered.append(i)+ triggered.append(i + diffs_n)else:scores.append(0.0)continue@@ -119,7 +139,7 @@ class ZScoreDetector(BaseDetector):scores.append(prob)if prob > threshold:- triggered.append(i)+ triggered.append(i + diffs_n)return DetectionResult(is_anomaly=len(triggered) > 0,diff --git a/posthog/tasks/alerts/detectors/test/test_detectors.py b/posthog/tasks/alerts/detectors/test/test_detectors.pyindex 3147cede3c26..e1f27d111dd5 100644--- a/posthog/tasks/alerts/detectors/test/test_detectors.py+++ b/posthog/tasks/alerts/detectors/test/test_detectors.py@@ -181,40 +181,114 @@ class TestStatisticalDetectors:for key in ["q1", "q3", "iqr", "raw_distance"]:assert key in result.metadata- def test_mad_rejects_data_that_only_covers_the_undiffed_window(self) -> None:+ @parameterized.expand(+ [+ ("zscore", ZScoreDetector),+ ("iqr", IQRDetector),+ ("mad", MADDetector),+ ]+ )+ def test_rejects_data_that_only_covers_the_undiffed_window(self, _name: str, detector_cls: Any) -> None:# With diffs_n=1, the training window needs one extra raw point beyond# window+1, otherwise first_difference()'s synthetic leading value (a# zero) would land inside the fit window and silently shrink it by one- # genuine point. window+1 (the old minimum) must now be rejected.+ # genuine point. window+1 must be rejected outright, not scored — a+ # scored-but-not-anomalous flat series would also report is_anomaly=False,+ # so assert the rejection path specifically via its empty metadata/score.data = np.array([10, 10, 10, 10, 10, 10]) # len == window + 1- detector = MADDetector({"threshold": 0.9, "window": 5, "preprocessing": {"diffs_n": 1}})- assert detector.detect(data).is_anomaly is False-- def test_mad_batch_triggered_indices_align_with_raw_series_when_diffing(self) -> None:- # detect_batch trims preprocess()'s synthetic leading points internally;- # triggered_indices/all_scores must be shifted back so callers (which- # map indices to posthog/tasks/alerts/detector.py's original series- # dates) don't get an off-by-one against every date after the first.- detector = MADDetector({"threshold": 0.9, "window": 5, "preprocessing": {"diffs_n": 1}})- result = detector.detect_batch(BATCH_DATA)- assert len(result.all_scores) == len(BATCH_DATA)- assert all(0 <= i < len(BATCH_DATA) for i in result.triggered_indices)- # The spike is at BATCH_DATA[6]; a diffed detector also flags the- # reversion at [7], but never an index outside the raw series.- assert 6 in result.triggered_indices-- def test_mad_detect_honors_training_offset_n(self) -> None:- # detect() used to hardcode a training_offset of 1 regardless of- # config, so training_offset_n had no effect on live checks (only- # detect_batch's loop bounds implicitly depended on window). Placing- # a spike so it falls inside the offset=1 training window but outside- # the offset=4 one must change whether the same current point trips.- data = np.array([9, 11, 10, 9, 11, 10, 30, 11, 14])- offset_1 = MADDetector({"threshold": 0.9, "window": 5, "training_offset_n": 1})- offset_4 = MADDetector({"threshold": 0.9, "window": 5, "training_offset_n": 4})+ detector = detector_cls({"threshold": 0.9, "window": 5, "preprocessing": {"diffs_n": 1}})+ result = detector.detect(data)+ assert result.is_anomaly is False+ assert result.score is None+ assert result.metadata == {}++ @parameterized.expand(+ [+ # zscore's mean/std and MAD's median tolerate the flat baseline BATCH_DATA+ # uses; IQR's fences collapse to zero width on a flat window (a separate,+ # pre-existing gap in IQR's zero-IQR handling), so it needs a baseline with+ # some spread.+ ("zscore", ZScoreDetector, BATCH_DATA, 6),+ ("iqr", IQRDetector, np.array([10, 8, 12, 9, 11, 10, 8, 12, 9, 11, 100, 8, 12, 9]), 10),+ ("mad", MADDetector, BATCH_DATA, 6),+ ]+ )+ def test_batch_triggered_indices_align_with_raw_series_when_diffing(+ self, _name: str, detector_cls: Any, data: Any, spike_index: int+ ) -> None:+ # detect_batch trims preprocess()'s synthetic leading point internally, so the+ # first scorable position is window + diffs_n + offset - 1, not window alone.+ # triggered_indices/all_scores must be shifted back so callers (which map+ # indices to dates on the original series) don't get an off-by-one against+ # every date after the first.+ detector = detector_cls({"threshold": 0.9, "window": 5, "preprocessing": {"diffs_n": 1}})+ result = detector.detect_batch(data)+ assert len(result.all_scores) == len(data)+ assert result.all_scores[:6] == [None] * 6+ assert result.all_scores[6] is not None+ assert all(0 <= i < len(data) for i in result.triggered_indices)+ # A diffed detector may also flag the reversion right after the spike, but+ # never an index outside the raw series.+ assert spike_index in result.triggered_indices++ @parameterized.expand(+ [+ ("zscore", ZScoreDetector, np.array([9, 11, 10, 9, 11, 10, 30, 11, 14])),+ ("iqr", IQRDetector, np.array([9, 11, 10, 9, 11, 10, 30, 11, 20])),+ ("mad", MADDetector, np.array([9, 11, 10, 9, 11, 10, 30, 11, 14])),+ ]+ )+ def test_detect_honors_training_offset_n(self, _name: str, detector_cls: Any, data: Any) -> None:+ # Changing training_offset_n must change which historical points enter the+ # training window: a spike that falls inside the offset=1 window but outside+ # the offset=4 one must flip whether the same trailing point is flagged.+ offset_1 = detector_cls({"threshold": 0.9, "window": 5, "training_offset_n": 1})+ offset_4 = detector_cls({"threshold": 0.9, "window": 5, "training_offset_n": 4})assert offset_1.detect(data).is_anomaly is Falseassert offset_4.detect(data).is_anomaly is True+ @parameterized.expand(+ [+ ("zscore", ZScoreDetector),+ ("iqr", IQRDetector),+ ("mad", MADDetector),+ ]+ )+ def test_handles_explicit_none_preprocessing(self, _name: str, detector_cls: Any) -> None:+ # Serializers round-trip a detector_config with an explicit "preprocessing": None+ # key (not merely omitted) when no preprocessing was configured. `config.get(key,+ # {})` only falls back to `{}` when the key is absent, so a present-but-None value+ # used to reach detect()/detect_batch() as None and crash on `.get("diffs_n", ...)`.+ detector = detector_cls({"threshold": 0.9, "window": 5, "preprocessing": None})+ data = np.arange(20, dtype=float)+ detector.detect(data)+ detector.detect_batch(data)++ @parameterized.expand(+ [+ (f"{name}_diffs_{diffs_n}", detector_type, detector_cls, diffs_n)+ for name, detector_type, detector_cls in (+ ("zscore", "zscore", ZScoreDetector),+ ("iqr", "iqr", IQRDetector),+ ("mad", "mad", MADDetector),+ )+ for diffs_n in (0, 1, 2)+ ]+ )+ def test_detect_scores_the_sample_count_the_check_fetches(+ self, _name: str, detector_type: str, detector_cls: Any, diffs_n: int+ ) -> None:+ # A check only fetches _compute_min_samples_for_detector() points, so any detector+ # demanding more silently returns the _validate_data rejection (score None) forever+ # instead of firing. preprocess_data treats diffs_n as a boolean toggle, so a+ # detector counting it as a pass count over-reserves once diffs_n > 1 and drifts+ # out of agreement with the fetch.+ window = 30+ config = {"type": detector_type, "window": window, "preprocessing": {"diffs_n": diffs_n}}+ data = np.array([10.0] * (_compute_min_samples_for_detector(config) - 1) + [500.0])+ result = detector_cls({"threshold": 0.9, "window": window, "preprocessing": {"diffs_n": diffs_n}}).detect(data)+ assert result.score is not None+class TestPyODDetectors:@parameterized.expand(PYOD_DETECTORS_FOR_ANOMALY_TEST)