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): refuse a cutover while any destination cannot move natively (#117413)

Jimmy Zhufd99fdb16cc5
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index 29819636c7c1..da008a349720 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -230,17 +230,24 @@ def list_delivery_destination_groups(
def classify_alert_destinations(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str], lock: bool = False
) -> tuple[DestinationEligibility, ...]:
- """Every destination function of one alert, with what native delivery cannot carry for each."""
+ """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.
+ """
return destination_eligibility.classify_alert_destinations(
- team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids
+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids, lock=lock
)
-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 unbound_alert_destinations(
+ *, team_id: int, allowed_event_ids: Collection[str], include_disabled: bool = False
+) -> tuple[UUID, ...]:
+ """Functions that take a source's alert events without being bound to one alert, enabled ones only by default."""
+ return destination_eligibility.unbound_alert_destinations(
+ team_id=team_id, allowed_event_ids=allowed_event_ids, include_disabled=include_disabled
+ )
def bucket_for(eligibility: DestinationEligibility) -> DestinationBucket:
diff --git a/products/alerts/backend/logic/destination_eligibility.py b/products/alerts/backend/logic/destination_eligibility.py
index 607135586fd6..601ed6c63b64 100644
--- a/products/alerts/backend/logic/destination_eligibility.py
+++ b/products/alerts/backend/logic/destination_eligibility.py
@@ -90,17 +90,21 @@ _RECEIVES_ALERT_EVENTS: Final = {"type": "internal_destination", "filters__sourc
def classify_alert_destinations(
- *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str], lock: bool = False
) -> tuple[DestinationEligibility, ...]:
- """Every destination function of one alert, with what native delivery cannot carry for each."""
- functions = list(
+ """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.
+ """
+ functions = (
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")
)
- return _classify(team_id, functions, allowed_event_ids)
+ return _classify(team_id, list(functions.select_for_update() if lock else functions), allowed_event_ids)
def classify_destinations_by_alert(
@@ -169,19 +173,22 @@ def bucket_for(eligibility: DestinationEligibility) -> DestinationBucket:
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.
+def unbound_alert_destinations(
+ *, team_id: int, allowed_event_ids: Collection[str], include_disabled: bool = False
+) -> tuple[UUID, ...]:
+ """Functions that take a source's alert events without being bound to one alert, enabled ones only by default.
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.
"""
+ enabled = {} if include_disabled else {"enabled": True}
candidates = (
HogFunction.objects.filter(
_allowed_event_filter(allowed_event_ids),
team_id=team_id,
deleted=False,
- enabled=True,
+ **enabled,
**_RECEIVES_ALERT_EVENTS,
)
.order_by("created_at", "id")
@@ -232,6 +239,9 @@ def _hold_backs(
# 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)
+ # Native delivery reads ordinary headers only, so a secret header such as a token never reaches the receiver.
+ if template_id == WebhookDestination.template_id and input_value(function.encrypted_inputs or {}, "secret_headers"):
+ found.append(DestinationHoldBack.WEBHOOK_HEADERS)
# 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):
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index 9525f086b192..db5acca29cf5 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -10,7 +10,6 @@ from dataclasses import replace
from typing import Any, Final
import structlog
-import posthoganalytics
from posthog.dataclasses import frozen
from posthog.models import Team
@@ -24,6 +23,7 @@ from products.alerts_platform.backend.delivery.in_app import InAppTransport
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport
from products.alerts_platform.backend.delivery.slack import SlackTransport
+from products.alerts_platform.backend.delivery.team_flags import team_flag_enabled
from products.alerts_platform.backend.delivery.teams import TeamsTransport
from products.alerts_platform.backend.delivery.telemetry import record_delivery
from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusy
@@ -78,7 +78,7 @@ def destinations_are_live(team: Team) -> bool:
is where everything was before this existed. Reading a blip the other way starts sending.
"""
try:
- return bool(_team_flag_enabled(LIVE_DELIVERY_FLAG, team))
+ return bool(team_flag_enabled(LIVE_DELIVERY_FLAG, team))
except Exception:
logger.warning(
"alerts_platform_live_delivery_flag_check_failed_defaulting_off",
@@ -88,24 +88,6 @@ def destinations_are_live(team: Team) -> bool:
return False
-def _team_flag_enabled(flag: str, team: Team) -> bool | None:
- """None when the flag could not be evaluated: the SDK logs and swallows a failed lookup, and it
- answers None for a flag that does not exist too."""
- return posthoganalytics.feature_enabled(
- flag,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- group_properties={
- "organization": {"id": str(team.organization_id)},
- # Both regions read flags from one PostHog project, and project ids repeat across
- # regions. A condition on the uuid names one team in one region.
- "project": {"id": str(team.id), "uuid": str(team.uuid)},
- },
- # This runs in a Temporal activity, where a captured event is silently dropped.
- send_feature_flag_events=False,
- )
-
-
class _WebhookTransports:
"""The webhook transport for one evaluation, with the legacy body when the team keeps it.
@@ -139,7 +121,7 @@ class _WebhookTransports:
if body is None:
return None
try:
- keeps_legacy_body = _team_flag_enabled(legacy_webhook.LEGACY_WEBHOOK_BODY_FLAG, self._team)
+ keeps_legacy_body = legacy_webhook.keeps_legacy_webhook_body(self._team)
except Exception as error:
raise DeliveryError("Could not read which webhook body this team receives.") from error
if keeps_legacy_body is None:
diff --git a/products/alerts_platform/backend/delivery/legacy_webhook.py b/products/alerts_platform/backend/delivery/legacy_webhook.py
index fc161b929942..5a00386853d1 100644
--- a/products/alerts_platform/backend/delivery/legacy_webhook.py
+++ b/products/alerts_platform/backend/delivery/legacy_webhook.py
@@ -5,10 +5,16 @@ had webhook destinations before the platform delivered for them keep that body u
so a receiver that parses it does not break when the platform takes over.
"""
-from typing import Final
+from __future__ import annotations
+from typing import TYPE_CHECKING, Final
+
+from products.alerts_platform.backend.delivery.team_flags import team_flag_enabled
from products.alerts_platform.backend.facade.contracts import LegacyWebhookBody, SourceKind
+if TYPE_CHECKING:
+ from posthog.models import Team
+
# A closed list of teams. No team joins it after the platform delivers for its source.
LEGACY_WEBHOOK_BODY_FLAG: Final = "alert-platform-legacy-webhook-body"
@@ -27,3 +33,8 @@ def register(source: SourceKind, body: LegacyWebhookBody) -> None:
def body_for(source: SourceKind) -> LegacyWebhookBody | None:
return _bodies.get(source)
+
+
+def keeps_legacy_webhook_body(team: Team) -> bool | None:
+ """Whether native delivery sends this team the body its source's own stack sent. None when unknown."""
+ return team_flag_enabled(LEGACY_WEBHOOK_BODY_FLAG, team)
diff --git a/products/alerts_platform/backend/delivery/team_flags.py b/products/alerts_platform/backend/delivery/team_flags.py
new file mode 100644
index 000000000000..c0917581879c
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/team_flags.py
@@ -0,0 +1,28 @@
+"""Per-team delivery flags, kept out of `evaluation` so readers at Django startup skip the delivery runtime."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import posthoganalytics
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+
+def team_flag_enabled(flag: str, team: Team) -> bool | None:
+ """None when the flag could not be evaluated: the SDK logs and swallows a failed lookup, and it
+ answers None for a flag that does not exist too."""
+ return posthoganalytics.feature_enabled(
+ flag,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ # Both regions read flags from one PostHog project, and project ids repeat across
+ # regions. A condition on the uuid names one team in one region.
+ "project": {"id": str(team.id), "uuid": str(team.uuid)},
+ },
+ # This runs in a Temporal activity, where a captured event is silently dropped.
+ send_feature_flag_events=False,
+ )
diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.py
index 8a891b0e0deb..e56572fb27dc 100644
--- a/products/alerts_platform/backend/facade/delivery.py
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -1,5 +1,9 @@
"""Facade for native delivery: how other products plug in destinations and their own wording."""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
from products.alerts_platform.backend.delivery import addresses, describers, destinations, legacy_webhook
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
@@ -9,6 +13,9 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
)
+if TYPE_CHECKING:
+ from posthog.models import Team
+
def register_destination_resolver(resolver: DestinationResolver) -> None:
destinations.register(resolver)
@@ -25,3 +32,8 @@ def refused_destination(data: AlertDestinationData) -> str | None:
def register_legacy_webhook_body(source: SourceKind, body: LegacyWebhookBody) -> None:
legacy_webhook.register(source, body)
+
+
+def keeps_legacy_webhook_body(team: Team) -> bool | None:
+ """Whether native delivery sends this team the legacy webhook body. None when the flag could not be read."""
+ return legacy_webhook.keeps_legacy_webhook_body(team)
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index d75050b07a49..0636ade4bc1c 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -156,7 +156,7 @@ class TestDeliverEvaluation(APIBaseTest):
with (
patch(
- f"{_MODULE}.posthoganalytics.feature_enabled",
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
**({"side_effect": live} if isinstance(live, Exception) else {"return_value": live}),
),
patch(f"{_MODULE}.announcement", return_value=announced),
@@ -302,7 +302,10 @@ class TestDeliverEvaluation(APIBaseTest):
url = "https://app.example.com/project/7/logs/alerts/legacy-1"
with (
- patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=True),
+ patch(
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
+ return_value=True,
+ ),
patch(f"{_MODULE}.announcement", return_value=_announcement(_transition(AlertEventKind.FIRING))),
patch(f"{_MODULE}.list_alert_destination_groups", return_value=[_group(SLACK)]),
patch(f"{_MODULE}.DatabaseThreadStore"),
@@ -330,7 +333,10 @@ class TestDeliverEvaluation(APIBaseTest):
# Without the project group the condition never matches, and the platform stays silent
# with nothing to say why.
with (
- patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=False) as flag,
+ patch(
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
+ return_value=False,
+ ) as flag,
patch(f"{_MODULE}.announcement", return_value=None),
):
deliver_evaluation(_request(self.team.id))
@@ -378,7 +384,10 @@ class TestDeliverEvaluation(APIBaseTest):
return {"version": "legacy", "alert_id": kwargs["alert_id"]}
with (
- patch(f"{_MODULE}.posthoganalytics.feature_enabled", side_effect=flag),
+ patch(
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
+ side_effect=flag,
+ ),
patch(f"{_MODULE}.announcement", return_value=_announcement(_transition(AlertEventKind.FIRING))),
patch(f"{_MODULE}.list_alert_destination_groups", return_value=[_group(WEBHOOK), _group(SECOND_WEBHOOK)]),
patch(f"{_MODULE}.DatabaseThreadStore"),
diff --git a/products/logs/backend/cutover_gate.py b/products/logs/backend/cutover_gate.py
new file mode 100644
index 000000000000..baccf50afd08
--- /dev/null
+++ b/products/logs/backend/cutover_gate.py
@@ -0,0 +1,109 @@
+"""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/management/commands/cut_over_logs_alerts_to_platform.py b/products/logs/backend/management/commands/cut_over_logs_alerts_to_platform.py
index b761c037c7fe..9a45bf6fdbc5 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,8 +1,9 @@
from collections import Counter
from typing import Any
-from django.core.management.base import BaseCommand
+from django.core.management.base import BaseCommand, CommandError
+from products.logs.backend.cutover_gate import CutoverRefused
from products.logs.backend.platform_cutover import cut_over_team
@@ -13,9 +14,18 @@ class Command(BaseCommand):
parser.add_argument("--team-id", type=int, required=True, help="The team to move.")
def handle(self, *args: Any, **options: Any) -> None:
- results = cut_over_team(options["team_id"])
+ 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")
for result in results:
if result.skipped is not None:
self.stdout.write(f"alert={result.alert_id} skipped={result.skipped}")
outcomes = Counter(str(result.skipped or "moved") for result in results)
- self.stdout.write(f"team={options['team_id']} {dict(outcomes) or 'no alerts'}")
+ self.stdout.write(f"team={team_id} {dict(outcomes) or 'no alerts'}")
diff --git a/products/logs/backend/platform_cutover.py b/products/logs/backend/platform_cutover.py
index 571956406612..9ddf667420b0 100644
--- a/products/logs/backend/platform_cutover.py
+++ b/products/logs/backend/platform_cutover.py
@@ -20,6 +20,7 @@ from products.alerts_platform.backend.facade.contracts import PlatformOwnershipH
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.logs.backend.alert_state_machine import FIRING_STATES
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
from products.logs.backend.platform_alert_backfill import PLATFORM_HANDOVER_STATE, platform_upsert_of
@@ -37,6 +38,8 @@ 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
@@ -46,14 +49,24 @@ class AlertCutover:
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."""
+ """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.
+ """
+ gate = TeamGate(team_id)
+ refusals = gate.refusals()
+ if refusals:
+ raise CutoverRefused(team_id, refusals)
alert_ids = list(
LogsAlertConfiguration.objects.filter(team_id=team_id).order_by("created_at", "id").values_list("id", flat=True)
)
- return tuple(AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, now)) for alert_id in alert_ids)
+ return tuple(
+ AlertCutover(alert_id=alert_id, skipped=_cut_over_alert(alert_id, gate, now)) for alert_id in alert_ids
+ )
-def _cut_over_alert(alert_id: UUID, now: datetime | None) -> CutoverSkip | None:
+def _cut_over_alert(alert_id: UUID, gate: TeamGate, 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.
@@ -70,6 +83,9 @@ def _cut_over_alert(alert_id: UUID, now: datetime | None) -> CutoverSkip | None:
.exists()
):
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 5934a8c53deb..b43bbd9747ff 100644
--- a/products/logs/backend/test/test_platform_cutover.py
+++ b/products/logs/backend/test/test_platform_cutover.py
@@ -1,21 +1,40 @@
from datetime import UTC, datetime, timedelta
from typing import Any
+from uuid import UUID
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from posthog.models.scoping import team_scope
+from products.alerts.backend.facade.contracts import DestinationBucket
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.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.models import LogsAlertConfiguration
from products.logs.backend.platform_alert_backfill import platform_upsert_of
from products.logs.backend.platform_cutover import CutoverSkip, cut_over_team
NOW = datetime(2026, 10, 13, 12, 0, tzinfo=UTC)
State = LogsAlertConfiguration.State
+LEGACY_BODY_FLAG = "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled"
+STOCK_HOG = "return event"
+WEBHOOK_INPUTS: dict[str, Any] = {
+ "url": {"value": "https://hooks.example.com/hook"},
+ "method": {"value": "POST"},
+ "body": {"value": {"type": "logs_alert.firing"}},
+}
+SLACK_INPUTS: dict[str, Any] = {
+ "slack_workspace": {"value": 1},
+ "channel": {"value": "C-1"},
+ "text": {"value": "Log alert is firing"},
+}
class TestPlatformCutover(APIBaseTest):
@@ -116,3 +135,157 @@ class TestPlatformCutover(APIBaseTest):
(result,) = cut_over_team(self.team.id, now=NOW + timedelta(minutes=1))
assert result.skipped == CutoverSkip.ALREADY_MOVED
+
+ def _destination(
+ self, alert_id: UUID | None, template_id: str, inputs: dict[str, Any], edit: dict[str, Any] | None = None
+ ) -> HogFunction:
+ function = HogFunction.objects.create(
+ team=self.team,
+ name="Alert destination",
+ type="internal_destination",
+ template_id=template_id,
+ enabled=True,
+ inputs=inputs,
+ inputs_schema=[{"key": key, "type": "string", "secret": False} for key in inputs],
+ hog=STOCK_HOG,
+ filters={
+ "source": "internal-events",
+ "events": [{"id": LOGS_ALERT_EVENT_IDS[0], "type": "events"}],
+ "properties": [{"key": "alert_id", "value": str(alert_id), "operator": "exact", "type": "event"}]
+ if alert_id
+ else [],
+ },
+ )
+ if edit:
+ 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, **edit)
+ return function
+
+ @parameterized.expand(
+ [
+ (
+ "rewritten_webhook_body",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {"inputs": {**WEBHOOK_INPUTS, "body": {"value": {"text": "relay"}}}},
+ True,
+ (DestinationBucket.PORTABLE, GateRefusal.NOT_READY),
+ ),
+ (
+ "edited_code",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {"hog": "fetch('https://relay.example.com')"},
+ True,
+ (DestinationBucket.CODE, GateRefusal.NOT_READY),
+ ),
+ (
+ "stock_webhook_without_legacy_body",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {},
+ False,
+ (DestinationBucket.STOCK, GateRefusal.NEW_WEBHOOK_BODY),
+ ),
+ (
+ "stock_webhook_with_unreadable_flag",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {},
+ None,
+ (DestinationBucket.STOCK, GateRefusal.WEBHOOK_BODY_UNKNOWN),
+ ),
+ (
+ "header_native_delivery_drops",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {"inputs": {**WEBHOOK_INPUTS, "headers": {"value": {"Host": "internal.example.com"}}}},
+ True,
+ (DestinationBucket.STATIC_HEADERS, GateRefusal.NOT_READY),
+ ),
+ (
+ "secret_header",
+ "template-webhook",
+ WEBHOOK_INPUTS,
+ {"encrypted_inputs": {"secret_headers": {"value": {"Authorization": "Bearer not-a-real-token"}}}},
+ True,
+ (DestinationBucket.STATIC_HEADERS, GateRefusal.NOT_READY),
+ ),
+ ]
+ )
+ def test_a_destination_native_delivery_cannot_send_yet_keeps_the_whole_team(
+ self,
+ _name: str,
+ template_id: str,
+ inputs: dict[str, Any],
+ edit: dict[str, Any],
+ keeps_legacy_body: bool | None,
+ refused: tuple[DestinationBucket, GateRefusal],
+ ) -> 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)
+
+ assert [(refusal.alert_id, refusal.bucket, refusal.reason) for refusal in raised.exception.refusals] == [
+ (held.id, *refused)
+ ]
+ 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"
+
+ @parameterized.expand([("enabled", True), ("disabled", False)])
+ def test_an_unbound_destination_keeps_the_whole_team(self, _name: str, enabled: bool) -> None:
+ 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)
+
+ assert [(refusal.hog_function_id, refusal.reason) for refusal in raised.exception.refusals] == [
+ (function.id, GateRefusal.UNBOUND)
+ ]
+
+ @parameterized.expand(
+ [
+ ("stock_slack", "template-slack", SLACK_INPUTS, {}),
+ ("stock_webhook_with_legacy_body", "template-webhook", WEBHOOK_INPUTS, {}),
+ ]
+ )
+ def test_a_team_moves_when_every_destination_is_ready(
+ self, _name: str, template_id: str, inputs: dict[str, Any], edit: dict[str, Any]
+ ) -> None:
+ alert = self._alert()
+ self._destination(alert.id, template_id, inputs, edit)
+
+ with patch(LEGACY_BODY_FLAG, return_value=True):
+ (result,) = cut_over_team(self.team.id, now=NOW)
+
+ assert result.skipped is None
+ alert.refresh_from_db()
+ assert alert.owner == "platform"