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(logs): send customized logs alerts through their HogFunctions after cutover (#118876)

Jimmy Zhu0ef9e0f47b8b
diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.py
index 4f41b4020cc5..3a313c3cd976 100644
--- a/products/alerts/backend/apps.py
+++ b/products/alerts/backend/apps.py
@@ -15,7 +15,14 @@ class AlertsConfig(AppConfig):
from products.alerts.backend import activity_logging # noqa: F401, PLC0415
# The platform cannot import this product, so it reaches this product's destinations here.
- from products.alerts.backend.facade.destinations import list_delivery_destination_groups # noqa: PLC0415
- from products.alerts_platform.backend.facade.delivery import register_destination_resolver # noqa: PLC0415
+ from products.alerts.backend.facade.destinations import ( # noqa: PLC0415
+ choose_delivery_path,
+ list_delivery_destination_groups,
+ )
+ from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
+ register_delivery_path_chooser,
+ register_destination_resolver,
+ )
register_destination_resolver(list_delivery_destination_groups)
+ register_delivery_path_chooser(choose_delivery_path)
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 62a6622ec845..1c3bc23defbb 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -14,7 +14,7 @@ from uuid import UUID
from posthog.dataclasses import frozen
-from products.alerts_platform.backend.facade.contracts import DestinationType
+from products.alerts_platform.backend.facade.contracts import DeliveryPath, DestinationType
from products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT
# The internal event an insight alert's destinations fire on. Do not take it from
@@ -70,6 +70,28 @@ class DestinationBucket(StrEnum):
STOCK = "N0"
+class HogFunctionPathReason(StrEnum):
+ """Why an alert the platform owns sends through its HogFunctions rather than natively."""
+
+ CUSTOMIZED = "customized"
+ # A function takes the source's alert events without being bound to one alert. Native
+ # delivery reads destinations per alert, so it would never send to it.
+ UNBOUND = "unbound"
+ # A stock webhook whose team receives the platform body natively. Its receiver parses the
+ # body the HogFunction sends.
+ NEW_WEBHOOK_BODY = "new_webhook_body"
+ WEBHOOK_BODY_UNKNOWN = "webhook_body_unknown"
+
+
+@frozen
+class DeliveryPathChoice:
+ reason: HogFunctionPathReason | None = None
+
+ @property
+ def path(self) -> DeliveryPath:
+ return DeliveryPath.NATIVE if self.reason is None else DeliveryPath.HOG_FUNCTION
+
+
@frozen
class DestinationEligibility:
"""One alert destination function, and every reason native delivery cannot take it over."""
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index 35ff5ce90fd1..98e2727cb77a 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -21,20 +21,23 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationConfig,
AlertDestinationData,
AlertDestinationGroup,
+ DeliveryPath,
DestinationType,
EventKindSpec,
OwnedAlertDestination,
+ SourceKind,
)
from ..logic import (
delivery_destinations,
+ delivery_path,
destination_bucket_report,
destination_configs,
destination_eligibility,
destinations,
insight_alert_destinations,
)
-from .contracts import AlertInternalEvent, DestinationBucket, DestinationEligibility
+from .contracts import AlertInternalEvent, DeliveryPathChoice, DestinationBucket, DestinationEligibility
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
@@ -242,14 +245,11 @@ def list_delivery_destination_groups(
def classify_alert_destinations(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str], lock: bool = False
+ *, 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.
-
- With `lock`, call inside a transaction: the function rows stay locked until it ends.
- """
+ """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, lock=lock
+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
)
@@ -270,3 +270,21 @@ def bucket_for(eligibility: DestinationEligibility) -> DestinationBucket:
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)
+
+
+def team_delivery_paths(
+ *, source: SourceKind, team_id: int, alert_ids: Sequence[str], allowed_event_ids: Collection[str]
+) -> dict[str, DeliveryPathChoice]:
+ """Whether native delivery may send each alert's destinations now, and why not when it may not."""
+ return delivery_path.team_delivery_paths(
+ source=source, team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids
+ )
+
+
+def choose_delivery_path(
+ *, source: SourceKind, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> DeliveryPath:
+ """The platform's delivery path chooser, which `products.alerts` registers when Django starts."""
+ return delivery_path.delivery_path(
+ source=source, team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
+ )
diff --git a/products/alerts/backend/logic/delivery_path.py b/products/alerts/backend/logic/delivery_path.py
new file mode 100644
index 000000000000..d1a7ebea7eb5
--- /dev/null
+++ b/products/alerts/backend/logic/delivery_path.py
@@ -0,0 +1,92 @@
+"""Whether native delivery may send an alert's destinations, or they keep sending through HogFunctions.
+
+Native delivery reproduces a stock destination only. Every other destination keeps its HogFunction,
+which sends exactly what it sent before the cutover. The answer covers every destination of the
+alert, disabled ones too, because a person can enable one in the middle of a firing.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection, Sequence
+from functools import cached_property
+
+import structlog
+
+from posthog.models import Team
+
+from products.alerts.backend.facade.contracts import (
+ DeliveryPathChoice,
+ DestinationBucket,
+ DestinationEligibility,
+ HogFunctionPathReason,
+)
+from products.alerts.backend.logic.destination_configs import WebhookDestination
+from products.alerts.backend.logic.destination_eligibility import (
+ bucket_for,
+ classify_alert_destinations,
+ classify_destinations_by_alert,
+ unbound_alert_destinations,
+)
+from products.alerts_platform.backend.facade.contracts import DeliveryPath, SourceKind
+from products.alerts_platform.backend.facade.delivery import native_sends_legacy_webhook_body
+
+logger = structlog.get_logger(__name__)
+
+
+def delivery_path(
+ *, source: SourceKind, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> DeliveryPath:
+ """The platform's chooser: the path one alert's destinations allow now."""
+ team = _TeamDestinations(source=source, team_id=team_id, allowed_event_ids=allowed_event_ids)
+ choice = team.unbound_choice() or team.choice(
+ classify_alert_destinations(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
+ )
+ if choice.reason is not None:
+ logger.info("alert_delivery_path_hog_function", team_id=team_id, alert_id=alert_id, reason=choice.reason)
+ return choice.path
+
+
+def team_delivery_paths(
+ *, source: SourceKind, team_id: int, alert_ids: Sequence[str], allowed_event_ids: Collection[str]
+) -> dict[str, DeliveryPathChoice]:
+ """The path each alert of one team would take now, read with one lookup per kind for the whole team."""
+ team = _TeamDestinations(source=source, team_id=team_id, allowed_event_ids=allowed_event_ids)
+ if (unbound := team.unbound_choice()) is not None:
+ return dict.fromkeys(alert_ids, unbound)
+ by_alert = classify_destinations_by_alert(team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids)
+ return {alert_id: team.choice(destinations) for alert_id, destinations in by_alert.items()}
+
+
+class _TeamDestinations:
+ """What every alert of one team shares: its unbound functions and its webhook body."""
+
+ def __init__(self, *, source: SourceKind, team_id: int, allowed_event_ids: Collection[str]) -> None:
+ self._source = source
+ self._team_id = team_id
+ self._allowed_event_ids = allowed_event_ids
+
+ def unbound_choice(self) -> DeliveryPathChoice | None:
+ """Every alert of a team with an unbound function sends through HogFunctions, whatever its own destinations are."""
+ return DeliveryPathChoice(reason=HogFunctionPathReason.UNBOUND) if self._has_unbound else None
+
+ def choice(self, destinations: Sequence[DestinationEligibility]) -> DeliveryPathChoice:
+ if any(bucket_for(destination) != DestinationBucket.STOCK for destination in destinations):
+ return DeliveryPathChoice(reason=HogFunctionPathReason.CUSTOMIZED)
+ if any(destination.template_id == WebhookDestination.template_id for destination in destinations):
+ if self._native_webhook_body is None:
+ return DeliveryPathChoice(reason=HogFunctionPathReason.WEBHOOK_BODY_UNKNOWN)
+ if not self._native_webhook_body:
+ return DeliveryPathChoice(reason=HogFunctionPathReason.NEW_WEBHOOK_BODY)
+ return DeliveryPathChoice()
+
+ @cached_property
+ def _has_unbound(self) -> bool:
+ return bool(
+ unbound_alert_destinations(
+ team_id=self._team_id, allowed_event_ids=self._allowed_event_ids, include_disabled=True
+ )
+ )
+
+ @cached_property
+ def _native_webhook_body(self) -> bool | None:
+ return native_sends_legacy_webhook_body(self._source, Team.objects.get(id=self._team_id))
diff --git a/products/alerts/backend/logic/destination_eligibility.py b/products/alerts/backend/logic/destination_eligibility.py
index 601ed6c63b64..3b1a92424fb1 100644
--- a/products/alerts/backend/logic/destination_eligibility.py
+++ b/products/alerts/backend/logic/destination_eligibility.py
@@ -90,13 +90,9 @@ _RECEIVES_ALERT_EVENTS: Final = {"type": "internal_destination", "filters__sourc
def classify_alert_destinations(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str], lock: bool = False
+ *, 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.
-
- `lock` holds the function rows until the caller's transaction ends, so no edit lands between
- this read and what the caller does with it.
- """
+ """Every destination function of one alert, with what native delivery cannot carry for each."""
functions = (
owned_alert_destinations_qs(
team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids, known_templates_only=False
@@ -104,7 +100,7 @@ def classify_alert_destinations(
.filter(**_RECEIVES_ALERT_EVENTS)
.order_by("created_at", "id")
)
- return _classify(team_id, list(functions.select_for_update() if lock else functions), allowed_event_ids)
+ return _classify(team_id, list(functions), allowed_event_ids)
def classify_destinations_by_alert(
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index 5ddfb840be88..f0f45ed84841 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -457,13 +457,29 @@ class TestDeliverEvaluation(APIBaseTest):
assert post.call_args.kwargs["headers"] == {"X-PostHog-Webhook-Version": header}
assert post.call_args.args[1]["version"] == body_version
+ @parameterized.expand([("registered_a_body", True, True), ("registered_none", False, False)])
+ def test_native_delivery_keeps_the_webhook_body_only_for_a_source_that_registered_one(
+ self, _name: str, registered: bool, keeps: bool
+ ) -> None:
+ bodies: dict[SourceKind, Any] = {SourceKind.INSIGHT: lambda **_kwargs: {}} if registered else {}
+ with (
+ patch.dict(f"{_LEGACY_MODULE}._bodies", bodies, clear=True),
+ patch(
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
+ return_value=True,
+ ),
+ ):
+ assert legacy_webhook.native_sends_legacy_body(SourceKind.INSIGHT, self.team) is keeps
+
def test_logs_registers_its_legacy_webhook_body_at_startup(self) -> None:
# Every other case here patches the registry, so none of them notices a missing registration,
# which would send grandfathered teams the Alertmanager body without any error.
assert legacy_webhook.body_for(SourceKind.LOGS) is not None
+ assert delivery_paths.emitter_for(SourceKind.LOGS) is not None
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
assert (
list_alert_destination_groups(team_id=self.team.id, alert_id="unknown", allowed_event_ids=[FIRING_EVENT])
== []
diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.py
index 46c059908fe2..30eff1249d29 100644
--- a/products/logs/backend/apps.py
+++ b/products/logs/backend/apps.py
@@ -13,13 +13,16 @@ class LogsConfig(AppConfig):
# transitively imports the whole query-runner layer, which would drag posthog.schema and
# HogQL into django.setup() for every process type.
# - The alerts platform cannot import this product, so native alert messages get the logs
- # wording, and grandfathered webhooks the legacy logs body, through the functions registered below.
+ # wording, grandfathered webhooks the legacy logs body, and alerts on the HogFunction path
+ # their `$logs_alert_*` events, through the functions registered below.
from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415
from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
+ register_legacy_event_emitter,
register_legacy_webhook_body,
register_source_describer,
)
from products.logs.backend import activity_logging # noqa: F401, PLC0415
+ from products.logs.backend.platform_alert_legacy_events import emit_logs_legacy_events # noqa: PLC0415
from products.logs.backend.platform_alert_wording import ( # noqa: PLC0415
describe_logs_transition,
legacy_logs_webhook_body,
@@ -27,3 +30,4 @@ class LogsConfig(AppConfig):
register_source_describer(SourceKind.LOGS, describe_logs_transition)
register_legacy_webhook_body(SourceKind.LOGS, legacy_logs_webhook_body)
+ register_legacy_event_emitter(SourceKind.LOGS, emit_logs_legacy_events)
diff --git a/products/logs/backend/cutover_gate.py b/products/logs/backend/cutover_gate.py
deleted file mode 100644
index baccf50afd08..000000000000
--- a/products/logs/backend/cutover_gate.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Which of a team's logs alert destinations native delivery cannot take over yet. A team moves whole or not at all."""
-
-from __future__ import annotations
-
-from enum import StrEnum
-from functools import cached_property
-from uuid import UUID
-
-from posthog.dataclasses import frozen
-from posthog.models import Team
-
-from products.alerts.backend.facade.contracts import DestinationBucket
-from products.alerts.backend.facade.destinations import (
- bucket_for,
- classify_alert_destinations,
- destination_template_id,
- unbound_alert_destinations,
-)
-from products.alerts_platform.backend.facade.contracts import DestinationType
-from products.alerts_platform.backend.facade.delivery import keeps_legacy_webhook_body
-from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS
-from products.logs.backend.models import LogsAlertConfiguration
-
-# PORTABLE can hide edited code through `untracked_edit`, so it needs a code check before it joins.
-_READY_BUCKETS = frozenset({DestinationBucket.STOCK})
-
-
-class GateRefusal(StrEnum):
- """Why one destination stops its team from moving."""
-
- NOT_READY = "not_ready"
- # Native delivery reads destinations per alert, so this function would receive nothing.
- UNBOUND = "unbound"
- # The team's receivers parse the logs stack's body, and native delivery would send the platform body.
- NEW_WEBHOOK_BODY = "new_webhook_body"
- WEBHOOK_BODY_UNKNOWN = "webhook_body_unknown"
-
-
-@frozen
-class DestinationRefusal:
- hog_function_id: UUID
- # None for a function bound to no single alert.
- alert_id: UUID | None
- bucket: DestinationBucket | None
- reason: GateRefusal
-
-
-class CutoverRefused(Exception):
- """The team keeps every alert on the logs stack, because some destinations cannot move yet."""
-
- def __init__(self, team_id: int, refusals: tuple[DestinationRefusal, ...]) -> None:
- super().__init__(f"team {team_id} has {len(refusals)} destinations that cannot move yet")
- self.team_id = team_id
- self.refusals = refusals
-
-
-class TeamGate:
- """One team's destination checks. The unbound lookup and the webhook body flag are read once per team."""
-
- def __init__(self, team_id: int) -> None:
- self.team_id = team_id
- self._unbound = unbound_alert_destinations(
- team_id=team_id, allowed_event_ids=LOGS_ALERT_EVENT_IDS, include_disabled=True
- )
- self._webhook_template_id = destination_template_id(DestinationType.WEBHOOK)
-
- def refusals(self) -> tuple[DestinationRefusal, ...]:
- """Every destination that stops this team moving, or nothing when all of them can move."""
- refusals: list[DestinationRefusal] = []
- # Disabled alerts and disabled destinations count too, because a person can enable either after the move.
- alerts = LogsAlertConfiguration.objects.filter(team_id=self.team_id).order_by("created_at", "id")
- for alert_id in alerts.values_list("id", flat=True):
- refusals.extend(self.alert_refusals(alert_id))
- refusals.extend(
- DestinationRefusal(hog_function_id=function_id, alert_id=None, bucket=None, reason=GateRefusal.UNBOUND)
- for function_id in self._unbound
- )
- return tuple(refusals)
-
- def alert_refusals(self, alert_id: UUID, *, lock: bool = False) -> list[DestinationRefusal]:
- """One alert's refusals. `lock` keeps its destinations locked until the caller's transaction ends."""
- refusals: list[DestinationRefusal] = []
- for destination in classify_alert_destinations(
- team_id=self.team_id, alert_id=str(alert_id), allowed_event_ids=LOGS_ALERT_EVENT_IDS, lock=lock
- ):
- # A function that excludes one alert id also matches that alert here. It is refused once, as unbound.
- if destination.hog_function_id in self._unbound:
- continue
- bucket = bucket_for(destination)
- if bucket not in _READY_BUCKETS:
- reason: GateRefusal | None = GateRefusal.NOT_READY
- elif destination.template_id == self._webhook_template_id:
- reason = self._webhook_body_refusal
- else:
- reason = None
- if reason is not None:
- refusals.append(
- DestinationRefusal(
- hog_function_id=destination.hog_function_id, alert_id=alert_id, bucket=bucket, reason=reason
- )
- )
- return refusals
-
- @cached_property
- def _webhook_body_refusal(self) -> GateRefusal | None:
- keeps_legacy_body = keeps_legacy_webhook_body(Team.objects.get(id=self.team_id))
- if keeps_legacy_body is None:
- return GateRefusal.WEBHOOK_BODY_UNKNOWN
- return None if keeps_legacy_body else GateRefusal.NEW_WEBHOOK_BODY
diff --git a/products/logs/backend/delivery_path_report.py b/products/logs/backend/delivery_path_report.py
new file mode 100644
index 000000000000..1ee47b3f0fb0
--- /dev/null
+++ b/products/logs/backend/delivery_path_report.py
@@ -0,0 +1,54 @@
+"""Which path each logs alert of a team delivers through once the platform owns it.
+
+Native delivery sends an alert whose destinations are all stock. Every other alert keeps sending
+through its HogFunctions, from the `$logs_alert_*` events the platform emits for it. Both paths
+can deliver any destination, so the report only informs a cutover: it never stops one.
+
+Delivery decides the path again at send time, so an edit after the report changes what it says.
+"""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.facade.contracts import DeliveryPathChoice
+from products.alerts.backend.facade.destinations import (
+ team_delivery_paths as alert_delivery_paths,
+ unbound_alert_destinations,
+)
+from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS
+from products.logs.backend.models import LogsAlertConfiguration
+
+
+@frozen
+class AlertDeliveryPath:
+ alert_id: UUID
+ choice: DeliveryPathChoice
+
+
+@frozen
+class TeamDeliveryPaths:
+ alerts: tuple[AlertDeliveryPath, ...]
+ unbound_functions: tuple[UUID, ...]
+
+
+def team_delivery_paths(team_id: int) -> TeamDeliveryPaths:
+ # Disabled alerts and destinations count too, because a person can enable either after the move.
+ alert_ids = list(
+ LogsAlertConfiguration.objects.filter(team_id=team_id).order_by("created_at", "id").values_list("id", flat=True)
+ )
+ choices = alert_delivery_paths(
+ source=SourceKind.LOGS,
+ team_id=team_id,
+ alert_ids=[str(alert_id) for alert_id in alert_ids],
+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,
+ )
+ return TeamDeliveryPaths(
+ alerts=tuple(AlertDeliveryPath(alert_id=alert_id, choice=choices[str(alert_id)]) for alert_id in alert_ids),
+ unbound_functions=unbound_alert_destinations(
+ team_id=team_id, allowed_event_ids=LOGS_ALERT_EVENT_IDS, include_disabled=True
+ ),
+ )
diff --git a/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py b/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
index 9a45bf6fdbc5..2fc8e5ec2457 100644
--- a/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
+++ b/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
@@ -1,9 +1,9 @@
from collections import Counter
from typing import Any
-from django.core.management.base import BaseCommand, CommandError
+from django.core.management.base import BaseCommand
-from products.logs.backend.cutover_gate import CutoverRefused
+from products.logs.backend.delivery_path_report import team_delivery_paths
from products.logs.backend.platform_cutover import cut_over_team
@@ -15,17 +15,16 @@ class Command(BaseCommand):
def handle(self, *args: Any, **options: Any) -> None:
team_id = options["team_id"]
- try:
- results = cut_over_team(team_id)
- except CutoverRefused as refused:
- for refusal in refused.refusals:
- self.stdout.write(
- f"function={refusal.hog_function_id} alert={refusal.alert_id} "
- f"bucket={refusal.bucket} refused={refusal.reason}"
- )
- raise CommandError(f"team={team_id} moved nothing: {len(refused.refusals)} destinations cannot move yet")
+ paths = team_delivery_paths(team_id)
+ for function_id in paths.unbound_functions:
+ self.stdout.write(f"function={function_id} unbound")
+ for alert in paths.alerts:
+ if alert.choice.reason is not None:
+ self.stdout.write(f"alert={alert.alert_id} path={alert.choice.path} reason={alert.choice.reason}")
+ results = cut_over_team(team_id)
for result in results:
if result.skipped is not None:
self.stdout.write(f"alert={result.alert_id} skipped={result.skipped}")
+ delivery = Counter(str(alert.choice.path) for alert in paths.alerts)
outcomes = Counter(str(result.skipped or "moved") for result in results)
- self.stdout.write(f"team={team_id} {dict(outcomes) or 'no alerts'}")
+ self.stdout.write(f"team={team_id} {dict(outcomes) or 'no alerts'} paths={dict(delivery)}")
diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.py
index 287f210fc002..8b69cd8b5bce 100644
--- a/products/logs/backend/platform_cutover.py
+++ b/products/logs/backend/platform_cutover.py
@@ -20,7 +20,6 @@ from products.alerts_platform.backend.facade.contracts import HandbackRefusal, P
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.logs.backend.alert_state_machine import FIRING_STATES, ControlPlaneOutcome, apply_outcome
from products.logs.backend.alert_utils import due_alerts_q
-from products.logs.backend.cutover_gate import CutoverRefused, TeamGate
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.platform_alert_backfill import (
PLATFORM_HANDOVER_STATE,
@@ -42,8 +41,6 @@ class CutoverSkip(StrEnum):
CHECK_DUE = "check_due"
# A team on live delivery can have the platform copy inside a firing of its own.
PLATFORM_FIRING = "platform_firing"
- # A destination changed after the team passed the gate, and native delivery cannot send it now.
- DESTINATION_CHANGED = "destination_changed"
@frozen
@@ -71,20 +68,14 @@ def _logs_check_owed(alert_id: UUID, at: datetime) -> bool:
def cut_over_team(team_id: int, *, now: datetime | None = None) -> tuple[AlertCutover, ...]:
"""Hands every logs alert of one team to the platform, or says why one stays.
- Raises `CutoverRefused`, moving nothing, when native delivery cannot yet send one of the team's
- destinations the way the team receives it today.
+ No destination holds an alert back: delivery sends a customized one through its HogFunction.
"""
- gate = TeamGate(team_id)
- refusals = gate.refusals()
- if refusals:
- raise CutoverRefused(team_id, refusals)
return tuple(
- AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, gate, now))
- for alert_id in _team_alert_ids(team_id)
+ AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, now)) for alert_id in _team_alert_ids(team_id)
)
-def _cut_over_alert(alert_id: UUID, gate: TeamGate, now: datetime | None) -> CutoverSkip | None:
+def _cut_over_alert(alert_id: UUID, now: datetime | None) -> CutoverSkip | None:
with transaction.atomic():
alert = LogsAlertConfiguration.objects.select_for_update().get(id=alert_id)
# Read after the lock, so a check that became due while earlier alerts moved is seen as due.
@@ -95,9 +86,6 @@ def _cut_over_alert(alert_id: UUID, gate: TeamGate, now: datetime | None) -> Cut
return CutoverSkip.FIRING
if _logs_check_owed(alert.id, at):
return CutoverSkip.CHECK_DUE
- # Locks the alert's destinations, so no edit lands between this check and the move.
- if gate.alert_refusals(alert.id, lock=True):
- return CutoverSkip.DESTINATION_CHANGED
savepoint = transaction.savepoint()
upsert_configuration(platform_upsert_of(alert))
diff --git a/products/logs/backend/test/test_platform_cutover.py b/products/logs/backend/test/test_platform_cutover.py
index d4bd2ff3689a..55a2040fb74d 100644
--- a/products/logs/backend/test/test_platform_cutover.py
+++ b/products/logs/backend/test/test_platform_cutover.py
@@ -9,14 +9,14 @@ from parameterized import parameterized
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import DestinationBucket
+from products.alerts.backend.facade.contracts import HogFunctionPathReason
from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import get_configuration, upsert_configuration
-from products.alerts_platform.backend.facade.contracts import SourceKind
+from products.alerts_platform.backend.facade.contracts import DeliveryPath, SourceKind
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.hog_functions.hog_function_revision import HogFunctionRevision
from products.logs.backend.alert_destinations import LOGS_ALERT_EVENT_IDS
-from products.logs.backend.cutover_gate import CutoverRefused, GateRefusal, TeamGate
+from products.logs.backend.delivery_path_report import team_delivery_paths
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.platform_alert_backfill import platform_upsert_of
from products.logs.backend.platform_cutover import CutoverSkip, RollbackSkip, cut_over_team, roll_back_team
@@ -242,7 +242,7 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{"inputs": {**WEBHOOK_INPUTS, "body": {"value": {"text": "relay"}}}},
True,
- (DestinationBucket.PORTABLE, GateRefusal.NOT_READY),
+ HogFunctionPathReason.CUSTOMIZED,
),
(
"edited_code",
@@ -250,7 +250,7 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{"hog": "fetch('https://relay.example.com')"},
True,
- (DestinationBucket.CODE, GateRefusal.NOT_READY),
+ HogFunctionPathReason.CUSTOMIZED,
),
(
"stock_webhook_without_legacy_body",
@@ -258,7 +258,7 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{},
False,
- (DestinationBucket.STOCK, GateRefusal.NEW_WEBHOOK_BODY),
+ HogFunctionPathReason.NEW_WEBHOOK_BODY,
),
(
"stock_webhook_with_unreadable_flag",
@@ -266,7 +266,7 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{},
None,
- (DestinationBucket.STOCK, GateRefusal.WEBHOOK_BODY_UNKNOWN),
+ HogFunctionPathReason.WEBHOOK_BODY_UNKNOWN,
),
(
"header_native_delivery_drops",
@@ -274,7 +274,7 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{"inputs": {**WEBHOOK_INPUTS, "headers": {"value": {"Host": "internal.example.com"}}}},
True,
- (DestinationBucket.STATIC_HEADERS, GateRefusal.NOT_READY),
+ HogFunctionPathReason.CUSTOMIZED,
),
(
"secret_header",
@@ -282,55 +282,49 @@ class TestPlatformCutover(APIBaseTest):
WEBHOOK_INPUTS,
{"encrypted_inputs": {"secret_headers": {"value": {"Authorization": "Bearer not-a-real-token"}}}},
True,
- (DestinationBucket.STATIC_HEADERS, GateRefusal.NOT_READY),
+ HogFunctionPathReason.CUSTOMIZED,
),
]
)
- def test_a_destination_native_delivery_cannot_send_yet_keeps_the_whole_team(
+ def test_a_destination_native_delivery_cannot_send_moves_on_the_hog_function_path(
self,
_name: str,
template_id: str,
inputs: dict[str, Any],
edit: dict[str, Any],
keeps_legacy_body: bool | None,
- refused: tuple[DestinationBucket, GateRefusal],
+ reason: HogFunctionPathReason,
) -> None:
held = self._alert()
quiet = self._alert(name="Warnings")
self._destination(held.id, template_id, inputs, edit)
- with patch(LEGACY_BODY_FLAG, return_value=keeps_legacy_body), self.assertRaises(CutoverRefused) as raised:
- cut_over_team(self.team.id, now=NOW)
+ with patch(LEGACY_BODY_FLAG, return_value=keeps_legacy_body):
+ paths = team_delivery_paths(self.team.id)
+ results = cut_over_team(self.team.id, now=NOW)
- assert [(refusal.alert_id, refusal.bucket, refusal.reason) for refusal in raised.exception.refusals] == [
- (held.id, *refused)
+ assert [(alert.alert_id, alert.choice.path, alert.choice.reason) for alert in paths.alerts] == [
+ (held.id, DeliveryPath.HOG_FUNCTION, reason),
+ (quiet.id, DeliveryPath.NATIVE, None),
]
+ assert [result.skipped for result in results] == [None, None]
assert set(
LogsAlertConfiguration.objects.filter(id__in=[held.id, quiet.id]).values_list("owner", flat=True)
- ) == {"source"}
-
- def test_a_destination_edited_after_the_gate_keeps_its_alert(self) -> None:
- alert = self._alert()
- self._destination(alert.id, "template-webhook", WEBHOOK_INPUTS, {"hog": "fetch('https://relay.example.com')"})
-
- with patch.object(TeamGate, "refusals", return_value=()), patch(LEGACY_BODY_FLAG, return_value=True):
- (result,) = cut_over_team(self.team.id, now=NOW)
-
- assert result.skipped == CutoverSkip.DESTINATION_CHANGED
- alert.refresh_from_db()
- assert alert.owner == "source"
+ ) == {"platform"}
@parameterized.expand([("enabled", True), ("disabled", False)])
- def test_an_unbound_destination_keeps_the_whole_team(self, _name: str, enabled: bool) -> None:
- self._alert()
+ def test_an_unbound_destination_puts_every_alert_on_the_hog_function_path(self, _name: str, enabled: bool) -> None:
+ alert = self._alert()
function = self._destination(None, "template-slack", SLACK_INPUTS, {"enabled": enabled})
- with self.assertRaises(CutoverRefused) as raised:
- cut_over_team(self.team.id, now=NOW)
+ paths = team_delivery_paths(self.team.id)
+ (result,) = cut_over_team(self.team.id, now=NOW)
- assert [(refusal.hog_function_id, refusal.reason) for refusal in raised.exception.refusals] == [
- (function.id, GateRefusal.UNBOUND)
+ assert paths.unbound_functions == (function.id,)
+ assert [(a.alert_id, a.choice.path, a.choice.reason) for a in paths.alerts] == [
+ (alert.id, DeliveryPath.HOG_FUNCTION, HogFunctionPathReason.UNBOUND)
]
+ assert result.skipped is None
@parameterized.expand(
[
@@ -345,8 +339,10 @@ class TestPlatformCutover(APIBaseTest):
self._destination(alert.id, template_id, inputs, edit)
with patch(LEGACY_BODY_FLAG, return_value=True):
+ paths = team_delivery_paths(self.team.id)
(result,) = cut_over_team(self.team.id, now=NOW)
+ assert [(a.choice.path, a.choice.reason) for a in paths.alerts] == [(DeliveryPath.NATIVE, None)]
assert result.skipped is None
alert.refresh_from_db()
assert alert.owner == "platform"