: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): report every alert destination's cutover bucket for both sources (#117400)
Jimmy Zhubedb9dabff3f
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex 780ba39a5e9c..67b910f0c9d9 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -78,3 +78,13 @@ class DestinationEligibility:hold_backs: tuple[DestinationHoldBack, ...]# The md5 of the function's code, so the same code can be recognized across functions and teams.code_hash: str+++@frozen+class BucketedDestination:+ """One alert destination function in a cutover bucket report."""++ team_id: int+ # None for a function bound to no single alert, which fires for several alerts of the team.+ alert_id: str | None+ eligibility: DestinationEligibilitydiff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pyindex a8ce838bc2e8..29819636c7c1 100644--- a/products/alerts/backend/facade/destinations.py+++ b/products/alerts/backend/facade/destinations.py@@ -7,7 +7,7 @@ objects stay inside the product.from __future__ import annotations-from collections.abc import Collection, Sequence+from collections.abc import Collection, Iterable, Iterator, Sequencefrom dataclasses import asdictfrom datetime import datetimefrom typing import Any, Final@@ -28,6 +28,7 @@ from products.alerts_platform.backend.facade.contracts import (from ..logic import (delivery_destinations,+ destination_bucket_report,destination_configs,destination_eligibility,destinations,@@ -245,3 +246,8 @@ def unbound_alert_destinations(*, team_id: int, allowed_event_ids: Collection[stdef bucket_for(eligibility: DestinationEligibility) -> DestinationBucket:"""The most restrictive bucket among a destination's hold-backs. No hold-back means stock."""return destination_eligibility.bucket_for(eligibility)+++def bucket_report_lines(team_alerts: Iterable[tuple[int, str]], *, allowed_event_ids: Collection[str]) -> Iterator[str]:+ """One line per destination of the given (team id, alert id) pairs, then the count per bucket and per reason."""+ return destination_bucket_report.bucket_report_lines(team_alerts, allowed_event_ids=allowed_event_ids)diff --git a/products/alerts/backend/logic/destination_bucket_report.py b/products/alerts/backend/logic/destination_bucket_report.pynew file mode 100644index 000000000000..e7ad86884fbf--- /dev/null+++ b/products/alerts/backend/logic/destination_bucket_report.py@@ -0,0 +1,64 @@+"""Every destination of a source's alerts, with the bucket each goes to at cutover."""++from __future__ import annotations++from collections import Counter+from collections.abc import Collection, Iterable, Iterator++from products.alerts.backend.facade.contracts import BucketedDestination+from products.alerts.backend.logic.destination_eligibility import (+ bucket_for,+ classify_destinations_by_alert,+ classify_unbound_alert_destinations,+)+from products.alerts.backend.models.alert import AlertConfiguration+++def bucketed_destinations(+ team_alerts: Iterable[tuple[int, str]], *, allowed_event_ids: Collection[str]+) -> Iterator[BucketedDestination]:+ """Per team, the destinations bound to no single alert, then each alert's own destinations."""+ alert_ids_by_team: dict[int, list[str]] = {}+ for team_id, alert_id in team_alerts:+ alert_ids_by_team.setdefault(team_id, []).append(alert_id)+ for team_id, alert_ids in alert_ids_by_team.items():+ unbound = classify_unbound_alert_destinations(team_id=team_id, allowed_event_ids=allowed_event_ids)+ for eligibility in unbound:+ yield BucketedDestination(team_id=team_id, alert_id=None, eligibility=eligibility)+ unbound_ids = {eligibility.hog_function_id for eligibility in unbound}+ by_alert = classify_destinations_by_alert(+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids+ )+ for alert_id, eligibilities in by_alert.items():+ for eligibility in eligibilities:+ # A function that excludes this alert also names its id, but it is unbound and reported once.+ if eligibility.hog_function_id not in unbound_ids:+ yield BucketedDestination(team_id=team_id, alert_id=alert_id, eligibility=eligibility)+++def enabled_insight_alerts(*, team_id: int | None = None) -> Iterator[tuple[int, str]]:+ alerts = AlertConfiguration.objects.filter(enabled=True).order_by("team_id", "created_at")+ if team_id is not None:+ alerts = alerts.filter(team_id=team_id)+ for alert_team_id, alert_id in alerts.values_list("team_id", "id").iterator():+ yield alert_team_id, str(alert_id)+++def bucket_report_lines(team_alerts: Iterable[tuple[int, str]], *, allowed_event_ids: Collection[str]) -> Iterator[str]:+ """One line per destination, then the count per bucket and per reason."""+ buckets: Counter[str] = Counter()+ reasons: Counter[str] = Counter()+ for destination in bucketed_destinations(team_alerts, allowed_event_ids=allowed_event_ids):+ eligibility = destination.eligibility+ bucket = bucket_for(eligibility)+ buckets[str(bucket)] += 1+ reasons.update(str(reason) for reason in eligibility.hold_backs)+ if destination.alert_id is None:+ reasons["unbound"] += 1+ yield (+ f"team={destination.team_id} alert={destination.alert_id or 'unbound'} "+ f"destination={eligibility.hog_function_id} template={eligibility.template_id} "+ f"bucket={bucket} code_hash={eligibility.code_hash} reasons={','.join(eligibility.hold_backs)}"+ )+ yield f"Destinations by bucket: {dict(buckets) or 'none'}"+ yield f"Hold-backs by reason: {dict(reasons) or 'none'}"diff --git a/products/alerts/backend/logic/destination_eligibility.py b/products/alerts/backend/logic/destination_eligibility.pyindex f5de8b796001..00d926d7884a 100644--- a/products/alerts/backend/logic/destination_eligibility.py+++ b/products/alerts/backend/logic/destination_eligibility.py@@ -16,7 +16,7 @@ later edit can still be customized.from __future__ import annotationsimport hashlib-from collections.abc import Collection+from collections.abc import Collection, Sequencefrom datetime import UTC, datetime, timedeltafrom typing import Any, Finalfrom uuid import UUID@@ -67,6 +67,9 @@ _BUCKET_BY_HOLD_BACK: Final = {_BUCKET_ORDER: Final = tuple(DestinationBucket)+# The alert-id match is an OR of JSON containment clauses, so a team's alerts are read in batches.+_ALERT_BATCH_SIZE: Final = 200+# Only these receive alert events. Any other function on the same event id reads captured events._RECEIVES_ALERT_EVENTS: Final = {"type": "internal_destination", "filters__source": "internal-events"}@@ -82,6 +85,44 @@ def classify_alert_destinations(.filter(**_RECEIVES_ALERT_EVENTS).order_by("created_at", "id"))+ return _classify(team_id, functions)+++def classify_destinations_by_alert(+ *, team_id: int, alert_ids: Sequence[str], allowed_event_ids: Collection[str]+) -> dict[str, tuple[DestinationEligibility, ...]]:+ """The destination functions of several alerts of one team, keyed by alert id."""+ by_alert: dict[str, list[DestinationEligibility]] = {alert_id: [] for alert_id in alert_ids}+ for start in range(0, len(alert_ids), _ALERT_BATCH_SIZE):+ batch = set(alert_ids[start : start + _ALERT_BATCH_SIZE])+ functions = list(+ owned_alert_destinations_qs(+ team_id=team_id, alert_ids=batch, allowed_event_ids=allowed_event_ids, known_templates_only=False+ )+ .filter(**_RECEIVES_ALERT_EVENTS)+ .order_by("created_at", "id")+ )+ for function, eligibility in zip(functions, _classify(team_id, functions)):+ for alert_id in _named_alert_ids(function.filters) & batch:+ by_alert[alert_id].append(eligibility)+ return {alert_id: tuple(eligibilities) for alert_id, eligibilities in by_alert.items()}+++def classify_unbound_alert_destinations(+ *, team_id: int, allowed_event_ids: Collection[str]+) -> tuple[DestinationEligibility, ...]:+ """Every unbound destination function of a team, with what native delivery cannot carry for each."""+ unbound_ids = unbound_alert_destinations(team_id=team_id, allowed_event_ids=allowed_event_ids)+ if not unbound_ids:+ return ()+ return _classify(+ team_id, list(HogFunction.objects.filter(team_id=team_id, id__in=unbound_ids).order_by("created_at", "id"))+ )+++def _classify(team_id: int, functions: list[HogFunction]) -> tuple[DestinationEligibility, ...]:+ if not functions:+ return ()first_revisions: dict[UUID, HogFunctionRevision] = {revision.hog_function_id: revisionfor revision in HogFunctionRevision.objects.for_team(team_id)@@ -128,6 +169,16 @@ def unbound_alert_destinations(*, team_id: int, allowed_event_ids: Collection[streturn tuple(function_id for function_id, filters in candidates if not _bound_to_one_alert(filters))+def _named_alert_ids(filters: Any) -> set[str]:+ # Matches `owned_alert_destinations_qs`, which reads an alert id under any operator.+ properties = filters.get("properties") if isinstance(filters, dict) else None+ return {+ prop["value"]+ for prop in properties or ()+ if isinstance(prop, dict) and prop.get("key") == "alert_id" and isinstance(prop.get("value"), str)+ }++def _bound_to_one_alert(filters: Any) -> bool:# Only an exact match on one alert id scopes a function to that alert. Any other operator,# such as `is_not`, still lets it fire for other alerts.diff --git a/products/alerts/backend/management/commands/report_insight_alert_destination_buckets.py b/products/alerts/backend/management/commands/report_insight_alert_destination_buckets.pynew file mode 100644index 000000000000..31a591253e7b--- /dev/null+++ b/products/alerts/backend/management/commands/report_insight_alert_destination_buckets.py@@ -0,0 +1,20 @@+from typing import Any++from django.core.management.base import BaseCommand++from products.alerts.backend.facade.contracts import INSIGHT_ALERT_EVENT_IDS+from products.alerts.backend.facade.destinations import bucket_report_lines+from products.alerts.backend.logic.destination_bucket_report import enabled_insight_alerts+++class Command(BaseCommand):+ help = "List every destination of an enabled insight alert with the bucket it goes to at cutover."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--team-id", type=int, default=None, help="Report one team only.")++ def handle(self, *args: Any, **options: Any) -> None:+ for line in bucket_report_lines(+ enabled_insight_alerts(team_id=options["team_id"]), allowed_event_ids=INSIGHT_ALERT_EVENT_IDS+ ):+ self.stdout.write(line)diff --git a/products/alerts/backend/test/test_destination_eligibility.py b/products/alerts/backend/test/test_destination_eligibility.pyindex 5bf66bc401b7..e377cc8a569d 100644--- a/products/alerts/backend/test/test_destination_eligibility.py+++ b/products/alerts/backend/test/test_destination_eligibility.py@@ -15,6 +15,7 @@ from products.alerts.backend.facade.destinations import (classify_alert_destinations,unbound_alert_destinations,)+from products.alerts.backend.logic.destination_bucket_report import bucketed_destinationsfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision@@ -316,6 +317,31 @@ class TestDestinationEligibility(APIBaseTest):excluding_one_alert.id,)+ def test_the_report_buckets_an_unbound_function_by_its_content_once_per_team(self) -> None:+ other_alert = "01936a2e-0000-7000-8000-0000000000dd"+ bound = self._function("template-slack", SLACK_INPUTS)+ self._function("template-slack", SLACK_INPUTS, alert_id=other_alert)+ team_wide = self._function("template-slack", SLACK_INPUTS, alert_id=None)+ self._edited(team_wide, hog="fetch('https://hooks.example.com/hook')")+ excluding_one_alert = self._function("template-slack", SLACK_INPUTS)+ HogFunction.objects.filter(pk=excluding_one_alert.pk).update(+ filters={+ **(excluding_one_alert.filters or {}),+ "properties": [{"key": "alert_id", "value": ALERT_ID, "operator": "is_not", "type": "event"}],+ }+ )++ report = list(+ bucketed_destinations([(self.team.id, ALERT_ID), (self.team.id, other_alert)], allowed_event_ids=[EVENT])+ )++ assert [(d.alert_id, d.eligibility.hog_function_id, bucket_for(d.eligibility)) for d in report[:3]] == [+ (None, team_wide.id, DestinationBucket.CODE),+ (None, excluding_one_alert.id, DestinationBucket.STOCK),+ (ALERT_ID, bound.id, DestinationBucket.STOCK),+ ]+ assert [d.alert_id for d in report] == [None, None, ALERT_ID, other_alert]+class TestBucketFor(SimpleTestCase):@parameterized.expand(diff --git a/products/logs/backend/destination_buckets.py b/products/logs/backend/destination_buckets.pynew file mode 100644index 000000000000..3d3b7cba7a33--- /dev/null+++ b/products/logs/backend/destination_buckets.py@@ -0,0 +1,15 @@+"""The logs alerts whose destinations the cutover bucket report reads."""++from __future__ import annotations++from collections.abc import Iterator++from products.logs.backend.models import LogsAlertConfiguration+++def enabled_logs_alerts(*, team_id: int | None = None) -> Iterator[tuple[int, str]]:+ alerts = LogsAlertConfiguration.objects.filter(enabled=True).order_by("team_id", "created_at")+ if team_id is not None:+ alerts = alerts.filter(team_id=team_id)+ for alert_team_id, alert_id in alerts.values_list("team_id", "id").iterator():+ yield alert_team_id, str(alert_id)diff --git a/products/logs/backend/destination_hold_backs.py b/products/logs/backend/destination_hold_backs.pydeleted file mode 100644index 51011cc46104..000000000000--- a/products/logs/backend/destination_hold_backs.py+++ /dev/null@@ -1,43 +0,0 @@-"""Logs alerts whose destinations native delivery cannot take over, and why."""--from __future__ import annotations--from collections.abc import Iterator-from uuid import UUID--from posthog.dataclasses import frozen--from products.alerts.backend.facade.contracts import DestinationEligibility-from products.alerts.backend.facade.destinations import classify_alert_destinations, unbound_alert_destinations-from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS-from products.logs.backend.models import LogsAlertConfiguration---@frozen-class HeldBackDestination:- team_id: int- alert_id: UUID- destination: DestinationEligibility---def held_back_destinations(*, team_id: int | None = None) -> Iterator[HeldBackDestination]:- """Every destination of an enabled logs alert that native delivery cannot send as it does today."""- alerts = LogsAlertConfiguration.objects.filter(enabled=True).order_by("team_id", "created_at")- if team_id is not None:- alerts = alerts.filter(team_id=team_id)- for alert in alerts.only("id", "team_id").iterator():- for destination in classify_alert_destinations(- team_id=alert.team_id, alert_id=str(alert.id), allowed_event_ids=LOGS_ALERT_EVENT_IDS- ):- if destination.hold_backs:- yield HeldBackDestination(team_id=alert.team_id, alert_id=alert.id, destination=destination)---def unbound_destinations(*, team_id: int | None = None) -> Iterator[tuple[int, UUID]]:- """Every enabled logs alert function bound to no single alert, as (team id, function id), for teams with an enabled alert."""- teams = LogsAlertConfiguration.objects.filter(enabled=True)- if team_id is not None:- teams = teams.filter(team_id=team_id)- for alert_team_id in teams.order_by("team_id").values_list("team_id", flat=True).distinct().iterator():- for function_id in unbound_alert_destinations(team_id=alert_team_id, allowed_event_ids=LOGS_ALERT_EVENT_IDS):- yield alert_team_id, function_iddiff --git a/products/logs/backend/management/commands/report_logs_alert_destination_buckets.py b/products/logs/backend/management/commands/report_logs_alert_destination_buckets.pynew file mode 100644index 000000000000..a8e16d5a16d8--- /dev/null+++ b/products/logs/backend/management/commands/report_logs_alert_destination_buckets.py@@ -0,0 +1,20 @@+from typing import Any++from django.core.management.base import BaseCommand++from products.alerts.backend.facade.destinations import bucket_report_lines+from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS+from products.logs.backend.destination_buckets import enabled_logs_alerts+++class Command(BaseCommand):+ help = "List every destination of an enabled logs alert with the bucket it goes to at cutover."++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--team-id", type=int, default=None, help="Report one team only.")++ def handle(self, *args: Any, **options: Any) -> None:+ for line in bucket_report_lines(+ enabled_logs_alerts(team_id=options["team_id"]), allowed_event_ids=LOGS_ALERT_EVENT_IDS+ ):+ self.stdout.write(line)diff --git a/products/logs/backend/management/commands/report_logs_alert_hold_backs.py b/products/logs/backend/management/commands/report_logs_alert_hold_backs.pydeleted file mode 100644index 0c96b359c725..000000000000--- a/products/logs/backend/management/commands/report_logs_alert_hold_backs.py+++ /dev/null@@ -1,33 +0,0 @@-from collections import Counter-from typing import Any--from django.core.management.base import BaseCommand--from products.alerts.backend.facade.destinations import bucket_for-from products.logs.backend.destination_hold_backs import held_back_destinations, unbound_destinations---class Command(BaseCommand):- help = "List the logs alert destinations that cutover holds back, with the reasons."-- def add_arguments(self, parser: Any) -> None:- parser.add_argument("--team-id", type=int, default=None, help="Report one team only.")-- def handle(self, *args: Any, **options: Any) -> None:- reasons: Counter[str] = Counter()- buckets: Counter[str] = Counter()- for held in held_back_destinations(team_id=options["team_id"]):- destination = held.destination- bucket = bucket_for(destination)- reasons.update(str(reason) for reason in destination.hold_backs)- buckets[str(bucket)] += 1- self.stdout.write(- f"team={held.team_id} alert={held.alert_id} destination={destination.hog_function_id} "- f"template={destination.template_id} bucket={bucket} code_hash={destination.code_hash} "- f"reasons={','.join(destination.hold_backs)}"- )- for team_id, function_id in unbound_destinations(team_id=options["team_id"]):- reasons["unbound"] += 1- self.stdout.write(f"team={team_id} destination={function_id} reasons=unbound")- self.stdout.write(f"Held back by bucket: {dict(buckets) or 'none'}")- self.stdout.write(f"Held back by reason: {dict(reasons) or 'none'}")