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): read an announcement out of history and send it (#110397)

Jimmy Zhu0079135a3c13
diff --git a/products/alerts/backend/delivery/evaluation.py b/products/alerts/backend/delivery/evaluation.py
new file mode 100644
index 000000000000..82be8ac3050b
--- /dev/null
+++ b/products/alerts/backend/delivery/evaluation.py
@@ -0,0 +1,146 @@
+"""One evaluation, from the address a delivery carries to the messages it sends.
+
+The layer that knows a transport exists. `dispatch.deliver` handles one destination, and this
+is what decides which destinations there are and which transport each one takes.
+"""
+
+from dataclasses import replace
+from typing import Final
+
+import structlog
+import posthoganalytics
+
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.alerts.backend.delivery.dispatch import deliver
+from products.alerts.backend.delivery.slack import SlackTransport
+from products.alerts.backend.delivery.thread_store import DatabaseThreadStore
+from products.alerts.backend.delivery.transport import DeliveryTransport
+from products.alerts.backend.facade.contracts import (
+ AlertDeliveryRequest,
+ AlertDestinationData,
+ AnnouncedTransition,
+ DestinationType,
+ EvaluationAnnouncement,
+)
+from products.alerts.backend.facade.destinations import list_alert_destination_groups
+from products.alerts.backend.logic.platform_alert_events import announcement
+
+logger = structlog.get_logger(__name__)
+
+# Whether the platform may contact a team's destinations. Only the platform reads it: the
+# production logs path keeps delivering regardless, so a team with this on receives the legacy
+# message and the native one. Flipping a team from one deliverer to the other is the cutover,
+# and it is not this.
+LIVE_DELIVERY_FLAG: Final = "alert-platform-live-delivery"
+
+# A destination type with no entry here has no native transport. An alert that uses one is not
+# eligible for native delivery at all, which is checked before a team is made live rather than
+# branched on per destination: one alert delivering natively to Slack and through a HogFunction
+# to Discord would send two differently worded messages for one event.
+_TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.SLACK: SlackTransport}
+
+
+@frozen
+class DeliveryOutcome:
+ """What one evaluation's delivery did, for the activity to log and count."""
+
+ live: bool
+ sent: int
+ skipped_without_transport: int
+
+
+def destinations_are_live(team: Team) -> bool:
+ """Whether this team's destinations are the platform's to contact.
+
+ Fail closed. A flag-eval blip leaves the production logs path as the only deliverer, which
+ is where everything was before this existed. Reading a blip the other way starts sending.
+ """
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ LIVE_DELIVERY_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ # This runs in a Temporal activity, where a captured event is silently dropped.
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.warning(
+ "alerts_platform_live_delivery_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()
+ if team is None or not destinations_are_live(team):
+ return DeliveryOutcome(live=False, sent=0, skipped_without_transport=0)
+
+ announced = announcement(request.team_id, request.configuration_id, request.evaluation_key)
+ if announced is None:
+ return DeliveryOutcome(live=True, sent=0, skipped_without_transport=0)
+
+ thread_store = DatabaseThreadStore(request.team_id)
+ sent = 0
+ skipped = 0
+ # Per subscription rather than per destination. A destination subscribes to some of the
+ # kinds an alert can announce, so one that asked for firings must not be handed the resolve
+ # that another group produced in the same evaluation.
+ for event_id, transitions in _by_subscription(request, announced).items():
+ for target in _destinations(request, event_id):
+ transport_class = _TRANSPORTS.get(target["type"])
+ if transport_class is None:
+ skipped += 1
+ continue
+ deliver(
+ transport=transport_class(),
+ thread_store=thread_store,
+ team_id=request.team_id,
+ configuration_id=request.configuration_id,
+ evaluation_key=request.evaluation_key,
+ target=target,
+ announcement=replace(announced, transitions=transitions),
+ )
+ sent += 1
+ return DeliveryOutcome(live=True, sent=sent, skipped_without_transport=skipped)
+
+
+def _by_subscription(
+ request: AlertDeliveryRequest, announced: EvaluationAnnouncement
+) -> dict[str, tuple[AnnouncedTransition, ...]]:
+ """The transitions this evaluation announced, grouped by the event a destination subscribes to.
+
+ A kind the source does not map to an event id reaches nobody: no destination can have asked
+ for it.
+ """
+ grouped: dict[str, list[AnnouncedTransition]] = {}
+ for transition in announced.transitions:
+ event_id = request.event_ids_by_kind.get(transition.kind.value)
+ if event_id is None:
+ continue
+ grouped.setdefault(event_id, []).append(transition)
+ return {event_id: tuple(transitions) for event_id, transitions in grouped.items()}
+
+
+def _destinations(request: AlertDeliveryRequest, event_id: str) -> list[AlertDestinationData]:
+ """Who subscribed to this event, resolved now rather than pinned when the check ran.
+
+ A destination removed between the check and the send is not sent to, which a pinned set
+ would get wrong.
+ """
+ groups = list_alert_destination_groups(
+ team_id=request.team_id,
+ alert_id=request.destination_alert_id,
+ allowed_event_ids=[event_id],
+ )
+ return [group.data for group in groups if group.fully_enabled]
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 633ee10f20a2..5de39d382619 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -281,20 +281,26 @@ class EvaluationAnnouncement:
@frozen
-class AlertDeliveryPreview:
- """What delivery would send. The PoC records it instead of contacting a destination.
-
- A delivery addresses its history rows by `configuration_id`, the transition's `grouping_key`
- and `evaluation_key` together. The rows also carry an `alert_id`, which is the
- `PlatformAlert` instance rather than the configuration, so nothing here is joined to it.
+class AlertDeliveryRequest:
+ """Where to find what one evaluation decided, rather than a copy of it.
+
+ A delivery addresses its history rows by `configuration_id` and `evaluation_key`, and reads
+ the facts back from there. So a retry announces what was recorded rather than what one
+ attempt happened to carry, and a batch's payload does not grow with what its alerts say.
+
+ The two destination fields are supplied by the source because only the source knows them.
+ `destination_alert_id` is the id its destinations are matched on, which is the legacy
+ configuration while the platform runs beside a source's own stack. `event_ids_by_kind` maps
+ each kind the source can announce onto the event id its destinations filter on. The platform
+ imports no source, so it cannot derive either.
"""
source: SourceKind
+ team_id: int
configuration_id: str
- alert_name: str
evaluation_key: str
- destination_names: tuple[str, ...]
- transitions: tuple[GroupTransition, ...]
+ destination_alert_id: str
+ event_ids_by_kind: dict[str, str]
@frozen
@@ -306,7 +312,7 @@ class SourceBatchEvaluation:
"""
outcomes: tuple[PlatformAlertOutcome, ...]
- previews: tuple[AlertDeliveryPreview, ...]
+ deliveries: tuple[AlertDeliveryRequest, ...]
# Pairs the payload bound left out. They keep their due time and a later tick re-evaluates
# them, the way a truncated cohort already behaves.
omitted: int = 0
diff --git a/products/alerts/backend/logic/platform_alert_events.py b/products/alerts/backend/logic/platform_alert_events.py
index 919fef8fdbf7..de762a4db287 100644
--- a/products/alerts/backend/logic/platform_alert_events.py
+++ b/products/alerts/backend/logic/platform_alert_events.py
@@ -25,6 +25,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.dataclasses import frozen
+from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
from products.alerts.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TABLE
logger = structlog.get_logger(__name__)
@@ -136,3 +137,72 @@ def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:
)
return 0
return len(rows)
+
+
+_ANNOUNCEMENT_SQL = f"""
+SELECT grouping_key, kind, episode_started_at, value, labels, condition_snapshot,
+ source_config_snapshot, error_message, alert_name, consecutive_failures
+FROM {PLATFORM_ALERT_EVENTS_TABLE}
+WHERE team_id = %(team_id)s
+ AND configuration_id = %(configuration_id)s
+ AND evaluation_key = %(evaluation_key)s
+ AND kind != %(check_kind)s
+ORDER BY grouping_key, occurred_at DESC
+LIMIT 1 BY grouping_key
+"""
+
+
+def announcement(team_id: int, configuration_id: str, evaluation_key: str) -> EvaluationAnnouncement | None:
+ """What one evaluation left for a destination to say, or None when it announced nothing.
+
+ Rows whose kind is `CHECK` are excluded here rather than in the caller. They are recorded so
+ a comparison can read every check, and they say nothing, so a message built from one would
+ have no headline.
+
+ `LIMIT 1 BY grouping_key` is the read's own deduplication. The insert carries a token the
+ engine drops a repeat under, but it only remembers a bounded window of them, so a retry far
+ enough behind writes a second row for a group. The newest is the one this evaluation meant.
+ """
+ tag_queries(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.ALERTING)
+ rows = sync_execute(
+ _ANNOUNCEMENT_SQL,
+ {
+ "team_id": team_id,
+ "configuration_id": configuration_id,
+ "evaluation_key": evaluation_key,
+ "check_kind": AlertEventKind.CHECK.value,
+ },
+ team_id=team_id,
+ )
+ if not rows:
+ return None
+
+ transitions = tuple(
+ AnnouncedTransition(
+ grouping_key=grouping_key,
+ kind=AlertEventKind(kind),
+ episode_started_at=episode_started_at,
+ value=value,
+ labels=dict(labels or {}),
+ condition=_snapshot(condition_snapshot),
+ source_config=_snapshot(source_config_snapshot),
+ error_message=error_message or None,
+ )
+ for grouping_key, kind, episode_started_at, value, labels, condition_snapshot, source_config_snapshot, error_message, _, _ in rows
+ )
+ # Evaluation-level, and the same on every row of one evaluation, so the first row carries it.
+ alert_name, consecutive_failures = rows[0][8], rows[0][9]
+ return EvaluationAnnouncement(
+ alert_name=alert_name, consecutive_failures=consecutive_failures, transitions=transitions
+ )
+
+
+def _snapshot(raw: str) -> dict[str, Any]:
+ """A snapshot column the writer may have left empty, or that predates the field it holds."""
+ if not raw:
+ return {}
+ try:
+ loaded = json.loads(raw)
+ except ValueError:
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.py
index 02dab365fd78..d13808c1692f 100644
--- a/products/alerts/backend/temporal/workflows.py
+++ b/products/alerts/backend/temporal/workflows.py
@@ -32,8 +32,9 @@ with workflow.unsafe.imports_passed_through():
from posthog.sync import database_sync_to_async_pool
+ from products.alerts.backend.delivery.evaluation import deliver_evaluation
from products.alerts.backend.facade.contracts import (
- AlertDeliveryPreview,
+ AlertDeliveryRequest,
AlertDemand,
DemandDiscoveryInputs,
OrchestrateInputs,
@@ -93,29 +94,43 @@ async def alerts_platform_deliver_activity() -> None:
@activity.defn
-async def alerts_platform_deliver_preview_activity(preview: AlertDeliveryPreview) -> None:
- """Records what delivery would have sent. The PoC contacts no destination."""
+async def alerts_platform_deliver_preview_activity(request: AlertDeliveryRequest) -> None:
+ """Sends what one evaluation decided, once destinations are live for the team.
+
+ Until then it records what it would have sent and contacts nobody, which is the same shape
+ the activity has had since the PoC.
+
+ The delivery package is synchronous: it reads the history, resolves destinations through
+ the ORM and posts over a blocking client. Django refuses an ORM call from a thread with a
+ running event loop, so the whole call crosses on the pool rather than one part of it.
+ """
+ outcome = await database_sync_to_async_pool(deliver_evaluation)(request)
+ if not outcome.live:
+ await LOGGER.ainfo(
+ "alerts_platform_delivery_preview",
+ source=request.source.value,
+ configuration_id=request.configuration_id,
+ evaluation_key=request.evaluation_key,
+ )
+ safe_record(increment_deliveries_previewed, request.source.value)
+ return
+
await LOGGER.ainfo(
- "alerts_platform_delivery_preview",
- source=preview.source.value,
- configuration_id=preview.configuration_id,
- alert_name=preview.alert_name,
- evaluation_key=preview.evaluation_key,
- destinations=list(preview.destination_names),
- transitions=[
- {"grouping_key": transition.grouping_key, "kind": transition.kind.value, "value": transition.value}
- for transition in preview.transitions
- ],
+ "alerts_platform_delivered",
+ source=request.source.value,
+ configuration_id=request.configuration_id,
+ evaluation_key=request.evaluation_key,
+ sent=outcome.sent,
+ skipped_without_transport=outcome.skipped_without_transport,
)
- safe_record(increment_deliveries_previewed, preview.source.value)
@workflow.defn(name="alerts-platform-deliver-preview")
class AlertsPlatformDeliverPreviewWorkflow(PostHogWorkflow):
- inputs_cls = AlertDeliveryPreview
+ inputs_cls = AlertDeliveryRequest
@workflow.run
- async def run(self, inputs: AlertDeliveryPreview) -> None:
+ async def run(self, inputs: AlertDeliveryRequest) -> None:
await workflow.execute_activity(
alerts_platform_deliver_preview_activity,
inputs,
diff --git a/products/alerts/backend/test/test_delivery_evaluation.py b/products/alerts/backend/test/test_delivery_evaluation.py
new file mode 100644
index 000000000000..1317eac06a95
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_evaluation.py
@@ -0,0 +1,176 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from products.alerts.backend.delivery.evaluation import LIVE_DELIVERY_FLAG, deliver_evaluation
+from products.alerts.backend.delivery.message import AlertMessage
+from products.alerts.backend.delivery.transport import MessageHandle
+from products.alerts.backend.facade.contracts import (
+ AlertDeliveryRequest,
+ AlertDestinationData,
+ AlertDestinationGroup,
+ AlertEventKind,
+ AnnouncedTransition,
+ DestinationType,
+ EvaluationAnnouncement,
+ SourceKind,
+)
+
+_MODULE = "products.alerts.backend.delivery.evaluation"
+FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
+
+FIRING_EVENT = "$logs_alert_firing"
+RESOLVED_EVENT = "$logs_alert_resolved"
+
+SLACK = cast(AlertDestinationData, {"type": DestinationType.SLACK, "slack_workspace_id": 1, "slack_channel_id": "C-1"})
+WEBHOOK = cast(AlertDestinationData, {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/hook"})
+
+
+class RecordingTransport:
+ """Stands in for Slack at the edge, so everything inside `deliver` stays real."""
+
+ sends: list[tuple[str, AlertMessage]] = []
+ provider = "slack"
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return str(target.get("slack_channel_id", ""))
+
+ def deliver(
+ self, *, team_id: int, target: AlertDestinationData, message: AlertMessage, in_reply_to: Any = None
+ ) -> MessageHandle | None:
+ RecordingTransport.sends.append((self.channel_target(target), message))
+ return MessageHandle(external_ref={"channel": self.channel_target(target), "ts": "1"})
+
+
+def _request(team_id: int) -> AlertDeliveryRequest:
+ return AlertDeliveryRequest(
+ source=SourceKind.LOGS,
+ team_id=team_id,
+ configuration_id="cfg-1",
+ evaluation_key="eval-1",
+ destination_alert_id="legacy-1",
+ event_ids_by_kind={"firing": FIRING_EVENT, "resolved": RESOLVED_EVENT},
+ )
+
+
+def _transition(kind: AlertEventKind, grouping_key: str = "") -> AnnouncedTransition:
+ return AnnouncedTransition(
+ grouping_key=grouping_key,
+ kind=kind,
+ episode_started_at=FIRING,
+ value=None,
+ labels={},
+ condition={},
+ source_config={},
+ error_message=None,
+ )
+
+
+def _announcement(*transitions: AnnouncedTransition) -> EvaluationAnnouncement:
+ return EvaluationAnnouncement(alert_name="API errors", consecutive_failures=0, transitions=transitions)
+
+
+def _group(data: AlertDestinationData, fully_enabled: bool = True) -> AlertDestinationGroup:
+ return AlertDestinationGroup(hog_function_ids=(), data=data, fully_enabled=fully_enabled)
+
+
+class TestDeliverEvaluation(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ RecordingTransport.sends = []
+
+ def _run(self, announced: Any, by_event: dict[str, list[AlertDestinationGroup]], live: bool = True) -> Any:
+ def groups(*, team_id: int, alert_id: str, allowed_event_ids: list[str]) -> list[AlertDestinationGroup]:
+ return by_event.get(allowed_event_ids[0], [])
+
+ with (
+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=live),
+ patch(f"{_MODULE}.announcement", return_value=announced),
+ patch(f"{_MODULE}.list_alert_destination_groups", side_effect=groups),
+ patch(f"{_MODULE}.DatabaseThreadStore"),
+ patch.dict(f"{_MODULE}._TRANSPORTS", {DestinationType.SLACK: RecordingTransport}),
+ ):
+ return deliver_evaluation(_request(self.team.id))
+
+ def test_a_destination_hears_only_about_the_kinds_it_subscribed_to(self) -> None:
+ # One group fires while another resolves. A destination that asked for firings must not
+ # be told about the resolve just because the same evaluation produced it.
+ announced = _announcement(
+ _transition(AlertEventKind.FIRING, "checkout"),
+ _transition(AlertEventKind.RESOLVED, "search"),
+ )
+ fires_only = cast(AlertDestinationData, {**SLACK, "slack_channel_id": "C-fires"})
+ resolves_only = cast(AlertDestinationData, {**SLACK, "slack_channel_id": "C-resolves"})
+
+ self._run(announced, {FIRING_EVENT: [_group(fires_only)], RESOLVED_EVENT: [_group(resolves_only)]})
+
+ assert sorted((channel, m.headline) for channel, m in RecordingTransport.sends) == [
+ ("C-fires", "API errors is firing"),
+ ("C-resolves", "API errors is resolved"),
+ ]
+
+ def test_a_destination_subscribed_to_both_hears_about_both(self) -> None:
+ announced = _announcement(
+ _transition(AlertEventKind.FIRING, "checkout"),
+ _transition(AlertEventKind.RESOLVED, "search"),
+ )
+
+ self._run(announced, {FIRING_EVENT: [_group(SLACK)], RESOLVED_EVENT: [_group(SLACK)]})
+
+ assert sorted(m.headline for _, m in RecordingTransport.sends) == [
+ "API errors is firing",
+ "API errors is resolved",
+ ]
+
+ def test_a_destination_with_no_transport_is_skipped_rather_than_failing_the_send(self) -> None:
+ outcome = self._run(
+ _announcement(_transition(AlertEventKind.FIRING)),
+ {FIRING_EVENT: [_group(SLACK), _group(WEBHOOK)]},
+ )
+
+ assert [channel for channel, _ in RecordingTransport.sends] == ["C-1"]
+ assert (outcome.sent, outcome.skipped_without_transport) == (1, 1)
+
+ def test_a_destination_that_is_not_fully_enabled_receives_nothing(self) -> None:
+ outcome = self._run(
+ _announcement(_transition(AlertEventKind.FIRING)),
+ {FIRING_EVENT: [_group(SLACK, fully_enabled=False)]},
+ )
+
+ assert RecordingTransport.sends == []
+ assert outcome.sent == 0
+
+ def test_an_evaluation_that_announced_nothing_sends_nothing(self) -> None:
+ outcome = self._run(None, {FIRING_EVENT: [_group(SLACK)]})
+
+ assert RecordingTransport.sends == []
+ assert outcome.sent == 0
+
+ def test_a_team_without_the_flag_is_not_contacted(self) -> None:
+ outcome = self._run(
+ _announcement(_transition(AlertEventKind.FIRING)), {FIRING_EVENT: [_group(SLACK)]}, live=False
+ )
+
+ assert RecordingTransport.sends == []
+ assert outcome.live is False
+
+ def test_the_flag_is_read_against_the_project(self) -> None:
+ # Without the project group the condition never matches, and the platform stays silent
+ # with nothing to say why.
+ with (
+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=False) as flag,
+ patch(f"{_MODULE}.announcement", return_value=None),
+ ):
+ deliver_evaluation(_request(self.team.id))
+
+ assert flag.call_args.args[0] == LIVE_DELIVERY_FLAG
+ assert flag.call_args.kwargs["groups"]["project"] == str(self.team.id)
+
+ def test_a_flag_that_cannot_be_read_leaves_the_legacy_path_as_the_only_deliverer(self) -> None:
+ with patch(f"{_MODULE}.posthoganalytics.feature_enabled", side_effect=RuntimeError("flags unreachable")):
+ outcome = deliver_evaluation(_request(self.team.id))
+
+ assert RecordingTransport.sends == []
+ assert outcome.live is False
diff --git a/products/alerts/backend/test/test_platform_announcement.py b/products/alerts/backend/test/test_platform_announcement.py
new file mode 100644
index 000000000000..fd140e779872
--- /dev/null
+++ b/products/alerts/backend/test/test_platform_announcement.py
@@ -0,0 +1,126 @@
+from datetime import UTC, datetime, timedelta
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models.scoping import team_scope
+
+from products.alerts.backend.facade.contracts import AlertEventKind
+from products.alerts.backend.logic.platform_alert_events import (
+ _INSERT_SQL,
+ PlatformAlertEventRow,
+ announcement,
+ insert_events,
+)
+from products.alerts.backend.models import PlatformAlertConfiguration
+
+OCCURRED = datetime(2026, 9, 30, 10, tzinfo=UTC)
+FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
+
+
+class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ with team_scope(self.team.id):
+ self.configuration = PlatformAlertConfiguration.objects.create(
+ team=self.team,
+ name="API errors",
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config={},
+ threshold_count=10,
+ threshold_operator="above",
+ window_minutes=5,
+ check_interval_minutes=10,
+ )
+
+ def _row(self, **overrides) -> PlatformAlertEventRow:
+ fields = {
+ "team_id": self.team.id,
+ "configuration_id": self.configuration.id,
+ "alert_id": self.configuration.id,
+ "grouping_key": "",
+ "evaluation_key": "eval-1",
+ "kind": AlertEventKind.FIRING,
+ "alert_name": "API errors",
+ "previous_state": "not_firing",
+ "state": "firing",
+ "episode_started_at": FIRING,
+ "value": 300.0,
+ "labels": {},
+ "condition_snapshot": {"threshold_count": 10, "threshold_operator": "above"},
+ "source_config_snapshot": {"service_names": ["checkout"]},
+ "query_duration_ms": 12,
+ "error_message": "",
+ "consecutive_failures": 0,
+ "muted_notification": "",
+ "occurred_at": OCCURRED,
+ }
+ fields.update(overrides)
+ return PlatformAlertEventRow(**fields)
+
+ def _announcement(self, evaluation_key: str = "eval-1"):
+ return announcement(self.team.id, str(self.configuration.id), evaluation_key)
+
+ def test_a_recorded_firing_comes_back_as_the_message_it_should_send(self) -> None:
+ insert_events(self.team.id, [self._row()])
+
+ result = self._announcement()
+
+ assert result is not None
+ assert result.alert_name == "API errors"
+ assert [t.kind for t in result.transitions] == [AlertEventKind.FIRING]
+ transition = result.transitions[0]
+ assert transition.episode_started_at == FIRING
+ assert transition.value == 300.0
+ # The snapshots are what let a message state what its own check measured, however long
+ # after the check it is rendered.
+ assert transition.condition["threshold_count"] == 10
+ assert transition.source_config["service_names"] == ["checkout"]
+
+ def test_a_check_that_announced_nothing_reaches_no_destination(self) -> None:
+ insert_events(self.team.id, [self._row(kind=AlertEventKind.CHECK)])
+
+ assert self._announcement() is None
+
+ def test_every_group_that_announced_gets_its_own_transition(self) -> None:
+ insert_events(
+ self.team.id,
+ [self._row(grouping_key="checkout"), self._row(grouping_key="search", kind=AlertEventKind.RESOLVED)],
+ )
+
+ result = self._announcement()
+
+ assert result is not None
+ assert {(t.grouping_key, t.kind) for t in result.transitions} == {
+ ("checkout", AlertEventKind.FIRING),
+ ("search", AlertEventKind.RESOLVED),
+ }
+
+ def test_a_group_written_twice_announces_once_from_the_newer_row(self) -> None:
+ insert_events(self.team.id, [self._row()])
+ # Under its own token the engine drops this, which is what the token is for. The window
+ # it remembers tokens for is bounded, so a late enough retry does land a second row, and
+ # announcing both would send the same alert twice.
+ sync_execute(
+ _INSERT_SQL,
+ [self._row(kind=AlertEventKind.RESOLVED, occurred_at=OCCURRED + timedelta(minutes=1)).as_row()],
+ # Unique per run: ClickHouse remembers tokens between them, so a fixed one would
+ # make the second run of this test insert nothing.
+ settings={"insert_deduplication_token": str(uuid4())},
+ team_id=self.team.id,
+ )
+
+ result = self._announcement()
+
+ assert result is not None
+ assert [t.kind for t in result.transitions] == [AlertEventKind.RESOLVED]
+
+ def test_another_evaluation_of_the_same_alert_is_not_mixed_in(self) -> None:
+ insert_events(self.team.id, [self._row()])
+ insert_events(self.team.id, [self._row(evaluation_key="eval-2", kind=AlertEventKind.RESOLVED)])
+
+ result = self._announcement("eval-1")
+
+ assert result is not None
+ assert [t.kind for t in result.transitions] == [AlertEventKind.FIRING]
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 625ec56e366c..93b1defdee37 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -18,7 +18,7 @@ import time
from collections.abc import Sequence
from datetime import datetime, timedelta
from itertools import batched
-from typing import cast
+from typing import Final, cast
from uuid import UUID
import structlog
@@ -27,9 +27,8 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from products.alerts.backend.facade.contracts import (
- AlertDeliveryPreview,
+ AlertDeliveryRequest,
AlertEventKind,
- GroupTransition,
MuteReason,
PlatformAlertCheckInput,
PlatformAlertOutcome,
@@ -37,7 +36,6 @@ from products.alerts.backend.facade.contracts import (
SourceBatchEvaluation,
SourceKind,
)
-from products.alerts.backend.facade.destinations import list_active_alert_destinations
from products.alerts.backend.facade.lifecycle import (
PLATFORM_LOGS_ALERT_POLICY,
AlertCheckOutcome,
@@ -84,7 +82,7 @@ logger = structlog.get_logger(__name__)
# A fleet-wide burst would otherwise return one activity payload over Temporal's ~2 MiB limit,
# which fails the whole batch rather than truncating it. The bound drops an outcome along with
# the preview it belongs to, so a breach this batch cannot announce keeps its due time.
-MAX_PREVIEWS_PER_CYCLE = 500
+MAX_DELIVERIES_PER_CYCLE = 500
# Cohorts run one after another, and the production runner measures about four seconds each. A
# higher bound spends the query budget below and returns fewer cohorts, not more; a cohort left
@@ -169,7 +167,7 @@ def _snapshot(check: PlatformAlertCheckInput, prior_breached: tuple[bool, ...])
)
-Decision = tuple[PlatformAlertOutcome, AlertDeliveryPreview | None]
+Decision = tuple[PlatformAlertOutcome, AlertDeliveryRequest | None]
@frozen
@@ -298,26 +296,27 @@ def _delivery(
if outcome.notification == NotificationAction.NONE:
return recorded, None
- spec = EVENT_KIND_CONFIG[cast(EventKind, recorded.kind.value)]
- destinations = list_active_alert_destinations(
- team_id=check.team_id,
- alert_id=str(check.legacy_configuration_id or check.id),
- allowed_event_ids=[spec.event_id],
- )
- return recorded, AlertDeliveryPreview(
+ return recorded, AlertDeliveryRequest(
source=SourceKind.LOGS,
+ team_id=check.team_id,
configuration_id=str(check.id),
- alert_name=check.name,
# The recorded key unchanged, so a delivery can address the row the check wrote. The
# workflow id that has to be unique across alerts joins this to the configuration itself.
evaluation_key=recorded.evaluation_key,
- destination_names=tuple(destination.name for destination in destinations),
- # One transition with an empty grouping key. Logs does not group yet, and delivery
- # reads a list either way, so fan-out changes this call and nothing downstream.
- transitions=(GroupTransition(grouping_key="", kind=recorded.kind, value=recorded.value),),
+ destination_alert_id=str(check.legacy_configuration_id or check.id),
+ event_ids_by_kind=_EVENT_IDS_BY_KIND,
)
+# Which event id each announced kind's destinations filter on. Resolved here because the
+# platform imports no source and cannot read `EVENT_KIND_CONFIG`.
+_EVENT_IDS_BY_KIND: Final[dict[str, str]] = {
+ kind.value: EVENT_KIND_CONFIG[cast(EventKind, kind.value)].event_id
+ for kind in AlertEventKind
+ if kind.value in EVENT_KIND_CONFIG
+}
+
+
def _evaluate_one(
check: PlatformAlertCheckInput, buckets: list[BucketedCount], *, now: datetime, muted: bool
) -> AlertCheckOutcome:
@@ -480,27 +479,27 @@ def _triage(checks: Sequence[PlatformAlertCheckInput], *, now: datetime, tz_name
def _collect(decided: Sequence[Decision], team_id: int, slot: str, started_at: float) -> SourceBatchEvaluation:
"""Applies the payload bound and reports the batch."""
outcomes: list[PlatformAlertOutcome] = []
- previews: list[AlertDeliveryPreview] = []
+ deliveries: list[AlertDeliveryRequest] = []
omitted = 0
- for outcome, preview in decided:
- if preview is not None and len(previews) >= MAX_PREVIEWS_PER_CYCLE:
+ for outcome, delivery in decided:
+ if delivery is not None and len(deliveries) >= MAX_DELIVERIES_PER_CYCLE:
omitted += 1
continue
outcomes.append(outcome)
- if preview is not None:
- previews.append(preview)
+ if delivery is not None:
+ deliveries.append(delivery)
if omitted:
logger.warning(
"Deferred logs alert deliveries over the batch payload bound",
team_id=team_id,
slot=slot,
- delivered=len(previews),
+ delivered=len(deliveries),
deferred=omitted,
)
safe_record(increment_deliveries_deferred, SourceKind.LOGS.value, omitted)
safe_record(record_batch_duration, SourceKind.LOGS.value, int((time.monotonic() - started_at) * 1000))
- return SourceBatchEvaluation(outcomes=tuple(outcomes), previews=tuple(previews), omitted=omitted)
+ return SourceBatchEvaluation(outcomes=tuple(outcomes), deliveries=tuple(deliveries), omitted=omitted)
def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatchEvaluation:
@@ -516,11 +515,11 @@ def evaluate_logs_batch(team_id: int, slot: str, cutoff: datetime) -> SourceBatc
started_at = time.monotonic()
checks = due_checks(team_id, SourceKind.LOGS.value, slot, cutoff)
if not checks:
- return SourceBatchEvaluation(outcomes=(), previews=())
+ return SourceBatchEvaluation(outcomes=(), deliveries=())
team = Team.objects.filter(id=team_id).first()
if team is None:
- return SourceBatchEvaluation(outcomes=(), previews=())
+ return SourceBatchEvaluation(outcomes=(), deliveries=())
triage = _triage(checks, now=cutoff, tz_name=team.timezone)
if not triage.evaluable:
diff --git a/products/logs/backend/temporal/alert_evaluate.py b/products/logs/backend/temporal/alert_evaluate.py
index 5cb6376e0318..907ae05e6ae0 100644
--- a/products/logs/backend/temporal/alert_evaluate.py
+++ b/products/logs/backend/temporal/alert_evaluate.py
@@ -103,13 +103,13 @@ class LogsAlertEvaluateWorkflow(PostHogWorkflow):
*(
workflow.start_child_workflow(
"alerts-platform-deliver-preview",
- preview,
- id=f"alerts-deliver-preview-{preview.configuration_id}:{preview.evaluation_key}",
+ delivery,
+ id=f"alerts-deliver-preview-{delivery.configuration_id}:{delivery.evaluation_key}",
task_queue=settings.ALERTS_PLATFORM_DELIVERY_TASK_QUEUE,
parent_close_policy=workflow.ParentClosePolicy.ABANDON,
execution_timeout=dt.timedelta(minutes=1),
)
- for preview in evaluation.previews
+ for delivery in evaluation.deliveries
),
return_exceptions=True,
)
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 37bf1caa511b..ccc3d860da99 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -12,7 +12,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.models.scoping import team_scope
-from products.alerts.backend.facade.contracts import AlertEventKind, GroupTransition, SourceBatchEvaluation, SourceKind
+from products.alerts.backend.facade.contracts import AlertEventKind, SourceBatchEvaluation, SourceKind
from products.alerts.backend.facade.platform_alerts import due_checks, record_outcomes, slot_of
from products.alerts.backend.facade.temporal import SOURCE_EVALUATION_TIMEOUT
from products.alerts.backend.models import PlatformAlert, PlatformAlertConfiguration
@@ -88,9 +88,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(configuration)
self._record(evaluation)
- assert [t for preview in evaluation.previews for t in preview.transitions] == [
- GroupTransition(grouping_key="", kind=AlertEventKind.FIRING, value=500.0)
- ]
+ assert [(o.kind, o.value) for o in evaluation.outcomes] == [(AlertEventKind.FIRING, 500.0)]
with team_scope(self.team.id):
alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
configuration.refresh_from_db()
@@ -112,7 +110,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
evaluation, _ = self._run(configuration)
- assert evaluation.previews
+ assert evaluation.deliveries
with team_scope(self.team.id):
configuration.refresh_from_db()
assert not PlatformAlert.objects.filter(configuration=configuration).exists()
@@ -121,13 +119,13 @@ class TestLogsAlertEvaluation(APIBaseTest):
def test_a_delivery_the_batch_cannot_carry_leaves_its_alert_due(self) -> None:
configurations = [self._configuration(), self._configuration()]
- with patch(f"{_MODULE}.MAX_PREVIEWS_PER_CYCLE", 1):
+ with patch(f"{_MODULE}.MAX_DELIVERIES_PER_CYCLE", 1):
evaluation, _ = self._run(*configurations)
self._record(evaluation)
# A firing alert does not fire again, so recording the second outcome would retire its
# breach with no delivery to announce it.
- assert len(evaluation.previews) == 1
+ assert len(evaluation.deliveries) == 1
assert evaluation.omitted == 1
with team_scope(self.team.id):
still_due = PlatformAlertConfiguration.objects.filter(
@@ -174,7 +172,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
self._record(evaluation)
query.assert_called_once()
- assert evaluation.previews == ()
+ assert evaluation.deliveries == ()
with team_scope(self.team.id):
alert = PlatformAlert.objects.get(configuration=configuration, grouping_key="")
configuration.refresh_from_db()
@@ -190,7 +188,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
# firing reaching it, a FIRING alert does not fire again on its own and stays silent.
unmuted, _ = self._run(configuration, now=datetime(2026, 9, 16, 12, 30, tzinfo=UTC))
- assert [t.kind for preview in unmuted.previews for t in preview.transitions] == [AlertEventKind.FIRING]
+ assert [o.kind for o in unmuted.outcomes] == [AlertEventKind.FIRING]
def test_a_broken_filter_config_stops_being_discovered(self) -> None:
configuration = self._configuration(source_config={"filterGroup": {"type": "nonsense"}})
@@ -229,7 +227,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
def test_a_failure_the_batch_cannot_record_leaves_the_whole_batch_due(self) -> None:
configuration = self._configuration(consecutive_failures=4)
- with patch(f"{_MODULE}.list_active_alert_destinations", side_effect=RuntimeError("destinations unreachable")):
+ with patch(f"{_MODULE}._delivery", side_effect=RuntimeError("something after the query failed")):
with pytest.raises(RuntimeError):
self._run(configuration, query_error=ExposedHogQLError("unknown field"))
@@ -238,21 +236,6 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert not PlatformAlert.objects.filter(configuration=configuration).exists()
assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
- def test_a_destination_lookup_failure_is_not_the_checks_own_failure(self) -> None:
- configuration = self._configuration()
-
- # The second answer is what a retry inside the evaluation would reach. Reaching it means
- # a lookup failure was recorded as a failed check, after a query that succeeded.
- with patch(f"{_MODULE}.list_active_alert_destinations", side_effect=[RuntimeError("unreachable"), []]):
- with pytest.raises(RuntimeError):
- self._run(configuration)
-
- with team_scope(self.team.id):
- configuration.refresh_from_db()
- assert not PlatformAlert.objects.filter(configuration=configuration).exists()
- assert configuration.consecutive_failures == 0
- assert configuration.next_check_at == self.cutoff - timedelta(minutes=1)
-
def test_the_logs_product_rows_are_never_written(self) -> None:
legacy = LogsAlertConfiguration.objects.create(
team=self.team,
@@ -294,7 +277,7 @@ class TestLogsAlertEvaluation(APIBaseTest):
# same window end, and a key without it makes them one evaluation to any reader.
expected = f"slot:{self.cutoff.isoformat()}|window:{self.cutoff.isoformat()}"
assert evaluation.outcomes[0].evaluation_key == expected
- assert [p.evaluation_key for p in evaluation.previews] == [expected]
+ assert [d.evaluation_key for d in evaluation.deliveries] == [expected]
class TestEvaluationTimeoutLadder(SimpleTestCase):