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): record actual delivery receipts in alert check history (#81442)

Vasco de Krijgerb74818621602
diff --git a/posthog/tasks/alerts/investigation_notifications.py b/posthog/tasks/alerts/investigation_notifications.py
index da19d1b6ddd5..534e781322f5 100644
--- a/posthog/tasks/alerts/investigation_notifications.py
+++ b/posthog/tasks/alerts/investigation_notifications.py
@@ -21,7 +21,6 @@ from datetime import UTC, datetime, timedelta
from django.db import transaction
from django.db.models import Q
-from django.utils import timezone
import structlog
@@ -98,13 +97,8 @@ def run_investigation_notification_safety_net() -> int:
if locked.notification_sent_at is not None or locked.notification_suppressed_by_agent:
continue
breaches = _fallback_breach_descriptions(locked)
- targets = dispatch_alert_notification(alert, locked, breaches)
- if targets is not None:
- record_alert_delivery(alert, locked, targets)
- # Set notification_sent_at in lock-step with record_alert_delivery so
- # gating/idempotency reads that still use this marker stay consistent.
- locked.notification_sent_at = timezone.now()
- locked.save(update_fields=["notification_sent_at"])
+ deliveries = dispatch_alert_notification(alert, locked, breaches)
+ record_alert_delivery(alert, locked, deliveries, stamp_on_empty=True)
except Exception:
logger.exception(
"alert.investigation_safety_net_failed",
@@ -113,6 +107,10 @@ def run_investigation_notification_safety_net() -> int:
)
continue
+ if not deliveries:
+ # Stamped but undeliverable — nobody was notified, so it doesn't count.
+ continue
+
logger.warning(
"alert.investigation_safety_net_dispatched",
alert_id=str(alert.id),
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.py
index bc4b3ad0e97d..5e4b827f97fa 100644
--- a/posthog/tasks/alerts/test/alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/alert_check_helpers.py
@@ -52,15 +52,9 @@ def run_alert_check(alert_id: str) -> None:
return
breaches = result.breaches if result else None
- dispatch_targets = alert_utils.dispatch_alert_notification(alert, alert_check, breaches)
- if dispatch_targets is None:
+ deliveries = alert_utils.dispatch_alert_notification(alert, alert_check, breaches)
+ if deliveries is None:
return
- # Resolve targets directly from the alert — tests that @patch send_notifications_*
- # return MagicMock values, so we can't trust dispatch's return. The real activity
- # does trust the return (no mocks), and both paths resolve to the same list.
- targets = alert.get_subscribed_users_emails()
- if not targets:
- return
with transaction.atomic():
- alert_utils.record_alert_delivery(alert, alert_check, targets)
+ alert_utils.record_alert_delivery(alert, alert_check, deliveries)
diff --git a/posthog/tasks/alerts/test/test_alert_check_helpers.py b/posthog/tasks/alerts/test/test_alert_check_helpers.py
index 99e2c9010404..6d63aa777668 100644
--- a/posthog/tasks/alerts/test/test_alert_check_helpers.py
+++ b/posthog/tasks/alerts/test/test_alert_check_helpers.py
@@ -5,9 +5,10 @@ from posthog.schema import AlertConditionType, AlertState, InsightThresholdType
from posthog.api.test.dashboards import DashboardAPI
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
-from posthog.tasks.alerts.utils import AlertEvaluationResult
+from posthog.tasks.alerts.utils import AlertEvaluationResult, record_alert_delivery
-from products.alerts.backend.models import AlertCheck
+from products.alerts.backend.destinations import AlertDelivery
+from products.alerts.backend.models import AlertCheck, AlertConfiguration
class TestRunAlertCheck(APIBaseTest):
@@ -39,7 +40,10 @@ class TestRunAlertCheck(APIBaseTest):
).json()
self.alert_id = alert["id"]
- @patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=["[email protected]"])
+ @patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ return_value=[AlertDelivery(channel="email", target="[email protected]", at="2026-08-11T00:00:00+00:00")],
+ )
@patch("posthog.tasks.alerts.test.alert_check_helpers.check_alert_for_insight")
def test_firing_path_unpacks_tuple_and_records_delivery(self, mock_check: MagicMock, mock_send: MagicMock) -> None:
mock_check.return_value = AlertEvaluationResult(value=5.0, breaches=["breach_message"])
@@ -49,7 +53,8 @@ class TestRunAlertCheck(APIBaseTest):
alert_check = AlertCheck.objects.filter(alert_configuration=self.alert_id).latest("created_at")
assert alert_check.state == AlertState.FIRING
assert alert_check.calculated_value == 5.0
- assert alert_check.targets_notified == {"users": [self.user.email]}
+ assert alert_check.targets_notified == {"users": ["[email protected]"], "destinations": []}
+ assert alert_check.notification_sent_at is not None
mock_send.assert_called_once()
@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
@@ -64,9 +69,9 @@ class TestRunAlertCheck(APIBaseTest):
assert alert_check.targets_notified == {}
mock_send.assert_not_called()
- @patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
+ @patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
@patch("posthog.tasks.alerts.test.alert_check_helpers.check_alert_for_insight")
- def test_errored_path_records_error_and_notifies(self, mock_check: MagicMock, mock_send_err: MagicMock) -> None:
+ def test_errored_path_records_error_without_delivery(self, mock_check: MagicMock, mock_send_err: MagicMock) -> None:
mock_check.side_effect = RuntimeError("boom")
run_alert_check(self.alert_id)
@@ -75,5 +80,63 @@ class TestRunAlertCheck(APIBaseTest):
assert alert_check.state == AlertState.ERRORED
assert alert_check.error is not None
assert "boom" in alert_check.error["message"]
- assert alert_check.targets_notified == {"users": [self.user.email]}
+ assert alert_check.targets_notified == {}
+ assert alert_check.notification_sent_at is None
mock_send_err.assert_called_once()
+
+ def test_record_alert_delivery_noops_on_empty_receipts(self) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert_id)
+ check = AlertCheck.objects.create(alert_configuration=alert, targets_notified={}, state=AlertState.ERRORED)
+
+ assert record_alert_delivery(alert, check, []) is False
+
+ check.refresh_from_db()
+ assert check.targets_notified == {}
+ assert check.notification_sent_at is None
+
+ def test_record_alert_delivery_splits_mixed_channels(self) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert_id)
+ check = AlertCheck.objects.create(alert_configuration=alert, targets_notified={}, state=AlertState.FIRING)
+ email = AlertDelivery(channel="email", target="[email protected]", at="2026-08-11T00:00:00+00:00")
+ hog = AlertDelivery(
+ channel="hog_function",
+ target="Slack #eng",
+ target_id="hf-1",
+ template="slack",
+ at="2026-08-11T00:00:00+00:00",
+ )
+
+ assert record_alert_delivery(alert, check, [email, hog]) is True
+
+ check.refresh_from_db()
+ assert check.targets_notified["users"] == ["[email protected]"]
+ assert [d["target"] for d in check.targets_notified["destinations"]] == ["Slack #eng"]
+
+ def test_record_alert_delivery_writes_legacy_map_and_receipts(self) -> None:
+ alert = AlertConfiguration.objects.get(id=self.alert_id)
+ check = AlertCheck.objects.create(alert_configuration=alert, targets_notified={}, state=AlertState.FIRING)
+ hog = AlertDelivery(
+ channel="hog_function",
+ target="Slack #eng",
+ target_id="hf-1",
+ template="slack",
+ at="2026-08-11T00:00:00+00:00",
+ )
+
+ assert record_alert_delivery(alert, check, [hog]) is True
+
+ check.refresh_from_db()
+ assert check.targets_notified == {
+ "users": [],
+ "destinations": [
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng",
+ "target_id": "hf-1",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ }
+ ],
+ }
+ assert check.notification_sent_at is not None
diff --git a/posthog/tasks/alerts/test/test_investigation_notifications.py b/posthog/tasks/alerts/test/test_investigation_notifications.py
index 0f762b5eedee..c2a23d85ff11 100644
--- a/posthog/tasks/alerts/test/test_investigation_notifications.py
+++ b/posthog/tasks/alerts/test/test_investigation_notifications.py
@@ -14,6 +14,7 @@ from posthog.tasks.alerts.investigation_notifications import (
run_investigation_notification_safety_net,
)
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, InvestigationStatus
from products.product_analytics.backend.models.insight import Insight
@@ -122,17 +123,17 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):
]
)
@patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")
- @patch("posthog.tasks.alerts.investigation_notifications.record_alert_delivery")
def test_grace_period_predicate(
self,
_name: str,
age_minutes: int,
investigation_status: str | None,
expected_dispatched: bool,
- mock_record: object,
mock_dispatch: object,
) -> None:
- mock_dispatch.return_value = ["[email protected]"] # type: ignore[attr-defined]
+ mock_dispatch.return_value = [ # type: ignore[attr-defined]
+ AlertDelivery(channel="email", target="[email protected]", at="2026-08-11T00:00:00+00:00")
+ ]
check = self._make_check(age_minutes=age_minutes, investigation_status=investigation_status)
notified = run_investigation_notification_safety_net()
@@ -147,6 +148,23 @@ class TestInvestigationNotificationSafetyNet(APIBaseTest):
assert check.notification_sent_at is None
mock_dispatch.assert_not_called() # type: ignore[attr-defined]
+ @patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")
+ def test_zero_accept_dispatch_stamps_without_counting(self, mock_dispatch: object) -> None:
+ # Nothing accepted: the stamp must still land (sweep idempotency), but the
+ # check does not count as notified.
+ mock_dispatch.return_value = [] # type: ignore[attr-defined]
+
+ check = self._make_check(
+ age_minutes=INVESTIGATION_NOTIFY_GRACE_MINUTES + 60,
+ investigation_status=InvestigationStatus.DONE,
+ )
+ notified = run_investigation_notification_safety_net()
+
+ check.refresh_from_db()
+ assert notified == 0
+ assert check.notification_sent_at is not None
+ mock_dispatch.assert_called_once() # type: ignore[attr-defined]
+
@patch("posthog.tasks.alerts.investigation_notifications.dispatch_alert_notification")
def test_skips_legacy_delivered_check(self, mock_dispatch: object) -> None:
# Pre-PR-3 `notify_alert` populated targets_notified without setting
diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.py
index 1c1c1aed115f..ddccb4255043 100644
--- a/posthog/tasks/alerts/test/test_metrics_alerts.py
+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py
@@ -72,8 +72,8 @@ def _stub_investigation_result(metric_name: str, mover_label: str = "pod-1") ->
@freeze_time(FROZEN_TIME)
@patch("products.alerts.backend.api.alert.posthoganalytics.feature_enabled", side_effect=_metrics_flag_only)
-@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
+@patch("posthog.tasks.alerts.utils.send_notifications_for_errors", return_value=[])
+@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])
class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
index 8aa6d36aedc1..876cd6f9e8f1 100644
--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py
@@ -28,6 +28,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
# 8:55 AM
@@ -35,8 +36,14 @@ FROZEN_TIME = dateutil.parser.parse("2024-06-02T08:55:00.000Z")
@freeze_time(FROZEN_TIME)
-@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
+@patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_errors",
+ return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-02T08:55:00+00:00")],
+)
+@patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-02T08:55:00+00:00")],
+)
class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixin):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
index 04449dd3df06..6255dfc1456c 100644
--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py
+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py
@@ -29,6 +29,7 @@ from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.models.instance_setting import set_instance_setting
from posthog.tasks.alerts.test.alert_check_helpers import run_alert_check
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
# Tuesday
@@ -36,8 +37,14 @@ FROZEN_TIME = dateutil.parser.parse("2024-06-04T08:55:00.000Z")
@freeze_time(FROZEN_TIME)
-@patch("posthog.tasks.alerts.utils.send_notifications_for_errors")
-@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches")
+@patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_errors",
+ return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-04T08:55:00+00:00")],
+)
+@patch(
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ return_value=[AlertDelivery(channel="email", target="[email protected]", at="2024-06-04T08:55:00+00:00")],
+)
class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixin):
def setUp(self) -> None:
super().setUp()
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.py
index 20a27913fa2b..e9ec6378aef1 100644
--- a/posthog/tasks/alerts/test/test_utils.py
+++ b/posthog/tasks/alerts/test/test_utils.py
@@ -1,6 +1,8 @@
from datetime import UTC, datetime
+import pytest
from freezegun import freeze_time
+from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -9,9 +11,18 @@ 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 posthog.tasks.alerts.utils import (
+ calculation_interval_to_order,
+ disable_invalid_alert,
+ next_check_time,
+ send_notifications_for_breaches,
+ send_notifications_for_errors,
+ trigger_alert_hog_functions,
+)
-from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.destinations import ActiveAlertDestination
+from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.product_analytics.backend.models.insight import Insight
class TestAlertUtils:
@@ -57,11 +68,13 @@ 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")
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations", return_value=[])
def test_trigger_alert_hog_functions_uses_shared_delivery(
self,
_name: str,
detector_config: dict | None,
expected_props: dict,
+ _mock_list: MagicMock,
mock_produce: MagicMock,
mock_flush: MagicMock,
mock_delivered: MagicMock,
@@ -89,7 +102,10 @@ class TestAlertUtils:
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:
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations", return_value=[])
+ def test_trigger_alert_hog_functions_ignores_enqueue_failure(
+ self, _mock_list: MagicMock, _mock_produce: MagicMock
+ ) -> None:
alert = MagicMock(spec=AlertConfiguration)
alert.id = "00000000-0000-0000-0000-000000000001"
alert.team_id = 2
@@ -99,7 +115,10 @@ class TestAlertUtils:
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:
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations", return_value=[])
+ def test_destination_enqueue_failure_fails_delivery_slo(
+ self, _mock_list: MagicMock, _mock_produce: MagicMock
+ ) -> None:
alert = MagicMock(spec=AlertConfiguration)
alert.id = "00000000-0000-0000-0000-000000000001"
alert.name = "test alert"
@@ -132,8 +151,10 @@ class TestAlertUtils:
@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")
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations", return_value=[])
def test_destination_delivery_failure_fails_delivery_slo(
self,
+ _mock_list: MagicMock,
mock_produce: MagicMock,
mock_flush: MagicMock,
_mock_delivered: MagicMock,
@@ -169,3 +190,116 @@ class TestAlertUtils:
assert len(completed) == 1
assert completed[0].kwargs["properties"]["outcome"] == SloOutcome.FAILURE
assert completed[0].kwargs["properties"]["failure_phase"] == "notification_delivery"
+
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event")
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations")
+ def test_trigger_hog_functions_returns_receipt_per_destination(
+ self, mock_list: MagicMock, mock_produce: MagicMock
+ ) -> None:
+ mock_list.return_value = [ActiveAlertDestination(id="hf-1", name="#eng-alerts", destination_type="slack")]
+ mock_produce.return_value = MagicMock() # non-None = enqueue accepted
+ 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
+
+ receipts = trigger_alert_hog_functions(alert=alert, properties={"breaches": "x"})
+
+ assert [(r.channel, r.target, r.target_id, r.template, r.status) for r in receipts] == [
+ ("hog_function", "#eng-alerts", "hf-1", "slack", "accepted")
+ ]
+
+ @patch("posthog.tasks.alerts.utils.produce_alert_internal_event", return_value=None)
+ @patch("posthog.tasks.alerts.utils.list_active_alert_destinations")
+ def test_trigger_hog_functions_returns_empty_on_produce_failure(
+ self, mock_list: MagicMock, _mock_produce: MagicMock
+ ) -> None:
+ mock_list.return_value = [ActiveAlertDestination(id="hf-1", name="#eng-alerts", destination_type="slack")]
+ alert = MagicMock(spec=AlertConfiguration)
+ alert.id = "00000000-0000-0000-0000-000000000001"
+ alert.team_id = 2
+ alert.last_checked_at = None
+ alert.detector_config = None
+
+ assert trigger_alert_hog_functions(alert=alert, properties={}) == []
+
+
+class TestSendNotificationsReceipts(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="test insight")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.insight,
+ name="test alert",
+ condition={"type": "absolute_value"},
+ created_by=self.user,
+ )
+ self.alert.subscribed_users.add(self.user)
+
+ @patch("posthog.tasks.alerts.utils.trigger_alert_hog_functions", return_value=[])
+ @patch("posthog.tasks.alerts.utils.send_alert_email")
+ def test_breach_notifications_return_email_receipts(self, mock_send: MagicMock, _mock_trigger: MagicMock) -> None:
+ receipts = send_notifications_for_breaches(self.alert, ["breach"], idempotency_key="check-1")
+
+ assert [(r.channel, r.target, r.status) for r in receipts] == [("email", self.user.email, "accepted")]
+ mock_send.assert_called_once()
+
+ @patch("posthog.tasks.alerts.utils.trigger_alert_hog_functions", return_value=[])
+ @patch("posthog.tasks.alerts.utils.send_alert_email", side_effect=RuntimeError("smtp down"))
+ def test_breach_notifications_propagate_email_failure(
+ self, _mock_send: MagicMock, _mock_trigger: MagicMock
+ ) -> None:
+ with pytest.raises(RuntimeError):
+ send_notifications_for_breaches(self.alert, ["breach"], idempotency_key="check-1")
+
+ @patch("posthog.tasks.alerts.utils.send_alert_email")
+ def test_error_notifications_return_empty_without_eligible_recipients(self, mock_send: MagicMock) -> None:
+ self.alert.subscribed_users.clear()
+
+ assert send_notifications_for_errors(self.alert, {"message": "boom"}, idempotency_key="check-1") == []
+ mock_send.assert_not_called()
+
+ @patch("posthog.tasks.alerts.utils.send_alert_email")
+ def test_error_notifications_return_email_receipts(self, mock_send: MagicMock) -> None:
+ receipts = send_notifications_for_errors(self.alert, {"message": "boom"}, idempotency_key="check-1")
+
+ assert [(r.channel, r.target, r.status) for r in receipts] == [("email", self.user.email, "accepted")]
+ mock_send.assert_called_once()
+
+
+class TestDisableInvalidAlert(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.insight = Insight.objects.create(team=self.team, name="test insight")
+ self.alert = AlertConfiguration.objects.create(
+ team=self.team,
+ insight=self.insight,
+ name="test alert",
+ condition={"type": "absolute_value"},
+ created_by=self.user,
+ )
+ self.alert.subscribed_users.add(self.user)
+
+ @patch("posthog.tasks.alerts.utils.send_alert_email", side_effect=RuntimeError("smtp down"))
+ def test_disable_invalid_alert_records_nothing_when_send_fails(self, _mock_send: MagicMock) -> None:
+ with pytest.raises(RuntimeError):
+ disable_invalid_alert(self.alert, reason="bad config")
+
+ check = AlertCheck.objects.filter(alert_configuration=self.alert).latest("created_at")
+ assert check.targets_notified == {}
+ assert check.notification_sent_at is None
+
+ @patch("posthog.tasks.alerts.utils.send_alert_email")
+ def test_disable_invalid_alert_records_receipts_after_send(self, mock_send: MagicMock) -> None:
+ check = disable_invalid_alert(self.alert, reason="bad config")
+
+ check.refresh_from_db()
+ assert check.targets_notified == {"users": [self.user.email], "destinations": []}
+ mock_send.assert_called_once()
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.py
index fcbb39bf2ce5..f77663cb6d11 100644
--- a/posthog/tasks/alerts/utils.py
+++ b/posthog/tasks/alerts/utils.py
@@ -11,6 +11,7 @@ import structlog
from posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery
+from posthog.ph_client import ph_background_capture
from posthog.rbac.user_access_control import UserAccessControl
from posthog.slo.context import get_current_slo
from posthog.slo.types import SloOperation
@@ -19,9 +20,12 @@ from posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_sche
from products.alerts.backend.delivery_slo import alert_delivery_slo
from products.alerts.backend.destinations import (
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS,
+ AlertDelivery,
alert_internal_event_delivered,
flush_alert_internal_events,
+ list_active_alert_destinations,
produce_alert_internal_event,
+ serialize_deliveries,
)
from products.alerts.backend.facade.api import send_alert_email
from products.alerts.backend.insight_alert_state_machine import (
@@ -139,8 +143,13 @@ def next_check_at_after_schedule_restriction_change(alert: AlertConfiguration) -
alert.next_check_at = old_next
-def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) -> bool:
- """Trigger all HogFunctions linked to the alert as notification destinations by producing an internal event."""
+def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) -> list[AlertDelivery]:
+ """Trigger all HogFunctions linked to the alert as notification destinations by producing an internal event.
+
+ Returns one receipt per destination that accepted the notification. An empty list also
+ covers an alert with no destinations configured, so callers cannot use it to tell
+ "there was nothing to send" apart from "sending failed".
+ """
logger.info(
"Triggering internal event for alert destinations/hog functions",
@@ -160,17 +169,35 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->
**properties,
}
+ destinations = list_active_alert_destinations(
+ team_id=alert.team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids=(INSIGHT_ALERT_FIRING_EVENT,),
+ )
+ accepted_at = datetime.now(UTC).isoformat()
+ receipts = [
+ AlertDelivery(
+ channel="hog_function",
+ target=destination.name,
+ target_id=destination.id,
+ template=destination.destination_type,
+ at=accepted_at,
+ )
+ for destination in destinations
+ ]
+
produce_result = produce_alert_internal_event(
team_id=alert.team_id,
event_name=INSIGHT_ALERT_FIRING_EVENT,
properties=props,
)
+
slo = get_current_slo()
if slo is None or slo.operation != SloOperation.ALERT_DELIVERY:
- return produce_result is not None
+ return receipts if produce_result is not None else []
if produce_result is None:
slo.fail(failure_phase="destination_enqueue")
- return False
+ return []
flush_alert_internal_events(ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS)
if not alert_internal_event_delivered(
@@ -180,7 +207,8 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->
event_name=INSIGHT_ALERT_FIRING_EVENT,
):
slo.fail(failure_phase="notification_delivery")
- return True
+ return []
+ return receipts
def send_notifications_for_breaches(
@@ -188,13 +216,14 @@ def send_notifications_for_breaches(
breaches: list[str],
idempotency_key: str,
extra_properties: dict[str, str] | None = None,
-) -> list[str]:
+) -> list[AlertDelivery]:
"""A stable idempotency_key (typically alert_check.id) lets MessagingRecord enforce
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).
"""
+ deliveries: list[AlertDelivery] = []
email_targets = alert.get_subscribed_users_emails()
if email_targets:
subject = f"PostHog alert {alert.name} is firing for {alert.team.name}"
@@ -216,15 +245,19 @@ def send_notifications_for_breaches(
"project_name": alert.team.name,
},
)
+ accepted_at = datetime.now(UTC).isoformat()
+ deliveries.extend(AlertDelivery(channel="email", target=target, at=accepted_at) for target in email_targets)
# 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 {})},
+ deliveries.extend(
+ trigger_alert_hog_functions(
+ alert=alert,
+ properties={"breaches": "\n".join(breaches), **(extra_properties or {})},
+ )
)
- return email_targets
+ return deliveries
def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str], idempotency_key: str) -> None:
@@ -246,7 +279,7 @@ def send_test_alert_email(alert: AlertConfiguration, recipients: Collection[str]
)
-def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempotency_key: str) -> list[str]:
+def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempotency_key: str) -> list[AlertDelivery]:
logger.info("Sending alert error notifications", alert_id=alert.id, error=error)
email_targets = [email for _, email in get_alert_error_notification_recipients(alert) if email]
if not email_targets:
@@ -271,7 +304,8 @@ def send_notifications_for_errors(alert: AlertConfiguration, error: dict, idempo
"next_check_at": alert.next_check_at,
},
)
- return email_targets
+ accepted_at = datetime.now(UTC).isoformat()
+ return [AlertDelivery(channel="email", target=target, at=accepted_at) for target in email_targets]
def next_scheduled_check_time(alert: AlertConfiguration) -> str | None:
@@ -298,13 +332,13 @@ def dispatch_alert_notification(
alert_check: AlertCheck,
breaches: list[str] | None,
extra_properties: dict[str, str] | None = None,
-) -> list[str] | None:
+) -> list[AlertDelivery] | None:
"""Route an AlertCheck to the correct notification sender.
- Returns the list of recipients the delivery targeted, or None if nothing was sent
+ Returns the delivery receipts the notification produced, or None if nothing was sent
(NOT_FIRING, or ERRORED with a non-dict error payload). Callers pass the returned
- list to record_alert_delivery so the `targets_notified` sentinel reflects reality
- — never claiming delivery for a state that didn't actually send.
+ receipts to record_alert_delivery so the `targets_notified` sentinel reflects reality,
+ never claiming delivery for a state that didn't actually send.
Raises:
ValueError: state is FIRING but breaches is None/empty.
@@ -359,19 +393,54 @@ def dispatch_alert_notification(
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:
- """Persist the side-effects of a successful notification delivery.
-
- - alert_check.targets_notified: populated set = delivery happened (idempotency sentinel
- for Temporal notify retries).
- - alert.last_notified_at: used by monitoring / throttling.
+def record_alert_delivery(
+ alert: AlertConfiguration,
+ alert_check: AlertCheck,
+ deliveries: list[AlertDelivery] | None,
+ *,
+ stamp_on_empty: bool = False,
+) -> bool:
+ """Persist the side-effects of accepted notification deliveries.
+
+ Returns False without recording anything when nothing was accepted, so a check
+ can never claim delivery that didn't happen. `stamp_on_empty` is for the
+ investigation-gated dispatchers: a zero-accept attempt must still stamp
+ notification_sent_at (their sweep-idempotency marker), or the safety net would
+ re-dispatch an undeliverable check forever.
Caller must wrap in transaction.atomic() if atomic semantics are required.
"""
- alert_check.targets_notified = {"users": targets}
- alert_check.save(update_fields=["targets_notified"])
- alert.last_notified_at = datetime.now(UTC)
+ if not deliveries:
+ logger.warning(
+ "record_alert_delivery.no_transport_accepted",
+ alert_id=str(alert.id),
+ alert_check_id=str(alert_check.id),
+ alert_check_state=alert_check.state,
+ )
+ ph_background_capture()(
+ distinct_id=str(alert.id),
+ event="alert notification not delivered",
+ properties={
+ "team_id": alert.team_id,
+ "alert_id": str(alert.id),
+ "alert_check_id": str(alert_check.id),
+ "alert_state": alert_check.state,
+ },
+ )
+ if stamp_on_empty:
+ alert_check.notification_sent_at = datetime.now(UTC)
+ alert_check.save(update_fields=["notification_sent_at"])
+ return False
+ recorded_at = datetime.now(UTC)
+ alert_check.targets_notified = {
+ "users": [delivery.target for delivery in deliveries if delivery.channel == "email"],
+ "destinations": serialize_deliveries([d for d in deliveries if d.channel != "email"]),
+ }
+ alert_check.notification_sent_at = recorded_at
+ alert_check.save(update_fields=["targets_notified", "notification_sent_at"])
+ alert.last_notified_at = recorded_at
alert.save(update_fields=["last_notified_at"])
+ return True
def add_alert_check(
@@ -440,16 +509,17 @@ def disable_invalid_alert(alert: AlertConfiguration, reason: str) -> AlertCheck:
alert_configuration=alert,
calculated_value=None,
condition=alert.condition,
- targets_notified={"users": targets_to_notify} if targets_to_notify else {},
+ targets_notified={},
state=AlertState.ERRORED,
error={"message": reason},
)
if targets_to_notify:
- send_notifications_for_disabled(alert, reason, targets_to_notify)
+ deliveries = send_notifications_for_disabled(alert, reason, targets_to_notify)
+ record_alert_delivery(alert, alert_check, deliveries)
return alert_check
-def send_notifications_for_disabled(alert: AlertConfiguration, reason: str, targets: list[str]) -> None:
+def send_notifications_for_disabled(alert: AlertConfiguration, reason: str, targets: list[str]) -> list[AlertDelivery]:
logger.info("Sending alert disabled notification", alert_id=alert.id, reason=reason)
subject = f"PostHog alert {alert.name} for {alert.team.name} has been disabled"
@@ -470,3 +540,5 @@ def send_notifications_for_disabled(alert: AlertConfiguration, reason: str, targ
"project_name": alert.team.name,
},
)
+ accepted_at = datetime.now(UTC).isoformat()
+ return [AlertDelivery(channel="email", target=target, at=accepted_at) for target in targets]
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index c471eb1db2c0..ce7793e73c6a 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -15,7 +15,6 @@ from typing import TYPE_CHECKING, Optional
from uuid import UUID
from django.db import transaction
-from django.utils import timezone
import structlog
from asgiref.sync import sync_to_async
@@ -414,9 +413,8 @@ def _dispatch_gated_notification(
else None
)
try:
- targets = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties)
- if targets is not None:
- record_alert_delivery(alert, check, targets)
+ deliveries = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties)
+ record_alert_delivery(alert, check, deliveries, stamp_on_empty=True)
except Exception:
logger.exception(
"anomaly_investigation.gated_notification_failed",
@@ -426,11 +424,6 @@ def _dispatch_gated_notification(
# Don't swallow — let the safety-net task retry on the next tick.
raise
- # Keep notification_sent_at updated in lock-step with the delivery so the
- # safety-net's idempotency check still trips on a successful workflow dispatch.
- check.notification_sent_at = timezone.now()
- check.save(update_fields=["notification_sent_at"])
-
def _build_breach_descriptions(
*,
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index 7c4228ec7aec..a25e9ac3fcb9 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -432,7 +432,9 @@ async def record_failed_evaluation(inputs: RecordFailedEvaluationActivityInputs)
return await _record()
-def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breaches: list[str]) -> None:
+def dispatch_alert_firing_realtime_notification(
+ alert: AlertConfiguration, alert_check: AlertCheck, breaches: list[str]
+) -> None:
"""Fan out one realtime in-app notification per subscribed user when an alert fires.
Exceptions are caught and logged internally so a realtime delivery failure does not
@@ -459,6 +461,9 @@ def dispatch_alert_firing_realtime_notification(alert: AlertConfiguration, breac
source_url=source_url,
source_type=SourceType.INSIGHT,
source_id=str(alert.insight.short_id),
+ # A dispatch that accepted nothing leaves targets_notified empty, so a
+ # retried activity reaches this again; dedupe here rather than on that.
+ idempotency_key=f"alert-firing:{alert_check.id}:{user_id}",
)
)
except Exception:
@@ -538,21 +543,20 @@ async def notify_alert(inputs: NotifyAlertActivityInputs) -> None:
alert = alert_check.alert_configuration
# Raises if FIRING with no breaches; caller (workflow) must pipe breaches from evaluate.
- targets = dispatch_alert_notification(alert, alert_check, inputs.breaches)
- if targets is None:
+ deliveries = dispatch_alert_notification(alert, alert_check, inputs.breaches)
+ if deliveries is None:
return
with transaction.atomic():
- record_alert_delivery(alert, alert_check, targets)
- # Stamp notification_sent_at in lock-step with delivery — the investigation
- # workflow and safety-net both read this column to decide whether they still
+ # Writes the sentinel + notification_sent_at together — the investigation
+ # workflow and safety-net read that column to decide whether they still
# need to dispatch, and the gating path relies on it for idempotency.
- AlertCheck.objects.filter(id=alert_check.id).update(notification_sent_at=datetime.now(UTC))
+ record_alert_delivery(alert, alert_check, deliveries)
- # Realtime in-app dispatch sits AFTER record_alert_delivery so a Temporal retry
- # past this point sees `targets_notified` populated and skips the whole _notify.
+ # Both in-app paths dedupe on their own idempotency key, so neither depends on
+ # record_alert_delivery having written the sentinel.
if alert_check.state == AlertState.FIRING.value and inputs.breaches:
- dispatch_alert_firing_realtime_notification(alert, inputs.breaches)
+ dispatch_alert_firing_realtime_notification(alert, alert_check, inputs.breaches)
elif alert_check.state == AlertState.ERRORED.value:
dispatch_alert_error_in_app_notifications(alert, alert_check)
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 4255b2827481..c7dea0a863dd 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -51,12 +51,17 @@ from posthog.temporal.alerts.types import (
SkipReason,
)
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.validation import THRESHOLD_BOUNDS_REQUIRED_MESSAGE
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
from products.product_analytics.backend.models.insight import Insight
+def _email_delivery(target: str, at: str = "2026-08-11T00:00:00+00:00") -> AlertDelivery:
+ return AlertDelivery(channel="email", target=target, at=at)
+
+
def _valid_trends_query() -> dict:
return TrendsQuery(
series=[EventsNode(event="$pageview")],
@@ -439,7 +444,7 @@ class TestEvaluateAlert:
side_effect=AlertExtractionError("query returns 2 numeric columns — pick one"),
),
patch("posthog.temporal.alerts.activities.capture_exception") as mock_capture,
- patch("posthog.tasks.alerts.utils.send_notifications_for_disabled") as mock_notify,
+ patch("posthog.tasks.alerts.utils.send_notifications_for_disabled", return_value=[]) as mock_notify,
):
env = ActivityEnvironment()
result = await env.run(evaluate_alert, EvaluateAlertActivityInputs(alert_id=str(alert_with_user.id)))
@@ -555,6 +560,32 @@ class TestNotifyAlert:
mock_breaches.assert_not_called()
mock_errors.assert_not_called()
+ async def test_records_nothing_when_no_transport_accepts(self, alert_with_user) -> None:
+ # Zero accepted receipts must leave the check unstamped: stamping here would
+ # recreate the false "targets notified" rows the repair command exists to clear.
+ check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
+
+ with (
+ patch("posthog.slo.events.posthoganalytics"),
+ patch("products.alerts.backend.delivery_slo.get_instance_region", return_value="US"),
+ patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[]),
+ patch("posthog.tasks.alerts.utils.send_notifications_for_errors") as mock_errors,
+ ):
+ env = ActivityEnvironment()
+ await env.run(
+ notify_alert,
+ NotifyAlertActivityInputs(
+ alert_id=str(alert_with_user.id),
+ alert_check_id=str(check.id),
+ breaches=["value above threshold"],
+ ),
+ )
+
+ mock_errors.assert_not_called()
+ refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
+ assert refreshed.targets_notified == {}
+ assert refreshed.notification_sent_at is None
+
async def test_sends_breach_notifications_when_firing(self, alert_with_user) -> None:
check = await _create_alert_check(alert_with_user, state=AlertState.FIRING)
@@ -563,7 +594,7 @@ class TestNotifyAlert:
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]"],
+ return_value=[_email_delivery("[email protected]")],
) as mock_breaches,
patch("posthog.tasks.alerts.utils.send_notifications_for_errors") as mock_errors,
):
@@ -581,7 +612,8 @@ class TestNotifyAlert:
mock_errors.assert_not_called()
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
- assert refreshed.targets_notified == {"users": ["[email protected]"]}
+ assert refreshed.targets_notified == {"users": ["[email protected]"], "destinations": []}
+ assert refreshed.notification_sent_at is not None
refreshed_alert = await sync_to_async(AlertConfiguration.objects.get)(pk=alert_with_user.pk)
assert refreshed_alert.last_notified_at is not None
@@ -605,7 +637,7 @@ class TestNotifyAlert:
with patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
) as mock_breaches:
env = ActivityEnvironment()
await env.run(
@@ -637,7 +669,7 @@ class TestNotifyAlert:
patch("posthog.tasks.alerts.utils.send_notifications_for_breaches") as mock_breaches,
patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
) as mock_errors,
patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
):
@@ -670,7 +702,7 @@ class TestNotifyAlert:
assert "contact support" in notification.body
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
- assert refreshed.targets_notified == {"users": ["[email protected]"]}
+ assert refreshed.targets_notified == {"users": ["[email protected]"], "destinations": []}
@pytest.mark.parametrize("message", [None, "", " "])
async def test_error_notification_uses_fallback_for_missing_reason(self, alert_with_user, message) -> None:
@@ -679,7 +711,7 @@ class TestNotifyAlert:
with (
patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
),
patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
):
@@ -701,12 +733,12 @@ class TestNotifyAlert:
alert_with_user.next_check_at = next_check_at
with patch("posthog.tasks.alerts.utils.send_alert_email") as mock_send_alert_email:
- recipients = await sync_to_async(send_notifications_for_errors)(
+ deliveries = await sync_to_async(send_notifications_for_errors)(
alert_with_user, {"message": "boom"}, "notification-key"
)
subscriber_email = await sync_to_async(lambda: alert_with_user.subscribed_users.get().email)()
- assert recipients == [subscriber_email]
+ assert [(delivery.channel, delivery.target) for delivery in deliveries] == [("email", subscriber_email)]
assert mock_send_alert_email.call_args.kwargs["template_context"]["next_check_at"] == next_check_at
async def test_error_notification_does_not_include_an_unsubscribed_creator(self, alert, auser) -> None:
@@ -730,7 +762,7 @@ class TestNotifyAlert:
with (
patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
),
patch("posthog.temporal.alerts.activities.create_notification", side_effect=RuntimeError("kafka down")),
):
@@ -741,7 +773,7 @@ class TestNotifyAlert:
)
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
- assert refreshed.targets_notified == {"users": ["[email protected]"]}
+ assert refreshed.targets_notified == {"users": ["[email protected]"], "destinations": []}
async def test_idempotent_when_already_notified(self, alert_with_user) -> None:
# Simulate a previous successful notification by setting targets_notified.
@@ -825,7 +857,7 @@ class TestNotifyAlert:
with (
patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
),
patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
):
@@ -856,7 +888,7 @@ class TestNotifyAlert:
with (
patch(
"posthog.tasks.alerts.utils.send_notifications_for_breaches",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
) as mock_breaches,
patch(
"posthog.temporal.alerts.activities.create_notification",
@@ -876,7 +908,7 @@ class TestNotifyAlert:
mock_breaches.assert_called_once()
refreshed = await sync_to_async(AlertCheck.objects.get)(pk=check.id)
- assert refreshed.targets_notified == {"users": ["[email protected]"]}
+ assert refreshed.targets_notified == {"users": ["[email protected]"], "destinations": []}
@pytest.mark.parametrize("calculation_interval", [None, AlertCalculationInterval.REAL_TIME])
diff --git a/posthog/temporal/tests/test_alerts_workflows.py b/posthog/temporal/tests/test_alerts_workflows.py
index 9b1dd832eac4..a81e8d519964 100644
--- a/posthog/temporal/tests/test_alerts_workflows.py
+++ b/posthog/temporal/tests/test_alerts_workflows.py
@@ -35,6 +35,7 @@ from posthog.temporal.alerts.schedule import create_schedule_due_alert_checks_sc
from posthog.temporal.alerts.types import AlertInfo, CheckAlertWorkflowInputs, SkipReason
from posthog.temporal.alerts.workflows import CheckAlertWorkflow, ScheduleDueAlertChecksWorkflow
from posthog.temporal.common.slo_interceptor import SloInterceptor
+from posthog.temporal.tests.test_alerts_activities import _email_delivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
from products.product_analytics.backend.models.insight import Insight
@@ -221,7 +222,8 @@ async def test_check_alert_workflow_firing_drives_full_chain_with_slo(
with (
patch("posthog.temporal.alerts.activities.check_alert_for_insight", return_value=evaluation_result),
patch(
- "posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=recipients
+ "posthog.tasks.alerts.utils.send_notifications_for_breaches",
+ return_value=[_email_delivery(recipients[0])],
) as mock_send_breaches,
):
await _run_check_alert_workflow(
@@ -235,7 +237,7 @@ async def test_check_alert_workflow_firing_drives_full_chain_with_slo(
assert len(checks) == 1
check = checks[0]
assert check.state == AlertState.FIRING
- assert check.targets_notified == {"users": recipients}
+ assert check.targets_notified == {"users": recipients, "destinations": []}
mock_send_breaches.assert_called_once()
call = mock_send_breaches.call_args
@@ -347,7 +349,7 @@ async def test_check_alert_workflow_records_errored_check_when_evaluation_keeps_
) as mock_ch_query,
patch(
"posthog.tasks.alerts.utils.send_notifications_for_errors",
- return_value=["[email protected]"],
+ return_value=[_email_delivery("[email protected]")],
) as mock_send_errors,
failure_ctx,
):
diff --git a/products/alerts/backend/api/alert.py b/products/alerts/backend/api/alert.py
index 45939247e0d4..60e598689ad5 100644
--- a/products/alerts/backend/api/alert.py
+++ b/products/alerts/backend/api/alert.py
@@ -58,6 +58,7 @@ from posthog.tasks.alerts.utils import (
from posthog.utils import relative_date_parse
from products.alerts.backend.api.alert_schedule_restriction import AlertScheduleRestriction
+from products.alerts.backend.destination_configs import DestinationType
from products.alerts.backend.destinations import count_active_alert_destinations
from products.alerts.backend.evaluation.contract import AlertExtractionError
from products.alerts.backend.evaluation.detector import simulate_detector_on_insight
@@ -217,11 +218,48 @@ class ThresholdSerializer(serializers.ModelSerializer):
return data
+def _destination_deliveries(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ # Only Slack names its own channel; the rest repeat a bare type name, so carry the hog
+ # function id to tell two apart — never the webhook URL, which is the credential.
+ labelled = []
+ for row in rows:
+ label = row.get("target") or "Destination"
+ target_id = row.get("target_id")
+ if target_id and row.get("template") != DestinationType.SLACK.value:
+ label = f"{label} · {target_id[-4:]}"
+ labelled.append({**row, "display_label": label})
+ return labelled
+
+
+class AlertDeliverySerializer(serializers.Serializer):
+ channel = serializers.CharField(help_text="Delivery channel: 'email' or 'hog_function' (destinations).")
+ target = serializers.CharField(help_text="Email address, or destination name, that received the notification.")
+ target_id = serializers.CharField(
+ required=False, allow_null=True, help_text="Hog function ID, for destination deliveries. Null for email."
+ )
+ template = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Destination template: 'slack', 'discord', 'webhook', or 'teams'. Null for email.",
+ )
+ status = serializers.CharField(help_text="Delivery status. Always 'accepted', for a confirmed send.")
+ at = serializers.DateTimeField(allow_null=True, help_text="When the delivery was recorded.")
+ display_label = serializers.CharField(
+ help_text="Ready-to-display description of the delivery, e.g. 'Email: [email protected]' or 'Slack #eng-alerts'."
+ )
+
+
class AlertCheckSerializer(serializers.ModelSerializer):
targets_notified = serializers.SerializerMethodField()
investigation_notebook_short_id = serializers.SerializerMethodField(
help_text="Short ID of the Notebook produced by the investigation agent, when the agent ran for this check."
)
+ deliveries = serializers.SerializerMethodField(
+ allow_null=True,
+ help_text="Destinations that accepted this check's notification, one record per destination "
+ "(channel, target, status, at). Null when no delivery receipt was recorded, which covers "
+ "checks that notified nobody and checks predating delivery receipts.",
+ )
class Meta:
model = AlertCheck
@@ -242,6 +280,7 @@ class AlertCheckSerializer(serializers.ModelSerializer):
"investigation_notebook_short_id",
"notification_sent_at",
"notification_suppressed_by_agent",
+ "deliveries",
]
read_only_fields = fields
@@ -252,6 +291,24 @@ class AlertCheckSerializer(serializers.ModelSerializer):
notebook = instance.investigation_notebook
return notebook.short_id if notebook is not None else None
+ @extend_schema_field(AlertDeliverySerializer(many=True))
+ def get_deliveries(self, instance: AlertCheck) -> list[dict[str, Any]] | None:
+ if not instance.has_delivery_receipts:
+ return None
+ notified = instance.targets_notified or {}
+ accepted_at = instance.notification_sent_at.isoformat() if instance.notification_sent_at else None
+ emails = [
+ {
+ "channel": "email",
+ "target": email,
+ "status": "accepted",
+ "at": accepted_at,
+ "display_label": f"Email: {email}",
+ }
+ for email in notified.get("users") or []
+ ]
+ return emails + _destination_deliveries(notified.get("destinations") or [])
+
class AlertSubscriptionSerializer(serializers.ModelSerializer):
# nosemgrep: unscoped-primary-key-related-field — User model is not team-scoped; validate() checks team membership
diff --git a/products/alerts/backend/api/test/test_alert.py b/products/alerts/backend/api/test/test_alert.py
index a6d574338699..b2d9fea77c13 100644
--- a/products/alerts/backend/api/test/test_alert.py
+++ b/products/alerts/backend/api/test/test_alert.py
@@ -20,10 +20,15 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from products.alerts.backend.destinations import AlertDelivery
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.product_analytics.backend.models.insight import Insight
+TEST_DESTINATION_DELIVERY = AlertDelivery(
+ channel="hog_function", target="Eng alerts", template="slack", at="2026-08-11T00:00:00+00:00"
+)
+
class TestAlert(APIBaseTest, QueryMatchingTest):
def setUp(self):
@@ -498,6 +503,189 @@ class TestAlert(APIBaseTest, QueryMatchingTest):
values = [c["calculated_value"] for c in checks]
assert 4.0 not in values
+ @parameterized.expand(
+ [
+ (
+ "recorded_email_composed_as_accepted",
+ {"users": ["[email protected]"], "destinations": []},
+ [
+ {
+ "channel": "email",
+ "target": "[email protected]",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Email: [email protected]",
+ }
+ ],
+ True,
+ ),
+ (
+ "row_predating_receipts_is_null_but_still_notified",
+ {"users": ["[email protected]"]},
+ None,
+ True,
+ ),
+ (
+ "hog_function_only_delivery_keeps_truthful_yes",
+ {
+ "users": [],
+ "destinations": [
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-1",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ }
+ ],
+ },
+ [
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-1",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Slack #eng-alerts",
+ }
+ ],
+ True,
+ ),
+ (
+ "combined_email_and_destination_row",
+ {
+ "users": ["[email protected]"],
+ "destinations": [
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-1",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ }
+ ],
+ },
+ [
+ {
+ "channel": "email",
+ "target": "[email protected]",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Email: [email protected]",
+ },
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-1",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Slack #eng-alerts",
+ },
+ ],
+ True,
+ ),
+ (
+ "non_slack_destinations_carry_an_id_suffix",
+ {
+ "users": [],
+ "destinations": [
+ {
+ "channel": "hog_function",
+ "target": "Discord",
+ "target_id": "hf-aaaa4f2a",
+ "template": "discord",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ },
+ {
+ "channel": "hog_function",
+ "target": "Webhook example.com",
+ "target_id": "hf-bbbb9b17",
+ "template": "webhook",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ },
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-cccc0000",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ },
+ ],
+ },
+ [
+ {
+ "channel": "hog_function",
+ "target": "Discord",
+ "target_id": "hf-aaaa4f2a",
+ "template": "discord",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Discord · 4f2a",
+ },
+ {
+ "channel": "hog_function",
+ "target": "Webhook example.com",
+ "target_id": "hf-bbbb9b17",
+ "template": "webhook",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Webhook example.com · 9b17",
+ },
+ {
+ "channel": "hog_function",
+ "target": "Slack #eng-alerts",
+ "target_id": "hf-cccc0000",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ "display_label": "Slack #eng-alerts",
+ },
+ ],
+ True,
+ ),
+ (
+ "nothing_recorded_is_null",
+ {},
+ None,
+ False,
+ ),
+ ]
+ )
+ def test_alert_check_deliveries_field(
+ self,
+ _name: str,
+ targets_notified: dict,
+ expected_deliveries: list[dict] | None,
+ expected_targets_notified: bool,
+ ) -> None:
+ creation_request = {
+ "insight": self.insight["id"],
+ "subscribed_users": [self.user.id],
+ "condition": {"type": AlertConditionType.ABSOLUTE_VALUE},
+ "config": {"type": "TrendsAlertConfig", "series_index": 0},
+ "threshold": {"configuration": {"type": InsightThresholdType.ABSOLUTE, "bounds": {"upper": 100}}},
+ "name": "deliveries field test",
+ }
+ alert = self.client.post(f"/api/projects/{self.team.id}/alerts", creation_request).json()
+ check = AlertCheck.objects.create(
+ alert_configuration_id=alert["id"],
+ targets_notified=targets_notified,
+ notification_sent_at=datetime(2026, 8, 11, 0, 0, tzinfo=UTC) if targets_notified else None,
+ state=AlertState.FIRING,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/alerts/{alert['id']}")
+ serialized = next(c for c in response.json()["checks"] if c["id"] == str(check.id))
+ assert serialized["deliveries"] == expected_deliveries
+ assert serialized["targets_notified"] is expected_targets_notified
+
def test_alert_limit(self) -> None:
with mock.patch(
"products.alerts.backend.api.alert.AlertConfiguration.ALERTS_ALLOWED_ON_FREE_TIER"
@@ -1501,7 +1689,7 @@ class TestAlertTestDelivery(APIBaseTest):
@mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions")
def test_queues_test_delivery_for_active_destinations_without_changing_alert(self, mock_trigger) -> None:
- mock_trigger.return_value = True
+ mock_trigger.return_value = [TEST_DESTINATION_DELIVERY]
self._create_destination()
self._create_destination()
self._create_destination(enabled=False)
@@ -1552,7 +1740,9 @@ class TestAlertTestDelivery(APIBaseTest):
mock_trigger.assert_not_called()
@mock.patch("products.alerts.backend.api.alert.send_test_alert_email", side_effect=RuntimeError("email failed"))
- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=True)
+ @mock.patch(
+ "products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=[TEST_DESTINATION_DELIVERY]
+ )
def test_destination_still_queues_when_email_fails(self, mock_trigger, _mock_email) -> None:
alert = AlertConfiguration.objects.get(id=self.alert["id"])
AlertSubscription.objects.create(alert_configuration=alert, user=self.user)
@@ -1568,7 +1758,7 @@ class TestAlertTestDelivery(APIBaseTest):
}
mock_trigger.assert_called_once()
- @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=False)
+ @mock.patch("products.alerts.backend.api.alert.trigger_alert_hog_functions", return_value=[])
def test_returns_service_unavailable_when_destination_fails_to_queue(self, mock_trigger) -> None:
self._create_destination()
diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.py
index 449a52181205..e30f663d5d84 100644
--- a/products/alerts/backend/destinations.py
+++ b/products/alerts/backend/destinations.py
@@ -2,13 +2,16 @@
from __future__ import annotations
-from collections.abc import Collection
+import re
+from collections.abc import Collection, Sequence
+from dataclasses import asdict, dataclass
from datetime import datetime
from typing import Any
+from urllib.parse import urlsplit
from uuid import UUID
from django.db import transaction
-from django.db.models import Q
+from django.db.models import Q, QuerySet
import structlog
from prometheus_client import Counter
@@ -34,6 +37,48 @@ ALERT_INTERNAL_EVENT_DELIVERY_FAILURES = Counter(
)
+@dataclass(frozen=True, kw_only=True)
+class AlertDelivery:
+ """Receipt for one destination that accepted a send. `status` is an open set, so a
+ future transport can report an outcome other than "accepted"."""
+
+ channel: str # "email" | "hog_function"
+ target: str # email address or destination name
+ target_id: str | None = None # hog function id
+ template: str | None = None # "slack" | "discord" | "webhook" | "teams"
+ status: str = "accepted"
+ at: str # ISO-8601 timestamp
+
+
+def serialize_deliveries(deliveries: Sequence[AlertDelivery]) -> list[dict[str, Any]]:
+ return [asdict(delivery) for delivery in deliveries]
+
+
+@dataclass(frozen=True, kw_only=True)
+class ActiveAlertDestination:
+ id: str
+ name: str
+ destination_type: str | None
+
+
+_TEMPLATE_ID_TO_DESTINATION_TYPE = {
+ template_id: destination_type.value for destination_type, template_id in DESTINATION_TEMPLATE_IDS.items()
+}
+
+
+def _active_alert_destinations_qs(
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> QuerySet[HogFunction]:
+ return HogFunction.objects.filter(
+ _allowed_event_filter(allowed_event_ids),
+ team_id=team_id,
+ deleted=False,
+ enabled=True,
+ template_id__in=DESTINATION_TEMPLATE_IDS.values(),
+ filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
+ )
+
+
def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig], *, request: Any) -> list[HogFunction]:
created: list[HogFunction] = []
hog_function_ids_by_team: dict[int, list[UUID]] = {}
@@ -109,16 +154,57 @@ def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_e
def count_active_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:
- return HogFunction.objects.filter(
- _allowed_event_filter(allowed_event_ids),
- team_id=team_id,
- deleted=False,
- enabled=True,
- template_id__in=DESTINATION_TEMPLATE_IDS.values(),
- filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
+ return _active_alert_destinations_qs(
+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
).count()
+# Webhook-style destination names embed the full webhook URL, whose path is a channel
+# credential (Slack/Discord/Teams webhook secret). Receipts flow into the API and the
+# History tooltip, so keep only the host.
+_URL_IN_NAME_RE = re.compile(r"\b[a-z][a-z0-9+.-]*://\S+", re.IGNORECASE)
+
+_DESTINATION_NAME_SEPARATOR = " → "
+
+
+def _url_host(match: re.Match[str]) -> str:
+ # hostname, not the raw authority: it drops any user:password@ prefix.
+ try:
+ return urlsplit(match.group(0)).hostname or "destination"
+ except ValueError:
+ return "destination"
+
+
+def _receipt_safe_name(name: str) -> str:
+ return _URL_IN_NAME_RE.sub(_url_host, name)
+
+
+def _destination_display_name(name: str) -> str:
+ # Names read "<product> — <alert> (<kind>) → <destination>"; keep the trailing
+ # segment. rpartition, since an alert name may contain the separator too.
+ _, _, destination = name.rpartition(_DESTINATION_NAME_SEPARATOR)
+ return _receipt_safe_name(destination or name)
+
+
+def list_active_alert_destinations(
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> list[ActiveAlertDestination]:
+ rows = _active_alert_destinations_qs(
+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
+ ).values_list("id", "name", "template_id")
+ destinations = []
+ for hog_function_id, name, template_id in rows:
+ destination_type = _TEMPLATE_ID_TO_DESTINATION_TYPE.get(template_id) if template_id else None
+ destinations.append(
+ ActiveAlertDestination(
+ id=str(hog_function_id),
+ name=_destination_display_name(name) if name else "Destination",
+ destination_type=destination_type,
+ )
+ )
+ return destinations
+
+
def _allowed_event_filter(allowed_event_ids: Collection[str]) -> Q:
if not allowed_event_ids:
raise ValueError("allowed_event_ids must not be empty")
diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.py
index 7fc7797b9710..dede84fc73dc 100644
--- a/products/alerts/backend/models/alert.py
+++ b/products/alerts/backend/models/alert.py
@@ -433,6 +433,8 @@ class AlertCheck(UUIDTModel):
created_at = models.DateTimeField(auto_now_add=True)
calculated_value = models.FloatField(null=True, blank=True)
condition = models.JSONField(default=dict) # Snapshot of the condition at the time of the check
+ # {} = no delivery. For legacy reasons "users" holds email addresses only;
+ # "destinations" holds the other channels' receipts (see AlertDelivery).
targets_notified = models.JSONField(default=dict)
error = models.JSONField(null=True, blank=True)
@@ -479,6 +481,12 @@ class AlertCheck(UUIDTModel):
def __str__(self) -> str:
return f"AlertCheck for {self.alert_configuration.name} at {self.created_at}"
+ @property
+ def has_delivery_receipts(self) -> bool:
+ """True when this row was written by record_alert_delivery (which always sets
+ the "destinations" key); legacy rows only carry configured recipients."""
+ return "destinations" in (self.targets_notified or {})
+
@classmethod
def clean_up_old_checks(cls) -> int:
retention_days = 14
diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.py
index 1ae71c564ac1..3fee20d31c02 100644
--- a/products/alerts/backend/test/test_destinations.py
+++ b/products/alerts/backend/test/test_destinations.py
@@ -1,10 +1,14 @@
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from products.alerts.backend.destinations import (
+ AlertDelivery,
alert_internal_event_delivered,
+ list_active_alert_destinations,
+ serialize_deliveries,
soft_delete_alert_destinations,
soft_delete_all_alert_destinations,
)
@@ -157,3 +161,139 @@ class TestAlertInternalEventDelivery(APIBaseTest):
capture_exception.assert_not_called()
delivery_failures.labels.assert_called_once_with(event_name="$logs_alert_firing")
delivery_failures.labels.return_value.inc.assert_called_once_with()
+
+
+class TestListActiveAlertDestinations(APIBaseTest):
+ def _make_hog_function(
+ self, *, template_id: str, alert_id: str, event_id: str = "$logs_alert_firing", name: str = "Test destination"
+ ) -> HogFunction:
+ return HogFunction.objects.create(
+ team=self.team,
+ name=name,
+ type="destination",
+ template_id=template_id,
+ enabled=True,
+ inputs_schema=[],
+ inputs={},
+ hog="return event",
+ filters={
+ "events": [{"id": event_id, "type": "events"}],
+ "properties": [{"key": "alert_id", "value": alert_id}],
+ },
+ )
+
+ def test_list_active_alert_destinations_returns_name_and_type(self) -> None:
+ self._make_hog_function(
+ template_id="template-slack", alert_id="alert-1", name="Alerts — Signups (firing) → Slack #eng-alerts"
+ )
+ self._make_hog_function(
+ template_id="template-slack", alert_id="alert-1", name="Alerts — Signups (firing) → Slack #alerts"
+ )
+ self._make_hog_function(template_id="template-webhook", alert_id="alert-2")
+ disabled = self._make_hog_function(template_id="template-slack", alert_id="alert-1", name="Disabled")
+ disabled.enabled = False
+ disabled.save()
+ deleted = self._make_hog_function(template_id="template-slack", alert_id="alert-1", name="Deleted")
+ deleted.deleted = True
+ deleted.save()
+
+ destinations = list_active_alert_destinations(
+ team_id=self.team.id, alert_id="alert-1", allowed_event_ids=("$logs_alert_firing",)
+ )
+ names_and_types = [(d.name, d.destination_type) for d in destinations]
+
+ assert ("Slack #eng-alerts", "slack") in names_and_types
+ assert ("Slack #alerts", "slack") in names_and_types
+ assert all(isinstance(d.id, str) for d in destinations)
+ assert len(destinations) == 2
+
+ @parameterized.expand(
+ [
+ ("alert_name_contains_separator", "Alerts — A → B (firing) → Slack #eng-alerts", "Slack #eng-alerts"),
+ ("renamed_destination_has_no_separator", "My renamed destination", "My renamed destination"),
+ ("name_clipped_before_separator", "Alerts — a very long alert name…", "Alerts — a very long alert name…"),
+ ]
+ )
+ def test_destination_name_reduces_to_its_trailing_segment(
+ self, _name: str, hog_function_name: str, expected: str
+ ) -> None:
+ self._make_hog_function(template_id="template-slack", alert_id="alert-1", name=hog_function_name)
+
+ destinations = list_active_alert_destinations(
+ team_id=self.team.id, alert_id="alert-1", allowed_event_ids=("$logs_alert_firing",)
+ )
+
+ assert [d.name for d in destinations] == [expected]
+
+ @parameterized.expand(
+ [
+ ("userinfo_credentials_are_dropped", "https://user:[email protected]/hook", "hooks.example.com"),
+ ("uppercase_scheme_is_matched", "HTTPS://hooks.example.com/services/secret", "hooks.example.com"),
+ ("non_http_scheme_is_matched", "ftp://hooks.example.com/secret", "hooks.example.com"),
+ ("port_is_dropped", "https://hooks.example.com:8443/secret", "hooks.example.com"),
+ ]
+ )
+ def test_receipt_names_keep_only_the_url_host(self, _name: str, url: str, expected_host: str) -> None:
+ self._make_hog_function(
+ template_id="template-webhook", alert_id="alert-1", name=f"Alerts — X (firing) → Webhook {url}"
+ )
+
+ destinations = list_active_alert_destinations(
+ team_id=self.team.id, alert_id="alert-1", allowed_event_ids=("$logs_alert_firing",)
+ )
+
+ assert [d.name for d in destinations] == [f"Webhook {expected_host}"]
+
+ def test_list_active_alert_destinations_strips_webhook_urls_to_host(self) -> None:
+ # Webhook names embed the full URL, whose path is the channel credential —
+ # receipts surface in the API and tooltip, so only the host may survive.
+ self._make_hog_function(
+ template_id="template-webhook",
+ alert_id="alert-1",
+ name="Alerts — Signups (firing) → Webhook https://discord.com/api/webhooks/123/secret-token",
+ )
+
+ destinations = list_active_alert_destinations(
+ team_id=self.team.id, alert_id="alert-1", allowed_event_ids=("$logs_alert_firing",)
+ )
+
+ assert [d.name for d in destinations] == ["Webhook discord.com"]
+
+
+class TestSerializeDeliveries(APIBaseTest):
+ def test_serialize_deliveries_roundtrips_dataclass_fields(self) -> None:
+ delivery = AlertDelivery(channel="email", target="[email protected]", at="2026-08-11T00:00:00+00:00")
+ result = serialize_deliveries([delivery])
+
+ assert result == [
+ {
+ "channel": "email",
+ "target": "[email protected]",
+ "target_id": None,
+ "template": None,
+ "status": "accepted",
+ "at": "2026-08-11T00:00:00+00:00",
+ }
+ ]
+
+ def test_serialize_deliveries_with_all_fields(self) -> None:
+ delivery = AlertDelivery(
+ channel="hog_function",
+ target="Slack #general",
+ target_id="hf-123",
+ template="slack",
+ status="accepted",
+ at="2026-08-11T01:00:00+00:00",
+ )
+ result = serialize_deliveries([delivery])
+
+ assert result == [
+ {
+ "channel": "hog_function",
+ "target": "Slack #general",
+ "target_id": "hf-123",
+ "template": "slack",
+ "status": "accepted",
+ "at": "2026-08-11T01:00:00+00:00",
+ }
+ ]
diff --git a/products/alerts/frontend/generated/api.schemas.ts b/products/alerts/frontend/generated/api.schemas.ts
index 1f118251f851..0ab5a018b34f 100644
--- a/products/alerts/frontend/generated/api.schemas.ts
+++ b/products/alerts/frontend/generated/api.schemas.ts
@@ -153,6 +153,32 @@ export const InvestigationVerdictEnumApi = {
Inconclusive: 'inconclusive',
} as const
+export interface AlertDeliveryApi {
+ /** Delivery channel: 'email' or 'hog_function' (destinations). */
+ channel: string
+ /** Email address, or destination name, that received the notification. */
+ target: string
+ /**
+ * Hog function ID, for destination deliveries. Null for email.
+ * @nullable
+ */
+ target_id?: string | null
+ /**
+ * Destination template: 'slack', 'discord', 'webhook', or 'teams'. Null for email.
+ * @nullable
+ */
+ template?: string | null
+ /** Delivery status. Always 'accepted', for a confirmed send. */
+ status: string
+ /**
+ * When the delivery was recorded.
+ * @nullable
+ */
+ at: string | null
+ /** Ready-to-display description of the delivery, e.g. 'Email: [email protected]' or 'Slack #eng-alerts'. */
+ display_label: string
+}
+
export interface AlertCheckApi {
readonly id: string
readonly created_at: string
@@ -178,6 +204,11 @@ export interface AlertCheckApi {
/** @nullable */
readonly notification_sent_at: string | null
readonly notification_suppressed_by_agent: boolean
+ /**
+ * Destinations that accepted this check's notification, one record per destination (channel, target, status, at). Null when no delivery receipt was recorded, which covers checks that notified nobody and checks predating delivery receipts.
+ * @nullable
+ */
+ readonly deliveries: readonly AlertDeliveryApi[] | null
}
export type TrendsAlertConfigApiType = (typeof TrendsAlertConfigApiType)[keyof typeof TrendsAlertConfigApiType]
diff --git a/products/alerts/frontend/types.ts b/products/alerts/frontend/types.ts
index d6fb1b130404..6241f92f7cad 100644
--- a/products/alerts/frontend/types.ts
+++ b/products/alerts/frontend/types.ts
@@ -14,6 +14,10 @@ import {
} from '~/queries/schema/schema-general'
import { QueryBasedInsightModel, UserBasicType } from '~/types'
+import type { AlertDeliveryApi } from './generated/api.schemas'
+
+export type AlertCheckDelivery = AlertDeliveryApi
+
export type AlertConfig = TrendsAlertConfig | HogQLAlertConfig | FunnelsAlertConfig | MetricsAlertConfig
export const isTrendsAlertConfig = (config: AlertConfig | null | undefined): config is TrendsAlertConfig =>
@@ -146,6 +150,7 @@ export interface AlertCheck {
investigation_notebook_short_id?: string | null
notification_sent_at?: string | null
notification_suppressed_by_agent?: boolean
+ deliveries: AlertCheckDelivery[] | null
}
export interface AlertType extends AlertTypeBase {
diff --git a/products/alerts/frontend/utils.test.ts b/products/alerts/frontend/utils.test.ts
index 081697bff50d..9cb6b8531355 100644
--- a/products/alerts/frontend/utils.test.ts
+++ b/products/alerts/frontend/utils.test.ts
@@ -1,40 +1,107 @@
-import { AlertsTab, getActiveAlertsTab } from './utils'
+import { AlertState } from '~/queries/schema/schema-general'
-describe('getActiveAlertsTab', () => {
- it.each([
- {
- name: 'defaults to log alerts for a logs-only user',
- alertId: null,
- requestedTab: undefined,
- canViewInsightAlerts: false,
- canViewLogAlerts: true,
- expected: AlertsTab.LOGS,
- },
- {
- name: 'denies access when neither alert type is available',
- alertId: null,
- requestedTab: undefined,
- canViewInsightAlerts: false,
- canViewLogAlerts: false,
- expected: null,
- },
- {
- name: 'denies an insight alert deep link for a logs-only user',
- alertId: 'alert-id',
- requestedTab: undefined,
- canViewInsightAlerts: false,
- canViewLogAlerts: true,
- expected: null,
- },
- {
- name: 'falls back to insight alerts when log alerts are unavailable',
- alertId: null,
- requestedTab: AlertsTab.LOGS,
- canViewInsightAlerts: true,
- canViewLogAlerts: false,
- expected: AlertsTab.INSIGHTS,
- },
- ])('$name', ({ name: _, expected, ...state }) => {
- expect(getActiveAlertsTab(state)).toBe(expected)
+import type { AlertCheck, AlertCheckDelivery } from './types'
+import { AlertsTab, getActiveAlertsTab, isFailedDelivery, summarizeDeliveries } from './utils'
+
+describe('alerts utils', () => {
+ describe('getActiveAlertsTab', () => {
+ it.each([
+ {
+ name: 'defaults to log alerts for a logs-only user',
+ alertId: null,
+ requestedTab: undefined,
+ canViewInsightAlerts: false,
+ canViewLogAlerts: true,
+ expected: AlertsTab.LOGS,
+ },
+ {
+ name: 'denies access when neither alert type is available',
+ alertId: null,
+ requestedTab: undefined,
+ canViewInsightAlerts: false,
+ canViewLogAlerts: false,
+ expected: null,
+ },
+ {
+ name: 'denies an insight alert deep link for a logs-only user',
+ alertId: 'alert-id',
+ requestedTab: undefined,
+ canViewInsightAlerts: false,
+ canViewLogAlerts: true,
+ expected: null,
+ },
+ {
+ name: 'falls back to insight alerts when log alerts are unavailable',
+ alertId: null,
+ requestedTab: AlertsTab.LOGS,
+ canViewInsightAlerts: true,
+ canViewLogAlerts: false,
+ expected: AlertsTab.INSIGHTS,
+ },
+ ])('$name', ({ name: _, expected, ...state }) => {
+ expect(getActiveAlertsTab(state)).toBe(expected)
+ })
+ })
+
+ describe('summarizeDeliveries', () => {
+ const accepted: AlertCheckDelivery[] = [
+ {
+ channel: 'email',
+ target: '[email protected]',
+ status: 'accepted',
+ at: '2026-08-11T00:00:00Z',
+ display_label: 'Email: [email protected]',
+ },
+ {
+ channel: 'hog_function',
+ target: '#eng-alerts',
+ template: 'slack',
+ status: 'accepted',
+ at: '2026-08-11T00:00:00Z',
+ display_label: 'Slack #eng-alerts',
+ },
+ ]
+ it('labels accepted receipts with their count and lines', () => {
+ expect(summarizeDeliveries(accepted, true)).toEqual({
+ kind: 'delivered',
+ label: 'Yes · 2',
+ lines: ['Email: [email protected]', 'Slack #eng-alerts'],
+ })
+ })
+
+ it('still reports a check without receipts as notified', () => {
+ expect(summarizeDeliveries(null, true)).toEqual({ kind: 'notified' })
+ })
+
+ it('returns none when nothing was recorded', () => {
+ expect(summarizeDeliveries(null, false)).toEqual({ kind: 'none' })
+ expect(summarizeDeliveries([], false)).toEqual({ kind: 'none' })
+ })
+ })
+
+ describe('isFailedDelivery', () => {
+ const check = (overrides: Partial<AlertCheck>): AlertCheck =>
+ ({ state: AlertState.FIRING, ...overrides }) as AlertCheck
+
+ it.each([
+ { name: 'blames delivery for a plain firing check', overrides: {}, expected: true },
+ {
+ name: 'stays silent when the agent suppressed the notification',
+ overrides: { notification_suppressed_by_agent: true },
+ expected: false,
+ },
+ {
+ name: 'stays silent while an investigation still gates the dispatch',
+ overrides: { investigation_status: 'running' as const },
+ expected: false,
+ },
+ {
+ name: 'stays silent for a non-firing check',
+ overrides: { state: AlertState.NOT_FIRING },
+ expected: false,
+ },
+ ])('$name', ({ overrides, expected }) => {
+ expect(isFailedDelivery(check(overrides))).toBe(expected)
+ })
})
})
diff --git a/products/alerts/frontend/utils.ts b/products/alerts/frontend/utils.ts
index 6639bf04220a..76e841d5baef 100644
--- a/products/alerts/frontend/utils.ts
+++ b/products/alerts/frontend/utils.ts
@@ -1,3 +1,7 @@
+import { AlertState } from '~/queries/schema/schema-general'
+
+import type { AlertCheck, AlertCheckDelivery } from './types'
+
export enum AlertsTab {
INSIGHTS = 'insights',
LOGS = 'logs',
@@ -49,3 +53,29 @@ export function getAlertsTabs({
}
return tabs
}
+
+export type DeliverySummary =
+ | { kind: 'delivered'; label: string; lines: string[] }
+ | { kind: 'notified' }
+ | { kind: 'none' }
+
+export function summarizeDeliveries(
+ deliveries: AlertCheckDelivery[] | null,
+ targetsNotified: boolean
+): DeliverySummary {
+ const accepted = (deliveries ?? []).filter((delivery) => delivery.status === 'accepted')
+ if (accepted.length > 0) {
+ return { kind: 'delivered', label: `Yes · ${accepted.length}`, lines: accepted.map((d) => d.display_label) }
+ }
+ // Checks predating delivery receipts know only that something was notified, not what.
+ return targetsNotified ? { kind: 'notified' } : { kind: 'none' }
+}
+
+/** Whether an empty receipt list means a dispatch accepted nothing, rather than one never running. */
+export function isFailedDelivery(check: AlertCheck): boolean {
+ if (check.state !== AlertState.FIRING || check.notification_suppressed_by_agent) {
+ return false
+ }
+ // Gated on an investigation: no dispatch has run yet, so there is nothing to blame.
+ return check.investigation_status !== 'pending' && check.investigation_status !== 'running'
+}
diff --git a/products/alerts/frontend/views/AlertHistorySection.tsx b/products/alerts/frontend/views/AlertHistorySection.tsx
index b93d59145315..388b0fbda5b9 100644
--- a/products/alerts/frontend/views/AlertHistorySection.tsx
+++ b/products/alerts/frontend/views/AlertHistorySection.tsx
@@ -27,6 +27,7 @@ import { AlertHistoryChart } from 'products/alerts/frontend/views/AlertHistoryCh
import { alertLogic, CHART_CHECKS_LIMIT, TABLE_CHECKS_PAGE_SIZE } from '../logic/alertLogic'
import { isAnyRowHogQLConfig } from '../types'
import type { AlertCheck, AlertType, InvestigationVerdict } from '../types'
+import { isFailedDelivery, summarizeDeliveries } from '../utils'
const VERDICT_CONFIG: Record<InvestigationVerdict, { label: string; className: string; tooltip: string }> = {
true_positive: {
@@ -211,7 +212,35 @@ export function AlertHistorySection({
title: 'Targets notified',
key: 'targets_notified',
align: 'right',
- render: (_value, check) => (check.targets_notified ? 'Yes' : 'No'),
+ render: (_value, check) => {
+ const summary = summarizeDeliveries(check.deliveries, check.targets_notified)
+ if (summary.kind === 'notified') {
+ return 'Yes'
+ }
+ if (summary.kind === 'none') {
+ if (isFailedDelivery(check)) {
+ return (
+ <Tooltip title="This alert fired but nothing was sent. Check who's subscribed and which destinations are set up.">
+ <span>No</span>
+ </Tooltip>
+ )
+ }
+ return 'No'
+ }
+ return (
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-0.5">
+ {summary.lines.map((line, i) => (
+ <span key={i}>{line}</span>
+ ))}
+ </div>
+ }
+ >
+ <span>{summary.label}</span>
+ </Tooltip>
+ )
+ },
})
return columns
}, [alertHistoryIsAnomalyDetection, investigationAgentEnabled, isAnyRowSqlAlert])
diff --git a/products/alerts/frontend/views/AlertModal.stories.tsx b/products/alerts/frontend/views/AlertModal.stories.tsx
index a915a58a05e1..8bcb5451064a 100644
--- a/products/alerts/frontend/views/AlertModal.stories.tsx
+++ b/products/alerts/frontend/views/AlertModal.stories.tsx
@@ -35,6 +35,7 @@ function makeChecks(values: number[]): AlertCheck[] {
calculated_value: calculatedValue,
state: AlertState.NOT_FIRING,
targets_notified: false,
+ deliveries: null,
}))
}
@@ -87,6 +88,27 @@ const makeAlert = (overrides: Partial<AlertType>): AlertType =>
}) as AlertType
const trendsAlert = makeAlert({})
+// Shows the delivery details tooltip on the History tab's "Targets notified" cell.
+trendsAlert.checks![trendsAlert.checks!.length - 1].targets_notified = true
+trendsAlert.checks![trendsAlert.checks!.length - 1].deliveries = [
+ {
+ channel: 'email',
+ target: '[email protected]',
+ status: 'accepted',
+ at: '2026-07-16T14:00:00Z',
+ display_label: 'Email: [email protected]',
+ },
+ {
+ channel: 'hog_function',
+ target: 'Slack #eng-alerts',
+ template: 'slack',
+ status: 'accepted',
+ at: '2026-07-16T14:00:00Z',
+ display_label: 'Slack #eng-alerts',
+ },
+]
+// A check recorded before delivery receipts existed: a bare "Yes", no receipt list.
+trendsAlert.checks![trendsAlert.checks!.length - 2].targets_notified = true
const funnelAlert = makeAlert({
id: 'alert-funnel',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 68c2772b7f54..5b32c4b0d0e1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8893,6 +8893,32 @@ export namespace Schemas {
Inconclusive: 'inconclusive',
} as const;
+ export interface AlertDelivery {
+ /** Delivery channel: 'email' or 'hog_function' (destinations). */
+ channel: string;
+ /** Email address, or destination name, that received the notification. */
+ target: string;
+ /**
+ * Hog function ID, for destination deliveries. Null for email.
+ * @nullable
+ */
+ target_id?: string | null;
+ /**
+ * Destination template: 'slack', 'discord', 'webhook', or 'teams'. Null for email.
+ * @nullable
+ */
+ template?: string | null;
+ /** Delivery status. Always 'accepted', for a confirmed send. */
+ status: string;
+ /**
+ * When the delivery was recorded.
+ * @nullable
+ */
+ at: string | null;
+ /** Ready-to-display description of the delivery, e.g. 'Email: [email protected]' or 'Slack #eng-alerts'. */
+ display_label: string;
+ }
+
export interface AlertCheck {
readonly id: string;
readonly created_at: string;
@@ -8918,6 +8944,11 @@ export namespace Schemas {
/** @nullable */
readonly notification_sent_at: string | null;
readonly notification_suppressed_by_agent: boolean;
+ /**
+ * Destinations that accepted this check's notification, one record per destination (channel, target, status, at). Null when no delivery receipt was recorded, which covers checks that notified nobody and checks predating delivery receipts.
+ * @nullable
+ */
+ readonly deliveries: readonly AlertDelivery[] | null;
}
export type TrendsAlertConfigType = typeof TrendsAlertConfigType[keyof typeof TrendsAlertConfigType];