Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): add the HogFunction delivery path for platform-owned alerts (#118873)

Jimmy Zhu9cd28d4d366a
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 5349a622e2f6..84d4526bf5fa 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -414,6 +414,7 @@ rules:
|SubscriptionDelivery
|PlatformAlert
|PlatformAlertConfiguration
+ |PlatformAlertDeliveryPath
|PlatformAlertThread
|Survey
|SurveyResponseArchive
@@ -875,6 +876,7 @@ rules:
|SubscriptionDelivery
|PlatformAlert
|PlatformAlertConfiguration
+ |PlatformAlertDeliveryPath
|PlatformAlertThread
|Survey
|SurveyResponseArchive
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 400ec66aa8c4..62a6622ec845 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -7,8 +7,9 @@ an insight alert means.
from __future__ import annotations
+from datetime import datetime
from enum import StrEnum
-from typing import Final
+from typing import Any, Final
from uuid import UUID
from posthog.dataclasses import frozen
@@ -96,3 +97,18 @@ class FiringAlert:
name: str
insight_name: str | None
insight_short_id: str
+
+
+@frozen
+class AlertInternalEvent:
+ """One internal event that makes an alert's HogFunction destinations fire."""
+
+ event_name: str
+ properties: dict[str, Any]
+ timestamp: datetime
+ # Stable across attempts, so a receiver can drop an event a retry emits again.
+ uuid: str
+
+
+class AlertInternalEventsNotDelivered(Exception):
+ """The broker did not take every event, so the caller retries."""
diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.py
index da008a349720..35ff5ce90fd1 100644
--- a/products/alerts/backend/facade/destinations.py
+++ b/products/alerts/backend/facade/destinations.py
@@ -34,7 +34,7 @@ from ..logic import (
destinations,
insight_alert_destinations,
)
-from .contracts import DestinationBucket, DestinationEligibility
+from .contracts import AlertInternalEvent, DestinationBucket, DestinationEligibility
ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0
@@ -219,6 +219,18 @@ def alert_internal_event_delivered(
)
+def emit_alert_internal_events(
+ *, team_id: int, alert_id: str, events: Sequence[AlertInternalEvent], flush_timeout_seconds: float
+) -> None:
+ """Enqueue the events and wait for the broker. Raises `AlertInternalEventsNotDelivered` when it took not all of them.
+
+ Each event's `uuid` is what lets a receiver drop the copy a retry emits.
+ """
+ destinations.emit_alert_internal_events(
+ team_id=team_id, alert_id=alert_id, events=events, flush_timeout_seconds=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/logic/destinations.py b/products/alerts/backend/logic/destinations.py
index bf4200c08a40..e9c27296b66a 100644
--- a/products/alerts/backend/logic/destinations.py
+++ b/products/alerts/backend/logic/destinations.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import re
-from collections.abc import Collection
+from collections.abc import Collection, Sequence
from datetime import datetime
from typing import Any, NamedTuple, cast
from uuid import UUID
@@ -19,6 +19,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.client import ProduceResult
from posthog.plugins.plugin_server_api import reload_hog_functions_on_workers
+from products.alerts.backend.facade.contracts import AlertInternalEvent, AlertInternalEventsNotDelivered
from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID, url_hostname
from products.alerts_platform.backend.facade.contracts import (
ActiveAlertDestination,
@@ -501,3 +502,33 @@ def alert_internal_event_delivered(
ALERT_INTERNAL_EVENT_DELIVERY_FAILURES.labels(event_name=event_name).inc()
logger.warning("Alert internal event was not delivered", error=str(error), **context)
return False
+
+
+def emit_alert_internal_events(
+ *, team_id: int, alert_id: str, events: Sequence[AlertInternalEvent], flush_timeout_seconds: float
+) -> None:
+ """Produce the events and return once the broker took all of them. Raise otherwise."""
+ pending = [
+ (
+ event.event_name,
+ produce_alert_internal_event(
+ team_id=team_id,
+ event_name=event.event_name,
+ properties=event.properties,
+ timestamp=event.timestamp,
+ uuid=event.uuid,
+ ),
+ )
+ for event in events
+ ]
+ if not pending:
+ return
+ flush_alert_internal_events(flush_timeout_seconds)
+ undelivered = [
+ event_name
+ for event_name, result in pending
+ if result is None
+ or not alert_internal_event_delivered(result, team_id=team_id, alert_id=alert_id, event_name=event_name)
+ ]
+ if undelivered:
+ raise AlertInternalEventsNotDelivered(f"{len(undelivered)} of {len(pending)} alert events were not delivered")
diff --git a/products/alerts_platform/backend/delivery/delivery_paths.py b/products/alerts_platform/backend/delivery/delivery_paths.py
new file mode 100644
index 000000000000..aaf3e358813b
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/delivery_paths.py
@@ -0,0 +1,63 @@
+"""Which path an alert the platform owns delivers through: native, or its source's HogFunctions.
+
+Native delivery reproduces a stock destination only. A destination a person customized keeps
+sending through its HogFunction, which the source feeds by emitting the internal events its own
+stack emitted. Two products plug in here when Django starts, because the platform imports neither:
+
+- the product that owns destinations registers the chooser, which reads them at send time;
+- each source registers the emitter for its own events.
+
+A source with no emitter delivers every alert natively.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Collection
+
+import structlog
+
+from products.alerts_platform.backend.facade.contracts import (
+ DeliveryPath,
+ DeliveryPathChooser,
+ LegacyEventEmitter,
+ SourceKind,
+)
+
+logger = structlog.get_logger(__name__)
+
+_chooser: DeliveryPathChooser | None = None
+_emitters: dict[SourceKind, LegacyEventEmitter] = {}
+
+
+def register_chooser(chooser: DeliveryPathChooser) -> None:
+ global _chooser
+ if _chooser is not None and _chooser is not chooser:
+ raise RuntimeError("A different delivery path chooser is already registered.")
+ _chooser = chooser
+
+
+def register_emitter(source: SourceKind, emitter: LegacyEventEmitter) -> None:
+ registered = _emitters.get(source)
+ if registered is not None and registered is not emitter:
+ raise RuntimeError(f"A different legacy event emitter is already registered for {source} alerts.")
+ _emitters[source] = emitter
+
+
+def emitter_for(source: SourceKind) -> LegacyEventEmitter | None:
+ return _emitters.get(source)
+
+
+def choose_path(*, source: SourceKind, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> DeliveryPath:
+ """The path the alert's destinations allow now. Any failure takes the HogFunction path.
+
+ The HogFunction path sends what the source's own stack sent, so it is the safe answer to doubt.
+ Only a source with an emitter asks, so a missing chooser is doubt too.
+ """
+ if _chooser is None:
+ logger.warning("alerts_platform_delivery_path_chooser_missing", team_id=team_id)
+ return DeliveryPath.HOG_FUNCTION
+ try:
+ return _chooser(source=source, team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)
+ except Exception:
+ logger.warning("alerts_platform_delivery_path_choice_failed", team_id=team_id, exc_info=True)
+ return DeliveryPath.HOG_FUNCTION
diff --git a/products/alerts_platform/backend/delivery/episode_paths.py b/products/alerts_platform/backend/delivery/episode_paths.py
new file mode 100644
index 000000000000..13391cf53324
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/episode_paths.py
@@ -0,0 +1,36 @@
+"""The path each firing delivers through, stored so a firing and its resolve take the same one."""
+
+from collections.abc import Callable
+from datetime import datetime
+
+from products.alerts_platform.backend.facade.contracts import DeliveryPath
+from products.alerts_platform.backend.models import PlatformAlertDeliveryPath
+
+
+def episode_path(
+ *,
+ team_id: int,
+ configuration_id: str,
+ grouping_key: str,
+ episode_started_at: datetime,
+ choose: Callable[[], DeliveryPath],
+) -> DeliveryPath:
+ """The path this firing already took, or the one `choose` picks now, stored for the rest of it.
+
+ The first writer wins, so two deliveries of one firing that race agree on the path.
+ """
+ stored = (
+ PlatformAlertDeliveryPath.objects.for_team(team_id)
+ .filter(configuration_id=configuration_id, grouping_key=grouping_key, episode_started_at=episode_started_at)
+ .values_list("path", flat=True)
+ .first()
+ )
+ if stored is not None:
+ return DeliveryPath(stored)
+ row, _ = PlatformAlertDeliveryPath.objects.for_team(team_id).get_or_create(
+ configuration_id=configuration_id,
+ grouping_key=grouping_key,
+ episode_started_at=episode_started_at,
+ defaults={"team_id": team_id, "path": choose()},
+ )
+ return DeliveryPath(row.path)
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index e82efdc45ead..d3124190b9fc 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -7,6 +7,7 @@ is what decides which destinations there are and which transport each one takes.
import json
from collections.abc import Callable
from dataclasses import replace
+from functools import cache
from typing import Any, Final
import structlog
@@ -14,7 +15,7 @@ import structlog
from posthog.dataclasses import frozen
from posthog.models import Team
-from products.alerts_platform.backend.delivery import legacy_webhook
+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
@@ -34,9 +35,11 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertEventKind,
AnnouncedTransition,
+ DeliveryPath,
DestinationType,
EvaluationAnnouncement,
IncidentAction,
+ LegacyEventEmission,
)
from products.alerts_platform.backend.logic.platform_alert_events import announced_kinds, announcement
@@ -70,6 +73,8 @@ class DeliveryOutcome:
live: bool
sent: int
skipped_without_transport: int
+ # Transitions handed to the source to emit its own events, on the HogFunction path.
+ emitted: int = 0
def destinations_are_live(team: Team) -> bool:
@@ -158,6 +163,8 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
)
if announced is None:
return DeliveryOutcome(live=True, sent=0, skipped_without_transport=0)
+ announced, emissions = _split_by_path(request, announced)
+ emitter = delivery_paths.emitter_for(request.source) if emissions else None
notice_keys: dict[str, str] = {}
if request.parts > 1 and request.overflowed:
notice_keys = _overflow_notice_keys(
@@ -239,6 +246,19 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
failures.append(type(error).__name__)
else:
sent += 1
+ # Emitted last and only without a held thread, because the workflow runs a held delivery again
+ # in full, and a second emission sends every HogFunction message a second time.
+ if emitter is not None and not busy:
+ try:
+ emitter(request=request, announcement=announced, emissions=emissions)
+ except Exception as error:
+ logger.warning(
+ "alerts_platform_legacy_event_emission_failed",
+ team_id=request.team_id,
+ configuration_id=request.configuration_id,
+ exc_info=True,
+ )
+ failures.append(f"legacy events: {type(error).__name__}")
# A held thread wins over a failure. The workflow waits a held thread out and then runs the
# whole delivery again, which retries the failed destinations too. A failure raised instead
# spends the activity's retries inside the claim's TTL, and the held message is lost.
@@ -247,7 +267,60 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
raise ThreadBusy("; ".join([*busy, *failures]))
if failures:
raise DeliveryError(f"{len(failures)} destination(s) failed: " + "; ".join(failures)) from first_refusal
- return DeliveryOutcome(live=True, sent=sent, skipped_without_transport=skipped)
+ return DeliveryOutcome(live=True, sent=sent, skipped_without_transport=skipped, emitted=len(emissions))
+
+
+def _split_by_path(
+ request: AlertDeliveryRequest, announced: EvaluationAnnouncement
+) -> tuple[EvaluationAnnouncement, tuple[LegacyEventEmission, ...]]:
+ """The transitions to deliver natively, and the ones the source emits for its HogFunctions.
+
+ Only an alert the platform owns can take the HogFunction path. While the source owns it, its
+ own stack emits those events, and emitting them here too would send every message twice.
+
+ A transition inside a firing takes the path its firing took first, so a firing and its resolve
+ never split across paths. Any other transition takes the path its destinations allow now.
+ """
+ if not request.owned_by_platform or delivery_paths.emitter_for(request.source) is None:
+ return announced, ()
+
+ # Read once per delivery, because the chooser reads every destination of the alert.
+ @cache
+ def choose() -> DeliveryPath:
+ return delivery_paths.choose_path(
+ source=request.source,
+ team_id=request.team_id,
+ alert_id=request.destination_alert_id,
+ allowed_event_ids=[*request.event_ids_by_kind.values(), *request.event_ids_by_incident_action.values()],
+ )
+
+ native: list[AnnouncedTransition] = []
+ emissions: list[LegacyEventEmission] = []
+ for transition in announced.transitions:
+ path = (
+ episode_paths.episode_path(
+ team_id=request.team_id,
+ configuration_id=request.configuration_id,
+ grouping_key=transition.grouping_key,
+ episode_started_at=transition.episode_started_at,
+ choose=choose,
+ )
+ if transition.episode_started_at is not None
+ else choose()
+ )
+ if path == DeliveryPath.NATIVE:
+ native.append(transition)
+ continue
+ subscribed = _subscribed_events(request, transition)
+ if subscribed.message_event or subscribed.incident_event:
+ emissions.append(
+ LegacyEventEmission(
+ transition=transition,
+ sends_message=subscribed.message_event is not None,
+ incident_action=subscribed.incident_action if subscribed.incident_event else None,
+ )
+ )
+ return replace(announced, transitions=tuple(native)), tuple(emissions)
def _overflow_notice_keys(request: AlertDeliveryRequest, kinds: dict[str, AlertEventKind]) -> dict[str, str]:
@@ -284,15 +357,30 @@ def _by_subscription(
"""
grouped: dict[str, list[AnnouncedTransition]] = {}
for transition in announced.transitions:
- message_event = request.event_ids_by_kind.get(transition.kind.value) if request.sends_messages else None
- action = request.incident_actions.get(transition.grouping_key)
- incident_event = request.event_ids_by_incident_action.get(action.value) if action else None
- for event_id in (message_event, incident_event):
+ subscribed = _subscribed_events(request, transition)
+ for event_id in (subscribed.message_event, subscribed.incident_event):
if event_id is not None:
grouped.setdefault(event_id, []).append(transition)
return {event_id: tuple(transitions) for event_id, transitions in grouped.items()}
+@frozen
+class _SubscribedEvents:
+ message_event: str | None
+ incident_action: IncidentAction | None
+ incident_event: str | None
+
+
+def _subscribed_events(request: AlertDeliveryRequest, transition: AnnouncedTransition) -> _SubscribedEvents:
+ """The message event and the incident event one transition reaches, on either delivery path."""
+ action = request.incident_actions.get(transition.grouping_key)
+ return _SubscribedEvents(
+ message_event=request.event_ids_by_kind.get(transition.kind.value) if request.sends_messages else None,
+ incident_action=action,
+ incident_event=request.event_ids_by_incident_action.get(action.value) if action else None,
+ )
+
+
def _destinations(request: AlertDeliveryRequest, event_id: str) -> list[AlertDestinationData]:
"""Who subscribed to this event, resolved now rather than pinned when the check ran.
diff --git a/products/alerts_platform/backend/delivery/legacy_webhook.py b/products/alerts_platform/backend/delivery/legacy_webhook.py
index 5a00386853d1..5351c2424f07 100644
--- a/products/alerts_platform/backend/delivery/legacy_webhook.py
+++ b/products/alerts_platform/backend/delivery/legacy_webhook.py
@@ -38,3 +38,13 @@ def body_for(source: SourceKind) -> LegacyWebhookBody | None:
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)
+
+
+def native_sends_legacy_body(source: SourceKind, team: Team) -> bool | None:
+ """Whether native delivery sends this team the webhook body its source's HogFunction sent. None when unknown.
+
+ A source that registered no body gets the platform body natively, whatever the flag says.
+ """
+ if body_for(source) is None:
+ return False
+ return keeps_legacy_webhook_body(team)
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index f04d00d3fc3e..41aece18754d 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -17,7 +17,7 @@ from uuid import UUID
from posthog.dataclasses import frozen
from posthog.enums import LabeledStrEnum
-from products.alerts_platform.backend.facade.enums import PlatformAlertCheckStatus, PlatformAlertState
+from products.alerts_platform.backend.facade.enums import DeliveryPath, PlatformAlertCheckStatus, PlatformAlertState
if TYPE_CHECKING:
# facade.lifecycle imports this module, so the policy type stays off the runtime import path.
@@ -103,6 +103,11 @@ def source_condition(source_config: dict[str, Any]) -> dict[str, Any]:
return condition if isinstance(condition, dict) else {}
+def source_filters(source_config: dict[str, Any]) -> dict[str, Any]:
+ """A source's own configuration, without the bound `source_condition` reads."""
+ return {key: value for key, value in source_config.items() if key != SOURCE_CONDITION_KEY}
+
+
class GroupingMode(StrEnum):
SINGLE = "single"
BY_RESULT_LABELS = "by_result_labels"
@@ -1056,6 +1061,46 @@ class LegacyWebhookBody(Protocol):
) -> dict[str, Any]: ...
+class DeliveryPathChooser(Protocol):
+ """Which path an alert's destinations allow now. The product that owns destinations registers it.
+
+ Answers `HOG_FUNCTION` whenever it is unsure, because that path sends what the source's own
+ stack sent. It reads destinations and flags, so it runs once per delivery, not per destination.
+ """
+
+ def __call__(
+ self, *, source: SourceKind, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+ ) -> DeliveryPath: ...
+
+
+@frozen
+class LegacyEventEmission:
+ """One transition the platform hands to its source on the HogFunction path."""
+
+ transition: AnnouncedTransition
+ # The source emits the transition's message event, as its own stack did when it notified.
+ sends_message: bool
+ # The source emits the incident event for this action too, when it is set.
+ incident_action: IncidentAction | None
+
+
+class LegacyEventEmitter(Protocol):
+ """Emits the internal events a source's own stack emitted, for transitions on the HogFunction path.
+
+ Returns only once the broker has every event, and raises otherwise, so delivery can retry. A
+ retry emits the events again, so each event carries an id stable across attempts that a
+ receiver can deduplicate on. The source's destinations match on `request.destination_alert_id`.
+ """
+
+ def __call__(
+ self,
+ *,
+ request: AlertDeliveryRequest,
+ announcement: EvaluationAnnouncement,
+ emissions: Sequence[LegacyEventEmission],
+ ) -> None: ...
+
+
# 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 e56572fb27dc..9c5cd92e6864 100644
--- a/products/alerts_platform/backend/facade/delivery.py
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -4,10 +4,18 @@ 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.delivery import (
+ addresses,
+ delivery_paths,
+ describers,
+ destinations,
+ legacy_webhook,
+)
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
+ DeliveryPathChooser,
DestinationResolver,
+ LegacyEventEmitter,
LegacyWebhookBody,
SourceDescriber,
SourceKind,
@@ -37,3 +45,18 @@ def register_legacy_webhook_body(source: SourceKind, body: LegacyWebhookBody) ->
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)
+
+
+def register_delivery_path_chooser(chooser: DeliveryPathChooser) -> None:
+ """The product that owns destinations decides, per alert, whether native delivery may send them."""
+ delivery_paths.register_chooser(chooser)
+
+
+def register_legacy_event_emitter(source: SourceKind, emitter: LegacyEventEmitter) -> None:
+ """A source's alerts on the HogFunction path send through the internal events this emits."""
+ delivery_paths.register_emitter(source, emitter)
+
+
+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)
diff --git a/products/alerts_platform/backend/facade/enums.py b/products/alerts_platform/backend/facade/enums.py
index 13e3ac23c85b..6507a5cb74d2 100644
--- a/products/alerts_platform/backend/facade/enums.py
+++ b/products/alerts_platform/backend/facade/enums.py
@@ -22,6 +22,17 @@ class PlatformAlertOwner(LabeledStrEnum):
PLATFORM = "platform", "Platform"
+class DeliveryPath(LabeledStrEnum):
+ """How the platform sends an alert it owns.
+
+ `HOG_FUNCTION` sends nothing natively. The source emits the internal events its own stack
+ emitted, and the alert's HogFunctions send exactly what they sent before the cutover.
+ """
+
+ NATIVE = "native", "Native"
+ HOG_FUNCTION = "hog_function", "HogFunction"
+
+
class PlatformAlertState(LabeledStrEnum):
"""Where one alert instance stands."""
diff --git a/products/alerts_platform/backend/logic/platform_lifecycle.py b/products/alerts_platform/backend/logic/platform_lifecycle.py
index 06c189cf1bc8..ebc13cc60a22 100644
--- a/products/alerts_platform/backend/logic/platform_lifecycle.py
+++ b/products/alerts_platform/backend/logic/platform_lifecycle.py
@@ -335,6 +335,7 @@ def _condition_snapshot(configuration: PlatformAlertConfiguration) -> dict[str,
return {
**source_condition(configuration.source_config),
"evaluation_periods": configuration.evaluation_periods,
+ "check_interval_minutes": configuration.check_interval_minutes,
"datapoints_to_alarm": configuration.datapoints_to_alarm,
"cooldown_minutes": configuration.cooldown_minutes,
}
diff --git a/products/alerts_platform/backend/migrations/0016_platformalertdeliverypath.py b/products/alerts_platform/backend/migrations/0016_platformalertdeliverypath.py
new file mode 100644
index 000000000000..cdb819d8e2f3
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0016_platformalertdeliverypath.py
@@ -0,0 +1,69 @@
+# Generated by Django 5.2.18 on 2026-10-16 22:09
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0015_backfill_platformalert_last_seen_at"),
+ ("posthog", "1401_drop_userproductlist_table"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PlatformAlertDeliveryPath",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "grouping_key",
+ models.CharField(db_default="", default="", max_length=255),
+ ),
+ ("episode_started_at", models.DateTimeField()),
+ (
+ "path",
+ models.CharField(
+ choices=[("native", "Native"), ("hog_function", "HogFunction")],
+ max_length=16,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="delivery_paths",
+ to="alerts_platform.platformalertconfiguration",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "alerts_platformalertdeliverypath",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("configuration", "grouping_key", "episode_started_at"),
+ name="platform_alert_delivery_path_one_per_episode",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index 15b4175ff23a..ab8cfc825bf6 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_backfill_platformalert_last_seen_at
+0016_platformalertdeliverypath
diff --git a/products/alerts_platform/backend/models/__init__.py b/products/alerts_platform/backend/models/__init__.py
index dcd4a997509b..f9389a4daa6e 100644
--- a/products/alerts_platform/backend/models/__init__.py
+++ b/products/alerts_platform/backend/models/__init__.py
@@ -1,7 +1,8 @@
-from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertThread
+from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertDeliveryPath, PlatformAlertThread
__all__ = [
"PlatformAlert",
"PlatformAlertConfiguration",
+ "PlatformAlertDeliveryPath",
"PlatformAlertThread",
]
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 24df3e302ce8..f4544a801f8c 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -15,6 +15,7 @@ from posthog.models.utils import UUIDModel
from products.alerts_platform.backend.facade.contracts import Grouping
from products.alerts_platform.backend.facade.enums import (
+ DeliveryPath,
PlatformAlertCheckStatus,
PlatformAlertConfigurationRecurrenceUnit,
PlatformAlertConfigurationSourceKind,
@@ -215,3 +216,32 @@ class PlatformAlertThread(TeamScopedRootMixin, UUIDModel):
name="platform_alert_thread_one_per_conversation",
)
]
+
+
+class PlatformAlertDeliveryPath(TeamScopedRootMixin, UUIDModel):
+ """The path one firing of one group delivers through, fixed by the first delivery about it.
+
+ The path is read from the alert's destinations at send time, and those can change mid-firing.
+ Without this row a firing sent through HogFunctions could resolve natively, and an incident
+ manager would hold the first incident open, because the two paths key incidents differently.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ configuration = models.ForeignKey(
+ PlatformAlertConfiguration, on_delete=models.CASCADE, related_name="delivery_paths"
+ )
+
+ grouping_key = models.CharField(max_length=255, default="", db_default="")
+ episode_started_at = models.DateTimeField()
+ path = models.CharField(max_length=16, choices=DeliveryPath.choices)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ db_table = "alerts_platformalertdeliverypath"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["configuration", "grouping_key", "episode_started_at"],
+ name="platform_alert_delivery_path_one_per_episode",
+ )
+ ]
diff --git a/products/alerts_platform/backend/temporal/workflows.py b/products/alerts_platform/backend/temporal/workflows.py
index 380356cd6143..59f2a29ad345 100644
--- a/products/alerts_platform/backend/temporal/workflows.py
+++ b/products/alerts_platform/backend/temporal/workflows.py
@@ -154,6 +154,7 @@ async def alerts_platform_deliver_preview_activity(request: AlertDeliveryRequest
evaluation_key=request.evaluation_key,
sent=outcome.sent,
skipped_without_transport=outcome.skipped_without_transport,
+ emitted=outcome.emitted,
)
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index ca19e7e67aab..5ddfb840be88 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -8,7 +8,7 @@ from unittest.mock import patch
from parameterized import parameterized
-from products.alerts_platform.backend.delivery import legacy_webhook
+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
from products.alerts_platform.backend.delivery.legacy_webhook import LEGACY_WEBHOOK_BODY_FLAG
@@ -21,11 +21,14 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationGroup,
AlertEventKind,
AnnouncedTransition,
+ DeliveryPath,
DestinationType,
EvaluationAnnouncement,
IncidentAction,
+ LegacyEventEmission,
SourceKind,
)
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
_MODULE = "products.alerts_platform.backend.delivery.evaluation"
_LEGACY_MODULE = "products.alerts_platform.backend.delivery.legacy_webhook"
@@ -87,6 +90,7 @@ class HeldTransport(RecordingTransport):
def _request(
team_id: int,
*,
+ configuration_id: str = "cfg-1",
sends_messages: bool = True,
incident_actions: dict[str, IncidentAction] | None = None,
owned_by_platform: bool = False,
@@ -97,7 +101,7 @@ def _request(
return AlertDeliveryRequest(
source=SourceKind.LOGS,
team_id=team_id,
- configuration_id="cfg-1",
+ configuration_id=configuration_id,
evaluation_key="eval-1",
destination_alert_id="legacy-1",
event_ids_by_kind={"firing": FIRING_EVENT, "resolved": RESOLVED_EVENT},
@@ -111,11 +115,13 @@ def _request(
)
-def _transition(kind: AlertEventKind, grouping_key: str = "") -> AnnouncedTransition:
+def _transition(
+ kind: AlertEventKind, grouping_key: str = "", episode_started_at: datetime | None = FIRING
+) -> AnnouncedTransition:
return AnnouncedTransition(
grouping_key=grouping_key,
kind=kind,
- episode_started_at=FIRING,
+ episode_started_at=episode_started_at,
value=None,
labels={},
condition={},
@@ -170,6 +176,8 @@ class TestDeliverEvaluation(APIBaseTest):
patch(f"{_MODULE}.announced_kinds", return_value=kinds or {}),
patch(f"{_MODULE}.list_alert_destination_groups", side_effect=groups),
patch(f"{_MODULE}.DatabaseThreadStore"),
+ # The path is covered by `TestDeliveryPath`. Without an emitter every alert delivers natively.
+ patch.dict(delivery_paths._emitters, clear=True),
patch.dict(
f"{_MODULE}._TRANSPORTS",
{
@@ -460,3 +468,111 @@ class TestDeliverEvaluation(APIBaseTest):
list_alert_destination_groups(team_id=self.team.id, alert_id="unknown", allowed_event_ids=[FIRING_EVENT])
== []
)
+
+
+class TestDeliveryPath(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ RecordingTransport.sends = []
+ self.emitted: list[tuple[LegacyEventEmission, ...]] = []
+ self.configuration = PlatformAlertConfiguration.objects.for_team(self.team.id).create(
+ team=self.team, name="API errors", source_kind=SourceKind.LOGS, check_interval_minutes=1
+ )
+
+ def _emit(self, *, emissions: tuple[LegacyEventEmission, ...], **_kwargs: Any) -> None:
+ self.emitted.append(tuple(emissions))
+
+ def _run(
+ self,
+ announced: EvaluationAnnouncement,
+ chooser: Any,
+ *,
+ owned_by_platform: bool = True,
+ incident_actions: dict[str, IncidentAction] | None = None,
+ emitter: Any = None,
+ ) -> Any:
+ with (
+ patch(
+ "products.alerts_platform.backend.delivery.team_flags.posthoganalytics.feature_enabled",
+ return_value=True,
+ ),
+ patch(f"{_MODULE}.announcement", return_value=announced),
+ patch(f"{_MODULE}.list_alert_destination_groups", return_value=[_group(SLACK)]),
+ patch(f"{_MODULE}.DatabaseThreadStore"),
+ patch.dict(f"{_MODULE}._TRANSPORTS", {DestinationType.SLACK: RecordingTransport}),
+ patch.dict(delivery_paths._emitters, {SourceKind.LOGS: emitter or self._emit}),
+ patch.object(delivery_paths, "_chooser", chooser),
+ ):
+ return deliver_evaluation(
+ _request(
+ self.team.id,
+ configuration_id=str(self.configuration.id),
+ owned_by_platform=owned_by_platform,
+ incident_actions=incident_actions,
+ )
+ )
+
+ @staticmethod
+ def _chooses(path: DeliveryPath) -> Any:
+ return lambda **_kwargs: path
+
+ @staticmethod
+ def _fails(**_kwargs: Any) -> DeliveryPath:
+ raise RuntimeError("classifier down")
+
+ @parameterized.expand(
+ [
+ ("stock_destinations_send_natively", True, DeliveryPath.NATIVE, (0, 1)),
+ ("customized_destinations_emit_for_their_hog_functions", True, DeliveryPath.HOG_FUNCTION, (1, 0)),
+ # The source's own stack still emits these events, so emitting them here would send twice.
+ ("an_alert_the_source_owns_never_emits", False, DeliveryPath.HOG_FUNCTION, (0, 1)),
+ ("a_chooser_that_fails_emits", True, None, (1, 0)),
+ ]
+ )
+ def test_an_alert_delivers_through_the_path_its_destinations_allow(
+ self, _name: str, owned_by_platform: bool, path: DeliveryPath | None, expected: tuple[int, int]
+ ) -> None:
+ chooser = self._chooses(path) if path else self._fails
+ outcome = self._run(
+ _announcement(_transition(AlertEventKind.FIRING)), chooser, owned_by_platform=owned_by_platform
+ )
+
+ assert (len(self.emitted), len(RecordingTransport.sends)) == expected
+ assert outcome.emitted == expected[0]
+
+ def test_a_firing_and_its_resolve_take_the_path_the_firing_took(self) -> None:
+ self._run(
+ _announcement(_transition(AlertEventKind.FIRING)),
+ self._chooses(DeliveryPath.HOG_FUNCTION),
+ incident_actions={"": IncidentAction.TRIGGER},
+ )
+ # Every destination became stock mid-firing. The resolve still closes what the HogFunction opened.
+ self._run(
+ _announcement(_transition(AlertEventKind.RESOLVED)),
+ self._chooses(DeliveryPath.NATIVE),
+ incident_actions={"": IncidentAction.RESOLVE},
+ )
+ # The next firing reads the destinations again.
+ self._run(
+ _announcement(_transition(AlertEventKind.FIRING, episode_started_at=datetime(2026, 9, 30, 10, tzinfo=UTC))),
+ self._chooses(DeliveryPath.NATIVE),
+ )
+
+ assert [
+ [(e.transition.kind, e.sends_message, e.incident_action) for e in emissions] for emissions in self.emitted
+ ] == [
+ [(AlertEventKind.FIRING, True, IncidentAction.TRIGGER)],
+ [(AlertEventKind.RESOLVED, True, IncidentAction.RESOLVE)],
+ ]
+ assert len(RecordingTransport.sends) == 1
+
+ def test_an_emission_the_broker_did_not_take_fails_the_delivery_so_it_retries(self) -> None:
+ def refuse(**_kwargs: Any) -> None:
+ raise RuntimeError("not acknowledged")
+
+ with pytest.raises(DeliveryError):
+ self._run(
+ _announcement(_transition(AlertEventKind.FIRING, episode_started_at=None)),
+ self._chooses(DeliveryPath.HOG_FUNCTION),
+ emitter=refuse,
+ )
diff --git a/products/logs/backend/alert_check_query.py b/products/logs/backend/alert_check_query.py
index 29574c86602c..f6b7c615f491 100644
--- a/products/logs/backend/alert_check_query.py
+++ b/products/logs/backend/alert_check_query.py
@@ -96,11 +96,6 @@ def _period_ranges(
]
-def rolling_check_lookback_minutes(window_minutes: int, cadence_minutes: int, period_count: int) -> int:
- """Total minutes of history covered by M cadence-stepped rolling windows."""
- return window_minutes + (period_count - 1) * cadence_minutes
-
-
def _rolling_check_ranges(
nca: dt.datetime,
window_minutes: int,
diff --git a/products/logs/backend/alert_event_properties.py b/products/logs/backend/alert_event_properties.py
new file mode 100644
index 000000000000..ee77bcdfa260
--- /dev/null
+++ b/products/logs/backend/alert_event_properties.py
@@ -0,0 +1,76 @@
+"""The properties of the internal events that drive logs alert HogFunctions.
+
+The logs stack emits these for the alerts it owns, and the platform emits them for the alerts it
+owns on the HogFunction path. A HogFunction reads them by name, so both build them here.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from products.logs.backend.logs_url_params import build_logs_url_params
+
+
+def threshold_event_properties(
+ *,
+ alert_id: str,
+ alert_name: str,
+ team_id: int,
+ threshold_count: int,
+ threshold_operator: str,
+ window_minutes: int,
+ result_count: int | None,
+ filters: dict[str, Any],
+ date_from: datetime,
+ date_to: datetime,
+ triggered_at: datetime,
+) -> dict[str, Any]:
+ """A firing, a resolve, or an opened incident."""
+ return {
+ "alert_id": alert_id,
+ "alert_name": alert_name,
+ "team_id": team_id,
+ "threshold_count": threshold_count,
+ "threshold_operator": threshold_operator,
+ "window_minutes": window_minutes,
+ "result_count": result_count,
+ "filters": filters,
+ "service_names": filters.get("serviceNames", []),
+ "severity_levels": filters.get("severityLevels", []),
+ "logs_url_params": build_logs_url_params(filters, date_from=date_from, date_to=date_to),
+ "triggered_at": triggered_at.isoformat(),
+ }
+
+
+def failure_event_properties(
+ *,
+ alert_id: str,
+ alert_name: str,
+ team_id: int,
+ consecutive_failures: int,
+ filters: dict[str, Any],
+ triggered_at: datetime,
+) -> dict[str, Any]:
+ """An errored or an auto-disabled alert, without the error, whose key differs between the two."""
+ return {
+ "alert_id": alert_id,
+ "alert_name": alert_name,
+ "team_id": team_id,
+ "consecutive_failures": consecutive_failures,
+ "service_names": filters.get("serviceNames", []),
+ "severity_levels": filters.get("severityLevels", []),
+ "triggered_at": triggered_at.isoformat(),
+ }
+
+
+def incident_closed_event_properties(
+ *, alert_id: str, alert_name: str, team_id: int, reason: str, triggered_at: datetime
+) -> dict[str, Any]:
+ return {
+ "alert_id": alert_id,
+ "alert_name": alert_name,
+ "team_id": team_id,
+ "reason": reason,
+ "triggered_at": triggered_at.isoformat(),
+ }
diff --git a/products/logs/backend/alert_incidents.py b/products/logs/backend/alert_incidents.py
index 222a8f16664e..795e5d991024 100644
--- a/products/logs/backend/alert_incidents.py
+++ b/products/logs/backend/alert_incidents.py
@@ -15,6 +15,7 @@ from products.alerts.backend.facade.destinations import (
)
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
from products.logs.backend.alert_destinations import LOGS_ALERT_INCIDENT_CLOSED_EVENT, LOGS_ALERT_INCIDENT_OPENED_EVENT
+from products.logs.backend.alert_event_properties import incident_closed_event_properties
from products.logs.backend.alert_state_machine import IncidentCloseReason
from products.logs.backend.models import LogsAlertConfiguration
@@ -37,13 +38,9 @@ def has_incident_destination(alert: LogsAlertConfiguration) -> bool:
def incident_closed_properties(
alert: LogsAlertConfiguration, reason: IncidentCloseReason, now: datetime
) -> dict[str, Any]:
- return {
- "alert_id": str(alert.id),
- "alert_name": alert.name,
- "team_id": alert.team_id,
- "reason": reason.value,
- "triggered_at": now.isoformat(),
- }
+ return incident_closed_event_properties(
+ alert_id=str(alert.id), alert_name=alert.name, team_id=alert.team_id, reason=reason.value, triggered_at=now
+ )
def close_incident(
diff --git a/products/logs/backend/alert_lookback.py b/products/logs/backend/alert_lookback.py
new file mode 100644
index 000000000000..6ab71a24711c
--- /dev/null
+++ b/products/logs/backend/alert_lookback.py
@@ -0,0 +1,6 @@
+"""How far back a logs alert check reads. Light, so the event builders loaded at startup can use it."""
+
+
+def rolling_check_lookback_minutes(window_minutes: int, cadence_minutes: int, period_count: int) -> int:
+ """Total minutes of history covered by M cadence-stepped rolling windows."""
+ return window_minutes + (period_count - 1) * cadence_minutes
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index d45feb2545c1..35a34293de67 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -91,12 +91,12 @@ from products.logs.backend.alert_check_query import (
fetch_live_logs_checkpoint,
is_projection_eligible,
resolve_alert_date_to,
- rolling_check_lookback_minutes,
)
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
from products.logs.backend.alert_group_columns import GROUP_COLUMNS
+from products.logs.backend.alert_lookback import rolling_check_lookback_minutes
from products.logs.backend.models import LogsAlertConfiguration
from products.logs.backend.platform_alert_backfill import platform_upsert_of
diff --git a/products/logs/backend/platform_alert_legacy_events.py b/products/logs/backend/platform_alert_legacy_events.py
new file mode 100644
index 000000000000..4c80b134670b
--- /dev/null
+++ b/products/logs/backend/platform_alert_legacy_events.py
@@ -0,0 +1,142 @@
+"""The `$logs_alert_*` events the platform emits for a logs alert it owns on the HogFunction path.
+
+The alert's HogFunctions filter on these events and render these properties, so the platform
+reproduces what the logs stack emits, from what the check recorded.
+
+Imported from `ready()`, so it stays light: no models, no query layer.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from datetime import timedelta
+from typing import Any, Final, cast
+from uuid import NAMESPACE_URL, uuid5
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.facade.contracts import AlertInternalEvent
+from products.alerts.backend.facade.destinations import emit_alert_internal_events
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDeliveryRequest,
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+ IncidentAction,
+ LegacyEventEmission,
+ source_filters,
+)
+from products.logs.backend.alert_destinations import (
+ EVENT_KIND_CONFIG,
+ LOGS_ALERT_INCIDENT_CLOSED_EVENT,
+ LOGS_ALERT_INCIDENT_OPENED_EVENT,
+ EventKind,
+)
+from products.logs.backend.alert_event_properties import (
+ failure_event_properties,
+ incident_closed_event_properties,
+ threshold_event_properties,
+)
+from products.logs.backend.alert_lookback import rolling_check_lookback_minutes
+from products.logs.backend.alert_state_machine import IncidentCloseReason
+from products.logs.backend.platform_alert_wording import check_window_end, in_utc
+
+# Below the delivery activity's own timeout, which a flush must not use up.
+FLUSH_TIMEOUT_SECONDS: Final = 5.0
+
+
+def emit_logs_legacy_events(
+ *, request: AlertDeliveryRequest, announcement: EvaluationAnnouncement, emissions: Sequence[LegacyEventEmission]
+) -> None:
+ alert = _Alert(
+ team_id=request.team_id,
+ alert_id=request.destination_alert_id,
+ alert_name=announcement.alert_name,
+ consecutive_failures=announcement.consecutive_failures,
+ )
+ events: list[AlertInternalEvent] = []
+ for emission in emissions:
+ transition = in_utc(emission.transition)
+ if emission.sends_message:
+ events.append(_message_event(transition, alert))
+ if emission.incident_action is not None:
+ events.append(_incident_event(transition, emission.incident_action, alert))
+ emit_alert_internal_events(
+ team_id=alert.team_id, alert_id=alert.alert_id, events=events, flush_timeout_seconds=FLUSH_TIMEOUT_SECONDS
+ )
+
+
+@frozen
+class _Alert:
+ team_id: int
+ alert_id: str
+ alert_name: str
+ consecutive_failures: int
+
+ def event(self, event_name: str, properties: dict[str, Any], transition: AnnouncedTransition) -> AlertInternalEvent:
+ # The occurrence is in the seed too, so two firings recorded without an evaluation key keep distinct ids.
+ seed = (
+ f"{self.alert_id}|{transition.grouping_key}|{event_name}|{transition.evaluation_key}|"
+ f"{transition.occurred_at.isoformat()}"
+ )
+ return AlertInternalEvent(
+ event_name=event_name,
+ properties=properties,
+ timestamp=transition.occurred_at,
+ uuid=str(uuid5(NAMESPACE_URL, seed)),
+ )
+
+
+def _message_event(transition: AnnouncedTransition, alert: _Alert) -> AlertInternalEvent:
+ event_name = EVENT_KIND_CONFIG[cast(EventKind, transition.kind.value)].event_id
+ if transition.kind in (AlertEventKind.FIRING, AlertEventKind.RESOLVED):
+ return alert.event(event_name, _threshold_properties(transition, alert), transition)
+ error_key = "last_error_message" if transition.kind == AlertEventKind.BROKEN else "error_message"
+ properties = failure_event_properties(
+ alert_id=alert.alert_id,
+ alert_name=alert.alert_name,
+ team_id=alert.team_id,
+ consecutive_failures=alert.consecutive_failures,
+ filters=source_filters(transition.source_config),
+ triggered_at=transition.occurred_at,
+ )
+ return alert.event(event_name, {**properties, error_key: transition.error_message or ""}, transition)
+
+
+def _incident_event(transition: AnnouncedTransition, action: IncidentAction, alert: _Alert) -> AlertInternalEvent:
+ if action == IncidentAction.TRIGGER:
+ return alert.event(LOGS_ALERT_INCIDENT_OPENED_EVENT, _threshold_properties(transition, alert), transition)
+ reason = IncidentCloseReason.BROKEN if transition.kind == AlertEventKind.BROKEN else IncidentCloseReason.RESOLVED
+ properties = incident_closed_event_properties(
+ alert_id=alert.alert_id,
+ alert_name=alert.alert_name,
+ team_id=alert.team_id,
+ reason=reason.value,
+ triggered_at=transition.occurred_at,
+ )
+ return alert.event(LOGS_ALERT_INCIDENT_CLOSED_EVENT, properties, transition)
+
+
+def _threshold_properties(transition: AnnouncedTransition, alert: _Alert) -> dict[str, Any]:
+ condition = transition.condition
+ date_to = check_window_end(transition)
+ # The logs stack links every window a check read, not only the latest. A row recorded before
+ # the snapshot held the interval falls back to one window.
+ lookback = rolling_check_lookback_minutes(
+ condition["window_minutes"],
+ condition.get("check_interval_minutes") or 0,
+ condition.get("evaluation_periods") or 1,
+ )
+ return threshold_event_properties(
+ alert_id=alert.alert_id,
+ alert_name=alert.alert_name,
+ team_id=alert.team_id,
+ threshold_count=condition["threshold_count"],
+ threshold_operator=condition["threshold_operator"],
+ window_minutes=condition["window_minutes"],
+ result_count=int(transition.value) if transition.value is not None else None,
+ filters=source_filters(transition.source_config),
+ date_from=date_to - timedelta(minutes=lookback),
+ date_to=date_to,
+ triggered_at=transition.occurred_at,
+ )
diff --git a/products/logs/backend/platform_alert_wording.py b/products/logs/backend/platform_alert_wording.py
index e610778822f2..ceeb23f4726c 100644
--- a/products/logs/backend/platform_alert_wording.py
+++ b/products/logs/backend/platform_alert_wording.py
@@ -7,7 +7,7 @@ Imported from `ready()`, so it stays light: no models, no query layer.
"""
from dataclasses import replace
-from datetime import UTC, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, Final
from uuid import NAMESPACE_URL, uuid5
@@ -82,7 +82,7 @@ def _logs_url(project_id: int, transition: AnnouncedTransition) -> str:
return absolute_uri(f"/project/{project_id}/logs" + (f"?{params}" if params else ""))
-def _in_utc(transition: AnnouncedTransition) -> AnnouncedTransition:
+def in_utc(transition: AnnouncedTransition) -> AnnouncedTransition:
# History rows come back from ClickHouse without a zone. A link or a body with zoneless times
# reads them in whatever zone the reader is in.
if transition.occurred_at.tzinfo is not None:
@@ -90,11 +90,17 @@ def _in_utc(transition: AnnouncedTransition) -> AnnouncedTransition:
return replace(transition, occurred_at=transition.occurred_at.replace(tzinfo=UTC))
-def _window_params(transition: AnnouncedTransition) -> str:
- # The window the check counted, so the link opens on the logs that decided it. The window end
- # can sit before the record time, because the check clamps it to the ingestion checkpoint.
+def check_window_end(transition: AnnouncedTransition) -> datetime:
+ """The end of the window the check counted, so a link opens on the logs that decided it.
+
+ The window end can sit before the record time, because the check clamps it to the ingestion checkpoint.
+ """
window_end = window_end_of(transition.evaluation_key)
- date_to = _in_utc(replace(transition, occurred_at=window_end) if window_end else transition).occurred_at
+ return in_utc(replace(transition, occurred_at=window_end) if window_end else transition).occurred_at
+
+
+def _window_params(transition: AnnouncedTransition) -> str:
+ date_to = check_window_end(transition)
date_from = date_to - timedelta(minutes=transition.condition["window_minutes"])
return build_logs_url_params(_group_filters(transition), date_from=date_from, date_to=date_to)
@@ -150,7 +156,7 @@ def legacy_logs_webhook_body(
Its template rendered a lone placeholder as the value's own type, so counts stay numbers and
filter lists stay lists here too.
"""
- transition = _in_utc(transition)
+ transition = in_utc(transition)
occurred_at = transition.occurred_at
filters = transition.source_config
alert_url = absolute_uri(f"/project/{project_id}/logs/alerts/{alert_id}")
diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.py
index 9cfa11b68dd8..e7ae5bfbe05c 100644
--- a/products/logs/backend/temporal/activities.py
+++ b/products/logs/backend/temporal/activities.py
@@ -41,14 +41,15 @@ from products.logs.backend.alert_check_query import (
fetch_live_logs_checkpoint,
is_projection_eligible,
resolve_alert_date_to,
- rolling_check_lookback_minutes,
)
from products.logs.backend.alert_destinations import LOGS_ALERT_INCIDENT_CLOSED_EVENT, LOGS_ALERT_INCIDENT_OPENED_EVENT
from products.logs.backend.alert_error_classifier import (
AlertErrorCode,
classify as classify_alert_error,
)
+from products.logs.backend.alert_event_properties import failure_event_properties, threshold_event_properties
from products.logs.backend.alert_incidents import close_incident, has_incident_destination, incident_closed_properties
+from products.logs.backend.alert_lookback import rolling_check_lookback_minutes
from products.logs.backend.alert_signal_emitter import (
NotifiedAlert,
emit_alert_state_change_signal,
@@ -72,7 +73,6 @@ from products.logs.backend.alert_utils import (
due_alerts_q,
next_allowed_check_at,
)
-from products.logs.backend.logs_url_params import build_logs_url_params
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
from products.logs.backend.temporal.constants import (
EMIT_SIGNAL_CONCURRENCY,
@@ -1597,20 +1597,19 @@ def _emit_alert_event(
date_from: datetime,
date_to: datetime,
) -> ProduceResult | None:
- properties: dict = {
- "alert_id": str(alert.id),
- "alert_name": alert.name,
- "team_id": alert.team_id,
- "threshold_count": alert.threshold_count,
- "threshold_operator": alert.threshold_operator,
- "window_minutes": alert.window_minutes,
- "result_count": check_result.result_count,
- "filters": alert.filters,
- "service_names": alert.filters.get("serviceNames", []),
- "severity_levels": alert.filters.get("severityLevels", []),
- "logs_url_params": build_logs_url_params(alert.filters, date_from=date_from, date_to=date_to),
- "triggered_at": now.isoformat(),
- }
+ properties = threshold_event_properties(
+ alert_id=str(alert.id),
+ alert_name=alert.name,
+ team_id=alert.team_id,
+ threshold_count=alert.threshold_count,
+ threshold_operator=alert.threshold_operator,
+ window_minutes=alert.window_minutes,
+ result_count=check_result.result_count,
+ filters=alert.filters,
+ date_from=date_from,
+ date_to=date_to,
+ triggered_at=now,
+ )
return _produce_alert_internal_event(alert, event_name, properties, now)
@@ -1619,15 +1618,14 @@ def _base_failure_properties(
outcome: AlertCheckOutcome,
now: datetime,
) -> dict:
- return {
- "alert_id": str(alert.id),
- "alert_name": alert.name,
- "team_id": alert.team_id,
- "consecutive_failures": outcome.consecutive_failures,
- "service_names": alert.filters.get("serviceNames", []),
- "severity_levels": alert.filters.get("severityLevels", []),
- "triggered_at": now.isoformat(),
- }
+ return failure_event_properties(
+ alert_id=str(alert.id),
+ alert_name=alert.name,
+ team_id=alert.team_id,
+ consecutive_failures=outcome.consecutive_failures,
+ filters=alert.filters,
+ triggered_at=now,
+ )
def _emit_auto_disabled_event(
diff --git a/products/logs/backend/test/test_platform_alert_legacy_events.py b/products/logs/backend/test/test_platform_alert_legacy_events.py
new file mode 100644
index 000000000000..83b983a268e1
--- /dev/null
+++ b/products/logs/backend/test/test_platform_alert_legacy_events.py
@@ -0,0 +1,163 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import UUID
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.alerts.backend.facade.contracts import AlertInternalEventsNotDelivered
+from products.alerts_platform.backend.facade.contracts import (
+ SOURCE_CONDITION_KEY,
+ AlertDeliveryRequest,
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+ IncidentAction,
+ LegacyEventEmission,
+ SourceKind,
+)
+from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
+from products.logs.backend.alert_state_machine import (
+ AlertCheckOutcome,
+ AlertState,
+ CheckResult,
+ IncidentCloseReason,
+ NotificationAction,
+)
+from products.logs.backend.models import LogsAlertConfiguration
+from products.logs.backend.platform_alert_legacy_events import emit_logs_legacy_events
+from products.logs.backend.temporal import activities
+
+_ACTIVITIES_PRODUCE = "products.logs.backend.temporal.activities.produce_alert_internal_event"
+_PRODUCER = "products.alerts.backend.logic.destinations"
+NOW = datetime(2026, 10, 16, 12, 0, tzinfo=UTC)
+WINDOW_END = NOW - timedelta(seconds=30)
+ALERT_ID = UUID("01900000-0000-0000-0000-000000000001")
+FILTERS: dict[str, Any] = {"severityLevels": ["error"], "serviceNames": ["checkout"]}
+CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 5}
+# Three rolling windows a minute apart, so the link reaches back past the latest window, as the logs stack's does.
+SCHEDULE = {"check_interval_minutes": 1, "evaluation_periods": 3}
+
+
+REQUEST = AlertDeliveryRequest(
+ source=SourceKind.LOGS,
+ team_id=7,
+ configuration_id="cfg-1",
+ evaluation_key="eval-1",
+ destination_alert_id=str(ALERT_ID),
+ event_ids_by_kind={},
+)
+ANNOUNCEMENT = EvaluationAnnouncement(
+ configuration_id="cfg-1", source=SourceKind.LOGS, alert_name="Errors", consecutive_failures=3, transitions=()
+)
+
+
+def _alert() -> LogsAlertConfiguration:
+ return LogsAlertConfiguration(id=ALERT_ID, team_id=7, name="Errors", filters=FILTERS, **CONDITION, **SCHEDULE)
+
+
+def _transition(kind: AlertEventKind) -> AnnouncedTransition:
+ return AnnouncedTransition(
+ grouping_key="",
+ kind=kind,
+ episode_started_at=NOW,
+ value=42.0 if kind in (AlertEventKind.FIRING, AlertEventKind.RESOLVED) else None,
+ labels={},
+ condition={**CONDITION, **SCHEDULE},
+ source_config={**FILTERS, SOURCE_CONDITION_KEY: CONDITION},
+ error_message="query timed out",
+ occurred_at=NOW,
+ evaluation_key=f"slot:1|{WINDOW_MARKER}{WINDOW_END.isoformat()}",
+ )
+
+
+def _failure(notification: NotificationAction) -> AlertCheckOutcome:
+ return AlertCheckOutcome(
+ new_state=AlertState.ERRORED,
+ notification=notification,
+ consecutive_failures=3,
+ update_last_notified_at=True,
+ error_message="query timed out",
+ )
+
+
+def _legacy_emit(event_name: str) -> None:
+ alert = _alert()
+ check = CheckResult(result_count=42, threshold_breached=True)
+ window = {"date_from": WINDOW_END - timedelta(minutes=7), "date_to": WINDOW_END}
+ if event_name == "$logs_alert_errored":
+ activities._emit_alert_errored_event(alert, _failure(NotificationAction.ERROR), NOW)
+ elif event_name == "$logs_alert_auto_disabled":
+ activities._emit_auto_disabled_event(alert, _failure(NotificationAction.BROKEN), NOW)
+ elif event_name == "$logs_alert_incident_closed":
+ activities._emit_incident_closed_event(alert, IncidentCloseReason.RESOLVED, NOW)
+ else:
+ activities._emit_alert_event(alert, event_name, check, NOW, **window)
+
+
+class TestEmitLogsLegacyEvents(SimpleTestCase):
+ def _emit(self, *emissions: LegacyEventEmission, delivered: bool = True) -> MagicMock:
+ with (
+ patch(f"{_PRODUCER}.produce_alert_internal_event", return_value=MagicMock()) as produce,
+ patch(f"{_PRODUCER}.flush_alert_internal_events"),
+ patch(f"{_PRODUCER}.alert_internal_event_delivered", return_value=delivered),
+ ):
+ emit_logs_legacy_events(request=REQUEST, announcement=ANNOUNCEMENT, emissions=emissions)
+ return produce
+
+ @parameterized.expand(
+ [
+ ("firing", AlertEventKind.FIRING, True, None, "$logs_alert_firing"),
+ ("resolved", AlertEventKind.RESOLVED, True, None, "$logs_alert_resolved"),
+ ("errored", AlertEventKind.ERRORED, True, None, "$logs_alert_errored"),
+ ("auto_disabled", AlertEventKind.BROKEN, True, None, "$logs_alert_auto_disabled"),
+ # Cooldown held the message, and the incident still opens.
+ ("incident_opened", AlertEventKind.FIRING, False, IncidentAction.TRIGGER, "$logs_alert_incident_opened"),
+ ("incident_closed", AlertEventKind.RESOLVED, False, IncidentAction.RESOLVE, "$logs_alert_incident_closed"),
+ ]
+ )
+ def test_an_event_carries_what_the_logs_stack_emits_for_the_same_check(
+ self,
+ _name: str,
+ kind: AlertEventKind,
+ sends_message: bool,
+ incident_action: IncidentAction | None,
+ event_name: str,
+ ) -> None:
+ with patch(_ACTIVITIES_PRODUCE) as legacy:
+ _legacy_emit(event_name)
+
+ produce = self._emit(
+ LegacyEventEmission(
+ transition=_transition(kind), sends_message=sends_message, incident_action=incident_action
+ )
+ )
+
+ (call,) = produce.call_args_list
+ assert (call.kwargs["event_name"], call.kwargs["properties"]) == (
+ legacy.call_args.kwargs["event_name"],
+ legacy.call_args.kwargs["properties"],
+ )
+
+ def test_a_retried_emission_reuses_each_event_id_so_a_receiver_can_drop_it(self) -> None:
+ emission = LegacyEventEmission(
+ transition=_transition(AlertEventKind.FIRING), sends_message=True, incident_action=IncidentAction.TRIGGER
+ )
+
+ first = [call.kwargs["uuid"] for call in self._emit(emission).call_args_list]
+ second = [call.kwargs["uuid"] for call in self._emit(emission).call_args_list]
+
+ assert first == second
+ assert len(set(first)) == 2
+
+ def test_an_event_the_broker_did_not_take_raises_so_the_delivery_retries(self) -> None:
+ emission = LegacyEventEmission(
+ transition=_transition(AlertEventKind.FIRING), sends_message=True, incident_action=None
+ )
+
+ with pytest.raises(AlertInternalEventsNotDelivered):
+ self._emit(emission, delivered=False)