: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(today): show firing insight alerts as a highlight (#117266)
Shy Alter97c5b05955a7
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex 4cdd189a9fbe..f3668384eb91 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -8,20 +8,25 @@ lifecycle machine in `facade.lifecycle`, and scheduling math in `facade.scheduliimport uuidfrom collections.abc import Collectionfrom datetime import datetime, timedelta+from itertools import islicefrom typing import Literalfrom zoneinfo import ZoneInfofrom django.db import transaction+from django.db.models import Qfrom django.utils import timezoneimport structlogfrom posthog.models.activity_logging.model_activity import ActingUserContext+from posthog.models.team import Teamfrom posthog.models.user import User+from posthog.schema_enums import AlertStatefrom posthog.user_permissions import UserPermissionsfrom posthog.utils import relative_date_parsefrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.alerts.backend.facade import contractsfrom products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.judge.contract import (LLM_DETECTOR_UNAVAILABLE_ERROR_CODE,@@ -39,7 +44,7 @@ from products.alerts.backend.llm_detector_limits import (is_llm_detector_config,llm_detector_access_error,)-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration+from products.alerts.backend.models.alert import METRICS_INSIGHT_QUERY_FILTER, AlertCheck, AlertConfigurationlogger = structlog.get_logger(__name__)@@ -177,6 +182,35 @@ def snooze_alert_from_slack(return "snoozed"+FIRING_ALERT_CANDIDATES = 200+++def list_firing_alerts_created_by(+ team: Team, user: User, *, include_metrics_insights: bool, limit: int+) -> list[contracts.FiringAlert]:+ alerts = AlertConfiguration.objects.filter(+ team_id=team.id,+ enabled=True,+ state=AlertState.FIRING,+ created_by_id=user.id,+ insight__deleted=False,+ ).filter(Q(snoozed_until__isnull=True) | Q(snoozed_until__lt=timezone.now()))+ if not include_metrics_insights:+ alerts = alerts.exclude(id__in=alerts.filter(METRICS_INSIGHT_QUERY_FILTER).values("id"))+ access = UserAccessControl(user, team=team)+ candidates = alerts.select_related("insight").order_by("-created_at")[:FIRING_ALERT_CANDIDATES]+ viewable = (alert for alert in candidates if access.check_access_level_for_object(alert.insight, "viewer"))+ return [+ contracts.FiringAlert(+ id=alert.id,+ name=alert.name,+ insight_name=alert.insight.name or alert.insight.derived_name,+ insight_short_id=alert.insight.short_id,+ )+ for alert in islice(viewable, limit)+ ]++__all__ = ["LLM_DETECTOR_UNAVAILABLE_ERROR_CODE","LLM_DETECTOR_UNAVAILABLE_MESSAGE",diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex 67b910f0c9d9..400ec66aa8c4 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -88,3 +88,11 @@ class BucketedDestination:# None for a function bound to no single alert, which fires for several alerts of the team.alert_id: str | Noneeligibility: DestinationEligibility+++@frozen+class FiringAlert:+ id: UUID+ name: str+ insight_name: str | None+ insight_short_id: strdiff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex ed6ea516975d..c55492b4c845 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -25,6 +25,12 @@ ALERT_STATE_CHOICES = [(AlertState.SNOOZED, AlertState.SNOOZED),]+# Matches insights whose (bare or one-level-wrapped) query is a MetricsQuery — the shapes the+# product persists today. Used to hide metric alert data from tokens lacking the metrics scope.+METRICS_INSIGHT_QUERY_FILTER = models.Q(insight__query__kind="MetricsQuery") | models.Q(+ insight__query__source__kind="MetricsQuery"+)+class InvestigationStatus(models.TextChoices):PENDING = "pending", "pending"diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex 52f0d9106236..29c8c61b93e9 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -4,7 +4,7 @@ from typing import Annotated, Any, castfrom zoneinfo import ZoneInfofrom django.db import transaction-from django.db.models import OuterRef, Prefetch, Q, QuerySet, Subquery+from django.db.models import OuterRef, Prefetch, QuerySet, Subqueryfrom django.utils import timezoneimport pydantic@@ -108,7 +108,13 @@ from products.alerts.backend.insight_alert_state_machine import (apply_threshold_change,apply_unsnooze,)-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, AlertSubscription, Threshold+from products.alerts.backend.models.alert import (+ METRICS_INSIGHT_QUERY_FILTER,+ AlertCheck,+ AlertConfiguration,+ AlertSubscription,+ Threshold,+)from products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,@@ -369,11 +375,6 @@ def _enforce_alert_feature_flags(context: dict[str, Any], insight: Insight) -> Nraise ValidationError("Metrics insight alerts are not enabled for your account.")-# Matches insights whose (bare or one-level-wrapped) query is a MetricsQuery — the shapes the-# product persists today. Used to hide metric alert data from tokens lacking the metrics scope.-_METRICS_INSIGHT_QUERY_FILTER = Q(insight__query__kind="MetricsQuery") | Q(insight__query__source__kind="MetricsQuery")--def _token_lacks_metrics_scope(request) -> bool:# Session auth (no token scopes) is exempt: those users are gated by team membership and# insight viewer access instead.@@ -1534,7 +1535,7 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# filter-then-exclude-by-id rather than exclude(Q) — NOT over a JSON path is three-valued,# so a plain exclude also drops rows whose query lacks the key entirely.if _token_lacks_metrics_scope(self.request):- queryset = queryset.exclude(id__in=queryset.filter(_METRICS_INSIGHT_QUERY_FILTER).values("id"))+ queryset = queryset.exclude(id__in=queryset.filter(METRICS_INSIGHT_QUERY_FILTER).values("id"))latest_check = AlertCheck.objects.filter(alert_configuration=OuterRef("pk")).order_by("-created_at")queryset = queryset.annotate(last_value=Subquery(latest_check.values("calculated_value")[:1]))@@ -1904,5 +1905,5 @@ class ThresholdViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):# Thresholds embed full alerts (including check values), so they get the same read-side# metrics scope gate as the alerts endpoints. Same null-safe filter-then-exclude shape.if _token_lacks_metrics_scope(self.request):- queryset = queryset.exclude(id__in=queryset.filter(_METRICS_INSIGHT_QUERY_FILTER).values("id"))+ queryset = queryset.exclude(id__in=queryset.filter(METRICS_INSIGHT_QUERY_FILTER).values("id"))return querysetdiff --git a/products/alerts/backend/tests/test_facade.py b/products/alerts/backend/tests/test_facade.pynew file mode 100644index 000000000000..8d2397cec18e--- /dev/null+++ b/products/alerts/backend/tests/test_facade.py@@ -0,0 +1,124 @@+from datetime import UTC, datetime++import time_machine+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, Team+from posthog.schema_enums import AlertState++from products.access_control.backend.models.access_control import AccessControl+from products.alerts.backend.facade import api, contracts+from products.alerts.backend.models.alert import AlertConfiguration+from products.product_analytics.backend.facade.models import Insight+++@time_machine.travel("2026-10-14T12:00:00Z", tick=False)+class TestListFiringAlertsCreatedBy(BaseTest):+ def _alert(+ self, team: Team, insight_fields: dict[str, object], alert_fields: dict[str, object]+ ) -> AlertConfiguration:+ insight = Insight.objects.create(+ **{"team": team, "name": "Checkout funnel", "created_by": self.user, **insight_fields}+ )+ return AlertConfiguration.objects.create(+ **{+ "team": team,+ "insight": insight,+ "name": "Checkout conversion",+ "state": AlertState.FIRING,+ "enabled": True,+ "created_by": self.user,+ **alert_fields,+ }+ )++ def _firing(self, include_metrics_insights: bool = True) -> list[contracts.FiringAlert]:+ return api.list_firing_alerts_created_by(+ self.team, self.user, include_metrics_insights=include_metrics_insights, limit=10+ )++ @parameterized.expand(+ [+ ("a named insight", {}, "Checkout funnel"),+ ("an unnamed insight", {"name": None, "derived_name": "Pageview count"}, "Pageview count"),+ ]+ )+ def test_lists_a_firing_alert_you_created(+ self, _name: str, insight_fields: dict[str, object], insight_name: str+ ) -> None:+ alert = self._alert(self.team, insight_fields, {})++ assert self._firing() == [+ contracts.FiringAlert(+ id=alert.id,+ name="Checkout conversion",+ insight_name=insight_name,+ insight_short_id=alert.insight.short_id,+ )+ ]++ @parameterized.expand(+ [+ ("its snooze has ended", {}, {"snoozed_until": datetime(2026, 10, 13, tzinfo=UTC)}, True),+ ("it is snoozed", {}, {"snoozed_until": datetime(2026, 10, 15, tzinfo=UTC)}, False),+ ("it is not firing", {}, {"state": AlertState.NOT_FIRING}, False),+ ("it is disabled", {}, {"enabled": False}, False),+ ("its insight is deleted", {"deleted": True}, {}, False),+ ]+ )+ def test_lists_an_alert_only_while_it_fires(+ self, _name: str, insight_fields: dict[str, object], alert_fields: dict[str, object], listed: bool+ ) -> None:+ self._alert(self.team, insight_fields, alert_fields)++ assert len(self._firing()) == (1 if listed else 0)++ def test_lists_only_your_alerts_in_this_project(self) -> None:+ teammate = self._create_user("[email protected]")+ yours = self._alert(self.team, {"created_by": teammate}, {})+ self._alert(self.team, {}, {"created_by": teammate})+ self._alert(Team.objects.create(organization=self.organization, name="Other project"), {}, {})++ assert [alert.id for alert in self._firing()] == [yours.id]++ def test_leaves_out_an_alert_whose_insight_you_cannot_view(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ viewable = self._alert(self.team, {}, {})+ hidden = self._alert(self.team, {"created_by": self._create_user("[email protected]")}, {})+ AccessControl.objects.create(+ resource="insight", resource_id=hidden.insight.id, team=self.team, access_level="none"+ )+ AlertConfiguration.objects.filter(id=hidden.id).update(created_at=datetime(2026, 10, 14, 13, tzinfo=UTC))++ assert [+ alert.id+ for alert in api.list_firing_alerts_created_by(self.team, self.user, include_metrics_insights=True, limit=1)+ ] == [viewable.id]++ @parameterized.expand(+ [+ ("a metrics insight with the metrics scope", {"kind": "MetricsQuery"}, True, True),+ ("a metrics insight without it", {"kind": "MetricsQuery"}, False, False),+ (+ "a wrapped metrics insight without it",+ {"kind": "InsightVizNode", "source": {"kind": "MetricsQuery"}},+ False,+ False,+ ),+ ("an insight with no query kind without it", {"source": {}}, False, True),+ ]+ )+ def test_metrics_insight_alerts_need_the_metrics_scope(+ self, _name: str, query: dict[str, object], include_metrics_insights: bool, listed: bool+ ) -> None:+ self._alert(self.team, {"query": query}, {})++ assert len(self._firing(include_metrics_insights)) == (1 if listed else 0)diff --git a/products/today/backend/logic/highlight_sources/alerts.py b/products/today/backend/logic/highlight_sources/alerts.pynew file mode 100644index 000000000000..0ac4d9952510--- /dev/null+++ b/products/today/backend/logic/highlight_sources/alerts.py@@ -0,0 +1,37 @@+import re++from products.alerts.backend.facade.api import list_firing_alerts_created_by+from products.alerts.backend.facade.contracts import FiringAlert++from ...facade.enums import HighlightLabel+from ..highlight_rules import short+from ..highlight_types import Candidate, Context, Found, Source++ALERT_FIRING = "Alert ‘{alert}’ is firing"+UNNAMED_ALERT_FIRING = "An alert is firing"+ALERT_FIRING_DETAIL = "Insight ‘{insight}’"+++def find(context: Context) -> Found:+ alerts = list_firing_alerts_created_by(+ context.team, context.user, include_metrics_insights=context.allows("metrics:read"), limit=10+ )+ return Found(items=tuple(_candidate(alert) for alert in alerts))+++def _candidate(alert: FiringAlert) -> Candidate:+ name = re.sub(r"(?i)\s+alert$", "", short(alert.name))+ return Candidate(+ key=f"alert:{alert.id}",+ label=HighlightLabel.RISK,+ family="alerts",+ importance=0.85,+ relevance=1.0,+ title=ALERT_FIRING.format(alert=name) if name else UNNAMED_ALERT_FIRING,+ detail=ALERT_FIRING_DETAIL.format(insight=short(alert.insight_name or alert.insight_short_id)),+ url=f"/insights/{alert.insight_short_id}",+ ref=alert.insight_short_id,+ )+++SOURCE = Source(name="alerts", find=find, scopes=("alert:read",))diff --git a/products/today/backend/tests/test_highlight_alerts.py b/products/today/backend/tests/test_highlight_alerts.pynew file mode 100644index 000000000000..354d7056ca7a--- /dev/null+++ b/products/today/backend/tests/test_highlight_alerts.py@@ -0,0 +1,59 @@+import uuid+from datetime import date++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.alerts.backend.facade.contracts import FiringAlert+from products.today.backend.logic.highlight_registry import load_sources+from products.today.backend.logic.highlight_sources import alerts+from products.today.backend.logic.highlight_types import Context+++class TestAlerts(BaseTest):+ @parameterized.expand(+ [+ (+ "the kind word is cut from the alert name",+ "Checkout conversion alert",+ "Checkout funnel",+ "Alert ‘Checkout conversion’ is firing",+ "Insight ‘Checkout funnel’",+ ),+ ("an unnamed insight shows its id", "Signups", None, "Alert ‘Signups’ is firing", "Insight ‘abc123’"),+ ("an unnamed alert", "", "Checkout funnel", "An alert is firing", "Insight ‘Checkout funnel’"),+ ]+ )+ def test_each_firing_alert_is_one_risk_item(+ self, _name: str, alert_name: str, insight_name: str | None, title: str, detail: str+ ) -> None:+ alert = FiringAlert(id=uuid.uuid4(), name=alert_name, insight_name=insight_name, insight_short_id="abc123")+ registered = next(s for s in load_sources() if s.name == "alerts")++ with patch.object(alerts, "list_firing_alerts_created_by", return_value=[alert]):+ found = registered.find(Context(self.team, self.user, date(2026, 10, 13)))++ self.assertEqual(+ [(c.key, c.title, c.detail, c.url) for c in found.items],+ [(f"alert:{alert.id}", title, detail, "/insights/abc123")],+ )++ @parameterized.expand(+ [+ ("a session", None, True),+ ("a key with the metrics scope", frozenset({"alert:read", "metrics:read"}), True),+ ("a key without it", frozenset({"alert:read"}), False),+ ]+ )+ def test_metrics_insight_alerts_follow_the_metrics_scope(+ self, _name: str, scopes: frozenset[str] | None, include: bool+ ) -> None:+ listed = MagicMock(return_value=[])+ registered = next(s for s in load_sources() if s.name == "alerts")++ with patch.object(alerts, "list_firing_alerts_created_by", listed):+ registered.find(Context(self.team, self.user, date(2026, 10, 13), scopes))++ self.assertEqual(listed.call_args.kwargs["include_metrics_insights"], include)diff --git a/tach.toml b/tach.tomlindex 6ec2f3238bf1..4b0e9631667d 100644--- a/tach.toml+++ b/tach.toml@@ -1644,6 +1644,7 @@ depends_on = ["ee","posthog","products.access_control",+ "products.alerts","products.conversations","products.dashboards","products.product_analytics",