Skip to content

: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.

fix(alerts): auto-disable alerts whose insight can no longer run (#103543)

Thomas Obermüllerd272ce79f0e0
diff --git a/posthog/hogql_queries/validation/validate_query.py b/posthog/hogql_queries/validation/validate_query.py
new file mode 100644
index 000000000000..5fb66f5a10bf
--- /dev/null
+++ b/posthog/hogql_queries/validation/validate_query.py
@@ -0,0 +1,80 @@
+"""Run a query's own validation rules against it without executing it.
+
+`QueryRunner.validate()` runs the rules in this package from `calculate()`, so a stored query is
+only judged while it is read, and only on a read that misses the result cache. A caller that has
+to know whether a stored query can run at all, such as an insight write or an alert check, asks
+here instead of waiting for the next uncached read to tell it.
+"""
+
+import logging
+from typing import Any
+
+from pydantic import BaseModel
+from rest_framework.exceptions import ErrorDetail, ValidationError
+
+from posthog.dataclasses import frozen
+from posthog.hogql_queries.query_runner import QueryRunner, get_query_runner_or_none
+from posthog.models import Team, User
+
+logger = logging.getLogger(__name__)
+
+
+@frozen
+class QueryRuleViolation:
+ code: str
+ message: str
+ query_kind: str
+
+
+def first_query_rule_violation(
+ query: dict[str, Any] | BaseModel,
+ *,
+ team: Team,
+ user: User | None = None,
+) -> QueryRuleViolation | None:
+ """The first validation rule the query breaks, or None when every rule passes."""
+ runner = _runner_or_none(query, team=team, user=user)
+ if runner is None:
+ return None
+
+ try:
+ runner.validate()
+ except ValidationError as error:
+ detail = _first_detail(error)
+ code = detail.code if isinstance(detail, ErrorDetail) else None
+ return QueryRuleViolation(
+ code=code or "invalid",
+ message=str(detail),
+ query_kind=str(getattr(runner.query, "kind", "unknown")),
+ )
+ except Exception:
+ # Only a rule saying "this query can never run" is a verdict on the query. Anything else a
+ # rule throws is our bug, and acting on it would reject a query the read path accepts.
+ logger.exception("Query validation rule failed")
+ return None
+
+ return None
+
+
+def rule_violation_message(error: ValidationError) -> str:
+ """The sentence a validation rule raised, out of DRF's list-or-dict-of-lists detail."""
+ return str(_first_detail(error))
+
+
+def _runner_or_none(query: dict[str, Any] | BaseModel, *, team: Team, user: User | None) -> QueryRunner | None:
+ try:
+ return get_query_runner_or_none(query, team, user=user)
+ except Exception:
+ # A payload no runner can be built for is one the read path already handles its own way.
+ # Refusing it here would turn every shape we do not recognize into a rejection.
+ return None
+
+
+def _first_detail(error: ValidationError) -> ErrorDetail | str:
+ # DRF coerces detail to a list, or to a dict of lists when the rule named a field.
+ detail: ErrorDetail | list | dict | str = error.detail
+ if isinstance(detail, dict):
+ detail = next(iter(detail.values()), "")
+ if isinstance(detail, list):
+ detail = detail[0] if detail else ""
+ return detail if isinstance(detail, ErrorDetail | str) else str(detail)
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 6fed101fc150..f21e45c0e628 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -57,7 +57,7 @@ from posthog.temporal.common.metrics import get_metric_meter
from products.alerts.backend.evaluation import check_alert_for_insight
from products.alerts.backend.evaluation.contract import AlertExtractionError
-from products.alerts.backend.evaluation.validation import validate_alert_config
+from products.alerts.backend.evaluation.validation import validate_alert_config, validate_alert_insight_query
from products.alerts.backend.facade.destinations import count_active_alert_destinations
from products.alerts.backend.insight_alert_state_machine import apply_unsnooze
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
@@ -271,6 +271,7 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
if insight.query is None:
raise ValueError("Alert's insight has no valid query")
threshold_config = alert.threshold.configuration if alert.threshold else None
+ validate_alert_insight_query(insight.query, team=alert.team, user=alert.created_by)
validate_alert_config(
insight.query,
alert.condition,
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 8fbed5721f04..46010c7314dc 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -350,6 +350,26 @@ class TestPrepareAlert:
assert check.error is not None
assert result.reason in check.error["message"]
+ async def test_auto_disable_when_the_insight_query_can_no_longer_run(self, ateam) -> None:
+ # The check runs before every evaluation, so an insight that loses a step after the alert
+ # was created disables the alert instead of leaving it failing and silent.
+ a = await _create_alert(
+ ateam,
+ query={"kind": "FunnelsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},
+ config={"type": "FunnelsAlertConfig", "metric": "conversion_from_start", "funnel_step": None},
+ )
+
+ env = ActivityEnvironment()
+ result = await env.run(prepare_alert, PrepareAlertActivityInputs(alert_id=str(a.id)))
+
+ assert result.action == PrepareAction.AUTO_DISABLE
+ assert result.reason is not None
+ assert "Funnels require at least two steps." in result.reason
+
+ refreshed = await sync_to_async(AlertConfiguration.objects.get)(pk=a.pk)
+ assert refreshed.enabled is False
+ assert refreshed.state == AlertState.ERRORED
+
async def test_auto_disable_email_alert_when_email_is_unavailable(self, alert_with_user) -> None:
with patch("posthog.temporal.alerts.activities.is_email_available", return_value=False):
env = ActivityEnvironment()
diff --git a/products/alerts/backend/evaluation/dispatcher.py b/products/alerts/backend/evaluation/dispatcher.py
index 9f4a0f3126f1..b9e747e0770a 100644
--- a/products/alerts/backend/evaluation/dispatcher.py
+++ b/products/alerts/backend/evaluation/dispatcher.py
@@ -1,12 +1,21 @@
+from rest_framework.exceptions import ValidationError as DRFValidationError
+
from posthog.schema import AlertCondition, InsightThreshold, IntervalType, NodeKind
from posthog.api.services.query import ExecutionMode
+from posthog.hogql_queries.validation.validate_query import rule_violation_message
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResult
from posthog.utils import get_from_dict_or_attr
from products.alerts.backend.evaluation.comparator import evaluate_threshold
-from products.alerts.backend.evaluation.contract import DetectorExtractor, Extractor, execution_mode_for_alert
+from products.alerts.backend.evaluation.contract import (
+ AlertExtractionError,
+ DetectorExtractor,
+ ExtractionResult,
+ Extractor,
+ execution_mode_for_alert,
+)
from products.alerts.backend.evaluation.detector import TrendsDetectorExtractor, evaluate_with_detector
from products.alerts.backend.evaluation.funnels import FunnelsExtractor
from products.alerts.backend.evaluation.hogql import HogQLDetectorExtractor, HogQLExtractor
@@ -42,6 +51,34 @@ def _resolve_execution_mode(alert: AlertConfiguration, kind: NodeKind, query: ob
return execution_mode_for_alert(interval, high_frequency=alert.is_high_frequency_interval)
+def run_extractor(
+ extractor: Extractor,
+ alert: AlertConfiguration,
+ insight: Insight,
+ query: object,
+ execution_mode: ExecutionMode,
+) -> ExtractionResult:
+ """Run an extractor, routing a query the runner refuses to the auto-disable path.
+
+ The query layer raises a DRF ValidationError for an insight it can never run as written: a
+ validation rule the insight breaks, an action a step points at that no longer exists, a cohort
+ property it can no longer resolve. The alert cannot evaluate until someone fixes the insight,
+ so it is disabled and its owner emailed, rather than the same failure being captured on every
+ scheduled check.
+
+ A breaker replay is not such a verdict. It carries the remembered ClickHouse failure of a query
+ that is itself sound (see ``build_failure_exception`` in
+ ``posthog/hogql_queries/query_failure_handling.py``), and disabling on it would silence a
+ working alert over a load problem, so it keeps the ordinary failure path.
+ """
+ try:
+ return extractor.extract(alert, insight, query, execution_mode)
+ except DRFValidationError as err:
+ if getattr(err, "served_from_query_failure_cache", False):
+ raise
+ raise AlertExtractionError(rule_violation_message(err)) from err
+
+
def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: object) -> AlertEvaluationResult:
"""Route a detector (anomaly) alert to its kind's detector extractor, then score the series.
@@ -55,7 +92,7 @@ def check_detector_alert(alert: AlertConfiguration, insight: Insight, query: obj
detector_extractor = DETECTOR_EXTRACTORS.get(kind)
if detector_extractor is None:
raise NotImplementedError(f"AlertCheckError: Detector alerts for {kind} are not supported yet")
- result = detector_extractor.extract(alert, insight, query, _resolve_execution_mode(alert, kind, query))
+ result = run_extractor(detector_extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))
return evaluate_with_detector(result, detector_config)
@@ -92,5 +129,5 @@ def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:
return AlertEvaluationResult(value=0, breaches=[])
condition = AlertCondition.model_validate(alert.condition)
- result = extractor.extract(alert, insight, query, _resolve_execution_mode(alert, kind, query))
+ result = run_extractor(extractor, alert, insight, query, _resolve_execution_mode(alert, kind, query))
return evaluate_threshold(result, condition, threshold)
diff --git a/products/alerts/backend/evaluation/test/test_dispatcher.py b/products/alerts/backend/evaluation/test/test_dispatcher.py
new file mode 100644
index 000000000000..7137c039f7ff
--- /dev/null
+++ b/products/alerts/backend/evaluation/test/test_dispatcher.py
@@ -0,0 +1,66 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from rest_framework.exceptions import ValidationError as DRFValidationError
+
+from posthog.api.services.query import ExecutionMode
+from posthog.hogql_queries.query_failure_handling import build_failure_exception
+from posthog.query_cache.failures import QueryFailureRecord
+
+from products.alerts.backend.evaluation.contract import AlertExtractionError, ExtractionResult
+from products.alerts.backend.evaluation.dispatcher import run_extractor
+
+IF_STALE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+
+
+class _Extractor:
+ def __init__(self, outcome: Exception | ExtractionResult) -> None:
+ self._outcome = outcome
+
+ def extract(self, alert: Any, insight: Any, query: Any, execution_mode: ExecutionMode) -> ExtractionResult:
+ if isinstance(self._outcome, Exception):
+ raise self._outcome
+ return self._outcome
+
+
+def _run(outcome: Exception | ExtractionResult) -> ExtractionResult:
+ return run_extractor(_Extractor(outcome), MagicMock(), MagicMock(), {}, IF_STALE)
+
+
+def _breaker_replay() -> Exception:
+ return build_failure_exception(
+ QueryFailureRecord(
+ kind="too_many_bytes",
+ detail="Query read too many bytes.",
+ consecutive_failures=1,
+ last_failed_at=datetime.now(UTC),
+ open_until=datetime.now(UTC) + timedelta(hours=1),
+ )
+ )
+
+
+ "detail,expected_message",
+ [
+ ("Funnels require at least two steps.", "Funnels require at least two steps."),
+ ({"query": ["Action ID 7 does not exist!"]}, "Action ID 7 does not exist!"),
+ ],
+)
+def test_a_rejected_insight_becomes_an_extraction_error(detail, expected_message) -> None:
+ with pytest.raises(AlertExtractionError, match=expected_message):
+ _run(DRFValidationError(detail))
+
+
+def test_a_breaker_replay_keeps_the_ordinary_failure_path() -> None:
+ # Same exception family, opposite verdict: the insight is sound, so the alert stays enabled.
+ replay = _breaker_replay()
+ with pytest.raises(type(replay)):
+ _run(replay)
+
+
+def test_a_successful_extraction_passes_through() -> None:
+ result = ExtractionResult(series=[])
+ assert _run(result) is result
diff --git a/products/alerts/backend/evaluation/validation.py b/products/alerts/backend/evaluation/validation.py
index bce557531241..fe5c2f88e02a 100644
--- a/products/alerts/backend/evaluation/validation.py
+++ b/products/alerts/backend/evaluation/validation.py
@@ -21,6 +21,9 @@ from posthog.schema import (
TrendsQuery,
)
+from posthog.hogql_queries.validation.validate_query import first_query_rule_violation
+from posthog.models.team import Team
+from posthog.models.user import User
from posthog.tasks.alerts.utils import REAL_TIME_CADENCE_MINUTES, WRAPPER_NODE_KINDS, is_non_time_series_trend
from posthog.utils import get_from_dict_or_attr
@@ -320,7 +323,8 @@ def validate_alert_config(
) -> None:
"""Validate alert configuration dicts. Raises ValueError on failure.
- Common checks run here; per-config-type rules live in ``_ALERT_CONFIG_VALIDATORS``.
+ Common checks run here; per-config-type rules live in ``_ALERT_CONFIG_VALIDATORS``. Whether
+ the insight itself can run is a separate question, answered by ``validate_alert_insight_query``.
"""
if not calculation_interval or not isinstance(calculation_interval, str):
raise ValueError(f"Invalid calculation interval: {calculation_interval}")
@@ -350,6 +354,7 @@ def validate_alert_config(
validator = _ALERT_CONFIG_VALIDATORS.get(config_type) if isinstance(config_type, str) else None
if validator is None:
raise ValueError(f"Unsupported alert config type: {config}")
+
validator(
_AlertConfigValidationContext(
config=config if isinstance(config, dict) else {},
@@ -361,3 +366,17 @@ def validate_alert_config(
detector_config=detector_config,
)
)
+
+
+def validate_alert_insight_query(query: dict, *, team: Team, user: User | None) -> None:
+ """Check the insight an alert points at against the query runner's own validation rules.
+
+ Raises ValueError like ``validate_alert_config``, so a caller handles both the same way. It is
+ separate because it answers a different question from different inputs: the alert configuration
+ is validated from dicts alone, while these rules need the team and the user that the query would
+ run as. Reading the runner's rules rather than copying them keeps this in step with what the
+ query will accept, for every insight kind.
+ """
+ violation = first_query_rule_violation(query, team=team, user=user)
+ if violation is not None:
+ raise ValueError(f"Alert's insight can't run: {violation.message}")
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index eac3c5939ae3..eb6c0628fd01 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -67,6 +67,7 @@ from products.alerts.backend.evaluation.validation import (
THRESHOLD_BOUNDS_REQUIRED_MESSAGE,
should_default_check_ongoing_interval,
validate_alert_config,
+ validate_alert_insight_query,
)
from products.alerts.backend.facade.api import INSIGHT_ALERT_DESTINATION_TYPES, INSIGHT_ALERT_EVENT_IDS
from products.alerts.backend.facade.contracts import (
@@ -853,7 +854,16 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
config = {**config, "check_ongoing_interval": True}
attrs["config"] = config
+ request_user = self.context["request"].user
+ creating_user = request_user if isinstance(request_user, User) else None
try:
+ validate_alert_insight_query(
+ query,
+ team=self.context["get_team"](),
+ # The alert evaluates as its creator, so an update validates as that user rather
+ # than as whoever is editing it.
+ user=self.instance.created_by if self.instance is not None else creating_user,
+ )
validate_alert_config(
query,
condition,
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index 61356333d8b0..c2f88f048261 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -1060,6 +1060,29 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert expected_error_fragment in response.json()["detail"].lower()
+ def test_create_alert_rejects_an_insight_the_query_runner_cannot_run(self) -> None:
+ seriesless_insight_data = deepcopy(self.default_insight_data)
+ seriesless_insight_data["query"]["series"] = []
+ seriesless_insight = self.client.post(
+ f"/api/projects/{self.team.id}/insights", data=seriesless_insight_data
+ ).json()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ {
+ "insight": seriesless_insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "alert name",
+ "calculation_interval": "daily",
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "require at least one series" in response.json()["detail"]
+
@parameterized.expand(
[
(
diff --git a/products/product_analytics/backend/presentation/insight_write_validation.py b/products/product_analytics/backend/presentation/insight_write_validation.py
index a46a76ffc783..4892634f404b 100644
--- a/products/product_analytics/backend/presentation/insight_write_validation.py
+++ b/products/product_analytics/backend/presentation/insight_write_validation.py
@@ -1,10 +1,9 @@
-"""Run the query runners' validation rules when an insight is written, not only when it runs.
+"""Report an insight write whose query no runner can execute.
-The rules in `posthog/hogql_queries/validation` fire from `QueryRunner.calculate()`, so they
-only see a query on the read path. An insight whose query no runner can execute saves
-cleanly and then fails on every render, so a dashboard can hold a tile that has never drawn.
-This module runs the same rule objects against the query that is being written, which
-reports the problem once instead of on every read.
+An insight whose query breaks a validation rule saves cleanly and then fails on every render,
+so a dashboard can hold a tile that has never drawn. `first_query_rule_violation` runs the
+runner's own rules against the query being written, which reports the problem once instead of
+on every read.
A rejection is recorded but not raised until the enforcement flag is on for the team. That
shows which saves the rules would refuse before any save starts to fail.
@@ -22,7 +21,7 @@ from rest_framework.request import Request
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_action
-from posthog.hogql_queries.query_runner import QueryRunner, get_query_runner_or_none
+from posthog.hogql_queries.validation.validate_query import first_query_rule_violation
from posthog.models import Team, User
from posthog.ph_client import feature_enabled_or_false
from posthog.synthetic_user import SyntheticUser
@@ -48,12 +47,6 @@ class InsightWriteRejection:
query_kind: str
-@frozen
-class _RuleError:
- message: str
- code: str
-
-
def validate_insight_write(
*,
query: dict[str, Any] | None,
@@ -115,44 +108,15 @@ def _rejection_for(
team: Team,
user: Writer,
) -> InsightWriteRejection | None:
- runner = _runner_or_none(query, team=team, user=user)
- if runner is None:
- return None
-
- try:
- runner.validate()
- except ValidationError as error:
- rule_error = _first_error(error)
- return InsightWriteRejection(
- rule_code=rule_error.code,
- message=rule_error.message,
- query_kind=str(getattr(runner.query, "kind", "unknown")),
- )
- except Exception:
- # Only a rule saying "this can never run" is worth a 400. Anything else a rule throws
- # is our bug, and failing the save on it would block writes the read path accepts.
- logger.exception("Insight write validation rule failed")
+ violation = first_query_rule_violation(query, team=team, user=user if isinstance(user, User) else None)
+ if violation is None:
return None
- return None
-
-
-def _runner_or_none(query: dict[str, Any] | BaseModel, *, team: Team, user: Writer) -> QueryRunner | None:
- try:
- return get_query_runner_or_none(query, team, user=user if isinstance(user, User) else None)
- except Exception:
- # A payload no runner can be built for is one the read path already handles its own
- # way. Rejecting it here would turn every shape we don't recognize into a 400.
- return None
-
-
-def _first_error(error: ValidationError) -> _RuleError:
- detail: Any = error.detail
- if isinstance(detail, dict):
- detail = next(iter(detail.values()), "")
- if isinstance(detail, list):
- detail = detail[0] if detail else ""
- return _RuleError(message=str(detail), code=str(getattr(detail, "code", "invalid")))
+ return InsightWriteRejection(
+ rule_code=violation.code,
+ message=violation.message,
+ query_kind=violation.query_kind,
+ )
def _record(