:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): keep firing state through errored alert checks (#69299)
Jon McCallumfb325a4c0c3b
diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex d3ad742390e1..3e1fd3cdc8dc 100644--- a/products/logs/backend/alert_state_machine.py+++ b/products/logs/backend/alert_state_machine.py@@ -123,22 +123,28 @@ def evaluate_alert_check(effective_state = snapshot.stateif check.error_message is not None:- consecutive_failures = (- snapshot.consecutive_failures if check.is_transient_error else snapshot.consecutive_failures + 1- )- new_state = AlertState.BROKEN if consecutive_failures >= MAX_CONSECUTIVE_FAILURES else AlertState.ERRORED- first_error = (- effective_state != AlertState.ERRORED- and snapshot.state != AlertState.ERRORED # prevents re-notification after snooze auto-expiry- and new_state == AlertState.ERRORED- )- first_broken = new_state == AlertState.BROKEN- if first_broken:+ # Errors never move firing state — only threshold checks do (CloudWatch's+ # INSUFFICIENT_DATA doesn't clear ALARM). A FIRING alert rides through a+ # failed check, so recovery continues the episode instead of re-firing it.+ if check.is_transient_error:+ # Transient errors (cluster blips, `unknown`) hit whole cohorts at+ # once; notifying would broadcast noise to every destination. Skip+ # the cycle entirely — the next check retries naturally.+ return AlertCheckOutcome(+ new_state=snapshot.state,+ notification=NotificationAction.NONE,+ consecutive_failures=snapshot.consecutive_failures,+ update_last_notified_at=False,+ error_message=check.error_message,+ )+ consecutive_failures = snapshot.consecutive_failures + 1+ if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:+ new_state = AlertState.BROKENnotification = NotificationAction.BROKEN- elif first_error:- notification = NotificationAction.ERRORelse:- notification = NotificationAction.NONE+ new_state = snapshot.state+ # Notify once per error streak (0 → 1), not on every failed check.+ notification = NotificationAction.ERROR if snapshot.consecutive_failures == 0 else NotificationAction.NONEreturn AlertCheckOutcome(new_state=new_state,notification=notification,diff --git a/products/logs/backend/test/test_alert_state_machine.py b/products/logs/backend/test/test_alert_state_machine.pyindex 313125bea883..f2e577492ac0 100644--- a/products/logs/backend/test/test_alert_state_machine.py+++ b/products/logs/backend/test/test_alert_state_machine.py@@ -215,10 +215,17 @@ class TestCooldownSuppression(TestCase):class TestErrorHandling(TestCase):- def test_error_transitions_to_errored(self) -> None:- snapshot = _snapshot(state=NOT_FIRING)+ @parameterized.expand(+ [+ ("from_not_firing", NOT_FIRING),+ ("from_firing", FIRING),+ ("from_pending_resolve", PENDING_RESOLVE),+ ]+ )+ def test_error_keeps_prior_state(self, _name: str, prior: AlertState) -> None:+ snapshot = _snapshot(state=prior)outcome = evaluate_alert_check(snapshot, _check(error="ClickHouse timeout"), NOW)- assert outcome.new_state == ERRORED+ assert outcome.new_state == priorassert outcome.notification == NotificationAction.ERRORassert outcome.error_message == "ClickHouse timeout"@@ -232,11 +239,37 @@ class TestErrorHandling(TestCase):outcome = evaluate_alert_check(snapshot, _check(breached=False), NOW)assert outcome.consecutive_failures == 0- def test_error_from_firing_state(self) -> None:- snapshot = _snapshot(state=FIRING)+ def test_firing_survives_error_then_recovery_emits_no_duplicate_fire(self) -> None:+ # The firing episode must ride through a failed check: an error while+ # FIRING keeps FIRING, and the next successful still-breaching check is+ # a continuation, not a new FIRE notification.+ firing = _snapshot(state=FIRING)+ after_error = evaluate_alert_check(firing, _check(error="timeout"), NOW)+ assert after_error.new_state == FIRING++ recovered = _snapshot(state=after_error.new_state, consecutive_failures=after_error.consecutive_failures)+ outcome = evaluate_alert_check(recovered, _check(breached=True), NOW)+ assert outcome.new_state == FIRING+ assert outcome.notification == NotificationAction.NONE++ def test_second_consecutive_error_does_not_renotify(self) -> None:+ snapshot = _snapshot(state=NOT_FIRING, consecutive_failures=1)outcome = evaluate_alert_check(snapshot, _check(error="timeout"), NOW)- assert outcome.new_state == ERRORED+ assert outcome.notification == NotificationAction.NONE+ assert outcome.consecutive_failures == 2+ def test_error_after_expired_snooze_stays_snoozed(self) -> None:+ # An error keeps the persisted SNOOZED label (only a successful check moves+ # it out), but still counts as a failure and notifies once on the 0 -> 1 edge.+ # The scheduler excludes on `state == SNOOZED AND snooze_until > now`, so an+ # expired snooze keeps getting checked and won't stall in this label.+ snapshot = _snapshot(state=SNOOZED, snooze_until=NOW - timedelta(minutes=1))+ outcome = evaluate_alert_check(snapshot, _check(error="timeout"), NOW)+ assert outcome.new_state == SNOOZED+ assert outcome.notification == NotificationAction.ERROR+ assert outcome.consecutive_failures == 1++ # Legacy rows: alerts persisted as ERRORED before errors stopped moving state.def test_errored_recovery_with_breach(self) -> None:snapshot = _snapshot(state=ERRORED)outcome = evaluate_alert_check(snapshot, _check(breached=True), NOW)@@ -259,17 +292,26 @@ class TestTransientErrors(TestCase):outcome = evaluate_alert_check(snapshot, check, NOW)assert outcome.consecutive_failures == 2- def test_transient_error_still_transitions_to_errored(self) -> None:- snapshot = _snapshot(state=NOT_FIRING)+ @parameterized.expand(+ [+ ("from_not_firing", NOT_FIRING),+ ("from_firing", FIRING),+ ]+ )+ def test_transient_error_is_silent_and_keeps_state(self, _name: str, prior: AlertState) -> None:+ # Transient errors (cluster blips, `unknown`) propagate cohort-wide, so+ # notifying on them broadcasts noise to every destination in the fleet.+ snapshot = _snapshot(state=prior)check = CheckResult(result_count=None, threshold_breached=False, error_message="cluster busy", is_transient_error=True)outcome = evaluate_alert_check(snapshot, check, NOW)- assert outcome.new_state == ERRORED- assert outcome.notification == NotificationAction.ERROR+ assert outcome.new_state == prior+ assert outcome.notification == NotificationAction.NONE+ assert outcome.error_message == "cluster busy"def test_transient_error_does_not_push_counter_past_threshold(self) -> None:- # MAX_CONSECUTIVE_FAILURES - 1 non-transient errors → ERRORED, counter at 4.+ # MAX_CONSECUTIVE_FAILURES - 1 non-transient errors, counter at 4.# A transient error must NOT push it to 5 (BROKEN).snapshot = _snapshot(state=ERRORED, consecutive_failures=4)check = CheckResult(@@ -291,7 +333,7 @@ class TestTransientErrors(TestCase):class TestBrokenTransition(TestCase):@parameterized.expand([- ("below_threshold", 3, ERRORED, 4),+ ("below_threshold", 3, NOT_FIRING, 4),("one_below_threshold", 4, BROKEN, 5),("at_threshold", 5, BROKEN, 6),]@@ -309,6 +351,12 @@ class TestBrokenTransition(TestCase):assert outcome.consecutive_failures == expected_failuresassert outcome.error_message == "ClickHouse timeout"+ def test_broken_overrides_kept_firing_state(self) -> None:+ snapshot = _snapshot(state=FIRING, consecutive_failures=4)+ outcome = evaluate_alert_check(snapshot, _check(error="ClickHouse timeout"), NOW)+ assert outcome.new_state == BROKEN+ assert outcome.notification == NotificationAction.BROKEN+# Scheduler excludes BROKEN so these shouldn't occur, but belt-and-braces:# a BROKEN alert must not silently self-heal and its failure counter stays frozen# until an explicit unbreak path resets it.diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex 55933b4aa93d..89458d7f88dd 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -970,7 +970,7 @@ class TestEvaluateSingleAlert(APIBaseTest):"below_threshold",3,LogsAlertConfiguration.State.NOT_FIRING,- LogsAlertConfiguration.State.ERRORED,+ LogsAlertConfiguration.State.NOT_FIRING,4,0,),@@ -1253,7 +1253,9 @@ class TestEvaluateSingleAlert(APIBaseTest):_evaluate_and_save_one(alert, datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC), _make_stats())alert.refresh_from_db()- assert alert.state == LogsAlertConfiguration.State.ERRORED+ # Errors no longer move firing state; the notification and counter carry the signal.+ assert alert.state == LogsAlertConfiguration.State.NOT_FIRING+ assert alert.consecutive_failures == 1errored_calls = [cfor c in mock_produce.call_args_list@@ -1262,30 +1264,6 @@ class TestEvaluateSingleAlert(APIBaseTest):assert len(errored_calls) == 1assert errored_calls[0].kwargs["event"].properties["consecutive_failures"] == 1- @freeze_time("2025-01-01T00:01:00Z")- @patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.capture_exception")- def test_errored_notification_retried_after_kafka_failure(self, _mock_capture, mock_query_cls):- mock_query_cls.return_value.execute_rolling_checks.side_effect = RuntimeError("CH down")- alert = self._make_alert()- now1 = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)- now2 = datetime(2025, 1, 1, 0, 6, 0, tzinfo=UTC)-- with patch("products.logs.backend.temporal.activities.produce_internal_event") as mock_produce:- mock_produce.side_effect = Exception("Kafka down")- _evaluate_and_save_one(alert, now1, _make_stats())-- mock_produce.side_effect = None- mock_produce.reset_mock()- _evaluate_and_save_one(alert, now2, _make_stats())-- errored_calls = [- c- for c in mock_produce.call_args_list- if c.kwargs.get("event") and c.kwargs["event"].event == "$logs_alert_errored"- ]- assert len(errored_calls) == 1-@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")@patch("products.logs.backend.temporal.activities.capture_exception")