: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
refactor(alerts): converge anomaly-detector path onto the evaluation contract (#62668)
Vasco de Krijger3910ff769ae5
diff --git a/posthog/tasks/alerts/detector.py b/posthog/tasks/alerts/detector.pyindex 4da72ce8802c..6692fa289121 100644--- a/posthog/tasks/alerts/detector.py+++ b/posthog/tasks/alerts/detector.py@@ -1,27 +1,12 @@from dataclasses import dataclass-from typing import Any, cast+from typing import Anyimport numpy as np-from posthog.schema import DetectorType, IntervalType, TrendsAlertConfig, TrendsQuery+from posthog.schema import DetectorType, IntervalType, TrendsQuery-from posthog.api.services.query import ExecutionMode-from posthog.caching.calculate_results import calculate_for_query_based_insight-from posthog.schema_migrations.upgrade_manager import upgrade_query-from posthog.tasks.alerts.detectors import get_detectorfrom posthog.tasks.alerts.detectors.base import DetectionResult-from posthog.tasks.alerts.trends import (- TrendResult,- _drop_incomplete_current_interval,- _has_breakdown,- _is_non_time_series_trend,- _pick_series_result,-)-from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult-from posthog.utils import get_from_dict_or_attr--from products.alerts.backend.models.alert import AlertConfiguration-from products.product_analytics.backend.models.insight import Insight+from posthog.tasks.alerts.trends import TrendResult, _drop_incomplete_current_interval# Minimum samples required for each detector typeDETECTOR_MIN_SAMPLES: dict[DetectorType, int] = {@@ -48,11 +33,6 @@ DETECTOR_DEFAULT_WINDOW = 30MAX_DETECTOR_BREAKDOWN_VALUES = 25-# ----------------------------------------------------------------------------# Shared data-prep and detection helpers-# -----------------------------------------------------------------------------@dataclassclass PreparedSeries:"""Data extracted from a TrendResult, ready for detection."""@@ -81,13 +61,6 @@ def _prepare_series(series: TrendResult, is_non_time_series: bool) -> PreparedSereturn PreparedSeries(data=data, dates=dates, label=series.get("label", "Series"))-def _map_triggered_dates(result: DetectionResult, dates: list[str]) -> list[str]:- """Map triggered indices to their corresponding date strings."""- if not result.triggered_indices or not dates:- return []- return [dates[i] for i in result.triggered_indices if i < len(dates)]--def _extract_sub_detector_scores(detector_type_str: str, result: DetectionResult) -> list[dict[str, Any]] | None:"""Extract per-sub-detector scores for ensemble detectors."""if detector_type_str != "ensemble" or not result.metadata:@@ -101,11 +74,6 @@ def _extract_sub_detector_scores(detector_type_str: str, result: DetectionResultreturn scores or None-# ----------------------------------------------------------------------------# Min-samples and date-range helpers-# -----------------------------------------------------------------------------def _compute_min_samples_for_detector(detector_config: dict[str, Any]) -> int:"""Compute the number of historical data points needed for a detector.@@ -157,272 +125,3 @@ def _date_range_override_for_detector(query: TrendsQuery, min_samples: int) -> ddate_from = f"-{min_samples}h"return {"date_from": date_from}---# ----------------------------------------------------------------------------# Alert check-# ------------------------------------------------------------------------------def check_trends_alert_with_detector(- alert: AlertConfiguration, insight: Insight, query: TrendsQuery, detector_config: dict[str, Any]-) -> AlertEvaluationResult:- """Check a trends alert using detector-based anomaly detection."""- config = (- TrendsAlertConfig.model_validate(alert.config)- if alert.config- else TrendsAlertConfig(type="TrendsAlertConfig", series_index=0)- )- detector_type_str = detector_config.get("type", "zscore")-- # Request one extra sample because we drop the current (incomplete) interval.- min_samples = _compute_min_samples_for_detector(detector_config) + 1- filters_override = _date_range_override_for_detector(query, min_samples)-- is_non_time_series = _is_non_time_series_trend(query)- if is_non_time_series:- filters_override = None-- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE- if query.interval == IntervalType.HOUR:- execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS-- calculation_result = calculate_for_query_based_insight(- insight,- team=alert.team,- execution_mode=execution_mode,- user=None,- filters_override=filters_override,- )-- if calculation_result.result is None:- raise RuntimeError(f"No results found for insight with alert id = {alert.id}")-- if not calculation_result.result:- return AlertEvaluationResult(- value=0,- breaches=[],- interval=query.interval.value if query.interval else None,- )-- interval_value = query.interval.value if query.interval else None-- if _has_breakdown(query):- breakdown_results = cast(list[TrendResult], calculation_result.result)[:MAX_DETECTOR_BREAKDOWN_VALUES]-- for bd_index, breakdown_result in enumerate(breakdown_results):- prepared = _prepare_series(breakdown_result, is_non_time_series)- if prepared is None:- continue-- detector = get_detector(detector_config)- result = detector.detect(prepared.data)-- if result.is_anomaly:- current_value = float(prepared.data[-1])- score_str = f" (anomaly probability: {result.score:.0%})" if result.score is not None else ""- return AlertEvaluationResult(- value=current_value,- breaches=[- f"Anomaly detected in {prepared.label}: value {current_value:.2f}{score_str} using {detector_type_str} detector"- ],- anomaly_scores=result.all_scores or None,- triggered_points=result.triggered_indices if result.triggered_indices else None,- triggered_dates=_map_triggered_dates(result, prepared.dates) or None,- interval=interval_value,- triggered_metadata={"series_index": bd_index},- )-- return AlertEvaluationResult(value=None, breaches=[], interval=interval_value)-- # Non-breakdown: pick a single series by index- selected = _pick_series_result(config, calculation_result)- prepared = _prepare_series(selected, is_non_time_series)- if prepared is None:- return AlertEvaluationResult(value=None, breaches=[], interval=interval_value)-- detector = get_detector(detector_config)- result = detector.detect(prepared.data)-- triggered_dates = _map_triggered_dates(result, prepared.dates) or None-- breaches: list[str] = []- if result.is_anomaly:- current_value = float(prepared.data[-1])- score_str = f" (anomaly probability: {result.score:.0%})" if result.score is not None else ""-- sub_scores_str = ""- if detector_type_str == "ensemble" and result.metadata:- sub_results = result.metadata.get("sub_results", [])- if sub_results:- parts = []- for sr in sub_results:- sr_type = sr.get("type", "unknown")- sr_score = sr.get("score")- sr_fired = sr.get("is_anomaly", False)- score_pct = f"{sr_score:.0%}" if sr_score is not None else "n/a"- parts.append(f"{sr_type}: {score_pct}{' [fired]' if sr_fired else ''}")- sub_scores_str = f" | sub-detectors: {', '.join(parts)}"-- breaches.append(- f"Anomaly detected in {prepared.label}: value {current_value:.2f}{score_str} using {detector_type_str} detector{sub_scores_str}"- )-- return AlertEvaluationResult(- value=float(prepared.data[-1]) if len(prepared.data) > 0 else None,- breaches=breaches if breaches else [],- anomaly_scores=result.all_scores or None,- triggered_points=result.triggered_indices if result.triggered_indices else None,- triggered_dates=triggered_dates,- interval=interval_value,- )---# ----------------------------------------------------------------------------# Simulation (read-only, no AlertCheck records)-# ------------------------------------------------------------------------------def _build_series_sim_result(- prepared: PreparedSeries,- detector_config: dict[str, Any],- detector_type_str: str,-) -> dict[str, Any]:- """Run detect_batch on a single prepared series and return a simulation result dict."""- detector = get_detector(detector_config)- result = detector.detect_batch(prepared.data)-- triggered_dates = _map_triggered_dates(result, prepared.dates)- scores = result.all_scores if result.all_scores else [None] * len(prepared.data)-- sim: dict[str, Any] = {- "label": prepared.label,- "data": prepared.data.tolist(),- "dates": prepared.dates,- "scores": scores,- "triggered_indices": result.triggered_indices or [],- "triggered_dates": triggered_dates,- "total_points": len(prepared.data),- "anomaly_count": len(result.triggered_indices) if result.triggered_indices else 0,- }-- sub_scores = _extract_sub_detector_scores(detector_type_str, result)- if sub_scores:- sim["sub_detector_scores"] = sub_scores-- return sim---def simulate_detector_on_insight(- insight: Insight,- team: Any,- detector_config: dict[str, Any],- series_index: int = 0,- date_from: str | None = None,-) -> dict[str, Any]:- """Run a detector over historical insight data for chart visualization.-- No AlertCheck records are created — this is read-only.- """- if insight.query is None:- raise ValueError("Insight has no valid query.")-- with upgrade_query(insight):- query = insight.query-- kind = get_from_dict_or_attr(query, "kind")- if kind in WRAPPER_NODE_KINDS:- query = get_from_dict_or_attr(query, "source")- kind = get_from_dict_or_attr(query, "kind")-- if kind != "TrendsQuery":- raise ValueError("Only TrendsQuery insights are supported for simulation.")-- trends_query = TrendsQuery.model_validate(query)- detector_type_str = detector_config.get("type", "zscore")- min_samples = _compute_min_samples_for_detector(detector_config)-- # +1 because _drop_incomplete_current_interval removes the last point- min_samples_with_padding = min_samples + 1- min_date_from = _date_range_override_for_detector(trends_query, min_samples_with_padding)-- is_non_time_series = _is_non_time_series_trend(trends_query)- if is_non_time_series:- filters_override = None- elif date_from:- # Use whichever goes further back: the user's range or the detector minimum.- # We parse both to absolute datetimes and pick the earlier one.- from zoneinfo import ZoneInfo-- from posthog.utils import relative_date_parse-- utc = ZoneInfo("UTC")- user_dt = relative_date_parse(date_from, utc)- min_dt = relative_date_parse(min_date_from["date_from"], utc) if min_date_from else None- if min_dt and min_dt < user_dt:- filters_override = min_date_from- else:- filters_override = {"date_from": date_from}- else:- filters_override = min_date_from-- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE- if trends_query.interval == IntervalType.HOUR:- execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS-- calculation_result = calculate_for_query_based_insight(- insight,- team=team,- execution_mode=execution_mode,- user=None,- filters_override=filters_override,- )-- if calculation_result.result is None or not calculation_result.result:- raise ValueError("No results found for insight.")-- interval_value = trends_query.interval.value if trends_query.interval else None-- if _has_breakdown(trends_query):- all_results = cast(list[TrendResult], calculation_result.result)[:MAX_DETECTOR_BREAKDOWN_VALUES]- breakdown_sims: list[dict[str, Any]] = []- total_points = 0- total_anomalies = 0-- for br in all_results:- prepared = _prepare_series(br, is_non_time_series)- if prepared is None:- continue-- sim = _build_series_sim_result(prepared, detector_config, detector_type_str)- breakdown_sims.append(sim)- total_points += sim["total_points"]- total_anomalies += sim["anomaly_count"]-- if not breakdown_sims:- raise ValueError("No breakdown values had enough data points for simulation.")-- return {- "data": [],- "dates": [],- "scores": [],- "triggered_indices": [],- "triggered_dates": [],- "interval": interval_value,- "total_points": total_points,- "anomaly_count": total_anomalies,- "breakdown_results": breakdown_sims,- }-- # Non-breakdown- config = TrendsAlertConfig(type="TrendsAlertConfig", series_index=series_index)- selected = _pick_series_result(config, calculation_result)- prepared = _prepare_series(selected, is_non_time_series)- if prepared is None:- raise ValueError("No data points found for the selected series.")-- sim = _build_series_sim_result(prepared, detector_config, detector_type_str)-- # For non-breakdown, promote fields to top level (no "label" key)- sim.pop("label", None)- return {**sim, "interval": interval_value}diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.pyindex 2bfd8102f488..86661ef79224 100644--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py@@ -1,7 +1,10 @@from typing import Any+import pytestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from posthog.schema import (AlertCalculationInterval,BaseMathType,@@ -10,17 +13,20 @@ from posthog.schema import (ChartDisplayType,EventsNode,IntervalType,+ NodeKind,TrendsFilter,TrendsQuery,)from posthog.caching.fetch_from_cache import InsightResult-from posthog.tasks.alerts.detector import (- MAX_DETECTOR_BREAKDOWN_VALUES,- check_trends_alert_with_detector,+from posthog.tasks.alerts.detector import MAX_DETECTOR_BREAKDOWN_VALUES++from products.alerts.backend.evaluation.detector import (+ evaluate_with_detector,+ extract_detector_series,simulate_detector_on_insight,)-+from products.alerts.backend.evaluation.dispatcher import check_detector_alertfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.models.insight import Insight@@ -83,7 +89,7 @@ ZSCORE_DETECTOR_CONFIG = {"type": "zscore", "threshold": 0.9, "window": 10}class TestCheckTrendsAlertWithDetectorBreakdowns:- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_fires_when_one_breakdown_is_anomalous(self, mock_calc: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -102,7 +108,7 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_with_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)assert result.breaches is not None and len(result.breaches) > 0assert "staking" in result.breaches[0]@@ -110,7 +116,7 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:# "staking" is at index 1 in the breakdown resultsassert result.triggered_metadata == {"series_index": 1}- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_does_not_fire_when_all_breakdowns_are_normal(self, mock_calc: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -130,12 +136,12 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_with_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)assert result.breaches == []assert result.value is None- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_caps_at_max_breakdown_values(self, mock_calc: MagicMock) -> None:# Create more than MAX_DETECTOR_BREAKDOWN_VALUES breakdown results# Put the anomaly in the last one (beyond the cap)@@ -162,12 +168,12 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_with_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)# The anomalous breakdown is beyond the cap, so it should NOT fireassert result.breaches == []- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_skips_breakdown_with_insufficient_data(self, mock_calc: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -186,12 +192,12 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_with_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)# Should not error, and should not fire (stable data only)assert result.breaches == []- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_non_breakdown_still_works(self, mock_calc: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -209,14 +215,14 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_without_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)assert result.breaches is not None and len(result.breaches) > 0assert "Anomaly detected" in result.breaches[0]# Non-breakdown alerts should not set triggered_metadataassert result.triggered_metadata is None- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_breakdown_result_includes_anomaly_scores(self, mock_calc: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -234,16 +240,75 @@ class TestCheckTrendsAlertWithDetectorBreakdowns:insight = MagicMock(spec=Insight)query = _make_query_with_breakdown()- result = check_trends_alert_with_detector(alert, insight, query, ZSCORE_DETECTOR_CONFIG)+ result = check_detector_alert(alert, insight, query)assert result.anomaly_scores is not Noneassert result.triggered_points is not Noneassert result.interval == "day"+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")+ def test_empty_query_result_reports_zero(self, mock_calc: MagicMock) -> None:+ # No rows at all → the metric genuinely is 0, distinct from "couldn't compute".+ mock_calc.return_value = InsightResult(+ result=[], columns=[], timezone="UTC", last_refresh=None, cache_key="", is_cached=False+ )++ alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)+ extraction = extract_detector_series(+ MagicMock(spec=Insight), alert.team, _make_query_without_breakdown(), ZSCORE_DETECTOR_CONFIG+ )+ assert extraction.series == []+ assert extraction.empty_query_result is True++ result = evaluate_with_detector(extraction, ZSCORE_DETECTOR_CONFIG)+ assert result.value == 0+ assert result.breaches == []++ @parameterized.expand(+ [+ ("non_breakdown", _make_query_without_breakdown(), [_make_trend_result("signed_up", [5.0], "")]),+ (+ "breakdown_all_short",+ _make_query_with_breakdown(),+ [_make_trend_result("a", [5.0], "a"), _make_trend_result("b", [3.0], "b")],+ ),+ ]+ )+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")+ def test_unscorable_series_report_uncomputed_value(+ self, _name: str, query: TrendsQuery, result_data: list[dict[str, Any]], mock_calc: MagicMock+ ) -> None:+ # Rows exist but every series is too short to score → value is None (NULL), not 0.+ mock_calc.return_value = InsightResult(+ result=result_data, columns=[], timezone="UTC", last_refresh=None, cache_key="", is_cached=False+ )++ alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)+ extraction = extract_detector_series(MagicMock(spec=Insight), alert.team, query, ZSCORE_DETECTOR_CONFIG)+ assert extraction.series == []+ assert extraction.empty_query_result is False++ result = evaluate_with_detector(extraction, ZSCORE_DETECTOR_CONFIG)+ assert result.value is None+ assert result.breaches == []++ @parameterized.expand(+ [+ ("hogql", NodeKind.HOG_QL_QUERY),+ ("funnels", NodeKind.FUNNELS_QUERY),+ ]+ )+ def test_detector_alert_on_unsupported_kind_raises(self, _name: str, kind: NodeKind) -> None:+ # Detector alerts are trends-only: a detector_config on any other insight kind is rejected+ # loudly via the DETECTOR_EXTRACTORS miss, not silently routed to the threshold path.+ alert = _make_alert(MagicMock(), ZSCORE_DETECTOR_CONFIG)+ with pytest.raises(NotImplementedError):+ check_detector_alert(alert, MagicMock(spec=Insight), {"kind": kind})+class TestSimulateDetectorBreakdowns:- @patch("posthog.tasks.alerts.detector.upgrade_query")- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.upgrade_query")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_returns_breakdown_results(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -274,8 +339,8 @@ class TestSimulateDetectorBreakdowns:# Aggregated totals (each series has 1 point dropped for the incomplete current interval)assert result["total_points"] == (len(STABLE_DATA) - 1) + (len(ANOMALOUS_DATA) - 1)- @patch("posthog.tasks.alerts.detector.upgrade_query")- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.upgrade_query")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_non_breakdown_has_no_breakdown_results(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:mock_calc.return_value = InsightResult(result=[@@ -300,8 +365,8 @@ class TestSimulateDetectorBreakdowns:assert "breakdown_results" not in result- @patch("posthog.tasks.alerts.detector.upgrade_query")- @patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @patch("products.alerts.backend.evaluation.detector.upgrade_query")+ @patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_caps_breakdown_simulations(self, mock_calc: MagicMock, _mock_upgrade: MagicMock) -> None:breakdown_results = [_make_trend_result(f"origin_{i}", STABLE_DATA, f"origin_{i}")diff --git a/posthog/temporal/ai/anomaly_investigation/tools.py b/posthog/temporal/ai/anomaly_investigation/tools.pyindex 8359d1c8f97e..1630b1c2515e 100644--- a/posthog/temporal/ai/anomaly_investigation/tools.py+++ b/posthog/temporal/ai/anomaly_investigation/tools.py@@ -105,7 +105,7 @@ def _run_detector_simulation("""# Imported lazily because the workflow module can't pull in heavy query machinery# at Temporal workflow-definition time — only activities can.- from posthog.tasks.alerts.detector import simulate_detector_on_insight+ from products.alerts.backend.evaluation.detector import simulate_detector_on_insighttry:return simulate_detector_on_insight(diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 906cf98ad98a..be2c5fa6318f 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -10,7 +10,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.schema import AlertCalculationInterval, AlertState-from posthog.clickhouse.query_tagging import tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.errors import CH_TRANSIENT_ERRORSfrom posthog.exceptions_capture import capture_exceptionfrom posthog.schema_migrations.upgrade_manager import upgrade_query@@ -201,8 +201,8 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRenon_retryable=True,)- # CH workload management keys off this tag to isolate alert queries from other tenants.- tag_queries(alert_config_id=str(alert.id))+ # CH workload management keys off these tags to isolate alert queries from other tenants.+ tag_queries(alert_config_id=str(alert.id), product=Product.PRODUCT_ANALYTICS, feature=Feature.ALERTING)# Snapshot before add_alert_check mutates alert.state — needed to detect the# NOT_FIRING/ERRORED -> FIRING transition that triggers an investigation.diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.pyindex 38ff338dec0e..71311f6070ad 100644--- a/products/alerts/backend/api/alert.py+++ b/products/alerts/backend/api/alert.py@@ -39,6 +39,7 @@ from posthog.tasks.alerts.utils import (from posthog.utils import relative_date_parsefrom products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction+from products.alerts.backend.evaluation.detector import simulate_detector_on_insightfrom products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Thresholdfrom products.product_analytics.backend.models.insight import Insight@@ -915,8 +916,6 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(detail=False, methods=["POST"], url_path="simulate", required_scopes=["alert:read"])def simulate(self, request, *args, **kwargs):- from posthog.tasks.alerts.detector import simulate_detector_on_insight-serializer = AlertSimulateSerializer(data=request.data, context=self.get_serializer_context())serializer.is_valid(raise_exception=True)diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.pyindex 9519c68d4ef8..94df98a0affe 100644--- a/products/alerts/backend/api/test/test_alert.py+++ b/products/alerts/backend/api/test/test_alert.py@@ -1007,7 +1007,7 @@ class TestAlertSimulate(APIBaseTest):}self.insight = self.client.post(f"/api/projects/{self.team.id}/insights", data=self.insight_data).json()- @mock.patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @mock.patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_simulate_returns_valid_response(self, mock_calculate) -> None:mock_calculate.return_value = mock.MagicMock(result=[@@ -1073,7 +1073,7 @@ class TestAlertSimulate(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST- @mock.patch("posthog.tasks.alerts.detector.calculate_for_query_based_insight")+ @mock.patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")def test_simulate_does_not_create_alert_check_records(self, mock_calculate) -> None:mock_calculate.return_value = mock.MagicMock(result=[diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.pynew file mode 100644index 000000000000..b897f538f7ad--- /dev/null+++ b/products/alerts/backend/evaluation/detector.py@@ -0,0 +1,275 @@+from typing import Any, cast+from zoneinfo import ZoneInfo++import numpy as np++from posthog.schema import IntervalType, NodeKind, TrendsAlertConfig, TrendsQuery++from posthog.api.services.query import ExecutionMode+from posthog.caching.calculate_results import calculate_for_query_based_insight+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.schema_migrations.upgrade_manager import upgrade_query++# Low-level scoring/extraction primitives still live in the legacy detector module.+from posthog.tasks.alerts.detector import (+ MAX_DETECTOR_BREAKDOWN_VALUES,+ _compute_min_samples_for_detector,+ _date_range_override_for_detector,+ _extract_sub_detector_scores,+ _prepare_series,+)+from posthog.tasks.alerts.detectors import get_detector+from posthog.tasks.alerts.trends import TrendResult, _has_breakdown, _is_non_time_series_trend, _pick_series_result+from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult+from posthog.utils import get_from_dict_or_attr, relative_date_parse++from products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult, SeriesPoint+from products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight+++def extract_detector_series(+ insight: Insight,+ team: Any,+ query: TrendsQuery,+ detector_config: dict[str, Any],+ *,+ series_index: int = 0,+ date_from: str | None = None,+) -> ExtractionResult:+ """Run a trends insight over the detector's lookback window and normalize it into series.++ Each ``ComparableSeries`` carries the full (complete-interval) history the detector scores —+ the incomplete current interval is already dropped by ``_prepare_series``. Raises on a ``None``+ result (swallowed query error). A genuinely empty query result yields an empty series list with+ ``empty_query_result=True``; rows that exist but are too short to score are dropped, also leaving+ an empty series list, but with the flag False — the two cases evaluate to 0 and None respectively.+ """+ min_samples = _compute_min_samples_for_detector(detector_config) + 1+ is_non_time_series = _is_non_time_series_trend(query)+ has_breakdown = _has_breakdown(query)++ if is_non_time_series:+ filters_override = None+ elif date_from:+ # Use whichever goes further back: the caller's range or the detector minimum.+ min_date_from = _date_range_override_for_detector(query, min_samples)+ utc = ZoneInfo("UTC")+ user_dt = relative_date_parse(date_from, utc)+ min_dt = relative_date_parse(min_date_from["date_from"], utc) if min_date_from else None+ filters_override = min_date_from if (min_dt and min_dt < user_dt) else {"date_from": date_from}+ else:+ filters_override = _date_range_override_for_detector(query, min_samples)++ execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ if query.interval == IntervalType.HOUR:+ execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS++ calculation_result = calculate_for_query_based_insight(+ insight, team=team, execution_mode=execution_mode, user=None, filters_override=filters_override+ )++ if calculation_result.result is None:+ raise RuntimeError(f"No results found for insight with id = {insight.id}")+ if not calculation_result.result:+ return ExtractionResult(+ series=[], is_breakdown=has_breakdown, interval_type=query.interval, empty_query_result=True+ )++ if has_breakdown:+ results = cast(list[TrendResult], calculation_result.result)[:MAX_DETECTOR_BREAKDOWN_VALUES]+ else:+ config = TrendsAlertConfig(type="TrendsAlertConfig", series_index=series_index)+ results = [_pick_series_result(config, calculation_result)]++ series: list[ComparableSeries] = []+ for result in results:+ prepared = _prepare_series(result, is_non_time_series)+ if prepared is None:+ continue+ points = [+ SeriesPoint(date=(prepared.dates[i] if i < len(prepared.dates) else None), value=float(value))+ for i, value in enumerate(prepared.data)+ ]+ # current_index is set for contract conformance but unread on this path: the detector scores+ # the whole series rather than comparing against a single anchor interval.+ series.append(ComparableSeries(label=prepared.label, points=points, current_index=len(points) - 1))++ return ExtractionResult(series=series, is_breakdown=has_breakdown, interval_type=query.interval)+++def _triggered_dates(series: ComparableSeries, triggered_indices: list[int]) -> list[str]:+ """Map triggered indices to their date strings, skipping points that carry no date."""+ return [date for i in triggered_indices if i < len(series.points) and (date := series.points[i].date) is not None]+++def _anomaly_breach(+ label: str, current_value: float, score: float | None, detector_type_str: str, suffix: str = ""+) -> str:+ score_str = f" (anomaly probability: {score:.0%})" if score is not None else ""+ return (+ f"Anomaly detected in {label}: value {current_value:.2f}{score_str} using {detector_type_str} detector{suffix}"+ )+++def _format_sub_detector(sub_result: dict[str, Any]) -> str:+ """Render one ensemble sub-detector's score for the breach message suffix."""+ score = sub_result.get("score")+ score_pct = f"{score:.0%}" if score is not None else "n/a"+ fired = " [fired]" if sub_result.get("is_anomaly", False) else ""+ return f"{sub_result.get('type', 'unknown')}: {score_pct}{fired}"+++def evaluate_with_detector(result: ExtractionResult, detector_config: dict[str, Any]) -> AlertEvaluationResult:+ """Score an extracted trends series with an anomaly detector (the non-threshold alert path).++ Breakdown alerts fire on the first anomalous breakdown value; non-breakdown alerts score the+ single selected series.+ """+ detector_type_str = detector_config.get("type", "zscore")+ interval_value = result.interval_type.value if result.interval_type else None++ if not result.series:+ # Empty query → the metric is genuinely 0; rows present but unscorable → uncomputed (None).+ value: float | None = 0 if result.empty_query_result else None+ return AlertEvaluationResult(value=value, breaches=[], interval=interval_value)++ if result.is_breakdown:+ for bd_index, s in enumerate(result.series):+ data = np.array([p.value for p in s.points])+ detection = get_detector(detector_config).detect(data)+ if detection.is_anomaly:+ current_value = float(data[-1])+ return AlertEvaluationResult(+ value=current_value,+ breaches=[_anomaly_breach(s.label, current_value, detection.score, detector_type_str)],+ anomaly_scores=detection.all_scores or None,+ triggered_points=detection.triggered_indices or None,+ triggered_dates=_triggered_dates(s, detection.triggered_indices or []) or None,+ interval=interval_value,+ triggered_metadata={"series_index": bd_index},+ )+ return AlertEvaluationResult(value=None, breaches=[], interval=interval_value)++ s = result.series[0]+ data = np.array([p.value for p in s.points])+ detection = get_detector(detector_config).detect(data)++ breaches: list[str] = []+ if detection.is_anomaly:+ current_value = float(data[-1])+ suffix = ""+ if detector_type_str == "ensemble" and detection.metadata:+ sub_results = detection.metadata.get("sub_results", [])+ if sub_results:+ parts = [_format_sub_detector(sr) for sr in sub_results]+ suffix = f" | sub-detectors: {', '.join(parts)}"+ breaches.append(_anomaly_breach(s.label, current_value, detection.score, detector_type_str, suffix))++ return AlertEvaluationResult(+ value=float(data[-1]) if len(data) > 0 else None,+ breaches=breaches,+ anomaly_scores=detection.all_scores or None,+ triggered_points=detection.triggered_indices or None,+ triggered_dates=_triggered_dates(s, detection.triggered_indices or []) or None,+ interval=interval_value,+ )+++class TrendsDetectorExtractor:+ """Detector-path extractor for trends insights. Conforms to the same ``Extractor`` protocol as+ the threshold ``TrendsExtractor`` and emits the same ``ComparableSeries`` — it only differs in+ fetching the detector's wider lookback window (the whole series is scored, not a single anchor).+ """++ def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:+ detector_config = alert.detector_config+ if not detector_config:+ raise ValueError("TrendsDetectorExtractor requires detector_config — dispatcher invariant violated")+ trends_query = TrendsQuery.model_validate(query)+ series_index = (alert.config or {}).get("series_index", 0)+ return extract_detector_series(insight, alert.team, trends_query, detector_config, series_index=series_index)+++def simulate_detector_on_insight(+ insight: Insight,+ team: Any,+ detector_config: dict[str, Any],+ series_index: int = 0,+ date_from: str | None = None,+) -> dict[str, Any]:+ """Run a detector over historical insight data for chart visualization. Read-only (no AlertCheck)."""+ if insight.query is None:+ raise ValueError("Insight has no valid query.")++ with upgrade_query(insight):+ query = insight.query++ kind = get_from_dict_or_attr(query, "kind")+ if kind in WRAPPER_NODE_KINDS:+ query = get_from_dict_or_attr(query, "source")+ kind = get_from_dict_or_attr(query, "kind")+ if kind != NodeKind.TRENDS_QUERY:+ raise ValueError("Only TrendsQuery insights are supported for simulation.")++ trends_query = TrendsQuery.model_validate(query)+ # Read-only simulation runs outside the alert-check activity, so tag its query directly.+ tag_queries(product=Product.PRODUCT_ANALYTICS, feature=Feature.ALERTING)+ detector_type_str = detector_config.get("type", "zscore")+ result = extract_detector_series(+ insight, team, trends_query, detector_config, series_index=series_index, date_from=date_from+ )+ interval_value = trends_query.interval.value if trends_query.interval else None++ if not result.series:+ # Preserve the original, more specific diagnostics: a genuinely empty query vs rows that+ # exist but are all too short to score (per breakdown / single-series).+ if result.empty_query_result:+ raise ValueError("No results found for insight.")+ if result.is_breakdown:+ raise ValueError("No breakdown values had enough data points for simulation.")+ raise ValueError("No data points found for the selected series.")++ if result.is_breakdown:+ breakdown_sims = [_sim_from_series(s, detector_config, detector_type_str) for s in result.series]+ return {+ "data": [],+ "dates": [],+ "scores": [],+ "triggered_indices": [],+ "triggered_dates": [],+ "interval": interval_value,+ "total_points": sum(sim["total_points"] for sim in breakdown_sims),+ "anomaly_count": sum(sim["anomaly_count"] for sim in breakdown_sims),+ "breakdown_results": breakdown_sims,+ }++ sim = _sim_from_series(result.series[0], detector_config, detector_type_str)+ sim.pop("label", None)+ return {**sim, "interval": interval_value}+++def _sim_from_series(+ series: ComparableSeries, detector_config: dict[str, Any], detector_type_str: str+) -> dict[str, Any]:+ """Score a single extracted series with detect_batch and shape it for the simulation chart."""+ detection = get_detector(detector_config).detect_batch(np.array([p.value for p in series.points]))+ triggered = detection.triggered_indices or []+ scores = detection.all_scores if detection.all_scores else [None] * len(series.points)++ sim: dict[str, Any] = {+ "label": series.label,+ "data": [p.value for p in series.points],+ # Non-time-series points carry no date; emit [] (not [None]) to match the legacy shape and+ # satisfy the dates=ListField(child=CharField()) serializer.+ "dates": [p.date for p in series.points if p.date is not None],+ "scores": scores,+ "triggered_indices": triggered,+ "triggered_dates": _triggered_dates(series, triggered),+ "total_points": len(series.points),+ "anomaly_count": len(triggered),+ }+ sub_scores = _extract_sub_detector_scores(detector_type_str, detection)+ if sub_scores:+ sim["sub_detector_scores"] = sub_scores+ return simdiff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex 8fae674b5173..0405f69933bd 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -1,27 +1,52 @@-from posthog.schema import AlertCondition, InsightThreshold, NodeKind, TrendsQuery+from posthog.schema import AlertCondition, InsightThreshold, NodeKindfrom posthog.schema_migrations.upgrade_manager import upgrade_query-from posthog.tasks.alerts.detector import check_trends_alert_with_detectorfrom posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attrfrom products.alerts.backend.evaluation.comparator import evaluate_thresholdfrom products.alerts.backend.evaluation.contract import Extractor+from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detectorfrom products.alerts.backend.evaluation.trends import TrendsExtractorfrom products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight-# Each insight kind that supports alerts maps to one extractor. The comparator is shared.+# Each insight kind that supports threshold alerts maps to one extractor. The comparator is shared.EXTRACTORS: dict[NodeKind, Extractor] = {NodeKind.TRENDS_QUERY: TrendsExtractor(),}+# The anomaly-detector path mirrors EXTRACTORS: one detector extractor per kind, scored by the shared+# evaluate_with_detector. Trends-only in v1, but the dispatch no longer hardcodes the kind.+DETECTOR_EXTRACTORS: dict[NodeKind, Extractor] = {+ NodeKind.TRENDS_QUERY: TrendsDetectorExtractor(),+}+++def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: object) -> AlertEvaluationResult:+ """Route a detector (anomaly) alert to its kind's detector extractor, then score the series.++ Shared by the dispatcher and the detector tests. The registry lookup is the kind gate — an+ unsupported kind raises rather than silently falling through to the threshold path.+ """+ detector_config = alert.detector_config+ if not detector_config:+ raise ValueError("check_detector_alert requires detector_config — dispatcher invariant violated")+ kind = get_from_dict_or_attr(query, "kind")+ detector_extractor = DETECTOR_EXTRACTORS.get(kind)+ if detector_extractor is None:+ raise NotImplementedError(f"AlertCheckError: Detector alerts for {kind} are not supported yet")+ result = detector_extractor.extract(alert, insight, query)+ return evaluate_with_detector(result, detector_config)+def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:"""Dispatch an alert to its insight-kind extractor, then run the shared comparator.- If ``detector_config`` is set, evaluation goes through the anomaly-detector abstraction- (trends-only); otherwise the extractor normalizes the query result into an ``ExtractionResult``- and the comparator evaluates it against the threshold — the same path for every kind.+ If ``detector_config`` is set, routes through the anomaly-detector registry (trends-only in v1);+ each detector extractor shares the ``ComparableSeries`` contract, so the dispatch shape mirrors+ the threshold path. Otherwise the extractor normalizes the query result into an+ ``ExtractionResult`` and the comparator evaluates it against the threshold."""insight = alert.insight@@ -33,9 +58,8 @@ def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:query = get_from_dict_or_attr(query, "source")kind = get_from_dict_or_attr(query, "kind")- if alert.detector_config and kind == NodeKind.TRENDS_QUERY:- trends_query = TrendsQuery.model_validate(query)- return check_trends_alert_with_detector(alert, insight, trends_query, alert.detector_config)+ if alert.detector_config:+ return check_detector_alert(alert, insight, query)extractor = EXTRACTORS.get(kind)if extractor is None: