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.

refactor(alerts): migrate insight lifecycle to shared engine (#73959)

Matt Puaed9566d4dcc0
diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.md
index 54be8c2b6bca..84cac3824a64 100644
--- a/.agents/skills/adding-product-alerting/references/architecture.md
+++ b/.agents/skills/adding-product-alerting/references/architecture.md
@@ -13,9 +13,9 @@ Use this reference to decide where code belongs before editing it.
| Shared product alert UI | `products/alerts/frontend/components/` | Container-agnostic editor layout, definition primitives, advanced options, destination editor, schedule presentation, and evaluation chart |
| Product UI | `products/<name>/frontend/` or `frontend/src/scenes/<name>/` | Form logic, API calls, product fields, normalized adapters, entry points, detail tables, and wizard configuration |
-`products/logs` is the reference adopter for the shared lifecycle, fixed-cadence scheduling, HogFunction destinations, delivery rollback, product-owned Temporal orchestration, and the shared product alert editor components.
+`products/logs` is the reference adopter for fixed-cadence scheduling, HogFunction destinations, delivery rollback, product-owned Temporal orchestration, and the shared product alert editor components.
-Insight alerts are the reference adopter for shared calendar anchors, schedule restrictions, weekend skipping, and email delivery. Their model, API, query evaluation, and Django scheduling adapters live in `products/alerts/backend/` and `posthog/tasks/alerts/`. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.
+Logs and insight alerts both adapt their product state to the shared lifecycle engine. Insight alerts are also the reference adopter for shared calendar anchors, schedule restrictions, weekend skipping, and email delivery. Their model, API, query evaluation, and Django scheduling adapters live in `products/alerts/backend/` and `posthog/tasks/alerts/`. The evaluation package is shared across insight query kinds, but it is not a generic evaluator for unrelated products.
## Frontend contract
diff --git a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
index 0de68df81a5a..77d75962b40b 100644
--- a/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
+++ b/.semgrep/rules/security/alert-state-must-go-through-state-machine.yaml
@@ -1,44 +1,19 @@
-# Enforces the invariant that ALL writes to an alert configuration's `state` and
-# `consecutive_failures` go through the product's alert state machine module.
-#
-# The decision logic is shared across products in products/alerts/backend/state_machine.py;
-# each product owns one module that is the single legal mutator of its alert model:
-# - products/logs/backend/alert_state_machine.py (apply_outcome)
-#
-# There are dedicated helpers for every legal control-plane transition
-# (apply_user_reset, apply_enable, apply_disable, apply_snooze, apply_unsnooze,
-# apply_threshold_change), and the check-driven path goes through evaluate_alert_check.
-#
-# If you need a new transition, add a helper in products/alerts/backend/state_machine.py (or
-# the product's state machine module) rather than bypassing this rule — the point is
-# to keep the legal-transitions table readable in one place.
-#
-# When a new product adopts the shared machine, add its backend to paths.include and
-# its state machine module + tests to paths.exclude below.
+# Products decide whether an alert is triggered. Shared lifecycle code owns state
+# transitions, notification decisions, snoozing, and enable/disable behavior.
rules:
- - id: alert-state-direct-mutation
+ - id: logs-alert-state-direct-mutation
patterns:
- pattern-either:
- pattern: $ALERT.state = $VALUE
- pattern: $ALERT.consecutive_failures = $VALUE
+ - pattern: $ALERT.enabled = $VALUE
+ - pattern: $QUERY.update(..., state=$VALUE, ...)
+ - pattern: $QUERY.update(..., consecutive_failures=$VALUE, ...)
+ - pattern: $QUERY.update(..., enabled=$VALUE, ...)
message: |
- Direct mutation of an alert configuration's .state / .consecutive_failures
- bypasses the product's alert state machine module, which is the single
- source of truth for alert state transitions.
-
- Route state changes through the state machine instead, e.g. for logs:
-
- from products.logs.backend.alert_state_machine import (
- apply_outcome, apply_user_reset, apply_disable, ...
- )
-
- outcome = apply_user_reset(alert.to_snapshot())
- update_fields = apply_outcome(alert, outcome)
- alert.save(update_fields=update_fields)
-
- If you need a new transition type, add a helper in
- products/alerts/backend/state_machine.py (e.g. apply_<your_action>) and a
- ControlPlaneOutcome return — do not mutate these fields directly.
+ Direct mutation of a logs alert's lifecycle fields bypasses its state
+ machine adapter. Route the change through
+ products.logs.backend.alert_state_machine.
languages: [python]
severity: ERROR
metadata:
@@ -48,9 +23,39 @@ rules:
paths:
include:
- '/products/logs/backend/**/*.py'
+ - '/.semgrep/rules/security/tests/logs-alert-state-must-go-through-state-machine.py'
exclude:
- # The state machine itself — apply_outcome is the one legal mutator.
- '/products/logs/backend/alert_state_machine.py'
- # Test files — fixtures and parametrized snapshots set state directly.
- '/products/logs/backend/test/**'
- '/products/logs/backend/**/test_*.py'
+
+ - id: insight-alert-state-direct-mutation
+ patterns:
+ - pattern-either:
+ - pattern: $ALERT.state = $VALUE
+ - pattern: $ALERT.enabled = $VALUE
+ - pattern: $QUERY.update(..., state=$VALUE, ...)
+ - pattern: $QUERY.update(..., enabled=$VALUE, ...)
+ message: |
+ Direct mutation of an insight alert's lifecycle fields bypasses its state
+ machine adapter. Route the change through
+ products.alerts.backend.insight_alert_state_machine.
+ languages: [python]
+ severity: ERROR
+ metadata:
+ category: correctness
+ subcategory: audit
+ confidence: HIGH
+ paths:
+ include:
+ - '/products/alerts/backend/api/alert.py'
+ - '/products/alerts/backend/facade/api.py'
+ - '/products/alerts/backend/max_tools.py'
+ - '/products/alerts/backend/models/alert.py'
+ - '/posthog/tasks/alerts/**/*.py'
+ - '/posthog/temporal/alerts/**/*.py'
+ - '/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py'
+ exclude:
+ - '/products/alerts/backend/api/test/**'
+ - '/products/alerts/backend/**/test_*.py'
+ - '/posthog/tasks/alerts/test/**'
diff --git a/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py b/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py
new file mode 100644
index 000000000000..1f8d9f987aa1
--- /dev/null
+++ b/.semgrep/rules/security/tests/insight-alert-state-must-go-through-state-machine.py
@@ -0,0 +1,17 @@
+class AlertConfiguration:
+ enabled: bool
+ state: str
+
+
+def direct_mutations(alert: AlertConfiguration) -> None:
+ # ruleid: insight-alert-state-direct-mutation
+ alert.enabled = False
+ # ruleid: insight-alert-state-direct-mutation
+ alert.state = "firing"
+
+
+def queryset_mutations(queryset) -> None:
+ # ruleid: insight-alert-state-direct-mutation
+ queryset.update(enabled=False)
+ # ruleid: insight-alert-state-direct-mutation
+ queryset.update(state="firing")
diff --git a/.semgrep/rules/security/tests/logs-alert-state-must-go-through-state-machine.py b/.semgrep/rules/security/tests/logs-alert-state-must-go-through-state-machine.py
new file mode 100644
index 000000000000..5fdf319d1cf7
--- /dev/null
+++ b/.semgrep/rules/security/tests/logs-alert-state-must-go-through-state-machine.py
@@ -0,0 +1,22 @@
+class LogsAlertConfiguration:
+ enabled: bool
+ state: str
+ consecutive_failures: int
+
+
+def direct_mutations(alert: LogsAlertConfiguration) -> None:
+ # ruleid: logs-alert-state-direct-mutation
+ alert.enabled = False
+ # ruleid: logs-alert-state-direct-mutation
+ alert.state = "firing"
+ # ruleid: logs-alert-state-direct-mutation
+ alert.consecutive_failures = 1
+
+
+def queryset_mutations(queryset) -> None:
+ # ruleid: logs-alert-state-direct-mutation
+ queryset.update(enabled=False)
+ # ruleid: logs-alert-state-direct-mutation
+ queryset.update(state="firing")
+ # ruleid: logs-alert-state-direct-mutation
+ queryset.update(consecutive_failures=1)
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index 0460fe81fd2a..080c1032684c 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -1,11 +1,13 @@
from datetime import UTC, datetime
from freezegun import freeze_time
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
from posthog.schema import AlertCalculationInterval
-from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_time
+from posthog.tasks.alerts.utils import calculation_interval_to_order, next_check_time, trigger_alert_hog_functions
from products.alerts.backend.models.alert import AlertConfiguration
@@ -27,3 +29,63 @@ class TestAlertUtils:
with freeze_time("2026-04-06T14:00:00Z"):
assert next_check_time(alert) == datetime(2026, 4, 6, 14, 2, 0, tzinfo=UTC)
+
+ @parameterized.expand(
+ [
+ ("threshold", None, {"alert_mode": "threshold", "detector_type": None, "ensemble_operator": None}),
+ (
+ "detector",
+ {"type": "zscore", "threshold": 0.95, "window": 30},
+ {"alert_mode": "detector", "detector_type": "zscore", "ensemble_operator": None},
+ ),
+ (
+ "ensemble",
+ {
+ "type": "ensemble",
+ "operator": "AND",
+ "detectors": [
+ {"type": "zscore", "threshold": 0.95, "window": 30},
+ {"type": "mad", "threshold": 0.95, "window": 30},
+ ],
+ },
+ {"alert_mode": "detector", "detector_type": "ensemble", "ensemble_operator": "AND"},
+ ),
+ ]
+ )
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event")
+ def test_trigger_alert_hog_functions_uses_shared_delivery(
+ self,
+ _name: str,
+ detector_config: dict | None,
+ expected_props: dict,
+ mock_produce: MagicMock,
+ ) -> None:
+ mock_produce.return_value = MagicMock()
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.id = "00000000-0000-0000-0000-000000000001"
+ alert.name = "test alert"
+ alert.insight.name = "test insight"
+ alert.insight.short_id = "abcd1234"
+ alert.state = "firing"
+ alert.last_checked_at = None
+ alert.team_id = 2
+ alert.team.name = "test project"
+ alert.detector_config = detector_config
+
+ trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
+
+ props = mock_produce.call_args.kwargs["properties"]
+ for key, expected_value in expected_props.items():
+ assert props[key] == expected_value
+ assert props["breaches"] == "test breach"
+ assert "uuid" not in mock_produce.call_args.kwargs
+
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event", return_value=None)
+ def test_trigger_alert_hog_functions_ignores_enqueue_failure(self, _mock_produce: MagicMock) -> None:
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.id = "00000000-0000-0000-0000-000000000001"
+ alert.team_id = 2
+ alert.last_checked_at = None
+ alert.detector_config = None
+
+ trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 7a293784fe3b..42c1a2a90fb5 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -8,11 +8,16 @@ import structlog
from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
-from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
-from posthog.exceptions_capture import capture_exception
from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction
+from products.alerts.backend.destinations import produce_alert_internal_event
from products.alerts.backend.facade.api import send_alert_email
+from products.alerts.backend.insight_alert_state_machine import (
+ apply_invalid_configuration,
+ apply_outcome,
+ evaluate_alert_check,
+ should_notify,
+)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields
from products.alerts.backend.scheduling import (
EVERY_15_MINUTES_CADENCE_MINUTES as EVERY_15_MINUTES_CADENCE_MINUTES,
@@ -24,6 +29,8 @@ from products.alerts.backend.scheduling import (
logger = structlog.get_logger(__name__)
+INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"
+
@dataclass
class AlertEvaluationResult:
@@ -106,7 +113,7 @@ def next_check_time(alert: AlertConfiguration) -> datetime:
def next_check_at_after_schedule_restriction_change(alert: AlertConfiguration) -> datetime:
"""
After persisting a new schedule_restriction (or clearing it), compute next_check_at like
- ``mark_for_recheck`` + ``next_check_time`` (same as the worker after a check).
+ Clearing ``next_check_at`` before ``next_check_time`` matches the worker after a check.
We temporarily clear ``next_check_at`` so the interval math uses *now* (not a stale future instant).
Otherwise a previously snapped time (e.g. first minute after quiet hours) can stick at 4pm local
@@ -129,42 +136,23 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->
properties=properties,
)
- try:
- props = {
- "alert_id": str(alert.id),
- "alert_name": alert.name,
- "project_name": alert.team.name,
- "insight_name": alert.insight.name,
- "insight_id": alert.insight.short_id,
- "state": alert.state,
- "last_checked_at": alert.last_checked_at.isoformat() if alert.last_checked_at else None,
- **derive_detector_event_fields(alert.detector_config),
- **properties,
- }
-
- produce_internal_event(
- team_id=alert.team_id,
- event=InternalEventEvent(
- event="$insight_alert_firing",
- distinct_id=f"team_{alert.team_id}",
- properties=props,
- ),
- )
-
- except Exception as e:
- capture_exception(
- e,
- additional_properties={
- "alert_id": str(alert.id),
- "feature": "alerts",
- },
- )
- logger.error(
- "Failed to produce internal event for alert destinations/hog functions",
- alert_id=alert.id,
- error=str(e),
- exc_info=True,
- )
+ props = {
+ "alert_id": str(alert.id),
+ "alert_name": alert.name,
+ "project_name": alert.team.name,
+ "insight_name": alert.insight.name,
+ "insight_id": alert.insight.short_id,
+ "state": alert.state,
+ "last_checked_at": alert.last_checked_at.isoformat() if alert.last_checked_at else None,
+ **derive_detector_event_fields(alert.detector_config),
+ **properties,
+ }
+
+ produce_alert_internal_event(
+ team_id=alert.team_id,
+ event_name=INSIGHT_ALERT_FIRING_EVENT,
+ properties=props,
+ )
def send_notifications_for_breaches(
@@ -174,7 +162,7 @@ def send_notifications_for_breaches(
extra_properties: dict[str, str] | None = None,
) -> list[str]:
"""A stable idempotency_key (typically alert_check.id) lets MessagingRecord enforce
- per-recipient at-most-once delivery on retries.
+ per-recipient at-most-once email delivery on retries.
`extra_properties` are merged into the internal-event properties that HogFunction
destinations render (e.g. the anomaly investigation notebook URL for the Slack button).
@@ -203,7 +191,10 @@ def send_notifications_for_breaches(
# Join with newlines so each breach/investigation line renders on its own line in
# Slack/Discord/Teams destinations rather than as one run-on comma-separated string.
- trigger_alert_hog_functions(alert=alert, properties={"breaches": "\n".join(breaches), **(extra_properties or {})})
+ trigger_alert_hog_functions(
+ alert=alert,
+ properties={"breaches": "\n".join(breaches), **(extra_properties or {})},
+ )
return email_targets
@@ -317,16 +308,14 @@ def add_alert_check(
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
+ error_message = error.get("message") if error else None
+ outcome = evaluate_alert_check(
+ alert,
+ threshold_breached=bool(breaches),
+ error_message=error_message,
+ now=datetime.now(UTC),
+ )
+ state_fields = apply_outcome(alert, outcome)
alert.last_checked_at = datetime.now(UTC)
# Update next_check_at per interval so we don't recheck until the next one is due.
@@ -346,9 +335,9 @@ def add_alert_check(
interval=interval,
)
- alert.save(update_fields=["state", "last_checked_at", "next_check_at"])
+ alert.save(update_fields=[*state_fields, "last_checked_at", "next_check_at"])
- return alert_check, notify
+ return alert_check, should_notify(outcome)
def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> AlertCheck:
@@ -359,12 +348,9 @@ def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> AlertCheck:
as an exception. Returns the recorded ERRORED AlertCheck so callers can reference it.
"""
logger.warning("check_alert.auto_disabling", alert_id=alert.id, reason=reason)
- AlertConfiguration.objects.filter(pk=alert.pk).update(
- enabled=False,
- state=AlertState.ERRORED,
- last_checked_at=datetime.now(UTC),
- )
- alert.refresh_from_db()
+ state_fields = apply_invalid_configuration(alert)
+ alert.last_checked_at = datetime.now(UTC)
+ alert.save(update_fields=[*state_fields, "last_checked_at"])
targets_to_notify = alert.get_subscribed_users_emails()
alert_check = AlertCheck.objects.create(
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 3546738fe40a..ce34a00e29dc 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -45,6 +45,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.alerts.backend.evaluation import check_alert_for_insight
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.validation import validate_alert_config
+from products.alerts.backend.insight_alert_state_machine import apply_unsnooze
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
from products.notifications.backend.facade.api import (
NotificationData,
@@ -166,8 +167,8 @@ async def prepare_alert(inputs: PrepareAlertActivityInputs) -> PrepareAlertResul
return PrepareAlertResult(action=PrepareAction.SKIP, reason=SkipReason.SNOOZED)
# Snooze expired — persist clear so evaluate_alert reads the fresh state.
alert.snoozed_until = None
- alert.state = AlertState.NOT_FIRING
- alert.save(update_fields=["snoozed_until", "state"])
+ state_fields = apply_unsnooze(alert)
+ alert.save(update_fields=["snoozed_until", *state_fields])
try:
insight = alert.insight
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index d42c314cefe9..9e61771c6e4d 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -518,8 +518,8 @@ class TestNotifyAlert:
assert refreshed_alert.last_notified_at is not None
async def test_firing_passes_stable_idempotency_key_to_breach_sender(self, alert_with_user) -> None:
- # MessagingRecord dedupes retries via campaign_key; notify_alert must pass the
- # AlertCheck id so a retry reuses the same key and the provider skips re-sending.
+ # MessagingRecord dedupes email retries via campaign_key; notify_alert must pass
+ # the AlertCheck id so a retry reuses the same key.
check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
with patch(
@@ -539,8 +539,7 @@ class TestNotifyAlert:
mock_breaches.assert_called_once()
call_kwargs = mock_breaches.call_args.kwargs
assert call_kwargs.get("idempotency_key") == str(check.id), (
- "notify_alert must pass alert_check.id as idempotency_key so MessagingRecord "
- "dedupes Temporal retries at the provider level"
+ "notify_alert must pass alert_check.id as idempotency_key so MessagingRecord dedupes email retries"
)
async def test_sends_error_notifications_when_errored(self, alert_with_user) -> None:
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index bbd6451d88b3..180f0419ec21 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -2,6 +2,7 @@ import uuid
from typing import Annotated, Any, cast
from zoneinfo import ZoneInfo
+from django.db import transaction
from django.db.models import OuterRef, Q, QuerySet, Subquery
import posthoganalytics
@@ -18,7 +19,6 @@ from rest_framework.response import Response
from posthog.schema import (
AlertCalculationInterval,
AlertCondition,
- AlertState,
DetectorConfig,
FunnelsAlertConfig,
HogQLAlertConfig,
@@ -56,6 +56,13 @@ from products.alerts.backend.evaluation.validation import (
should_default_check_ongoing_interval,
validate_alert_config,
)
+from products.alerts.backend.insight_alert_state_machine import (
+ apply_disable,
+ apply_enable,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+)
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
@@ -463,28 +470,20 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
)
return instance
+ @transaction.atomic
def update(self, instance, validated_data):
- if "snoozed_until" in validated_data:
- snoozed_until_param = validated_data.pop("snoozed_until")
-
- if snoozed_until_param is None:
- instance.state = AlertState.NOT_FIRING
- instance.snoozed_until = None
- AlertCheck.objects.create(
- alert_configuration=instance,
- calculated_value=None,
- condition=instance.condition,
- targets_notified={},
- state=instance.state,
- error=None,
- )
- else:
- # always store snoozed_until as UTC time
- # as we look at current UTC time to check when to run alerts
- snoozed_until = relative_date_parse(
- snoozed_until_param, ZoneInfo("UTC"), increase=True, always_truncate=True
- )
- instance.snooze(until=snoozed_until)
+ enabled_changed = "enabled" in validated_data and validated_data["enabled"] != instance.enabled
+ resulting_enabled = validated_data.get("enabled", instance.enabled)
+ if enabled_changed and validated_data["enabled"]:
+ apply_enable(instance)
+
+ snoozed_until_param = validated_data.pop("snoozed_until", serializers.empty)
+ snooze_changed = snoozed_until_param is not serializers.empty
+ snoozed_until = None
+ if snooze_changed and snoozed_until_param is not None:
+ snoozed_until = relative_date_parse(
+ snoozed_until_param, ZoneInfo("UTC"), increase=True, always_truncate=True
+ )
conditions_or_threshold_changed = False
@@ -520,7 +519,29 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize
and validated_data["calculation_interval"] != instance.calculation_interval
)
if conditions_or_threshold_changed or calculation_interval_changed:
- instance.mark_for_recheck(reset_state=conditions_or_threshold_changed)
+ if conditions_or_threshold_changed:
+ apply_threshold_change(instance)
+ instance.next_check_at = None
+
+ if snooze_changed:
+ instance.snoozed_until = snoozed_until
+ if snoozed_until_param is None:
+ apply_unsnooze(instance)
+ else:
+ apply_snooze(instance)
+
+ if not resulting_enabled:
+ apply_disable(instance)
+
+ if snooze_changed:
+ AlertCheck.objects.create(
+ alert_configuration=instance,
+ calculated_value=None,
+ condition=instance.condition,
+ targets_notified={},
+ state=instance.state,
+ error=None,
+ )
schedule_restriction_changed = False
if "schedule_restriction" in validated_data:
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index a25cd29be6c4..92e7b6310651 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -783,6 +783,44 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
check = AlertCheck.objects.filter(alert_configuration=firing_alert.id).latest("created_at")
assert check.state == AlertState.SNOOZED
+ self.client.patch(f"/api/projects/{self.team.id}/alerts/{firing_alert.id}", {"enabled": False})
+ disabled_and_snoozed_alert = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{firing_alert.id}",
+ {"snoozed_until": datetime.now()},
+ ).json()
+ assert disabled_and_snoozed_alert["enabled"] is False
+ assert disabled_and_snoozed_alert["state"] == AlertState.NOT_FIRING
+ disabled_check = AlertCheck.objects.filter(alert_configuration=firing_alert.id).latest("created_at")
+ assert disabled_check.state == AlertState.NOT_FIRING
+
+ enabled_and_snoozed_alert = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{firing_alert.id}",
+ {"enabled": True, "snoozed_until": "1d"},
+ ).json()
+ assert enabled_and_snoozed_alert["enabled"] is True
+ assert enabled_and_snoozed_alert["state"] == AlertState.SNOOZED
+
+ snoozed_alert = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{firing_alert.id}",
+ {"snoozed_until": datetime.now()},
+ ).json()
+ assert snoozed_alert["state"] == AlertState.SNOOZED
+
+ edited_snoozed_alert = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{firing_alert.id}",
+ {"threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 200}}}},
+ ).json()
+ assert edited_snoozed_alert["state"] == AlertState.NOT_FIRING
+
+ edited_and_snoozed_alert = self.client.patch(
+ f"/api/projects/{self.team.id}/alerts/{firing_alert.id}",
+ {
+ "snoozed_until": "1d",
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 300}}},
+ },
+ ).json()
+ assert edited_and_snoozed_alert["state"] == AlertState.SNOOZED
+
@parameterized.expand(
[
(
@@ -910,6 +948,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
status.HTTP_400_BAD_REQUEST,
"weekly",
None,
+ False,
),
(
"omitted_interval_preserves_existing",
@@ -917,6 +956,7 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
status.HTTP_200_OK,
"weekly",
"renamed alert",
+ False,
),
(
"updated_interval_applied",
@@ -924,10 +964,19 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
status.HTTP_200_OK,
"hourly",
"alert name",
+ True,
),
]
)
- def test_patch_calculation_interval(self, _name, patch_payload, expected_status, expected_interval, expected_name):
+ def test_patch_calculation_interval(
+ self,
+ _name: str,
+ patch_payload: dict[str, Any],
+ expected_status: int,
+ expected_interval: str,
+ expected_name: str | None,
+ clears_next_check: bool,
+ ) -> None:
creation_request = {
"insight": self.insight["id"],
"subscribed_users": [self.user.id],
@@ -939,6 +988,8 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
}
alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()
assert alert["calculation_interval"] == "weekly"
+ scheduled_check = datetime(2027, 1, 1, tzinfo=UTC)
+ AlertConfiguration.objects.filter(id=alert["id"]).update(next_check_at=scheduled_check)
response = self.client.patch(
f"/api/projects/{self.team.id}/alerts/{alert['id']}",
@@ -950,6 +1001,9 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
assert response.json()["calculation_interval"] == expected_interval
assert response.json()["name"] == expected_name
+ persisted_alert = AlertConfiguration.objects.get(id=alert["id"])
+ assert persisted_alert.next_check_at == (None if clears_next_check else scheduled_check)
+
def test_create_alert_with_schedule_restriction(self) -> None:
creation_request = {
"insight": self.insight["id"],
@@ -1558,62 +1612,6 @@ class TestAlertEventProperties(APIBaseTest):
assert props[key] == value, f"{key} expected {value}, got {props[key]}"
-class TestTriggerAlertHogFunctions(APIBaseTest):
- @parameterized.expand(
- [
- (
- "threshold_alert",
- None,
- {"alert_mode": "threshold", "detector_type": None, "ensemble_operator": None},
- ),
- (
- "single_detector",
- {"type": "zscore", "threshold": 0.95, "window": 30},
- {"alert_mode": "detector", "detector_type": "zscore", "ensemble_operator": None},
- ),
- (
- "ensemble_detector",
- {
- "type": "ensemble",
- "operator": "AND",
- "detectors": [
- {"type": "zscore", "threshold": 0.95, "window": 30},
- {"type": "mad", "threshold": 0.95, "window": 30},
- ],
- },
- {"alert_mode": "detector", "detector_type": "ensemble", "ensemble_operator": "AND"},
- ),
- ]
- )
- @mock.patch("posthog.tasks.alerts.utils.produce_internal_event")
- def test_insight_alert_firing_detector_props(
- self,
- _name: str,
- detector_config: dict | None,
- expected_props: dict,
- mock_produce: mock.MagicMock,
- ) -> None:
- from posthog.tasks.alerts.utils import trigger_alert_hog_functions
-
- alert = mock.MagicMock()
- alert.id = "00000000-0000-0000-0000-000000000001"
- alert.name = "test alert"
- alert.insight.name = "test insight"
- alert.insight.short_id = "abcd1234"
- alert.state = AlertState.FIRING
- alert.last_checked_at = None
- alert.team_id = self.team.id
- alert.detector_config = detector_config
-
- trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
-
- assert mock_produce.call_count == 1
- event = mock_produce.call_args.kwargs["event"]
- for key, value in expected_props.items():
- assert event.properties[key] == value, f"{key} expected {value}, got {event.properties[key]}"
- assert event.properties["breaches"] == "test breach"
-
-
class TestAlertListFilters(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 61e0da70cd2a..2add22858137 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -28,7 +28,8 @@ from products.alerts.backend.destinations import (
soft_delete_all_alert_destinations,
)
from products.alerts.backend.email_notifications import send_alert_email
-from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.insight_alert_state_machine import apply_snooze
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
logger = structlog.get_logger(__name__)
@@ -125,7 +126,17 @@ def snooze_alert_from_slack(
return "disabled"
with ActingUserContext(user):
- locked_alert.snooze(until=snoozed_until)
+ state_fields = apply_snooze(locked_alert)
+ locked_alert.snoozed_until = snoozed_until
+ locked_alert.save(update_fields=[*state_fields, "snoozed_until"])
+ AlertCheck.objects.create(
+ alert_configuration=locked_alert,
+ calculated_value=None,
+ condition=locked_alert.condition,
+ targets_notified={},
+ state=locked_alert.state,
+ error=None,
+ )
return "snoozed"
diff --git a/products/alerts/backend/insight_alert_state_machine.py b/products/alerts/backend/insight_alert_state_machine.py
new file mode 100644
index 000000000000..55ba838e6318
--- /dev/null
+++ b/products/alerts/backend/insight_alert_state_machine.py
@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING
+
+from posthog.schema_enums import AlertState as InsightAlertState
+
+from products.alerts.backend.state_machine import (
+ AlertCheckOutcome,
+ AlertPolicy,
+ AlertSnapshot,
+ AlertState,
+ CheckInput,
+ ControlPlaneOutcome,
+ NotificationAction,
+ Outcome,
+ apply_disable as shared_apply_disable,
+ apply_enable as shared_apply_enable,
+ apply_snooze as shared_apply_snooze,
+ apply_threshold_change as shared_apply_threshold_change,
+ apply_unsnooze as shared_apply_unsnooze,
+ evaluate_alert_check as shared_evaluate_alert_check,
+)
+
+if TYPE_CHECKING:
+ from products.alerts.backend.models.alert import AlertConfiguration
+
+
+INSIGHT_ALERT_POLICY = AlertPolicy(
+ max_consecutive_failures=None,
+ notify_error_on_every_failure=True,
+ renotify_while_firing=True,
+ notify_resolve=False,
+ errors_set_errored_state=True,
+)
+
+
+def snapshot_from_alert(alert: AlertConfiguration) -> AlertSnapshot:
+ return AlertSnapshot(
+ state=AlertState[InsightAlertState(alert.state).name],
+ cooldown=timedelta(0),
+ last_notified_at=alert.last_notified_at,
+ snooze_until=alert.snoozed_until,
+ consecutive_failures=0,
+ )
+
+
+def evaluate_alert_check(
+ alert: AlertConfiguration,
+ *,
+ threshold_breached: bool,
+ error_message: str | None,
+ now: datetime,
+) -> AlertCheckOutcome:
+ return shared_evaluate_alert_check(
+ snapshot_from_alert(alert),
+ CheckInput(threshold_breached=threshold_breached, error_message=error_message),
+ now,
+ policy=INSIGHT_ALERT_POLICY,
+ )
+
+
+def apply_outcome(alert: AlertConfiguration, outcome: Outcome) -> list[str]:
+ alert.state = InsightAlertState[outcome.new_state.name]
+ return ["state"]
+
+
+def apply_enable(alert: AlertConfiguration) -> list[str]:
+ alert.enabled = True
+ return ["enabled", *apply_outcome(alert, shared_apply_enable(snapshot_from_alert(alert)))]
+
+
+def apply_disable(alert: AlertConfiguration) -> list[str]:
+ alert.enabled = False
+ return ["enabled", *apply_outcome(alert, shared_apply_disable(snapshot_from_alert(alert)))]
+
+
+def apply_snooze(alert: AlertConfiguration) -> list[str]:
+ return apply_outcome(alert, shared_apply_snooze(snapshot_from_alert(alert)))
+
+
+def apply_unsnooze(alert: AlertConfiguration) -> list[str]:
+ return apply_outcome(alert, shared_apply_unsnooze(snapshot_from_alert(alert)))
+
+
+def apply_threshold_change(alert: AlertConfiguration) -> list[str]:
+ return apply_outcome(
+ alert,
+ shared_apply_threshold_change(snapshot_from_alert(alert), preserve_snoozed_state=False),
+ )
+
+
+def apply_invalid_configuration(alert: AlertConfiguration) -> list[str]:
+ alert.enabled = False
+ return [
+ "enabled",
+ *apply_outcome(alert, ControlPlaneOutcome(new_state=AlertState.ERRORED, consecutive_failures=0)),
+ ]
+
+
+def should_notify(outcome: AlertCheckOutcome) -> bool:
+ return outcome.notification != NotificationAction.NONE
diff --git a/products/alerts/backend/max_tools.py b/products/alerts/backend/max_tools.py
index 4fc8bbb3e531..12a1410dbbbe 100644
--- a/products/alerts/backend/max_tools.py
+++ b/products/alerts/backend/max_tools.py
@@ -24,6 +24,7 @@ from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
+from products.alerts.backend.insight_alert_state_machine import apply_disable, apply_enable, apply_threshold_change
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
from products.product_analytics.backend.models.insight import Insight
@@ -361,9 +362,14 @@ class UpsertAlertTool(MaxTool):
alert.config = {**(alert.config or {}), "series_index": action.series_index}
update_fields.append("config")
+ enabled_changed = action.enabled is not None and action.enabled != alert.enabled
if action.enabled is not None:
- alert.enabled = action.enabled
- update_fields.append("enabled")
+ if enabled_changed and action.enabled:
+ update_fields.extend(apply_enable(alert))
+ elif enabled_changed:
+ update_fields.extend(apply_disable(alert))
+ else:
+ update_fields.append("enabled")
if action.skip_weekend is not None:
alert.skip_weekend = action.skip_weekend
@@ -384,7 +390,10 @@ class UpsertAlertTool(MaxTool):
if not update_fields and not has_threshold_changes:
return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}
- update_fields.extend(alert.mark_for_recheck(reset_state=conditions_or_threshold_changed))
+ if conditions_or_threshold_changed:
+ update_fields.extend(apply_threshold_change(alert))
+ alert.next_check_at = None
+ update_fields.append("next_check_at")
await sync_to_async(alert.save)(update_fields=update_fields)
await sync_to_async(alert.report_updated)(self._user, {"source": EventSource.POSTHOG_AI})
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 1c17f9025bfb..7fc7797b9710 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -4,7 +4,7 @@ from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
from django.core.exceptions import ValidationError
-from django.db import models, transaction
+from django.db import models
if TYPE_CHECKING:
from posthog.event_usage import AnalyticsProps
@@ -210,46 +210,6 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):
)
)
- def mark_for_recheck(self, *, reset_state: bool = False) -> list[str]:
- """Returns list of field names that were modified (for use with update_fields)."""
- updated: list[str] = []
- if reset_state:
- self.state = AlertState.NOT_FIRING
- updated.append("state")
- self.next_check_at = None
- updated.append("next_check_at")
- return updated
-
- def save(self, *args, **kwargs) -> None:
- if not self.enabled:
- # When disabling an alert, set the state to not firing
- self.state = AlertState.NOT_FIRING
- if "update_fields" in kwargs:
- kwargs["update_fields"].append("state")
-
- super().save(*args, **kwargs)
-
- def snooze(self, *, until: datetime) -> AlertCheck:
- """Snooze this alert until the given time, recording an audit AlertCheck row.
-
- The check is created *after* save() so it reflects whatever actually got persisted —
- save() forces a disabled alert's state back to NOT_FIRING, and the audit row must not
- claim SNOOZED for an alert that was in fact left NOT_FIRING.
- """
- with transaction.atomic():
- self.state = AlertState.SNOOZED
- self.snoozed_until = until
- self.save(update_fields=["state", "snoozed_until"])
-
- return AlertCheck.objects.create(
- alert_configuration=self,
- calculated_value=None,
- condition=self.condition,
- targets_notified={},
- state=self.state,
- error=None,
- )
-
def _get_event_properties(self) -> dict:
detector_config = self.detector_config or {}
detector_type = detector_config.get("type")
diff --git a/products/alerts/backend/state_machine.py b/products/alerts/backend/state_machine.py
index 25a2b4b19634..6e199f52c57e 100644
--- a/products/alerts/backend/state_machine.py
+++ b/products/alerts/backend/state_machine.py
@@ -58,7 +58,8 @@ class AlertPolicy:
flag speculatively, and do not change a default without checking every adopter.
"""
- max_consecutive_failures: int = MAX_CONSECUTIVE_FAILURES
+ # None keeps failures from escalating to BROKEN for products without that state.
+ max_consecutive_failures: int | None = MAX_CONSECUTIVE_FAILURES
# True (logs): BROKEN is terminal until an explicit user reset. False (billing):
# a successful check on a BROKEN alert re-evaluates it from scratch — manual
# check-now is billing's only un-break path.
@@ -73,6 +74,10 @@ class AlertPolicy:
cooldown_gates_resolve: bool = True
# True: an alert that stays breached re-notifies once per cooldown window.
renotify_while_firing: bool = False
+ # False for products that record recovery without sending a resolve notification.
+ notify_resolve: bool = True
+ # Some adopters expose evaluation failures as a visible ERRORED state.
+ errors_set_errored_state: bool = False
# True (billing): snooze only mutes while breached — a clear check resolves and
# un-snoozes; a breached check parks the alert in SNOOZED without notifying.
# False (logs): a snoozed alert stays snoozed untouched until snooze_until passes.
@@ -243,7 +248,8 @@ def evaluate_alert_check(
notification = NotificationAction.FIRE
else:
new_state = AlertState.NOT_FIRING
- notification = NotificationAction.RESOLVE
+ if policy.notify_resolve:
+ notification = NotificationAction.RESOLVE
else:
new_state = AlertState.NOT_FIRING
@@ -301,7 +307,7 @@ def evaluate_alert_failure(
consecutive_failures = snapshot.consecutive_failures + 1
- if consecutive_failures >= policy.max_consecutive_failures:
+ if policy.max_consecutive_failures is not None and consecutive_failures >= policy.max_consecutive_failures:
return AlertCheckOutcome(
new_state=AlertState.BROKEN,
notification=NotificationAction.BROKEN,
@@ -318,8 +324,9 @@ def evaluate_alert_failure(
else:
notification = NotificationAction.NONE
+ new_state = AlertState.ERRORED if policy.errors_set_errored_state else snapshot.state
return AlertCheckOutcome(
- new_state=snapshot.state,
+ new_state=new_state,
notification=notification,
consecutive_failures=consecutive_failures,
update_last_notified_at=False,
@@ -357,10 +364,8 @@ def apply_unsnooze(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
return ControlPlaneOutcome(new_state=AlertState.NOT_FIRING, consecutive_failures=0)
-def apply_threshold_change(snapshot: StatefulSnapshot) -> ControlPlaneOutcome:
- # Snoozed alerts stay snoozed on edit — editing configuration must not wake a
- # silenced alert.
- if snapshot.state == AlertState.SNOOZED:
+def apply_threshold_change(snapshot: StatefulSnapshot, *, preserve_snoozed_state: bool = True) -> ControlPlaneOutcome:
+ if preserve_snoozed_state and snapshot.state == AlertState.SNOOZED:
return ControlPlaneOutcome(
new_state=AlertState.SNOOZED,
consecutive_failures=snapshot.consecutive_failures,
diff --git a/products/alerts/backend/test/test_insight_alert_state_machine.py b/products/alerts/backend/test/test_insight_alert_state_machine.py
new file mode 100644
index 000000000000..98270798f64d
--- /dev/null
+++ b/products/alerts/backend/test/test_insight_alert_state_machine.py
@@ -0,0 +1,72 @@
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import cast
+
+from posthog.schema_enums import AlertState as InsightAlertState
+
+from products.alerts.backend.insight_alert_state_machine import (
+ apply_disable,
+ apply_enable,
+ apply_snooze,
+ apply_threshold_change,
+ apply_unsnooze,
+ evaluate_alert_check,
+ should_notify,
+)
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.state_machine import AlertState
+
+NOW = datetime(2026, 7, 27, 12, 0, tzinfo=UTC)
+
+
+def alert_with_state(state: InsightAlertState, *, enabled: bool = True) -> AlertConfiguration:
+ return cast(
+ AlertConfiguration,
+ SimpleNamespace(enabled=enabled, state=state.value, last_notified_at=None, snoozed_until=None),
+ )
+
+
+def test_repeated_breach_stays_firing_and_notifies() -> None:
+ outcome = evaluate_alert_check(
+ alert_with_state(InsightAlertState.FIRING), threshold_breached=True, error_message=None, now=NOW
+ )
+
+ assert outcome.new_state == AlertState.FIRING
+ assert should_notify(outcome)
+
+
+def test_clear_check_resolves_without_notification() -> None:
+ outcome = evaluate_alert_check(
+ alert_with_state(InsightAlertState.FIRING), threshold_breached=False, error_message=None, now=NOW
+ )
+
+ assert outcome.new_state == AlertState.NOT_FIRING
+ assert not should_notify(outcome)
+
+
+def test_error_enters_errored_without_broken_escalation() -> None:
+ alert = alert_with_state(InsightAlertState.ERRORED)
+
+ for _ in range(10):
+ outcome = evaluate_alert_check(alert, threshold_breached=False, error_message="query failed", now=NOW)
+ assert outcome.new_state == AlertState.ERRORED
+ assert should_notify(outcome)
+
+
+def test_control_plane_transitions_use_shared_outcomes() -> None:
+ alert = alert_with_state(InsightAlertState.FIRING)
+
+ assert apply_snooze(alert) == ["state"]
+ assert alert.state == InsightAlertState.SNOOZED
+ assert apply_threshold_change(alert) == ["state"]
+ assert alert.state == InsightAlertState.NOT_FIRING
+ apply_snooze(alert)
+ assert apply_unsnooze(alert) == ["state"]
+ assert alert.state == InsightAlertState.NOT_FIRING
+ assert apply_disable(alert) == ["enabled", "state"]
+ assert alert.enabled is False
+
+ disabled_alert = alert_with_state(InsightAlertState.NOT_FIRING, enabled=False)
+ assert apply_enable(disabled_alert) == ["enabled", "state"]
+ assert disabled_alert.enabled is True
+ assert disabled_alert.state == InsightAlertState.NOT_FIRING
diff --git a/products/alerts/backend/test/test_state_machine.py b/products/alerts/backend/test/test_state_machine.py
index 94c157a5e89f..a823984767b2 100644
--- a/products/alerts/backend/test/test_state_machine.py
+++ b/products/alerts/backend/test/test_state_machine.py
@@ -31,6 +31,9 @@ RENOTIFY = AlertPolicy(renotify_while_firing=True)
SNOOZE_UNTIL_CLEAR = AlertPolicy(clear_check_ends_snooze=True)
DISABLE_ON_BROKEN = AlertPolicy(disable_when_broken=True)
BREAKS_EARLY = AlertPolicy(max_consecutive_failures=2)
+NO_FAILURE_ESCALATION = AlertPolicy(max_consecutive_failures=None, notify_error_on_every_failure=True)
+NO_RESOLVE_NOTIFICATION = AlertPolicy(notify_resolve=False)
+VISIBLE_ERROR_STATE = AlertPolicy(errors_set_errored_state=True)
def snapshot(**overrides) -> AlertSnapshot:
@@ -76,6 +79,14 @@ class TestPolicyDecisionTable:
AlertState.BROKEN,
NotificationAction.NONE,
),
+ (
+ "resolve_without_notification",
+ NO_RESOLVE_NOTIFICATION,
+ snapshot(state=AlertState.FIRING),
+ CLEAR,
+ AlertState.NOT_FIRING,
+ NotificationAction.NONE,
+ ),
# transient_errors_count_toward_broken
(
"transient_error_spared",
@@ -243,6 +254,20 @@ class TestPolicyDecisionTable:
)
assert outcome.consecutive_failures == 3
+ def test_failures_can_skip_broken_escalation(self) -> None:
+ outcome = evaluate_alert_check(
+ snapshot(state=AlertState.ERRORED, consecutive_failures=10),
+ ERROR,
+ NOW,
+ policy=NO_FAILURE_ESCALATION,
+ )
+ assert outcome.new_state == AlertState.ERRORED
+ assert outcome.notification == NotificationAction.ERROR
+
+ def test_failure_can_enter_errored_state(self) -> None:
+ outcome = evaluate_alert_check(snapshot(), ERROR, NOW, policy=VISIBLE_ERROR_STATE)
+ assert outcome.new_state == AlertState.ERRORED
+
@parameterized.expand(
[
("default_keeps_enabled", LOGS_ALERT_POLICY, False),
diff --git a/products/alerts/backend/test_max_tools.py b/products/alerts/backend/test_max_tools.py
index c60110ac81a2..dc94dc8aff98 100644
--- a/products/alerts/backend/test_max_tools.py
+++ b/products/alerts/backend/test_max_tools.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime
+
import pytest
from posthog.test.base import BaseTest
from unittest import mock
@@ -441,6 +443,12 @@ class TestUpsertAlertTool(BaseTest):
{"enabled": False},
lambda a, t: a.enabled is False,
),
+ (
+ "unchanged_enabled_preserves_firing_state",
+ {"enabled": True},
+ {"enabled": True},
+ lambda a, t: a.enabled is True and a.state == AlertState.FIRING,
+ ),
(
"condition_type",
{"condition_type": AlertConditionType.ABSOLUTE_VALUE},
@@ -497,7 +505,10 @@ class TestUpsertAlertTool(BaseTest):
async def test_update_alert(self, _name, create_kwargs, update_kwargs, check):
insight = await self._create_insight()
alert = await self._create_alert(insight, **create_kwargs)
- await sync_to_async(AlertConfiguration.objects.filter(id=alert.id).update)(state=AlertState.FIRING)
+ await sync_to_async(AlertConfiguration.objects.filter(id=alert.id).update)(
+ state=AlertState.FIRING,
+ next_check_at=datetime(2027, 1, 1, tzinfo=UTC),
+ )
tool = self._setup_tool()
content, artifact = await tool._arun_impl(action=UpdateAlertAction(alert_id=str(alert.id), **update_kwargs))
@@ -506,6 +517,7 @@ class TestUpsertAlertTool(BaseTest):
await sync_to_async(alert.refresh_from_db)()
threshold = await sync_to_async(lambda: alert.threshold)()
assert check(alert, threshold), f"Check failed for {_name}"
+ assert alert.next_check_at is None
@pytest.mark.django_db
@pytest.mark.asyncio