: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
feat(alerts): add evaluation delay for late-arriving data (#108382)
posthog[bot]219fd32f9a46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 54174d291034..f6ffb7057660 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6114,6 +6114,10 @@ snapshots:hash: v1.k794b7964.aff80ff28ac505a67d825f095688d9f424cb3d885052e8ef1064f7efd0fae2ae.zyQl0OgEH3hLa51zt2hYN0sPd-50XwnwddfpOzMa3Poproducts-alerts-shared-components--preview-breakdown--light:hash: v1.k794b7964.e1839b06a48fc951fa0d80007250480e0070d5c4c8de140dcc94623372c66a85.Ws7QP_xjYLQHx5zUmIIrDyPZUEgTi8VaBsbXqvhQhxc+ products-alerts-shared-components--preview-delay-history-too-short--dark:+ hash: v1.k794b7964.897b075b40384ff4cafbcc82af76e6652f09a660eebffaa7b305f671b4a6db25.hxk6Zc5UP6hsDvVbMnmtXFAD_u4gUFsiY2u7pqqSCIY+ products-alerts-shared-components--preview-delay-history-too-short--light:+ hash: v1.k794b7964.935cead201ff5d13605d74fa3ae4b1e0e30e50e1e2d201673b14e043a0c76757.T73KDliqtQr0TSZ_VxBBUuODDEsIATCuW9qCHibBCzwproducts-alerts-shared-components--preview-log-scale--dark:hash: v1.k794b7964.906c1930c0e5ceee290a929d4ba68eb4ff58ce08f6e89f89474ada2fff12505d.U1FElozFVhx4UwEdkRh8KkkZQl-n3074MGTZtdFD5Z4products-alerts-shared-components--preview-log-scale--light:diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 219d2405ccb8..a7fbfd5e08f9 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -2430,6 +2430,7 @@"posthog_alertconfiguration"."insight_id","posthog_alertconfiguration"."name","posthog_alertconfiguration"."config",+ "posthog_alertconfiguration"."evaluation_delay_intervals","posthog_alertconfiguration"."calculation_interval","posthog_alertconfiguration"."threshold_id","posthog_alertconfiguration"."condition",@@ -8009,6 +8010,7 @@"posthog_alertconfiguration"."insight_id","posthog_alertconfiguration"."name","posthog_alertconfiguration"."config",+ "posthog_alertconfiguration"."evaluation_delay_intervals","posthog_alertconfiguration"."calculation_interval","posthog_alertconfiguration"."threshold_id","posthog_alertconfiguration"."condition",diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.pyindex bdb1f7b3ed38..f4154e796aaf 100644--- a/posthog/tasks/alerts/investigation_notifications.py+++ b/posthog/tasks/alerts/investigation_notifications.py@@ -76,6 +76,8 @@ def run_investigation_notification_safety_net() -> int:targets_notified={},alert_configuration__investigation_agent_enabled=True,)+ # A skipped check copies the alert's FIRING state but evaluated nothing, so it has no fire to deliver.+ .exclude(triggered_metadata__has_key="skipped_reason").filter(# Terminal investigation states (DONE / FAILED): the workflow is not coming# back, so a 5-min grace gets stuck dispatches through quickly. Non-terminaldiff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.pyindex 46f6f31256ee..6aef632c03dc 100644--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py@@ -5,13 +5,29 @@ from posthog.schema import AlertConditionType, AlertState, InsightThresholdTypefrom posthog.api.test.dashboards import DashboardAPIfrom posthog.tasks.alerts.test.alert_check_helpers import run_alert_check-from posthog.tasks.alerts.utils import AlertEvaluationResult, record_alert_delivery+from posthog.tasks.alerts.utils import AlertEvaluationResult, add_alert_check, record_alert_deliveryfrom products.alerts.backend.facade.contracts import AlertDeliveryfrom products.alerts.backend.models import AlertCheck, AlertConfigurationclass TestRunAlertCheck(APIBaseTest):+ def test_skipped_check_preserves_firing_state_without_notification(self) -> None:+ alert = AlertConfiguration.objects.get(id=self.alert_id)+ alert.state = AlertState.FIRING+ alert.save(update_fields=["state"])+ check, notify = add_alert_check(+ alert, AlertEvaluationResult(value=None, breaches=[], skipped_reason="Not enough completed intervals"), None+ )+ alert.refresh_from_db()+ assert alert.state == AlertState.FIRING+ assert alert.enabled+ assert not notify+ assert check.calculated_value is None+ assert check.triggered_metadata is not None+ assert check.triggered_metadata["skipped_reason"] == "Not enough completed intervals"+ assert alert.next_check_at is not None+def setUp(self) -> None:super().setUp()self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)diff --git a/posthog/tasks/alerts/test/test_detector_breakdowns.py b/posthog/tasks/alerts/test/test_detector_breakdowns.pyindex 80793b7d06e9..4292476367aa 100644--- a/posthog/tasks/alerts/test/test_detector_breakdowns.py+++ b/posthog/tasks/alerts/test/test_detector_breakdowns.py@@ -72,6 +72,7 @@ def _make_query_without_breakdown() -> TrendsQuery:def _make_alert(team: MagicMock, detector_config: dict[str, Any], series_index: int = 0) -> MagicMock:alert = MagicMock(spec=AlertConfiguration)+ alert.evaluation_delay_intervals = 0alert.id = "test-alert-id"alert.team = teamalert.config = {"type": "TrendsAlertConfig", "series_index": series_index}diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.pyindex 9a8c56d0ec34..d2e979eb4ff8 100644--- a/posthog/tasks/alerts/test/test_investigation_notifications.py+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py@@ -47,6 +47,7 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):notification_suppressed_by_agent: bool = False,targets_notified: dict | None = None,state: str = AlertState.FIRING,+ triggered_metadata: dict | None = None,) -> AlertCheck:check = AlertCheck.objects.create(alert_configuration=self.alert,@@ -56,6 +57,7 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):notification_sent_at=notification_sent_at,notification_suppressed_by_agent=notification_suppressed_by_agent,targets_notified=targets_notified or {},+ triggered_metadata=triggered_metadata,)# `created_at` is auto_now_add — bypass with an UPDATE so the parametrized# ages drive the safety-net's cutoff predicate.@@ -178,6 +180,17 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):assert notified == 0mock_dispatch.assert_not_called() # type: ignore[attr-defined]+ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")+ def test_skips_evaluation_skipped_check(self, mock_dispatch: object) -> None:+ self._make_check(+ age_minutes=INVESTIGATION_RUNNING_GRACE_MINUTES + 60,+ investigation_status=None,+ triggered_metadata={"skipped_reason": "Not enough completed intervals after the evaluation delay."},+ )+ notified = run_investigation_notification_safety_net()+ assert notified == 0+ mock_dispatch.assert_not_called() # type: ignore[attr-defined]+@patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")def test_skips_already_suppressed_check(self, mock_dispatch: object) -> None:self._make_check(diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 152c5f43519b..c73a32ef78a1 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -69,6 +69,7 @@ class AlertEvaluationResult:triggered_dates: list[str] | None = Noneinterval: str | None = Nonetriggered_metadata: dict | None = None+ skipped_reason: str | None = NoneWRAPPER_NODE_KINDS = [NodeKind.DATA_TABLE_NODE, NodeKind.DATA_VISUALIZATION_NODE, NodeKind.INSIGHT_VIZ_NODE]@@ -608,6 +609,19 @@ def add_alert_check("""# Evaluation never ran (query error): record an all-empty result so the check row still lands.result = evaluation_result if evaluation_result is not None else AlertEvaluationResult(value=None, breaches=None)+ if result.skipped_reason is not None:+ alert.last_checked_at = datetime.now(UTC)+ alert.next_check_at = next_check_time(alert)+ alert_check = AlertCheck.objects.create(+ alert_configuration=alert,+ calculated_value=None,+ condition=alert.condition,+ state=alert.state,+ targets_notified={},+ triggered_metadata={**(result.triggered_metadata or {}), "skipped_reason": result.skipped_reason},+ )+ alert.save(update_fields=["last_checked_at", "next_check_at"])+ return alert_check, Falseerror_message = error.get("message") if error else Noneoutcome = evaluate_alert_check(alert,diff --git a/posthog/temporal/ai/anomaly_investigation/tools.py b/posthog/temporal/ai/anomaly_investigation/tools.pyindex addce8dc9d6b..02c3b4a15a35 100644--- a/posthog/temporal/ai/anomaly_investigation/tools.py+++ b/posthog/temporal/ai/anomaly_investigation/tools.py@@ -132,6 +132,7 @@ def _run_detector_simulation(# columns fails with "more than one of them is numeric", so the investigation gets no# series and no baseline.config=alert.config,+ evaluation_delay_intervals=alert.evaluation_delay_intervals,date_from=date_from,user=alert.created_by,score=score and not is_llm_detector_config(alert.detector_config),diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex 38b5b4510b12..76e1ab196cc4 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -757,6 +757,10 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe)previous_state = alert.statealert_check, should_notify = add_alert_check(alert, alert_evaluation_result, error)+ if alert_evaluation_result is not None and alert_evaluation_result.skipped_reason is not None:+ return EvaluateAlertResult(+ alert_check_id=str(alert_check.id), should_notify=False, new_state=AlertState(alert.state)+ )investigation = decide_investigation(alert, alert_check)if investigation.should_investigate and claim_investigation_slot(alert, alert_check):@@ -888,6 +892,7 @@ def _evaluation_fingerprint(alert: AlertConfiguration) -> str:"condition","config","detector_config",+ "evaluation_delay_intervals","threshold_id","calculation_interval","next_check_at",diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.pyindex 4ca5178ce695..3c7c463b7050 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_tools.py@@ -1,3 +1,4 @@+from datetime import date, timedeltafrom typing import Anyimport pytest@@ -28,13 +29,14 @@ from products.product_analytics.backend.facade.models import Insightdef _trend_result(label: str, data: list[float]) -> dict[str, Any]:- dates = [f"2026-07-{day:02d}" for day in range(1, len(data) + 1)]+ dates = [(date(2026, 7, 1) + timedelta(days=day)).isoformat() for day in range(len(data))]return {"data": data, "days": dates, "label": label}[email protected]("delay", [0, 1])@patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight")-def test_run_detector_simulation_returns_the_alerts_configured_series(mock_calculate: MagicMock) -> None:- configured_series = [1000.0, 1100.0, 1000.0, 900.0] * 3+def test_run_detector_simulation_returns_the_alerts_configured_series(mock_calculate: MagicMock, delay: int) -> None:+ configured_series = [1000.0, 1100.0, 1000.0, 900.0] * 9mock_calculate.return_value = InsightResult(result=[_trend_result("series 0", [10.0, 11.0, 10.0, 9.0] * 3),@@ -60,6 +62,7 @@ def test_run_detector_simulation_returns_the_alerts_configured_series(mock_calcu).model_dump()alert = MagicMock(spec=AlertConfiguration)alert.insight = insight+ alert.evaluation_delay_intervals = delayalert.config = {"type": "TrendsAlertConfig", "series_index": 2}alert.detector_config = {"type": "zscore", "threshold": 0.9, "window": 10}alert.created_by = None@@ -67,7 +70,7 @@ def test_run_detector_simulation_returns_the_alerts_configured_series(mock_calcuresult = _run_detector_simulation(alert=alert, team=MagicMock(), date_from=None)assert not isinstance(result, str)- assert result["data"] == configured_series[:-1]+ assert result["data"] == configured_series[: -1 - delay]@pytest.mark.parametrize("triggered_dates,expected_indices", [(["2026-07-09"], [8]), (["2026-06-01"], [])])@@ -97,6 +100,7 @@ def test_run_detector_simulation_never_rescores_an_ai_alert(interval=IntervalType.DAY,).model_dump()alert = MagicMock(spec=AlertConfiguration)+ alert.evaluation_delay_intervals = 0alert.insight = insightalert.config = {"type": "TrendsAlertConfig", "series_index": 0}alert.detector_config = {"type": "llm", "threshold": 0.7, "window": 10}@@ -223,6 +227,7 @@ def test_run_detector_simulation_scores_the_configured_column_of_a_multi_numericinsight = MagicMock(spec=Insight)insight.query = HogQLQuery(query="SELECT day, failure_rate_pct, run_count FROM ci_runs").model_dump()alert = MagicMock(spec=AlertConfiguration)+ alert.evaluation_delay_intervals = 0alert.insight = insightalert.config = {"type": "HogQLAlertConfig", "column": "failure_rate_pct", "evaluation": "last_row"}alert.detector_config = {"type": "zscore", "threshold": 0.9, "window": 7}diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex f49e514ecc79..4e2206f478dc 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -1039,6 +1039,39 @@ class TestEvaluateAlert:refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=alert.pk)assert refreshed.enabled is True+ @pytest.mark.parametrize("state", [AlertState.FIRING, AlertState.NOT_FIRING])+ async def test_delayed_data_skips_without_recovery_or_investigation(self, ateam, state) -> None:+ alert = await _create_alert(+ ateam,+ query={+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "order completed"}],+ "interval": "hour",+ },+ state=state,+ )+ alert.evaluation_delay_intervals = 2+ await sync_to_async(alert.save)(update_fields=["evaluation_delay_intervals"])+ dates = ["2026-01-15T08:00:00Z", "2026-01-15T09:00:00Z", "2026-01-15T10:00:00Z"]+ with (+ patch(+ "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight",+ return_value=MagicMock(result=[{"data": [0, 0, 0], "dates": dates, "label": "Orders"}]),+ ),+ patch("posthog.temporal.alerts.activities.decide_investigation") as investigate,+ ):+ result = await ActivityEnvironment().run(+ evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert.id))+ )+ assert result.new_state == state+ assert result.should_notify is False+ check = await sync_to_async(AlertCheck.objects.get)(pk=result.alert_check_id)+ assert check.state == state+ assert check.calculated_value is None+ assert check.triggered_metadata is not None+ assert check.triggered_metadata["skipped_reason"]+ investigate.assert_not_called()+async def test_unavailable_data_records_error_without_disabling(self, alert_with_user) -> None:with (patch(@@ -1124,7 +1157,6 @@ class TestEvaluateAlert:async def test_evaluate_auto_disables_and_skips_error_tracking_on_configuration_error(self, alert_with_user, error_type) -> None:-with (patch("posthog.temporal.alerts.activities.check_alert_for_insight",diff --git a/products/alerts/backend/evaluation/contract.py b/products/alerts/backend/evaluation/contract.pyindex 81392e1fca33..7c5ed53af390 100644--- a/products/alerts/backend/evaluation/contract.py+++ b/products/alerts/backend/evaluation/contract.py@@ -5,6 +5,7 @@ from typing import Any, Protocolfrom posthog.schema import AlertCondition, AlertConditionType, IntervalTypefrom posthog.api.services.query import ExecutionMode+from posthog.dataclasses import frozenfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -26,7 +27,15 @@ class ComparableSeries:is_current_interval: bool = False # anchor is the ongoing (incomplete) interval — affects breach wording-@dataclass+@frozen+class EvaluatedInterval:+ start: str+ end: str+ timezone: str+ delay: int+++@dataclass(frozen=False)class ExtractionResult:"""Everything the comparator needs from an extractor, so the dispatcher stays kind-agnostic.@@ -58,6 +67,7 @@ class ExtractionResult:# decimals, duration, %). None → the comparator falls back to raw ``f"{value}{unit}"``. Only the# trends extractor sets it today; the PERCENTAGE-threshold path ignores it (relative % ratios).value_formatter: Callable[[float], str] | None = None+ evaluated_interval: EvaluatedInterval | None = Nonedef zero_sentinel_series() -> ComparableSeries:@@ -105,7 +115,7 @@ def execution_mode_for_alert(interval: IntervalType | None, *, high_frequency: breturn ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE-@dataclass+@dataclass(frozen=False)class SimulationContext:"""Alert-less inputs for a read-only detector simulation. Each extractor reads only the fields itskind needs: trends uses ``series_index``/``date_from``, SQL uses ``config``; both use ``team``,@@ -117,6 +127,7 @@ class SimulationContext:series_index: int = 0date_from: str | None = Noneconfig: dict[str, Any] | None = None+ evaluation_delay_intervals: int = 0class Extractor(Protocol):diff --git a/products/alerts/backend/evaluation/delay.py b/products/alerts/backend/evaluation/delay.pynew file mode 100644index 000000000000..e20d07e28405--- /dev/null+++ b/products/alerts/backend/evaluation/delay.py@@ -0,0 +1,116 @@+from dataclasses import replace+from datetime import date, datetime, timedelta+from zoneinfo import ZoneInfo++from posthog.schema import ChartDisplayType, IntervalType, NodeKind, TrendsQuery++from posthog.tasks.alerts.trends import _has_breakdown, _is_non_time_series_trend+from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult+from posthog.utils import get_from_dict_or_attr++from products.alerts.backend.evaluation.contract import EvaluatedInterval, ExtractionResult+++class DelayedEvaluationUnavailable(Exception):+ pass+++def validate_evaluation_delay(query: object, config: object, delay: int) -> None:+ if isinstance(delay, bool) or not isinstance(delay, int) or not 0 <= delay <= 100:+ raise ValueError("Evaluation delay must be a whole number between 0 and 100 intervals.")+ if delay == 0:+ return+ if get_from_dict_or_attr(query, "kind") in WRAPPER_NODE_KINDS:+ query = get_from_dict_or_attr(query, "source")+ if get_from_dict_or_attr(query, "kind") != NodeKind.TRENDS_QUERY:+ raise ValueError("Evaluation delay is only supported for time-series Trends insights.")+ trends_query = TrendsQuery.model_validate(query)+ display = trends_query.trendsFilter.display if trends_query.trendsFilter else None+ # The Trends runner returns a calendar heatmap as one aggregated value, not interval points.+ if _is_non_time_series_trend(trends_query) or display == ChartDisplayType.CALENDAR_HEATMAP:+ raise ValueError("Evaluation delay is only supported for time-series Trends insights.")+ # Compare mode adds previous-period breakdown rows with their own dates, and the check cannot+ # tell which row breached, so it cannot name the evaluated interval.+ if _has_breakdown(trends_query) and trends_query.compareFilter and trends_query.compareFilter.compare:+ raise ValueError(+ "Evaluation delay is not supported for breakdown insights that compare to a previous period. "+ "Turn off the comparison or set the delay to 0."+ )+ # A daysOfWeek filter drops day buckets, so a calendar-day lookback returns too few intervals.+ days_of_week = trends_query.dateRange.daysOfWeek if trends_query.dateRange else None+ if (trends_query.interval or IntervalType.DAY) == IntervalType.DAY and days_of_week and len(set(days_of_week)) < 7:+ raise ValueError(+ "Evaluation delay is not supported for daily insights that filter days of the week. "+ "Include every day or set the delay to 0."+ )+ if config is not None and not isinstance(config, dict):+ raise ValueError("Alert config must be a JSON object.")+ if (config or {}).get("check_ongoing_interval"):+ raise ValueError("Turn off Check ongoing period to use an evaluation delay.")+++def apply_evaluation_delay(+ result: ExtractionResult, *, delay: int, minimum_points: int, timezone: str+) -> ExtractionResult:+ if delay == 0:+ return result+ selected_series = []+ evaluated_interval = None+ for series in result.series:+ index = series.current_index - delay+ if index + 1 < minimum_points:+ raise DelayedEvaluationUnavailable(+ f"Not enough completed intervals after the evaluation delay. At least {minimum_points} eligible "+ "intervals are required. Wait for more data or reduce the evaluation delay."+ )+ if any(point.value is None for point in series.points[index + 1 - minimum_points : index + 1]):+ raise DelayedEvaluationUnavailable(+ "The eligible intervals contain missing values. Wait for more data or check the insight."+ )+ start, end = series.points[index].date, series.points[index + 1].date+ if start is None or end is None:+ raise DelayedEvaluationUnavailable("The delayed interval has no dates. Check the insight and try again.")+ if result.interval_type == IntervalType.DAY:+ end = _day_bucket_end(start, end, timezone)+ evaluated_interval = EvaluatedInterval(start=start, end=end, timezone=timezone, delay=delay)+ selected_series.append(replace(series, points=series.points[: index + 1], current_index=index))+ if not selected_series:+ raise DelayedEvaluationUnavailable(+ "No completed intervals are available after the evaluation delay. Wait for more data or reduce the delay."+ )+ return replace(+ result, series=selected_series, evaluated_interval=evaluated_interval, framed=False, include_series_label=True+ )+++def _day_bucket_end(start: str, next_start: str, timezone: str) -> str:+ # A daysOfWeek filter drops day buckets, so the next returned bucket can start days later.+ try:+ if date.fromisoformat(next_start[:10]) - date.fromisoformat(start[:10]) <= timedelta(days=1):+ return next_start+ if len(start) == 10:+ return (date.fromisoformat(start) + timedelta(days=1)).isoformat()+ moment = datetime.fromisoformat(start)+ except ValueError:+ return next_start+ if moment.tzinfo is not None:+ moment = moment.astimezone(ZoneInfo(timezone))+ return (moment + timedelta(days=1)).isoformat()+++def describe_delayed_evaluation(result: AlertEvaluationResult, extraction: ExtractionResult) -> AlertEvaluationResult:+ interval = extraction.evaluated_interval+ if interval is None:+ return result+ context = f"Evaluated {interval.start} to {interval.end} ({interval.timezone}; delay: {interval.delay} intervals)."+ return replace(+ result,+ breaches=[f"{context} {breach}" for breach in result.breaches] if result.breaches else result.breaches,+ triggered_metadata={+ **(result.triggered_metadata or {}),+ "evaluation_delay_intervals": interval.delay,+ "evaluated_interval_start": interval.start,+ "evaluated_interval_end": interval.end,+ "evaluated_interval_timezone": interval.timezone,+ },+ )diff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.pyindex c91ef4aca171..de3e71d7a83f 100644--- a/products/alerts/backend/evaluation/detector.py+++ b/products/alerts/backend/evaluation/detector.py@@ -21,6 +21,7 @@ from posthog.tasks.alerts.detector import (_date_range_override_for_detector,_extract_sub_detector_scores,_prepare_series,+ min_points_to_evaluate,)from posthog.tasks.alerts.detectors import DetectionResult, get_detectorfrom posthog.tasks.alerts.metric_definition import MetricDateRange, describe_metric_definition@@ -42,6 +43,11 @@ from products.alerts.backend.evaluation.contract import (SimulationContext,execution_mode_for_alert,)+from products.alerts.backend.evaluation.delay import (+ DelayedEvaluationUnavailable,+ apply_evaluation_delay,+ validate_evaluation_delay,+)from products.alerts.backend.judge import (JudgeAttribution,LLMDetectorMisconfiguredError,@@ -65,6 +71,7 @@ def extract_detector_series(series_index: int = 0,date_from: str | None = None,user: Optional[User] = None,+ evaluation_delay_intervals: int = 0,) -> ExtractionResult:"""Run a trends insight over the detector's lookback window and normalize it into series.@@ -74,7 +81,7 @@ def extract_detector_series(``empty_query_result=True``; rows that exist but are too short to score are dropped, also leavingan 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+ min_samples = _compute_min_samples_for_detector(detector_config) + 1 + evaluation_delay_intervalsis_non_time_series = _is_non_time_series_trend(query)already_complete = query_excludes_incomplete_periods(query)has_breakdown = _has_breakdown(query)@@ -98,6 +105,10 @@ def extract_detector_series(if calculation_result.result is None:raise RuntimeError(f"No results found for insight with id = {insight.id}")if not calculation_result.result:+ if evaluation_delay_intervals:+ raise DelayedEvaluationUnavailable(+ "No series is available to score. Wait for more data or check the insight."+ )return ExtractionResult(series=[], is_breakdown=has_breakdown, interval_type=query.interval, empty_query_result=True)@@ -112,16 +123,37 @@ def extract_detector_series(for result in results:prepared = _prepare_series(result, is_non_time_series, drop_current=not already_complete)if prepared is None:+ if evaluation_delay_intervals:+ raise DelayedEvaluationUnavailable(+ "A series has too few completed intervals. Wait for more data or reduce the delay."+ )continue+ if evaluation_delay_intervals:+ dates = result.get("dates") or result.get("days") or []+ prepared.dates = dates[: len(prepared.data)]points = [- SeriesPoint(date=(prepared.dates[i] if i < len(prepared.dates) else None), value=float(value))+ SeriesPoint(+ date=(prepared.dates[i] if i < len(prepared.dates) else None),+ value=None if value is None and evaluation_delay_intervals else 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)+ delayed = apply_evaluation_delay(+ ExtractionResult(series=series, is_breakdown=has_breakdown, interval_type=query.interval),+ delay=evaluation_delay_intervals,+ minimum_points=min_points_to_evaluate(detector_config),+ timezone=team.timezone,+ )+ # The detector scores every retained point, not only the trailing window the delay checks.+ if any(point.value is None for item in delayed.series for point in item.points):+ raise DelayedEvaluationUnavailable(+ "The eligible intervals contain missing values. Wait for more data or check the insight."+ )+ return delayeddef _triggered_dates(series: ComparableSeries, triggered_indices: list[int]) -> list[str]:@@ -411,6 +443,7 @@ class TrendsDetectorExtractor:execution_mode,series_index=series_index,user=alert.created_by,+ evaluation_delay_intervals=alert.evaluation_delay_intervals,)def simulate(self, insight: Insight, query: object, ctx: SimulationContext) -> tuple[ExtractionResult, str | None]:@@ -426,6 +459,7 @@ class TrendsDetectorExtractor:series_index=ctx.series_index,date_from=ctx.date_from,user=ctx.user,+ evaluation_delay_intervals=ctx.evaluation_delay_intervals,)interval_value = trends_query.interval.value if trends_query.interval else Nonereturn result, interval_value@@ -442,6 +476,7 @@ def simulate_detector_on_insight(*,score: bool = True,is_agent_billable: bool = True,+ evaluation_delay_intervals: int = 0,) -> dict[str, Any]:"""Run a detector over historical insight data for chart visualization. Read-only (no AlertCheck).@@ -475,6 +510,7 @@ def simulate_detector_on_insight(if extractor is None:raise ValueError(f"Anomaly detection simulation isn't supported for {kind} insights")+ validate_evaluation_delay(query, config, evaluation_delay_intervals)ctx = SimulationContext(team=team,detector_config=detector_config,@@ -482,8 +518,19 @@ def simulate_detector_on_insight(series_index=series_index,date_from=date_from,config=config,+ evaluation_delay_intervals=evaluation_delay_intervals,)result, interval_value = extractor.simulate(insight, query, ctx)+ interval_metadata = (+ {+ "evaluation_delay_intervals": result.evaluated_interval.delay,+ "evaluated_interval_start": result.evaluated_interval.start,+ "evaluated_interval_end": result.evaluated_interval.end,+ "evaluated_interval_timezone": result.evaluated_interval.timezone,+ }+ if result.evaluated_interval is not None+ else {}+ )if not result.series:# Preserve the original, more specific diagnostics: a genuinely empty query vs rows that@@ -526,11 +573,12 @@ def simulate_detector_on_insight("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,+ **interval_metadata,}sim = _sim_from_series(result.series[0], detector_config, detector_type_str, sim_context)sim.pop("label", None)- return {**sim, "interval": interval_value}+ return {**sim, "interval": interval_value, **interval_metadata}@frozendiff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.pyindex e44f3b071920..0c8926a646e6 100644--- a/products/alerts/backend/evaluation/dispatcher.py+++ b/products/alerts/backend/evaluation/dispatcher.py@@ -16,11 +16,18 @@ from products.alerts.backend.evaluation.contract import (Extractor,execution_mode_for_alert,)+from products.alerts.backend.evaluation.delay import (+ DelayedEvaluationUnavailable,+ describe_delayed_evaluation,+ validate_evaluation_delay,+)from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detectorfrom products.alerts.backend.evaluation.funnels import FunnelsExtractorfrom products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractorfrom products.alerts.backend.evaluation.metrics import MetricsExtractorfrom products.alerts.backend.evaluation.trends import TrendsExtractor+from products.alerts.backend.judge.contract import LLMDetectorUnavailableError+from products.alerts.backend.llm_detector_limits import is_llm_detector_configfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.facade.models import Insight@@ -95,10 +102,13 @@ def check_detector_alert(if detector_extractor is None:raise NotImplementedError(f"AlertCheckError: Detector alerts for {kind} are not supported yet")result = run_extractor(detector_extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))- return evaluate_with_detector(result, detector_config, insight=insight, alert=alert, evaluation_id=evaluation_id)+ return describe_delayed_evaluation(+ evaluate_with_detector(result, detector_config, insight=insight, alert=alert, evaluation_id=evaluation_id),+ result,+ )-def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:+def _check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:"""Dispatch an alert to its insight-kind extractor, then run the shared comparator.If ``detector_config`` is set, routes through the anomaly-detector registry (one extractor per@@ -118,6 +128,11 @@ def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | Nquery = get_from_dict_or_attr(query, "source")kind = get_from_dict_or_attr(query, "kind")+ try:+ validate_evaluation_delay(query, alert.config, alert.evaluation_delay_intervals)+ except ValueError as err:+ raise AlertExtractionError(str(err)) from err+if alert.detector_config:return check_detector_alert(alert, insight, query, evaluation_id=evaluation_id)@@ -132,4 +147,21 @@ def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | Ncondition = AlertCondition.model_validate(alert.condition)result = run_extractor(extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))- return evaluate_threshold(result, condition, threshold)+ return describe_delayed_evaluation(evaluate_threshold(result, condition, threshold), result)+++def check_alert_for_insight(alert: AlertConfiguration, *, evaluation_id: str | None = None) -> AlertEvaluationResult:+ try:+ return _check_alert_for_insight(alert, evaluation_id=evaluation_id)+ except DelayedEvaluationUnavailable as err:+ if is_llm_detector_config(alert.detector_config):+ raise LLMDetectorUnavailableError(str(err)) from err+ return AlertEvaluationResult(+ value=None,+ breaches=[],+ skipped_reason=str(err),+ triggered_metadata={+ "evaluation_delay_intervals": alert.evaluation_delay_intervals,+ "skipped_reason": str(err),+ },+ )diff --git a/products/alerts/backend/evaluation/test/test_date_range_overrides.py b/products/alerts/backend/evaluation/test/test_date_range_overrides.pyindex 7f3be4beac62..d7b2adb4ebe6 100644--- a/products/alerts/backend/evaluation/test/test_date_range_overrides.py+++ b/products/alerts/backend/evaluation/test/test_date_range_overrides.py@@ -71,6 +71,7 @@ def _trends_alert(condition_type: AlertConditionType, check_ongoing: bool = Falsalert = MagicMock()alert.config = {"type": "TrendsAlertConfig", "series_index": 0, "check_ongoing_interval": check_ongoing}alert.condition = {"type": condition_type}+ alert.evaluation_delay_intervals = 0threshold = MagicMock()threshold.configuration = {"type": "absolute", "bounds": {"upper": 100}}alert.threshold = threshold@@ -87,6 +88,24 @@ def _clipped_trends_query() -> dict:class TestTrendsExtractorIncompletePeriods(TestCase):+ @parameterized.expand([(False,), (True,)])+ def test_evaluation_delay_skips_empty_completed_buckets(self, already_complete: bool) -> None:+ alert = _trends_alert(AlertConditionType.ABSOLUTE_VALUE)+ alert.evaluation_delay_intervals = 2+ query = _clipped_trends_query()+ query["interval"] = "hour"+ query["dateRange"]["excludeIncompletePeriods"] = already_complete+ row = {+ "data": [40.0, 42.0, 0.0, 0.0] + ([] if already_complete else [0.0]),+ "dates": [f"2026-01-15T{hour:02d}:00:00Z" for hour in range(6, 10 if already_complete else 11)],+ "label": "Orders",+ }+ with patch(TRENDS_CALC_PATH, return_value=MagicMock(result=[row])):+ result = TrendsExtractor().extract(alert, MagicMock(), query, ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ selected = result.series[0].points[result.series[0].current_index]+ self.assertEqual(selected.value, 42.0)+ self.assertEqual(selected.date, "2026-01-15T07:00:00Z")+@parameterized.expand([("absolute", AlertConditionType.ABSOLUTE_VALUE),diff --git a/products/alerts/backend/evaluation/test/test_evaluation_delay.py b/products/alerts/backend/evaluation/test/test_evaluation_delay.pynew file mode 100644index 000000000000..2e0fa1785354--- /dev/null+++ b/products/alerts/backend/evaluation/test/test_evaluation_delay.py@@ -0,0 +1,280 @@+from datetime import UTC, datetime, timedelta+from typing import Any++import time_machine+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.team import Team+from posthog.tasks.alerts.utils import AlertEvaluationResult++from products.alerts.backend.evaluation.delay import DelayedEvaluationUnavailable, validate_evaluation_delay+from products.alerts.backend.evaluation.detector import simulate_detector_on_insight+from products.alerts.backend.evaluation.dispatcher import check_alert_for_insight+from products.alerts.backend.judge.contract import LLMDetectorUnavailableError+from products.alerts.backend.models.alert import AlertConfiguration, Threshold+from products.alerts.backend.presentation.views.alert import AlertSerializer, AlertSimulateSerializer+from products.product_analytics.backend.facade.models import Insight+++class TestEvaluationDelay(SimpleTestCase):+ def setUp(self) -> None:+ self.team = Team(timezone="UTC")+ self.query: dict[str, Any] = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "order completed"}],+ "interval": "hour",+ "dateRange": {"date_from": "-7d"},+ }+ self.insight = Insight(team=self.team, query=self.query)+ self.alert = AlertConfiguration(+ team=self.team,+ insight=self.insight,+ config={"type": "TrendsAlertConfig", "series_index": 0, "check_ongoing_interval": False},+ condition={"type": "absolute_value"},+ threshold=Threshold(configuration={"type": "absolute", "bounds": {"lower": 10}}),+ calculation_interval="every_15_minutes",+ evaluation_delay_intervals=2,+ )++ def evaluate(self, data: list[float | None], dates: list[str], detector: bool = False) -> AlertEvaluationResult:+ module = "detector" if detector else "trends"+ with patch(f"products.alerts.backend.evaluation.{module}.calculate_for_query_based_insight") as calculate:+ calculate.return_value.result = [{"data": data, "dates": dates, "days": dates, "label": "Orders"}]+ return check_alert_for_insight(self.alert)++ @parameterized.expand(+ [+ ("absolute_normal", "absolute_value", "absolute", 42.0, 42.0, False),+ ("absolute_zero", "absolute_value", "absolute", 0.0, 0.0, True),+ ("relative_increase", "relative_increase", "absolute", 60.0, 20.0, True),+ ("relative_decrease", "relative_decrease", "absolute", 20.0, 20.0, True),+ ("percentage_increase", "relative_increase", "percentage", 60.0, 0.5, True),+ ("percentage_decrease", "relative_decrease", "percentage", 20.0, 0.5, True),+ ]+ )+ @time_machine.travel("2026-01-15T10:30:00Z", tick=False)+ def test_threshold_uses_eligible_interval_and_comparison(+ self, _name: str, condition: str, threshold_type: str, value: float, expected: float, fires: bool+ ) -> None:+ self.alert.condition = {"type": condition}+ if condition != "absolute_value":+ assert self.alert.threshold is not None+ self.alert.threshold.configuration = {+ "type": threshold_type,+ "bounds": {"upper": 0.1 if threshold_type == "percentage" else 10},+ }+ dates = [f"2026-01-15T{hour:02d}:00:00Z" for hour in range(6, 11)]+ result = self.evaluate([40.0, value, 0.0, 0.0, 0.0], dates)+ self.assertEqual(result.value, expected)+ assert result.breaches is not None+ self.assertEqual(bool(result.breaches), fires)+ self.assertEqual(+ result.triggered_metadata,+ {+ "evaluation_delay_intervals": 2,+ "evaluated_interval_start": dates[1],+ "evaluated_interval_end": dates[2],+ "evaluated_interval_timezone": "UTC",+ },+ )+ if fires:+ self.assertIn(f"{dates[1]} to {dates[2]}", result.breaches[0])+ self.assertNotIn("previous hour", result.breaches[0])+ assert self.insight.query is not None+ self.assertEqual(self.insight.query["dateRange"], self.query["dateRange"])++ @parameterized.expand([(False, 101.0, False), (True, 101.0, False), (False, 0.0, True), (True, 0.0, True)])+ @time_machine.travel("2026-01-15T10:30:00Z", tick=False)+ def test_detector_and_simulation_share_eligible_history(self, clipped: bool, value: float, fires: bool) -> None:+ self.query["dateRange"]["excludeIncompletePeriods"] = clipped+ self.alert.detector_config = {"type": "zscore", "window": 30, "threshold": 0.9}+ data = [100.0 + i % 3 for i in range(31)] + [value, 0.0, 0.0] + ([] if clipped else [0.0])+ dates = [(datetime(2026, 1, 15, 7, tzinfo=UTC) + timedelta(hours=i - 31)).isoformat() for i in range(len(data))]+ with patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight") as calculate:+ calculate.return_value.result = [{"data": data, "dates": dates, "days": dates, "label": "Orders"}]+ result = check_alert_for_insight(self.alert)+ simulation = simulate_detector_on_insight(+ self.insight, self.team, self.alert.detector_config, evaluation_delay_intervals=2+ )+ self.assertEqual(calculate.call_args.kwargs["filters_override"], {"date_from": "-34h"})+ self.assertEqual(result.value, value)+ self.assertEqual(bool(result.breaches), fires)+ self.assertEqual(simulation["data"], data[:32])+ self.assertEqual(simulation["evaluated_interval_start"], dates[31])+ self.assertEqual(simulation["evaluated_interval_end"], dates[32])+ assert result.triggered_metadata is not None+ self.assertEqual(result.triggered_metadata["evaluated_interval_start"], simulation["dates"][-1])++ @parameterized.expand([(False,), (True,)])+ def test_short_history_is_skipped(self, detector: bool) -> None:+ if detector:+ self.alert.detector_config = {"type": "zscore", "window": 30}+ result = self.evaluate(+ [0.0, 0.0, 0.0], ["2026-01-15T08:00:00Z", "2026-01-15T09:00:00Z", "2026-01-15T10:00:00Z"], detector+ )+ self.assertIsNone(result.value)+ self.assertFalse(result.breaches)+ assert result.skipped_reason is not None+ self.assertIn("Not enough completed intervals", result.skipped_reason)++ def test_empty_breakdown_result_breaches_as_zero(self) -> None:+ self.query["breakdownFilter"] = {"breakdown": "$browser", "breakdown_type": "event"}+ with patch("products.alerts.backend.evaluation.trends.calculate_for_query_based_insight") as calculate:+ calculate.return_value.result = []+ result = check_alert_for_insight(self.alert)+ self.assertIsNone(result.skipped_reason)+ self.assertEqual(result.value, 0)+ assert result.breaches is not None+ self.assertEqual(len(result.breaches), 1)+ self.assertIn("less than lower threshold", result.breaches[0])+ self.assertNotIn("previous hour", result.breaches[0])++ def test_empty_detector_result_skips_without_a_baseline(self) -> None:+ self.alert.detector_config = {"type": "zscore", "window": 30}+ self.query["breakdownFilter"] = {"breakdown": "$browser", "breakdown_type": "event"}+ with patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight") as calculate:+ calculate.return_value.result = []+ result = check_alert_for_insight(self.alert)+ self.alert.evaluation_delay_intervals = 0+ without_delay = check_alert_for_insight(self.alert)+ self.assertIsNone(result.value)+ self.assertEqual(result.breaches, [])+ assert result.skipped_reason is not None+ self.assertIn("No series is available to score", result.skipped_reason)+ self.assertEqual(without_delay.value, 0)+ self.assertIsNone(without_delay.skipped_reason)++ @parameterized.expand([(False, 31), (True, 31), (True, 0)])+ def test_missing_eligible_value_is_skipped(self, detector: bool, missing_index: int) -> None:+ self.alert.detector_config = {"type": "zscore", "window": 30} if detector else None+ data = list[float | None]([100.0] * 31 + [0.0, 0.0, 0.0, 0.0])+ data[missing_index] = None+ dates = [(datetime(2026, 1, 15, tzinfo=UTC) + timedelta(hours=i)).isoformat() for i in range(len(data))]+ result = self.evaluate(data, dates, detector)+ self.assertIsNone(result.value)+ assert result.skipped_reason is not None+ self.assertIn("missing values", result.skipped_reason)++ @parameterized.expand([("short_history", 3, None), ("missing_value", 10, 4)])+ def test_delayed_ai_without_a_verdict_raises(self, _name: str, length: int, missing_index: int | None) -> None:+ self.alert.detector_config = {"type": "llm"}+ data = list[float | None]([100.0] * length)+ if missing_index is not None:+ data[missing_index] = None+ dates = [(datetime(2026, 1, 15, tzinfo=UTC) + timedelta(hours=i)).isoformat() for i in range(length)]++ with self.assertRaises(LLMDetectorUnavailableError) as raised:+ self.evaluate(data, dates, detector=True)+ self.assertIsInstance(raised.exception.__cause__, DelayedEvaluationUnavailable)++ def test_delayed_ai_without_a_series_raises(self) -> None:+ self.alert.detector_config = {"type": "llm"}+ with patch("products.alerts.backend.evaluation.detector.calculate_for_query_based_insight") as calculate:+ calculate.return_value.result = []+ with self.assertRaisesRegex(LLMDetectorUnavailableError, "No series is available to score"):+ check_alert_for_insight(self.alert)++ @parameterized.expand(+ [+ (+ "hour",+ "America/New_York",+ [+ "2026-11-01T00:00:00-04:00",+ "2026-11-01T01:00:00-04:00",+ "2026-11-01T01:00:00-05:00",+ "2026-11-01T02:00:00-05:00",+ "2026-11-01T03:00:00-05:00",+ ],+ ),+ (+ "day",+ "America/New_York",+ [+ "2026-03-07T00:00:00-05:00",+ "2026-03-08T00:00:00-05:00",+ "2026-03-09T00:00:00-04:00",+ "2026-03-10T00:00:00-04:00",+ "2026-03-11T00:00:00-04:00",+ ],+ ),+ ("month", "UTC", ["2026-01-01", "2026-02-01", "2026-03-01", "2026-04-01", "2026-05-01"]),+ ("day", "UTC", ["2026-01-08", "2026-01-09", "2026-01-12", "2026-01-13", "2026-01-14"], "2026-01-10"),+ (+ "day",+ "America/New_York",+ [+ "2026-03-06T00:00:00-05:00",+ "2026-03-08T00:00:00-05:00",+ "2026-03-10T00:00:00-04:00",+ "2026-03-11T00:00:00-04:00",+ "2026-03-12T00:00:00-04:00",+ ],+ "2026-03-09T00:00:00-04:00",+ ),+ ]+ )+ def test_delay_uses_query_bucket_boundaries(+ self, interval: str, timezone: str, dates: list[str], expected_end: str | None = None+ ) -> None:+ self.query["interval"] = interval+ self.team.timezone = timezone+ result = self.evaluate([40.0, 42.0, 0.0, 0.0, 0.0], dates)+ assert result.triggered_metadata is not None+ self.assertEqual(result.triggered_metadata["evaluated_interval_start"], dates[1])+ self.assertEqual(result.triggered_metadata["evaluated_interval_end"], expected_end or dates[2])++ @parameterized.expand([(-1,), (101,), (1.5,), (True,), (None,)])+ def test_invalid_delay_rejected_before_query(self, delay: object) -> None:+ for serializer_type in (AlertSerializer, AlertSimulateSerializer):+ serializer = serializer_type(data={"evaluation_delay_intervals": delay}, partial=True)+ self.assertFalse(serializer.is_valid())+ self.assertIn("evaluation_delay_intervals", serializer.errors)++ def test_simulate_validation_upgrades_stored_series_without_kind(self) -> None:+ self.insight.query = {**self.query, "series": [{"event": "order completed"}]}+ attrs = {"insight": self.insight, "config": None, "evaluation_delay_intervals": 2}+ self.assertEqual(AlertSimulateSerializer().validate(attrs), attrs)++ @parameterized.expand(+ [+ ({"kind": "HogQLQuery", "query": "SELECT 1"}, {}, "time-series Trends"),+ ({"kind": "FunnelsQuery", "series": []}, {}, "time-series Trends"),+ (+ {"kind": "TrendsQuery", "series": [], "trendsFilter": {"display": "BoldNumber"}},+ {},+ "time-series Trends",+ ),+ (+ {"kind": "TrendsQuery", "series": [], "trendsFilter": {"display": "CalendarHeatmap"}},+ {},+ "time-series Trends",+ ),+ (+ {+ "kind": "TrendsQuery",+ "series": [],+ "breakdownFilter": {"breakdown": "$browser", "breakdown_type": "event"},+ "compareFilter": {"compare": True},+ },+ {},+ "compare to a previous period",+ ),+ (+ {"kind": "TrendsQuery", "series": [], "dateRange": {"daysOfWeek": [1, 2, 3, 4, 5]}},+ {},+ "filter days of the week",+ ),+ ({"kind": "TrendsQuery", "series": []}, {"check_ongoing_interval": True}, "Turn off"),+ ({"kind": "TrendsQuery", "series": []}, '{"type": "TrendsAlertConfig"}', "JSON object"),+ ({"kind": "TrendsQuery", "series": []}, [1], "JSON object"),+ ]+ )+ def test_unsupported_delay_configuration(self, query: dict, config: object, message: str) -> None:+ validate_evaluation_delay(query, config, 0)+ with self.assertRaisesRegex(ValueError, message):+ validate_evaluation_delay(query, config, 1)diff --git a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.pyindex bd57677fa96e..750145bc1f8c 100644--- a/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py+++ b/products/alerts/backend/evaluation/test/test_high_frequency_freshness.py@@ -46,6 +46,7 @@ def _day_query() -> TrendsQuery:def _trends_alert(*, high_frequency: bool) -> MagicMock:alert = MagicMock(spec=AlertConfiguration)+ alert.evaluation_delay_intervals = 0alert.team = MagicMock()alert.config = {"type": "TrendsAlertConfig", "series_index": 0}alert.condition = AlertCondition(type=AlertConditionType.ABSOLUTE_VALUE).model_dump()diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.pyindex 0f54c07ca89a..fec3980b2732 100644--- a/products/alerts/backend/evaluation/trends.py+++ b/products/alerts/backend/evaluation/trends.py@@ -33,6 +33,7 @@ from products.alerts.backend.evaluation.contract import (lookback_intervals_for,zero_sentinel_series,)+from products.alerts.backend.evaluation.delay import apply_evaluation_delayfrom products.alerts.backend.evaluation.formatting import make_trends_value_formatterfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.product_analytics.backend.facade.models import Insight@@ -79,7 +80,8 @@ class TrendsExtractor:"check_ongoing_interval is not supported when the insight excludes incomplete periods ""(DateRange.excludeIncompletePeriods): the ongoing interval is clipped from the query results")- lookback_intervals = lookback_intervals_for(condition)+ delay = alert.evaluation_delay_intervals+ lookback_intervals = lookback_intervals_for(condition) + delayinterval_type = None if is_non_time_series else query.intervalmatch condition.type:@@ -151,11 +153,16 @@ class TrendsExtractor:is_current_interval=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,- value_formatter=value_formatter,+ return apply_evaluation_delay(+ ExtractionResult(+ series=series,+ is_breakdown=has_breakdown,+ interval_type=interval_type,+ value_formatter=value_formatter,+ ),+ delay=delay,+ minimum_points=1 if condition.type == AlertConditionType.ABSOLUTE_VALUE else 2,+ timezone=alert.team.timezone,)def _calculate(@@ -190,10 +197,12 @@ class TrendsExtractor:if calculation_result.result is None:raise RuntimeError(f"No results found for insight with alert id = {alert.id}")if not calculation_result.result:+ # The window includes the delayed interval, so no rows still means that interval is zero.return ExtractionResult(series=[zero_sentinel_series()],is_breakdown=has_breakdown,interval_type=interval_type,+ framed=not alert.evaluation_delay_intervals,empty_query_result=True,value_formatter=value_formatter,)diff --git a/products/alerts/backend/facade/evaluation.py b/products/alerts/backend/facade/evaluation.pyindex 17cb857c8f24..7a4f5d272656 100644--- a/products/alerts/backend/facade/evaluation.py+++ b/products/alerts/backend/facade/evaluation.py@@ -3,9 +3,18 @@`evaluate_threshold` is the one place that decides whether a value is out of bounds, so an adopterthat compares a measured number against a threshold (a signals report check, for instance) words abreach the same way an insight alert does. The series types are the input shape it expects.+The evaluation delay check is here so the alert API can reject a delay the check cannot apply."""from products.alerts.backend.evaluation.comparator import evaluate_thresholdfrom products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult, SeriesPoint+from products.alerts.backend.evaluation.delay import DelayedEvaluationUnavailable, validate_evaluation_delay-__all__ = ["ComparableSeries", "ExtractionResult", "SeriesPoint", "evaluate_threshold"]+__all__ = [+ "ComparableSeries",+ "DelayedEvaluationUnavailable",+ "ExtractionResult",+ "SeriesPoint",+ "evaluate_threshold",+ "validate_evaluation_delay",+]diff --git a/products/alerts/backend/migrations/0010_alertconfiguration_evaluation_delay_intervals.py b/products/alerts/backend/migrations/0010_alertconfiguration_evaluation_delay_intervals.pynew file mode 100644index 000000000000..a9fbdec70e47--- /dev/null+++ b/products/alerts/backend/migrations/0010_alertconfiguration_evaluation_delay_intervals.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-09-29 13:06++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts", "0009_redact_webhook_urls_in_destination_names"),+ ]++ operations = [+ migrations.AddField(+ model_name="alertconfiguration",+ name="evaluation_delay_intervals",+ field=models.PositiveSmallIntegerField(db_default=0, default=0),+ ),+ ]diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txtindex 4d2167e651cb..0fae3069f5e3 100644--- a/products/alerts/backend/migrations/max_migration.txt+++ b/products/alerts/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_redact_webhook_urls_in_destination_names+0010_alertconfiguration_evaluation_delay_intervalsdiff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex 2e1c2d9c3282..d063dae286b6 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -124,6 +124,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):# insight specific config for the alertconfig = models.JSONField(default=dict, null=True, blank=True)+ evaluation_delay_intervals = models.PositiveSmallIntegerField(default=0, db_default=0)# how often to recalculate the alertCALCULATION_INTERVAL_CHOICES = [@@ -270,6 +271,7 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):"config_type": alert_config.get("type"),"trends_series_index": alert_config.get("series_index"),"trends_check_ongoing_interval": alert_config.get("check_ongoing_interval"),+ "evaluation_delay_intervals": self.evaluation_delay_intervals,"hogql_evaluation": (alert_config.get("evaluation") or "last_row") if is_hogql_config else None,"hogql_has_explicit_column": bool(alert_config.get("column")) if is_hogql_config else None,"hogql_has_label_column": bool(alert_config.get("label_column")) if is_hogql_config else None,diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex ed716aa709f7..a80e80a2cc6a 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -106,6 +106,7 @@ from products.alerts.backend.facade.destinations import (soft_delete_alert_destinations,validate_destination_data,)+from products.alerts.backend.facade.evaluation import DelayedEvaluationUnavailable, validate_evaluation_delayfrom products.alerts.backend.facade.scheduling import validate_and_normalize_schedule_start_timefrom products.alerts.backend.insight_alert_state_machine import (apply_disable,@@ -633,6 +634,14 @@ class RelativeDateTimeField(serializers.DateTimeField):class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):+ evaluation_delay_intervals = serializers.IntegerField(+ min_value=0,+ max_value=100,+ required=False,+ help_text="Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). "+ "Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, "+ "not the check frequency. Allows late data to arrive, but also delays detection of real problems.",+ )created_by = UserBasicSerializer(read_only=True)checks = AlertCheckSerializer(many=True,@@ -805,6 +814,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize"checks_total","config","detector_config",+ "evaluation_delay_intervals","calculation_interval","snoozed_until","skip_weekend",@@ -966,7 +976,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializeevaluation_changed = conditions_or_threshold_changed or any(validated_data.get(field, getattr(instance, field)) != getattr(instance, field)- for field in ("condition", "config", "skip_weekend", "detector_config")+ for field in ("condition", "config", "skip_weekend", "detector_config", "evaluation_delay_intervals"))calculation_interval_changed = ("calculation_interval" in validated_data@@ -1101,7 +1111,10 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize# Mirror the UI's default for cadences finer than the insight interval. Applied before# validate_alert_config so the validated config is the persisted config.- if isinstance(config, dict) and config.get("check_ongoing_interval") is None:+ evaluation_delay = attrs.get(+ "evaluation_delay_intervals", self.instance.evaluation_delay_intervals if self.instance else 0+ )+ if not evaluation_delay and isinstance(config, dict) and config.get("check_ongoing_interval") is None:if should_default_check_ongoing_interval(query=query,config=config,@@ -1115,6 +1128,7 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializerequest_user = self.context["request"].usercreating_user = request_user if isinstance(request_user, User) else Nonetry:+ validate_evaluation_delay(query, config, evaluation_delay)validate_alert_insight_query(query,team=self.context["get_team"](),@@ -1208,6 +1222,13 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializeclass AlertSimulateSerializer(serializers.Serializer):+ evaluation_delay_intervals = serializers.IntegerField(+ min_value=0,+ max_value=100,+ default=0,+ help_text="Skip this many completed insight intervals before simulation, matching live evaluation. "+ "Time-series Trends only; a positive delay requires check_ongoing_interval=false.",+ )insight = TeamScopedInsightReferenceField(queryset=Insight.objects.all(),help_text="Numeric insight ID or saved insight short ID to simulate the detector on.",@@ -1256,6 +1277,15 @@ class AlertSimulateSerializer(serializers.Serializer):_enforce_alert_feature_flags(self.context, value)return value+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ with upgrade_insight(attrs["insight"]):+ query = attrs["insight"].query+ try:+ validate_evaluation_delay(query, attrs.get("config"), attrs["evaluation_delay_intervals"])+ except ValueError as err:+ raise ValidationError({"evaluation_delay_intervals": [str(err)]}) from err+ return attrs+def validate_detector_config(self, value):# Same gate as create/update: previewing a flag-gated detector must be rejected the# same way saving one is, or the preview becomes the way to use it.@@ -1287,6 +1317,12 @@ class BreakdownSimulationResultSerializer(serializers.Serializer):class AlertSimulateResponseSerializer(serializers.Serializer):+ evaluation_delay_intervals = serializers.IntegerField(required=False, help_text="Completed intervals skipped.")+ evaluated_interval_start = serializers.CharField(required=False, help_text="Start of the latest eligible interval.")+ evaluated_interval_end = serializers.CharField(+ required=False, help_text="Exclusive end of the latest eligible interval."+ )+ evaluated_interval_timezone = serializers.CharField(required=False, help_text="Project timezone of the interval.")data = serializers.ListField(child=serializers.FloatField(), help_text="Data values for each point.") # type: ignore[assignment]dates = serializers.ListField(child=serializers.CharField(), help_text="Date labels for each point.")scores = serializers.ListField(@@ -1843,8 +1879,9 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):user=cast(User, request.user),config=config,is_agent_billable=not is_impersonated(request),+ evaluation_delay_intervals=serializer.validated_data["evaluation_delay_intervals"],)- except (ValueError, IndexError, AlertExtractionError) as e:+ except (ValueError, IndexError, AlertExtractionError, DelayedEvaluationUnavailable) as e:raise ValidationError(str(e))except LLMDetectorError as e:capture_exception(e)diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 751360bb7deb..e850d7c9e49e 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -57,6 +57,49 @@ class TrendsInsightAPITest(APIBaseTest):class TestAlert(TrendsInsightAPITest, QueryMatchingTest):+ def test_evaluation_delay_persists_and_patch_rejects_conflicts(self) -> None:+ insight = self.create_trends_insight(interval="hour")+ response = self.client.post(+ f"/api/projects/{self.team.id}/alerts",+ {+ "insight": insight["id"],+ "name": "Delayed orders",+ "subscribed_users": [],+ "config": {"type": "TrendsAlertConfig", "series_index": 0},+ "condition": {"type": "absolute_value"},+ "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 100}}},+ "calculation_interval": "hourly",+ "evaluation_delay_intervals": 2,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content+ alert_id = response.json()["id"]+ assert response.json()["evaluation_delay_intervals"] == 2+ url = f"/api/projects/{self.team.id}/alerts/{alert_id}"+ scheduled_check = datetime.now(UTC) + timedelta(days=20)+ AlertConfiguration.objects.filter(id=alert_id).update(state=AlertState.FIRING, next_check_at=scheduled_check)+ changed = self.client.patch(url, {"name": "Delayed completed orders"}, format="json")+ assert changed.status_code == status.HTTP_200_OK, changed.content+ assert changed.json()["evaluation_delay_intervals"] == 2+ renamed = AlertConfiguration.objects.get(id=alert_id)+ assert renamed.state == AlertState.FIRING+ assert renamed.next_check_at == scheduled_check+ for patch_data in (+ {"config": {"type": "TrendsAlertConfig", "series_index": 0, "check_ongoing_interval": True}},+ {"insight": self.insight["id"]},+ {"evaluation_delay_intervals": -1},+ ):+ invalid = self.client.patch(url, patch_data, format="json")+ assert invalid.status_code == status.HTTP_400_BAD_REQUEST, invalid.content+ assert AlertConfiguration.objects.get(id=alert_id).evaluation_delay_intervals == 2+ delayed = self.client.patch(url, {"evaluation_delay_intervals": 3}, format="json")+ assert delayed.status_code == status.HTTP_200_OK, delayed.content+ saved = AlertConfiguration.objects.get(id=alert_id)+ assert saved.state == AlertState.NOT_FIRING+ assert saved.next_check_at is not None+ assert saved.next_check_at <= datetime.now(UTC)+def setUp(self):super().setUp()self.default_insight_data: dict[str, Any] = {@@ -95,6 +138,7 @@ class TestAlert(TrendsInsightAPITest, QueryMatchingTest):"state": "Not firing","config": {"type": "TrendsAlertConfig", "series_index": 0},"detector_config": None,+ "evaluation_delay_intervals": 0,"threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}},"created_at": mock.ANY,diff --git a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsxindex 2fc5d35611eb..7d0af4375d03 100644--- a/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx+++ b/products/alerts/frontend/components/AlertAdvancedOptionsSection.tsx@@ -1,7 +1,7 @@import { Group } from 'kea-forms'import { IconInfo } from '@posthog/icons'-import { LemonCheckbox, Tooltip } from '@posthog/lemon-ui'+import { LemonCheckbox, LemonInput, Tooltip } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'@@ -24,6 +24,9 @@ export interface AlertAdvancedOptionsSectionProps {canCheckOngoingInterval: booleanprojectTimezone: stringenabledAdvancedOptionsCount: number+ evaluationDelayInterval?: string+ evaluationDelayPreview?: string+ evaluationDelayUnsupportedReason?: stringdefaultOpen?: booleanonSetAlertFormValue: <K extends keyof AlertFormType>(key: K, value: AlertFormType[K]) => void}@@ -33,6 +36,9 @@ export function AlertAdvancedOptionsSection({canCheckOngoingInterval,projectTimezone,enabledAdvancedOptionsCount,+ evaluationDelayInterval,+ evaluationDelayPreview,+ evaluationDelayUnsupportedReason,defaultOpen,onSetAlertFormValue,}: AlertAdvancedOptionsSectionProps): JSX.Element {@@ -50,6 +56,52 @@ export function AlertAdvancedOptionsSection({onChange={(next) => onSetAlertFormValue('schedule_restriction', next)}/><AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount} defaultOpen={defaultOpen}>+ {evaluationDelayInterval ? (+ <LemonField name="evaluation_delay_intervals" label="Evaluation delay">+ {() => (+ <div className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <LemonInput+ type="number"+ min={0}+ max={100}+ step={1}+ value={alertForm.evaluation_delay_intervals ?? 0}+ onChange={(value) =>+ onSetAlertFormValue(+ 'evaluation_delay_intervals',+ typeof value === 'number' && Number.isFinite(value) ? value : 0+ )+ }+ className="w-24"+ data-attr="alert-evaluation-delay"+ aria-label="Evaluation delay"+ disabledReason={+ ongoing.checked+ ? 'Turn off Check ongoing period to use an evaluation delay.'+ : undefined+ }+ />+ <span>{`completed ${evaluationDelayInterval} intervals`}</span>+ </div>+ <p className="text-sm text-secondary mb-0">+ Skip recent completed intervals to allow late data to arrive. This also delays+ detection of real problems and does not guarantee that a data sync has finished.+ Uses the insight interval; the check schedule stays the same.+ </p>+ {evaluationDelayUnsupportedReason ? (+ <p className="text-sm text-danger mb-0">{evaluationDelayUnsupportedReason}</p>+ ) : !ongoing.checked && evaluationDelayPreview ? (+ <p className="text-sm text-secondary mb-0">+ <span>If checked now: </span>+ <span>{evaluationDelayPreview}</span>+ <span>{` (${projectTimezone}).`}</span>+ </p>+ ) : null}+ </div>+ )}+ </LemonField>+ ) : null}{ongoing.show ? (<Group name={['config']}><div className="flex gap-1">@@ -59,7 +111,12 @@ export function AlertAdvancedOptionsSection({data-attr="alertForm-check-ongoing-interval"fullWidthlabel="Check ongoing period"- disabledReason={ongoing.disabledReason}+ disabledReason={+ ongoing.disabledReason ??+ ((alertForm.evaluation_delay_intervals ?? 0) > 0+ ? 'Set Evaluation delay to 0 to check the ongoing period.'+ : undefined)+ }/></LemonField><Tooltip title={ongoing.tooltip} placement="right" delayMs={0}>diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsxindex c15f4eda7568..1cdaed504e06 100644--- a/products/alerts/frontend/components/AlertComponents.stories.tsx+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx@@ -416,6 +416,20 @@ function PreviewStory(): JSX.Element {)}+function PreviewDelayHistoryTooShortStory(): JSX.Element {+ return (+ <div className="max-w-md border rounded bg-surface-primary p-4">+ <AlertPreviewCard+ alertForm={buildTrendsAlertForm({ evaluation_delay_intervals: 10 })}+ trendsValues={[]}+ funnelPreview={null}+ hogqlPreview={null}+ previewHistoryTooShort+ />+ </div>+ )+}+function PreviewRelativeStory(): JSX.Element {return (<div className="max-w-md border rounded bg-surface-primary p-4">@@ -499,6 +513,7 @@ export const NotificationsMultipleSlackWorkspaces: Story = { render: () => <Multexport const QuietHours: Story = { render: () => <QuietHoursStory /> }export const EvaluationHistory: Story = { render: () => <EvaluationHistoryStory /> }export const Preview: Story = { render: () => <PreviewStory /> }+export const PreviewDelayHistoryTooShort: Story = { render: () => <PreviewDelayHistoryTooShortStory /> }export const PreviewRelative: Story = { render: () => <PreviewRelativeStory /> }export const PreviewLogScale: Story = { render: () => <PreviewLogScaleStory /> }export const PreviewBreakdown: Story = { render: () => <PreviewBreakdownStory /> }diff --git a/products/alerts/frontend/components/AlertPreviewCard.test.tsx b/products/alerts/frontend/components/AlertPreviewCard.test.tsxindex aa32bcd469e0..6385804c8ff6 100644--- a/products/alerts/frontend/components/AlertPreviewCard.test.tsx+++ b/products/alerts/frontend/components/AlertPreviewCard.test.tsx@@ -52,4 +52,22 @@ describe('AlertPreviewCard', () => {expect(within(container).queryByText(EMPTY_BREAKDOWN_TEXT)).toBeNull()})++ it.each([false, true])('explains when the delayed %s preview runs out of loaded history', (isBreakdown) => {+ const { container } = render(+ <AlertPreviewCard+ alertForm={alertForm}+ trendsValues={[]}+ isBreakdown={isBreakdown}+ trendsBreakdownSeries={isBreakdown ? [{ key: 'chrome', label: 'Chrome', data: [] }] : undefined}+ funnelPreview={null}+ hogqlPreview={null}+ previewHistoryTooShort+ />+ )++ expect(within(container).getByText(/date range is too short to preview this delay/)).toBeTruthy()+ expect(within(container).queryByText(EMPTY_BREAKDOWN_TEXT)).toBeNull()+ expect(within(container).queryByText('No insight data available to preview.')).toBeNull()+ })})diff --git a/products/alerts/frontend/components/AlertPreviewCard.tsx b/products/alerts/frontend/components/AlertPreviewCard.tsxindex 26adf22e0a4b..f385eba71e6b 100644--- a/products/alerts/frontend/components/AlertPreviewCard.tsx+++ b/products/alerts/frontend/components/AlertPreviewCard.tsx@@ -75,6 +75,7 @@ export interface AlertPreviewCardProps {funnelPreview: FunnelAlertPreview | nullhogqlPreview: HogQLAlertPreview | nullcheckPreview?: TrendsAlertPreviewSeries+ previewHistoryTooShort?: boolean// Keeps the card visible with a skeleton while data loads instead of popping in once it arrives.loading?: boolean}@@ -88,6 +89,7 @@ export function AlertPreviewCard({funnelPreview,hogqlPreview,checkPreview,+ previewHistoryTooShort,loading,}: AlertPreviewCardProps): JSX.Element {const config = alertForm.config@@ -130,6 +132,12 @@ export function AlertPreviewCard({Set less than or more than to preview this alert.</div>)+ } else if (previewHistoryTooShort && !loading) {+ body = (+ <div className="flex h-24 items-center justify-center rounded border border-dashed border-border text-sm text-muted">+ The insight's date range is too short to preview this delay. The alert loads more history when it runs.+ </div>+ )} else if (isBreakdownPreview && breakdownPreview && breakdownPreviewValues.length > 0) {body = (<AlertPreviewChartdiff --git a/products/alerts/frontend/components/AlertSimulationSection.tsx b/products/alerts/frontend/components/AlertSimulationSection.tsxindex 655a4b9a327c..d12f61532d7f 100644--- a/products/alerts/frontend/components/AlertSimulationSection.tsx+++ b/products/alerts/frontend/components/AlertSimulationSection.tsx@@ -26,7 +26,7 @@ export function AlertSimulationSection({}: AlertSimulationSectionProps): JSX.Element {return (<div className="deprecated-space-y-2">- <div className="flex gap-2 items-center">+ <div className="flex flex-wrap gap-2 items-center"><h4 className="m-0">Simulation</h4><LemonSelectsize="small"@@ -46,6 +46,11 @@ export function AlertSimulationSection({Simulate</LemonButton></div>+ {simulationResult?.evaluated_interval_start && simulationResult.evaluated_interval_end ? (+ <p className="text-sm text-secondary">+ {`Latest evaluated interval: ${simulationResult.evaluated_interval_start} to ${simulationResult.evaluated_interval_end} (${simulationResult.evaluated_interval_timezone}; delay: ${simulationResult.evaluation_delay_intervals} intervals).`}+ </p>+ ) : null}{simulationResult && alertForm.detector_config && (<SimulationSummary result={simulationResult} detectorConfig={alertForm.detector_config} />)}diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.tsindex affb65ae0ded..970f5c683b35 100644--- a/products/alerts/frontend/generated/api.schemas.ts+++ b/products/alerts/frontend/generated/api.schemas.ts@@ -696,6 +696,12 @@ export interface AlertApi {/** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */config?: AlertConfigUnionApi | nulldetector_config?: DetectorConfigApi | null+ /**+ * Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number/** How often the alert is checked: real time (Scale+), every 15 minutes (Boost+), hourly, daily, weekly, or monthly.** * `real_time` - real_time@@ -795,6 +801,12 @@ export interface PatchedAlertApi {/** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */config?: AlertConfigUnionApi | nulldetector_config?: DetectorConfigApi | null+ /**+ * Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number/** How often the alert is checked: real time (Scale+), every 15 minutes (Boost+), hourly, daily, weekly, or monthly.** * `real_time` - real_time@@ -892,6 +904,12 @@ export interface AlertTestDeliveryResponseApi {}export interface AlertSimulateApi {+ /**+ * Skip this many completed insight intervals before simulation, matching live evaluation. Time-series Trends only; a positive delay requires check_ongoing_interval=false.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number/** Numeric insight ID or saved insight short ID to simulate the detector on. */insight: number | string/** Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). */@@ -933,6 +951,14 @@ export interface BreakdownSimulationResultApi {}export interface AlertSimulateResponseApi {+ /** Completed intervals skipped. */+ evaluation_delay_intervals?: number+ /** Start of the latest eligible interval. */+ evaluated_interval_start?: string+ /** Exclusive end of the latest eligible interval. */+ evaluated_interval_end?: string+ /** Project timezone of the interval. */+ evaluated_interval_timezone?: string/** Data values for each point. */data: number[]/** Date labels for each point. */diff --git a/products/alerts/frontend/generated/api.zod.ts b/products/alerts/frontend/generated/api.zod.tsindex cbfe5fa53e60..11914dc7f1de 100644--- a/products/alerts/frontend/generated/api.zod.ts+++ b/products/alerts/frontend/generated/api.zod.ts@@ -58,6 +58,10 @@ export const AlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({/*** Simulate a detector on an insight's historical data. No AlertCheck records are created. The AI detector makes a real model call, so that mode needs the 'alert:write' scope.*/+export const alertsSimulateCreateBodyEvaluationDelayIntervalsDefault = 0+export const alertsSimulateCreateBodyEvaluationDelayIntervalsMin = 0+export const alertsSimulateCreateBodyEvaluationDelayIntervalsMax = 100+export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`@@ -99,6 +103,14 @@ export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertCoexport const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`export const AlertsSimulateCreateBody = /* @__PURE__ */ zod.object({+ evaluation_delay_intervals: zod+ .number()+ .min(alertsSimulateCreateBodyEvaluationDelayIntervalsMin)+ .max(alertsSimulateCreateBodyEvaluationDelayIntervalsMax)+ .default(alertsSimulateCreateBodyEvaluationDelayIntervalsDefault)+ .describe(+ 'Skip this many completed insight intervals before simulation, matching live evaluation. Time-series Trends only; a positive delay requires check_ongoing_interval=false.'+ ),insight: zod.union([zod.number(), zod.string()]).describe('Numeric insight ID or saved insight short ID to simulate the detector on.'),diff --git a/products/alerts/frontend/logic/alertFormLogic.test.ts b/products/alerts/frontend/logic/alertFormLogic.test.tsindex 1842f1fc4b7f..a45bdfe79343 100644--- a/products/alerts/frontend/logic/alertFormLogic.test.ts+++ b/products/alerts/frontend/logic/alertFormLogic.test.ts@@ -28,6 +28,7 @@ import type { AlertType } from '../types'import {alertFormLogic,canCheckOngoingInterval,+ evaluationDelayField,ongoingIntervalField,thresholdAlertHasBounds,type AlertFormType,@@ -202,6 +203,10 @@ describe('alertFormLogic', () => {)it.each([+ [+ 'delayed',+ (logic: ReturnType<typeof mountForm>) => logic.actions.setAlertFormValue('evaluation_delay_intervals', 2),+ ],['cleared', (logic: ReturnType<typeof mountForm>) => logic.actions.clearSimulation()],['run over another range', (logic: ReturnType<typeof mountForm>) => logic.actions.setSimulationDateFrom('-7d')],[@@ -1110,6 +1115,17 @@ describe('alertFormLogic', () => {})})+ it.each([+ ['time-series trends', 'trends', false, 0, true, false],+ ['non-time-series trends with no saved delay', 'trends', true, 0, false, true],+ ['non-time-series trends with a saved delay', 'trends', true, 2, true, true],+ ['funnels with a saved delay', 'funnels', false, 2, true, true],+ ] as const)('evaluationDelayField: %s', (_name, kind, isNonTimeSeriesDisplay, savedDelay, show, unsupported) => {+ const field = evaluationDelayField(kind, isNonTimeSeriesDisplay, savedDelay)+ expect(field.show).toBe(show)+ expect(field.unsupportedReason !== undefined).toBe(unsupported)+ })+describe('ongoing-interval gating', () => {const funnelConfig = { type: 'FunnelsAlertConfig', metric: 'conversion_from_start', funnel_step: null }const trendsAbsoluteWithUpper = (condition: AlertConditionType): any => ({diff --git a/products/alerts/frontend/logic/alertFormLogic.ts b/products/alerts/frontend/logic/alertFormLogic.tsindex 0d848e40aa69..2ac11c71777e 100644--- a/products/alerts/frontend/logic/alertFormLogic.ts+++ b/products/alerts/frontend/logic/alertFormLogic.ts@@ -44,7 +44,7 @@ import {isTrendsAlertConfig,supportsOngoingInterval,} from '../types'-import { getAlertFormValidationErrors } from './alertFormSchema'+import { canCheckOngoingInterval, getAlertFormValidationErrors } from './alertFormSchema'import { alertLogic } from './alertLogic'import { alertNotificationLogic } from './alertNotificationLogic'import { getDefaultAnomalyDetectorConfig } from './detectorConfigDefaults'@@ -52,7 +52,7 @@ import { deriveFunnelAlertPreview, FunnelAlertPreview } from './funnelAlertPreviimport { columnIsNumeric, deriveHogQLAlertPreview, HogQLAlertPreview } from './hogqlAlertPreview'import { insightAlertsLogic } from './insightAlertsLogic'-export { THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'+export { canCheckOngoingInterval, THRESHOLD_BOUNDS_FORM_ERROR, thresholdAlertHasBounds } from './alertFormSchema'export type AlertFormType = Pick<AlertType,@@ -69,6 +69,7 @@ export type AlertFormType = Pick<| 'schedule_restriction'| 'schedule_start_time'| 'detector_config'+ | 'evaluation_delay_intervals'| 'investigation_agent_enabled'| 'investigation_gates_notifications'| 'investigation_inconclusive_action'@@ -78,25 +79,6 @@ export type AlertFormType = Pick<insight?: InsightModel['id']}-export function canCheckOngoingInterval(- alert?: AlertType | AlertFormType,- { isTrendsFunnel = false }: { isTrendsFunnel?: boolean } = {}-): boolean {- // A funnel conversion rate isn't biased low over a partial period, so a trends funnel can always- // check the ongoing one (steps funnels have no periods). A trends count is cumulative, so it's only- // safe for an absolute/increase check above an upper bound.- if (isFunnelsAlertConfig(alert?.config)) {- return isTrendsFunnel- }- const upper = alert?.threshold?.configuration?.bounds?.upper- return (- (alert?.condition?.type === AlertConditionType.ABSOLUTE_VALUE ||- alert?.condition?.type === AlertConditionType.RELATIVE_INCREASE) &&- upper != null &&- !isNaN(upper)- )-}-const ONGOING_DISABLED_REASON ='Can only alert for ongoing period when checking for absolute value/increase above a set upper threshold.'const ONGOING_TOOLTIP_FUNNEL =@@ -142,6 +124,28 @@ export function insightAlertKindForQuery(query?: Record<string, any> | null): Inreturn 'trends'}+const EVALUATION_DELAY_UNSUPPORTED_REASON =+ "This insight doesn't support an evaluation delay. Set it to 0 to save the alert."++export interface EvaluationDelayField {+ show: boolean+ unsupportedReason?: string+}++/** A saved delay stays editable after its insight stops supporting one, because the API+ * rejects every save of that alert until the delay is 0. */+export function evaluationDelayField(+ insightAlertKind: InsightAlertKind,+ isNonTimeSeriesDisplay: boolean,+ savedDelay: number+): EvaluationDelayField {+ const supported = insightAlertKind === 'trends' && !isNonTimeSeriesDisplay+ return {+ show: supported || savedDelay > 0,+ unsupportedReason: supported ? undefined : EVALUATION_DELAY_UNSUPPORTED_REASON,+ }+}+export interface AlertFormLogicProps {alert: AlertType | nullinsightId: InsightModel['id']@@ -537,6 +541,7 @@ export const alertFormLogic = kea<alertFormLogicType>([// SQL insights have no series_index; the config carries the evaluated column// and read direction so the preview matches what the alert will score.config: formConfig,+ evaluation_delay_intervals: values.alertForm.evaluation_delay_intervals ?? 0,})) as AlertSimulationResult} catch (error) {if (values.simulationRequestId === requestId) {@@ -569,6 +574,7 @@ export const alertFormLogic = kea<alertFormLogicType>([created_by: null,created_at: '',enabled: true,+ evaluation_delay_intervals: 0,config: defaultConfigForInsight(props.insightAlertKind),threshold: {configuration: {@@ -978,6 +984,7 @@ export const alertFormLogic = kea<alertFormLogicType>([: simulationResult.anomaly_countposthog.capture('alert simulation run', {success: true,+ evaluation_delay_intervals: values.alertForm.evaluation_delay_intervals ?? 0,detector_type: detectorConfig?.type ?? null,ensemble_operator: detectorConfig?.type === 'ensemble' ? detectorConfig.operator : null,date_from:@@ -1028,7 +1035,7 @@ export const alertFormLogic = kea<alertFormLogicType>([const field = Array.isArray(name) ? name[0] : name// The evaluated series or column, and the detector settings, are inputs to the// preview, so an edit to either leaves nothing the chart can honestly show.- if (field === 'config' || field === 'detector_config') {+ if (field === 'config' || field === 'detector_config' || field === 'evaluation_delay_intervals') {discardSimulation()}},diff --git a/products/alerts/frontend/logic/alertFormSchema.test.ts b/products/alerts/frontend/logic/alertFormSchema.test.tsindex 9074168ca1f7..c8a1b404cb35 100644--- a/products/alerts/frontend/logic/alertFormSchema.test.ts+++ b/products/alerts/frontend/logic/alertFormSchema.test.ts@@ -39,6 +39,28 @@ describe('alertFormSchema', () => {expect(getAlertFormValidationErrors(baseAlert)).toEqual({})})+ test.each([-1, 101, 1.5])('rejects evaluation delay %s', (delay) => {+ expect(+ getAlertFormValidationErrors({ ...baseAlert, evaluation_delay_intervals: delay }).evaluation_delay_intervals+ ).toBeTruthy()+ })++ test.each([+ ['rejects', AlertConditionType.ABSOLUTE_VALUE, { upper: 100 }, true],+ ['allows a stale flag on', AlertConditionType.RELATIVE_DECREASE, { upper: 100 }, false],+ ['allows a stale flag on', AlertConditionType.ABSOLUTE_VALUE, { lower: 5 }, false],+ ])('%s the ongoing interval with a delay on %s %o', (_, conditionType, bounds, rejected) => {+ expect(+ !!getAlertFormValidationErrors({+ ...baseAlert,+ evaluation_delay_intervals: 2,+ condition: { type: conditionType },+ threshold: { configuration: { type: InsightThresholdType.ABSOLUTE, bounds } },+ config: { type: 'TrendsAlertConfig', series_index: 0, check_ongoing_interval: true },+ }).evaluation_delay_intervals+ ).toBe(rejected)+ })+it('requires a name', () => {expect(getAlertFormValidationErrors({ ...baseAlert, name: '' }).name).toBe('You need to give your alert a name')})diff --git a/products/alerts/frontend/logic/alertFormSchema.ts b/products/alerts/frontend/logic/alertFormSchema.tsindex 79fa0ce0dbcc..c85e246e3d4f 100644--- a/products/alerts/frontend/logic/alertFormSchema.ts+++ b/products/alerts/frontend/logic/alertFormSchema.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import { AlertConditionType } from '~/queries/schema/schema-general'-import type { AlertType } from '../types'+import { AlertType, isFunnelsAlertConfig, isTrendsAlertConfig, supportsOngoingInterval } from '../types'import type { AlertFormType } from './alertFormLogic'import { quietHoursFormError } from './scheduleRestrictionValidation'@@ -27,9 +27,29 @@ export function thresholdAlertHasBounds(alert: AlertFormType | AlertType): boolereturn isFiniteThresholdBound(lower) || isFiniteThresholdBound(upper)}+export function canCheckOngoingInterval(+ alert?: AlertType | AlertFormType,+ { isTrendsFunnel = false }: { isTrendsFunnel?: boolean } = {}+): boolean {+ // A funnel conversion rate isn't biased low over a partial period, so a trends funnel can always+ // check the ongoing one (steps funnels have no periods). A trends count is cumulative, so it's only+ // safe for an absolute/increase check above an upper bound.+ if (isFunnelsAlertConfig(alert?.config)) {+ return isTrendsFunnel+ }+ const upper = alert?.threshold?.configuration?.bounds?.upper+ return (+ (alert?.condition?.type === AlertConditionType.ABSOLUTE_VALUE ||+ alert?.condition?.type === AlertConditionType.RELATIVE_INCREASE) &&+ upper != null &&+ !isNaN(upper)+ )+}+const alertFormSchema = z.object({name: z.string(),+ evaluation_delay_intervals: z.number().int().min(0).max(100).optional(),detector_config: z.unknown().nullable(),condition: z.object({ type: z.nativeEnum(AlertConditionType) }),threshold: z@@ -50,6 +70,20 @@ const alertFormSchema = z}).passthrough().superRefine((alert, ctx) => {+ const config = (alert as AlertFormType).config+ // Submit clears a Trends ongoing-period flag the condition no longer allows, so check that value.+ if (+ (alert.evaluation_delay_intervals ?? 0) > 0 &&+ supportsOngoingInterval(config) &&+ config.check_ongoing_interval &&+ (!isTrendsAlertConfig(config) || canCheckOngoingInterval(alert as AlertFormType))+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['evaluation_delay_intervals'],+ message: 'Turn off Check ongoing period to use an evaluation delay.',+ })+ }if (!alert.name) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['name'], message: NAME_REQUIRED_MESSAGE })}diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.test.ts b/products/alerts/frontend/logic/alertIntervalHelpers.test.tsindex 516f01d3464a..8c665935c8a3 100644--- a/products/alerts/frontend/logic/alertIntervalHelpers.test.ts+++ b/products/alerts/frontend/logic/alertIntervalHelpers.test.ts@@ -1,5 +1,6 @@import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'+import { dayjs } from 'lib/dayjs'import { userLogic } from 'scenes/userLogic'import { AlertCalculationInterval } from '~/queries/schema/schema-general'@@ -7,6 +8,7 @@ import { initKeaTests } from '~/test/init'import { AvailableFeature } from '~/types'import {+ evaluationDelayPreview,canSetAlertScheduleStartTime,getAlertScheduleStartMinute,getDefaultSimulationRange,@@ -21,6 +23,34 @@ describe('alertIntervalHelpers', () => {initKeaTests()})+ test.each([+ ['hour', 0, 'UTC', 0, '2026-09-29T10:30:00Z', 'Sep 29, 2026 09:00 +00:00 to Sep 29, 2026 10:00 +00:00'],+ ['hour', 2, 'UTC', 0, '2026-09-29T10:30:00Z', 'Sep 29, 2026 07:00 +00:00 to Sep 29, 2026 08:00 +00:00'],+ [+ 'day',+ 1,+ 'America/New_York',+ 0,+ '2026-03-10T12:00:00Z',+ 'Mar 8, 2026 00:00 -05:00 to Mar 9, 2026 00:00 -04:00',+ ],+ [+ 'hour',+ 1,+ 'America/New_York',+ 0,+ '2026-11-01T07:30:00Z',+ 'Nov 1, 2026 01:00 -04:00 to Nov 1, 2026 01:00 -05:00',+ ],+ ['month', 1, 'UTC', 0, '2026-03-15T12:00:00Z', 'Jan 1, 2026 00:00 +00:00 to Feb 1, 2026 00:00 +00:00'],+ ['week', 1, 'UTC', 1, '2026-09-29T10:30:00Z', 'Sep 14, 2026 00:00 +00:00 to Sep 21, 2026 00:00 +00:00'],+ ] as const)(+ 'previews the eligible %s interval with delay %s in %s',+ (interval, delay, timezone, weekStart, now, expected) => {+ expect(evaluationDelayPreview(interval, delay, timezone, weekStart, dayjs(now))).toBe(expected)+ }+ )+describe('getDefaultSimulationRange', () => {it.each([[AlertCalculationInterval.REAL_TIME, '-1h'],diff --git a/products/alerts/frontend/logic/alertIntervalHelpers.ts b/products/alerts/frontend/logic/alertIntervalHelpers.tsindex c79daf81ae50..d4417fe38ad9 100644--- a/products/alerts/frontend/logic/alertIntervalHelpers.ts+++ b/products/alerts/frontend/logic/alertIntervalHelpers.ts@@ -1,10 +1,41 @@import posthog from 'posthog-js'import type { GuardAvailableFeatureFn } from 'lib/components/UpgradeModal/upgradeModalLogic'+import { dayjs, Dayjs } from 'lib/dayjs'import { AlertCalculationInterval } from '~/queries/schema/schema-general'import { AvailableFeature, IntervalType } from '~/types'+export function evaluationDelayPreview(+ interval: IntervalType,+ delay: number,+ timezone: string,+ weekStartDay: number = 0,+ now: Dayjs = dayjs()+): string {+ const local = now.tz(timezone)+ let start: Dayjs+ let end: Dayjs+ if (interval === 'hour' || interval === 'minute' || interval === 'second') {+ const boundary = local+ .utc()+ .subtract(interval === 'hour' ? local.minute() : 0, 'minute')+ .subtract(interval !== 'second' ? local.second() : 0, 'second')+ .millisecond(0)+ end = boundary.subtract(delay, interval).tz(timezone)+ start = boundary.subtract(delay + 1, interval).tz(timezone)+ } else {+ const wallClock = dayjs.utc(local.format('YYYY-MM-DDTHH:mm:ss'))+ const boundary =+ interval === 'week'+ ? wallClock.startOf('day').subtract((wallClock.day() - weekStartDay + 7) % 7, 'day')+ : wallClock.startOf(interval)+ start = dayjs.tz(boundary.subtract(delay + 1, interval).format('YYYY-MM-DDTHH:mm:ss'), timezone)+ end = dayjs.tz(boundary.subtract(delay, interval).format('YYYY-MM-DDTHH:mm:ss'), timezone)+ }+ return `${start.format('MMM D, YYYY HH:mm Z')} to ${end.format('MMM D, YYYY HH:mm Z')}`+}+export function getDefaultSimulationRange(interval: AlertCalculationInterval): string {switch (interval) {case AlertCalculationInterval.REAL_TIME:diff --git a/products/alerts/frontend/types.ts b/products/alerts/frontend/types.tsindex 4573c7a827ed..41801e220cdd 100644--- a/products/alerts/frontend/types.ts+++ b/products/alerts/frontend/types.ts@@ -14,7 +14,7 @@ import {} from '~/queries/schema/schema-general'import { InsightModel, UserBasicType } from '~/types'-import type { AlertDeliveryApi } from './generated/api.schemas'+import type { AlertApi, AlertDeliveryApi, AlertSimulateResponseApi } from './generated/api.schemas'export type AlertCheckDelivery = AlertDeliveryApi@@ -82,7 +82,10 @@ export interface BreakdownSimulationResult {sub_detector_scores?: SubDetectorScores[]}-export interface AlertSimulationResult {+export interface AlertSimulationResult extends Pick<+ AlertSimulateResponseApi,+ 'evaluation_delay_intervals' | 'evaluated_interval_start' | 'evaluated_interval_end' | 'evaluated_interval_timezone'+> {data: number[]dates: string[]scores: (number | null)[]@@ -108,7 +111,7 @@ export type AlertThreshold = Omit<InsightThreshold, 'bounds'> & {bounds?: InsightsThresholdBounds | null}-export interface AlertTypeBase {+export interface AlertTypeBase extends Pick<AlertApi, 'evaluation_delay_intervals'> {name: stringcondition: AlertConditionthreshold: { configuration: AlertThreshold }diff --git a/products/alerts/frontend/views/AlertHistorySection.tsx b/products/alerts/frontend/views/AlertHistorySection.tsxindex 6cd8726207af..56c397bbf9ad 100644--- a/products/alerts/frontend/views/AlertHistorySection.tsx+++ b/products/alerts/frontend/views/AlertHistorySection.tsx@@ -157,7 +157,7 @@ export function AlertHistorySection({const showWhyColumn =isLLMDetectorAlert ||alertHistoryChecksSortedDesc.some(- (check) => !!(check.triggered_metadata as { rationale?: string } | null)?.rationale+ (check) => !!check.triggered_metadata?.rationale || !!check.triggered_metadata?.skipped_reason)const checkHistoryColumns = useMemo((): LemonTableColumn<AlertCheck, keyof AlertCheck | undefined>[] => {@@ -165,7 +165,7 @@ export function AlertHistorySection({{title: 'Status',key: 'state',- render: (_value, check) => check.state,+ render: (_value, check) => (check.triggered_metadata?.skipped_reason ? 'Skipped' : check.state),},{title: 'Time',@@ -180,6 +180,17 @@ export function AlertHistorySection({render: (_value, check) => check.calculated_value ?? '—',},]+ if (alertHistoryChecksSortedDesc.some((check) => check.triggered_metadata?.evaluated_interval_start)) {+ columns.push({+ title: 'Evaluated interval',+ render: (_value, check) => {+ const metadata = check.triggered_metadata+ return metadata?.evaluated_interval_start ? (+ <div className="text-sm max-w-xs break-words">{`${metadata.evaluated_interval_start} to ${metadata.evaluated_interval_end} (${metadata.evaluated_interval_timezone}; delay: ${metadata.evaluation_delay_intervals} intervals)`}</div>+ ) : null+ },+ })+ }if (alertHistoryIsAnomalyDetection) {columns.push({title: alertHistoryChartSeriesName === 'Anomaly confidence' ? 'Anomaly confidence' : 'Score',@@ -199,7 +210,8 @@ export function AlertHistorySection({columns.push({title: 'Why',render: (_value, check) => {- const rationale = (check.triggered_metadata as { rationale?: string } | null)?.rationale?.trim()+ const metadata = check.triggered_metadata as { rationale?: string; skipped_reason?: string } | null+ const rationale = (metadata?.skipped_reason ?? metadata?.rationale)?.trim()if (!rationale) {return '—'}@@ -279,6 +291,7 @@ export function AlertHistorySection({isAnyRowSqlAlert,alertHistoryChartSeriesName,showWhyColumn,+ alertHistoryChecksSortedDesc,])if (!alert) {diff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsxindex c2530f95d3fd..adaeab8ffb0d 100644--- a/products/alerts/frontend/views/EditAlertModal.tsx+++ b/products/alerts/frontend/views/EditAlertModal.tsx@@ -15,7 +15,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { AlertCalculationInterval, AlertConditionType, InsightThresholdType } from '~/queries/schema/schema-general'-import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'+import { isFunnelsQuery, isInsightVizNode, isTrendsQuery } from '~/queries/utils'import { FunnelVizType, InsightLogicProps, InsightShortId, InsightModel } from '~/types'import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/AlertAdvancedOptionsSection'@@ -31,13 +31,18 @@ import { AlertPreviewCard } from 'products/alerts/frontend/components/AlertPreviimport { buildAlertSummary } from 'products/alerts/frontend/components/alertSummary'import { AlertWizard } from 'products/alerts/frontend/components/AlertWizard'import { ThresholdConditionRow } from 'products/alerts/frontend/components/ThresholdConditionRow'-import { isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'+import { evaluationDelayPreview, isSubDailyAlertInterval } from 'products/alerts/frontend/logic/alertIntervalHelpers'import { quietHoursFormError } from 'products/alerts/frontend/logic/scheduleRestrictionValidation'import { deriveAlertCheckPreviewSeries } from 'products/alerts/frontend/logic/trendsAlertPreview'import { InsightAlertNotificationSection } from 'products/alerts/frontend/views/InsightAlertNotificationSection'import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'-import { alertFormLogic, canCheckOngoingInterval, insightAlertKindForQuery } from '../logic/alertFormLogic'+import {+ alertFormLogic,+ canCheckOngoingInterval,+ evaluationDelayField,+ insightAlertKindForQuery,+} from '../logic/alertFormLogic'import { alertLogic } from '../logic/alertLogic'import { alertNotificationLogic } from '../logic/alertNotificationLogic'import { isNextPlannedEvaluationStale } from '../logic/alertSchedulingStale'@@ -257,8 +262,14 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {])+ const delayField = evaluationDelayField(+ insightAlertKind,+ isNonTimeSeriesDisplay,+ alert?.evaluation_delay_intervals ?? 0+ )+const enabledAdvancedOptionsCount = useMemo(() => {- let n = 0+ let n = (alertForm.evaluation_delay_intervals ?? 0) > 0 ? 1 : 0if (supportsOngoingInterval(alertForm.config) &&alertForm.config.check_ongoing_interval &&@@ -274,7 +285,13 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {n += 1}return n- }, [alertForm.calculation_interval, alertForm.config, alertForm.skip_weekend, can_check_ongoing_interval])+ }, [+ alertForm.calculation_interval,+ alertForm.config,+ alertForm.skip_weekend,+ alertForm.evaluation_delay_intervals,+ can_check_ongoing_interval,+ ])const subscribedCount = alertForm.subscribed_users?.length ?? 0const destinationCount = existingHogFunctions.length + pendingNotifications.length@@ -283,16 +300,36 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {[alertForm, destinationCount, subscribedCount])+ const delayedPreviewResults = useMemo(() => {+ const delay = alertForm.evaluation_delay_intervals ?? 0+ if (!delay) {+ return indexedResults+ }+ const source = query && isInsightVizNode(query) ? query.source : query+ const excludesIncomplete = source && isTrendsQuery(source) && source.dateRange?.excludeIncompletePeriods+ const skipped = delay + (excludesIncomplete ? 0 : 1)+ return indexedResults?.map((series) => ({+ ...series,+ data: series.data.slice(0, -skipped),+ labels: series.labels?.slice(0, -skipped),+ }))+ }, [alertForm.evaluation_delay_intervals, indexedResults, query])+ const previewHistoryTooShort =+ !useAlertCheckPreview &&+ (alertForm.evaluation_delay_intervals ?? 0) > 0 &&+ !!indexedResults?.some((series) => series.data.length > 0) &&+ !!delayedPreviewResults?.every((series) => series.data.length === 0)+// The monitored trends series' values, for the live preview sparkline. Picked by the alert's// series_index so the preview matches what the alert actually evaluates.const trendsPreviewValues = useMemo(() => {if (!isTrendsFunnel && alertForm.config?.type === 'TrendsAlertConfig') {const idx = alertForm.config.series_index ?? 0- const series = indexedResults?.[idx]+ const series = delayedPreviewResults?.[idx]return series?.data ?? null}return null- }, [alertForm.config, indexedResults, isTrendsFunnel])+ }, [alertForm.config, delayedPreviewResults, isTrendsFunnel])const checkPreview = useMemo(() => {if (!useAlertCheckPreview || !alert) {@@ -398,6 +435,14 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {canCheckOngoingInterval={can_check_ongoing_interval}projectTimezone={projectTimezone}enabledAdvancedOptionsCount={enabledAdvancedOptionsCount}+ evaluationDelayInterval={delayField.show ? (trendInterval ?? 'day') : undefined}+ evaluationDelayUnsupportedReason={delayField.unsupportedReason}+ evaluationDelayPreview={evaluationDelayPreview(+ trendInterval ?? 'day',+ alertForm.evaluation_delay_intervals ?? 0,+ projectTimezone,+ currentTeam?.week_start_day ?? 0+ )}defaultOpenonSetAlertFormValue={setAlertFormValue}/>@@ -408,14 +453,14 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {alertForm={alertForm}trendsValues={trendsPreviewValues}trendsLabels={- indexedResults?.[+ delayedPreviewResults?.[alertForm.config?.type === 'TrendsAlertConfig' ? (alertForm.config.series_index ?? 0) : 0]?.labels ?? null}isBreakdown={isBreakdownValid && !isTrendsFunnel}trendsBreakdownSeries={isBreakdownValid && !isTrendsFunnel- ? indexedResults?.map((series) => ({+ ? delayedPreviewResults?.map((series) => ({key: String(series.seriesIndex),label: String(series.breakdown_value ?? series.label),data: series.data,@@ -425,6 +470,7 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {funnelPreview={funnelAlertPreview}hogqlPreview={hogqlAlertPreview}checkPreview={checkPreview}+ previewHistoryTooShort={previewHistoryTooShort}loading={!useAlertCheckPreview && (insightLoading || insightDataLoading)}/>)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex dd273e9b2fe1..5ea760fb8c86 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11891,6 +11891,12 @@ export namespace Schemas {/** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */config?: AlertConfigUnion | null;detector_config?: DetectorConfig | null;+ /**+ * Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number;/** How often the alert is checked: real time (Scale+), every 15 minutes (Boost+), hourly, daily, weekly, or monthly.** * `real_time` - real_time@@ -11968,6 +11974,12 @@ export namespace Schemas {}export interface AlertSimulate {+ /**+ * Skip this many completed insight intervals before simulation, matching live evaluation. Time-series Trends only; a positive delay requires check_ongoing_interval=false.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number;/** Numeric insight ID or saved insight short ID to simulate the detector on. */insight: number | string;/** Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing). */@@ -12009,6 +12021,14 @@ export namespace Schemas {}export interface AlertSimulateResponse {+ /** Completed intervals skipped. */+ evaluation_delay_intervals?: number;+ /** Start of the latest eligible interval. */+ evaluated_interval_start?: string;+ /** Exclusive end of the latest eligible interval. */+ evaluated_interval_end?: string;+ /** Project timezone of the interval. */+ evaluated_interval_timezone?: string;/** Data values for each point. */data: number[];/** Date labels for each point. */@@ -73711,6 +73731,12 @@ export namespace Schemas {/** Per-insight-kind alert configuration, discriminated by `type`. TrendsAlertConfig: series_index (which series to monitor) and check_ongoing_interval (whether to check the current incomplete interval). HogQLAlertConfig (SQL insights): column (which result column to evaluate, defaults to the single numeric column), evaluation ('last_row' checks the latest value of an oldest->newest query, 'first_row' checks the first value of a newest->oldest query, 'any_row' fires if any row breaches), and label_column (names the evaluated row(s) in breach messages, in every evaluation mode). FunnelsAlertConfig (funnel insights): funnel_step (the step to monitor, null for the overall last step), metric ('conversion_from_start' or 'conversion_from_previous'), and check_ongoing_interval (historical-trend funnels: also evaluate the current in-progress period). Steps funnels support only absolute_value conditions; historical-trend funnels also support relative_increase/relative_decrease (compared against the prior period). */config?: AlertConfigUnion | null;detector_config?: DetectorConfig | null;+ /**+ * Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.+ * @minimum 0+ * @maximum 100+ */+ evaluation_delay_intervals?: number;/** How often the alert is checked: real time (Scale+), every 15 minutes (Boost+), hourly, daily, weekly, or monthly.** * `real_time` - real_timediff --git a/services/mcp/src/generated/alerts/api.ts b/services/mcp/src/generated/alerts/api.tsindex 1d39bcfccf6c..33c8e934f508 100644--- a/services/mcp/src/generated/alerts/api.ts+++ b/services/mcp/src/generated/alerts/api.ts@@ -87,6 +87,9 @@ export const alertsCreateBodyDetectorConfigOneOnefourTypeDefault = `llm`export const alertsCreateBodyDetectorConfigOneOnefourWindowOneMin = 5export const alertsCreateBodyDetectorConfigOneOnefourWindowOneMax = 400+export const alertsCreateBodyEvaluationDelayIntervalsMin = 0+export const alertsCreateBodyEvaluationDelayIntervalsMax = 100+export const AlertsCreateBody = () => zod.object({insight: zod.number()@@ -1288,6 +1291,14 @@ export const AlertsCreateBody = () => zod.object({zod.null(),]).optional(),+ evaluation_delay_intervals: zod+ .number()+ .min(alertsCreateBodyEvaluationDelayIntervalsMin)+ .max(alertsCreateBodyEvaluationDelayIntervalsMax)+ .optional()+ .describe(+ 'Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.'+ ),calculation_interval: zod.enum(['real_time', 'every_15_minutes', 'hourly', 'daily', 'weekly', 'monthly']).describe(@@ -1439,6 +1450,9 @@ export const alertsPartialUpdateBodyDetectorConfigOneOnefourTypeDefault = `llm`export const alertsPartialUpdateBodyDetectorConfigOneOnefourWindowOneMin = 5export const alertsPartialUpdateBodyDetectorConfigOneOnefourWindowOneMax = 400+export const alertsPartialUpdateBodyEvaluationDelayIntervalsMin = 0+export const alertsPartialUpdateBodyEvaluationDelayIntervalsMax = 100+export const AlertsPartialUpdateBody = () => zod.object({insight: zod.number()@@ -2665,6 +2679,14 @@ export const AlertsPartialUpdateBody = () => zod.object({zod.null(),]).optional(),+ evaluation_delay_intervals: zod+ .number()+ .min(alertsPartialUpdateBodyEvaluationDelayIntervalsMin)+ .max(alertsPartialUpdateBodyEvaluationDelayIntervalsMax)+ .optional()+ .describe(+ 'Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.'+ ),calculation_interval: zod.enum(['real_time', 'every_15_minutes', 'hourly', 'daily', 'weekly', 'monthly']).describe(@@ -2805,6 +2827,10 @@ export const AlertsSimulateCreateParams = () => zod.object({),})+export const alertsSimulateCreateBodyEvaluationDelayIntervalsDefault = 0+export const alertsSimulateCreateBodyEvaluationDelayIntervalsMin = 0+export const alertsSimulateCreateBodyEvaluationDelayIntervalsMax = 100+export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemOneTypeDefault = `zscore`export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemTwoTypeDefault = `mad`export const alertsSimulateCreateBodyDetectorConfigOneOneDetectorsItemThreeTypeDefault = `iqr`@@ -2846,6 +2872,14 @@ export const alertsSimulateCreateBodyConfigOneThreeTypeDefault = `FunnelsAlertCoexport const alertsSimulateCreateBodyConfigOneFourTypeDefault = `MetricsAlertConfig`export const AlertsSimulateCreateBody = () => zod.object({+ evaluation_delay_intervals: zod+ .number()+ .min(alertsSimulateCreateBodyEvaluationDelayIntervalsMin)+ .max(alertsSimulateCreateBodyEvaluationDelayIntervalsMax)+ .default(alertsSimulateCreateBodyEvaluationDelayIntervalsDefault)+ .describe(+ 'Skip this many completed insight intervals before simulation, matching live evaluation. Time-series Trends only; a positive delay requires check_ongoing_interval=false.'+ ),insight: zod.union([zod.number(), zod.string()]).describe('Numeric insight ID or saved insight short ID to simulate the detector on.'),diff --git a/services/mcp/src/tools/generated/alerts.ts b/services/mcp/src/tools/generated/alerts.tsindex 047bad623180..bdcf6a0a855e 100644--- a/services/mcp/src/tools/generated/alerts.ts+++ b/services/mcp/src/tools/generated/alerts.ts@@ -44,6 +44,9 @@ const alertCreate = (): ToolBase<ReturnType<typeof AlertCreateSchema>, WithPostHif (params.detector_config !== undefined) {body['detector_config'] = params.detector_config}+ if (params.evaluation_delay_intervals !== undefined) {+ body['evaluation_delay_intervals'] = params.evaluation_delay_intervals+ }if (params.calculation_interval !== undefined) {body['calculation_interval'] = params.calculation_interval}@@ -206,6 +209,9 @@ const alertSimulate = (): ToolBase<ReturnType<typeof AlertSimulateSchema>, Schemhandler: async (context: Context, params: z.infer<ReturnType<typeof AlertSimulateSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}+ if (params.evaluation_delay_intervals !== undefined) {+ body['evaluation_delay_intervals'] = params.evaluation_delay_intervals+ }if (params.insight !== undefined) {body['insight'] = params.insight}@@ -269,6 +275,9 @@ const alertUpdate = (): ToolBase<ReturnType<typeof AlertUpdateSchema>, WithPostHif (params.detector_config !== undefined) {body['detector_config'] = params.detector_config}+ if (params.evaluation_delay_intervals !== undefined) {+ body['evaluation_delay_intervals'] = params.evaluation_delay_intervals+ }if (params.calculation_interval !== undefined) {body['calculation_interval'] = params.calculation_interval}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.jsonindex 14c2d9a0f30e..9543fb624939 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-create.json@@ -2275,6 +2275,12 @@"description": "Whether the alert is actively being evaluated.","type": "boolean"},+ "evaluation_delay_intervals": {+ "description": "Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.",+ "maximum": 100,+ "minimum": 0,+ "type": "number"+ },"insight": {"description": "Insight ID monitored by this alert. Note: Response returns full InsightBasicSerializer object.","type": "number"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.jsonindex ab5cbb0f188b..9158de7674f1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-simulate.json@@ -2252,6 +2252,13 @@],"description": "Detector configuration to simulate. Omit it to use the default daily z-score detector (threshold 0.95, window 90, first-difference preprocessing)."},+ "evaluation_delay_intervals": {+ "default": 0,+ "description": "Skip this many completed insight intervals before simulation, matching live evaluation. Time-series Trends only; a positive delay requires check_ongoing_interval=false.",+ "maximum": 100,+ "minimum": 0,+ "type": "number"+ },"insight": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.jsonindex e7c7bde4d079..84f4b9540575 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/alert-update.json@@ -2275,6 +2275,12 @@"description": "Whether the alert is actively being evaluated.","type": "boolean"},+ "evaluation_delay_intervals": {+ "description": "Skip this many completed insight intervals after excluding the ongoing interval (0-100, default 0). Time-series Trends only. A positive delay requires check_ongoing_interval=false. Uses the insight interval, not the check frequency. Allows late data to arrive, but also delays detection of real problems.",+ "maximum": 100,+ "minimum": 0,+ "type": "number"+ },"id": {"description": "A UUID string identifying this alert configuration.","type": "string"