:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): send customized insight destinations their events after cutover (#120022)
Jimmy Zhue9d9b48e032d
diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.pyindex dce2f4ed560c..394958041b3f 100644--- a/posthog/tasks/alerts/test/test_utils.py+++ b/posthog/tasks/alerts/test/test_utils.py@@ -1,4 +1,5 @@from datetime import UTC, datetime+from functools import partialimport pytestimport time_machine@@ -112,6 +113,7 @@ class TestAlertUtils:alert.team_id = 2alert.team.name = "test project"alert.detector_config = detector_config+ alert.internal_event_properties.side_effect = partial(AlertConfiguration.internal_event_properties, alert)trigger_alert_hog_functions(alert, properties={"breaches": "test breach"})diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 5cd76688c170..3232c3b48fe8 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -34,7 +34,7 @@ from products.alerts.backend.insight_alert_state_machine import (evaluate_alert_check,should_notify,)-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, derive_detector_event_fields+from products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.alerts_platform.backend.facade.contracts import AlertDeliveryfrom products.alerts_platform.backend.facade.delivery_slo import alert_delivery_slofrom products.alerts_platform.backend.facade.enums import PlatformAlertOwner@@ -211,14 +211,7 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->)props = {- "alert_id": str(alert.id),- "alert_name": alert.name,- "project_name": alert.team.name,- "insight_name": alert.insight.name,- "insight_id": alert.insight.short_id,- "state": alert.state,- "last_checked_at": alert.last_checked_at.isoformat() if alert.last_checked_at else None,- **derive_detector_event_fields(alert.detector_config),+ **alert.internal_event_properties(state=alert.state, last_checked_at=alert.last_checked_at),**properties,}diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.pyindex ff06566b0e33..338c92d7536c 100644--- a/products/alerts/backend/apps.py+++ b/products/alerts/backend/apps.py@@ -14,20 +14,24 @@ class AlertsConfig(AppConfig):# scope — see activity_logging's docstring.from products.alerts.backend import activity_logging # noqa: F401, PLC0415- # The platform cannot import this product, so it reaches this product's destinations, and the- # schema an edit to an insight alert's copy is checked against, here.+ # The platform cannot import this product, so it reaches this product's destinations, the schema+ # an edit to an insight alert's copy is checked against, and the `$insight_alert_firing` events of+ # an insight alert on the HogFunction path, here.from products.alerts.backend.facade.destinations import ( # noqa: PLC0415choose_delivery_path,list_delivery_destination_groups,)+ from products.alerts.backend.platform_hooks import emit_insight_legacy_events # noqa: PLC0415from products.alerts.backend.platform_source_config import load_insight_source_config # noqa: PLC0415from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415register_delivery_path_chooser,register_destination_resolver,+ register_legacy_event_emitter,)from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415register_destination_resolver(list_delivery_destination_groups)register_delivery_path_chooser(choose_delivery_path)+ register_legacy_event_emitter(SourceKind.INSIGHT, emit_insight_legacy_events)register_source_config(SourceKind.INSIGHT, load_insight_source_config)diff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex 862425046ae1..2ecbd72f5339 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom datetime import UTC, datetime, timedelta-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom django.core.exceptions import ValidationErrorfrom django.db import models@@ -218,6 +218,19 @@ class AlertConfiguration(ModelActivityMixin, CreatedMetaFields, UUIDTModel):def __str__(self) -> str:return f"{self.name} (Team: {self.team})"+ def internal_event_properties(self, *, state: str, last_checked_at: datetime | None) -> dict[str, Any]:+ """The properties every `$insight_alert_firing` carries, from the insight stack or the platform."""+ return {+ "alert_id": str(self.id),+ "alert_name": self.name,+ "project_name": self.team.name,+ "insight_name": self.insight.name,+ "insight_id": self.insight.short_id,+ "state": state,+ "last_checked_at": last_checked_at.isoformat() if last_checked_at else None,+ **derive_detector_event_fields(self.detector_config),+ }+@propertydef platform_owned(self) -> bool:"""The platform evaluates and delivers this alert. The insight stack may still evaluate it todiff --git a/products/alerts/backend/platform_alert_legacy_events.py b/products/alerts/backend/platform_alert_legacy_events.pynew file mode 100644index 000000000000..c3868bd46e49--- /dev/null+++ b/products/alerts/backend/platform_alert_legacy_events.py@@ -0,0 +1,91 @@+"""The `$insight_alert_firing` events the platform emits for an insight alert it owns on the HogFunction path.++The alert's HogFunctions filter on this event and render these properties, so the platform+reproduces what `trigger_alert_hog_functions` sends: the same names, read from the same alert,+with the breach text and chart URL the check recorded beside its verdict.++The insight stack emits no internal event for a failed check. It emails the subscribers only, and+native delivery already sends that, so an errored transition emits nothing here.+"""++from __future__ import annotations++from collections.abc import Sequence+from typing import Any, Final+from uuid import NAMESPACE_URL, uuid5++from posthog.schema_enums import AlertState+from posthog.tasks.alerts.utils import RenderedInsightChart, insight_chart_url++from products.alerts.backend.facade.contracts import AlertInternalEvent+from products.alerts.backend.logic.destinations import emit_alert_internal_events+from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts_platform.backend.facade.contracts import (+ AlertDeliveryRequest,+ AlertEventKind,+ AnnouncedTransition,+ EvaluationAnnouncement,+ LegacyEventEmission,+)+from products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT++# Below the delivery activity's own timeout, which a flush must not use up.+FLUSH_TIMEOUT_SECONDS: Final = 5.0+++def emit_insight_legacy_events(+ *, request: AlertDeliveryRequest, announcement: EvaluationAnnouncement, emissions: Sequence[LegacyEventEmission]+) -> None:+ firings = [+ emission.transition+ for emission in emissions+ if emission.sends_message and emission.transition.kind == AlertEventKind.FIRING+ ]+ if not firings:+ return+ alert = (+ AlertConfiguration.objects.select_related("team", "insight")+ .filter(team_id=request.team_id, id=request.destination_alert_id)+ .first()+ )+ # A deleted alert takes its destinations with it, so nobody is left to receive the event.+ if alert is None:+ return+ emit_alert_internal_events(+ team_id=request.team_id,+ alert_id=request.destination_alert_id,+ events=[_firing_event(alert, transition) for transition in firings],+ flush_timeout_seconds=FLUSH_TIMEOUT_SECONDS,+ )+++def insight_chart_url_of(team_id: int, source_detail: dict[str, Any]) -> str | None:+ """The URL that embeds the chart a check rendered, minted now from the ids the check stored."""+ asset_id = source_detail.get("insight_chart_asset_id")+ render_user_id = source_detail.get("insight_chart_render_user_id")+ if not isinstance(asset_id, int) or not isinstance(render_user_id, int):+ return None+ return insight_chart_url(+ team_id=team_id, chart=RenderedInsightChart(asset_id=asset_id, render_user_id=render_user_id)+ )+++def _firing_event(alert: AlertConfiguration, transition: AnnouncedTransition) -> AlertInternalEvent:+ detail = transition.source_detail+ properties: dict[str, Any] = {+ **alert.internal_event_properties(state=AlertState.FIRING.value, last_checked_at=transition.occurred_at),+ "breaches": "\n".join(detail.get("breaches") or []),+ }+ if chart_url := insight_chart_url_of(alert.team_id, detail):+ properties["insight_chart_url"] = chart_url+ # The occurrence is in the seed too, so two firings recorded without an evaluation key keep distinct ids.+ seed = (+ f"{alert.id}|{transition.grouping_key}|{LEGACY_INSIGHT_ALERT_EVENT}|{transition.evaluation_key}|"+ f"{transition.occurred_at.isoformat()}"+ )+ return AlertInternalEvent(+ event_name=LEGACY_INSIGHT_ALERT_EVENT,+ properties=properties,+ timestamp=transition.occurred_at,+ uuid=str(uuid5(NAMESPACE_URL, seed)),+ )diff --git a/products/alerts/backend/platform_hooks.py b/products/alerts/backend/platform_hooks.pynew file mode 100644index 000000000000..8c9de6c45f8a--- /dev/null+++ b/products/alerts/backend/platform_hooks.py@@ -0,0 +1,30 @@+"""The insight hooks the alerts platform calls, registered from `ready()`.++Each hook imports its implementation on its first call. The implementations reach the alert task+helpers, and `ready()` runs in every process, so a module-level import would put them on every+process's startup path.+"""++from __future__ import annotations++from collections.abc import Sequence+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from products.alerts_platform.backend.facade.contracts import (+ AlertDeliveryRequest,+ EvaluationAnnouncement,+ LegacyEventEmission,+ )+++def emit_insight_legacy_events(+ *, request: AlertDeliveryRequest, announcement: EvaluationAnnouncement, emissions: Sequence[LegacyEventEmission]+) -> None:+ from products.alerts.backend import (+ platform_alert_legacy_events, # noqa: PLC0415 - keeps the alert task helpers off the startup path+ )++ platform_alert_legacy_events.emit_insight_legacy_events(+ request=request, announcement=announcement, emissions=emissions+ )diff --git a/products/alerts/backend/test/test_platform_alert_legacy_events.py b/products/alerts/backend/test/test_platform_alert_legacy_events.pynew file mode 100644index 000000000000..522c4089dde0--- /dev/null+++ b/products/alerts/backend/test/test_platform_alert_legacy_events.py@@ -0,0 +1,118 @@+from datetime import UTC, datetime+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.schema_enums import AlertState+from posthog.tasks.alerts.utils import RenderedInsightChart, trigger_alert_hog_functions++from products.alerts.backend.platform_alert_legacy_events import emit_insight_legacy_events+from products.alerts.backend.test.insight_alerts import create_insight_alert+from products.alerts_platform.backend.facade.contracts import (+ AlertDeliveryRequest,+ AlertEventKind,+ AnnouncedTransition,+ EvaluationAnnouncement,+ LegacyEventEmission,+ SourceKind,+)++_MODULE = "products.alerts.backend.platform_alert_legacy_events"+CHECKED_AT = datetime(2026, 10, 20, 9, 0, tzinfo=UTC)+CHART_URL = "https://example.com/chart.png"+_EMITTER = "products.alerts.backend.platform_alert_legacy_events"+++class TestInsightLegacyEvents(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.alert = create_insight_alert(+ self.team,+ name="Signups dropped",+ detector_config={"type": "zscore"},+ state=AlertState.FIRING.value,+ last_checked_at=CHECKED_AT,+ )++ def _emit(self, *emissions: LegacyEventEmission, alert_id: str | None = None) -> list[Any]:+ request = AlertDeliveryRequest(+ source=SourceKind.INSIGHT,+ team_id=self.team.id,+ configuration_id="cfg-1",+ evaluation_key="slot:1",+ destination_alert_id=alert_id or str(self.alert.id),+ event_ids_by_kind={},+ )+ announcement = EvaluationAnnouncement(+ configuration_id="cfg-1",+ source=SourceKind.INSIGHT,+ alert_name=self.alert.name,+ consecutive_failures=0,+ transitions=tuple(emission.transition for emission in emissions),+ )+ with patch(f"{_MODULE}.emit_alert_internal_events") as emit:+ emit_insight_legacy_events(request=request, announcement=announcement, emissions=emissions)+ return [event for call in emit.call_args_list for event in call.kwargs["events"]]++ @staticmethod+ def _emission(+ kind: AlertEventKind = AlertEventKind.FIRING,+ *,+ sends_message: bool = True,+ detail: dict[str, Any] | None = None,+ ) -> LegacyEventEmission:+ transition = AnnouncedTransition(+ grouping_key="",+ kind=kind,+ episode_started_at=CHECKED_AT,+ value=150.0,+ labels={},+ condition={},+ source_config={},+ error_message=None,+ occurred_at=CHECKED_AT,+ evaluation_key="slot:1",+ source_detail=detail or {},+ )+ return LegacyEventEmission(transition=transition, sends_message=sends_message, incident_action=None)++ @parameterized.expand(+ [+ ("without_a_chart", {}, {}),+ (+ "with_a_chart",+ {"insight_chart_asset_id": 7, "insight_chart_render_user_id": 3},+ {"insight_chart_url": CHART_URL},+ ),+ ]+ )+ def test_a_firing_emits_the_properties_the_insight_stack_sends(+ self, _name: str, stored: dict[str, int], sent: dict[str, str]+ ) -> None:+ breaches = ["The insight value (150) is more than upper threshold (100)", "A second series breached"]+ with patch("posthog.tasks.alerts.utils.produce_alert_internal_event") as produce:+ trigger_alert_hog_functions(self.alert, {"breaches": "\n".join(breaches), **sent})++ with patch(f"{_EMITTER}.insight_chart_url", return_value=CHART_URL) as mint:+ (event,) = self._emit(self._emission(detail={"breaches": breaches, **stored}))++ assert event.event_name == produce.call_args.kwargs["event_name"]+ assert event.properties == produce.call_args.kwargs["properties"]+ # The URL opens the chart without a login, so it is minted for the user that rendered it.+ if stored:+ assert mint.call_args.kwargs["chart"] == RenderedInsightChart(asset_id=7, render_user_id=3)++ @parameterized.expand(+ [+ ("an_error", AlertEventKind.ERRORED, True, None),+ ("a_held_message", AlertEventKind.FIRING, False, None),+ ("a_deleted_alert", AlertEventKind.FIRING, True, "01900000-0000-0000-0000-00000000dead"),+ ]+ )+ def test_nothing_the_insight_stack_would_not_send_is_emitted(+ self, _name: str, kind: AlertEventKind, sends_message: bool, alert_id: str | None+ ) -> None:+ assert self._emit(self._emission(kind, sends_message=sends_message), alert_id=alert_id) == []diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.pyindex 4e8ae5104343..7cc0c79e478c 100644--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py@@ -535,6 +535,8 @@ class TestDeliverEvaluation(APIBaseTest):def test_the_destination_owner_registers_its_lookup_at_startup(self) -> None:# Every other case here patches the lookup, so none of them notices a missing registration.assert delivery_paths._chooser is not None+ # Without it an insight alert on the HogFunction path sends nothing at all.+ assert delivery_paths.emitter_for(SourceKind.INSIGHT) is not Noneassert (list_alert_destination_groups(team_id=self.team.id, alert_id="unknown", allowed_event_ids=[FIRING_EVENT])== []