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): deliver platform alerts to subscribers as in-app notifications (#114771)

Jimmy Zhuec92b0b20f4f
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index e9bdf094cf6b..71963cbbae33 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -99,6 +99,7 @@ from products.alerts.backend.facade.api import (
is_llm_detector_config,
)
from products.alerts.backend.facade.destinations import count_active_alert_destinations
+from products.alerts.backend.facade.email import alert_email_recipients
from products.alerts.backend.insight_alert_state_machine import apply_unsnooze
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
from products.notifications.backend.facade.api import (
@@ -1007,7 +1008,7 @@ async def record_failed_evaluation(inputs: RecordFailedEvaluationActivityInputs)
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.
+ """Fan out one realtime in-app notification per subscribed user who can view the insight.
Exceptions are caught and logged internally so a realtime delivery failure does not
poison the email path or the alert-check transaction.
@@ -1018,7 +1019,7 @@ def dispatch_alert_firing_realtime_notification(
body += f" (+{len(breaches) - 3} more)"
title = f"Alert firing: {alert.name}"[:100]
source_url = f"/project/{alert.team.project_id}/insights/{alert.insight.short_id}#alert={alert.id}"
- for user_id in alert.subscribed_users.values_list("id", flat=True):
+ for user_id, _ in alert_email_recipients(team_id=alert.team_id, alert_id=alert.id):
create_notification(
NotificationData(
team_id=alert.team_id,
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 282ce4cec33b..50927812ca54 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -1727,6 +1727,32 @@ class TestNotifyAlert:
assert recipients == []
+ async def test_firing_notification_excludes_subscriber_without_insight_access(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",
+ return_value=[_email_delivery("[email protected]")],
+ ),
+ patch(
+ "products.alerts.backend.logic.alert_email.UserAccessControl.check_access_level_for_object",
+ return_value=False,
+ ),
+ patch("posthog.temporal.alerts.activities.create_notification") as mock_create_notification,
+ ):
+ 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_create_notification.assert_not_called()
+
async def test_error_realtime_notification_failure_does_not_block_recording_delivery(self, alert_with_user) -> None:
check = await _create_alert_check(alert_with_user, state=AlertState.ERRORED, error={"message": "boom"})
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index 7ccd84f8c6bd..78c81644a044 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -26,7 +26,7 @@ from products.alerts_platform.backend.facade.contracts import (
OwnedAlertDestination,
)
-from ..logic import alert_email, destination_configs, destinations, insight_alert_destinations
+from ..logic import delivery_destinations, destination_configs, destinations, insight_alert_destinations
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
@@ -214,7 +214,8 @@ def alert_internal_event_delivered(
def list_delivery_destination_groups(
*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
) -> list[AlertDestinationGroup]:
- """Everything the shared platform delivers one alert's events to, including subscriber email."""
- return alert_email.list_delivery_destination_groups(
+ """Everything the shared platform delivers one alert's events to, including subscriber email and
+ in-app notifications."""
+ return delivery_destinations.list_delivery_destination_groups(
team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
)
diff --git a/products/alerts/backend/logic/alert_email.py b/products/alerts/backend/logic/alert_email.py
index c5f50873f383..f63c26a7d576 100644
--- a/products/alerts/backend/logic/alert_email.py
+++ b/products/alerts/backend/logic/alert_email.py
@@ -11,7 +11,6 @@ from typing import Final
from uuid import UUID
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.alerts.backend.logic.destinations import list_alert_destination_groups
from products.alerts.backend.models.alert import AlertConfiguration
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
@@ -24,14 +23,25 @@ from products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT
# platform routes errored transitions to email by this id, which no HogFunction can subscribe to.
INSIGHT_ALERT_ERRORED_EVENT_ID: Final = "$insight_alert_errored"
-_EMAIL_EVENT_IDS: Final = frozenset({LEGACY_INSIGHT_ALERT_EVENT, INSIGHT_ALERT_ERRORED_EVENT_ID})
+SUBSCRIBER_EVENT_IDS: Final = frozenset({LEGACY_INSIGHT_ALERT_EVENT, INSIGHT_ALERT_ERRORED_EVENT_ID})
+
+
+def insight_alert(*, team_id: int, alert_id: str) -> AlertConfiguration | None:
+ """The insight alert a platform destination lookup names, or None when the id is another source's."""
+ try:
+ alert_uuid = UUID(alert_id)
+ except ValueError:
+ return None
+ return AlertConfiguration.objects.filter(team_id=team_id, id=alert_uuid).select_related("team", "insight").first()
def alert_email_recipients(*, team_id: int, alert_id: UUID) -> list[tuple[int, str]]:
"""Subscribed users who can still view the project and the alert's insight."""
alert = AlertConfiguration.objects.filter(team_id=team_id, id=alert_id).select_related("team", "insight").first()
- if alert is None:
- return []
+ return recipients_with_access(alert) if alert is not None else []
+
+
+def recipients_with_access(alert: AlertConfiguration) -> list[tuple[int, str]]:
candidates = (
alert.team.all_users_with_access()
.filter(id__in=alert.subscribed_users.values_list("id", flat=True))
@@ -44,31 +54,9 @@ def alert_email_recipients(*, team_id: int, alert_id: UUID) -> list[tuple[int, s
]
-def list_delivery_destination_groups(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
-) -> list[AlertDestinationGroup]:
- """Everything the platform delivers one alert's events to: its HogFunction destinations, plus
- its subscribers' email for an insight alert.
-
- Separate from `list_alert_destination_groups`, which the alert APIs list and delete through. An
- email group there would show up as a destination a person could delete.
- """
- groups = list_alert_destination_groups(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
- email = _insight_email_group(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
- return [*groups, email] if email is not None else groups
-
-
-def _insight_email_group(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
-) -> AlertDestinationGroup | None:
- if _EMAIL_EVENT_IDS.isdisjoint(allowed_event_ids):
- return None
- try:
- alert_uuid = UUID(alert_id)
- except ValueError:
- return None
- addresses = sorted({email for _, email in alert_email_recipients(team_id=team_id, alert_id=alert_uuid) if email})
+def insight_email_groups(recipients: Collection[tuple[int, str]]) -> list[AlertDestinationGroup]:
+ addresses = sorted({email for _, email in recipients if email})
if not addresses:
- return None
+ return []
data: AlertDestinationData = {"type": DestinationType.EMAIL, "email_addresses": addresses}
- return AlertDestinationGroup(hog_function_ids=(), data=data, fully_enabled=True)
+ return [AlertDestinationGroup(hog_function_ids=(), data=data, fully_enabled=True)]
diff --git a/products/alerts/backend/logic/alert_in_app.py b/products/alerts/backend/logic/alert_in_app.py
new file mode 100644
index 000000000000..c68bdce3bda7
--- /dev/null
+++ b/products/alerts/backend/logic/alert_in_app.py
@@ -0,0 +1,48 @@
+"""Who an insight alert notifies in the app, for the shared platform.
+
+An insight alert notifies its subscribers in the app besides any HogFunction destinations. Only
+subscribers who can still view the alert's insight receive one, because the notification inbox
+checks access to insights in general and not to one insight. The recipients are the email
+recipients, so a user who loses access to the insight stops receiving either.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+
+from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID
+from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationGroup,
+ DestinationType,
+)
+from products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT
+
+
+def insight_in_app_groups(
+ alert: AlertConfiguration, *, event_ids: Collection[str], recipients_with_access: Collection[tuple[int, str]]
+) -> list[AlertDestinationGroup]:
+ user_ids = [user_id for user_id, _ in recipients_with_access]
+ if not user_ids:
+ return []
+ short_id = alert.insight.short_id
+ # Each kind links where the production notification for that kind links.
+ urls = {
+ LEGACY_INSIGHT_ALERT_EVENT: f"/project/{alert.team.project_id}/insights/{short_id}#alert={alert.id}",
+ INSIGHT_ALERT_ERRORED_EVENT_ID: f"/project/{alert.team_id}/insights/{short_id}?alert_id={alert.id}",
+ }
+ return [
+ _group(user_ids=user_ids, short_id=short_id, url=url) for event_id, url in urls.items() if event_id in event_ids
+ ]
+
+
+def _group(*, user_ids: list[int], short_id: str, url: str) -> AlertDestinationGroup:
+ data: AlertDestinationData = {
+ "type": DestinationType.IN_APP,
+ "in_app_user_ids": sorted(user_ids),
+ "in_app_resource_type": "insight",
+ "in_app_resource_id": short_id,
+ "in_app_url": url,
+ }
+ return AlertDestinationGroup(hog_function_ids=(), data=data, fully_enabled=True)
diff --git a/products/alerts/backend/logic/delivery_destinations.py b/products/alerts/backend/logic/delivery_destinations.py
new file mode 100644
index 000000000000..7ef4dfb6a7c6
--- /dev/null
+++ b/products/alerts/backend/logic/delivery_destinations.py
@@ -0,0 +1,39 @@
+"""Everything the shared platform delivers one alert's events to."""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+
+from products.alerts.backend.logic.alert_email import (
+ SUBSCRIBER_EVENT_IDS,
+ insight_alert,
+ insight_email_groups,
+ recipients_with_access,
+)
+from products.alerts.backend.logic.alert_in_app import insight_in_app_groups
+from products.alerts.backend.logic.destinations import list_alert_destination_groups
+from products.alerts_platform.backend.facade.contracts import AlertDestinationGroup
+
+
+def list_delivery_destination_groups(
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> list[AlertDestinationGroup]:
+ """An alert's HogFunction destinations, plus its subscribers' email and in-app notifications
+ for an insight alert.
+
+ Separate from `list_alert_destination_groups`, which the alert APIs list and delete through. A
+ subscriber group there would show up as a destination a person could delete.
+ """
+ groups = list_alert_destination_groups(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
+ event_ids = SUBSCRIBER_EVENT_IDS.intersection(allowed_event_ids)
+ if not event_ids:
+ return groups
+ alert = insight_alert(team_id=team_id, alert_id=alert_id)
+ if alert is None:
+ return groups
+ recipients = recipients_with_access(alert)
+ return [
+ *groups,
+ *insight_email_groups(recipients),
+ *insight_in_app_groups(alert, event_ids=event_ids, recipients_with_access=recipients),
+ ]
diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.py
index b6bf976ab047..25bc31898dd1 100644
--- a/products/alerts/backend/logic/destination_configs.py
+++ b/products/alerts/backend/logic/destination_configs.py
@@ -370,9 +370,13 @@ def _redact_routing_key(value: str) -> str:
return f"••••{value[-4:]}"
-# Email reaches an alert's subscribers and is never stored as a HogFunction, so it has no spec.
+# Email and in-app notifications reach an alert's subscribers and are never stored as a HogFunction,
+# so they have no spec. Listed by hand so that a new HogFunction type without a spec fails the
+# one-to-one test against `DESTINATION_SPECS`.
HOG_FUNCTION_DESTINATION_TYPES: tuple[DestinationType, ...] = tuple(
- destination_type for destination_type in DestinationType if destination_type != DestinationType.EMAIL
+ destination_type
+ for destination_type in DestinationType
+ if destination_type not in (DestinationType.EMAIL, DestinationType.IN_APP)
)
DESTINATION_SPECS: dict[DestinationType, DestinationSpec] = {
diff --git a/products/alerts/backend/test/test_alert_email.py b/products/alerts/backend/test/test_alert_email.py
index 90b378d80ec5..06b36f8ebf0c 100644
--- a/products/alerts/backend/test/test_alert_email.py
+++ b/products/alerts/backend/test/test_alert_email.py
@@ -1,9 +1,11 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from posthog.models.user import User
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.alerts.backend.facade.destinations import list_alert_destination_groups, list_delivery_destination_groups
from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription
@@ -20,19 +22,38 @@ class TestInsightAlertEmailDestination(APIBaseTest):
AlertSubscription.objects.create(user=user, alert_configuration=alert)
@parameterized.expand([("firing", LEGACY_INSIGHT_ALERT_EVENT), ("errored", INSIGHT_ALERT_ERRORED_EVENT_ID)])
- def test_the_platform_emails_subscribers_who_can_still_see_the_alert(self, _name: str, event_id: str) -> None:
+ def test_the_platform_reaches_only_subscribers_who_can_still_see_the_insight(
+ self, _name: str, event_id: str
+ ) -> None:
alert = self._alert()
self._subscribe(alert, self.user)
self._subscribe(alert, User.objects.create(email="[email protected]"))
+ denied = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._subscribe(alert, denied)
+ firing = event_id == LEGACY_INSIGHT_ALERT_EVENT
+ short_id = alert.insight.short_id
- groups = list_delivery_destination_groups(
- team_id=self.team.id, alert_id=str(alert.id), allowed_event_ids=[event_id]
- )
+ def can_view(access_control: UserAccessControl, *_args: object) -> bool:
+ return access_control._user.id != denied.id
+
+ with patch.object(UserAccessControl, "check_access_level_for_object", autospec=True, side_effect=can_view):
+ groups = list_delivery_destination_groups(
+ team_id=self.team.id, alert_id=str(alert.id), allowed_event_ids=[event_id]
+ )
assert [group.data for group in groups] == [
- {"type": DestinationType.EMAIL, "email_addresses": [self.user.email]}
+ {"type": DestinationType.EMAIL, "email_addresses": [self.user.email]},
+ {
+ "type": DestinationType.IN_APP,
+ "in_app_user_ids": [self.user.id],
+ "in_app_resource_type": "insight",
+ "in_app_resource_id": short_id,
+ "in_app_url": f"/project/{self.team.project_id}/insights/{short_id}#alert={alert.id}"
+ if firing
+ else f"/project/{self.team.id}/insights/{short_id}?alert_id={alert.id}",
+ },
]
- # The alert APIs list and delete through this one, so an email group there would read as a
+ # The alert APIs list and delete through this one, so a subscriber group there would read as a
# destination a person could remove.
assert (
list_alert_destination_groups(team_id=self.team.id, alert_id=str(alert.id), allowed_event_ids=[event_id])
@@ -46,7 +67,7 @@ class TestInsightAlertEmailDestination(APIBaseTest):
("an_alert_nobody_subscribed_to", False, None, LEGACY_INSIGHT_ALERT_EVENT),
]
)
- def test_no_email_group_without_an_insight_alert_and_a_subscriber(
+ def test_no_subscriber_group_without_an_insight_alert_and_a_subscriber(
self, _name: str, subscribed: bool, alert_id: str | None, event_id: str
) -> None:
alert = self._alert()
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index edcba6e7a733..813d4a11be49 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -99,14 +99,31 @@ class TestPlatformInsightEvaluation(APIBaseTest):
assert AlertConfiguration.objects.values("state", "next_check_at", "last_checked_at").get(id=alert.id) == before
assert not AlertCheck.objects.filter(alert_configuration=alert).exists()
- @parameterized.expand([("allowlisted", True), ("not_allowlisted", False)])
- def test_only_an_allowlisted_alert_asks_for_a_delivery(self, _name: str, allowlisted: bool) -> None:
+ @parameterized.expand(
+ [
+ ("allowlisted", True, False),
+ ("not_allowlisted", False, False),
+ ("allowlisted_resolve", True, True),
+ ]
+ )
+ def test_only_an_allowlisted_firing_or_failure_asks_for_a_delivery(
+ self, _name: str, allowlisted: bool, was_firing: bool
+ ) -> None:
alert = self._alert()
configuration = self._copy(alert)
allowlist = frozenset({str(alert.id)}) if allowlisted else frozenset()
+ if was_firing:
+ fired, _ = self._evaluate(configuration, result=AlertEvaluationResult(value=150.0, breaches=["above 100"]))
+ assert fired is not None
+ record_outcomes(self.team.id, (fired,), CUTOFF)
+ with team_scope(self.team.id):
+ platform_testing.set_due_at(configuration.id, CUTOFF - timedelta(minutes=1))
with patch(f"{_MODULE}.LIVE_DELIVERY_INSIGHT_ALERT_IDS", allowlist):
- self._evaluate(configuration, result=AlertEvaluationResult(value=150.0, breaches=["above 100"]))
+ self._evaluate(
+ configuration,
+ result=AlertEvaluationResult(value=50.0, breaches=[] if was_firing else ["above 100"]),
+ )
expected = [
(
@@ -118,7 +135,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):
assert [
(delivery.configuration_id, delivery.destination_alert_id, delivery.event_ids_by_kind)
for delivery in self.deliveries
- ] == (expected if allowlisted else [])
+ ] == (expected if allowlisted and not was_firing else [])
@parameterized.expand(
[
diff --git a/products/alerts_platform/backend/delivery/destinations.py b/products/alerts_platform/backend/delivery/destinations.py
index 228a9ce44b52..5e9e6d376780 100644
--- a/products/alerts_platform/backend/delivery/destinations.py
+++ b/products/alerts_platform/backend/delivery/destinations.py
@@ -1,8 +1,11 @@
"""Who a delivery sends to.
-Destinations are HogFunction rows, and `products.alerts` owns them. The platform imports no other
+`products.alerts` owns every destination: the HogFunction rows a person configured, and the
+subscriber email and in-app groups it adds for an insight alert. The platform imports no other
product, so that product registers its lookup here when Django starts, and delivery asks this
-module rather than the owner. This module goes away when destinations move into the platform.
+module rather than the owner. One lookup answers for every source. A source decides which groups
+it can reach through the event ids it maps each kind onto, because the lookup answers per event
+id. This module goes away when destinations move into the platform.
"""
from collections.abc import Collection
diff --git a/products/alerts_platform/backend/delivery/email.py b/products/alerts_platform/backend/delivery/email.py
index f9c230988c13..3b0014f553a9 100644
--- a/products/alerts_platform/backend/delivery/email.py
+++ b/products/alerts_platform/backend/delivery/email.py
@@ -7,14 +7,13 @@ recipient against a campaign key, so a retried delivery sends nobody a second co
An email starts no conversation, so a send returns no handle and a resolve is a new email.
"""
-import hashlib
from typing import Final
from django.core.exceptions import ImproperlyConfigured
from posthog.email import EmailMessage
-from products.alerts_platform.backend.delivery.message import AlertMessage
+from products.alerts_platform.backend.delivery.message import AlertMessage, transition_delivery_key
from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
from products.alerts_platform.backend.delivery.wire import credential_digest
from products.alerts_platform.backend.facade.contracts import AlertDestinationData
@@ -23,20 +22,6 @@ PROVIDER: Final = "email"
TEMPLATE_NAME: Final = "alert_platform_notification"
-def _campaign_key(message: AlertMessage) -> str:
- # One key per transition a check recorded. `posthog.email` refuses a second send under one key
- # to one recipient, so a retry of this delivery reaches nobody twice. The column holds 128
- # characters, which a long evaluation or group key would exceed, so the key is a digest.
- transition = message.transition
- parts = (
- message.configuration_id,
- transition.grouping_key,
- transition.kind.value,
- transition.occurred_at.isoformat(),
- )
- return f"alert-platform-{hashlib.sha256('|'.join(parts).encode()).hexdigest()[:32]}"
-
-
def subject_for(message: AlertMessage) -> str:
# The alert name is user-written, and a header cannot carry a line break.
return f"PostHog alert: {' '.join(message.headline.split())}"
@@ -62,7 +47,7 @@ class EmailTransport:
raise DeliveryError("This email destination has no recipients.")
try:
email = EmailMessage(
- campaign_key=_campaign_key(message),
+ campaign_key=transition_delivery_key(message),
template_name=TEMPLATE_NAME,
subject=subject_for(message),
template_context={
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index a62d76dfedd6..ca2aa18eb4c7 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -17,6 +17,7 @@ from products.alerts_platform.backend.delivery.destinations import list_alert_de
from products.alerts_platform.backend.delivery.discord import DiscordTransport
from products.alerts_platform.backend.delivery.dispatch import deliver
from products.alerts_platform.backend.delivery.email import EmailTransport
+from products.alerts_platform.backend.delivery.in_app import InAppTransport
from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport
from products.alerts_platform.backend.delivery.slack import SlackTransport
from products.alerts_platform.backend.delivery.teams import TeamsTransport
@@ -52,6 +53,7 @@ _TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {
DestinationType.DISCORD: DiscordTransport,
DestinationType.PAGERDUTY: PagerDutyTransport,
DestinationType.EMAIL: EmailTransport,
+ DestinationType.IN_APP: InAppTransport,
}
diff --git a/products/alerts_platform/backend/delivery/in_app.py b/products/alerts_platform/backend/delivery/in_app.py
new file mode 100644
index 000000000000..6a2149a72528
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/in_app.py
@@ -0,0 +1,87 @@
+"""In-app delivery, to the PostHog notification inbox of the people subscribed to an alert.
+
+The user ids arrive resolved, like an email destination's addresses. The product that owns the
+subscriptions applies its access rules before the platform sees an id. Each notification carries
+an idempotency key per transition and recipient, so a retried delivery notifies nobody twice.
+
+A notification starts no conversation, so a send returns no handle and a resolve is a new one.
+"""
+
+from typing import Final, cast
+from urllib.parse import urlsplit
+
+from posthog.slack.channels import clip_text
+
+from products.alerts_platform.backend.delivery.message import AlertMessage, transition_delivery_key
+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.delivery.wire import credential_digest
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind
+from products.notifications.backend.facade.api import (
+ NotificationData,
+ NotificationResourceType,
+ NotificationType,
+ Priority,
+ TargetType,
+ create_notification,
+)
+
+PROVIDER: Final = "in_app"
+MAX_TITLE_CHARS: Final = 100
+
+# A person turns off each type in their notification settings. A resolve has no type of its own, so
+# it shares the firing type, and turning off alert notifications turns off both.
+_NOTIFICATION_TYPES: Final[dict[AlertEventKind, NotificationType]] = {
+ AlertEventKind.FIRING: NotificationType.ALERT_FIRING,
+ AlertEventKind.RESOLVED: NotificationType.ALERT_FIRING,
+ AlertEventKind.ERRORED: NotificationType.PIPELINE_FAILURE,
+ AlertEventKind.BROKEN: NotificationType.PIPELINE_FAILURE,
+}
+
+
+def body_for(message: AlertMessage) -> str:
+ return "; ".join([*(f"{detail.label}: {detail.value}" for detail in message.details), *message.context])
+
+
+class InAppTransport:
+ provider = PROVIDER
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return credential_digest("\n".join(str(user_id) for user_id in sorted(target.get("in_app_user_ids", []))))
+
+ def deliver(
+ self,
+ *,
+ team_id: int,
+ target: AlertDestinationData,
+ message: AlertMessage,
+ in_reply_to: MessageHandle | None = None,
+ ) -> MessageHandle | None:
+ user_ids = target.get("in_app_user_ids") or []
+ if not user_ids:
+ raise DeliveryError("This in-app destination has no recipients.")
+ notification_type = _NOTIFICATION_TYPES.get(message.transition.kind)
+ if notification_type is None:
+ raise DeliveryError(f"In-app notifications have no type for {message.transition.kind.value} alerts.")
+ key = transition_delivery_key(message)
+ raw_resource_type = target.get("in_app_resource_type")
+ resource_type = cast(NotificationResourceType, raw_resource_type) if raw_resource_type else None
+ title = clip_text(message.headline, MAX_TITLE_CHARS)
+ body = body_for(message)
+ source_url = target.get("in_app_url") or urlsplit(message.alert_url).path
+ for user_id in user_ids:
+ create_notification(
+ NotificationData(
+ team_id=team_id,
+ notification_type=notification_type,
+ priority=Priority.NORMAL,
+ title=title,
+ body=body,
+ target_type=TargetType.USER,
+ target_id=str(user_id),
+ resource_type=resource_type,
+ resource_id=target.get("in_app_resource_id", ""),
+ source_url=source_url,
+ idempotency_key=f"{key}:{user_id}",
+ )
+ )
+ return None
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index a39a2dbbebe6..d50e1c267b7a 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -6,6 +6,7 @@ it is rendered. A source can word parts of it in its own vocabulary through a re
A provider turns this into its own body shape.
"""
+import hashlib
from typing import Any, Final
from posthog.dataclasses import frozen
@@ -83,6 +84,23 @@ class AlertMessage:
return (self.data_link, view_alert) if self.data_link is not None else (view_alert,)
+def transition_delivery_key(message: AlertMessage) -> str:
+ """One key per transition a check recorded, for a provider that refuses a second send under one key.
+
+ A retried delivery builds the same key, so it reaches nobody twice. The email campaign column
+ and the notification idempotency column hold 128 characters, which a long evaluation or group
+ key would exceed, so the key is a digest.
+ """
+ transition = message.transition
+ parts = (
+ message.configuration_id,
+ transition.grouping_key,
+ transition.kind.value,
+ transition.occurred_at.isoformat(),
+ )
+ return f"alert-platform-{hashlib.sha256('|'.join(parts).encode()).hexdigest()[:32]}"
+
+
def state_symbol(kind: AlertEventKind) -> str:
"""The symbol a message about `kind` leads with, so an edited root matches its own messages."""
return _SYMBOLS[kind]
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index db73988a98ae..7691c4367a5b 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -469,6 +469,7 @@ class DestinationType(LabeledStrEnum):
TEAMS = "teams", "Microsoft Teams"
PAGERDUTY = "pagerduty", "PagerDuty"
EMAIL = "email", "Email"
+ IN_APP = "in_app", "In-app notification"
class PagerDutySeverity(StrEnum):
@@ -505,6 +506,12 @@ class AlertDestinationData(TypedDict):
pagerduty_severity: NotRequired[str]
pagerduty_region: NotRequired[str]
email_addresses: NotRequired[list[str]]
+ in_app_user_ids: NotRequired[list[int]]
+ # What an in-app notification is about, so the inbox applies its access rules for that resource.
+ in_app_resource_type: NotRequired[str]
+ in_app_resource_id: NotRequired[str]
+ # A path in the app, because the inbox opens it with the client-side router.
+ in_app_url: NotRequired[str]
class AlertDestinationValidationError(Exception):
diff --git a/products/alerts_platform/backend/tests/test_delivery_in_app.py b/products/alerts_platform/backend/tests/test_delivery_in_app.py
new file mode 100644
index 000000000000..dcbe2419db45
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_delivery_in_app.py
@@ -0,0 +1,71 @@
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models.user import User
+
+from products.alerts_platform.backend.delivery.in_app import InAppTransport
+from products.alerts_platform.backend.delivery.message import MessageDetail
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind, DestinationType
+from products.alerts_platform.backend.tests.delivery_messages import OCCURRED, alert_message, announced_transition
+from products.notifications.backend.facade.testing import stored_notifications_for_team
+
+
+class TestInAppTransport(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag = patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+ self.other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+
+ def _deliver(self, kind: AlertEventKind, **transition: Any) -> None:
+ target: AlertDestinationData = {
+ "type": DestinationType.IN_APP,
+ "in_app_user_ids": [self.user.id, self.other_user.id],
+ "in_app_resource_type": "insight",
+ "in_app_resource_id": "abc123",
+ "in_app_url": "/project/1/insights/abc123",
+ }
+ message = alert_message(
+ headline="Insight alert 'API errors' is firing",
+ details=(MessageDetail(label="Value", value="312"), MessageDetail(label="Threshold", value="> 300")),
+ transition=announced_transition(kind, **transition),
+ )
+ assert InAppTransport().deliver(team_id=self.team.id, target=target, message=message) is None
+
+ @parameterized.expand(
+ [
+ ("firing", AlertEventKind.FIRING, "alert_firing"),
+ ("errored", AlertEventKind.ERRORED, "pipeline_failure"),
+ ]
+ )
+ def test_a_retry_notifies_nobody_twice_and_a_later_transition_notifies_again(
+ self, _name: str, kind: AlertEventKind, notification_type: str
+ ) -> None:
+ self._deliver(kind)
+ self._deliver(kind)
+
+ events = stored_notifications_for_team(self.team.id)
+ assert sorted(user_id for event in events for user_id in event.resolved_user_ids) == sorted(
+ [self.user.id, self.other_user.id]
+ )
+ assert {
+ (event.notification_type, event.title, event.body, event.resource_id, event.source_url) for event in events
+ } == {
+ (
+ notification_type,
+ "Insight alert 'API errors' is firing",
+ "Value: 312; Threshold: > 300",
+ "abc123",
+ "/project/1/insights/abc123",
+ )
+ }
+
+ self._deliver(kind, occurred_at=OCCURRED + timedelta(hours=1))
+
+ assert len(stored_notifications_for_team(self.team.id)) == 4
diff --git a/products/notifications/backend/facade/testing.py b/products/notifications/backend/facade/testing.py
index 58843512c12f..e45768b38f51 100644
--- a/products/notifications/backend/facade/testing.py
+++ b/products/notifications/backend/facade/testing.py
@@ -11,15 +11,28 @@ from products.notifications.backend.models import NotificationEvent
@frozen
class StoredNotification:
+ notification_type: str
title: str
+ body: str
+ resource_id: str
source_url: str
resolved_user_ids: list[int]
-def stored_notification_for_resource(*, resource_type: str, resource_id: str) -> StoredNotification:
- event = NotificationEvent.objects.get(resource_type=resource_type, resource_id=resource_id)
+def _stored(event: NotificationEvent) -> StoredNotification:
return StoredNotification(
+ notification_type=event.notification_type,
title=event.title,
+ body=event.body,
+ resource_id=event.resource_id,
source_url=event.source_url,
resolved_user_ids=list(event.resolved_user_ids),
)
+
+
+def stored_notification_for_resource(*, resource_type: str, resource_id: str) -> StoredNotification:
+ return _stored(NotificationEvent.objects.get(resource_type=resource_type, resource_id=resource_id))
+
+
+def stored_notifications_for_team(team_id: int) -> list[StoredNotification]:
+ return [_stored(event) for event in NotificationEvent.objects.filter(team_id=team_id).order_by("created_at")]
diff --git a/tach.toml b/tach.toml
index 87c3deb3f227..39de0b5a51c4 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1642,7 +1642,7 @@ layer = "modules"
[[modules]]
path = "products.alerts_platform"
-depends_on = ["posthog", "products.access_control"]
+depends_on = ["posthog", "products.access_control", "products.notifications"]
layer = "modules"
[[interfaces]]