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.

chore(alerts): delete Celery orchestration layer for alert checks (#53837)

Vasco de Krijger9200e1ec283b
diff --git a/posthog/api/annotation.py b/posthog/api/annotation.py
index 9ff3ce799ec2..00916b5a0e28 100644
--- a/posthog/api/annotation.py
+++ b/posthog/api/annotation.py
@@ -152,7 +152,7 @@ class AnnotationsViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mo
# across all actions — including `partial_update`, so they cannot be
# individually edited or restored while their parent is soft-deleted.
# They reappear automatically when the parent is restored. Mirrors how
- # alerts behave (see posthog/tasks/alerts/checks.py).
+ # alerts behave (see posthog/temporal/alerts/activities.py).
queryset = queryset.filter(
Q(dashboard_item__isnull=True) | Q(dashboard_item__deleted=False),
Q(dashboard__isnull=True) | Q(dashboard__deleted=False),
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index 2e614fe5be0c..7aa67c682643 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -2721,7 +2721,6 @@
"posthog_alertconfiguration"."detector_config",
"posthog_alertconfiguration"."state",
"posthog_alertconfiguration"."enabled",
- "posthog_alertconfiguration"."is_calculating",
"posthog_alertconfiguration"."last_notified_at",
"posthog_alertconfiguration"."last_checked_at",
"posthog_alertconfiguration"."next_check_at",
@@ -10343,7 +10342,6 @@
"posthog_alertconfiguration"."detector_config",
"posthog_alertconfiguration"."state",
"posthog_alertconfiguration"."enabled",
- "posthog_alertconfiguration"."is_calculating",
"posthog_alertconfiguration"."last_notified_at",
"posthog_alertconfiguration"."last_checked_at",
"posthog_alertconfiguration"."next_check_at",
diff --git a/posthog/migrations/1167_remove_alertconfiguration_is_calculating.py b/posthog/migrations/1167_remove_alertconfiguration_is_calculating.py
new file mode 100644
index 000000000000..ac44a00fdfa9
--- /dev/null
+++ b/posthog/migrations/1167_remove_alertconfiguration_is_calculating.py
@@ -0,0 +1,32 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ """
+ Phase 1 of 2: Remove is_calculating from Django state.
+
+ This keeps the column in the database but removes it from the Django model.
+ The actual column drop happens in the follow-up
+ ``drop_alertconfiguration_is_calculating_column`` migration.
+
+ The field was used by the old Celery alert check flow to prevent two workers
+ from running the same alert check concurrently. The Temporal-based flow relies
+ on Temporal's deterministic workflow ID guarantee instead, so the flag is dead
+ state.
+ """
+
+ dependencies = [
+ ("posthog", "1166_oauth_impersonated_by"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveField(
+ model_name="alertconfiguration",
+ name="is_calculating",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 044f05361250..f7de5fe37ae8 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1166_oauth_impersonated_by
+1167_remove_alertconfiguration_is_calculating
diff --git a/posthog/models/alert.py b/posthog/models/alert.py
index 3b3d16b0cf34..e1038b93041e 100644
--- a/posthog/models/alert.py
+++ b/posthog/models/alert.py
@@ -141,7 +141,6 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
state = models.CharField(max_length=10, choices=ALERT_STATE_CHOICES, default=AlertState.NOT_FIRING)
enabled = models.BooleanField(default=True)
- is_calculating = models.BooleanField(default=False, null=True, blank=True)
last_notified_at = models.DateTimeField(null=True, blank=True)
last_checked_at = models.DateTimeField(null=True, blank=True)
@@ -156,14 +155,14 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
# When enabled and the alert transitions to FIRING, an investigation agent runs
# and writes its findings to a linked Notebook. Only effective for detector-based
- # (anomaly) alerts. See posthog/tasks/alerts/checks.py for the trigger logic.
+ # (anomaly) alerts. See posthog/temporal/alerts/workflows.py for the trigger logic.
investigation_agent_enabled = models.BooleanField(default=False)
# When enabled (and investigation_agent_enabled is on), notification dispatch is
# held until the investigation agent produces a verdict — and suppressed if the
- # verdict is false_positive. A safety-net celery task force-notifies after a
+ # verdict is false_positive. A safety-net Temporal workflow force-notifies after a
# grace period if the investigation stalls, so users can never silently miss a
- # real fire. See posthog/tasks/alerts/investigation_notifications.py.
+ # real fire. See posthog/temporal/alerts/workflows.py (RunInvestigationSafetyNetWorkflow).
investigation_gates_notifications = models.BooleanField(default=False)
# What to do with an "inconclusive" verdict when notifications are gated.
diff --git a/posthog/tasks/alerts/checks.py b/posthog/tasks/alerts/checks.py
deleted file mode 100644
index c4802e4a8c40..000000000000
--- a/posthog/tasks/alerts/checks.py
+++ /dev/null
@@ -1,490 +0,0 @@
-import traceback
-from collections import defaultdict
-from datetime import UTC, datetime, timedelta
-from typing import cast
-
-from django.db import transaction
-from django.db.models import F, Q
-
-import structlog
-from celery import shared_task
-from celery.canvas import chain
-from dateutil.relativedelta import relativedelta
-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
-
-from posthog.schema import AlertCalculationInterval, AlertState, TrendsQuery
-
-from posthog.clickhouse.query_tagging import tag_queries
-from posthog.errors import CH_TRANSIENT_ERRORS
-from posthog.exceptions_capture import capture_exception
-from posthog.models import AlertConfiguration
-from posthog.models.alert import AlertCheck
-from posthog.ph_client import ph_scoped_capture
-from posthog.schema_migrations.upgrade_manager import upgrade_query
-from posthog.scoping_audit import skip_team_scope_audit
-from posthog.slo.context import SloSpec, slo_operation
-from posthog.slo.types import SloArea, SloOperation
-from posthog.tasks.alerts.detector import check_trends_alert_with_detector
-from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utc
-from posthog.tasks.alerts.trends import check_trends_alert
-from posthog.tasks.alerts.utils import (
- WRAPPER_NODE_KINDS,
- AlertEvaluationResult,
- calculation_interval_to_order,
- disable_invalid_alert,
- dispatch_alert_notification,
- next_check_time,
- record_alert_delivery,
- skip_because_of_weekend,
- validate_alert_config,
-)
-from posthog.tasks.utils import CeleryQueue
-from posthog.utils import get_from_dict_or_attr
-
-logger = structlog.get_logger(__name__)
-
-
-class AlertCheckException(Exception):
- """
- Required for custom exceptions to pass stack trace to error tracking.
- Subclassing through other ways doesn't transfer the traceback.
- https://stackoverflow.com/a/69963663/5540417
- """
-
- def __init__(self, err: Exception):
- self.__traceback__ = err.__traceback__
-
-
-ANIRUDH_DISTINCT_ID = "wcPbDRs08GtNzrNIXfzHvYAkwUaekW7UrAo4y3coznT"
-
-
-@shared_task(ignore_result=True)
-def checks_cleanup_task() -> None:
- AlertCheck.clean_up_old_checks()
-
-
-@shared_task(
- ignore_result=True,
- expires=60 * 60,
-)
-@skip_team_scope_audit
-def alerts_backlog_task() -> None:
- """
- This runs every 5min to check backlog for alerts
- - hourly alerts - alerts that haven't been checked in the last hour + 5min
- - daily alerts - alerts that haven't been checked in the last hour + 15min
- """
- now = datetime.now(UTC)
-
- hourly_alerts_breaching_sla = AlertConfiguration.objects.filter(
- Q(
- enabled=True,
- calculation_interval=AlertCalculationInterval.HOURLY,
- last_checked_at__lte=now - relativedelta(hours=1, minutes=5),
- ),
- insight__deleted=False,
- ).count()
-
- now = datetime.now(UTC)
-
- daily_alerts_breaching_sla = AlertConfiguration.objects.filter(
- Q(
- enabled=True,
- calculation_interval=AlertCalculationInterval.HOURLY,
- last_checked_at__lte=now - relativedelta(days=1, minutes=15),
- ),
- insight__deleted=False,
- ).count()
-
- with ph_scoped_capture() as capture_ph_event:
- capture_ph_event(
- distinct_id=ANIRUDH_DISTINCT_ID,
- event="alert check backlog",
- properties={
- "calculation_interval": AlertCalculationInterval.DAILY,
- "backlog": daily_alerts_breaching_sla,
- },
- )
-
- capture_ph_event(
- distinct_id=ANIRUDH_DISTINCT_ID,
- event="alert check backlog",
- properties={
- "calculation_interval": AlertCalculationInterval.HOURLY,
- "backlog": hourly_alerts_breaching_sla,
- },
- )
-
-
-@shared_task(
- ignore_result=True,
- expires=60 * 60,
-)
-@skip_team_scope_audit
-def reset_stuck_alerts_task() -> None:
- now = datetime.now(UTC)
-
- # TRICKY: When celery task exits due to timeout/insight calc taking too long
- # the finally block below isn't run and the alert gets stuck with is_calculating = True
- # hence when checking is_calculating, we also need to check if task has been stuck in is_calculating for too long
- stuck_alerts = AlertConfiguration.objects.filter(
- Q(enabled=True, is_calculating=True, last_checked_at__lte=now - relativedelta(minutes=45))
- | Q(
- enabled=True,
- is_calculating=True,
- last_checked_at__isnull=True,
- created_at__lte=now - relativedelta(minutes=45),
- ),
- insight__deleted=False,
- )
-
- for alert in stuck_alerts:
- # we need to check the alert, reset is_calculating
- logger.info("check_alert.reset_stuck_alert", alert_id=alert.id)
- alert.is_calculating = False
- alert.save()
-
-
-@shared_task(
- ignore_result=True,
- expires=60 * 60,
-)
-@skip_team_scope_audit
-def check_alerts_task() -> None:
- """
- This runs every 2min to check for alerts that are due to recalculate
- """
- now = datetime.now(UTC)
- # Use a fixed expiration time since tasks in the chain are executed sequentially
- expire_after = now + timedelta(minutes=30)
-
- # find all alerts with the provided interval that are due to be calculated
- # (next_check_at is null or less than now) and it's not snoozed
- alerts = (
- AlertConfiguration.objects.filter(
- Q(enabled=True, is_calculating=False, next_check_at__lte=now)
- | Q(enabled=True, is_calculating=False, next_check_at__isnull=True)
- )
- .filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=now))
- .filter(insight__deleted=False)
- .order_by(F("next_check_at").asc(nulls_first=True))
- .only("id", "team", "calculation_interval", "insight_id")
- )
-
- sorted_alerts = sorted(
- alerts,
- key=lambda alert: calculation_interval_to_order(
- cast(AlertCalculationInterval | None, alert.calculation_interval)
- ),
- )
-
- grouped_by_team: defaultdict[int, list[tuple[str, int, str | None, int]]] = defaultdict(list)
- for alert in sorted_alerts:
- grouped_by_team[alert.team_id].append(
- (
- str(alert.id),
- alert.team_id,
- cast(AlertCalculationInterval | None, alert.calculation_interval),
- alert.insight_id or 0,
- )
- )
-
- for alert_data in grouped_by_team.values():
- # We chain the task execution to prevent queries *for a single team* running at the same time
- chain(
- *(
- check_alert_task.si(alert_id, team_id, calculation_interval, insight_id).set(expires=expire_after)
- for alert_id, team_id, calculation_interval, insight_id in alert_data
- )
- )()
-
-
-@shared_task(
- ignore_result=True,
- queue=CeleryQueue.ALERTS.value,
- expires=60 * 60,
-)
-# @limit_concurrency(5) Concurrency controlled by CeleryQueue.ALERTS for now
-def check_alert_task(
- alert_id: str, team_id: int = 0, calculation_interval: str | None = None, insight_id: int = 0
-) -> None:
- with ph_scoped_capture() as capture_ph_event:
- with slo_operation(
- spec=SloSpec(
- distinct_id=alert_id,
- area=SloArea.ANALYTIC_PLATFORM,
- operation=SloOperation.ALERT_CHECK,
- team_id=team_id,
- resource_id=alert_id,
- ),
- properties={"calculation_interval": calculation_interval, "insight_id": insight_id},
- capture=capture_ph_event,
- ):
- check_alert(alert_id)
-
-
-@retry(
- retry=retry_if_exception_type(CH_TRANSIENT_ERRORS),
- stop=stop_after_attempt(4),
- wait=wait_exponential_jitter(initial=1, max=10),
- before_sleep=lambda rs: logger.info(
- "check_alert.retrying",
- attempt=rs.attempt_number,
- error=str(rs.outcome.exception()) if rs.outcome else None,
- ),
- reraise=True,
-)
-def check_alert(alert_id: str) -> None:
- try:
- alert = AlertConfiguration.objects.select_related("insight", "team").get(id=alert_id, enabled=True)
- except AlertConfiguration.DoesNotExist:
- logger.warning("Alert not found or not enabled", alert_id=alert_id)
- return
-
- if alert.insight.deleted:
- logger.info("Skipping alert for deleted insight", alert_id=alert_id, insight_id=alert.insight_id)
- return
-
- now = datetime.now(UTC)
-
- if alert.next_check_at and alert.next_check_at > now:
- logger.info(
- """Alert took too long to compute or was queued too long during which it already got computed.
- So not attempting to compute it again until it's due next""",
- alert=alert,
- )
- return
-
- if alert.is_calculating:
- logger.info(
- "Alert is already being computed so skipping checking it now",
- alert=alert,
- )
- return
-
- if skip_because_of_weekend(alert):
- logger.info(
- "Skipping alert check because weekend checking is disabled",
- alert=alert,
- )
-
- # ignore alert check until due again
- alert.next_check_at = next_check_time(alert)
- alert.save(update_fields=["next_check_at"])
- return
-
- if is_utc_datetime_blocked(alert, now):
- logger.info(
- "Skipping alert check because of schedule restriction (quiet hours)",
- alert_id=alert.id,
- )
- alert.next_check_at = next_unblocked_utc(alert, now)
- alert.save(update_fields=["next_check_at"])
- return
-
- if alert.snoozed_until:
- if alert.snoozed_until > now:
- logger.info(
- "Alert has been snoozed so skipping checking it now",
- alert=alert,
- )
- return
- else:
- # not snoozed (anymore) so clear snoozed_until
- alert.snoozed_until = None
- alert.state = AlertState.NOT_FIRING
-
- try:
- insight = alert.insight
- with upgrade_query(insight):
- 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_config(
- insight.query, alert.condition, alert.config, threshold_config, alert.calculation_interval
- )
- except ValueError as e:
- disable_invalid_alert(alert, str(e))
- return
-
- # we will attempt to check alert
- logger.info("check_alert", alert_id=alert.id)
- alert.last_checked_at = datetime.now(UTC)
- alert.is_calculating = True
- alert.save()
-
- try:
- check_alert_and_notify_atomically(alert)
- except Exception as err:
- logger.exception(AlertCheckException(err))
- capture_exception(
- AlertCheckException(err),
- additional_properties={
- "alert_configuration_id": alert_id,
- "insight_id": alert.insight_id,
- "team_id": alert.team_id,
- },
- )
-
- # raise again so alert check is retried depending on error type
- raise
- finally:
- # TRICKY: When celery task exits due to timeout/insight calc taking too long
- # this finally block isn't run and the alert gets stuck with is_calculating = True
- # hence when checking is_calculating, we also need to check if task has been stuck in is_calculating for too long
-
- # Get all updates with alert checks
- alert.refresh_from_db()
- alert.is_calculating = False
- alert.save()
-
-
-def check_alert_and_notify_atomically(alert: AlertConfiguration) -> None:
- """
- Computes insight results, checks alert for breaches and notifies user.
- Only commits updates to alert state if all of the above complete successfully.
- TODO: Later separate notification mechanism from alert checking mechanism (when we move to CDP)
- so we can retry notification without re-computing insight.
- """
- tag_queries(alert_config_id=str(alert.id))
-
- value = breaches = error = None
- alert_evaluation_result = None
-
- # 1. Evaluate insight and get alert value
- try:
- alert_evaluation_result = check_alert_for_insight(alert)
- value = alert_evaluation_result.value
- breaches = alert_evaluation_result.breaches
- except CH_TRANSIENT_ERRORS:
- # Re-raise so we retry the full flow
- raise
- except Exception as err:
- error_message = f"Alert id = {alert.id}, failed to evaluate"
- logger.exception(error_message, exc_info=err)
- capture_exception(AlertCheckException(err))
-
- # error can be on user side (incorrectly configured insight/alert)
- # we won't retry and set alert to errored state
- error = {"message": str(err), "traceback": traceback.format_exc()}
-
- # 2. Extract detector fields and create alert check
- anomaly_scores = getattr(alert_evaluation_result, "anomaly_scores", None) if alert_evaluation_result else None
- triggered_points = getattr(alert_evaluation_result, "triggered_points", None) if alert_evaluation_result else None
- triggered_dates = getattr(alert_evaluation_result, "triggered_dates", None) if alert_evaluation_result else None
- interval = getattr(alert_evaluation_result, "interval", None) if alert_evaluation_result else None
- triggered_metadata = (
- getattr(alert_evaluation_result, "triggered_metadata", None) if alert_evaluation_result else None
- )
- alert_check, should_notify = add_alert_check(
- alert,
- value,
- breaches,
- error,
- anomaly_scores,
- triggered_points,
- triggered_dates,
- interval,
- triggered_metadata,
- )
-
- # 3. Notify users if needed
- if not should_notify:
- return
-
- try:
- targets = dispatch_alert_notification(alert, alert_check, breaches)
- if targets is not None:
- record_alert_delivery(alert, alert_check, targets)
- except Exception as err:
- error_message = f"AlertCheckError: error sending notifications for alert_id = {alert.id}"
- logger.exception(error_message, exc_info=err)
- capture_exception(Exception(error_message))
-
- # don't want alert state to be updated (so that it's retried as next_check_at won't be updated)
- # so we raise again as @transaction.atomic decorator won't commit db updates
- # TODO: later should have a way just to retry notification mechanism
- raise
-
-
-def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:
- """
- Matches insight type with alert checking logic.
-
- If detector_config is set, uses the detector abstraction.
- Otherwise falls back to threshold-based checking.
- """
- insight = alert.insight
-
- with upgrade_query(insight):
- query = insight.query
- kind = get_from_dict_or_attr(query, "kind")
-
- if kind in WRAPPER_NODE_KINDS:
- query = get_from_dict_or_attr(query, "source")
- kind = get_from_dict_or_attr(query, "kind")
-
- match kind:
- case "TrendsQuery":
- query = TrendsQuery.model_validate(query)
- # Use detector-based checking if detector_config is set
- if alert.detector_config:
- return check_trends_alert_with_detector(alert, insight, query, alert.detector_config)
- return check_trends_alert(alert, insight, query)
- case _:
- raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")
-
-
-def add_alert_check(
- alert: AlertConfiguration,
- value: float | None,
- breaches: list[str] | None,
- error: dict | None,
- anomaly_scores: list[float | None] | None = None,
- triggered_points: list[int] | None = None,
- triggered_dates: list[str] | None = None,
- interval: str | None = None,
- triggered_metadata: dict | None = None,
-) -> tuple[AlertCheck, bool]:
- """Persist an AlertCheck row and return it plus a decision on whether notification is needed.
-
- `targets_notified` is always created empty; `notify_alert_activity` fills it on
- successful delivery and treats a non-empty value as the idempotency sentinel on retry.
- `last_notified_at` is likewise set by the notify activity on success, not here.
- """
- should_notify = False
-
- if error:
- alert.state = AlertState.ERRORED
- should_notify = True
- elif breaches:
- alert.state = AlertState.FIRING
- should_notify = True
- else:
- alert.state = AlertState.NOT_FIRING # Set the Alert to not firing if the threshold is no longer met
- # TODO: Optionally send a resolved notification when alert goes from firing to not_firing?
-
- alert.last_checked_at = datetime.now(UTC)
-
- # IMPORTANT: update next_check_at according to interval
- # ensure we don't recheck alert until the next interval is due
- alert.next_check_at = next_check_time(alert)
-
- alert_check = AlertCheck.objects.create(
- alert_configuration=alert,
- calculated_value=value,
- condition=alert.condition,
- targets_notified={},
- state=alert.state,
- triggered_metadata=triggered_metadata,
- error=error,
- anomaly_scores=anomaly_scores,
- triggered_points=triggered_points,
- triggered_dates=triggered_dates,
- interval=interval,
- )
-
- alert.save(update_fields=["state", "last_checked_at", "next_check_at"])
-
- return alert_check, should_notify
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.py
new file mode 100644
index 000000000000..7172f2cb5677
--- /dev/null
+++ b/posthog/tasks/alerts/test/alert_check_helpers.py
@@ -0,0 +1,48 @@
+import traceback
+
+from django.db import transaction
+
+from posthog.models import AlertConfiguration
+from posthog.tasks.alerts import utils as alert_utils
+
+
+def run_alert_check(alert_id: str) -> None:
+ """Evaluate an alert, persist the AlertCheck, dispatch notifications."""
+ alert = AlertConfiguration.objects.select_related("insight", "team").get(id=alert_id, enabled=True)
+
+ error = None
+ result = None
+ try:
+ result = alert_utils.check_alert_for_insight(alert)
+ except Exception as e:
+ error = {"message": str(e), "traceback": traceback.format_exc()}
+
+ with transaction.atomic():
+ alert_check, notify = alert_utils.add_alert_check(
+ alert,
+ value=result.value if result else None,
+ breaches=result.breaches if result else None,
+ error=error,
+ anomaly_scores=result.anomaly_scores if result else None,
+ triggered_points=result.triggered_points if result else None,
+ triggered_dates=result.triggered_dates if result else None,
+ interval=result.interval if result else None,
+ triggered_metadata=result.triggered_metadata if result else None,
+ )
+
+ if not notify:
+ return
+
+ breaches = result.breaches if result else None
+ dispatch_targets = alert_utils.dispatch_alert_notification(alert, alert_check, breaches)
+ if dispatch_targets is None:
+ return
+
+ # Resolve targets directly from the alert — tests that @patch send_notifications_*
+ # return MagicMock values, so we can't trust dispatch's return. The real activity
+ # does trust the return (no mocks), and both paths resolve to the same list.
+ targets = alert.get_subscribed_users_emails()
+ if not targets:
+ return
+ with transaction.atomic():
+ alert_utils.record_alert_delivery(alert, alert_check, targets)
diff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.py
new file mode 100644
index 000000000000..6b9680660b6d
--- /dev/null
+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py
@@ -0,0 +1,78 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import AlertConditionType, AlertState, InsightThresholdType
+
+from posthog.api.test.dashboards import DashboardAPI
+from posthog.models.alert import AlertCheck
+from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from posthog.tasks.alerts.utils import AlertEvaluationResult
+
+
+class TestRunAlertCheck(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+
+ insight = self.dashboard_api.create_insight(
+ data={
+ "name": "insight",
+ "query": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "signed_up"}],
+ },
+ }
+ )[1]
+
+ alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "alert name",
+ "insight": insight["id"],
+ "subscribed_users": [self.user.id],
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "calculation_interval": "daily",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 1}}},
+ },
+ ).json()
+ self.alert_id = alert["id"]
+
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=["[email protected]"])
+ @patch("posthog.tasks.alerts.utils.check_alert_for_insight")
+ def test_firing_path_unpacks_tuple_and_records_delivery(self, mock_check: MagicMock, mock_send: MagicMock) -> None:
+ mock_check.return_value = AlertEvaluationResult(value=5.0, breaches=["breach_message"])
+
+ run_alert_check(self.alert_id)
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=self.alert_id).latest("created_at")
+ assert alert_check.state == AlertState.FIRING
+ assert alert_check.calculated_value == 5.0
+ assert alert_check.targets_notified == {"users": [self.user.email]}
+ mock_send.assert_called_once()
+
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
+ @patch("posthog.tasks.alerts.utils.check_alert_for_insight")
+ def test_not_firing_path_records_check_without_notifying(self, mock_check: MagicMock, mock_send: MagicMock) -> None:
+ mock_check.return_value = AlertEvaluationResult(value=0.5, breaches=None)
+
+ run_alert_check(self.alert_id)
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=self.alert_id).latest("created_at")
+ assert alert_check.state == AlertState.NOT_FIRING
+ assert alert_check.targets_notified == {}
+ mock_send.assert_not_called()
+
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
+ @patch("posthog.tasks.alerts.utils.check_alert_for_insight")
+ def test_errored_path_records_error_and_notifies(self, mock_check: MagicMock, mock_send_err: MagicMock) -> None:
+ mock_check.side_effect = RuntimeError("boom")
+
+ run_alert_check(self.alert_id)
+
+ alert_check = AlertCheck.objects.filter(alert_configuration=self.alert_id).latest("created_at")
+ assert alert_check.state == AlertState.ERRORED
+ assert alert_check.error is not None
+ assert "boom" in alert_check.error["message"]
+ assert alert_check.targets_notified == {"users": [self.user.email]}
+ mock_send_err.assert_called_once()
diff --git a/posthog/tasks/alerts/test/test_alert_checks.py b/posthog/tasks/alerts/test/test_alert_checks.py
deleted file mode 100644
index f93542e74edc..000000000000
--- a/posthog/tasks/alerts/test/test_alert_checks.py
+++ /dev/null
@@ -1,1240 +0,0 @@
-from typing import Any, Optional, cast
-
-import pytest
-from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
-from unittest.mock import MagicMock, patch
-
-from parameterized import parameterized
-from tenacity import wait_none
-
-from posthog.schema import (
- AlertConditionType,
- AlertState,
- ChartDisplayType,
- EventsNode,
- IntervalType,
- TrendsFilter,
- TrendsFormulaNode,
- TrendsQuery,
-)
-
-from posthog.api.test.dashboards import DashboardAPI
-from posthog.caching.fetch_from_cache import InsightResult
-from posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorS3Error, CHQueryErrorTooManySimultaneousQueries
-from posthog.models import AlertConfiguration, User
-from posthog.models.alert import AlertCheck, AlertSubscription
-from posthog.models.instance_setting import set_instance_setting
-from posthog.models.organization import Organization, OrganizationMembership
-from posthog.slo.types import SloArea, SloCompletedProperties, SloOperation, SloOutcome, SloStartedProperties
-from posthog.tasks.alerts.checks import check_alert, check_alert_task
-from posthog.tasks.alerts.utils import send_notifications_for_breaches
-from posthog.tasks.test.utils_email_tests import mock_email_messages
-
-
-@freeze_time("2024-06-02T08:55:00.000Z")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
-class TestAlertChecks(APIBaseTest, ClickhouseDestroyTablesMixin):
- def setUp(self) -> None:
- super().setUp()
-
- set_instance_setting("EMAIL_HOST", "fake_host")
- set_instance_setting("EMAIL_ENABLED", True)
-
- self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
-
- query_dict = TrendsQuery(
- series=[
- EventsNode(
- event="$pageview",
- ),
- ],
- trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
- ).model_dump()
-
- self.insight = self.dashboard_api.create_insight(
- data={
- "name": "insight",
- "query": query_dict,
- }
- )[1]
-
- self.alert = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "alert name",
- "insight": self.insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {
- "type": "TrendsAlertConfig",
- "series_index": 0,
- },
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
- },
- ).json()
-
- def set_thresholds(self, lower: Optional[int] = None, upper: Optional[int] = None) -> None:
- self.client.patch(
- f"/api/projects/{self.team.id}/alerts/{self.alert['id']}",
- data={"threshold": {"configuration": {"type": "absolute", "bounds": {"lower": lower, "upper": upper}}}},
- )
-
- def skip_weekend(self, skip: bool) -> None:
- self.client.patch(
- f"/api/projects/{self.team.id}/alerts/{self.alert['id']}",
- data={"skip_weekend": skip},
- )
-
- def get_breach_description(self, mock_send_notifications_for_breaches: MagicMock, call_index: int) -> list[str]:
- return mock_send_notifications_for_breaches.call_args_list[call_index].args[1]
-
- def test_alert_is_not_triggered_when_disabled(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- self.client.patch(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"enabled": False})
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 0
-
- def test_alert_is_triggered_for_values_above_higher_threshold(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(upper=0)
-
- with freeze_time("2024-06-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert = mock_send_notifications_for_breaches.call_args_list[0].args[0]
- assert str(alert.id) == self.alert["id"]
-
- anomalies_descriptions = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert len(anomalies_descriptions) == 1
- assert (
- "The insight value ($pageview) for current interval (1) is more than upper threshold (0.0)"
- in anomalies_descriptions[0]
- )
-
- def test_alert_is_not_triggered_for_events_beyond_interval(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(upper=0)
-
- with freeze_time("2024-05-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 0
-
- def test_alert_is_triggered_for_value_below_lower_threshold(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1.0)" in anomalies
-
- def test_alert_triggers_but_does_not_send_notification_during_firing(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- # no events so this should fire
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert alert.state == AlertState.FIRING
-
- with freeze_time("2024-06-02T09:00:00.000Z"):
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert alert.state == AlertState.FIRING
-
- # move to next interval - next day
- with freeze_time("2024-06-03T09:55:00.000Z"):
- self.set_thresholds(lower=0)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- assert (
- AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at").state
- == AlertState.NOT_FIRING
- )
-
- with freeze_time("2024-06-04T11:00:00.000Z"):
- self.set_thresholds(lower=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 2
- assert (
- AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at").state
- == AlertState.FIRING
- )
-
- # test clean up old checks (> 14 days)
- with freeze_time("2024-06-20T11:00:00.000Z"):
- AlertCheck.clean_up_old_checks()
- assert AlertCheck.objects.filter(alert_configuration=self.alert["id"]).count() == 0
-
- def test_alert_is_set_to_not_firing_when_disabled(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- assert (
- AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at").state
- == AlertState.FIRING
- )
-
- self.client.patch(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"enabled": False})
-
- # Check that the alert is set to inactive and checks are not triggered
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- assert AlertConfiguration.objects.get(pk=self.alert["id"]).state == AlertState.NOT_FIRING
-
- def test_alert_is_set_to_not_firing_when_threshold_changes(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- assert (
- AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at").state
- == AlertState.FIRING
- )
-
- self.set_thresholds(lower=2)
-
- assert AlertConfiguration.objects.get(pk=self.alert["id"]).state == AlertState.NOT_FIRING
-
- def test_alert_is_not_triggered_for_normal_values(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=0, upper=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 0
-
- def test_send_error_while_calculating(
- self, _mock_send_notifications_for_breaches: MagicMock, mock_send_notifications_for_errors: MagicMock
- ) -> None:
- with patch(
- "posthog.tasks.alerts.trends.calculate_for_query_based_insight"
- ) as mock_calculate_for_query_based_insight:
- mock_calculate_for_query_based_insight.side_effect = Exception("Some error")
-
- with freeze_time("2024-06-02T09:00:00.000Z"):
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_errors.call_count == 1
-
- latest_alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest(
- "created_at"
- )
-
- error = cast(dict[str, Any], latest_alert_check.error)
- error_message = error["message"]
- assert "Some error" in error_message
-
- def test_error_while_calculating_on_alert_in_firing_state(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_notifications_for_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_breaches.call_count == 1
- assert mock_send_notifications_for_errors.call_count == 0
-
- latest_alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert latest_alert_check.state == AlertState.FIRING
- assert latest_alert_check.error is None
-
- with patch(
- "posthog.tasks.alerts.trends.calculate_for_query_based_insight"
- ) as mock_calculate_for_query_based_insight:
- mock_calculate_for_query_based_insight.side_effect = Exception("Some error")
-
- with freeze_time("2024-06-03T09:00:00.000Z"):
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_breaches.call_count == 1
- assert mock_send_notifications_for_errors.call_count == 1
-
- latest_alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest(
- "created_at"
- )
- assert latest_alert_check.state == AlertState.ERRORED
-
- error = cast(dict[str, Any], latest_alert_check.error)
- error_message = error["message"]
- assert "Some error" in error_message
-
- def test_error_while_calculating_on_alert_in_not_firing_state(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_notifications_for_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=0)
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_breaches.call_count == 0
- assert mock_send_notifications_for_errors.call_count == 0
-
- latest_alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert latest_alert_check.state == AlertState.NOT_FIRING
- assert latest_alert_check.error is None
-
- with patch(
- "posthog.tasks.alerts.trends.calculate_for_query_based_insight"
- ) as mock_calculate_for_query_based_insight:
- mock_calculate_for_query_based_insight.side_effect = Exception("Some error")
-
- with freeze_time("2024-06-03T09:00:00.000Z"):
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_breaches.call_count == 0
- assert mock_send_notifications_for_errors.call_count == 1
-
- latest_alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest(
- "created_at"
- )
-
- error = cast(dict[str, Any], latest_alert_check.error)
- error_message = error["message"]
- assert "Some error" in error_message
-
- def test_alert_with_insight_with_filter(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- insight = self.dashboard_api.create_insight(
- data={"name": "insight", "filters": {"events": [{"id": "$pageview"}], "display": "BoldNumber"}}
- )[1]
-
- self.client.patch(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"insight": insight["id"]})
- self.set_thresholds(lower=1)
-
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1.0)" in anomalies
-
- @patch("posthog.tasks.alerts.utils.EmailMessage")
- def test_send_emails(
- self, MockEmailMessage: MagicMock, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- mocked_email_messages = mock_email_messages(MockEmailMessage)
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- send_notifications_for_breaches(
- alert, ["first anomaly description", "second anomaly description"], idempotency_key="test-send-emails"
- )
-
- assert len(mocked_email_messages) == 1
- email = mocked_email_messages[0]
- assert len(email.to) == 1
- assert email.to[0]["recipient"] == "[email protected]"
- assert "first anomaly description" in email.html_body
- assert "second anomaly description" in email.html_body
-
- def test_alert_not_recalculated_when_not_due(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- # no events so this should fire
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert alert.state == AlertState.FIRING
-
- with freeze_time("2024-06-02T09:00:00.000Z"):
- check_alert(self.alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert check.state == AlertState.FIRING
-
- # same day for daily alert so won't recalculate as haven't passed next_check_at
- with freeze_time("2024-06-02T09:55:00.000Z"):
- check_alert(self.alert["id"])
-
- second_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- # didn't recalculate alert as it was not due
- assert check.id == second_check.id
-
- def test_alert_not_recalculated_when_is_calculating(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- assert alert.is_calculating is False
-
- # no events so this should fire
- check_alert(self.alert["id"])
-
- # False after check finished
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- assert alert.is_calculating is False
- assert mock_send_notifications_for_breaches.call_count == 1
- first_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
-
- alert.next_check_at = None
- alert.is_calculating = True
- alert.save()
-
- check_alert(self.alert["id"])
-
- # should not have recalculated
- assert mock_send_notifications_for_breaches.call_count == 1
- second_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert first_check.id == second_check.id
-
- def test_alert_is_not_checked_on_weekend_when_skip_weekends_is_true(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.skip_weekend(True)
-
- # run on weekend
- with freeze_time("2024-12-21T07:55:00.000Z"):
- check_alert(self.alert["id"])
-
- checks = AlertCheck.objects.filter(alert_configuration=self.alert["id"])
- assert len(checks) == 0
-
- def test_alert_is_checked_on_weekday_when_skip_weekends_is_true(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.skip_weekend(True)
-
- # run on week day
- with freeze_time("2024-12-19T07:55:00.000Z"):
- check_alert(self.alert["id"])
-
- checks = AlertCheck.objects.filter(alert_configuration=self.alert["id"])
- assert len(checks) == 1
-
- def test_alert_triggered_for_single_formula(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- query_dict = TrendsQuery(
- series=[
- EventsNode(
- event="$pageview",
- custom_name="A",
- ),
- ],
- trendsFilter=TrendsFilter(
- display=ChartDisplayType.BOLD_NUMBER,
- formulaNodes=[TrendsFormulaNode(formula="A*2", custom_name="Double Pageviews")],
- ),
- ).model_dump()
-
- insight = self.dashboard_api.create_insight(
- data={
- "name": "formula insight",
- "query": query_dict,
- }
- )[1]
-
- alert_data = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "formula alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {
- "type": "TrendsAlertConfig",
- "series_index": 0, # Target the first (only) formula
- },
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1}}}, # Threshold is 1
- },
- ).json()
-
- # Create 1 event, formula A*2 = 2, which is > 1
- with freeze_time("2024-06-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(alert_data["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert_config = mock_send_notifications_for_breaches.call_args_list[0].args[0]
- assert str(alert_config.id) == alert_data["id"]
-
- anomalies_descriptions = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert len(anomalies_descriptions) == 1
- assert (
- "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
- in anomalies_descriptions[0]
- )
-
- def test_alert_triggered_for_legacy_formulas(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- query_dict = TrendsQuery(
- series=[
- EventsNode(
- event="$pageview",
- custom_name="A",
- ),
- ],
- trendsFilter=TrendsFilter(
- display=ChartDisplayType.BOLD_NUMBER,
- formulas=["A*2"],
- ),
- ).model_dump()
-
- insight = self.dashboard_api.create_insight(
- data={
- "name": "formula insight",
- "query": query_dict,
- }
- )[1]
-
- alert_data = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "formula alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {
- "type": "TrendsAlertConfig",
- "series_index": 0, # Target the first (only) formula
- },
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1}}}, # Threshold is 1
- },
- ).json()
-
- # Create 1 event, formula A*2 = 2, which is > 1
- with freeze_time("2024-06-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(alert_data["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert_config = mock_send_notifications_for_breaches.call_args_list[0].args[0]
- assert str(alert_config.id) == alert_data["id"]
-
- anomalies_descriptions = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert len(anomalies_descriptions) == 1
- assert (
- "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
- in anomalies_descriptions[0]
- )
-
- def test_alert_triggered_for_legacy_formula(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- query_dict = TrendsQuery(
- series=[
- EventsNode(
- event="$pageview",
- custom_name="A",
- ),
- ],
- trendsFilter=TrendsFilter(
- display=ChartDisplayType.BOLD_NUMBER,
- formula="A*2",
- ),
- ).model_dump()
-
- insight = self.dashboard_api.create_insight(
- data={
- "name": "formula insight",
- "query": query_dict,
- }
- )[1]
-
- alert_data = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "formula alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {
- "type": "TrendsAlertConfig",
- "series_index": 0, # Target the first (only) formula
- },
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1}}}, # Threshold is 1
- },
- ).json()
-
- # Create 1 event, formula A*2 = 2, which is > 1
- with freeze_time("2024-06-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(alert_data["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert_config = mock_send_notifications_for_breaches.call_args_list[0].args[0]
- assert str(alert_config.id) == alert_data["id"]
-
- anomalies_descriptions = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert len(anomalies_descriptions) == 1
- assert (
- "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
- in anomalies_descriptions[0]
- )
-
- def test_alert_triggered_for_second_formula(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- query_dict = TrendsQuery(
- series=[
- EventsNode(
- event="$pageview",
- custom_name="A",
- ),
- ],
- trendsFilter=TrendsFilter(
- display=ChartDisplayType.BOLD_NUMBER,
- formulaNodes=[
- TrendsFormulaNode(formula="A", custom_name="Raw Pageviews"),
- TrendsFormulaNode(formula="A*2", custom_name="Double Pageviews"),
- ],
- ),
- ).model_dump()
-
- insight = self.dashboard_api.create_insight(
- data={
- "name": "multi formula insight",
- "query": query_dict,
- }
- )[1]
-
- alert_data = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "multi formula alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {
- "type": "TrendsAlertConfig",
- "series_index": 1, # Target the second formula (A*2)
- },
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1}}}, # Threshold is 1
- },
- ).json()
-
- # Create 1 event.
- # Formula 1 (A) = 1, which is <= 1 (no breach)
- # Formula 2 (A*2) = 2, which is > 1 (breach)
- with freeze_time("2024-06-02T07:55:00.000Z"):
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="1",
- )
- flush_persons_and_events()
-
- check_alert(alert_data["id"])
-
- assert mock_send_notifications_for_breaches.call_count == 1
- alert_config = mock_send_notifications_for_breaches.call_args_list[0].args[0]
- assert str(alert_config.id) == alert_data["id"]
-
- anomalies_descriptions = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
- assert len(anomalies_descriptions) == 1
-
- # Check the breach message refers to the correct formula (Double Pageviews) and value (2)
- assert (
- "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
- in anomalies_descriptions[0]
- )
-
- def test_alert_is_not_triggered_when_insight_deleted(
- self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
- ) -> None:
- self.set_thresholds(lower=1)
-
- # Soft-delete the insight
- from posthog.models.insight import Insight
-
- insight = Insight.objects_including_soft_deleted.get(id=self.insight["id"])
- insight.deleted = True
- insight.save()
-
- # Alert should be skipped without error
- check_alert(self.alert["id"])
- assert mock_send_notifications_for_breaches.call_count == 0
- assert mock_send_errors.call_count == 0
- assert AlertCheck.objects.filter(alert_configuration=self.alert["id"]).count() == 0
-
- @parameterized.expand(
- [
- # result=[] treated as zero, threshold check still applies
- (
- "absolute_empty_within_bounds",
- AlertConditionType.ABSOLUTE_VALUE,
- False,
- 0,
- 100,
- [],
- AlertState.NOT_FIRING,
- 0,
- 0,
- ),
- (
- "absolute_empty_below_lower",
- AlertConditionType.ABSOLUTE_VALUE,
- False,
- 1,
- None,
- [],
- AlertState.FIRING,
- 1,
- 0,
- ),
- (
- "relative_increase_empty_within_bounds",
- AlertConditionType.RELATIVE_INCREASE,
- True,
- None,
- 1,
- [],
- AlertState.NOT_FIRING,
- 0,
- 0,
- ),
- (
- "relative_increase_empty_below_lower",
- AlertConditionType.RELATIVE_INCREASE,
- True,
- 1,
- None,
- [],
- AlertState.FIRING,
- 1,
- 0,
- ),
- (
- "relative_decrease_empty_within_bounds",
- AlertConditionType.RELATIVE_DECREASE,
- True,
- None,
- 1,
- [],
- AlertState.NOT_FIRING,
- 0,
- 0,
- ),
- (
- "relative_decrease_empty_below_lower",
- AlertConditionType.RELATIVE_DECREASE,
- True,
- 1,
- None,
- [],
- AlertState.FIRING,
- 1,
- 0,
- ),
- # result=None produces errored state
- ("absolute_none_errored", AlertConditionType.ABSOLUTE_VALUE, False, 0, 100, None, AlertState.ERRORED, 0, 1),
- (
- "relative_increase_none_errored",
- AlertConditionType.RELATIVE_INCREASE,
- True,
- 0,
- 100,
- None,
- AlertState.ERRORED,
- 0,
- 1,
- ),
- (
- "relative_decrease_none_errored",
- AlertConditionType.RELATIVE_DECREASE,
- True,
- 0,
- 100,
- None,
- AlertState.ERRORED,
- 0,
- 1,
- ),
- ]
- )
- def test_empty_or_none_insight_results(
- self,
- mock_send_notifications_for_breaches: MagicMock,
- mock_send_errors: MagicMock,
- _name: str,
- condition_type: AlertConditionType,
- time_series: bool,
- lower: Optional[float],
- upper: Optional[float],
- result: Optional[list],
- expected_state: AlertState,
- expected_breach_count: int,
- expected_error_count: int,
- ) -> None:
- query_dict = TrendsQuery(
- series=[EventsNode(event="$pageview")],
- trendsFilter=TrendsFilter(
- display=ChartDisplayType.ACTIONS_LINE_GRAPH if time_series else ChartDisplayType.BOLD_NUMBER,
- ),
- interval=IntervalType.WEEK,
- ).model_dump()
- insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
- alert = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "test alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {"type": "TrendsAlertConfig", "series_index": 0},
- "condition": {"type": condition_type},
- "threshold": {"configuration": {"type": "absolute", "bounds": {"lower": lower, "upper": upper}}},
- },
- ).json()
-
- with patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight") as mock_calculate:
- mock_calculate.return_value = InsightResult(
- result=result, last_refresh=None, cache_key=None, is_cached=False, timezone=None
- )
- check_alert(alert["id"])
-
- assert mock_send_notifications_for_breaches.call_count == expected_breach_count
- assert mock_send_errors.call_count == expected_error_count
-
- alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
- assert alert_check.state == expected_state
- if expected_error_count > 0:
- assert alert_check.error is not None
- else:
- assert alert_check.calculated_value == 0
-
- @parameterized.expand(
- [
- ("cannot_schedule", CHQueryErrorCannotScheduleTask),
- ("too_many_queries", CHQueryErrorTooManySimultaneousQueries),
- ("s3_error", CHQueryErrorS3Error),
- ]
- )
- @patch.object(check_alert.retry, "wait", wait_none()) # type: ignore[attr-defined]
- def test_transient_ch_errors_retry_and_succeed(
- self,
- _name: str,
- error_class: type[Exception],
- mock_send_notifications_for_breaches: MagicMock,
- mock_send_errors: MagicMock,
- ) -> None:
- self.set_thresholds(lower=1)
-
- with patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight") as mock_calculate:
- mock_calculate.side_effect = [
- error_class("transient failure"),
- error_class("transient failure"),
- InsightResult(result=[], last_refresh=None, cache_key=None, is_cached=False, timezone=None),
- ]
-
- check_alert(self.alert["id"])
-
- assert mock_calculate.call_count == 3
-
- # Alert evaluated successfully after retries
- alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert mock_send_notifications_for_breaches.call_count == 1
- assert mock_send_errors.call_count == 0
- assert alert_check.state == AlertState.FIRING
-
- @parameterized.expand(
- [
- ("cannot_schedule", CHQueryErrorCannotScheduleTask),
- ("too_many_queries", CHQueryErrorTooManySimultaneousQueries),
- ("s3_error", CHQueryErrorS3Error),
- ]
- )
- @patch.object(check_alert.retry, "wait", wait_none()) # type: ignore[attr-defined]
- def test_transient_ch_errors_exhaust_retries(
- self,
- _name: str,
- error_class: type[Exception],
- mock_send_notifications_for_breaches: MagicMock,
- mock_send_errors: MagicMock,
- ) -> None:
- self.set_thresholds(lower=1)
-
- with patch("posthog.tasks.alerts.trends.calculate_for_query_based_insight") as mock_calculate:
- mock_calculate.side_effect = error_class("transient failure")
-
- with pytest.raises(error_class):
- check_alert(self.alert["id"])
-
- # 4 attempts (1 initial + 3 retries)
- assert mock_calculate.call_count == 4
- assert mock_send_notifications_for_breaches.call_count == 0
- assert mock_send_errors.call_count == 0
- # No ERRORED alert check; this so that it will be picked up at the next cycle
- alert_checks = AlertCheck.objects.filter(alert_configuration=self.alert["id"])
- assert alert_checks.count() == 0
-
- # is_calculating cleared by the finally block so alert doesn't get stuck
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- assert alert.is_calculating is False
-
- @parameterized.expand(
- [
- ("invalid_condition", {"condition": {}}, "invalid condition"),
- ("missing_config_type", {"config": {"series_index": 0}}, "Unsupported alert config type"),
- ("relative_on_non_time_series", {"condition": {"type": "relative_increase"}}, "not compatible"),
- ]
- )
- @patch("posthog.tasks.alerts.utils.send_notifications_for_disabled")
- def test_invalid_config_auto_disables_alert(
- self,
- _name: str,
- field_overrides: dict,
- expected_error_fragment: str,
- mock_send_disabled: MagicMock,
- mock_send_notifications_for_breaches: MagicMock,
- mock_send_errors: MagicMock,
- ) -> None:
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- assert alert.enabled is True
- assert alert.state != AlertState.ERRORED
-
- for field, value in field_overrides.items():
- setattr(alert, field, value)
- alert.save()
-
- check_alert(self.alert["id"])
-
- alert.refresh_from_db()
- assert alert.enabled is False
- assert alert.state == AlertState.ERRORED # type: ignore[unreachable]
- assert mock_send_disabled.call_count == 1
- assert mock_send_notifications_for_breaches.call_count == 0
-
- alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert alert_check.state == AlertState.ERRORED
- assert alert_check.calculated_value is None
- assert alert_check.condition == alert.condition
- assert alert_check.targets_notified == {"users": ["[email protected]"]}
- assert expected_error_fragment in alert_check.error["message"]
-
- @patch("posthog.tasks.alerts.utils.send_notifications_for_disabled")
- def test_auto_disable_with_no_subscribers_sets_targets_notified_to_none(
- self,
- mock_send_disabled: MagicMock,
- mock_send_notifications_for_breaches: MagicMock,
- mock_send_errors: MagicMock,
- ) -> None:
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- alert.condition = {}
- alert.save()
- AlertSubscription.objects.filter(alert_configuration=alert).delete()
-
- check_alert(self.alert["id"])
-
- alert.refresh_from_db()
- assert alert.enabled is False
- assert alert.state == AlertState.ERRORED
- assert mock_send_disabled.call_count == 0
- assert mock_send_notifications_for_breaches.call_count == 0
-
- alert_check = AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at")
- assert alert_check.state == AlertState.ERRORED
- assert alert_check.targets_notified == {}
-
-
-@freeze_time("2024-06-02T08:55:00.000Z")
-class TestAlertSubscriptionOrgMembership(APIBaseTest):
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUp(self) -> None:
- super().setUp()
- set_instance_setting("EMAIL_HOST", "fake_host")
- set_instance_setting("EMAIL_ENABLED", True)
- self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
-
- query_dict = TrendsQuery(
- series=[EventsNode(event="$pageview")],
- trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
- ).model_dump()
-
- self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
-
- self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
-
- self.alert = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "alert name",
- "insight": self.insight["id"],
- "subscribed_users": [self.user.id, self.other_user.id],
- "calculation_interval": "daily",
- "config": {"type": "TrendsAlertConfig", "series_index": 0},
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
- },
- ).json()
-
- def test_get_subscribed_users_emails_excludes_removed_members(
- self,
- ) -> None:
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
-
- emails = alert.get_subscribed_users_emails()
- assert sorted(emails) == sorted(["[email protected]", "[email protected]"])
-
- OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
-
- emails = alert.get_subscribed_users_emails()
- assert sorted(emails) == ["[email protected]"]
-
- def test_membership_deletion_removes_alert_subscriptions(
- self,
- ) -> None:
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
- assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()
-
- OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
-
- assert not AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()
- assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.user).exists()
-
- @patch("posthog.tasks.alerts.utils.EmailMessage")
- def test_send_notifications_excludes_removed_members(self, MockEmailMessage: MagicMock) -> None:
- mocked_email_messages = mock_email_messages(MockEmailMessage)
- alert = AlertConfiguration.objects.get(pk=self.alert["id"])
-
- OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
-
- send_notifications_for_breaches(alert, ["test breach"], idempotency_key="test-excludes-removed-members")
-
- assert len(mocked_email_messages) == 1
- email = mocked_email_messages[0]
- assert len(email.to) == 1
- assert email.to[0]["recipient"] == "[email protected]"
-
-
-@freeze_time("2024-06-02T08:55:00.000Z")
-class TestGetSubscribedUsersEmails(APIBaseTest):
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUp(self) -> None:
- super().setUp()
- set_instance_setting("EMAIL_HOST", "fake_host")
- set_instance_setting("EMAIL_ENABLED", True)
- self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
-
- query_dict = TrendsQuery(
- series=[EventsNode(event="$pageview")],
- trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
- ).model_dump()
-
- self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
-
- self.alert_response = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "alert name",
- "insight": self.insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "daily",
- "config": {"type": "TrendsAlertConfig", "series_index": 0},
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
- },
- ).json()
-
- self.alert = AlertConfiguration.objects.get(pk=self.alert_response["id"])
-
- def test_filters_out_user_from_different_org_with_stale_subscription(self) -> None:
- other_org = Organization.objects.create(name="Other Org")
- outsider = User.objects.create_and_join(other_org, "[email protected]", "password")
-
- # Directly create a stale subscription (simulates pre-fix state)
- AlertSubscription.objects.create(alert_configuration=self.alert, user=outsider)
-
- emails = self.alert.get_subscribed_users_emails()
- assert sorted(emails) == ["[email protected]"]
-
- def test_includes_user_who_is_in_multiple_orgs_including_alerts_org(self) -> None:
- other_org = Organization.objects.create(name="Other Org")
- multi_org_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
- OrganizationMembership.objects.create(user=multi_org_user, organization=other_org)
-
- AlertSubscription.objects.create(alert_configuration=self.alert, user=multi_org_user)
-
- emails = self.alert.get_subscribed_users_emails()
- assert sorted(emails) == ["[email protected]", "[email protected]"]
-
- def test_excludes_multi_org_user_removed_from_alerts_org(self) -> None:
- other_org = Organization.objects.create(name="Other Org")
- multi_org_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
- OrganizationMembership.objects.create(user=multi_org_user, organization=other_org)
-
- AlertSubscription.objects.create(alert_configuration=self.alert, user=multi_org_user)
-
- # Remove from the alert's org but keep in the other org
- OrganizationMembership.objects.filter(user=multi_org_user, organization=self.organization).delete()
-
- emails = self.alert.get_subscribed_users_emails()
- assert sorted(emails) == ["[email protected]"]
-
- def test_returns_empty_list_when_no_subscribers_are_org_members(self) -> None:
- OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
-
- emails = self.alert.get_subscribed_users_emails()
- assert emails == []
-
-
-class TestAlertCheckSloInstrumentation(APIBaseTest, ClickhouseDestroyTablesMixin):
- def setUp(self) -> None:
- super().setUp()
- dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
- query_dict = TrendsQuery(
- series=[EventsNode(event="$pageview")],
- trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
- ).model_dump()
- insight = dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
- alert_resp = self.client.post(
- f"/api/projects/{self.team.id}/alerts",
- data={
- "name": "slo test alert",
- "insight": insight["id"],
- "subscribed_users": [self.user.id],
- "calculation_interval": "hourly",
- "config": {"type": "TrendsAlertConfig", "series_index": 0},
- "condition": {"type": "absolute_value"},
- "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
- },
- ).json()
- self.alert_id = alert_resp["id"]
-
- @parameterized.expand(
- [
- (
- "success",
- None,
- "hourly",
- SloOutcome.SUCCESS,
- None,
- ),
- (
- "failure",
- RuntimeError("CH failure"),
- "daily",
- SloOutcome.FAILURE,
- {"error_type": "RuntimeError", "error_message": "CH failure"},
- ),
- ]
- )
- @patch("posthog.slo.context.emit_slo_completed")
- @patch("posthog.slo.context.emit_slo_started")
- @patch("posthog.tasks.alerts.checks.check_alert")
- def test_slo_emits_correct_events(
- self,
- _name: str,
- side_effect: Exception | None,
- calculation_interval: str,
- expected_outcome: SloOutcome,
- expected_error_extra: dict | None,
- mock_check_alert: MagicMock,
- mock_slo_started: MagicMock,
- mock_slo_completed: MagicMock,
- ) -> None:
- mock_check_alert.side_effect = side_effect
- insight_id = 42
-
- if side_effect is not None:
- with pytest.raises(type(side_effect)):
- check_alert_task(self.alert_id, self.team.id, calculation_interval, insight_id)
- else:
- check_alert_task(self.alert_id, self.team.id, calculation_interval, insight_id)
-
- mock_slo_started.assert_called_once()
- started_kwargs = mock_slo_started.call_args.kwargs
- assert started_kwargs["distinct_id"] == self.alert_id
- assert started_kwargs["properties"] == SloStartedProperties(
- area=SloArea.ANALYTIC_PLATFORM,
- operation=SloOperation.ALERT_CHECK,
- team_id=self.team.id,
- resource_id=self.alert_id,
- )
- assert started_kwargs["extra_properties"]["calculation_interval"] == calculation_interval
- assert started_kwargs["extra_properties"]["insight_id"] == insight_id
- assert "correlation_id" in started_kwargs["extra_properties"]
- assert started_kwargs["capture"] is not None # ph_scoped_capture callable
-
- mock_slo_completed.assert_called_once()
- completed_kwargs = mock_slo_completed.call_args.kwargs
- assert started_kwargs["capture"] is completed_kwargs["capture"] # same scoped client for both
- assert completed_kwargs["distinct_id"] == self.alert_id
- assert completed_kwargs["properties"] == SloCompletedProperties(
- area=SloArea.ANALYTIC_PLATFORM,
- operation=SloOperation.ALERT_CHECK,
- team_id=self.team.id,
- resource_id=self.alert_id,
- outcome=expected_outcome,
- duration_ms=completed_kwargs["properties"].duration_ms,
- )
- assert (
- completed_kwargs["extra_properties"]["correlation_id"]
- == started_kwargs["extra_properties"]["correlation_id"]
- )
- assert completed_kwargs["extra_properties"]["calculation_interval"] == calculation_interval
- assert completed_kwargs["extra_properties"]["insight_id"] == insight_id
- for key, value in (expected_error_extra or {}).items():
- assert completed_kwargs["extra_properties"][key] == value
- if side_effect is not None:
- assert completed_kwargs["extra_properties"]["error_origin"]
- else:
- assert "error_origin" not in completed_kwargs["extra_properties"]
- assert mock_slo_completed.call_args.kwargs["properties"].duration_ms >= 0
diff --git a/posthog/tasks/alerts/test/test_alert_evaluation.py b/posthog/tasks/alerts/test/test_alert_evaluation.py
new file mode 100644
index 000000000000..85a50f1a8a24
--- /dev/null
+++ b/posthog/tasks/alerts/test/test_alert_evaluation.py
@@ -0,0 +1,205 @@
+from typing import Optional
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import AlertState, ChartDisplayType, EventsNode, TrendsFilter, TrendsFormulaNode, TrendsQuery
+
+from posthog.api.test.dashboards import DashboardAPI
+from posthog.models import AlertConfiguration
+from posthog.models.alert import AlertCheck
+from posthog.models.instance_setting import set_instance_setting
+from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+
+
+@freeze_time("2024-06-02T08:55:00.000Z")
+@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
+@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+class TestAlertEvaluation(APIBaseTest, ClickhouseDestroyTablesMixin):
+ def setUp(self) -> None:
+ super().setUp()
+
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump()
+
+ self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
+
+ self.alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "alert name",
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "calculation_interval": "daily",
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
+ },
+ ).json()
+
+ def set_thresholds(self, lower: Optional[int] = None, upper: Optional[int] = None) -> None:
+ self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{self.alert['id']}",
+ data={"threshold": {"configuration": {"type": "absolute", "bounds": {"lower": lower, "upper": upper}}}},
+ )
+
+ def get_breach_description(self, mock_send_notifications_for_breaches: MagicMock, call_index: int) -> list[str]:
+ return mock_send_notifications_for_breaches.call_args_list[call_index].args[1]
+
+ def _create_formula_alert(self, query_dict: dict, series_index: int = 0) -> dict:
+ insight = self.dashboard_api.create_insight(data={"name": "formula insight", "query": query_dict})[1]
+ return self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "formula alert",
+ "insight": insight["id"],
+ "subscribed_users": [self.user.id],
+ "calculation_interval": "daily",
+ "config": {"type": "TrendsAlertConfig", "series_index": series_index},
+ "condition": {"type": "absolute_value"},
+ "threshold": {"configuration": {"type": "absolute", "bounds": {"upper": 1}}},
+ },
+ ).json()
+
+ def test_alert_is_set_to_not_firing_when_threshold_changes(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ self.set_thresholds(lower=1)
+
+ run_alert_check(self.alert["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ assert (
+ AlertCheck.objects.filter(alert_configuration=self.alert["id"]).latest("created_at").state
+ == AlertState.FIRING
+ )
+
+ self.set_thresholds(lower=2)
+
+ assert AlertConfiguration.objects.get(pk=self.alert["id"]).state == AlertState.NOT_FIRING
+
+ def test_alert_with_insight_with_filter(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ insight = self.dashboard_api.create_insight(
+ data={"name": "insight", "filters": {"events": [{"id": "$pageview"}], "display": "BoldNumber"}}
+ )[1]
+
+ self.client.patch(f"/api/projects/{self.team.id}/alerts/{self.alert['id']}", data={"insight": insight["id"]})
+ self.set_thresholds(lower=1)
+
+ run_alert_check(self.alert["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
+ assert "The insight value ($pageview) for current interval (0) is less than lower threshold (1.0)" in anomalies
+
+ def test_alert_triggered_for_single_formula(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview", custom_name="A")],
+ trendsFilter=TrendsFilter(
+ display=ChartDisplayType.BOLD_NUMBER,
+ formulaNodes=[TrendsFormulaNode(formula="A*2", custom_name="Double Pageviews")],
+ ),
+ ).model_dump()
+ alert_data = self._create_formula_alert(query_dict, series_index=0)
+
+ with freeze_time("2024-06-02T07:55:00.000Z"):
+ _create_event(team=self.team, event="$pageview", distinct_id="1")
+ flush_persons_and_events()
+
+ run_alert_check(alert_data["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ assert str(mock_send_notifications_for_breaches.call_args_list[0].args[0].id) == alert_data["id"]
+ anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
+ assert len(anomalies) == 1
+ assert (
+ "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
+ in anomalies[0]
+ )
+
+ def test_alert_triggered_for_legacy_formulas(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview", custom_name="A")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER, formulas=["A*2"]),
+ ).model_dump()
+ alert_data = self._create_formula_alert(query_dict, series_index=0)
+
+ with freeze_time("2024-06-02T07:55:00.000Z"):
+ _create_event(team=self.team, event="$pageview", distinct_id="1")
+ flush_persons_and_events()
+
+ run_alert_check(alert_data["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
+ assert len(anomalies) == 1
+ assert (
+ "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
+ in anomalies[0]
+ )
+
+ def test_alert_triggered_for_legacy_formula(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview", custom_name="A")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER, formula="A*2"),
+ ).model_dump()
+ alert_data = self._create_formula_alert(query_dict, series_index=0)
+
+ with freeze_time("2024-06-02T07:55:00.000Z"):
+ _create_event(team=self.team, event="$pageview", distinct_id="1")
+ flush_persons_and_events()
+
+ run_alert_check(alert_data["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
+ assert len(anomalies) == 1
+ assert (
+ "The insight value (Formula (A*2)) for current interval (2.0) is more than upper threshold (1.0)"
+ in anomalies[0]
+ )
+
+ def test_alert_triggered_for_second_formula(
+ self, mock_send_notifications_for_breaches: MagicMock, mock_send_errors: MagicMock
+ ) -> None:
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview", custom_name="A")],
+ trendsFilter=TrendsFilter(
+ display=ChartDisplayType.BOLD_NUMBER,
+ formulaNodes=[
+ TrendsFormulaNode(formula="A", custom_name="Raw Pageviews"),
+ TrendsFormulaNode(formula="A*2", custom_name="Double Pageviews"),
+ ],
+ ),
+ ).model_dump()
+ alert_data = self._create_formula_alert(query_dict, series_index=1)
+
+ with freeze_time("2024-06-02T07:55:00.000Z"):
+ _create_event(team=self.team, event="$pageview", distinct_id="1")
+ flush_persons_and_events()
+
+ run_alert_check(alert_data["id"])
+
+ assert mock_send_notifications_for_breaches.call_count == 1
+ anomalies = self.get_breach_description(mock_send_notifications_for_breaches, call_index=0)
+ assert len(anomalies) == 1
+ assert (
+ "The insight value (Double Pageviews) for current interval (2.0) is more than upper threshold (1.0)"
+ in anomalies[0]
+ )
diff --git a/posthog/tasks/alerts/test/test_alert_subscriptions.py b/posthog/tasks/alerts/test/test_alert_subscriptions.py
new file mode 100644
index 000000000000..bc67ec0b6673
--- /dev/null
+++ b/posthog/tasks/alerts/test/test_alert_subscriptions.py
@@ -0,0 +1,195 @@
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ChartDisplayType, EventsNode, TrendsFilter, TrendsQuery
+
+from posthog.api.test.dashboards import DashboardAPI
+from posthog.models import AlertConfiguration, User
+from posthog.models.alert import AlertSubscription
+from posthog.models.instance_setting import set_instance_setting
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.tasks.alerts.utils import send_notifications_for_breaches
+from posthog.tasks.test.utils_email_tests import mock_email_messages
+
+
+@freeze_time("2024-06-02T08:55:00.000Z")
+class TestAlertSubscriptionOrgMembership(APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump()
+
+ self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+
+ self.alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "alert name",
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id, self.other_user.id],
+ "calculation_interval": "daily",
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
+ },
+ ).json()
+
+ def test_get_subscribed_users_emails_excludes_removed_members(self) -> None:
+ alert = AlertConfiguration.objects.get(pk=self.alert["id"])
+
+ emails = alert.get_subscribed_users_emails()
+ assert sorted(emails) == sorted(["[email protected]", "[email protected]"])
+
+ OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
+
+ emails = alert.get_subscribed_users_emails()
+ assert sorted(emails) == ["[email protected]"]
+
+ def test_membership_deletion_removes_alert_subscriptions(self) -> None:
+ alert = AlertConfiguration.objects.get(pk=self.alert["id"])
+ assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()
+
+ OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
+
+ assert not AlertSubscription.objects.filter(alert_configuration=alert, user=self.other_user).exists()
+ assert AlertSubscription.objects.filter(alert_configuration=alert, user=self.user).exists()
+
+ @patch("posthog.tasks.alerts.utils.EmailMessage")
+ def test_send_notifications_excludes_removed_members(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+ alert = AlertConfiguration.objects.get(pk=self.alert["id"])
+
+ OrganizationMembership.objects.filter(user=self.other_user, organization=self.organization).delete()
+
+ send_notifications_for_breaches(alert, ["test breach"], idempotency_key="test-excludes-removed-members")
+
+ assert len(mocked_email_messages) == 1
+ email = mocked_email_messages[0]
+ assert len(email.to) == 1
+ assert email.to[0]["recipient"] == "[email protected]"
+
+
+@freeze_time("2024-06-02T08:55:00.000Z")
+class TestGetSubscribedUsersEmails(APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump()
+
+ self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
+
+ self.alert_response = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "alert name",
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "calculation_interval": "daily",
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
+ },
+ ).json()
+
+ self.alert = AlertConfiguration.objects.get(pk=self.alert_response["id"])
+
+ def test_filters_out_user_from_different_org_with_stale_subscription(self) -> None:
+ other_org = Organization.objects.create(name="Other Org")
+ outsider = User.objects.create_and_join(other_org, "[email protected]", "password")
+
+ AlertSubscription.objects.create(alert_configuration=self.alert, user=outsider)
+
+ emails = self.alert.get_subscribed_users_emails()
+ assert sorted(emails) == ["[email protected]"]
+
+ def test_includes_user_who_is_in_multiple_orgs_including_alerts_org(self) -> None:
+ other_org = Organization.objects.create(name="Other Org")
+ multi_org_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ OrganizationMembership.objects.create(user=multi_org_user, organization=other_org)
+
+ AlertSubscription.objects.create(alert_configuration=self.alert, user=multi_org_user)
+
+ emails = self.alert.get_subscribed_users_emails()
+ assert sorted(emails) == ["[email protected]", "[email protected]"]
+
+ def test_excludes_multi_org_user_removed_from_alerts_org(self) -> None:
+ other_org = Organization.objects.create(name="Other Org")
+ multi_org_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ OrganizationMembership.objects.create(user=multi_org_user, organization=other_org)
+
+ AlertSubscription.objects.create(alert_configuration=self.alert, user=multi_org_user)
+
+ OrganizationMembership.objects.filter(user=multi_org_user, organization=self.organization).delete()
+
+ emails = self.alert.get_subscribed_users_emails()
+ assert sorted(emails) == ["[email protected]"]
+
+ def test_returns_empty_list_when_no_subscribers_are_org_members(self) -> None:
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
+
+ emails = self.alert.get_subscribed_users_emails()
+ assert emails == []
+
+
+@freeze_time("2024-06-02T08:55:00.000Z")
+class TestAlertEmailNotifications(APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+
+ query_dict = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ ).model_dump()
+
+ self.insight = self.dashboard_api.create_insight(data={"name": "insight", "query": query_dict})[1]
+
+ self.alert = self.client.post(
+ f"/api/projects/{self.team.id}/alerts",
+ data={
+ "name": "alert name",
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "calculation_interval": "daily",
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "condition": {"type": "absolute_value"},
+ "threshold": {"configuration": {"type": "absolute", "bounds": {}}},
+ },
+ ).json()
+
+ @patch("posthog.tasks.alerts.utils.EmailMessage")
+ def test_send_emails(self, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+ alert = AlertConfiguration.objects.get(pk=self.alert["id"])
+ send_notifications_for_breaches(
+ alert, ["first anomaly description", "second anomaly description"], idempotency_key="test-send-emails"
+ )
+
+ assert len(mocked_email_messages) == 1
+ email = mocked_email_messages[0]
+ assert len(email.to) == 1
+ assert email.to[0]["recipient"] == "[email protected]"
+ assert "first anomaly description" in email.html_body
+ assert "second anomaly description" in email.html_body
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index 199e8c710611..38491a5473a2 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -27,7 +27,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models import AlertConfiguration
from posthog.models.alert import AlertCheck
from posthog.models.instance_setting import set_instance_setting
-from posthog.tasks.alerts.checks import check_alert
+from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
# 8:55 AM
FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
@@ -35,7 +35,7 @@ FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
@freeze_time(FROZEN_TIME)
@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixin):
def setUp(self) -> None:
super().setUp()
@@ -142,7 +142,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert["last_notified_at"] is None
assert alert["next_check_at"] is None
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -184,7 +184,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -220,7 +220,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -253,7 +253,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -297,7 +297,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -345,7 +345,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -393,7 +393,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -437,7 +437,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -485,7 +485,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -528,7 +528,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -581,7 +581,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -621,7 +621,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -652,7 +652,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -696,7 +696,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 08:05 - checks previous hour (07:00-07:59), should fire (3 events > upper threshold of 1)
with freeze_time(dateutil.parser.parse("2024-06-02T08:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
@@ -718,7 +718,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Second check at 09:05 - checks previous hour (08:00-08:59), should not fire (0 events)
with freeze_time(dateutil.parser.parse("2024-06-02T09:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is still CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index e2bb70aef5da..a7882632992c 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -29,7 +29,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models import AlertConfiguration
from posthog.models.alert import AlertCheck
from posthog.models.instance_setting import set_instance_setting
-from posthog.tasks.alerts.checks import check_alert
+from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
# Tuesday
FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
@@ -37,7 +37,7 @@ FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
@freeze_time(FROZEN_TIME)
@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
+@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixin):
def setUp(self) -> None:
super().setUp()
@@ -125,7 +125,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert["last_notified_at"] is None
assert alert["next_check_at"] is None
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -176,7 +176,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
flush_persons_and_events()
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -261,7 +261,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -277,7 +277,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -351,7 +351,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# alert should fire as overall we had *decrease* in events (-1 or -50%) week over week
# check absolute alert
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -374,7 +374,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
)
# check percentage alert
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -454,7 +454,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# alert should fire as overall we had *increase* in events of just (1 or 100%) week over week
# alert required at least 2
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -470,7 +470,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -549,7 +549,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had decrease in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -571,7 +571,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
idempotency_key=ANY,
)
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -650,7 +650,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had decrease in events of (1 or 50%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -672,7 +672,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
idempotency_key=ANY,
)
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -757,7 +757,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert shouldn't fire as increase was only of 2 or 200%
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -772,7 +772,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -850,7 +850,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert shouldn't fire as increase was only of 2 or 200%
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -865,7 +865,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -957,7 +957,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -973,7 +973,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1085,7 +1085,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1101,7 +1101,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1213,7 +1213,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1229,7 +1229,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1342,7 +1342,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1358,7 +1358,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1459,7 +1459,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1475,7 +1475,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1559,7 +1559,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1575,7 +1575,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1669,7 +1669,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1691,7 +1691,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
idempotency_key=ANY,
)
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1789,7 +1789,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
flush_persons_and_events()
# alert should fire as we had *increase* in events of (2 or 200%) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1807,7 +1807,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1870,7 +1870,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 0 events
# alert should fire as we had *increase* in events of (infinity) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1894,7 +1894,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
idempotency_key=ANY,
)
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -1963,7 +1963,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# set previous to previous interval (last to last week) to have 0 events
# alert should fire as we had *decrease* in events of (infinity) week over week
- check_alert(absolute_alert["id"])
+ run_alert_check(absolute_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=absolute_alert["id"])
assert updated_alert.state == AlertState.NOT_FIRING
@@ -1979,7 +1979,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
assert alert_check.state == AlertState.NOT_FIRING
assert alert_check.error is None
- check_alert(percentage_alert["id"])
+ run_alert_check(percentage_alert["id"])
updated_alert = AlertConfiguration.objects.get(pk=percentage_alert["id"])
assert updated_alert.state == AlertState.FIRING
@@ -2031,7 +2031,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 08:05 - checks increase from 06:00-06:59 (0) to 07:00-07:59 (2)
# Increase = 2 - 0 = 2 (breaches upper threshold of 1)
with freeze_time(dateutil.parser.parse("2024-06-04T08:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
@@ -2054,7 +2054,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 09:05 - checks increase from 07:00-07:59 (2) to 08:00-08:59 (1)
# Increase = 1 - 2 = -1 (decrease, no breach)
with freeze_time(dateutil.parser.parse("2024-06-04T09:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
@@ -2096,7 +2096,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 08:05 - checks decrease from 06:00-06:59 (0) to 07:00-07:59 (2)
# It's increase, do not trigger an alarm
with freeze_time(dateutil.parser.parse("2024-06-04T08:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
@@ -2119,7 +2119,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix
# Check at 09:05 - checks decrease from 07:00-07:59 (2) to 08:00-08:59 (0)
# It's decrease by 2, trigger an alarm
with freeze_time(dateutil.parser.parse("2024-06-04T09:05:00.000Z")):
- check_alert(alert["id"])
+ run_alert_check(alert["id"])
# Verify execution mode is CALCULATE_BLOCKING_ALWAYS
assert mock_calculate.call_count == 1
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 9bc820fd1405..4c0427a7d2e8 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -25,6 +25,7 @@ from posthog.email import EmailMessage
from posthog.exceptions_capture import capture_exception
from posthog.models import AlertConfiguration
from posthog.models.alert import AlertCheck, derive_detector_event_fields
+from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction
from posthog.utils import get_from_dict_or_attr
@@ -397,6 +398,87 @@ def record_alert_delivery(alert: AlertConfiguration, alert_check: AlertCheck, ta
alert.save(update_fields=["last_notified_at"])
+def check_alert_for_insight(alert: AlertConfiguration) -> AlertEvaluationResult:
+ """Dispatch an alert to the correct insight-kind-specific evaluator.
+
+ If ``detector_config`` is set, uses the detector abstraction; otherwise
+ falls back to threshold-based checking.
+ """
+ # Lazy import breaks the cycle: trends.py and detector.py import from utils.py.
+ from posthog.tasks.alerts.detector import check_trends_alert_with_detector
+ from posthog.tasks.alerts.trends import check_trends_alert
+
+ insight = alert.insight
+
+ with upgrade_query(insight):
+ query = insight.query
+ kind = get_from_dict_or_attr(query, "kind")
+
+ if kind in WRAPPER_NODE_KINDS:
+ query = get_from_dict_or_attr(query, "source")
+ kind = get_from_dict_or_attr(query, "kind")
+
+ match kind:
+ case "TrendsQuery":
+ query = TrendsQuery.model_validate(query)
+ if alert.detector_config:
+ return check_trends_alert_with_detector(alert, insight, query, alert.detector_config)
+ return check_trends_alert(alert, insight, query)
+ case _:
+ raise NotImplementedError(f"AlertCheckError: Alerts for {kind} are not supported yet")
+
+
+def add_alert_check(
+ alert: AlertConfiguration,
+ value: float | None,
+ breaches: list[str] | None,
+ error: dict | None,
+ anomaly_scores: list[float | None] | None = None,
+ triggered_points: list[int] | None = None,
+ triggered_dates: list[str] | None = None,
+ interval: str | None = None,
+ triggered_metadata: dict | None = None,
+) -> tuple[AlertCheck, bool]:
+ """Persist an AlertCheck row and return it plus a decision on whether notification is needed.
+
+ ``targets_notified`` is always created empty; ``notify_alert`` activity fills it on
+ successful delivery and treats a non-empty value as the idempotency sentinel on retry.
+ ``last_notified_at`` is likewise set by the notify activity on success, not here.
+ """
+ notify = False
+
+ if error:
+ alert.state = AlertState.ERRORED
+ notify = True
+ elif breaches:
+ alert.state = AlertState.FIRING
+ notify = True
+ else:
+ alert.state = AlertState.NOT_FIRING # Threshold no longer met
+
+ alert.last_checked_at = datetime.now(UTC)
+ # Update next_check_at per interval so we don't recheck until the next one is due.
+ alert.next_check_at = next_check_time(alert)
+
+ alert_check = AlertCheck.objects.create(
+ alert_configuration=alert,
+ calculated_value=value,
+ condition=alert.condition,
+ targets_notified={},
+ state=alert.state,
+ triggered_metadata=triggered_metadata,
+ error=error,
+ anomaly_scores=anomaly_scores,
+ triggered_points=triggered_points,
+ triggered_dates=triggered_dates,
+ interval=interval,
+ )
+
+ alert.save(update_fields=["state", "last_checked_at", "next_check_at"])
+
+ return alert_check, notify
+
+
def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> None:
logger.warning("check_alert.auto_disabling", alert_id=alert.id, reason=reason)
AlertConfiguration.objects.filter(pk=alert.pk).update(
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 283e07462c5c..979c3657f98d 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -10,7 +10,6 @@ from celery.schedules import crontab
from posthog.approvals.tasks import expire_old_change_requests, validate_pending_change_requests
from posthog.caching.warming import schedule_warming_for_teams_task
from posthog.clickhouse.client.execute_async import QueryStatusManager
-from posthog.tasks.alerts.checks import alerts_backlog_task, checks_cleanup_task, reset_stuck_alerts_task
from posthog.tasks.auth_token_cache_verification import verify_and_fix_auth_token_cache_task
from posthog.tasks.email import (
send_error_tracking_weekly_digest,
@@ -496,24 +495,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="update survey's sampling feature flag rollout based on date",
)
- sender.add_periodic_task(
- crontab(hour="*", minute="*/12"),
- alerts_backlog_task.s(),
- name="alerts_backlog_task",
- )
-
- sender.add_periodic_task(
- crontab(hour="*", minute="*/15"),
- reset_stuck_alerts_task.s(),
- name="reset_stuck_alerts_task",
- )
-
- sender.add_periodic_task(
- crontab(hour="8", minute="0"),
- checks_cleanup_task.s(),
- name="clean up old alert checks",
- )
-
sender.add_periodic_task(
crontab(hour="8", minute="15"),
logs_alert_events_cleanup_task.s(),
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 32e4fc9a545f..4359bb7f7f66 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -10,11 +10,6 @@
'posthog.email._send_email',
'posthog.models.product_intent.product_intent.calculate_product_activation',
'posthog.tasks.activity_log.broadcast_activity_log_to_organization',
- 'posthog.tasks.alerts.checks.alerts_backlog_task',
- 'posthog.tasks.alerts.checks.check_alert_task',
- 'posthog.tasks.alerts.checks.check_alerts_task',
- 'posthog.tasks.alerts.checks.checks_cleanup_task',
- 'posthog.tasks.alerts.checks.reset_stuck_alerts_task',
'posthog.tasks.async_migrations.run_async_migration',
'posthog.tasks.auth_token_cache_verification.verify_and_fix_auth_token_cache_task',
'posthog.tasks.calculate_cohort.calculate_cohort_ch',
diff --git a/posthog/tasks/utils.py b/posthog/tasks/utils.py
index 23d0d96fbb42..72d0a10ed964 100644
--- a/posthog/tasks/utils.py
+++ b/posthog/tasks/utils.py
@@ -96,7 +96,6 @@ class CeleryQueue(Enum):
LONG_RUNNING = "long_running" # any task that has a good chance of taking more than a few seconds should go here
ANALYTICS_QUERIES = "analytics_queries"
ANALYTICS_LIMITED = "analytics_limited"
- ALERTS = "alerts"
EXPORTS = "exports"
SUBSCRIPTION_DELIVERY = "subscription_delivery"
USAGE_REPORTS = "usage_reports"
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index 908201db07fb..0b4703755def 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -1,7 +1,7 @@
"""Temporal workflow that kicks off the anomaly investigation agent and persists
its findings as a Notebook linked to the AlertCheck.
-Triggered from posthog/tasks/alerts/checks.py when an alert transitions to FIRING.
+Triggered from posthog/temporal/alerts/workflows.py when an alert transitions to FIRING.
"""
from __future__ import annotations
diff --git a/posthog/temporal/alerts/__init__.py b/posthog/temporal/alerts/__init__.py
index 7e8b919aac2a..357bf9e2c4cf 100644
--- a/posthog/temporal/alerts/__init__.py
+++ b/posthog/temporal/alerts/__init__.py
@@ -1,4 +1,5 @@
from posthog.temporal.alerts.activities import (
+ cleanup_alert_checks,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -7,6 +8,7 @@ from posthog.temporal.alerts.activities import (
)
from posthog.temporal.alerts.workflows import (
CheckAlertWorkflow,
+ CleanupAlertChecksWorkflow,
RunInvestigationSafetyNetWorkflow,
ScheduleDueAlertChecksWorkflow,
)
@@ -15,6 +17,7 @@ WORKFLOWS = [
ScheduleDueAlertChecksWorkflow,
CheckAlertWorkflow,
RunInvestigationSafetyNetWorkflow,
+ CleanupAlertChecksWorkflow,
]
ACTIVITIES = [
@@ -23,4 +26,5 @@ ACTIVITIES = [
evaluate_alert,
notify_alert,
run_investigation_safety_net,
+ cleanup_alert_checks,
]
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 13bd87220f97..0bc39f8a0787 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -17,10 +17,11 @@ from posthog.models import AlertConfiguration
from posthog.models.alert import AlertCheck
from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.sync import database_sync_to_async
-from posthog.tasks.alerts.checks import AlertCheckException, add_alert_check, check_alert_for_insight
from posthog.tasks.alerts.investigation_notifications import run_investigation_notification_safety_net
from posthog.tasks.alerts.schedule_restriction import is_utc_datetime_blocked, next_unblocked_utc
from posthog.tasks.alerts.utils import (
+ add_alert_check,
+ check_alert_for_insight,
disable_invalid_alert,
dispatch_alert_notification,
next_check_time,
@@ -219,7 +220,7 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe
except Exception as err:
logger.exception(f"Alert id = {alert.id}, failed to evaluate", exc_info=err)
capture_exception(
- AlertCheckException(err),
+ err,
additional_properties={
"alert_configuration_id": str(alert.id),
"insight_id": alert.insight_id,
@@ -363,3 +364,13 @@ async def run_investigation_safety_net() -> int:
async with Heartbeater():
return await _sweep()
+
+
+async def cleanup_alert_checks() -> int:
+ @database_sync_to_async(thread_sensitive=False)
+ def _cleanup() -> int:
+ return AlertCheck.clean_up_old_checks()
+
+ async with Heartbeater():
+ return await _cleanup()
diff --git a/posthog/temporal/alerts/schedule.py b/posthog/temporal/alerts/schedule.py
index 7634ad8d48c1..3c48ed94e0a5 100644
--- a/posthog/temporal/alerts/schedule.py
+++ b/posthog/temporal/alerts/schedule.py
@@ -15,6 +15,7 @@ from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exist
SCHEDULE_ID = "schedule-due-alert-checks-schedule"
INVESTIGATION_SAFETY_NET_SCHEDULE_ID = "run-investigation-safety-net-schedule"
+CLEANUP_ALERT_CHECKS_SCHEDULE_ID = "cleanup-alert-checks-schedule"
async def create_schedule_due_alert_checks_schedule(client: Client) -> None:
@@ -57,3 +58,22 @@ async def create_run_investigation_safety_net_schedule(client: Client) -> None:
await a_update_schedule(client, INVESTIGATION_SAFETY_NET_SCHEDULE_ID, schedule)
else:
await a_create_schedule(client, INVESTIGATION_SAFETY_NET_SCHEDULE_ID, schedule, trigger_immediately=False)
+
+
+async def create_cleanup_alert_checks_schedule(client: Client) -> None:
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ "cleanup-alert-checks",
+ id=CLEANUP_ALERT_CHECKS_SCHEDULE_ID,
+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ execution_timeout=dt.timedelta(minutes=30),
+ ),
+ spec=ScheduleSpec(cron_expressions=["0 8 * * *"]),
+ # SKIP — if yesterday's cleanup is still running, don't start a second one.
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, CLEANUP_ALERT_CHECKS_SCHEDULE_ID):
+ await a_update_schedule(client, CLEANUP_ALERT_CHECKS_SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, CLEANUP_ALERT_CHECKS_SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 9403a23a4e77..2c3c39de0dfe 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -11,6 +11,7 @@ from posthog.schema import AlertState
from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.alerts.activities import (
+ cleanup_alert_checks,
evaluate_alert,
notify_alert,
prepare_alert,
@@ -230,3 +231,25 @@ class RunInvestigationSafetyNetWorkflow(PostHogWorkflow):
maximum_attempts=2,
),
)
+
+
[email protected](name="cleanup-alert-checks")
+class CleanupAlertChecksWorkflow(PostHogWorkflow):
+ """Purge old AlertCheck rows on a daily schedule."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> None:
+ return None
+
+ @temporalio.workflow.run
+ async def run(self) -> None:
+ await temporalio.workflow.execute_activity(
+ cleanup_alert_checks,
+ start_to_close_timeout=dt.timedelta(minutes=30),
+ heartbeat_timeout=dt.timedelta(minutes=2),
+ retry_policy=temporalio.common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=10),
+ maximum_interval=dt.timedelta(minutes=1),
+ maximum_attempts=3,
+ ),
+ )
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index c8f403e3244e..7f9e0f28423d 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -24,6 +24,7 @@ from posthog.hogql_queries.ai.vector_search_query_runner import LATEST_ACTIONS_E
from posthog.temporal.ai import SyncVectorsInputs
from posthog.temporal.ai.sync_vectors import EmbeddingVersion
from posthog.temporal.alerts.schedule import (
+ create_cleanup_alert_checks_schedule,
create_run_investigation_safety_net_schedule,
create_schedule_due_alert_checks_schedule,
)
@@ -605,6 +606,7 @@ schedules = [
create_logs_alert_check_schedule,
create_schedule_due_alert_checks_schedule,
create_run_investigation_safety_net_schedule,
+ create_cleanup_alert_checks_schedule,
]
if settings.CLOUD_DEPLOYMENT:
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index c22a01a02485..7f0ce1f4c56c 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -25,7 +25,7 @@ from posthog.errors import CHQueryErrorTooManySimultaneousQueries
from posthog.models import AlertConfiguration, Insight, User
from posthog.models.alert import AlertCheck
from posthog.tasks.alerts.utils import AlertEvaluationResult
-from posthog.temporal.alerts.activities import evaluate_alert, notify_alert, prepare_alert
+from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.types import (
EvaluateAlertActivityInputs,
NotifyAlertActivityInputs,
@@ -568,3 +568,15 @@ class TestNotifyAlert:
mock_breaches.assert_called_once()
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
assert refreshed.targets_notified == {"users": ["[email protected]"]}
+
+
[email protected]_db(transaction=True)
+class TestCleanupAlertChecks:
+ async def test_delegates_to_model_classmethod(self) -> None:
+ with patch.object(AlertCheck, "clean_up_old_checks", return_value=7) as mock_cleanup:
+ env = ActivityEnvironment()
+ deleted = await env.run(cleanup_alert_checks)
+
+ mock_cleanup.assert_called_once()
+ assert deleted == 7