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.

chore(alerts): stop emitting $alert_transition (#121494)

Jimmy Zhuebc44d9f1212
diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.py
index f5cbe49e9347..ff06566b0e33 100644
--- a/products/alerts/backend/apps.py
+++ b/products/alerts/backend/apps.py
@@ -18,7 +18,6 @@ class AlertsConfig(AppConfig):
# schema an edit to an insight alert's copy is checked against, here.
from products.alerts.backend.facade.destinations import ( # noqa: PLC0415
choose_delivery_path,
- emit_alert_transition_events,
list_delivery_destination_groups,
)
from products.alerts.backend.platform_source_config import load_insight_source_config # noqa: PLC0415
@@ -26,11 +25,9 @@ class AlertsConfig(AppConfig):
from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
register_delivery_path_chooser,
register_destination_resolver,
- register_transition_event_producer,
)
from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415
register_destination_resolver(list_delivery_destination_groups)
register_delivery_path_chooser(choose_delivery_path)
register_source_config(SourceKind.INSIGHT, load_insight_source_config)
- register_transition_event_producer(emit_alert_transition_events)
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index 3ffec29c9b64..1913465b3e9d 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -16,7 +16,6 @@ from uuid import UUID
from posthog.kafka_client.client import ProduceResult
from products.alerts_platform.backend.facade.contracts import (
- ALERT_TRANSITION_EVENT,
ActiveAlertDestination,
AlertDelivery,
AlertDestinationConfig,
@@ -27,7 +26,6 @@ from products.alerts_platform.backend.facade.contracts import (
EventKindSpec,
OwnedAlertDestination,
SourceKind,
- TransitionEvent,
)
from ..logic import (
@@ -49,9 +47,6 @@ from .contracts import (
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
-# Below the emitting activity's own timeout, which a flush must not use up.
-TRANSITION_EVENT_FLUSH_TIMEOUT_SECONDS: Final = 5.0
-
# Each destination is another message every time the alert fires, so a caller in a loop is capped.
MAX_DESTINATIONS_PER_ALERT: Final = 5
@@ -253,24 +248,6 @@ def emit_alert_internal_events(
)
-def emit_alert_transition_events(*, team_id: int, configuration_id: str, events: Sequence[TransitionEvent]) -> None:
- """The platform's `$alert_transition` events. Raises `AlertInternalEventsNotDelivered` when the broker took not all of them."""
- destinations.emit_alert_internal_events(
- team_id=team_id,
- alert_id=configuration_id,
- events=[
- AlertInternalEvent(
- event_name=ALERT_TRANSITION_EVENT,
- properties=event.properties,
- timestamp=event.timestamp,
- uuid=event.uuid,
- )
- for event in events
- ],
- flush_timeout_seconds=TRANSITION_EVENT_FLUSH_TIMEOUT_SECONDS,
- )
-
-
def list_delivery_destination_groups(
*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
) -> list[AlertDestinationGroup]:
diff --git a/products/alerts/backend/test/test_transition_event_reservation.py b/products/alerts/backend/test/test_transition_event_reservation.py
deleted file mode 100644
index b050f9c779d2..000000000000
--- a/products/alerts/backend/test/test_transition_event_reservation.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from django.test import SimpleTestCase
-
-from products.alerts_platform.backend.facade.contracts import ALERT_TRANSITION_EVENT
-from products.cdp.backend.internal_events import is_reserved_internal_event
-
-
-class TestTransitionEventReservation(SimpleTestCase):
- def test_the_event_the_platform_emits_is_closed_to_user_created_destinations(self) -> None:
- assert is_reserved_internal_event(ALERT_TRANSITION_EVENT)
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index b0f3b1c55b3c..77bedd2a54b8 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -16,7 +16,7 @@ import structlog
from posthog.dataclasses import frozen
from posthog.models import Team
-from products.alerts_platform.backend.delivery import delivery_paths, episode_paths, legacy_webhook, transition_events
+from products.alerts_platform.backend.delivery import delivery_paths, episode_paths, legacy_webhook
from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
from products.alerts_platform.backend.delivery.discord import DiscordTransport
from products.alerts_platform.backend.delivery.dispatch import deliver
@@ -153,47 +153,6 @@ class _WebhookTransports:
)
-def emit_transition_events(request: AlertDeliveryRequest) -> int:
- """Emits one `$alert_transition` per transition the evaluation announced, and returns how many.
-
- Only where native delivery would contact the team, so a workflow never hears about an alert
- whose source still delivers on its own. Every transition goes out whatever path its destinations
- take, because a workflow is a separate subscription, not a destination.
- """
- if not request.sends_messages:
- return 0
- team = Team.objects.filter(id=request.team_id).first()
- if team is None or not transition_events_enabled(team):
- return 0
- if not (request.owned_by_platform or destinations_are_live(team)):
- return 0
- announced = announcement(
- request.team_id,
- request.configuration_id,
- request.evaluation_key,
- source=request.source,
- part=request.part,
- parts=request.parts,
- )
- if announced is None:
- return 0
- events = transition_events.transition_events(request, announced)
- if events:
- transition_events.producer()(team_id=request.team_id, configuration_id=request.configuration_id, events=events)
- return len(events)
-
-
-def transition_events_enabled(team: Team) -> bool:
- """Fail closed: a flag-eval blip leaves the team without the event, which is where it started."""
- try:
- return bool(team_flag_enabled(transition_events.TRANSITION_EVENT_FLAG, team))
- except Exception:
- logger.warning(
- "alerts_platform_transition_event_flag_check_failed_defaulting_off", team_id=team.id, exc_info=True
- )
- return False
-
-
def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
"""Sends what one evaluation decided, to every destination configured for it."""
team = Team.objects.filter(id=request.team_id).first()
diff --git a/products/alerts_platform/backend/delivery/transition_events.py b/products/alerts_platform/backend/delivery/transition_events.py
deleted file mode 100644
index 8c0c9e0f0e25..000000000000
--- a/products/alerts_platform/backend/delivery/transition_events.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""The `$alert_transition` event: one per announced transition, for a workflow to subscribe to.
-
-The platform imports neither the product that produces internal events nor any source, so both
-plug in here when Django starts:
-
-- the product that owns alert destinations registers the producer;
-- a source registers its facts, which carry the property names its own alert events used.
-
-Imported from `ready()`, so it stays light: no models, no query layer, no transports.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Final
-from uuid import NAMESPACE_URL, uuid5
-
-from products.alerts_platform.backend.facade.contracts import (
- AlertDeliveryRequest,
- AlertEventKind,
- AnnouncedTransition,
- EvaluationAnnouncement,
- SourceFacts,
- SourceKind,
- TransitionEvent,
- TransitionEventProducer,
-)
-
-# Whether the platform emits `$alert_transition` for a team's alerts. Read only where delivery
-# already contacts the team's destinations, and a failed read emits nothing.
-TRANSITION_EVENT_FLAG: Final = "alert-platform-transition-event"
-
-_FAILURE_KINDS: Final = frozenset({AlertEventKind.ERRORED, AlertEventKind.BROKEN})
-
-_producer: TransitionEventProducer | None = None
-_source_facts: dict[SourceKind, SourceFacts] = {}
-
-
-def register_producer(producer: TransitionEventProducer) -> None:
- global _producer
- if _producer is not None and _producer is not producer:
- raise RuntimeError("A different transition event producer is already registered.")
- _producer = producer
-
-
-def register_source_facts(source: SourceKind, facts: SourceFacts) -> None:
- registered = _source_facts.get(source)
- if registered is not None and registered is not facts:
- raise RuntimeError(f"Different source facts are already registered for {source} alerts.")
- _source_facts[source] = facts
-
-
-def producer() -> TransitionEventProducer:
- if _producer is None:
- raise RuntimeError("No transition event producer is registered.")
- return _producer
-
-
-def transition_events(request: AlertDeliveryRequest, announced: EvaluationAnnouncement) -> list[TransitionEvent]:
- """One event per transition the evaluation announced.
-
- A source with no registered facts gets an empty `source` block, so its events still carry
- every platform field.
- """
- facts = _source_facts.get(request.source)
- return [
- TransitionEvent(
- properties=_properties(
- request,
- announced,
- transition,
- facts(request=request, announcement=announced, transition=transition) if facts is not None else {},
- ),
- timestamp=transition.occurred_at,
- uuid=_event_uuid(request, transition),
- )
- for transition in announced.transitions
- ]
-
-
-def _properties(
- request: AlertDeliveryRequest,
- announced: EvaluationAnnouncement,
- transition: AnnouncedTransition,
- source_facts: dict[str, Any],
-) -> dict[str, Any]:
- failed = transition.kind in _FAILURE_KINDS
- return {
- "alert_configuration_id": announced.configuration_id,
- "alert_name": announced.alert_name,
- "source_kind": announced.source.value,
- "transition": transition.kind.value,
- "occurred_at": transition.occurred_at.isoformat(),
- "episode_started_at": transition.episode_started_at.isoformat() if transition.episode_started_at else None,
- "value": transition.value,
- "labels": transition.labels,
- "grouping_key": transition.grouping_key,
- "error_message": transition.error_message if failed else None,
- "consecutive_failures": announced.consecutive_failures if failed else None,
- "url": request.source_alert_url or "",
- "source": source_facts,
- }
-
-
-def _event_uuid(request: AlertDeliveryRequest, transition: AnnouncedTransition) -> str:
- # The occurrence is in the seed too, so two transitions recorded without an evaluation key keep distinct ids.
- seed = (
- f"{request.team_id}|{request.configuration_id}|{request.evaluation_key}|{transition.grouping_key}|"
- f"{transition.kind.value}|{transition.occurred_at.isoformat()}"
- )
- return str(uuid5(NAMESPACE_URL, seed))
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 3e6607cb1b9e..4ef3660e9fd5 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -1320,44 +1320,6 @@ class LegacyEventEmitter(Protocol):
) -> None: ...
-# The internal event a workflow subscribes to for an alert's transitions. One name for every source.
-ALERT_TRANSITION_EVENT: Final = "$alert_transition"
-
-
-@frozen
-class TransitionEvent:
- """One `$alert_transition` event."""
-
- properties: dict[str, Any]
- timestamp: datetime
- # Stable across attempts, so a receiver can drop an event a retry emits again.
- uuid: str
-
-
-class TransitionEventProducer(Protocol):
- """Puts `$alert_transition` events on the internal events topic.
-
- Returns only once the broker has every event, and raises otherwise, so delivery can retry.
- """
-
- def __call__(self, *, team_id: int, configuration_id: str, events: Sequence[TransitionEvent]) -> None: ...
-
-
-class SourceFacts(Protocol):
- """A source's facts about one transition, under the property names its own alert events used.
-
- A HogFunction ported to a workflow renders these names, so they must match the legacy events.
- """
-
- def __call__(
- self,
- *,
- request: AlertDeliveryRequest,
- announcement: EvaluationAnnouncement,
- transition: AnnouncedTransition,
- ) -> dict[str, Any]: ...
-
-
# Comparison against a source's own stack.
#
# What a comparison reads, and what a source must supply for one.
diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.py
index 343698586c9a..b5425e87eaae 100644
--- a/products/alerts_platform/backend/facade/delivery.py
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -10,7 +10,6 @@ from products.alerts_platform.backend.delivery import (
describers,
destinations,
legacy_webhook,
- transition_events,
)
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
@@ -19,9 +18,7 @@ from products.alerts_platform.backend.facade.contracts import (
LegacyEventEmitter,
LegacyWebhookBody,
SourceDescriber,
- SourceFacts,
SourceKind,
- TransitionEventProducer,
)
if TYPE_CHECKING:
@@ -69,13 +66,3 @@ def has_legacy_event_emitter(source: SourceKind) -> bool:
def native_sends_legacy_webhook_body(source: SourceKind, team: Team) -> bool | None:
"""Whether a stock webhook receives the body its HogFunction sent when delivered natively. None when unknown."""
return legacy_webhook.native_sends_legacy_body(source, team)
-
-
-def register_transition_event_producer(producer: TransitionEventProducer) -> None:
- """The product that produces internal events puts the platform's `$alert_transition` events on the topic."""
- transition_events.register_producer(producer)
-
-
-def register_source_facts(source: SourceKind, facts: SourceFacts) -> None:
- """A source's facts ride on each `$alert_transition` under the property names its own alert events used."""
- transition_events.register_source_facts(source, facts)
diff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.py
index 5f7fb5ddfe55..c6a05c1934e4 100644
--- a/products/alerts_platform/backend/temporal/metrics.py
+++ b/products/alerts_platform/backend/temporal/metrics.py
@@ -172,13 +172,6 @@ def increment_root_edit_failures(provider: str) -> None:
).add(1)
-def increment_transition_events_emitted(source: str, count: int) -> None:
- get_metric_meter({"source": source}).create_counter(
- "alerts_platform_transition_events_emitted_total",
- "$alert_transition events put on the internal events topic",
- ).add(count)
-
-
def increment_deliveries_previewed(source: str) -> None:
get_metric_meter({"source": source}).create_counter(
"alerts_platform_deliveries_previewed_total",
diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.py
index 46ca4fe28e18..9f0bf83e04de 100644
--- a/products/alerts_platform/backend/temporal/workflows.py
+++ b/products/alerts_platform/backend/temporal/workflows.py
@@ -22,7 +22,6 @@ from posthog.temporal.common.logger import get_write_only_logger
from products.alerts_platform.backend.temporal.metrics import (
increment_deliveries_previewed,
increment_discovery_omitted,
- increment_transition_events_emitted,
safe_record,
)
from products.alerts_platform.backend.temporal.outcomes import alerts_platform_record_outcomes_activity
@@ -37,7 +36,7 @@ with workflow.unsafe.imports_passed_through():
from posthog.sync import database_sync_to_async_pool
- from products.alerts_platform.backend.delivery.evaluation import deliver_evaluation, emit_transition_events
+ from products.alerts_platform.backend.delivery.evaluation import deliver_evaluation
from products.alerts_platform.backend.delivery.thread_store import PENDING_CLAIM_TTL, ThreadBusy
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
@@ -81,14 +80,18 @@ DELIVERY_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=30)
# DELIVERY_SCHEDULE_TO_CLOSE, which is shorter than PENDING_CLAIM_TTL. A claim that a dead
# attempt left looks fresh to every one of those retries.
BUSY_RETRY_DELAY = dt.timedelta(seconds=20)
-# Delivery runs started before the transition events existed replay without them.
+# A delivery run that recorded TRANSITION_EVENTS_PATCH and not NO_TRANSITION_EVENTS_PATCH still
+# schedules the emit activity, so its replay matches its history. Once no such run can be open
+# (under five minutes per part after the deploy that added NO_TRANSITION_EVENTS_PATCH), delete
+# that branch, TRANSITION_EVENTS_PATCH and the activity. Replace the check with
+# `workflow.deprecate_patch(NO_TRANSITION_EVENTS_PATCH)`: every newer run carries that marker.
TRANSITION_EVENTS_PATCH = "alerts-platform-transition-events"
+NO_TRANSITION_EVENTS_PATCH = "alerts-platform-no-transition-events"
# From the first busy result to the start of a later attempt. An attempt that starts this late
# finds every claim the first one saw already stale, so a thread still held is a newer send's.
BUSY_WAIT_LIMIT = PENDING_CLAIM_TTL + BUSY_RETRY_DELAY
-# One schedule-to-close for the transition events and three for the send attempts. The last send
-# attempt can start one attempt and one delay past the limit.
-DELIVERY_EXECUTION_TIMEOUT = 4 * DELIVERY_SCHEDULE_TO_CLOSE + BUSY_WAIT_LIMIT + BUSY_RETRY_DELAY
+# The last attempt can start one attempt and one delay past the limit.
+DELIVERY_EXECUTION_TIMEOUT = 3 * DELIVERY_SCHEDULE_TO_CLOSE + BUSY_WAIT_LIMIT + BUSY_RETRY_DELAY
@frozen
@@ -120,20 +123,8 @@ async def alerts_platform_deliver_activity() -> None:
@activity.defn
async def alerts_platform_emit_transitions_activity(request: AlertDeliveryRequest) -> None:
- """Emits the `$alert_transition` events of one evaluation, apart from native delivery.
-
- Its own activity, so a held thread or a failing destination never delays or repeats them.
- """
- emitted = await database_sync_to_async_pool(emit_transition_events)(request)
- if emitted:
- await LOGGER.ainfo(
- "alerts_platform_transition_events_emitted",
- source=request.source.value,
- configuration_id=request.configuration_id,
- evaluation_key=request.evaluation_key,
- emitted=emitted,
- )
- safe_record(increment_transition_events_emitted, request.source.value, emitted)
+ """Emits nothing. Only a run that recorded TRANSITION_EVENTS_PATCH schedules it, and the flag that
+ enabled the event was never on, so the run gets the result it always got."""
@activity.defn
@@ -187,16 +178,14 @@ class AlertsPlatformDeliverPreviewWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: AlertDeliveryRequest) -> None:
- """Emits every part's transition events, then delivers each part in turn.
+ """Delivers each part in turn, so a split evaluation's sends to one destination never overlap.
- Emission comes first for every part, so a held thread on one part never delays another
- part's events. Parts deliver in turn, so a split evaluation's sends to one destination
- never overlap. A failure does not stop the steps after it. The first failure fails the
- run once every part has had its attempts, a failed send before a failed emission.
+ A part that fails does not stop the parts after it. The first failure fails the run once
+ every part has had its attempts, a failed send before a failed emission.
"""
parts = [inputs] if inputs.parts <= 1 else [replace(inputs, part=part) for part in range(inputs.parts)]
emission_failures: list[ActivityError] = []
- if workflow.patched(TRANSITION_EVENTS_PATCH):
+ if not workflow.patched(NO_TRANSITION_EVENTS_PATCH) and workflow.patched(TRANSITION_EVENTS_PATCH):
for request in parts:
try:
await self._emit(request)
diff --git a/products/alerts_platform/backend/tests/histories/split_delivery_with_transition_events.json b/products/alerts_platform/backend/tests/histories/split_delivery_with_transition_events.json
new file mode 100644
index 000000000000..771d49ce88f9
--- /dev/null
+++ b/products/alerts_platform/backend/tests/histories/split_delivery_with_transition_events.json
@@ -0,0 +1,535 @@
+{
+ "events": [
+ {
+ "eventId": "1",
+ "eventTime": "2026-10-21T18:32:52.539Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",
+ "workflowExecutionStartedEventAttributes": {
+ "workflowType": {
+ "name": "alerts-platform-deliver-preview"
+ },
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJjb25maWd1cmF0aW9uX2lkIjoiY2ZnLTEiLCJkZXN0aW5hdGlvbl9hbGVydF9pZCI6ImxlZ2FjeS0xIiwiZXZhbHVhdGlvbl9rZXkiOiJldmFsLTEiLCJldmVudF9pZHNfYnlfaW5jaWRlbnRfYWN0aW9uIjp7fSwiZXZlbnRfaWRzX2J5X2tpbmQiOnt9LCJpbmNpZGVudF9hY3Rpb25zIjp7fSwib3ZlcmZsb3dlZCI6MCwib3duZWRfYnlfcGxhdGZvcm0iOmZhbHNlLCJwYXJ0IjowLCJwYXJ0cyI6Miwic2VuZHNfbWVzc2FnZXMiOnRydWUsInNvdXJjZSI6ImxvZ3MiLCJzb3VyY2VfYWxlcnRfdXJsIjpudWxsLCJ0ZWFtX2lkIjoxfQ=="
+ }
+ ]
+ },
+ "workflowExecutionTimeout": "560s",
+ "workflowRunTimeout": "560s",
+ "workflowTaskTimeout": "10s",
+ "originalExecutionRunId": "99daf229-1863-45a7-9a0a-3ed6624adca3",
+ "identity": "test-worker",
+ "firstExecutionRunId": "99daf229-1863-45a7-9a0a-3ed6624adca3",
+ "attempt": 1,
+ "firstWorkflowTaskBackoff": "0s",
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "2",
+ "eventTime": "2026-10-21T18:32:52.539Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "3",
+ "eventTime": "2026-10-21T18:32:52.540Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "2",
+ "identity": "test-worker",
+ "historySizeBytes": "626"
+ }
+ },
+ {
+ "eventId": "4",
+ "eventTime": "2026-10-21T18:32:52.553Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "2",
+ "identity": "test-worker",
+ "binaryChecksum": "eba286eda5a8c68ffe6049bfacaa1b9a",
+ "sdkMetadata": {
+ "coreUsedFlags": [2, 1, 3],
+ "sdkName": "temporal-python",
+ "sdkVersion": "1.33.0"
+ },
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "5",
+ "eventTime": "2026-10-21T18:32:52.553Z",
+ "eventType": "EVENT_TYPE_MARKER_RECORDED",
+ "markerRecordedEventAttributes": {
+ "markerName": "core_patch",
+ "details": {
+ "patch-data": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJpZCI6ImFsZXJ0cy1wbGF0Zm9ybS10cmFuc2l0aW9uLWV2ZW50cyIsImRlcHJlY2F0ZWQiOmZhbHNlfQ=="
+ }
+ ]
+ }
+ },
+ "workflowTaskCompletedEventId": "3"
+ }
+ },
+ {
+ "eventId": "6",
+ "eventTime": "2026-10-21T18:32:52.553Z",
+ "eventType": "EVENT_TYPE_UPSERT_WORKFLOW_SEARCH_ATTRIBUTES",
+ "upsertWorkflowSearchAttributesEventAttributes": {
+ "workflowTaskCompletedEventId": "3",
+ "searchAttributes": {
+ "indexedFields": {
+ "TemporalChangeVersion": {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg==",
+ "type": "S2V5d29yZExpc3Q="
+ },
+ "data": "WyJhbGVydHMtcGxhdGZvcm0tdHJhbnNpdGlvbi1ldmVudHMiXQ=="
+ }
+ }
+ }
+ }
+ },
+ {
+ "eventId": "7",
+ "eventTime": "2026-10-21T18:32:52.553Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "1",
+ "activityType": {
+ "name": "alerts_platform_emit_transitions_activity"
+ },
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJjb25maWd1cmF0aW9uX2lkIjoiY2ZnLTEiLCJkZXN0aW5hdGlvbl9hbGVydF9pZCI6ImxlZ2FjeS0xIiwiZXZhbHVhdGlvbl9rZXkiOiJldmFsLTEiLCJldmVudF9pZHNfYnlfaW5jaWRlbnRfYWN0aW9uIjp7fSwiZXZlbnRfaWRzX2J5X2tpbmQiOnt9LCJpbmNpZGVudF9hY3Rpb25zIjp7fSwib3ZlcmZsb3dlZCI6MCwib3duZWRfYnlfcGxhdGZvcm0iOmZhbHNlLCJwYXJ0IjowLCJwYXJ0cyI6Miwic2VuZHNfbWVzc2FnZXMiOnRydWUsInNvdXJjZSI6ImxvZ3MiLCJzb3VyY2VfYWxlcnRfdXJsIjpudWxsLCJ0ZWFtX2lkIjoxfQ=="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "30s",
+ "scheduleToStartTimeout": "30s",
+ "startToCloseTimeout": "10s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "3",
+ "retryPolicy": {
+ "initialInterval": "1s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "100s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "8",
+ "eventTime": "2026-10-21T18:32:52.554Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "7",
+ "identity": "test-worker",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "9",
+ "eventTime": "2026-10-21T18:32:52.555Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "YmluYXJ5L251bGw="
+ }
+ }
+ ]
+ },
+ "scheduledEventId": "7",
+ "startedEventId": "8",
+ "identity": "test-worker"
+ }
+ },
+ {
+ "eventId": "10",
+ "eventTime": "2026-10-21T18:32:52.555Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "11",
+ "eventTime": "2026-10-21T18:32:52.555Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "10",
+ "identity": "test-worker",
+ "historySizeBytes": "1774"
+ }
+ },
+ {
+ "eventId": "12",
+ "eventTime": "2026-10-21T18:32:52.556Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "10",
+ "identity": "test-worker",
+ "binaryChecksum": "eba286eda5a8c68ffe6049bfacaa1b9a",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "13",
+ "eventTime": "2026-10-21T18:32:52.556Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "2",
+ "activityType": {
+ "name": "alerts_platform_emit_transitions_activity"
+ },
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJjb25maWd1cmF0aW9uX2lkIjoiY2ZnLTEiLCJkZXN0aW5hdGlvbl9hbGVydF9pZCI6ImxlZ2FjeS0xIiwiZXZhbHVhdGlvbl9rZXkiOiJldmFsLTEiLCJldmVudF9pZHNfYnlfaW5jaWRlbnRfYWN0aW9uIjp7fSwiZXZlbnRfaWRzX2J5X2tpbmQiOnt9LCJpbmNpZGVudF9hY3Rpb25zIjp7fSwib3ZlcmZsb3dlZCI6MCwib3duZWRfYnlfcGxhdGZvcm0iOmZhbHNlLCJwYXJ0IjoxLCJwYXJ0cyI6Miwic2VuZHNfbWVzc2FnZXMiOnRydWUsInNvdXJjZSI6ImxvZ3MiLCJzb3VyY2VfYWxlcnRfdXJsIjpudWxsLCJ0ZWFtX2lkIjoxfQ=="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "30s",
+ "scheduleToStartTimeout": "30s",
+ "startToCloseTimeout": "10s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "11",
+ "retryPolicy": {
+ "initialInterval": "1s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "100s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "14",
+ "eventTime": "2026-10-21T18:32:52.557Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "13",
+ "identity": "test-worker",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "15",
+ "eventTime": "2026-10-21T18:32:52.557Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "YmluYXJ5L251bGw="
+ }
+ }
+ ]
+ },
+ "scheduledEventId": "13",
+ "startedEventId": "14",
+ "identity": "test-worker"
+ }
+ },
+ {
+ "eventId": "16",
+ "eventTime": "2026-10-21T18:32:52.557Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "17",
+ "eventTime": "2026-10-21T18:32:52.557Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "16",
+ "identity": "test-worker",
+ "historySizeBytes": "2616"
+ }
+ },
+ {
+ "eventId": "18",
+ "eventTime": "2026-10-21T18:32:52.558Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "16",
+ "identity": "test-worker",
+ "binaryChecksum": "eba286eda5a8c68ffe6049bfacaa1b9a",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "19",
+ "eventTime": "2026-10-21T18:32:52.558Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "3",
+ "activityType": {
+ "name": "alerts_platform_deliver_preview_activity"
+ },
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJjb25maWd1cmF0aW9uX2lkIjoiY2ZnLTEiLCJkZXN0aW5hdGlvbl9hbGVydF9pZCI6ImxlZ2FjeS0xIiwiZXZhbHVhdGlvbl9rZXkiOiJldmFsLTEiLCJldmVudF9pZHNfYnlfaW5jaWRlbnRfYWN0aW9uIjp7fSwiZXZlbnRfaWRzX2J5X2tpbmQiOnt9LCJpbmNpZGVudF9hY3Rpb25zIjp7fSwib3ZlcmZsb3dlZCI6MCwib3duZWRfYnlfcGxhdGZvcm0iOmZhbHNlLCJwYXJ0IjowLCJwYXJ0cyI6Miwic2VuZHNfbWVzc2FnZXMiOnRydWUsInNvdXJjZSI6ImxvZ3MiLCJzb3VyY2VfYWxlcnRfdXJsIjpudWxsLCJ0ZWFtX2lkIjoxfQ=="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "30s",
+ "scheduleToStartTimeout": "30s",
+ "startToCloseTimeout": "10s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "17",
+ "retryPolicy": {
+ "initialInterval": "1s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "100s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "20",
+ "eventTime": "2026-10-21T18:32:52.558Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "19",
+ "identity": "test-worker",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "21",
+ "eventTime": "2026-10-21T18:32:52.559Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "YmluYXJ5L251bGw="
+ }
+ }
+ ]
+ },
+ "scheduledEventId": "19",
+ "startedEventId": "20",
+ "identity": "test-worker"
+ }
+ },
+ {
+ "eventId": "22",
+ "eventTime": "2026-10-21T18:32:52.559Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "23",
+ "eventTime": "2026-10-21T18:32:52.559Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "22",
+ "identity": "test-worker",
+ "historySizeBytes": "3457"
+ }
+ },
+ {
+ "eventId": "24",
+ "eventTime": "2026-10-21T18:32:52.561Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "22",
+ "identity": "test-worker",
+ "binaryChecksum": "eba286eda5a8c68ffe6049bfacaa1b9a",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "25",
+ "eventTime": "2026-10-21T18:32:52.561Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED",
+ "activityTaskScheduledEventAttributes": {
+ "activityId": "4",
+ "activityType": {
+ "name": "alerts_platform_deliver_preview_activity"
+ },
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue",
+ "kind": "TASK_QUEUE_KIND_NORMAL"
+ },
+ "header": {},
+ "input": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "anNvbi9wbGFpbg=="
+ },
+ "data": "eyJjb25maWd1cmF0aW9uX2lkIjoiY2ZnLTEiLCJkZXN0aW5hdGlvbl9hbGVydF9pZCI6ImxlZ2FjeS0xIiwiZXZhbHVhdGlvbl9rZXkiOiJldmFsLTEiLCJldmVudF9pZHNfYnlfaW5jaWRlbnRfYWN0aW9uIjp7fSwiZXZlbnRfaWRzX2J5X2tpbmQiOnt9LCJpbmNpZGVudF9hY3Rpb25zIjp7fSwib3ZlcmZsb3dlZCI6MCwib3duZWRfYnlfcGxhdGZvcm0iOmZhbHNlLCJwYXJ0IjoxLCJwYXJ0cyI6Miwic2VuZHNfbWVzc2FnZXMiOnRydWUsInNvdXJjZSI6ImxvZ3MiLCJzb3VyY2VfYWxlcnRfdXJsIjpudWxsLCJ0ZWFtX2lkIjoxfQ=="
+ }
+ ]
+ },
+ "scheduleToCloseTimeout": "30s",
+ "scheduleToStartTimeout": "30s",
+ "startToCloseTimeout": "10s",
+ "heartbeatTimeout": "0s",
+ "workflowTaskCompletedEventId": "23",
+ "retryPolicy": {
+ "initialInterval": "1s",
+ "backoffCoefficient": 2.0,
+ "maximumInterval": "100s",
+ "maximumAttempts": 3
+ },
+ "priority": {}
+ }
+ },
+ {
+ "eventId": "26",
+ "eventTime": "2026-10-21T18:32:52.561Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_STARTED",
+ "activityTaskStartedEventAttributes": {
+ "scheduledEventId": "25",
+ "identity": "test-worker",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "27",
+ "eventTime": "2026-10-21T18:32:52.562Z",
+ "eventType": "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
+ "activityTaskCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "YmluYXJ5L251bGw="
+ }
+ }
+ ]
+ },
+ "scheduledEventId": "25",
+ "startedEventId": "26",
+ "identity": "test-worker"
+ }
+ },
+ {
+ "eventId": "28",
+ "eventTime": "2026-10-21T18:32:52.562Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED",
+ "workflowTaskScheduledEventAttributes": {
+ "taskQueue": {
+ "name": "alerts-platform-delivery-task-queue"
+ },
+ "startToCloseTimeout": "10s",
+ "attempt": 1
+ }
+ },
+ {
+ "eventId": "29",
+ "eventTime": "2026-10-21T18:32:52.562Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED",
+ "workflowTaskStartedEventAttributes": {
+ "scheduledEventId": "28",
+ "identity": "test-worker",
+ "historySizeBytes": "4298"
+ }
+ },
+ {
+ "eventId": "30",
+ "eventTime": "2026-10-21T18:32:52.563Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED",
+ "workflowTaskCompletedEventAttributes": {
+ "scheduledEventId": "28",
+ "identity": "test-worker",
+ "binaryChecksum": "eba286eda5a8c68ffe6049bfacaa1b9a",
+ "sdkMetadata": {},
+ "meteringMetadata": {}
+ }
+ },
+ {
+ "eventId": "31",
+ "eventTime": "2026-10-21T18:32:52.563Z",
+ "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",
+ "workflowExecutionCompletedEventAttributes": {
+ "result": {
+ "payloads": [
+ {
+ "metadata": {
+ "encoding": "YmluYXJ5L251bGw="
+ }
+ }
+ ]
+ },
+ "workflowTaskCompletedEventId": "29"
+ }
+ }
+ ]
+}
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index 251a7e5f816b..a98207caf1cb 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -10,13 +10,9 @@ from unittest.mock import patch
from parameterized import parameterized
-from products.alerts_platform.backend.delivery import delivery_paths, legacy_webhook, transition_events
+from products.alerts_platform.backend.delivery import delivery_paths, legacy_webhook
from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
-from products.alerts_platform.backend.delivery.evaluation import (
- LIVE_DELIVERY_FLAG,
- deliver_evaluation,
- emit_transition_events,
-)
+from products.alerts_platform.backend.delivery.evaluation import LIVE_DELIVERY_FLAG, deliver_evaluation
from products.alerts_platform.backend.delivery.legacy_webhook import LEGACY_WEBHOOK_BODY_FLAG
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.thread_store import ThreadBusy
@@ -33,7 +29,6 @@ from products.alerts_platform.backend.facade.contracts import (
IncidentAction,
LegacyEventEmission,
SourceKind,
- TransitionEvent,
)
from products.alerts_platform.backend.models import PlatformAlertConfiguration
@@ -516,112 +511,16 @@ class TestDeliverEvaluation(APIBaseTest):
# 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
- assert SourceKind.LOGS in transition_events._source_facts
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 transition_events._producer is not None
assert (
list_alert_destination_groups(team_id=self.team.id, alert_id="unknown", allowed_event_ids=[FIRING_EVENT])
== []
)
-class TestTransitionEvents(APIBaseTest):
- def _emit(
- self,
- announced: EvaluationAnnouncement | None,
- *,
- transition_flag: bool = True,
- live: bool = False,
- owned_by_platform: bool = True,
- sends_messages: bool = True,
- facts: Any = None,
- ) -> list[TransitionEvent]:
- produced: list[TransitionEvent] = []
-
- def produce(*, team_id: int, configuration_id: str, events: list[TransitionEvent]) -> None:
- produced.extend(events)
-
- def flag_enabled(flag: str, *args: Any, **kwargs: Any) -> bool:
- return transition_flag if flag == transition_events.TRANSITION_EVENT_FLAG else live
-
- with (
- patch(
- "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
- side_effect=flag_enabled,
- ),
- patch(f"{_MODULE}.announcement", return_value=announced),
- patch.object(transition_events, "_producer", produce),
- patch.dict(transition_events._source_facts, {SourceKind.LOGS: facts} if facts else {}, clear=True),
- ):
- emitted = emit_transition_events(
- _request(self.team.id, owned_by_platform=owned_by_platform, sends_messages=sends_messages)
- )
- assert emitted == len(produced)
- return produced
-
- @parameterized.expand(
- [
- ("platform_owned", {}, 1),
- ("flag_off", {"transition_flag": False}, 0),
- ("source_still_delivers", {"owned_by_platform": False}, 0),
- ("source_owned_on_live_delivery", {"owned_by_platform": False, "live": True}, 1),
- ("incident_only_delivery", {"sends_messages": False}, 0),
- ]
- )
- def test_an_alert_emits_only_where_the_platform_contacts_its_team(
- self, _name: str, gates: dict[str, bool], expected: int
- ) -> None:
- assert len(self._emit(_announcement(_transition(AlertEventKind.FIRING)), **gates)) == expected
-
- def test_each_transition_carries_the_platform_fields_and_the_source_facts(self) -> None:
- firing = replace(_transition(AlertEventKind.FIRING), value=12.0, labels={"service": "api"})
- errored = replace(_transition(AlertEventKind.ERRORED, episode_started_at=None), error_message="timeout")
- announced = replace(_announcement(firing, errored), consecutive_failures=2)
-
- def facts(*, transition: AnnouncedTransition, **_kwargs: Any) -> dict[str, Any]:
- return {"alert_id": "legacy-1", "result_count": transition.value}
-
- events = self._emit(announced, facts=facts)
-
- assert [event.properties for event in events] == [
- {
- "alert_configuration_id": "cfg-1",
- "alert_name": "API errors",
- "source_kind": "logs",
- "transition": "firing",
- "occurred_at": FIRING.isoformat(),
- "episode_started_at": FIRING.isoformat(),
- "value": 12.0,
- "labels": {"service": "api"},
- "grouping_key": "",
- "error_message": None,
- "consecutive_failures": None,
- "url": "",
- "source": {"alert_id": "legacy-1", "result_count": 12.0},
- },
- {
- "alert_configuration_id": "cfg-1",
- "alert_name": "API errors",
- "source_kind": "logs",
- "transition": "errored",
- "occurred_at": FIRING.isoformat(),
- "episode_started_at": None,
- "value": None,
- "labels": {},
- "grouping_key": "",
- "error_message": "timeout",
- "consecutive_failures": 2,
- "url": "",
- "source": {"alert_id": "legacy-1", "result_count": None},
- },
- ]
- assert [event.uuid for event in events] == [event.uuid for event in self._emit(announced, facts=facts)]
- assert events[0].uuid != events[1].uuid
-
-
class TestDeliveryPath(APIBaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/products/alerts_platform/backend/tests/test_temporal_workflows.py b/products/alerts_platform/backend/tests/test_temporal_workflows.py
index 635b52e81c48..3a0273edfd2a 100644
--- a/products/alerts_platform/backend/tests/test_temporal_workflows.py
+++ b/products/alerts_platform/backend/tests/test_temporal_workflows.py
@@ -3,6 +3,7 @@ import asyncio
import logging
import datetime as dt
from collections.abc import AsyncIterator, Iterator
+from pathlib import Path
from typing import Literal
import pytest
@@ -18,7 +19,7 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanE
from parameterized import parameterized
from temporalio import activity, workflow
from temporalio.api.enums.v1 import EventType
-from temporalio.client import WorkflowExecutionStatus, WorkflowFailureError
+from temporalio.client import WorkflowExecutionStatus, WorkflowFailureError, WorkflowHistory
from temporalio.common import SearchAttributeKey, SearchAttributePair, TypedSearchAttributes
from temporalio.contrib.opentelemetry import OpenTelemetryPlugin
from temporalio.exceptions import (
@@ -81,11 +82,6 @@ class CloseAfterChildStartWorkflow:
await workflow.wait_condition(lambda: False)
[email protected](name="alerts_platform_emit_transitions_activity")
-async def emit_nothing(request: AlertDeliveryRequest) -> None:
- pass
-
-
@pytest.fixture(scope="module")
def sdk_metrics() -> MetricBuffer:
return MetricBuffer(10000)
@@ -351,7 +347,7 @@ async def test_delivery_waits_out_a_held_thread_and_fails_when_it_never_frees(
environment.client,
task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
workflows=DELIVERY_WORKFLOWS,
- activities=[held_thread, emit_nothing],
+ activities=[held_thread],
workflow_runner=UnsandboxedWorkflowRunner(),
):
handle = await environment.client.start_workflow(
@@ -379,7 +375,7 @@ async def test_delivery_waits_out_a_held_thread_and_fails_when_it_never_frees(
@pytest.mark.asyncio
-async def test_a_split_delivery_emits_every_part_then_sends_every_part_in_turn_even_after_one_fails(
+async def test_a_split_delivery_sends_every_part_in_turn_even_after_one_fails(
environment: WorkflowEnvironment,
) -> None:
steps: list[str] = []
@@ -420,50 +416,16 @@ async def test_a_split_delivery_emits_every_part_then_sends_every_part_in_turn_e
await handle.result()
assert isinstance(failure.value.cause, ActivityError)
- assert steps == ["emit 0", "emit 1", "emit 2", "send 0", "send 1", "send 2"]
+ assert steps == ["send 0", "send 1", "send 2"]
@pytest.mark.asyncio
-async def test_a_failed_transition_emission_still_sends_the_messages_then_fails_the_run(
- environment: WorkflowEnvironment,
-) -> None:
- calls: list[str] = []
-
- @activity.defn(name="alerts_platform_emit_transitions_activity")
- async def emit(request: AlertDeliveryRequest) -> None:
- calls.append("emit")
- raise ApplicationError("broker refused", non_retryable=True)
-
- @activity.defn(name="alerts_platform_deliver_preview_activity")
- async def deliver(request: AlertDeliveryRequest) -> None:
- calls.append("deliver")
-
- async with Worker(
- environment.client,
- task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
- workflows=DELIVERY_WORKFLOWS,
- activities=[emit, deliver],
- workflow_runner=UnsandboxedWorkflowRunner(),
- ):
- handle = await environment.client.start_workflow(
- "alerts-platform-deliver-preview",
- AlertDeliveryRequest(
- source=SourceKind.LOGS,
- team_id=1,
- configuration_id="cfg-1",
- evaluation_key="eval-1",
- destination_alert_id="legacy-1",
- event_ids_by_kind={},
- ),
- id=str(uuid.uuid4()),
- task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
- execution_timeout=DELIVERY_EXECUTION_TIMEOUT,
- )
- with pytest.raises(WorkflowFailureError) as failure:
- await handle.result()
-
- assert isinstance(failure.value.cause, ActivityError)
- assert calls == ["emit", "deliver"]
+async def test_a_delivery_that_emitted_transition_events_before_the_removal_still_replays() -> None:
+ history = WorkflowHistory.from_json(
+ "alerts-deliver-preview-cfg-1:eval-1",
+ (Path(__file__).parent / "histories" / "split_delivery_with_transition_events.json").read_text(),
+ )
+ await Replayer(workflows=DELIVERY_WORKFLOWS, workflow_runner=UnsandboxedWorkflowRunner()).replay_workflow(history)
@pytest.mark.parametrize("timeout_type", [TimeoutType.START_TO_CLOSE, TimeoutType.SCHEDULE_TO_CLOSE])
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index a9713f91b720..fab12008b345 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -218,16 +218,15 @@ class TestHogFunctionAPIWithoutAvailableFeature(ClickhouseTestMixin, APIBaseTest
self.assertEqual(response.json()["attr"], "filters")
self.assertIn("managed through the alert API", response.json()["detail"])
- @parameterized.expand([("$workflow_step_resume",), ("$alert_transition",)])
- def test_generic_api_cannot_subscribe_to_reserved_internal_events(self, event_id: str):
+ def test_generic_api_cannot_subscribe_to_reserved_internal_events(self):
response = self.client.post(
f"/api/projects/{self.team.id}/hog_functions/",
data={
- "name": "Reserved event exfiltration",
+ "name": "Workflow result exfiltration",
"hog": "fetch('https://example.com');",
"type": "internal_destination",
"enabled": True,
- "filters": {"events": [{"id": event_id, "type": "events"}]},
+ "filters": {"events": [{"id": "$workflow_step_resume", "type": "events"}]},
},
)
diff --git a/products/cdp/backend/internal_events.py b/products/cdp/backend/internal_events.py
index 893b628c9709..b2add5ecd302 100644
--- a/products/cdp/backend/internal_events.py
+++ b/products/cdp/backend/internal_events.py
@@ -25,13 +25,10 @@ _MANAGED_ALERT_EVENT = re.compile(MANAGED_ALERT_EVENT_PATTERN)
WORKFLOW_STEP_RESUME_EVENT = "$workflow_step_resume"
-# The alerts platform's transition event. Its properties carry the source product's alert data.
-ALERT_TRANSITION_EVENT = "$alert_transition"
-
# Internal events that only the product which emits them may consume. A user-created
# destination cannot subscribe to one, because its properties carry that product's data and
# forwarding them off-platform would bypass the read permission the product enforces on it.
-RESERVED_INTERNAL_EVENTS = frozenset({WORKFLOW_STEP_RESUME_EVENT, ALERT_TRANSITION_EVENT})
+RESERVED_INTERNAL_EVENTS = frozenset({WORKFLOW_STEP_RESUME_EVENT})
def is_reserved_internal_event(event_name: object) -> bool:
diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.py
index 13fd2994d36c..6246504e20ca 100644
--- a/products/logs/backend/apps.py
+++ b/products/logs/backend/apps.py
@@ -14,21 +14,17 @@ class LogsConfig(AppConfig):
# HogQL into django.setup() for every process type.
# - The alerts platform cannot import this product, so native alert messages get the logs
# wording, grandfathered webhooks the legacy logs body, alerts on the HogFunction path
- # their `$logs_alert_*` events, `$alert_transition` the logs source facts, and the platform
- # API the logs `source_config` schema, through the functions registered below.
+ # their `$logs_alert_*` events, and the platform API the logs `source_config` schema,
+ # 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,
- register_source_facts,
)
from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415
from products.logs.backend import activity_logging # noqa: F401, PLC0415
- from products.logs.backend.platform_alert_legacy_events import ( # noqa: PLC0415
- emit_logs_legacy_events,
- logs_source_facts,
- )
+ 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,
@@ -38,5 +34,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)
- register_source_facts(SourceKind.LOGS, logs_source_facts)
register_source_config(SourceKind.LOGS, load_logs_source_config)
diff --git a/products/logs/backend/platform_alert_legacy_events.py b/products/logs/backend/platform_alert_legacy_events.py
index 3eebe3685188..bf302e745008 100644
--- a/products/logs/backend/platform_alert_legacy_events.py
+++ b/products/logs/backend/platform_alert_legacy_events.py
@@ -66,19 +66,6 @@ def emit_logs_legacy_events(
)
-def logs_source_facts(
- *, request: AlertDeliveryRequest, announcement: EvaluationAnnouncement, transition: AnnouncedTransition
-) -> dict[str, Any]:
- """The properties of the `$logs_alert_*` message event for this transition, for `$alert_transition` to carry."""
- alert = _Alert(
- team_id=request.team_id,
- alert_id=request.destination_alert_id,
- alert_name=announcement.alert_name,
- consecutive_failures=announcement.consecutive_failures,
- )
- return _message_event(in_utc(transition), alert).properties
-
-
@frozen
class _Alert:
team_id: int