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): bucket each alert destination for cutover (#117392)

Jimmy Zhu3acaae4f6252
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index c024b47bbef6..780ba39a5e9c 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -28,13 +28,15 @@ INSIGHT_ALERT_DESTINATION_TYPES: Final[tuple[DestinationType, ...]] = (Destinati
class DestinationHoldBack(StrEnum):
"""Why native delivery cannot send what an alert destination sends today."""
- UNRECOGNIZED_TEMPLATE = "unrecognized_template"
+ NO_TEMPLATE = "no_template"
+ OTHER_TEMPLATE = "other_template"
CODE = "code"
CUSTOM_INPUTS = "custom_inputs"
FILTERS = "filters"
MASKING = "masking"
MAPPINGS = "mappings"
MESSAGE = "message"
+ MESSAGE_COSMETIC = "message_cosmetic"
WEBHOOK_BODY = "webhook_body"
WEBHOOK_METHOD = "webhook_method"
WEBHOOK_TEMPLATED_HEADER = "webhook_templated_header"
@@ -51,6 +53,22 @@ class DestinationHoldBack(StrEnum):
UNTRACKED_EDIT = "untracked_edit"
+class DestinationBucket(StrEnum):
+ """Where an alert destination goes at cutover, from its most restrictive hold-back.
+
+ Listed from the most to the least restrictive. `CODE` covers every edited-code bucket, because
+ which one applies depends on what the code does, which this classifier does not read.
+ """
+
+ REFUSED_ADDRESS = "R1"
+ CODE = "code"
+ PORTABLE = "W1"
+ COSMETIC = "C1"
+ TEMPLATED_HEADERS = "N2"
+ STATIC_HEADERS = "N1"
+ STOCK = "N0"
+
+
@frozen
class DestinationEligibility:
"""One alert destination function, and every reason native delivery cannot take it over."""
@@ -58,3 +76,5 @@ class DestinationEligibility:
hog_function_id: UUID
template_id: str | None
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
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index d802494427df..a8ce838bc2e8 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -33,7 +33,7 @@ from ..logic import (
destinations,
insight_alert_destinations,
)
-from .contracts import DestinationEligibility
+from .contracts import DestinationBucket, DestinationEligibility
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
@@ -240,3 +240,8 @@ def classify_alert_destinations(
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)
+
+
+def 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)
diff --git a/products/alerts/backend/logic/destination_eligibility.py b/products/alerts/backend/logic/destination_eligibility.py
index 2fb6834e89c6..f5de8b796001 100644
--- a/products/alerts/backend/logic/destination_eligibility.py
+++ b/products/alerts/backend/logic/destination_eligibility.py
@@ -15,15 +15,17 @@ later edit can still be customized.
from __future__ import annotations
+import hashlib
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.facade.contracts import DestinationBucket, DestinationEligibility, DestinationHoldBack
from products.alerts.backend.logic.destination_configs import (
SPEC_BY_TEMPLATE_ID,
WEBHOOK_HEADERS,
+ SlackDestination,
WebhookDestination,
added_webhook_headers,
input_value,
@@ -39,14 +41,32 @@ 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,
+# An edited input missing here changes the message.
+_INPUT_HOLD_BACKS: Final[dict[str, dict[str, DestinationHoldBack]]] = {
+ WebhookDestination.template_id: {
+ "body": DestinationHoldBack.WEBHOOK_BODY,
+ "method": DestinationHoldBack.WEBHOOK_METHOD,
+ },
+ SlackDestination.template_id: {
+ "icon_emoji": DestinationHoldBack.MESSAGE_COSMETIC,
+ "username": DestinationHoldBack.MESSAGE_COSMETIC,
+ },
}
_DERIVED_FILTER_KEYS: Final = ("bytecode", "bytecode_error", "bytecode_contract", "transpiled")
+_BUCKET_BY_HOLD_BACK: Final = {
+ DestinationHoldBack.REFUSED_ADDRESS: DestinationBucket.REFUSED_ADDRESS,
+ DestinationHoldBack.NO_TEMPLATE: DestinationBucket.CODE,
+ DestinationHoldBack.CODE: DestinationBucket.CODE,
+ DestinationHoldBack.MESSAGE_COSMETIC: DestinationBucket.COSMETIC,
+ DestinationHoldBack.WEBHOOK_TEMPLATED_HEADER: DestinationBucket.TEMPLATED_HEADERS,
+ DestinationHoldBack.WEBHOOK_HEADERS: DestinationBucket.STATIC_HEADERS,
+}
+_BUCKET_ORDER: Final = tuple(DestinationBucket)
+
+
# 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"}
@@ -75,11 +95,18 @@ def classify_alert_destinations(
hog_function_id=function.id,
template_id=function.template_id,
hold_backs=_hold_backs(function, first_revisions.get(function.id)),
+ code_hash=hashlib.md5((function.hog or "").encode(), usedforsecurity=False).hexdigest(),
)
for function in functions
)
+def bucket_for(eligibility: DestinationEligibility) -> DestinationBucket:
+ """The most restrictive bucket among a destination's hold-backs. No hold-back means stock."""
+ buckets = {_BUCKET_BY_HOLD_BACK.get(hold_back, DestinationBucket.PORTABLE) for hold_back in eligibility.hold_backs}
+ return min(buckets, key=_BUCKET_ORDER.index, default=DestinationBucket.STOCK)
+
+
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.
@@ -115,10 +142,13 @@ def _bound_to_one_alert(filters: Any) -> bool:
def _hold_backs(function: HogFunction, first_revision: HogFunctionRevision | None) -> tuple[DestinationHoldBack, ...]:
- template_id = function.template_id or ""
+ template_id = function.template_id
+ if not template_id:
+ return (DestinationHoldBack.NO_TEMPLATE,)
+ code_edited = first_revision is not None and function.hog != first_revision.content.get("hog")
spec = SPEC_BY_TEMPLATE_ID.get(template_id)
if spec is None:
- return (DestinationHoldBack.UNRECOGNIZED_TEMPLATE,)
+ return (DestinationHoldBack.OTHER_TEMPLATE, *((DestinationHoldBack.CODE,) if code_edited else ()))
found: list[DestinationHoldBack] = []
if function.masking:
@@ -145,7 +175,7 @@ def _hold_backs(function: HogFunction, first_revision: HogFunctionRevision | Non
first_snapshot = first_revision.content
- if function.hog != first_snapshot.get("hog"):
+ if code_edited:
found.append(DestinationHoldBack.CODE)
if function.inputs_schema != first_snapshot.get("inputs_schema"):
found.append(DestinationHoldBack.CUSTOM_INPUTS)
@@ -177,10 +207,7 @@ def _input_hold_backs(
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)
+ found.append(_INPUT_HOLD_BACKS.get(template_id, {}).get(key, DestinationHoldBack.MESSAGE))
return found
diff --git a/products/alerts/backend/test/test_destination_eligibility.py b/products/alerts/backend/test/test_destination_eligibility.py
index 655d7f3ded71..5bf66bc401b7 100644
--- a/products/alerts/backend/test/test_destination_eligibility.py
+++ b/products/alerts/backend/test/test_destination_eligibility.py
@@ -1,12 +1,20 @@
+import hashlib
from datetime import UTC, datetime, timedelta
from typing import Any
+from uuid import UUID
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
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.alerts.backend.facade.contracts import DestinationBucket, DestinationEligibility, DestinationHoldBack
+from products.alerts.backend.facade.destinations import (
+ bucket_for,
+ 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
@@ -63,9 +71,12 @@ class TestDestinationEligibility(APIBaseTest):
**fields,
)
- def _classify(self) -> tuple[DestinationHoldBack, ...]:
+ def _eligibility(self) -> DestinationEligibility:
(eligibility,) = classify_alert_destinations(team_id=self.team.id, alert_id=ALERT_ID, allowed_event_ids=[EVENT])
- return eligibility.hold_backs
+ return eligibility
+
+ def _classify(self) -> tuple[DestinationHoldBack, ...]:
+ return self._eligibility().hold_backs
def _edited(self, function: HogFunction, **changes: Any) -> None:
HogFunctionRevision.objects.for_team(self.team.id).create(
@@ -118,6 +129,14 @@ class TestDestinationEligibility(APIBaseTest):
{"Content-Type": "application/json", "X Bad": "ok"},
(DestinationHoldBack.WEBHOOK_HEADERS,),
),
+ (
+ "slack_bot_emoji",
+ "template-slack",
+ SLACK_INPUTS,
+ "icon_emoji",
+ ":rotating_light:",
+ (DestinationHoldBack.MESSAGE_COSMETIC,),
+ ),
("slack_text_saved_with_the_default_mode", "template-slack", SLACK_INPUTS, "text", "hog", ()),
(
"slack_text_moved_to_liquid",
@@ -172,7 +191,11 @@ class TestDestinationEligibility(APIBaseTest):
) -> None:
self._edited(self._function("template-webhook", WEBHOOK_INPUTS), **changes)
- assert self._classify() == expected
+ eligibility = self._eligibility()
+ assert eligibility.hold_backs == expected
+ # The code-family registry is keyed by the md5 of the code as it runs now.
+ current_hog = changes.get("hog", "return event")
+ assert eligibility.code_hash == hashlib.md5(current_hog.encode(), usedforsecurity=False).hexdigest()
@parameterized.expand(
[
@@ -245,12 +268,28 @@ class TestDestinationEligibility(APIBaseTest):
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", {})
+ @parameterized.expand(
+ [
+ ("other_template", "template-some-custom-sink", None, (DestinationHoldBack.OTHER_TEMPLATE,)),
+ (
+ "other_template_with_edited_code",
+ "template-some-custom-sink",
+ "fetch('https://hooks.example.com/hook')",
+ (DestinationHoldBack.OTHER_TEMPLATE, DestinationHoldBack.CODE),
+ ),
+ ("no_template", "", None, (DestinationHoldBack.NO_TEMPLATE,)),
+ ]
+ )
+ def test_a_template_native_delivery_does_not_know_is_held_back(
+ self, _name: str, template_id: str, edited_hog: str | None, expected: tuple[DestinationHoldBack, ...]
+ ) -> None:
+ function = self._function(template_id, {"url": {"value": "https://hooks.example.com/hook"}})
+ if edited_hog is not None:
+ self._edited(function, hog=edited_hog)
+ reads_captured_events = self._function(template_id, {})
HogFunction.objects.filter(pk=reads_captured_events.pk).update(type="destination")
- assert self._classify() == (DestinationHoldBack.UNRECOGNIZED_TEMPLATE,)
+ assert self._classify() == expected
def test_a_function_no_alert_owns_is_unbound(self) -> None:
self._function("template-slack", SLACK_INPUTS)
@@ -276,3 +315,39 @@ class TestDestinationEligibility(APIBaseTest):
untyped_event.id,
excluding_one_alert.id,
)
+
+
+class TestBucketFor(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("stock", (), DestinationBucket.STOCK),
+ ("other_template", (DestinationHoldBack.OTHER_TEMPLATE,), DestinationBucket.PORTABLE),
+ ("no_template", (DestinationHoldBack.NO_TEMPLATE,), DestinationBucket.CODE),
+ (
+ "refused_address_over_code",
+ (DestinationHoldBack.CODE, DestinationHoldBack.REFUSED_ADDRESS),
+ DestinationBucket.REFUSED_ADDRESS,
+ ),
+ ("code_over_message", (DestinationHoldBack.MESSAGE, DestinationHoldBack.CODE), DestinationBucket.CODE),
+ (
+ "message_over_cosmetic",
+ (DestinationHoldBack.MESSAGE_COSMETIC, DestinationHoldBack.MESSAGE),
+ DestinationBucket.PORTABLE,
+ ),
+ ("cosmetic", (DestinationHoldBack.MESSAGE_COSMETIC,), DestinationBucket.COSMETIC),
+ (
+ "templated_over_static_headers",
+ (DestinationHoldBack.WEBHOOK_HEADERS, DestinationHoldBack.WEBHOOK_TEMPLATED_HEADER),
+ DestinationBucket.TEMPLATED_HEADERS,
+ ),
+ ("static_headers", (DestinationHoldBack.WEBHOOK_HEADERS,), DestinationBucket.STATIC_HEADERS),
+ ]
+ )
+ def test_the_most_restrictive_hold_back_decides(
+ self, _name: str, hold_backs: tuple[DestinationHoldBack, ...], expected: DestinationBucket
+ ) -> None:
+ eligibility = DestinationEligibility(
+ hog_function_id=UUID(int=1), template_id="template-webhook", hold_backs=hold_backs, code_hash=""
+ )
+
+ assert bucket_for(eligibility) == expected
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.py
index 60e463fea0ef..0c96b359c725 100644
--- a/products/logs/backend/management/commands/report_logs_alert_hold_backs.py
+++ b/products/logs/backend/management/commands/report_logs_alert_hold_backs.py
@@ -3,6 +3,7 @@ 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
@@ -14,14 +15,19 @@ class Command(BaseCommand):
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"]):
- hold_backs = held.destination.hold_backs
- reasons.update(str(reason) for reason in hold_backs)
+ 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={held.destination.hog_function_id} "
- f"template={held.destination.template_id} reasons={','.join(hold_backs)}"
+ 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'}")