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.

feat(alerts): monitor notification delivery SLO (#74876)

Matt Puab19d0203ca81
diff --git a/posthog/slo/context.py b/posthog/slo/context.py
index 377edeefb0f1..e9b2a6496d36 100644
--- a/posthog/slo/context.py
+++ b/posthog/slo/context.py
@@ -57,6 +57,7 @@ class SloSpec:
@dataclasses.dataclass
class SloHandle:
+ operation: SloOperation | None = None
completion_properties: dict[str, JsonValue] = dataclasses.field(default_factory=dict)
outcome_override: SloOutcome | None = None
@@ -120,7 +121,7 @@ def slo_operation(
a no-exception path as an SLO failure.
"""
- handle = SloHandle()
+ handle = SloHandle(operation=spec.operation)
base_properties = dict(properties or {})
base_properties["correlation_id"] = str(uuid4())
# One coin flip per operation: started+completed share fate, so a sampled
diff --git a/posthog/slo/types.py b/posthog/slo/types.py
index a9d0f55f4b93..b384ea9eb4ca 100644
--- a/posthog/slo/types.py
+++ b/posthog/slo/types.py
@@ -14,6 +14,7 @@ class SloOperation(StrEnum):
SUBSCRIPTION_DELETE = "subscription_delete"
AI_SUBSCRIPTION_PROMPT_GENERATION = "ai_subscription_prompt_generation"
ALERT_CHECK = "alert_check"
+ ALERT_DELIVERY = "alert_delivery"
QUERY_SERVICE = "query_service"
DASHBOARD_WIDGET_DELIVERY = "dashboard_widget_delivery"
PULSE_BRIEF_GENERATION = "pulse-brief-generation"
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index 080c1032684c..20a27913fa2b 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -7,6 +7,8 @@ from parameterized import parameterized
from posthog.schema import AlertCalculationInterval
+from posthog.slo.context import SloSpec, slo_operation
+from posthog.slo.types import SloArea, SloOperation, SloOutcome
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
@@ -52,6 +54,8 @@ class TestAlertUtils:
),
]
)
+ @patch("posthog.tasks.alerts.utils.alert_internal_event_delivered", return_value=True)
+ @patch("posthog.tasks.alerts.utils.flush_alert_internal_events")
@patch("posthog.tasks.alerts.utils.produce_alert_internal_event")
def test_trigger_alert_hog_functions_uses_shared_delivery(
self,
@@ -59,6 +63,8 @@ class TestAlertUtils:
detector_config: dict | None,
expected_props: dict,
mock_produce: MagicMock,
+ mock_flush: MagicMock,
+ mock_delivered: MagicMock,
) -> None:
mock_produce.return_value = MagicMock()
alert = MagicMock(spec=AlertConfiguration)
@@ -79,6 +85,8 @@ class TestAlertUtils:
assert props[key] == expected_value
assert props["breaches"] == "test breach"
assert "uuid" not in mock_produce.call_args.kwargs
+ mock_flush.assert_not_called()
+ mock_delivered.assert_not_called()
@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:
@@ -89,3 +97,75 @@ class TestAlertUtils:
alert.detector_config = None
trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
+
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event", return_value=None)
+ def test_destination_enqueue_failure_fails_delivery_slo(self, _mock_produce: MagicMock) -> None:
+ 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 = None
+ capture = MagicMock()
+
+ with slo_operation(
+ spec=SloSpec(
+ distinct_id=str(alert.id),
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.ALERT_DELIVERY,
+ team_id=alert.team_id,
+ resource_id=str(alert.id),
+ ),
+ capture=capture,
+ ):
+ trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
+
+ completed = [call for call in capture.call_args_list if call.kwargs["event"] == "slo_operation_completed"]
+ assert len(completed) == 1
+ assert completed[0].kwargs["properties"]["outcome"] == SloOutcome.FAILURE
+ assert completed[0].kwargs["properties"]["failure_phase"] == "destination_enqueue"
+
+ @patch("posthog.tasks.alerts.utils.alert_internal_event_delivered", return_value=False)
+ @patch("posthog.tasks.alerts.utils.flush_alert_internal_events")
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event")
+ def test_destination_delivery_failure_fails_delivery_slo(
+ self,
+ mock_produce: MagicMock,
+ mock_flush: MagicMock,
+ _mock_delivered: MagicMock,
+ ) -> None:
+ produce_result = MagicMock()
+ mock_produce.return_value = produce_result
+ 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 = None
+ capture = MagicMock()
+
+ with slo_operation(
+ spec=SloSpec(
+ distinct_id=str(alert.id),
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.ALERT_DELIVERY,
+ team_id=alert.team_id,
+ resource_id=str(alert.id),
+ ),
+ capture=capture,
+ ):
+ trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})
+
+ mock_flush.assert_called_once_with(10.0)
+ completed = [call for call in capture.call_args_list if call.kwargs["event"] == "slo_operation_completed"]
+ assert len(completed) == 1
+ assert completed[0].kwargs["properties"]["outcome"] == SloOutcome.FAILURE
+ assert completed[0].kwargs["properties"]["failure_phase"] == "notification_delivery"
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index 9f492b0e2244..d8c3f2c3cdf6 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -1,4 +1,5 @@
from collections.abc import Collection
+from contextlib import ExitStack
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -9,9 +10,17 @@ import structlog
from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
+from posthog.slo.context import get_current_slo
+from posthog.slo.types import SloOperation
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.delivery_slo import alert_delivery_slo
+from products.alerts.backend.destinations import (
+ ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS,
+ alert_internal_event_delivered,
+ flush_alert_internal_events,
+ 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,
@@ -149,12 +158,27 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->
**properties,
}
- result = produce_alert_internal_event(
+ produce_result = produce_alert_internal_event(
team_id=alert.team_id,
event_name=INSIGHT_ALERT_FIRING_EVENT,
properties=props,
)
- return result is not None
+ slo = get_current_slo()
+ if slo is None or slo.operation != SloOperation.ALERT_DELIVERY:
+ return produce_result is not None
+ if produce_result is None:
+ slo.fail(failure_phase="destination_enqueue")
+ return False
+
+ flush_alert_internal_events(ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS)
+ if not alert_internal_event_delivered(
+ produce_result,
+ team_id=alert.team_id,
+ alert_id=str(alert.id),
+ event_name=INSIGHT_ALERT_FIRING_EVENT,
+ ):
+ slo.fail(failure_phase="notification_delivery")
+ return True
def send_notifications_for_breaches(
@@ -266,35 +290,53 @@ def dispatch_alert_notification(
ValueError: state is FIRING but breaches is None/empty.
AssertionError: unknown state — surfaces a missing AlertState branch loudly.
"""
- match alert_check.state:
- case AlertState.NOT_FIRING:
- logger.info("Check state is NOT_FIRING, nothing to send", alert_id=alert.id)
- return None
- case AlertState.ERRORED:
- if not isinstance(alert_check.error, dict):
- logger.warning(
- "ERRORED alert_check has non-dict error payload; skipping notification",
- alert_id=alert.id,
- alert_check_id=alert_check.id,
+ with ExitStack() as stack:
+ if alert_check.state == AlertState.FIRING:
+ stack.enter_context(
+ alert_delivery_slo(
+ alert_type="insight",
+ notification_action="fire",
+ distinct_id=str(alert.id),
+ team_id=alert.team_id,
+ resource_id=str(alert.id),
+ properties={
+ "alert_check_id": str(alert_check.id),
+ "alert_state": alert_check.state,
+ "calculation_interval": alert.calculation_interval,
+ "insight_id": alert.insight_id,
+ },
)
+ )
+
+ match alert_check.state:
+ case AlertState.NOT_FIRING:
+ logger.info("Check state is NOT_FIRING, nothing to send", alert_id=alert.id)
return None
- return send_notifications_for_errors(alert, alert_check.error)
- case AlertState.FIRING:
- if not breaches:
- raise ValueError(
- f"dispatch_alert_notification: FIRING alert_check {alert_check.id} has no breaches — "
- "caller must pass the breaches list from AlertEvaluationResult"
- )
- logger.info("Sending alert firing notifications", alert_id=alert.id)
- # Only forward extra_properties when there's something to add (anomaly investigations),
- # keeping the common threshold-alert call unchanged.
- if extra_properties:
- return send_notifications_for_breaches(
- alert, breaches, idempotency_key=str(alert_check.id), extra_properties=extra_properties
- )
- return send_notifications_for_breaches(alert, breaches, idempotency_key=str(alert_check.id))
- case _:
- raise AssertionError(f"dispatch_alert_notification: unhandled alert state: {alert_check.state}")
+ case AlertState.ERRORED:
+ if not isinstance(alert_check.error, dict):
+ logger.warning(
+ "ERRORED alert_check has non-dict error payload; skipping notification",
+ alert_id=alert.id,
+ alert_check_id=alert_check.id,
+ )
+ return None
+ return send_notifications_for_errors(alert, alert_check.error)
+ case AlertState.FIRING:
+ if not breaches:
+ raise ValueError(
+ f"dispatch_alert_notification: FIRING alert_check {alert_check.id} has no breaches — "
+ "caller must pass the breaches list from AlertEvaluationResult"
+ )
+ logger.info("Sending alert firing notifications", alert_id=alert.id)
+ # Only forward extra_properties when there's something to add (anomaly investigations),
+ # keeping the common threshold-alert call unchanged.
+ if extra_properties:
+ return send_notifications_for_breaches(
+ alert, breaches, idempotency_key=str(alert_check.id), extra_properties=extra_properties
+ )
+ return send_notifications_for_breaches(alert, breaches, idempotency_key=str(alert_check.id))
+ case _:
+ raise AssertionError(f"dispatch_alert_notification: unhandled alert state: {alert_check.state}")
def record_alert_delivery(alert: AlertConfiguration, alert_check: AlertCheck, targets: list[str]) -> None:
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index ce34a00e29dc..bd2cf3ff5b7d 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -1,4 +1,5 @@
import traceback
+from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from django.db import transaction
@@ -58,6 +59,8 @@ from products.notifications.backend.facade.api import (
logger = structlog.get_logger(__name__)
+_NOTIFICATION_DELIVERY_EXECUTOR = ThreadPoolExecutor(max_workers=10, thread_name_prefix="insight-alert-delivery")
+
@temporalio.activity.defn
async def retrieve_due_alerts() -> list[AlertInfo]:
@@ -372,7 +375,7 @@ def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breac
async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:
"""Send notifications for a previously evaluated alert check (idempotent)."""
- @database_sync_to_async(thread_sensitive=False)
+ @database_sync_to_async(thread_sensitive=False, executor=_NOTIFICATION_DELIVERY_EXECUTOR)
def _notify() -> None:
# Mismatched pair surfaces as DoesNotExist instead of notifying the wrong alert.
alert_check = AlertCheck.objects.select_related("alert_configuration", "alert_configuration__team").get(
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 9e61771c6e4d..48694c4054f6 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -24,6 +24,7 @@ from posthog.schema import (
from posthog.constants import AvailableFeature
from posthog.exceptions import ClickHouseAtCapacity
from posthog.models import User
+from posthog.slo.types import SloOperation, SloOutcome
from posthog.tasks.alerts.utils import AlertEvaluationResult
from posthog.temporal.alerts.activities import cleanup_alert_checks, evaluate_alert, notify_alert, prepare_alert
from posthog.temporal.alerts.types import (
@@ -492,6 +493,8 @@ class TestNotifyAlert:
check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
with (
+ patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,
+ patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),
patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
return_value=["[email protected]"],
@@ -517,6 +520,18 @@ class TestNotifyAlert:
refreshed_alert = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_user.pk)
assert refreshed_alert.last_notified_at is not None
+ completed = [
+ call
+ for call in mock_slo_analytics.capture.call_args_list
+ if call.kwargs["event"] == "slo_operation_completed"
+ ]
+ assert len(completed) == 1
+ properties = completed[0].kwargs["properties"]
+ assert properties["operation"] == SloOperation.ALERT_DELIVERY
+ assert properties["outcome"] == SloOutcome.SUCCESS
+ assert properties["region"] == "US"
+ assert properties["alert_check_id"] == str(check.id)
+
async def test_firing_passes_stable_idempotency_key_to_breach_sender(self, alert_with_user) -> None:
# MessagingRecord dedupes email retries via campaign_key; notify_alert must pass
# the AlertCheck id so a retry reuses the same key.
@@ -611,9 +626,13 @@ class TestNotifyAlert:
async def test_raises_on_send_failure(self, alert_with_user) -> None:
check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
- with patch(
- "posthog.tasks.alerts.utils.send_notifications_for_breaches",
- side_effect=RuntimeError("SMTP unavailable"),
+ with (
+ patch("posthog.slo.events.posthoganalytics") as mock_slo_analytics,
+ patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),
+ patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ side_effect=RuntimeError("SMTP unavailable"),
+ ),
):
env = ActivityEnvironment()
with pytest.raises(RuntimeError):
@@ -630,6 +649,14 @@ class TestNotifyAlert:
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
assert refreshed.targets_notified == {}
+ completed = [
+ call
+ for call in mock_slo_analytics.capture.call_args_list
+ if call.kwargs["event"] == "slo_operation_completed"
+ ]
+ assert len(completed) == 1
+ assert completed[0].kwargs["properties"]["outcome"] == SloOutcome.FAILURE
+
async def test_firing_dispatches_realtime_notification(self, alert_with_user) -> None:
check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 5203471e6f30..6ccf31e13805 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -188,11 +188,13 @@ async def _run_check_alert_workflow(alert_id: str, slo: SloConfig, team_id: int,
)
-def _completed_slo_props(mock_slo_analytics: MagicMock) -> dict:
+def _completed_slo_props(mock_slo_analytics: MagicMock, operation: SloOperation = SloOperation.ALERT_CHECK) -> dict:
completed = [
- c for c in mock_slo_analytics.capture.call_args_list if c.kwargs.get("event") == "slo_operation_completed"
+ c
+ for c in mock_slo_analytics.capture.call_args_list
+ if c.kwargs.get("event") == "slo_operation_completed" and c.kwargs["properties"]["operation"] == operation
]
- assert len(completed) == 1, f"expected 1 SLO completion event, got {len(completed)}"
+ assert len(completed) == 1, f"expected 1 {operation} SLO completion event, got {len(completed)}"
return completed[0].kwargs["properties"]
@@ -235,6 +237,11 @@ async def test_check_alert_workflow_firing_drives_full_chain_with_slo(
assert completed_props["alert_state"] == AlertState.FIRING
assert completed_props["calculation_interval"] == alert_with_subscriber.calculation_interval
+ delivery_props = _completed_slo_props(mock_slo_analytics, SloOperation.ALERT_DELIVERY)
+ assert delivery_props["outcome"] == SloOutcome.SUCCESS
+ assert delivery_props["alert_type"] == "insight"
+ assert delivery_props["region"] == "HOBBY"
+
@pytest.mark.parametrize(
"setup,expected_reason",
diff --git a/products/alerts/backend/delivery_slo.py b/products/alerts/backend/delivery_slo.py
new file mode 100644
index 000000000000..3099e450a8ef
--- /dev/null
+++ b/products/alerts/backend/delivery_slo.py
@@ -0,0 +1,34 @@
+from collections.abc import Iterator, Mapping
+from contextlib import contextmanager
+
+from posthog.slo.context import JsonValue, SloHandle, SloSpec, slo_operation
+from posthog.slo.types import SloArea, SloOperation
+from posthog.utils import get_instance_region
+
+
+@contextmanager
+def alert_delivery_slo(
+ *,
+ alert_type: str,
+ notification_action: str,
+ distinct_id: str,
+ team_id: int,
+ resource_id: str,
+ properties: Mapping[str, JsonValue] | None = None,
+) -> Iterator[SloHandle]:
+ with slo_operation(
+ spec=SloSpec(
+ distinct_id=distinct_id,
+ area=SloArea.ANALYTIC_PLATFORM,
+ operation=SloOperation.ALERT_DELIVERY,
+ team_id=team_id,
+ resource_id=resource_id,
+ ),
+ properties={
+ **dict(properties or {}),
+ "alert_type": alert_type,
+ "notification_action": notification_action,
+ "region": (get_instance_region() or "HOBBY").upper(),
+ },
+ ) as slo:
+ yield slo
diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.py
index d79d56541242..449a52181205 100644
--- a/products/alerts/backend/destinations.py
+++ b/products/alerts/backend/destinations.py
@@ -25,6 +25,8 @@ from products.cdp.backend.models.hog_functions.hog_function import HogFunction
logger = structlog.get_logger(__name__)
+ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS = 10.0
+
ALERT_INTERNAL_EVENT_DELIVERY_FAILURES = Counter(
"posthog_alert_internal_event_delivery_failures_total",
"Number of alert internal events that failed delivery",
diff --git a/products/alerts/backend/test/test_delivery_slo.py b/products/alerts/backend/test/test_delivery_slo.py
new file mode 100644
index 000000000000..1dfc5998d3ff
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_slo.py
@@ -0,0 +1,37 @@
+from unittest.mock import MagicMock, patch
+
+from posthog.slo.types import SloOperation, SloOutcome
+
+from products.alerts.backend.delivery_slo import alert_delivery_slo
+
+
+@patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="EU")
+@patch("posthog.slo.context.emit_slo_completed")
+@patch("posthog.slo.context.emit_slo_started")
+def test_alert_delivery_slo_emits_shared_dimensions(
+ mock_emit_started: MagicMock,
+ mock_emit_completed: MagicMock,
+ _mock_region: MagicMock,
+) -> None:
+ with alert_delivery_slo(
+ alert_type="future_alert_type",
+ notification_action="fire",
+ distinct_id="alert-1",
+ team_id=2,
+ resource_id="alert-1",
+ properties={"delivery_id": "delivery-1"},
+ ) as slo:
+ slo.fail(failure_phase="destination_enqueue")
+
+ started = mock_emit_started.call_args.kwargs
+ completed = mock_emit_completed.call_args.kwargs
+ assert started["properties"].operation == SloOperation.ALERT_DELIVERY
+ assert completed["properties"].outcome == SloOutcome.FAILURE
+ assert completed["extra_properties"] == {
+ "delivery_id": "delivery-1",
+ "alert_type": "future_alert_type",
+ "notification_action": "fire",
+ "region": "EU",
+ "correlation_id": started["extra_properties"]["correlation_id"],
+ "failure_phase": "destination_enqueue",
+ }
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index f21b019dfd2e..8542573a2748 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -26,6 +26,7 @@ from posthog.slo.context import SloHandle, SloSpec, slo_operation
from posthog.slo.types import SloArea, SloOperation
from posthog.sync import database_sync_to_async_pool
+from products.alerts.backend.delivery_slo import alert_delivery_slo
from products.alerts.backend.destinations import (
alert_internal_event_delivered,
flush_alert_internal_events,
@@ -646,6 +647,25 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
slo_handles[alert_id].fail(failure_phase="evaluation")
local_stats["errored"] += 1
+ delivery_slo_handles: dict[str, SloHandle] = {}
+ for evaluation in evaluations:
+ delivery_action = evaluation.outcome.notification
+ if delivery_action != NotificationAction.NONE:
+ alert_id = str(evaluation.alert.id)
+ delivery_slo_handles[alert_id] = slo_stack.enter_context(
+ alert_delivery_slo(
+ alert_type="logs",
+ notification_action=delivery_action.value,
+ distinct_id=alert_id,
+ team_id=evaluation.alert.team_id,
+ resource_id=alert_id,
+ properties={
+ "check_interval_minutes": evaluation.alert.check_interval_minutes,
+ "window_minutes": evaluation.alert.window_minutes,
+ },
+ )
+ )
+
dispatched_or_errors = await asyncio.gather(
*(dispatch_async(ev, now) for ev in evaluations),
return_exceptions=True,
@@ -663,6 +683,8 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
exc_info=result,
)
slo_handles[alert_id].fail(failure_phase="dispatch")
+ if delivery_slo := delivery_slo_handles.get(alert_id):
+ delivery_slo.fail(failure_phase="dispatch")
local_stats["errored"] += 1
else:
dispatched.append(result)
@@ -676,6 +698,14 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva
if any(d.produce_result is not None for d in dispatched):
dispatched = await asyncio.to_thread(_resolve_notification_deliveries, dispatched)
+ for dispatched_alert in dispatched:
+ alert_id = str(dispatched_alert.evaluation.alert.id)
+ if delivery_slo := delivery_slo_handles.get(alert_id):
+ if dispatched_alert.notification_failed:
+ delivery_slo.fail(failure_phase="notification_delivery")
+ else:
+ delivery_slo.succeed()
+
try:
saved, failed = (await save_cohort_async(dispatched, now)) if dispatched else ([], [])
except Exception as e:
diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.py
index 505d078e2370..d483a5d9e161 100644
--- a/products/logs/backend/test/test_logs_alerting_activities.py
+++ b/products/logs/backend/test/test_logs_alerting_activities.py
@@ -2154,6 +2154,7 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.alerts_checked == 1
@freeze_time("2025-01-01T00:01:00Z")
+ @patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US")
@patch("posthog.slo.context.emit_slo_completed")
@patch("posthog.slo.context.emit_slo_started")
@patch("products.alerts.backend.destinations.flush_internal_events_producer", return_value=0)
@@ -2166,6 +2167,7 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
_mock_flush,
mock_emit_slo_started,
mock_emit_slo_completed,
+ _mock_region,
):
from products.logs.backend.temporal.activities import (
CohortManifest,
@@ -2217,15 +2219,37 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):
assert result.notified == []
# The cycle still advances so the next cycle re-evaluates and retries the notification.
assert alert.next_check_at is not None
- mock_emit_slo_started.assert_called_once()
- mock_emit_slo_completed.assert_called_once()
- assert mock_emit_slo_completed.call_args.kwargs["properties"].outcome == SloOutcome.FAILURE
- assert mock_emit_slo_completed.call_args.kwargs["extra_properties"] == {
+ assert mock_emit_slo_started.call_count == 2
+ assert mock_emit_slo_completed.call_count == 2
+ started_by_operation = {
+ call.kwargs["properties"].operation: call for call in mock_emit_slo_started.call_args_list
+ }
+ completed_by_operation = {
+ call.kwargs["properties"].operation: call for call in mock_emit_slo_completed.call_args_list
+ }
+ alert_check_completed = completed_by_operation[SloOperation.ALERT_CHECK]
+ assert alert_check_completed.kwargs["properties"].outcome == SloOutcome.FAILURE
+ assert alert_check_completed.kwargs["extra_properties"] == {
"alert_type": "logs",
"check_interval_minutes": alert.check_interval_minutes,
"window_minutes": alert.window_minutes,
- "correlation_id": mock_emit_slo_started.call_args.kwargs["extra_properties"]["correlation_id"],
+ "correlation_id": started_by_operation[SloOperation.ALERT_CHECK].kwargs["extra_properties"][
+ "correlation_id"
+ ],
"alert_state": AlertState.NOT_FIRING,
"notification_action": NotificationAction.FIRE.value,
"failure_phase": "notification_delivery",
}
+ delivery_completed = completed_by_operation[SloOperation.ALERT_DELIVERY]
+ assert delivery_completed.kwargs["properties"].outcome == SloOutcome.FAILURE
+ assert delivery_completed.kwargs["extra_properties"] == {
+ "alert_type": "logs",
+ "notification_action": NotificationAction.FIRE.value,
+ "region": "US",
+ "check_interval_minutes": alert.check_interval_minutes,
+ "window_minutes": alert.window_minutes,
+ "correlation_id": started_by_operation[SloOperation.ALERT_DELIVERY].kwargs["extra_properties"][
+ "correlation_id"
+ ],
+ "failure_phase": "notification_delivery",
+ }
diff --git a/products/tasks/backend/temporal/bake_dev_stack_image/test_activities.py b/products/tasks/backend/temporal/bake_dev_stack_image/test_bake_dev_stack_image_activities.py
similarity index 100%
rename from products/tasks/backend/temporal/bake_dev_stack_image/test_activities.py
rename to products/tasks/backend/temporal/bake_dev_stack_image/test_bake_dev_stack_image_activities.py
diff --git a/terraform/us/project-2/team-analytics-platform/slo-monitoring/alerts.tf b/terraform/us/project-2/team-analytics-platform/slo-monitoring/alerts.tf
new file mode 100644
index 000000000000..6484cbdd4d2e
--- /dev/null
+++ b/terraform/us/project-2/team-analytics-platform/slo-monitoring/alerts.tf
@@ -0,0 +1,14 @@
+resource "posthog_alert" "alert_delivery_slo" {
+ for_each = posthog_insight.alert_delivery_failure_rate
+
+ name = "Alert notification delivery SLO breach (${each.key})"
+ enabled = true
+ calculation_interval = "daily"
+ condition_type = "absolute_value"
+ threshold_type = "absolute"
+ threshold_upper = 0.0005
+ series_index = 0
+ check_ongoing_interval = false
+ insight = each.value.id
+ subscribed_users = var.analytics_platform_alert_subscribed_user_ids
+}
diff --git a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
index 70c3aafbd617..77f8c8431efc 100644
--- a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
+++ b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
@@ -35,6 +35,11 @@ locals {
slo = 99.95 # error budget = 0.05%
regions = ["US", "EU"]
}
+ alert_delivery = {
+ name = "Alert notification delivery"
+ slo = 99.95 # error budget = 0.05%
+ regions = ["US", "EU"]
+ }
dashboard_widget_delivery = {
name = "Dashboard widget delivery"
slo = 99.95 # error budget = 0.05%
@@ -517,3 +522,148 @@ resource "posthog_insight" "slo_volume" {
dashboard_ids = [posthog_dashboard.slo_monitoring.id]
tags = ["managed-by:terraform", "slo"]
}
+
+resource "posthog_insight" "alert_delivery_by_type" {
+ name = "SLO: Alert notification delivery by alert type"
+ description = "Daily delivery success for each alert type and region. New alert types appear automatically."
+ query_json = jsonencode({
+ kind = "DataVisualizationNode"
+ source = {
+ kind = "HogQLQuery"
+ query = <<-SQL
+ WITH delivery_events AS (
+ SELECT
+ event,
+ timestamp,
+ coalesce(nullIf(properties.correlation_id, ''), '') AS correlation_id,
+ coalesce(nullIf(properties.region, ''), 'unknown') AS region,
+ coalesce(nullIf(properties.alert_type, ''), 'unknown') AS alert_type,
+ properties.outcome AS outcome
+ FROM events
+ WHERE event IN ('slo_operation_started', 'slo_operation_completed')
+ AND properties.operation = 'alert_delivery'
+ AND timestamp >= now() - INTERVAL 28 DAY
+ ),
+ per_delivery_day AS (
+ SELECT
+ correlation_id,
+ region,
+ alert_type,
+ toDate(timestamp) AS event_day,
+ countIf(event = 'slo_operation_started') AS starts,
+ countIf(event = 'slo_operation_completed' AND outcome = 'success') AS successes,
+ min(if(event = 'slo_operation_started', timestamp, NULL)) AS first_start
+ FROM delivery_events
+ GROUP BY correlation_id, region, alert_type, event_day
+ ),
+ daily AS (
+ SELECT day, region, alert_type, sum(started) AS started, sum(successes) AS successes
+ FROM (
+ SELECT
+ event_day AS day,
+ region,
+ alert_type,
+ starts AS started,
+ least(starts, successes) AS successes
+ FROM per_delivery_day
+ WHERE correlation_id = ''
+
+ UNION ALL
+
+ SELECT
+ toDate(min(first_start)) AS day,
+ region,
+ alert_type,
+ 1 AS started,
+ if(max(successes) > 0, 1, 0) AS successes
+ FROM per_delivery_day
+ WHERE correlation_id != ''
+ GROUP BY correlation_id, region, alert_type
+ HAVING day IS NOT NULL
+ )
+ GROUP BY day, region, alert_type
+ )
+ SELECT
+ day,
+ concat(region, ' / ', alert_type) AS series,
+ round(if(started > 0, successes / started * 100, 0), 4) AS success_rate,
+ started,
+ successes,
+ started - successes AS failures
+ FROM daily
+ ORDER BY day ASC, series ASC
+ SQL
+ }
+ display = "ActionsLineGraph"
+ chartSettings = {
+ xAxis = { column = "day" }
+ yAxis = [{ column = "success_rate", settings = { formatting = { suffix = "%" } } }]
+ seriesBreakdownColumn = "series"
+ showLegend = true
+ }
+ tableSettings = {
+ columns = [
+ { column = "day" },
+ { column = "series" },
+ { column = "success_rate", settings = { formatting = { suffix = "%" } } },
+ { column = "started" },
+ { column = "successes" },
+ { column = "failures" },
+ ]
+ }
+ })
+
+ dashboard_ids = [posthog_dashboard.slo_monitoring.id]
+ tags = ["managed-by:terraform", "slo"]
+}
+
+resource "posthog_insight" "alert_delivery_failure_rate" {
+ for_each = toset(["US", "EU"])
+
+ name = "SLO: Alert notification delivery failure rate (${each.value})"
+ description = "Daily failed alert notification deliveries among completed attempts."
+ query_json = jsonencode({
+ kind = "InsightVizNode"
+ source = {
+ kind = "TrendsQuery"
+ interval = "day"
+ dateRange = {
+ date_from = "-7d"
+ }
+ series = [
+ {
+ kind = "EventsNode"
+ event = "slo_operation_completed"
+ math = "total"
+ custom_name = "Failed"
+ properties = [
+ { key = "operation", type = "event", value = "alert_delivery", operator = "exact" },
+ { key = "region", type = "event", value = each.value, operator = "exact" },
+ { key = "outcome", type = "event", value = "failure", operator = "exact" },
+ ]
+ },
+ {
+ kind = "EventsNode"
+ event = "slo_operation_completed"
+ math = "total"
+ custom_name = "Completed"
+ properties = [
+ { key = "operation", type = "event", value = "alert_delivery", operator = "exact" },
+ { key = "region", type = "event", value = each.value, operator = "exact" },
+ ]
+ },
+ ]
+ trendsFilter = {
+ display = "ActionsLineGraph"
+ formulaNodes = [
+ { formula = "A/B", custom_name = "Failure rate" },
+ ]
+ aggregationAxisFormat = "percentage_scaled"
+ decimalPlaces = 4
+ showAlertThresholdLines = true
+ }
+ }
+ })
+
+ tags = ["managed-by:terraform", "slo"]
+}