: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): classify alert destinations native delivery cannot take over (#116684)
Jimmy Zhu6994cc9552c3
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.pyindex ecb298c6b9d3..c024b47bbef6 100644--- a/products/alerts/backend/facade/contracts.py+++ b/products/alerts/backend/facade/contracts.py@@ -7,7 +7,11 @@ an insight alert means.from __future__ import annotations+from enum import StrEnumfrom typing import Final+from uuid import UUID++from posthog.dataclasses import frozenfrom products.alerts_platform.backend.facade.contracts import DestinationTypefrom products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT@@ -19,3 +23,38 @@ INSIGHT_ALERT_EVENT_IDS: Final[tuple[str, ...]] = (LEGACY_INSIGHT_ALERT_EVENT,)# Slack only, because `alert:write` is grantable to a sandboxed agent. A connected workspace is a# destination an admin chose, while every other transport takes a URL the caller supplies.INSIGHT_ALERT_DESTINATION_TYPES: Final[tuple[DestinationType, ...]] = (DestinationType.SLACK,)+++class DestinationHoldBack(StrEnum):+ """Why native delivery cannot send what an alert destination sends today."""++ UNRECOGNIZED_TEMPLATE = "unrecognized_template"+ CODE = "code"+ CUSTOM_INPUTS = "custom_inputs"+ FILTERS = "filters"+ MASKING = "masking"+ MAPPINGS = "mappings"+ MESSAGE = "message"+ WEBHOOK_BODY = "webhook_body"+ WEBHOOK_METHOD = "webhook_method"+ WEBHOOK_TEMPLATED_HEADER = "webhook_templated_header"+ # An added header native delivery cannot send, such as an invalid name or a control character.+ WEBHOOK_HEADERS = "webhook_headers"+ # Native delivery refuses the destination, such as a plain-HTTP webhook URL or an unknown+ # PagerDuty severity, so it would send nothing.+ REFUSED_ADDRESS = "refused_address"+ # Native delivery sends to the stored address as written and does not render a template in it.+ TEMPLATED_ADDRESS = "templated_address"+ # Native delivery does not sign requests, so a receiver that checks the signature rejects them.+ WEBHOOK_SIGNING = "webhook_signing"+ # Saved again after it was built, before edits were recorded, so what changed is unknown.+ UNTRACKED_EDIT = "untracked_edit"+++@frozen+class DestinationEligibility:+ """One alert destination function, and every reason native delivery cannot take it over."""++ hog_function_id: UUID+ template_id: str | None+ hold_backs: tuple[DestinationHoldBack, ...]diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pyindex 78c81644a044..d802494427df 100644--- a/products/alerts/backend/facade/destinations.py+++ b/products/alerts/backend/facade/destinations.py@@ -26,7 +26,14 @@ from products.alerts_platform.backend.facade.contracts import (OwnedAlertDestination,)-from ..logic import delivery_destinations, destination_configs, destinations, insight_alert_destinations+from ..logic import (+ delivery_destinations,+ destination_configs,+ destination_eligibility,+ destinations,+ insight_alert_destinations,+)+from .contracts import DestinationEligibilityALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0@@ -219,3 +226,17 @@ def list_delivery_destination_groups(return delivery_destinations.list_delivery_destination_groups(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)+++def classify_alert_destinations(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> tuple[DestinationEligibility, ...]:+ """Every destination function of one alert, with what native delivery cannot carry for each."""+ return destination_eligibility.classify_alert_destinations(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )+++def unbound_alert_destinations(*, team_id: int, allowed_event_ids: Collection[str]) -> tuple[UUID, ...]:+ """Enabled functions that take a source's alert events without being bound to one alert."""+ return destination_eligibility.unbound_alert_destinations(team_id=team_id, allowed_event_ids=allowed_event_ids)diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.pyindex 384d2d3fdcdb..c30cb5531017 100644--- a/products/alerts/backend/logic/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -132,7 +132,7 @@ _HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")_CONTROL_CHARACTER = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]")-def _added_webhook_headers(headers: Any) -> dict[str, str]:+def added_webhook_headers(headers: Any) -> dict[str, str]:"""The headers a user added to a webhook destination, such as an auth token.A value with a `{` is a Hog template, which only the HogFunction path can render. Sending it@@ -165,7 +165,7 @@ def _added_webhook_headers(headers: Any) -> dict[str, str]:return dict(sorted(added.items()))-def _input_value(inputs: dict[str, Any], key: str) -> Any:+def input_value(inputs: dict[str, Any], key: str) -> Any:entry = inputs.get(key)return entry.get("value") if isinstance(entry, dict) else None@@ -177,6 +177,8 @@ class DestinationSpec(ABC):type: ClassVar[DestinationType]template_id: ClassVar[str]required_fields: ClassVar[tuple[str, ...]]+ # The inputs that say where a destination sends. Native delivery reads them.+ address_input_keys: ClassVar[frozenset[str]]def validate(self, data: AlertDestinationData) -> None:"""Raise `AlertDestinationValidationError` when the payload cannot become a destination of this type."""@@ -220,6 +222,7 @@ class DestinationSpec(ABC):class SlackDestination(DestinationSpec):type = DestinationType.SLACKtemplate_id = "template-slack"+ address_input_keys = frozenset({"slack_workspace", "channel"})required_fields = ("slack_workspace_id", "slack_channel_id")def build_name(self, data: AlertDestinationData) -> str:@@ -241,8 +244,8 @@ class SlackDestination(DestinationSpec):def read(self, inputs: dict[str, Any]) -> AlertDestinationData:data: AlertDestinationData = {"type": self.type}- slack_workspace_id = _input_value(inputs, "slack_workspace")- slack_channel_id = _input_value(inputs, "channel")+ slack_workspace_id = input_value(inputs, "slack_workspace")+ slack_channel_id = input_value(inputs, "channel")if isinstance(slack_workspace_id, int):data["slack_workspace_id"] = slack_workspace_idif isinstance(slack_channel_id, str):@@ -258,7 +261,7 @@ class _WebhookUrlDestination(DestinationSpec):def read(self, inputs: dict[str, Any]) -> AlertDestinationData:data: AlertDestinationData = {"type": self.type}- webhook_url = _input_value(inputs, self.url_input_key)+ webhook_url = input_value(inputs, self.url_input_key)if isinstance(webhook_url, str):data["webhook_url"] = webhook_urlreturn data@@ -276,10 +279,11 @@ class WebhookDestination(_WebhookUrlDestination):type = DestinationType.WEBHOOKtemplate_id = "template-webhook"url_input_key = "url"+ address_input_keys = frozenset({"url"})def read(self, inputs: dict[str, Any]) -> AlertDestinationData:data = super().read(inputs)- headers = _added_webhook_headers(_input_value(inputs, "headers"))+ headers = added_webhook_headers(input_value(inputs, "headers"))if headers:data["webhook_headers"] = headersreturn data@@ -311,6 +315,7 @@ class DiscordDestination(_WebhookUrlDestination):type = DestinationType.DISCORDtemplate_id = "template-discord"url_input_key = "webhookUrl"+ address_input_keys = frozenset({"webhookUrl"})def build_name(self, data: AlertDestinationData) -> str:return "Discord"@@ -332,6 +337,7 @@ class TeamsDestination(_WebhookUrlDestination):type = DestinationType.TEAMStemplate_id = "template-microsoft-teams"url_input_key = "webhookUrl"+ address_input_keys = frozenset({"webhookUrl"})def build_name(self, data: AlertDestinationData) -> str:return "Microsoft Teams"@@ -355,6 +361,7 @@ class PagerDutyDestination(DestinationSpec):type = DestinationType.PAGERDUTYtemplate_id = "template-pagerduty"+ address_input_keys = frozenset({"routing_key", "severity", "region"})required_fields = ("pagerduty_routing_key",)def validate(self, data: AlertDestinationData) -> None:@@ -404,14 +411,14 @@ class PagerDutyDestination(DestinationSpec):def read(self, inputs: dict[str, Any]) -> AlertDestinationData:data: AlertDestinationData = {"type": self.type}- routing_key = _input_value(inputs, "routing_key")+ routing_key = input_value(inputs, "routing_key")# Without the key two PagerDuty destinations cannot be told apart, so a config that# lacks it reads as unreadable rather than as "the same as every other one".if not isinstance(routing_key, str) or not routing_key:return datadata["pagerduty_routing_key"] = routing_key- severity = _input_value(inputs, "severity")- region = _input_value(inputs, "region")+ severity = input_value(inputs, "severity")+ region = input_value(inputs, "region")if isinstance(severity, str):data["pagerduty_severity"] = severityif isinstance(region, str):diff --git a/products/alerts/backend/logic/destination_eligibility.py b/products/alerts/backend/logic/destination_eligibility.pynew file mode 100644index 000000000000..2fb6834e89c6--- /dev/null+++ b/products/alerts/backend/logic/destination_eligibility.py@@ -0,0 +1,216 @@+"""Which alert destinations native delivery can take over without changing what they send.++A destination is a HogFunction a person can edit. Native delivery reads only where a destination+sends, so an edit to what it sends would be dropped silently at cutover. This finds those edits.++An edit is found by comparing a function with the first snapshot of its content, which the+HogFunction API writes on the first change it records. A template's stock text changes over time,+so comparing with what the code builds today would read an old, unedited function as edited.++The first snapshot is the stock content only when the function was created with stock inputs. The+logs alert API creates every logs destination that way. The HogFunction editor that insight alerts+use lets a person change the message before the first save, so for insight a function without a+later edit can still be customized.+"""++from __future__ import annotations++from collections.abc import Collection+from datetime import UTC, datetime, timedelta+from typing import Any, Final+from uuid import UUID++from products.alerts.backend.facade.contracts import DestinationEligibility, DestinationHoldBack+from products.alerts.backend.logic.destination_configs import (+ SPEC_BY_TEMPLATE_ID,+ WEBHOOK_HEADERS,+ WebhookDestination,+ added_webhook_headers,+ input_value,+)+from products.alerts.backend.logic.destinations import _allowed_event_filter, owned_alert_destinations_qs+from products.alerts_platform.backend.facade.delivery import refused_destination+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision++# The HogFunction API records edits from this date. A function built earlier and saved again has+# no record of what changed.+EDIT_TRACKING_STARTED: Final = datetime(2026, 8, 4, tzinfo=UTC)+# A function is saved in the moments after it is built. A later save means a person changed it.+RESAVED_AFTER: Final = timedelta(seconds=60)++_WEBHOOK_INPUT_HOLD_BACKS: Final = {+ "body": DestinationHoldBack.WEBHOOK_BODY,+ "method": DestinationHoldBack.WEBHOOK_METHOD,+}++_DERIVED_FILTER_KEYS: Final = ("bytecode", "bytecode_error", "bytecode_contract", "transpiled")+++# 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"}+++def classify_alert_destinations(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> tuple[DestinationEligibility, ...]:+ """Every destination function of one alert, with what native delivery cannot carry for each."""+ functions = list(+ owned_alert_destinations_qs(+ team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids, known_templates_only=False+ )+ .filter(**_RECEIVES_ALERT_EVENTS)+ .order_by("created_at", "id")+ )+ first_revisions: dict[UUID, HogFunctionRevision] = {+ revision.hog_function_id: revision+ for revision in HogFunctionRevision.objects.for_team(team_id)+ .filter(hog_function_id__in=[function.id for function in functions])+ .order_by("hog_function_id", "version")+ .distinct("hog_function_id")+ .only("hog_function_id", "content", "created_at")+ }+ return tuple(+ DestinationEligibility(+ hog_function_id=function.id,+ template_id=function.template_id,+ hold_backs=_hold_backs(function, first_revisions.get(function.id)),+ )+ for function in functions+ )+++def unbound_alert_destinations(*, team_id: int, allowed_event_ids: Collection[str]) -> tuple[UUID, ...]:+ """Enabled functions that take a source's alert events without being bound to one alert.++ Such a function fires for many alerts of the team. Native delivery reads destinations per+ alert, so it would stop sending at cutover. A function bound to a deleted alert receives+ nothing, so it is not unbound.+ """+ candidates = (+ HogFunction.objects.filter(+ _allowed_event_filter(allowed_event_ids),+ team_id=team_id,+ deleted=False,+ enabled=True,+ **_RECEIVES_ALERT_EVENTS,+ )+ .order_by("created_at", "id")+ .values_list("id", "filters")+ )+ return tuple(function_id for function_id, filters in candidates if not _bound_to_one_alert(filters))+++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.+ properties = filters.get("properties") if isinstance(filters, dict) else None+ return any(+ isinstance(prop, dict)+ and prop.get("key") == "alert_id"+ and prop.get("operator", "exact") == "exact"+ and isinstance(prop.get("value"), str)+ for prop in properties or ()+ )+++def _hold_backs(function: HogFunction, first_revision: HogFunctionRevision | None) -> tuple[DestinationHoldBack, ...]:+ template_id = function.template_id or ""+ spec = SPEC_BY_TEMPLATE_ID.get(template_id)+ if spec is None:+ return (DestinationHoldBack.UNRECOGNIZED_TEMPLATE,)++ found: list[DestinationHoldBack] = []+ if function.masking:+ found.append(DestinationHoldBack.MASKING)+ if function.mappings:+ found.append(DestinationHoldBack.MAPPINGS)+ # A secret input is not in `inputs` or in a snapshot, so it is read where it is stored.+ if template_id == WebhookDestination.template_id and input_value(function.encrypted_inputs or {}, "signing_secret"):+ found.append(DestinationHoldBack.WEBHOOK_SIGNING)+ # A secret address, such as a PagerDuty routing key, is stored in `encrypted_inputs`.+ stored_inputs = {**(function.inputs or {}), **(function.encrypted_inputs or {})}+ if any(_has_template(input_value(stored_inputs, key)) for key in spec.address_input_keys):+ found.append(DestinationHoldBack.TEMPLATED_ADDRESS)+ elif refused_destination(spec.read(stored_inputs)) is not None:+ found.append(DestinationHoldBack.REFUSED_ADDRESS)++ # The first revision holds the config as it stood at the first tracked edit, so an earlier+ # untracked save is already inside it and the snapshot is no stock baseline.+ last_untracked_save = function.updated_at if first_revision is None else first_revision.created_at+ if function.created_at < EDIT_TRACKING_STARTED and last_untracked_save - function.created_at > RESAVED_AFTER:+ found.append(DestinationHoldBack.UNTRACKED_EDIT)+ if first_revision is None:+ return tuple(found)++ first_snapshot = first_revision.content++ if function.hog != first_snapshot.get("hog"):+ found.append(DestinationHoldBack.CODE)+ if function.inputs_schema != first_snapshot.get("inputs_schema"):+ found.append(DestinationHoldBack.CUSTOM_INPUTS)+ if _without_derived(function.filters) != _without_derived(first_snapshot.get("filters")):+ found.append(DestinationHoldBack.FILTERS)+ found.extend(_input_hold_backs(template_id, function.inputs or {}, first_snapshot.get("inputs") or {}))+ # Ordered and unique, so a report reads the same for the same function.+ return tuple(dict.fromkeys(found))+++def _input_hold_backs(+ template_id: str, inputs: dict[str, Any], first_inputs: dict[str, Any]+) -> list[DestinationHoldBack]:+ found: list[DestinationHoldBack] = []+ is_webhook = template_id == WebhookDestination.template_id+ for key in sorted(set(inputs) | set(first_inputs)):+ if key in SPEC_BY_TEMPLATE_ID[template_id].address_input_keys:+ continue+ value, first_value = input_value(inputs, key), input_value(first_inputs, key)+ if is_webhook and key == "headers":+ # Native delivery sends the added headers that `added_webhook_headers` keeps, so only one+ # it drops changes what reaches the receiver.+ if value != first_value:+ dropped = _dropped_headers(value)+ if any(_has_template(header_value) for header_value in dropped.values()):+ found.append(DestinationHoldBack.WEBHOOK_TEMPLATED_HEADER)+ elif dropped:+ found.append(DestinationHoldBack.WEBHOOK_HEADERS)+ continue+ if value == first_value and _templating(inputs, key) == _templating(first_inputs, key):+ continue+ if is_webhook and key in _WEBHOOK_INPUT_HOLD_BACKS:+ found.append(_WEBHOOK_INPUT_HOLD_BACKS[key])+ else:+ found.append(DestinationHoldBack.MESSAGE)+ return found+++def _templating(inputs: dict[str, Any], key: str) -> Any:+ # The renderer follows this mode, so the same value renders differently under another one.+ entry = inputs.get(key)+ # The renderer reads an omitted mode as Hog, and the editor writes `hog` explicitly on save.+ templating = entry.get("templating") if isinstance(entry, dict) else None+ return templating or "hog"+++def _dropped_headers(headers: Any) -> dict[str, Any]:+ if not isinstance(headers, dict):+ return {}+ kept = {name.lower() for name in added_webhook_headers(headers)}+ owned = {name.lower() for name in WEBHOOK_HEADERS}+ return {+ name: value+ for name, value in headers.items()+ if not isinstance(name, str) or (name.strip().lower() not in kept and name.strip().lower() not in owned)+ }+++def _has_template(value: Any) -> bool:+ if isinstance(value, dict):+ return any(_has_template(item) for item in value.values())+ return isinstance(value, str) and "{" in value+++def _without_derived(filters: Any) -> Any:+ if not isinstance(filters, dict):+ return filters+ return {key: value for key, value in filters.items() if key not in _DERIVED_FILTER_KEYS}diff --git a/products/alerts/backend/logic/destinations.py b/products/alerts/backend/logic/destinations.pyindex 378e0ae4d875..bf4200c08a40 100644--- a/products/alerts/backend/logic/destinations.py+++ b/products/alerts/backend/logic/destinations.py@@ -139,18 +139,22 @@ def list_alert_destination_groups(def owned_alert_destinations_qs(- *, team_id: int, alert_ids: Collection[str], allowed_event_ids: Collection[str]+ *,+ team_id: int,+ alert_ids: Collection[str],+ allowed_event_ids: Collection[str],+ known_templates_only: bool = True,) -> QuerySet[HogFunction]:alert_id_filter = Q(pk__in=[])for alert_id in alert_ids:alert_id_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])- return HogFunction.objects.filter(+ functions = HogFunction.objects.filter(alert_id_filter,_allowed_event_filter(allowed_event_ids),team_id=team_id,deleted=False,- template_id__in=SPEC_BY_TEMPLATE_ID,)+ return functions.filter(template_id__in=SPEC_BY_TEMPLATE_ID) if known_templates_only else functionsdef list_owned_alert_destinations(@@ -421,7 +425,8 @@ def _allowed_event_filter(allowed_event_ids: Collection[str]) -> Q:event_filter = Q()for event_id in allowed_event_ids:- event_filter |= Q(filters__events__contains=[{"id": event_id, "type": "events"}])+ # `type` is optional in a stored filter, and the internal events consumer matches on the id alone.+ event_filter |= Q(filters__events__contains=[{"id": event_id}])return event_filterdiff --git a/products/alerts/backend/test/test_destination_eligibility.py b/products/alerts/backend/test/test_destination_eligibility.pynew file mode 100644index 000000000000..655d7f3ded71--- /dev/null+++ b/products/alerts/backend/test/test_destination_eligibility.py@@ -0,0 +1,278 @@+from datetime import UTC, datetime, timedelta+from typing import Any++from posthog.test.base import APIBaseTest++from parameterized import parameterized++from products.alerts.backend.facade.contracts import DestinationHoldBack+from products.alerts.backend.facade.destinations import classify_alert_destinations, unbound_alert_destinations+from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision++ALERT_ID = "01936a2e-0000-7000-8000-0000000000aa"+EVENT = "$logs_alert_firing"+WEBHOOK_INPUTS: dict[str, Any] = {+ "url": {"value": "https://hooks.example.com/hook"},+ "method": {"value": "POST"},+ "body": {"value": {"type": "logs_alert.firing"}},+ "headers": {"value": {"Content-Type": "application/json"}},+}+PAGERDUTY_INPUTS: dict[str, Any] = {+ "routing_key": {"value": "not-a-real-key"},+ "severity": {"value": "critical"},+ "region": {"value": "us"},+}+SLACK_INPUTS: dict[str, Any] = {+ "slack_workspace": {"value": 1},+ "channel": {"value": "C-1"},+ "text": {"value": "Log alert is firing"},+}+++def _with(inputs: dict[str, Any], key: str, value: Any) -> dict[str, Any]:+ return {**inputs, key: {"value": value}}+++class TestDestinationEligibility(APIBaseTest):+ def _function(+ self,+ template_id: str,+ inputs: dict[str, Any],+ secret_keys: frozenset[str] = frozenset(),+ alert_id: str | None = ALERT_ID,+ enabled: bool = True,+ **fields: Any,+ ) -> HogFunction:+ return HogFunction.objects.create(+ team=self.team,+ name="Alert destination",+ type="internal_destination",+ template_id=template_id,+ enabled=enabled,+ inputs=inputs,+ inputs_schema=[{"key": key, "type": "string", "secret": key in secret_keys} for key in inputs],+ hog="return event",+ filters={+ "source": "internal-events",+ "events": [{"id": EVENT, "type": "events"}],+ "properties": [{"key": "alert_id", "value": alert_id, "operator": "exact", "type": "event"}]+ if alert_id+ else [],+ },+ **fields,+ )++ def _classify(self) -> tuple[DestinationHoldBack, ...]:+ (eligibility,) = classify_alert_destinations(team_id=self.team.id, alert_id=ALERT_ID, allowed_event_ids=[EVENT])+ return eligibility.hold_backs++ def _edited(self, function: HogFunction, **changes: Any) -> None:+ HogFunctionRevision.objects.for_team(self.team.id).create(+ team=self.team,+ hog_function=function,+ version=1,+ content={+ "hog": function.hog,+ "inputs_schema": function.inputs_schema,+ "inputs": function.inputs,+ "filters": function.filters,+ "mappings": function.mappings,+ "masking": function.masking,+ },+ )+ HogFunction.objects.filter(pk=function.pk).update(version=2, **changes)++ @parameterized.expand(+ [+ ("a_moved_channel_is_still_native", "template-slack", SLACK_INPUTS, "channel", "C-2", ()),+ (+ "rewritten_slack_text",+ "template-slack",+ SLACK_INPUTS,+ "text",+ "<!here> it broke",+ (DestinationHoldBack.MESSAGE,),+ ),+ (+ "rewritten_webhook_body",+ "template-webhook",+ WEBHOOK_INPUTS,+ "body",+ {"text": "relay"},+ (DestinationHoldBack.WEBHOOK_BODY,),+ ),+ (+ "an_added_plain_auth_header_is_still_native",+ "template-webhook",+ WEBHOOK_INPUTS,+ "headers",+ {"Content-Type": "application/json", "Authorization": "Bearer not-a-real-token"},+ (),+ ),+ (+ "an_added_header_native_delivery_cannot_send",+ "template-webhook",+ WEBHOOK_INPUTS,+ "headers",+ {"Content-Type": "application/json", "X Bad": "ok"},+ (DestinationHoldBack.WEBHOOK_HEADERS,),+ ),+ ("slack_text_saved_with_the_default_mode", "template-slack", SLACK_INPUTS, "text", "hog", ()),+ (+ "slack_text_moved_to_liquid",+ "template-slack",+ SLACK_INPUTS,+ "text",+ None,+ (DestinationHoldBack.MESSAGE,),+ ),+ (+ "an_added_templated_header",+ "template-webhook",+ WEBHOOK_INPUTS,+ "headers",+ {"Authorization": "Bearer {inputs.token}"},+ (DestinationHoldBack.WEBHOOK_TEMPLATED_HEADER,),+ ),+ ]+ )+ def test_an_input_edit_holds_back_only_what_native_delivery_drops(+ self,+ _name: str,+ template_id: str,+ inputs: dict[str, Any],+ key: str,+ value: Any,+ expected: tuple[DestinationHoldBack, ...],+ ) -> None:+ function = self._function(template_id, inputs)+ if value is None:+ edited = {**inputs, key: {**inputs[key], "templating": "liquid"}}+ elif value == "hog":+ edited = {**inputs, key: {**inputs[key], "templating": "hog"}}+ else:+ edited = _with(inputs, key, value)+ self._edited(function, inputs=edited)++ assert self._classify() == expected++ @parameterized.expand(+ [+ ("edited_code", {"hog": "fetch(inputs.url, {'body': 'mine'})"}, (DestinationHoldBack.CODE,)),+ (+ "masking",+ {"masking": {"ttl": 3600, "hash": "{event.properties.alert_id}"}},+ (DestinationHoldBack.MASKING,),+ ),+ ]+ )+ def test_a_function_edit_holds_it_back(+ self, _name: str, changes: dict[str, Any], expected: tuple[DestinationHoldBack, ...]+ ) -> None:+ self._edited(self._function("template-webhook", WEBHOOK_INPUTS), **changes)++ assert self._classify() == expected++ @parameterized.expand(+ [+ ("built_before_tracking_and_saved_again", datetime(2026, 7, 1, tzinfo=UTC), timedelta(days=3), True),+ (+ "built_before_tracking_and_never_saved_again",+ datetime(2026, 7, 1, tzinfo=UTC),+ timedelta(seconds=1),+ False,+ ),+ ("built_after_tracking_without_an_edit", datetime(2026, 9, 1, tzinfo=UTC), timedelta(days=3), False),+ ]+ )+ def test_an_edit_from_before_edits_were_recorded_holds_it_back(+ self, _name: str, created_at: datetime, saved_after: timedelta, held_back: bool+ ) -> None:+ function = self._function("template-webhook", WEBHOOK_INPUTS)+ HogFunction.objects.filter(pk=function.pk).update(created_at=created_at, updated_at=created_at + saved_after)++ assert self._classify() == ((DestinationHoldBack.UNTRACKED_EDIT,) if held_back else ())++ @parameterized.expand(+ [+ ("webhook_url", "template-webhook", WEBHOOK_INPUTS, "url", frozenset()),+ (+ "secret_pagerduty_routing_key",+ "template-pagerduty",+ {"routing_key": {"value": "key"}, "severity": {"value": "critical"}},+ "routing_key",+ frozenset({"routing_key"}),+ ),+ ]+ )+ def test_a_templated_address_is_held_back(+ self, _name: str, template_id: str, inputs: dict[str, Any], key: str, secret_keys: frozenset[str]+ ) -> None:+ self._function(template_id, _with(inputs, key, "{event.properties.alert_id}"), secret_keys=secret_keys)++ assert self._classify() == (DestinationHoldBack.TEMPLATED_ADDRESS,)++ def test_a_revision_taken_long_after_an_untracked_build_is_no_baseline(self) -> None:+ function = self._function("template-slack", SLACK_INPUTS)+ HogFunction.objects.filter(pk=function.pk).update(created_at=datetime(2026, 7, 1, tzinfo=UTC))+ function.refresh_from_db()+ self._edited(function, inputs=_with(SLACK_INPUTS, "channel", "C-2"))++ assert self._classify() == (DestinationHoldBack.UNTRACKED_EDIT,)++ @parameterized.expand(+ [+ ("plain_http", "template-webhook", _with(WEBHOOK_INPUTS, "url", "http://hooks.example.com/hook")),+ ("malformed", "template-webhook", _with(WEBHOOK_INPUTS, "url", "https://[invalid/hook")),+ ("unknown_severity", "template-pagerduty", {**PAGERDUTY_INPUTS, "severity": {"value": "urgent"}}),+ ("unknown_region", "template-pagerduty", {**PAGERDUTY_INPUTS, "region": {"value": "apac"}}),+ ]+ )+ def test_a_destination_native_delivery_refuses_is_held_back(+ self, _name: str, template_id: str, inputs: dict[str, Any]+ ) -> None:+ self._function(template_id, inputs)++ assert self._classify() == (DestinationHoldBack.REFUSED_ADDRESS,)++ def test_a_signed_webhook_is_held_back(self) -> None:+ self._function(+ "template-webhook",+ {**WEBHOOK_INPUTS, "signing_secret": {"value": "whsec_not-a-real-secret"}},+ secret_keys=frozenset({"signing_secret"}),+ )++ assert self._classify() == (DestinationHoldBack.WEBHOOK_SIGNING,)++ def test_a_template_native_delivery_does_not_know_is_held_back(self) -> None:+ self._function("template-some-custom-sink", {"url": {"value": "https://hooks.example.com/hook"}})+ reads_captured_events = self._function("template-some-custom-sink", {})+ HogFunction.objects.filter(pk=reads_captured_events.pk).update(type="destination")++ assert self._classify() == (DestinationHoldBack.UNRECOGNIZED_TEMPLATE,)++ def test_a_function_no_alert_owns_is_unbound(self) -> None:+ self._function("template-slack", SLACK_INPUTS)+ team_wide = self._function("template-slack", SLACK_INPUTS, alert_id=None)+ self._function("template-slack", SLACK_INPUTS, alert_id=None, enabled=False)+ untyped_event = self._function("template-slack", SLACK_INPUTS, alert_id=None)+ HogFunction.objects.filter(pk=untyped_event.pk).update(+ filters={**(untyped_event.filters or {}), "events": [{"id": EVENT}]}+ )+ captured_events = self._function("template-slack", SLACK_INPUTS, alert_id=None)+ HogFunction.objects.filter(pk=captured_events.pk).update(type="destination")+ self._function("template-slack", SLACK_INPUTS, alert_id="01936a2e-0000-7000-8000-0000000000dd")+ 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"}],+ }+ )++ assert unbound_alert_destinations(team_id=self.team.id, allowed_event_ids=[EVENT]) == (+ team_wide.id,+ untyped_event.id,+ excluding_one_alert.id,+ )diff --git a/products/alerts_platform/backend/delivery/addresses.py b/products/alerts_platform/backend/delivery/addresses.pynew file mode 100644index 000000000000..f20551c52b72--- /dev/null+++ b/products/alerts_platform/backend/delivery/addresses.py@@ -0,0 +1,46 @@+"""Whether native delivery would send to a stored destination, without loading the delivery runtime."""++from __future__ import annotations++from typing import Final++from products.alerts_platform.backend.delivery.discord import DiscordTransport+from products.alerts_platform.backend.delivery.teams import TeamsTransport+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.delivery.webhook import WebhookTransport+from products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport+from products.alerts_platform.backend.facade.contracts import (+ DEFAULT_PAGERDUTY_REGION,+ DEFAULT_PAGERDUTY_SEVERITY,+ AlertDestinationData,+ DestinationType,+ PagerDutyRegion,+ PagerDutySeverity,+)++_URL_TRANSPORTS: Final[dict[DestinationType, type[WebhookUrlTransport]]] = {+ DestinationType.WEBHOOK: WebhookTransport,+ DestinationType.TEAMS: TeamsTransport,+ DestinationType.DISCORD: DiscordTransport,+}+++def refused_destination(data: AlertDestinationData) -> str | None:+ """Why native delivery would refuse to send to this destination, or None when it would send."""+ if data["type"] == DestinationType.PAGERDUTY:+ # The HogFunction template maps an unknown value to a default. Native delivery refuses it.+ try:+ PagerDutyRegion(data.get("pagerduty_region") or DEFAULT_PAGERDUTY_REGION)+ PagerDutySeverity(data.get("pagerduty_severity") or DEFAULT_PAGERDUTY_SEVERITY)+ except ValueError:+ return "This PagerDuty destination has an unknown region or severity."+ return None+ transport = _URL_TRANSPORTS.get(data["type"])+ url = data.get("webhook_url")+ if transport is None or not isinstance(url, str):+ return None+ try:+ transport().check_url(url)+ except DeliveryError as error:+ return str(error)+ return Nonediff --git a/products/alerts_platform/backend/delivery/webhook.py b/products/alerts_platform/backend/delivery/webhook.pyindex 59ae3bfde8c7..9947e2a77411 100644--- a/products/alerts_platform/backend/delivery/webhook.py+++ b/products/alerts_platform/backend/delivery/webhook.py@@ -112,7 +112,11 @@ class WebhookTransport(WebhookUrlTransport):def check_url(self, url: str) -> None:# Plain HTTP would expose the URL, which is the credential, and the alert body to anyone on# the path. Teams and Discord URLs are always HTTPS, so only the generic webhook needs this.- if urlsplit(url).scheme != "https":+ try:+ scheme = urlsplit(url).scheme+ except ValueError:+ raise DeliveryError("This webhook destination's URL is not a valid URL.") from None+ if scheme != "https":raise DeliveryError("This webhook destination's URL must use https.")def body_for(self, message: AlertMessage) -> dict[str, Any]:diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.pyindex a6ddb8af7369..8a891b0e0deb 100644--- a/products/alerts_platform/backend/facade/delivery.py+++ b/products/alerts_platform/backend/facade/delivery.py@@ -1,7 +1,8 @@"""Facade for native delivery: how other products plug in destinations and their own wording."""-from products.alerts_platform.backend.delivery import describers, destinations, legacy_webhook+from products.alerts_platform.backend.delivery import addresses, describers, destinations, legacy_webhookfrom products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,DestinationResolver,LegacyWebhookBody,SourceDescriber,@@ -17,5 +18,10 @@ def register_source_describer(source: SourceKind, describer: SourceDescriber) ->describers.register(source, describer)+def refused_destination(data: AlertDestinationData) -> str | None:+ """Why native delivery would refuse to send to this destination, or None when it would send."""+ return addresses.refused_destination(data)++def register_legacy_webhook_body(source: SourceKind, body: LegacyWebhookBody) -> None:legacy_webhook.register(source, body)diff --git a/products/logs/backend/alert_destinations.py b/products/logs/backend/alert_destinations.pyindex 21741c333a49..ff56a4a3450d 100644--- a/products/logs/backend/alert_destinations.py+++ b/products/logs/backend/alert_destinations.py@@ -161,6 +161,7 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {}EVENT_KINDS: tuple[EventKind, ...] = tuple(EVENT_KIND_CONFIG.keys())+LOGS_ALERT_EVENT_IDS: tuple[str, ...] = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())_SEVERITY_SERVICE_CONTEXT = ("{if(length(event.properties.severity_levels) > 0 or length(event.properties.service_names) > 0,"diff --git a/products/logs/backend/destination_hold_backs.py b/products/logs/backend/destination_hold_backs.pynew file mode 100644index 000000000000..51011cc46104--- /dev/null+++ b/products/logs/backend/destination_hold_backs.py@@ -0,0 +1,43 @@+"""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_hold_backs.py b/products/logs/backend/management/commands/report_logs_alert_hold_backs.pynew file mode 100644index 000000000000..60e463fea0ef--- /dev/null+++ b/products/logs/backend/management/commands/report_logs_alert_hold_backs.py@@ -0,0 +1,27 @@+from collections import Counter+from typing import Any++from django.core.management.base import BaseCommand++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()+ for held in held_back_destinations(team_id=options["team_id"]):+ hold_backs = held.destination.hold_backs+ reasons.update(str(reason) for reason in hold_backs)+ self.stdout.write(+ f"team={held.team_id} alert={held.alert_id} destination={held.destination.hog_function_id} "+ f"template={held.destination.template_id} reasons={','.join(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 reason: {dict(reasons) or 'none'}")diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex d289c4e48985..d920df88c46e 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -54,6 +54,7 @@ from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCoufrom products.logs.backend.alert_destinations import (EVENT_KIND_CONFIG,EVENT_KINDS,+ LOGS_ALERT_EVENT_IDS,LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,LOGS_DESTINATION_TYPES,)@@ -83,7 +84,6 @@ from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfigALLOWED_WINDOW_MINUTES = {5, 10, 15, 30, 60}MAX_ALERTS_PER_TEAM = 20-LOGS_ALERT_EVENT_IDS: Final = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())# Comma-separated team IDs that bypass MAX_ALERTS_PER_TEAM. Configured via# argocd for internal dogfood projects whose observability needs exceed the# customer-facing cap; the cap's correctness assumptions (bounded N+1 in list,