: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): extract trends alert evaluation into product module (#62667)
Vasco de Krijger2012ab611123
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.pyindex 7e3c89cd90fc..94b949a76c27 100644--- a/posthog/tasks/alerts/test/alert_check_helpers.py+++ b/posthog/tasks/alerts/test/alert_check_helpers.py@@ -4,6 +4,7 @@ from django.db import transactionfrom posthog.tasks.alerts import utils as alert_utils+from products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.models import AlertConfiguration@@ -14,7 +15,7 @@ def run_alert_check(alert_id: str) -> None:error = Noneresult = Nonetry:- result = alert_utils.check_alert_for_insight(alert)+ result = check_alert_for_insight(alert)except Exception as e:error = {"message": str(e), "traceback": traceback.format_exc()}diff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.pyindex a4e785c112bb..99e2c9010404 100644--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py@@ -40,7 +40,7 @@ class TestRunAlertCheck(APIBaseTest):self.alert_id = alert["id"]@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=["[email protected]"])- @patch("posthog.tasks.alerts.utils.check_alert_for_insight")+ @patch("posthog.tasks.alerts.test.alert_check_helpers.check_alert_for_insight")def test_firing_path_unpacks_tuple_and_records_delivery(self, mock_check: MagicMock, mock_send: MagicMock) -> None:mock_check.return_value = AlertEvaluationResult(value=5.0, breaches=["breach_message"])@@ -53,7 +53,7 @@ class TestRunAlertCheck(APIBaseTest):mock_send.assert_called_once()@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")- @patch("posthog.tasks.alerts.utils.check_alert_for_insight")+ @patch("posthog.tasks.alerts.test.alert_check_helpers.check_alert_for_insight")def test_not_firing_path_records_check_without_notifying(self, mock_check: MagicMock, mock_send: MagicMock) -> None:mock_check.return_value = AlertEvaluationResult(value=0.5, breaches=None)@@ -65,7 +65,7 @@ class TestRunAlertCheck(APIBaseTest):mock_send.assert_not_called()@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")- @patch("posthog.tasks.alerts.utils.check_alert_for_insight")+ @patch("posthog.tasks.alerts.test.alert_check_helpers.check_alert_for_insight")def test_errored_path_records_error_and_notifies(self, mock_check: MagicMock, mock_send_err: MagicMock) -> None:mock_check.side_effect = RuntimeError("boom")diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.pyindex aac2ebcb2231..caa9ded2ce8d 100644--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py@@ -676,7 +676,10 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixidempotency_key=ANY,)- @patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight", wraps=calculate_for_query_based_insight)+ @patch(+ "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight",+ wraps=calculate_for_query_based_insight,+ )def test_hourly_alert_respects_latest_data(self, mock_calculate: MagicMock, mock_send_breaches: MagicMock, mock_send_errors: MagicMock) -> None:diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.pyindex f1dad911f10c..a285017744a9 100644--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py@@ -2001,7 +2001,10 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixidempotency_key=ANY,)- @patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight", wraps=calculate_for_query_based_insight)+ @patch(+ "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight",+ wraps=calculate_for_query_based_insight,+ )def test_hourly_relative_increase_alert_respects_latest_data(self, mock_calculate: MagicMock, mock_send_breaches: MagicMock, mock_send_errors: MagicMock) -> None:@@ -2071,7 +2074,10 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixmock_send_breaches.assert_not_called()- @patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight", wraps=calculate_for_query_based_insight)+ @patch(+ "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight",+ wraps=calculate_for_query_based_insight,+ )def test_hourly_relative_decrease_alert_respects_latest_data(self, mock_calculate: MagicMock, mock_send_breaches: MagicMock, mock_send_errors: MagicMock) -> None:diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.pyindex cc758ffacc5d..d63d1032d2b5 100644--- a/posthog/tasks/alerts/trends.py+++ b/posthog/tasks/alerts/trends.py@@ -2,26 +2,11 @@ from typing import NotRequired, Optional, TypedDict, castimport numpy as np-from posthog.schema import (- AlertCondition,- AlertConditionType,- InsightsThresholdBounds,- InsightThreshold,- InsightThresholdType,- IntervalType,- TrendsAlertConfig,- TrendsQuery,-)+from posthog.schema import IntervalType, TrendsAlertConfig, TrendsQuery-from posthog.api.services.query import ExecutionMode-from posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.caching.fetch_from_cache import InsightResult-from posthog.event_usage import EventSourcefrom posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter-from posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES, AlertEvaluationResult--from products.alerts.backend.models.alert import AlertConfiguration-from products.product_analytics.backend.models.insight import Insight+from posthog.tasks.alerts.utils import NON_TIME_SERIES_DISPLAY_TYPES# TODO: move the TrendResult UI type to schema.ts and use that instead@@ -44,346 +29,6 @@ class TrendResult(TypedDict):filter: dict-def _is_empty_query_result(- calculation_result: InsightResult,- alert: AlertConfiguration,- bounds: InsightsThresholdBounds,- threshold_type: InsightThresholdType,- condition: AlertCondition,- interval_type: IntervalType | None,-) -> AlertEvaluationResult | None:- # is None -> Indicates that the query layer swallowed a legitimate error, in this case we still want- # to raise an exception to avoid mis-fires of the alert.- if calculation_result.result is None:- raise RuntimeError(f"No results found for insight with alert id = {alert.id}")-- # For other "empty" cases we assume that they had no legitimate results and as a result will treat it as a 0 value- # in terms of alerting. See: https://github.com/PostHog/posthog/pull/48701- if not calculation_result.result:- breaches = _breach_messages(bounds, 0, threshold_type, condition.type, interval_type, "empty result")- return AlertEvaluationResult(value=0, breaches=breaches)-- return None---def check_trends_alert(alert: AlertConfiguration, insight: Insight, query: TrendsQuery) -> AlertEvaluationResult:- """- Calculates insight value for the needed time periods and compares it with the threshold.-- Generally we check the insight value for the previous interval (day/week... grouping set on the trend insight) and compare it with the threshold/value for interval before that.- This is done because we need the current interval to complete before comparing against threshold.- (eg. if needing to check value < X, need to wait as more events will come in before interval finishes)-- But in some cases (when check_current_interval = True) like value > X or value inc > X, we can check the value for the current interval and alert right away if threshold is breached.- So then we check current interval value first and alert if threshold breached, otherwise fallback and process previous interval.- """-- if alert.config and "type" in alert.config and alert.config["type"] == "TrendsAlertConfig":- config = TrendsAlertConfig.model_validate(alert.config)- else:- raise ValueError(f"Unsupported alert config type: {alert.config}")-- condition = AlertCondition.model_validate(alert.condition)- threshold = InsightThreshold.model_validate(alert.threshold.configuration) if alert.threshold else None-- if not threshold or not threshold.bounds:- return AlertEvaluationResult(value=0, breaches=[])-- has_breakdown = _has_breakdown(query)- is_non_time_series = _is_non_time_series_trend(query)- check_current_interval = config.check_ongoing_interval-- # Do not use cache hourly trends alerts.- # The cache key uses relative times (e.g -2h), and this leads to- # using stale data irrelevant for the current alert check- execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE- if query.interval == IntervalType.HOUR:- execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS-- match condition.type:- case AlertConditionType.ABSOLUTE_VALUE:- if threshold.type != InsightThresholdType.ABSOLUTE:- raise ValueError(f"Absolute threshold not configured for alert condition ABSOLUTE_VALUE")-- if is_non_time_series:- # for non time series, it's an aggregated value for full interval- # so we need to compute full insight- filters_override = None- else:- # want values back till previous interval (last hour, last day, last week, last month)- # depending on the alert calculation interval- filters_override = _date_range_override_for_intervals(query, last_x_intervals=2)-- calculation_result = calculate_for_query_based_insight(- insight,- team=alert.team,- execution_mode=execution_mode,- user=None,- filters_override=filters_override,- analytics_props={"source": EventSource.ALERT},- )-- interval = query.interval if not is_non_time_series else None-- if no_result_evaluation := _is_empty_query_result(- calculation_result, alert, threshold.bounds, threshold.type, condition, interval- ):- return no_result_evaluation-- if check_current_interval and threshold.bounds.upper is None:- # checking for value > X so we can also check current interval value- raise ValueError(- f"check_ongoing_interval is only supported for alert condition ABSOLUTE_VALUE when upper threshold is specified"- )-- if has_breakdown:- # for breakdowns, we need to check all values in calculation_result.result- breakdown_results = cast(list[TrendResult], calculation_result.result)-- for breakdown_result in breakdown_results:- if check_current_interval or is_non_time_series:- current_interval_value = _pick_interval_value_from_trend_result(query, breakdown_result, 0)- breaches = _breach_messages(- bounds=threshold.bounds,- calculated_value=current_interval_value,- threshold_type=threshold.type,- condition_type=condition.type,- interval_type=interval,- series=breakdown_result["label"],- is_current_interval=True,- )- if breaches:- # found one breakdown value that breached the threshold- return AlertEvaluationResult(value=current_interval_value, breaches=breaches)- else:- prev_interval_value = _pick_interval_value_from_trend_result(query, breakdown_result, -1)- breaches = _breach_messages(- threshold.bounds,- prev_interval_value,- threshold.type,- condition.type,- interval,- breakdown_result["label"],- )- if breaches:- # found one breakdown value that breached the threshold- return AlertEvaluationResult(value=prev_interval_value, breaches=breaches)-- # None of the breakdown values breached the threshold- return AlertEvaluationResult(value=None, breaches=[])- else:- # for non breakdowns, we pick the series (config.series_index) from calculation_result.result- selected_series_result = _pick_series_result(config, calculation_result)-- if check_current_interval or is_non_time_series:- # pick current interval value- current_interval_value = _pick_interval_value_from_trend_result(query, selected_series_result, 0)- breaches = _breach_messages(- threshold.bounds,- current_interval_value,- threshold.type,- condition.type,- interval,- selected_series_result["label"],- is_current_interval=True,- )- return AlertEvaluationResult(value=current_interval_value, breaches=breaches)- else:- prev_interval_value = _pick_interval_value_from_trend_result(query, selected_series_result, -1)- breaches = _breach_messages(- threshold.bounds,- prev_interval_value,- threshold.type,- condition.type,- interval,- selected_series_result["label"],- )- return AlertEvaluationResult(value=prev_interval_value, breaches=breaches)- case AlertConditionType.RELATIVE_INCREASE:- if is_non_time_series:- raise ValueError(f"Relative alerts not supported for non time series trends")-- # to measure relative increase, we can't alert until current interval has completed- # as to check increase less than X, we need interval to complete- # so we need to compute the trend values for last 3 intervals- # and then compare the previous interval with value for the interval before previous- filters_overrides = _date_range_override_for_intervals(query, last_x_intervals=3)- calculation_result = calculate_for_query_based_insight(- insight,- team=alert.team,- execution_mode=execution_mode,- user=None,- filters_override=filters_overrides,- analytics_props={"source": EventSource.ALERT},- )-- if no_result_evaluation := _is_empty_query_result(- calculation_result, alert, threshold.bounds, threshold.type, condition, query.interval- ):- return no_result_evaluation-- results_to_evaluate: list[TrendResult] = []-- if has_breakdown:- # for breakdowns, we need to check all values in calculation_result.result- breakdown_results = cast(list[TrendResult], calculation_result.result)- results_to_evaluate.extend(breakdown_results)- else:- # for non breakdowns, we pick the series (config.series_index) from calculation_result.result- selected_series_result = _pick_series_result(config, calculation_result)- results_to_evaluate.append(selected_series_result)-- # if we don't have breakdown, we'll have to evaluate just one result- # and increase will be the evaluated value of that result- increase = None- breaches = []-- if check_current_interval and threshold.bounds.upper is None:- # checking for value increased > X so we can also check current interval value- # as can alert right away if current interval value - previous interval value > upper threshold- raise ValueError(- f"check_ongoing_interval is only supported for alert condition RELATIVE_INCREASE when upper threshold is specified"- )-- for result in results_to_evaluate:- current_interval_value = _pick_interval_value_from_trend_result(query, result, 0)- prev_interval_value = _pick_interval_value_from_trend_result(query, result, -1)- prev_prev_interval_value = _pick_interval_value_from_trend_result(query, result, -2)-- if check_current_interval:- if threshold.type == InsightThresholdType.ABSOLUTE:- increase = current_interval_value - prev_interval_value- elif threshold.type == InsightThresholdType.PERCENTAGE:- if prev_interval_value == 0 and current_interval_value == 0:- increase = 0- elif prev_interval_value == 0:- increase = float("inf")- else:- increase = (current_interval_value - prev_interval_value) / prev_interval_value- else:- raise ValueError(- f"Neither relative nor absolute threshold configured for alert condition RELATIVE_INCREASE"- )-- breaches = _breach_messages(- threshold.bounds,- increase,- threshold.type,- condition.type,- query.interval,- result["label"],- is_current_interval=True,- )-- if breaches:- # found a breach for one of the results so alert- return AlertEvaluationResult(value=increase, breaches=breaches)- else:- # fallback to check previous intervals- if threshold.type == InsightThresholdType.ABSOLUTE:- increase = prev_interval_value - prev_prev_interval_value- elif threshold.type == InsightThresholdType.PERCENTAGE:- if prev_prev_interval_value == 0 and prev_interval_value == 0:- increase = 0- elif prev_prev_interval_value == 0:- increase = float("inf")- else:- increase = (prev_interval_value - prev_prev_interval_value) / prev_prev_interval_value- else:- raise ValueError(- f"Neither relative nor absolute threshold configured for alert condition RELATIVE_INCREASE"- )-- breaches = _breach_messages(- threshold.bounds,- increase,- threshold.type,- condition.type,- query.interval,- result["label"],- )-- if breaches:- # found a breach for one of the results so alert- return AlertEvaluationResult(value=increase, breaches=breaches)-- return AlertEvaluationResult(value=(increase if not has_breakdown else None), breaches=[])-- case AlertConditionType.RELATIVE_DECREASE:- if is_non_time_series:- raise ValueError(f"Relative alerts not supported for non time series trends")-- # to measure relative decrease, we can't alert until current interval has completed- # as to check decrease more than X, we need interval to complete- # so we need to compute the trend values for last 3 intervals- # and then compare the previous interval with value for the interval before previous- filters_overrides = _date_range_override_for_intervals(query, last_x_intervals=3)- calculation_result = calculate_for_query_based_insight(- insight,- team=alert.team,- execution_mode=execution_mode,- user=None,- filters_override=filters_overrides,- analytics_props={"source": EventSource.ALERT},- )-- if no_result_evaluation := _is_empty_query_result(- calculation_result, alert, threshold.bounds, threshold.type, condition, query.interval- ):- return no_result_evaluation-- results_to_evaluate = []-- if has_breakdown:- # for breakdowns, we need to check all values in calculation_result.result- breakdown_results = cast(list[TrendResult], calculation_result.result)- results_to_evaluate.extend(breakdown_results)- else:- # for non breakdowns, we pick the series (config.series_index) from calculation_result.result- selected_series_result = _pick_series_result(config, calculation_result)- results_to_evaluate.append(selected_series_result)-- # if we don't have breakdown, we'll have to evaluate just one result- # and increase will be the evaluated value of that result- decrease = None-- for result in results_to_evaluate:- prev_interval_value = _pick_interval_value_from_trend_result(query, result, -1)- prev_prev_interval_value = _pick_interval_value_from_trend_result(query, result, -2)-- if threshold.type == InsightThresholdType.ABSOLUTE:- decrease = prev_prev_interval_value - prev_interval_value- elif threshold.type == InsightThresholdType.PERCENTAGE:- if prev_prev_interval_value == 0 and prev_interval_value == 0:- decrease = 0- elif prev_prev_interval_value == 0:- decrease = float("inf")- else:- decrease = (prev_prev_interval_value - prev_interval_value) / prev_prev_interval_value- else:- raise ValueError(- f"Neither relative nor absolute threshold configured for alert condition RELATIVE_INCREASE"- )-- breaches = _breach_messages(- threshold.bounds,- decrease,- threshold.type,- condition.type,- query.interval,- result["label"],- )-- if breaches:- # found a breach for one of the results so alert- return AlertEvaluationResult(value=decrease, breaches=breaches)-- return AlertEvaluationResult(value=(decrease if not has_breakdown else None), breaches=[])-- case _:- raise NotImplementedError(f"Unsupported alert condition type: {condition.type}")--def _is_non_time_series_trend(query: TrendsQuery) -> bool:return bool(query.trendsFilter and query.trendsFilter.display in NON_TIME_SERIES_DISPLAY_TYPES)@@ -433,54 +78,3 @@ def _pick_series_result(config: TrendsAlertConfig, results: InsightResult) -> Trresult = cast(list[TrendResult], results.result)[series_index]return result---def _pick_interval_value_from_trend_result(query: TrendsQuery, result: TrendResult, interval_to_pick: int = 0) -> float:- """- interval_to_pick to controls whether to pick value for current (0), last (-1), one before last (-2)...- """- assert interval_to_pick <= 0-- if _is_non_time_series_trend(query):- # only one value in result- return result["aggregated_value"]-- data = result["data"]- # data is pre sorted in ascending order of timestamps- index_from_back = len(data) - 1 + interval_to_pick- return data[index_from_back]---def _breach_messages(- bounds: InsightsThresholdBounds,- calculated_value: float,- threshold_type: InsightThresholdType,- condition_type: AlertConditionType,- interval_type: IntervalType | None,- series: str,- is_current_interval: bool = False,-) -> list[str]:- is_percentage = threshold_type == InsightThresholdType.PERCENTAGE- formatted_value = f"{calculated_value:.2%}" if is_percentage else calculated_value-- match condition_type:- case AlertConditionType.ABSOLUTE_VALUE:- condition_text = "is"- case AlertConditionType.RELATIVE_INCREASE:- condition_text = "increased"- case AlertConditionType.RELATIVE_DECREASE:- condition_text = "decreased"-- if bounds.lower is not None and calculated_value < bounds.lower:- lower_value = f"{bounds.lower:.2%}" if is_percentage else bounds.lower- return [- f"The insight value ({series}) for {'current' if is_current_interval else 'previous'} {interval_type or 'interval'} ({formatted_value}) {condition_text} less than lower threshold ({lower_value})"- ]-- if bounds.upper is not None and calculated_value > bounds.upper:- upper_value = f"{bounds.upper:.2%}" if is_percentage else bounds.upper- return [- f"The insight value ({series}) for {'current' if is_current_interval else 'previous'} {interval_type or 'interval'} ({formatted_value}) {condition_text} more than upper threshold ({upper_value})"- ]-- return []diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 9a239a19feae..ff7de94399c0 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -24,7 +24,6 @@ from posthog.schema import (from posthog.cdp.internal_events import InternalEventEvent, produce_internal_eventfrom posthog.email import EmailMessagefrom posthog.exceptions_capture import capture_exception-from posthog.schema_migrations.upgrade_manager import upgrade_queryfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restrictionfrom posthog.utils import get_from_dict_or_attr@@ -81,6 +80,23 @@ def validate_threshold_bounds_required(threshold_config: dict | None) -> None:raise ValueError(THRESHOLD_BOUNDS_REQUIRED_MESSAGE)+def _validate_condition_threshold_compatibility(+ parsed_condition: AlertCondition, threshold_config: dict | None+) -> InsightThreshold | None:+ """Parse the threshold and enforce condition/threshold compatibility shared by all insight kinds."""+ if threshold_config is None:+ return None+ try:+ threshold = InsightThreshold.model_validate(threshold_config)+ except Exception:+ raise ValueError(f"Alert has invalid threshold configuration: {threshold_config}")+ if parsed_condition.type == AlertConditionType.ABSOLUTE_VALUE and threshold.type != InsightThresholdType.ABSOLUTE:+ raise ValueError(+ "Absolute value alerts require an absolute threshold, but a percentage threshold was configured"+ )+ return threshold++def validate_alert_config(query: dict,condition: dict | None,@@ -103,18 +119,20 @@ def validate_alert_config(except Exception:raise ValueError(f"Alert has invalid condition: {condition}")- if not config or not isinstance(config, dict) or config.get("type") != "TrendsAlertConfig":- raise ValueError(f"Unsupported alert config type: {config}")- try:- parsed_config = TrendsAlertConfig.model_validate(config)- except Exception:- raise ValueError(f"Alert has invalid TrendsAlertConfig: {config}")+ config_type = config.get("type") if isinstance(config, dict) else Nonekind = 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 config_type != "TrendsAlertConfig":+ raise ValueError(f"Unsupported alert config type: {config}")+ try:+ parsed_config = TrendsAlertConfig.model_validate(config)+ except Exception:+ raise ValueError(f"Alert has invalid TrendsAlertConfig: {config}")+if kind != NodeKind.TRENDS_QUERY:raise ValueError(f"Alert's insight query kind '{kind}' is not supported (only TrendsQuery)")@@ -136,28 +154,20 @@ def validate_alert_config(if parsed_config.series_index >= result_count:raise ValueError(f"series_index {parsed_config.series_index} is out of range (query has {result_count} series)")- if threshold_config is not None:- try:- threshold = InsightThreshold.model_validate(threshold_config)- except Exception:- raise ValueError(f"Alert has invalid threshold configuration: {threshold_config}")-- if (- parsed_condition.type == AlertConditionType.ABSOLUTE_VALUE- and threshold.type != InsightThresholdType.ABSOLUTE- ):- raise ValueError(- "Absolute value alerts require an absolute threshold, but a percentage threshold was configured"- )-- if parsed_config.check_ongoing_interval and parsed_condition.type in (+ threshold = _validate_condition_threshold_compatibility(parsed_condition, threshold_config)+ if (+ threshold is not None+ and parsed_config.check_ongoing_interval+ and parsed_condition.type+ in (AlertConditionType.ABSOLUTE_VALUE,AlertConditionType.RELATIVE_INCREASE,- ):- if not threshold.bounds or threshold.bounds.upper is None:- raise ValueError(- f"check_ongoing_interval is only supported for alert condition {parsed_condition.type} when upper threshold is specified"- )+ )+ ):+ if not threshold.bounds or threshold.bounds.upper is None:+ raise ValueError(+ f"check_ongoing_interval is only supported for alert condition {parsed_condition.type} when upper threshold is specified"+ )if require_threshold_bounds and detector_config is None:validate_threshold_bounds_required(threshold_config)@@ -437,36 +447,6 @@ def record_alert_delivery(alert: AlertConfiguration, alert_check: AlertCheck, taalert.save(update_fields=["last_notified_at"])-def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:- """Dispatch an alert to the correct insight-kind-specific evaluator.-- If ``detector_config`` is set, uses the detector abstraction; otherwise- falls back to threshold-based checking.- """- # Lazy import breaks the cycle: trends.py and detector.py import from utils.py.- from posthog.tasks.alerts.detector import check_trends_alert_with_detector- from posthog.tasks.alerts.trends import check_trends_alert-- insight = alert.insight-- 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")-- match kind:- case "TrendsQuery":- query = TrendsQuery.model_validate(query)- if alert.detector_config:- return check_trends_alert_with_detector(alert, insight, query, alert.detector_config)- return check_trends_alert(alert, insight, query)- case _:- raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")--def add_alert_check(alert: AlertConfiguration,value: float | None,diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex b3357415ffcf..906cf98ad98a 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -19,7 +19,6 @@ from posthog.tasks.alerts.investigation_notifications import run_investigation_nfrom posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utcfrom posthog.tasks.alerts.utils import (add_alert_check,- check_alert_for_insight,disable_invalid_alert,dispatch_alert_notification,next_check_time,@@ -40,6 +39,7 @@ from posthog.temporal.alerts.types import ()from posthog.temporal.common.heartbeat import Heartbeater+from products.alerts.backend.evaluation import check_alert_for_insightfrom products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.notifications.backend.facade.api import (NotificationData,diff --git a/products/alerts/backend/evaluation/__init__.py b/products/alerts/backend/evaluation/__init__.pynew file mode 100644index 000000000000..5145c7c8f7c2--- /dev/null+++ b/products/alerts/backend/evaluation/__init__.py@@ -0,0 +1,3 @@+from products.alerts.backend.evaluation.dispatcher import check_alert_for_insight++__all__ = ["check_alert_for_insight"]diff --git a/products/alerts/backend/evaluation/comparator.py b/products/alerts/backend/evaluation/comparator.pynew file mode 100644index 000000000000..08b5bdb3bd01--- /dev/null+++ b/products/alerts/backend/evaluation/comparator.py@@ -0,0 +1,136 @@+from posthog.schema import (+ AlertCondition,+ AlertConditionType,+ InsightsThresholdBounds,+ InsightThreshold,+ InsightThresholdType,+ IntervalType,+)++from posthog.tasks.alerts.utils import AlertEvaluationResult++from products.alerts.backend.evaluation.contract import ExtractionResult+++def _breach_messages(+ bounds: InsightsThresholdBounds,+ calculated_value: float,+ threshold_type: InsightThresholdType,+ condition_type: AlertConditionType,+ *,+ subject: str,+ framed: bool,+ interval_type: IntervalType | None = None,+ series: str | None = None,+ is_current_interval: bool = False,+) -> list[str]:+ is_percentage = threshold_type == InsightThresholdType.PERCENTAGE+ formatted_value = f"{calculated_value:.2%}" if is_percentage else calculated_value++ match condition_type:+ case AlertConditionType.ABSOLUTE_VALUE:+ condition_text = "is"+ case AlertConditionType.RELATIVE_INCREASE:+ condition_text = "increased"+ case AlertConditionType.RELATIVE_DECREASE:+ condition_text = "decreased"+ case _:+ raise ValueError(f"Unsupported alert condition type: {condition_type}")++ # Framed (time-series trends): "(label) for current/previous interval". Unframed (e.g. SQL+ # insights): just the subject, since there is no series label or interval to reference.+ context = (+ f" ({series}) for {'current' if is_current_interval else 'previous'} {interval_type or 'interval'}"+ if framed+ else ""+ )++ if bounds.lower is not None and calculated_value < bounds.lower:+ lower_value = f"{bounds.lower:.2%}" if is_percentage else bounds.lower+ return [f"{subject}{context} ({formatted_value}) {condition_text} less than lower threshold ({lower_value})"]++ if bounds.upper is not None and calculated_value > bounds.upper:+ upper_value = f"{bounds.upper:.2%}" if is_percentage else bounds.upper+ return [f"{subject}{context} ({formatted_value}) {condition_text} more than upper threshold ({upper_value})"]++ return []+++def _relative_value(+ condition_type: AlertConditionType,+ threshold_type: InsightThresholdType,+ anchor: float,+ previous: float,+) -> float:+ """Compute the relative change between the anchor point and the one before it.++ Both increase and decrease divide by ``previous`` (the earlier interval); the sign of+ the numerator flips so a decrease is reported as a positive magnitude.+ """+ numerator = anchor - previous if condition_type == AlertConditionType.RELATIVE_INCREASE else previous - anchor++ if threshold_type == InsightThresholdType.ABSOLUTE:+ return numerator+ if threshold_type != InsightThresholdType.PERCENTAGE:+ raise ValueError(f"Neither relative nor absolute threshold configured for alert condition {condition_type}")+ if previous == 0 and anchor == 0:+ return 0+ if previous == 0:+ return float("inf")+ return numerator / previous+++def evaluate_threshold(+ result: ExtractionResult,+ condition: AlertCondition,+ threshold: InsightThreshold | None,+) -> AlertEvaluationResult:+ """Compare an extractor's result against the threshold; breach if ANY series breaches.++ Kind-agnostic: every insight kind's extractor normalizes into an ``ExtractionResult`` and the+ completeness/ongoing-interval policy is already encoded in each series' ``current_index``.++ ``result.is_breakdown`` controls only the no-breach reported value: a breakdown query has no+ single representative value, so it reports ``None``, whereas a single-series query reports its+ computed value.+ """+ bounds = threshold.bounds if threshold else None+ if not threshold or not bounds:+ return AlertEvaluationResult(value=0, breaches=[])++ calculated: float | None = None+ for s in result.series:+ anchor = s.points[s.current_index].value+ if anchor is None:+ continue++ if condition.type == AlertConditionType.ABSOLUTE_VALUE:+ calculated = anchor+ else:+ previous = s.points[s.current_index - 1].value if s.current_index - 1 >= 0 else None+ if previous is None:+ continue+ calculated = _relative_value(condition.type, threshold.type, anchor, previous)++ breaches = _breach_messages(+ bounds,+ calculated,+ threshold.type,+ condition.type,+ subject=result.subject,+ framed=result.framed,+ interval_type=result.interval_type,+ series=s.label,+ is_current_interval=s.is_current_interval,+ )+ if breaches:+ return AlertEvaluationResult(value=calculated, breaches=breaches)++ # No breach: an empty query result reports 0 regardless of breakdown (the metric is genuinely+ # zero — matching the original _is_empty_query_result); otherwise a non-breakdown query reports+ # its computed value and a breakdown has no single representative value, so it reports None.+ if result.empty_query_result:+ no_breach_value: float | None = 0+ else:+ no_breach_value = None if result.is_breakdown else calculated+ return AlertEvaluationResult(value=no_breach_value, breaches=[])diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pynew file mode 100644index 000000000000..7862b4e192ad--- /dev/null+++ b/products/alerts/backend/evaluation/contract.py@@ -0,0 +1,70 @@+from dataclasses import dataclass+from typing import Protocol++from posthog.schema import AlertCondition, AlertConditionType, IntervalType++from products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight+++@dataclass+class SeriesPoint:+ date: str | None # None for non-time-series (single aggregated value)+ value: float | None # None = missing data point this interval+++@dataclass+class ComparableSeries:+ label: str # series / breakdown label, used in breach messages+ points: list[SeriesPoint] # chronologically ascending; extractor guarantees order+ current_index: int # comparison anchor; previous = current_index - 1+ is_current_interval: bool = False # anchor is the ongoing (incomplete) interval — affects breach wording+++@dataclass+class ExtractionResult:+ """Everything the comparator needs from an extractor, so the dispatcher stays kind-agnostic.++ ``subject`` and ``framed`` shape the breach message: framed trends messages read+ "The insight value (label) for previous day (...)"; unframed messages (e.g. SQL insights,+ which have no series label or interval) read "The SQL insight value (...)".+ """++ series: list[ComparableSeries]+ is_breakdown: bool = False # breakdown queries report no single no-breach value+ interval_type: IntervalType | None = None # breach-message interval framing (time-series trends only)+ subject: str = "The insight value" # breach-message subject+ framed: bool = True # include the "(label) for current/previous interval" framing+ # Detector path only: the query returned zero rows, so the metric is genuinely 0. An empty+ # ``series`` with this False instead means rows existed but none were long enough to score —+ # the detector reports that as an uncomputed value (None). Threshold extractors never set this+ # (they emit a zero sentinel series) and the comparator ignores it.+ empty_query_result: bool = False+++class AlertExtractionError(Exception):+ """The alert cannot be evaluated as configured (wrong query shape, bad config).++ Routed to the errored-alert notification path — distinct from "evaluated fine,+ no data this interval", which is represented as SeriesPoint(value=None).+ """+++def lookback_intervals_for(condition: AlertCondition) -> int:+ """How many trailing intervals an extractor must fetch for this condition.++ Absolute needs the current + previous interval (2); relative needs three intervals+ because, when the current interval is still accumulating, it compares the previous+ interval against the one before it.+ """+ match condition.type:+ case AlertConditionType.ABSOLUTE_VALUE:+ return 2+ case AlertConditionType.RELATIVE_INCREASE | AlertConditionType.RELATIVE_DECREASE:+ return 3+ case _:+ raise AlertExtractionError(f"Unsupported alert condition type: {condition.type}")+++class Extractor(Protocol):+ def extract(self, alert: AlertConfiguration, insight: Insight, query: object) -> ExtractionResult: ...diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pynew file mode 100644index 000000000000..8fae674b5173--- /dev/null+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -0,0 +1,51 @@+from posthog.schema import AlertCondition, InsightThreshold, NodeKind, TrendsQuery++from posthog.schema_migrations.upgrade_manager import upgrade_query+from posthog.tasks.alerts.detector import check_trends_alert_with_detector+from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult+from posthog.utils import get_from_dict_or_attr++from products.alerts.backend.evaluation.comparator import evaluate_threshold+from products.alerts.backend.evaluation.contract import Extractor+from products.alerts.backend.evaluation.trends import TrendsExtractor+from products.alerts.backend.models.alert import AlertConfiguration++# Each insight kind that supports alerts maps to one extractor. The comparator is shared.+EXTRACTORS: dict[NodeKind, Extractor] = {+ NodeKind.TRENDS_QUERY: TrendsExtractor(),+}+++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.+ """+ insight = alert.insight++ 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 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)++ extractor = EXTRACTORS.get(kind)+ if extractor is None:+ raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")++ # Short-circuit before the (potentially expensive) query: no bounds means nothing to breach.+ threshold = InsightThreshold.model_validate(alert.threshold.configuration) if alert.threshold else None+ if not threshold or not threshold.bounds:+ return AlertEvaluationResult(value=0, breaches=[])++ condition = AlertCondition.model_validate(alert.condition)+ result = extractor.extract(alert, insight, query)+ return evaluate_threshold(result, condition, threshold)diff --git a/products/alerts/backend/evaluation/test/test_comparator.py b/products/alerts/backend/evaluation/test/test_comparator.pynew file mode 100644index 000000000000..e5c122626a66--- /dev/null+++ b/products/alerts/backend/evaluation/test/test_comparator.py@@ -0,0 +1,202 @@+import pytest++from posthog.schema import (+ AlertCondition,+ AlertConditionType,+ InsightsThresholdBounds,+ InsightThreshold,+ InsightThresholdType,+ IntervalType,+)++from products.alerts.backend.evaluation.comparator import evaluate_threshold+from products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult, SeriesPoint++ABSOLUTE = AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE)+INCREASE = AlertCondition(type=AlertConditionType.RELATIVE_INCREASE)+DECREASE = AlertCondition(type=AlertConditionType.RELATIVE_DECREASE)+++def _threshold(type_=InsightThresholdType.ABSOLUTE, lower=None, upper=None):+ return InsightThreshold(type=type_, bounds=InsightsThresholdBounds(lower=lower, upper=upper))+++def _result(+ series,+ *,+ is_breakdown=False,+ subject="The insight value",+ framed=True,+ interval_type=None,+ empty_query_result=False,+):+ return ExtractionResult(+ series=series,+ is_breakdown=is_breakdown,+ subject=subject,+ framed=framed,+ interval_type=interval_type,+ empty_query_result=empty_query_result,+ )+++def _single(value, label="A"):+ return _result([ComparableSeries(label=label, points=[SeriesPoint(date=None, value=value)], current_index=0)])+++ "value,lower,upper,expected_message",+ [+ (50.0, 10, 100, None), # within bounds → no breach+ (5.0, 10, None, "less than lower threshold"),+ (150.0, None, 100, "more than upper threshold"),+ ],+)+def test_absolute_breach_detection(value, lower, upper, expected_message):+ result = evaluate_threshold(_single(value), ABSOLUTE, _threshold(lower=lower, upper=upper))+ assert result.value == value+ if expected_message is None:+ assert result.breaches == []+ else:+ assert result.breaches is not None and len(result.breaches) == 1+ assert expected_message in result.breaches[0]+++ "values,current_index,is_current,condition,threshold_type,upper,expected_value,expected_message",+ [+ # non-current anchor (index 1 = prev): increase = prev - prev_prev = 20 - 10+ ([10.0, 20.0, 35.0], 1, False, INCREASE, InsightThresholdType.ABSOLUTE, 5, 10.0, "increased"),+ # check_ongoing → anchor = last (current): increase = current - prev = 35 - 20+ ([10.0, 20.0, 35.0], 2, True, INCREASE, InsightThresholdType.ABSOLUTE, 5, 15.0, "current"),+ # decrease = prev_prev - prev = 20 - 8+ ([20.0, 8.0, 5.0], 1, False, DECREASE, InsightThresholdType.ABSOLUTE, 5, 12.0, "decreased"),+ # percentage: (20 - 10) / 10 = 1.0+ ([10.0, 20.0, 30.0], 1, False, INCREASE, InsightThresholdType.PERCENTAGE, 0.5, 1.0, None),+ # percentage with a zero base → inf+ ([0.0, 10.0, 20.0], 1, False, INCREASE, InsightThresholdType.PERCENTAGE, 0.5, float("inf"), None),+ ],+)+def test_relative_value_computation(+ values, current_index, is_current, condition, threshold_type, upper, expected_value, expected_message+):+ series = [+ ComparableSeries(+ label="A",+ points=[SeriesPoint(None, v) for v in values],+ current_index=current_index,+ is_current_interval=is_current,+ )+ ]+ result = evaluate_threshold(_result(series), condition, _threshold(type_=threshold_type, upper=upper))+ assert result.value == expected_value+ if expected_message is not None:+ assert result.breaches is not None and expected_message in result.breaches[0]+++ "is_breakdown,n_series,expected_value",+ [+ (False, 1, 50.0), # single-series query reports its computed value+ (True, 2, None), # breakdown has no single representative value → None+ (True, 1, None), # a one-series breakdown still reports None (keyed off is_breakdown, not count)+ ],+)+def test_no_breach_value_reporting(is_breakdown, n_series, expected_value):+ series = [+ ComparableSeries(label=f"s{i}", points=[SeriesPoint(None, 50.0)], current_index=0) for i in range(n_series)+ ]+ result = evaluate_threshold(_result(series, is_breakdown=is_breakdown), ABSOLUTE, _threshold(lower=10))+ assert result.breaches == []+ assert result.value == expected_value+++ "threshold",+ [+ None, # no threshold at all+ InsightThreshold(type=InsightThresholdType.ABSOLUTE, bounds=None), # bounds=None+ ],+)+def test_missing_threshold_or_bounds_returns_zero(threshold):+ # The dispatcher short-circuits to value=0 before running the query; the comparator mirrors it.+ result = evaluate_threshold(_single(50.0), ABSOLUTE, threshold)+ assert result.breaches == []+ assert result.value == 0+++def test_empty_bounds_evaluates_but_never_breaches():+ # bounds present but both None: truthy → proceeds, no lower/upper to breach → reports value.+ result = evaluate_threshold(_single(50.0), ABSOLUTE, _threshold())+ assert result.breaches == []+ assert result.value == 50.0+++def test_breakdown_breaches_if_any_series_breaches():+ series = [+ ComparableSeries(label="us", points=[SeriesPoint(None, 50.0)], current_index=0),+ ComparableSeries(label="de", points=[SeriesPoint(None, 5.0)], current_index=0),+ ]+ result = evaluate_threshold(_result(series, is_breakdown=True), ABSOLUTE, _threshold(lower=10))+ assert result.breaches is not None and len(result.breaches) == 1+ assert "de" in result.breaches[0]+ assert result.value == 5.0+++def test_empty_query_result_reports_zero_even_for_breakdown():+ # An empty query result reports value=0 regardless of breakdown (the metric is genuinely zero),+ # matching the original _is_empty_query_result. Without the empty_query_result flag a breakdown+ # would report None here.+ sentinel = [+ ComparableSeries(label="empty result", points=[SeriesPoint(None, 0.0), SeriesPoint(None, 0.0)], current_index=1)+ ]+ for is_breakdown in (False, True):+ result = _result(sentinel, is_breakdown=is_breakdown, empty_query_result=True)+ no_breach = evaluate_threshold(result, ABSOLUTE, _threshold(lower=-5))+ assert no_breach.breaches == []+ assert no_breach.value == 0+++ "condition",+ [ABSOLUTE, INCREASE, DECREASE],+)+def test_empty_result_sentinel_evaluates_zero_and_can_breach(condition):+ # The extractor emits a two-zero-point sentinel for an empty result: absolute reads 0, relative+ # computes 0 - 0 = 0. A positive lower bound fires on that 0 (parity with the original).+ empty = _result(+ [+ ComparableSeries(+ label="empty result", points=[SeriesPoint(None, 0.0), SeriesPoint(None, 0.0)], current_index=1+ )+ ]+ )+ breach = evaluate_threshold(empty, condition, _threshold(lower=5))+ assert breach.value == 0.0+ assert breach.breaches is not None and len(breach.breaches) == 1+ no_breach = evaluate_threshold(empty, condition, _threshold(lower=-5))+ assert no_breach.value == 0.0+ assert no_breach.breaches == []+++def test_missing_current_point_skips_series():+ series = [ComparableSeries(label="A", points=[SeriesPoint(None, None)], current_index=0)]+ result = evaluate_threshold(_result(series), ABSOLUTE, _threshold(lower=10))+ assert result.breaches == []+++def test_framed_message_includes_series_and_interval():+ series = [ComparableSeries(label="US", points=[SeriesPoint(None, 5.0)], current_index=0)]+ result = evaluate_threshold(_result(series, interval_type=IntervalType.DAY), ABSOLUTE, _threshold(lower=10))+ assert result.breaches is not None+ assert result.breaches[0] == "The insight value (US) for previous day (5.0) is less than lower threshold (10.0)"+++def test_unframed_message_uses_subject_without_interval_framing():+ series = [ComparableSeries(label="result", points=[SeriesPoint(None, 5.0)], current_index=0)]+ result = evaluate_threshold(+ _result(series, subject="The SQL insight value", framed=False), ABSOLUTE, _threshold(lower=10)+ )+ assert result.breaches is not None+ assert result.breaches[0] == "The SQL insight value (5.0) is less than lower threshold (10.0)"+ assert "interval" not in result.breaches[0]diff --git a/products/alerts/backend/evaluation/test/test_contract.py b/products/alerts/backend/evaluation/test/test_contract.pynew file mode 100644index 000000000000..e127473d93fd--- /dev/null+++ b/products/alerts/backend/evaluation/test/test_contract.py@@ -0,0 +1,17 @@+import pytest++from posthog.schema import AlertCondition, AlertConditionType++from products.alerts.backend.evaluation.contract import lookback_intervals_for+++ "condition_type,expected_intervals",+ [+ (AlertConditionType.ABSOLUTE_VALUE, 2),+ (AlertConditionType.RELATIVE_INCREASE, 3),+ (AlertConditionType.RELATIVE_DECREASE, 3),+ ],+)+def test_lookback_intervals_for(condition_type, expected_intervals):+ assert lookback_intervals_for(AlertCondition(type=condition_type)) == expected_intervalsdiff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.pynew file mode 100644index 000000000000..ebdc20805a72--- /dev/null+++ b/products/alerts/backend/evaluation/trends.py@@ -0,0 +1,204 @@+from typing import Any, cast++from posthog.schema import (+ AlertCondition,+ AlertConditionType,+ InsightThreshold,+ InsightThresholdType,+ IntervalType,+ TrendsAlertConfig,+ TrendsQuery,+)++from posthog.api.services.query import ExecutionMode+from posthog.caching.calculate_results import calculate_for_query_based_insight+from posthog.caching.fetch_from_cache import InsightResult+from posthog.event_usage import EventSource++# These helpers also back the anomaly detector, so they remain in the tasks module for now.+from posthog.tasks.alerts.trends import (+ _date_range_override_for_intervals,+ _has_breakdown,+ _is_non_time_series_trend,+ _pick_series_result,+)++from products.alerts.backend.evaluation.contract import (+ ComparableSeries,+ ExtractionResult,+ SeriesPoint,+ lookback_intervals_for,+)+from products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.models.insight import Insight++EMPTY_RESULT_LABEL = "empty result"+++class TrendsExtractor:+ """Execute a trends insight and normalize the result into ``ComparableSeries``.++ Owns the trends-specific decisions — series/breakdown picking, how many intervals to+ fetch per condition, and which interval is the comparison anchor (the "wait for the+ current interval to complete" policy) — and hides them behind the contract. The+ comparator then interprets the series without knowing it came from a trend.++ Execution order per condition is significant and must hold: pre-execution config guards,+ run the query, handle empty/None results, post-execution ongoing-interval guard, then+ normalize. Relative conditions are invalid for non-time-series insights and raise.+ """++ def extract(self, alert: AlertConfiguration, insight: Insight, query: Any) -> ExtractionResult:+ query = TrendsQuery.model_validate(query)+ if not (alert.config and "type" in alert.config and alert.config["type"] == "TrendsAlertConfig"):+ raise ValueError(f"Unsupported alert config type: {alert.config}")+ config = TrendsAlertConfig.model_validate(alert.config)+ condition = AlertCondition.model_validate(alert.condition)+ # Dispatcher short-circuits when threshold/bounds are missing, so both are present here.+ if alert.threshold is None:+ raise ValueError("TrendsExtractor requires a threshold — dispatcher invariant violated")+ threshold = InsightThreshold.model_validate(alert.threshold.configuration)+ if threshold.bounds is None:+ raise ValueError("TrendsExtractor requires threshold bounds — dispatcher invariant violated")++ is_non_time_series = _is_non_time_series_trend(query)+ has_breakdown = _has_breakdown(query)+ check_current_interval = bool(config.check_ongoing_interval)+ lookback_intervals = lookback_intervals_for(condition)+ interval_type = None if is_non_time_series else query.interval++ execution_mode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ if query.interval == IntervalType.HOUR:+ execution_mode = ExecutionMode.CALCULATE_BLOCKING_ALWAYS++ match condition.type:+ case AlertConditionType.ABSOLUTE_VALUE:+ if threshold.type != InsightThresholdType.ABSOLUTE:+ raise ValueError("Absolute threshold not configured for alert condition ABSOLUTE_VALUE")+ # Non-time-series aggregates over the full interval; time-series looks back N intervals.+ filters_override = (+ None+ if is_non_time_series+ else _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)+ )+ calculation_result = self._calculate(alert, insight, execution_mode, filters_override)+ if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:+ return empty+ if check_current_interval and threshold.bounds.upper is None:+ raise ValueError(+ "check_ongoing_interval is only supported for alert condition ABSOLUTE_VALUE when upper threshold is specified"+ )+ anchor_is_current = check_current_interval or is_non_time_series++ case AlertConditionType.RELATIVE_INCREASE:+ if is_non_time_series:+ raise ValueError("Relative alerts not supported for non time series trends")+ # When the current interval is incomplete we compare the previous interval+ # against the one before it, so we need the extra lookback interval.+ filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)+ calculation_result = self._calculate(alert, insight, execution_mode, filters_override)+ if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:+ return empty+ if check_current_interval and threshold.bounds.upper is None:+ raise ValueError(+ "check_ongoing_interval is only supported for alert condition RELATIVE_INCREASE when upper threshold is specified"+ )+ anchor_is_current = check_current_interval++ case AlertConditionType.RELATIVE_DECREASE:+ if is_non_time_series:+ raise ValueError("Relative alerts not supported for non time series trends")+ filters_override = _date_range_override_for_intervals(query, last_x_intervals=lookback_intervals)+ calculation_result = self._calculate(alert, insight, execution_mode, filters_override)+ if (empty := self._empty_result(calculation_result, alert, has_breakdown, interval_type)) is not None:+ return empty+ anchor_is_current = False++ case _:+ raise NotImplementedError(f"Unsupported alert condition type: {condition.type}")++ series = self._to_series(config, calculation_result, has_breakdown, is_non_time_series, anchor_is_current)+ # subject/framed use the ExtractionResult defaults ("The insight value", framed).+ return ExtractionResult(series=series, is_breakdown=has_breakdown, interval_type=interval_type)++ def _calculate(+ self,+ alert: AlertConfiguration,+ insight: Insight,+ execution_mode: ExecutionMode,+ filters_override: dict | None,+ ) -> InsightResult:+ return calculate_for_query_based_insight(+ insight,+ team=alert.team,+ execution_mode=execution_mode,+ user=None,+ filters_override=filters_override,+ analytics_props={"source": EventSource.ALERT},+ )++ def _empty_result(+ self,+ calculation_result: InsightResult,+ alert: AlertConfiguration,+ has_breakdown: bool,+ interval_type: IntervalType | None,+ ) -> ExtractionResult | None:+ """A ``None`` result means the query layer swallowed an error — raise to avoid a misfire.+ An empty result means no data, treated as a 0 value compared against the threshold (this+ can fire a breach, e.g. a lower-bound alert).++ Two zero points (not one) so relative conditions compute 0 - 0 = 0 rather than skipping+ for lack of a previous point; absolute reads the same 0 at the anchor."""+ if calculation_result.result is None:+ raise RuntimeError(f"No results found for insight with alert id = {alert.id}")+ if not calculation_result.result:+ sentinel = ComparableSeries(+ label=EMPTY_RESULT_LABEL,+ points=[SeriesPoint(date=None, value=0.0), SeriesPoint(date=None, value=0.0)],+ current_index=1,+ is_current_interval=False,+ )+ return ExtractionResult(+ series=[sentinel],+ is_breakdown=has_breakdown,+ interval_type=interval_type,+ empty_query_result=True,+ )+ return None++ def _to_series(+ self,+ config: TrendsAlertConfig,+ calculation_result: InsightResult,+ has_breakdown: bool,+ is_non_time_series: bool,+ anchor_is_current: bool,+ ) -> list[ComparableSeries]:+ if has_breakdown:+ results = cast(list[dict[str, Any]], calculation_result.result)+ else:+ results = [cast(dict[str, Any], _pick_series_result(config, calculation_result))]++ series: list[ComparableSeries] = []+ for result in results:+ if is_non_time_series:+ points = [SeriesPoint(date=None, value=result["aggregated_value"])]+ else:+ data = result["data"]+ dates = result.get("dates") or result.get("days") or [None] * len(data)+ points = [SeriesPoint(date=date, value=value) for date, value in zip(dates, data)]++ # Anchor on the current (ongoing) interval, or the last complete one. On a series+ # shorter than expected this can go negative and wrap, which the comparator then+ # treats as having no previous point — acceptable for a degenerate sparse series.+ current_index = len(points) - 1 if anchor_is_current else len(points) - 2+ series.append(+ ComparableSeries(+ label=result["label"],+ points=points,+ current_index=current_index,+ is_current_interval=anchor_is_current,+ )+ )+ return series