:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): close the pagerduty incident when a person ends a firing (#112236)
Jimmy Zhu78d86517b7cc
diff --git a/products/logs/backend/alert_incidents.py b/products/logs/backend/alert_incidents.pynew file mode 100644index 000000000000..07a5259117bd--- /dev/null+++ b/products/logs/backend/alert_incidents.py@@ -0,0 +1,74 @@+"""Incident events for destinations that hold an incident open, such as PagerDuty."""++from __future__ import annotations++from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any++from products.alerts.backend.facade.destinations import (+ alert_internal_event_delivered,+ configured_destination_template_ids,+ flush_alert_internal_events,+ produce_alert_internal_event,+)+from products.logs.backend.alert_destinations import LOGS_ALERT_INCIDENT_CLOSED_EVENT, LOGS_ALERT_INCIDENT_OPENED_EVENT+from products.logs.backend.alert_state_machine import IncidentCloseReason++if TYPE_CHECKING:+ from products.logs.backend.models import LogsAlertConfiguration+++def has_incident_destination(alert: LogsAlertConfiguration) -> bool:+ """Whether a destination of this alert follows the incident kinds.++ An alert without one sends no incident events, so a lost incident event can never roll back a+ notification its Slack, Teams or webhook destinations already received.+ """+ return bool(+ configured_destination_template_ids(+ team_id=alert.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=(LOGS_ALERT_INCIDENT_OPENED_EVENT, LOGS_ALERT_INCIDENT_CLOSED_EVENT),+ )+ )+++def incident_closed_properties(+ alert: LogsAlertConfiguration, reason: IncidentCloseReason, now: datetime+) -> dict[str, Any]:+ return {+ "alert_id": str(alert.id),+ "alert_name": alert.name,+ "team_id": alert.team_id,+ "reason": reason.value,+ "triggered_at": now.isoformat(),+ }+++def close_incident(+ alert: LogsAlertConfiguration, reason: IncidentCloseReason, *, flush_timeout_seconds: float | None = None+) -> bool:+ """Send the close for an alert leaving firing, and return whether it was handed off.++ With `flush_timeout_seconds`, the return value says the broker took the close, and a lost close+ also shows in the delivery failure metric and log. Without it, the return value only says the+ close was queued. A web request passes none, because the flush waits on the process-wide producer.+ """+ now = datetime.now(UTC)+ produce_result = produce_alert_internal_event(+ team_id=alert.team_id,+ event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,+ properties=incident_closed_properties(alert, reason, now),+ timestamp=now,+ )+ if produce_result is None:+ return False+ if flush_timeout_seconds is None:+ return True+ flush_alert_internal_events(flush_timeout_seconds)+ return alert_internal_event_delivered(+ produce_result,+ team_id=alert.team_id,+ alert_id=str(alert.id),+ event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,+ )diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex 5af8011ea523..4bb9d2df654d 100644--- a/products/logs/backend/alert_state_machine.py+++ b/products/logs/backend/alert_state_machine.py@@ -50,6 +50,7 @@ __all__ = ["AlertCheckOutcome","AlertSnapshot","AlertState",+ "FIRING_STATES","CheckResult","ControlPlaneOutcome","IncidentCloseReason",@@ -98,9 +99,13 @@ class IncidentEdge(StrEnum):class IncidentCloseReason(StrEnum):RESOLVED = "resolved"BROKEN = "broken"+ DISABLED = "disabled"+ SNOOZED = "snoozed"+ CONFIG_CHANGED = "config_changed"+ DELETED = "deleted"-def incident_edge(state_before: str, new_state: AlertState) -> IncidentEdge | None:+def incident_edge(state_before: str, new_state: str) -> IncidentEdge | None:"""Whether a transition starts or ends a firing.Read from the states, not from the notification, because cooldown can suppress a notificationdiff --git a/products/logs/backend/facade/api.py b/products/logs/backend/facade/api.pyindex 7a817e0ed2de..51620cb81528 100644--- a/products/logs/backend/facade/api.py+++ b/products/logs/backend/facade/api.py@@ -1,3 +1,37 @@+from django.db import transaction++from products.logs.backend import alert_incidents+from products.logs.backend.alert_state_machine import FIRING_STATES, IncidentCloseReason, IncidentEdge, incident_edgefrom products.logs.backend.alert_utils import next_allowed_check_at+from products.logs.backend.models import LogsAlertConfiguration++__all__ = ["close_incident_before_delete", "close_incident_on_commit", "next_allowed_check_at"]+++def _close_if_subscribed(*, team_id: int, alert_id: str, reason: IncidentCloseReason) -> None:+ alert = LogsAlertConfiguration.objects.filter(team_id=team_id, id=alert_id).first()+ if alert is None or not alert_incidents.has_incident_destination(alert):+ return+ alert_incidents.close_incident(alert, reason)+++def close_incident_on_commit(+ *, team_id: int, alert_id: str, state_before: str, state_after: str, reason: IncidentCloseReason+) -> None:+ """Close the alert's incident after the change commits, when the change moved it out of firing."""+ if incident_edge(state_before, state_after) != IncidentEdge.CLOSED:+ return+ # Robust, so a failed close cannot turn a committed change into an error response.+ transaction.on_commit(+ lambda: _close_if_subscribed(team_id=team_id, alert_id=alert_id, reason=reason),+ robust=True,+ )+++def close_incident_before_delete(*, team_id: int, alert_id: str, state: str) -> None:+ """Close a firing alert's incident before the delete removes the functions that deliver it.-__all__ = ["next_allowed_check_at"]+ Best effort. The CDP consumer drops events for deleted functions, so the close often goes unsent.+ """+ if state in FIRING_STATES:+ _close_if_subscribed(team_id=team_id, alert_id=alert_id, reason=IncidentCloseReason.DELETED)diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 8fccdf604b4a..d289c4e48985 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -62,6 +62,7 @@ from products.logs.backend.alert_state_machine import (AlertSnapshot,AlertState,CheckResult,+ IncidentCloseReason,InvalidTransition,NotificationAction,apply_disable,@@ -73,7 +74,11 @@ from products.logs.backend.alert_state_machine import (apply_user_reset,evaluate_alert_check,)-from products.logs.backend.facade.api import next_allowed_check_at+from products.logs.backend.facade.api import (+ close_incident_before_delete,+ close_incident_on_commit,+ next_allowed_check_at,+)from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEventALLOWED_WINDOW_MINUTES = {5, 10, 15, 30, 60}@@ -563,6 +568,8 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):# state at all. All transitions return an Outcome; apply_outcome is the single# place that actually writes to `state`/`consecutive_failures`.snapshot = instance.to_snapshot()+ state_before = instance.state+ close_reason: IncidentCloseReason | None = Noneif enabled_change is True:if instance.first_enabled_at is None:instance.first_enabled_at = timezone.now()@@ -571,13 +578,25 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):apply_outcome(instance, apply_enable(snapshot), kind=LogsAlertEvent.Kind.ENABLE)elif enabled_change is False:apply_outcome(instance, apply_disable(snapshot), kind=LogsAlertEvent.Kind.DISABLE)+ close_reason = IncidentCloseReason.DISABLEDelif snooze_data is not _SENTINEL:if snooze_data is None:apply_outcome(instance, apply_unsnooze(snapshot), kind=LogsAlertEvent.Kind.UNSNOOZE)else:apply_outcome(instance, apply_snooze(snapshot), kind=LogsAlertEvent.Kind.SNOOZE)+ close_reason = IncidentCloseReason.SNOOZEDelif threshold_changed:apply_outcome(instance, apply_threshold_change(snapshot), kind=LogsAlertEvent.Kind.THRESHOLD_CHANGE)+ close_reason = IncidentCloseReason.CONFIG_CHANGED+ # The edge check inside decides whether a close goes out, so a new branch above that forgets+ # its reason still closes the incident.+ close_incident_on_commit(+ team_id=instance.team_id,+ alert_id=str(instance.id),+ state_before=state_before,+ state_after=instance.state,+ reason=close_reason or IncidentCloseReason.CONFIG_CHANGED,+ )# snooze_until is a timestamp column, not a state — carry it alongside the state# transition so the serializer's single save persists both.@@ -1373,6 +1392,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):self._track("updated", serializer.save())def perform_destroy(self, instance: LogsAlertConfiguration) -> None:+ close_incident_before_delete(team_id=instance.team_id, alert_id=str(instance.id), state=instance.state)with transaction.atomic():locked_instance = (LogsAlertConfiguration.objects.select_for_update()diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex daa3168808c2..ef2b2c57b0d5 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -29,7 +29,6 @@ from posthog.sync import database_sync_to_async_poolfrom products.alerts.backend.facade.destinations import (alert_internal_event_delivered,- configured_destination_template_ids,flush_alert_internal_events,produce_alert_internal_event,)@@ -49,6 +48,7 @@ from products.logs.backend.alert_error_classifier import (AlertErrorCode,classify as classify_alert_error,)+from products.logs.backend.alert_incidents import close_incident, has_incident_destination, incident_closed_propertiesfrom products.logs.backend.alert_signal_emitter import (NotifiedAlert,emit_alert_state_change_signal,@@ -511,7 +511,9 @@ def _mark_alert_broken_for_bad_config(alert_id: str, reason: str) -> None:returnif incident_edge(state_seen, AlertState.BROKEN) == IncidentEdge.CLOSED:alert_for_close = LogsAlertConfiguration.objects.get(pk=alert_id)- if _has_incident_destination(alert_for_close) and not _close_incident_for_bad_config(alert_for_close):+ if has_incident_destination(alert_for_close) and not close_incident(+ alert_for_close, IncidentCloseReason.BROKEN, flush_timeout_seconds=NOTIFICATION_FLUSH_TIMEOUT_SECONDS+ ):logger.warning("Deferring BROKEN until the incident close is delivered", alert_id=alert_id)returnwith transaction.atomic():@@ -544,20 +546,6 @@ def _mark_alert_broken_for_bad_config(alert_id: str, reason: str) -> None:capture_exception(e)-def _close_incident_for_bad_config(alert: LogsAlertConfiguration) -> bool:- """Send the close for an alert about to break on bad config. Return whether the broker took it."""- produce_result = _emit_incident_closed_event(alert, IncidentCloseReason.BROKEN, datetime.now(UTC))- if produce_result is None:- return False- flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)- return alert_internal_event_delivered(- produce_result,- team_id=alert.team_id,- alert_id=str(alert.id),- event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,- )--def _cohort_manifests_from_alerts(rows: Sequence[dict],*,@@ -1115,7 +1103,7 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _Dispatcdate_to=evaluation.date_to,)edge = incident_edge(evaluation.state_before, evaluation.outcome.new_state)- incident_expected = edge is not None and _has_incident_destination(evaluation.alert)+ incident_expected = edge is not None and has_incident_destination(evaluation.alert)incident_produce_result = _dispatch_incident_edge(edge, evaluation, now) if edge and incident_expected else Noneenqueue_failed = (evaluation.outcome.notification != NotificationAction.NONE and produce_result is None) or (incident_expected and incident_produce_result is None@@ -1128,21 +1116,6 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _Dispatc)-def _has_incident_destination(alert: LogsAlertConfiguration) -> bool:- """Whether a destination of this alert follows the incident kinds.-- An alert without one sends no incident events, so a lost incident event can never roll back a- notification its Slack, Teams or webhook destinations already received.- """- return bool(- configured_destination_template_ids(- team_id=alert.team_id,- alert_id=str(alert.id),- allowed_event_ids=(LOGS_ALERT_INCIDENT_OPENED_EVENT, LOGS_ALERT_INCIDENT_CLOSED_EVENT),- )- )--def _dispatch_incident_edge(edge: IncidentEdge, evaluation: _AlertEvaluation, now: datetime) -> ProduceResult | None:alert = evaluation.alertif edge == IncidentEdge.OPENED:@@ -1643,13 +1616,7 @@ def _emit_incident_closed_event(reason: IncidentCloseReason,now: datetime,) -> ProduceResult | None:- properties = {- "alert_id": str(alert.id),- "alert_name": alert.name,- "team_id": alert.team_id,- "reason": reason.value,- "triggered_at": now.isoformat(),- }+ properties = incident_closed_properties(alert, reason, now)return _produce_alert_internal_event(alert, LOGS_ALERT_INCIDENT_CLOSED_EVENT, properties, now)diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 88d39d53a98f..581b3860461a 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -654,6 +654,66 @@ class TestLogsAlertAPI(APIBaseTest):assert response.json()["state"] == "not_firing"assert response.json()["enabled"] is False+ def _add_pagerduty_destination(self, alert_id: str) -> None:+ self._sync_destination_templates()+ response = self.client.post(+ self._destinations_url(alert_id),+ {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ @parameterized.expand(+ [+ ("disable", lambda: {"enabled": False}, True, "disabled"),+ (+ "snooze",+ lambda: {"snooze_until": (datetime.now(UTC) + timedelta(hours=1)).isoformat()},+ True,+ "snoozed",+ ),+ ("threshold_change", lambda: {"threshold_count": 50}, True, "config_changed"),+ ("filter_change", lambda: {"filters": {"severityLevels": ["warn"]}}, True, "config_changed"),+ ("window_change", lambda: {"window_minutes": 10}, True, None),+ ("rename", lambda: {"name": "Renamed"}, True, None),+ ("disable_without_pagerduty", lambda: {"enabled": False}, False, None),+ ]+ )+ def test_leaving_firing_through_the_api_closes_the_incident(+ self, _name, make_payload, has_pagerduty, expected_reason+ ):+ created = self._create_via_api()+ if has_pagerduty:+ self._add_pagerduty_destination(created["id"])+ LogsAlertConfiguration.objects.filter(pk=created["id"]).update(state="firing")+ payload = make_payload()++ with (+ patch("products.logs.backend.alert_incidents.produce_alert_internal_event") as mock_produce,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.patch(f"{self.base_url}{created['id']}/", payload, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ closes = [c.kwargs["properties"] for c in mock_produce.call_args_list]+ if expected_reason is None:+ assert closes == []+ else:+ assert [(close["alert_id"], close["reason"]) for close in closes] == [(created["id"], expected_reason)]++ def test_deleting_a_firing_alert_sends_a_close_before_its_destinations_go(self):+ created = self._create_via_api()+ self._add_pagerduty_destination(created["id"])+ LogsAlertConfiguration.objects.filter(pk=created["id"]).update(state="firing")++ with patch("products.logs.backend.alert_incidents.produce_alert_internal_event") as mock_produce:+ response = self.client.delete(f"{self.base_url}{created['id']}/")++ assert response.status_code == status.HTTP_204_NO_CONTENT+ mock_produce.assert_called_once()+ assert mock_produce.call_args.kwargs["event_name"] == "$logs_alert_incident_closed"+ assert mock_produce.call_args.kwargs["properties"]["reason"] == "deleted"+# --- Edit behavior: recheck and state reset ---def test_threshold_change_resets_state_and_clears_next_check(self):diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex 5e7697e533ee..dc0730a9d2ca 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -2188,7 +2188,7 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):)_add_incident_destination(broken)- with patch("products.logs.backend.temporal.activities.produce_alert_internal_event") as mock_produce:+ with patch("products.logs.backend.alert_incidents.produce_alert_internal_event") as mock_produce:if not close_delivered:mock_produce.return_value.get.side_effect = TimeoutError("undelivered")result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.tsindex c4a441b8daeb..2225ff78782e 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts@@ -49,7 +49,8 @@ export const LOGS_ALERT_EVENT_KIND_META: Record<LogsAlertEventKind, { label: str},incident_closed: {label: 'Resolve incident',- description: 'Resolves the incident when the alert stops firing or is auto-disabled.',+ description:+ 'Resolves the incident when the alert stops firing, including when you disable, snooze, or edit it, or it is auto-disabled.',},}