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 a native delivery package with a slack transport (#105603)

Jimmy Zhu7ddf38be5d62
diff --git a/products/alerts/backend/delivery/__init__.py b/products/alerts/backend/delivery/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/alerts/backend/delivery/dispatch.py b/products/alerts/backend/delivery/dispatch.py
new file mode 100644
index 000000000000..2816895aa343
--- /dev/null
+++ b/products/alerts/backend/delivery/dispatch.py
@@ -0,0 +1,75 @@
+"""One delivery, end to end.
+
+Ties together what a notification says, where the last one landed, and the provider that sends
+it. Which destinations an alert has is resolved before this, so a change to that resolution
+reaches no transport.
+"""
+
+from products.alerts.backend.delivery.message import build_message
+from products.alerts.backend.delivery.telemetry import record_delivery
+from products.alerts.backend.delivery.thread_store import ThreadKey, ThreadStore
+from products.alerts.backend.delivery.transport import DeliveryTransport
+from products.alerts.backend.facade.contracts import AlertDestinationData, AnnouncedTransition, EvaluationAnnouncement
+
+
+def deliver(
+ *,
+ transport: DeliveryTransport,
+ thread_store: ThreadStore,
+ team_id: int,
+ configuration_id: str,
+ target: AlertDestinationData,
+ announcement: EvaluationAnnouncement,
+) -> None:
+ channel_target = transport.channel_target(target)
+
+ for transition in announcement.transitions:
+ key = _thread_key(
+ configuration_id=configuration_id,
+ provider=transport.provider,
+ channel_target=channel_target,
+ transition=transition,
+ )
+ handle = thread_store.handle_for(key) if key is not None else None
+ message = build_message(announcement, transition)
+ try:
+ sent = transport.deliver(team_id=team_id, target=target, message=message, in_reply_to=handle)
+ except Exception:
+ # Every failure class. Counting only the refusals a provider names leaves an outage
+ # reading as no delivery attempted at all.
+ record_delivery(
+ team_id=team_id,
+ configuration_id=configuration_id,
+ provider=transport.provider,
+ succeeded=False,
+ )
+ raise
+ record_delivery(team_id=team_id, configuration_id=configuration_id, provider=transport.provider, succeeded=True)
+ # Only the first message of a conversation is remembered. Remembering a reply would move
+ # the thread onto itself, so a later message would reply to a reply.
+ if sent is not None and handle is None and key is not None:
+ thread_store.remember(key, sent)
+
+
+def _thread_key(
+ *,
+ configuration_id: str,
+ provider: str,
+ channel_target: str,
+ transition: AnnouncedTransition,
+) -> ThreadKey | None:
+ """Which conversation this message belongs to, or None when it belongs to none.
+
+ A message about no firing, which is a failed or a turned-off check, continues no
+ conversation and starts none. Keying one on the absent firing would thread every such
+ message for a configuration into the first one, which is the defect the episode prevents.
+ """
+ if transition.episode_started_at is None:
+ return None
+ return ThreadKey(
+ configuration_id=configuration_id,
+ grouping_key=transition.grouping_key,
+ provider=provider,
+ channel_target=channel_target,
+ episode_started_at=transition.episode_started_at,
+ )
diff --git a/products/alerts/backend/delivery/message.py b/products/alerts/backend/delivery/message.py
new file mode 100644
index 000000000000..a3761e625a36
--- /dev/null
+++ b/products/alerts/backend/delivery/message.py
@@ -0,0 +1,94 @@
+"""What a notification says, built from the rows the evaluation recorded.
+
+Source-agnostic. Every fact comes from an `AnnouncedTransition`, which the platform projects from
+a `PlatformAlertEvent`, so a message states what its own check decided however long after the
+check it is rendered. A provider turns this into its own body shape.
+"""
+
+from typing import Any, Final
+
+from posthog.dataclasses import frozen
+from posthog.utils import pluralize
+
+from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
+
+_HEADLINES: Final[dict[AlertEventKind, str]] = {
+ AlertEventKind.FIRING: "{name} is firing",
+ AlertEventKind.RESOLVED: "{name} is resolved",
+ AlertEventKind.ERRORED: "{name} could not be checked",
+ AlertEventKind.BROKEN: "{name} is turned off",
+}
+
+
+@frozen
+class MessageDetail:
+ """One labelled fact in a message. Every provider renders these the same way, as a Slack
+ section, an Adaptive Card body, or lines of markdown."""
+
+ label: str
+ value: str
+
+
+@frozen
+class AlertMessage:
+ """One notification, before a provider formats it."""
+
+ headline: str
+ details: tuple[MessageDetail, ...]
+
+
+def _number(value: float) -> str:
+ """A count reads as 300 rather than 300.0, and a rate keeps the digits it needs."""
+ return f"{value:g}"
+
+
+def _threshold(condition: dict[str, Any]) -> str | None:
+ operator = condition.get("threshold_operator")
+ count = condition.get("threshold_count")
+ if operator is None or count is None:
+ return None
+ return f"{operator} {count}"
+
+
+def _breach_details(transition: AnnouncedTransition) -> list[MessageDetail]:
+ details: list[MessageDetail] = []
+ if transition.value is not None:
+ details.append(MessageDetail(label="Value", value=_number(transition.value)))
+ threshold = _threshold(transition.condition)
+ if threshold is not None:
+ details.append(MessageDetail(label="Threshold", value=threshold))
+ window_minutes = transition.condition.get("window_minutes")
+ if window_minutes:
+ details.append(MessageDetail(label="Window", value=pluralize(window_minutes, "minute")))
+ return details
+
+
+def _failure_details(transition: AnnouncedTransition, consecutive_failures: int) -> list[MessageDetail]:
+ details: list[MessageDetail] = []
+ if transition.error_message:
+ details.append(MessageDetail(label="Error", value=transition.error_message))
+ if consecutive_failures:
+ details.append(MessageDetail(label="Failed checks", value=str(consecutive_failures)))
+ return details
+
+
+def build_message(announcement: EvaluationAnnouncement, transition: AnnouncedTransition) -> AlertMessage:
+ """The message for one transition.
+
+ The announcement carries what the whole evaluation decided, the transition what one group
+ did. One message per transition: what a message says about several groups at once is a copy
+ decision nobody has made, and it arrives with fan-in rather than being guessed at here.
+ """
+ headline = _HEADLINES.get(transition.kind)
+ if headline is None:
+ # `announcement` excludes the check rows, so every transition that reaches delivery
+ # announces something. A check here means that filter is gone.
+ raise ValueError(f"{transition.kind} announces nothing and has no message")
+
+ failure_kinds = (AlertEventKind.ERRORED, AlertEventKind.BROKEN)
+ details = (
+ _failure_details(transition, announcement.consecutive_failures)
+ if transition.kind in failure_kinds
+ else _breach_details(transition)
+ )
+ return AlertMessage(headline=headline.format(name=announcement.alert_name), details=tuple(details))
diff --git a/products/alerts/backend/delivery/slack.py b/products/alerts/backend/delivery/slack.py
new file mode 100644
index 000000000000..fb8291d28e14
--- /dev/null
+++ b/products/alerts/backend/delivery/slack.py
@@ -0,0 +1,96 @@
+"""Slack delivery.
+
+The wire and its telemetry come from `posthog/egress/slack`, through `SlackIntegration`. What
+stays here is the part that is about alerts: which destination a message goes to, and how a
+message becomes blocks.
+"""
+
+from typing import Any, Final
+
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegration
+from posthog.slack.channels import MAX_SECTION_CHARS, clip_text, header_block, post_message, section_block
+from posthog.slack.formatting import escape_slack_mrkdwn
+
+from products.alerts.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts.backend.facade.contracts import AlertDestinationData
+
+PROVIDER: Final = "slack"
+
+# Separates alert traffic from the API-driven calls on the shared Slack egress metrics.
+EGRESS_SOURCE: Final = "alerts"
+
+
+def _line(detail: MessageDetail) -> str:
+ # The value carries a query error, which is user-written text. Unescaped `<...>` is live in
+ # mrkdwn, so `<!channel>` would broadcast and `<url|label>` would render a disguised link.
+ return f"*{detail.label}:* {escape_slack_mrkdwn(detail.value)}"
+
+
+def _body(details: tuple[MessageDetail, ...]) -> str:
+ lines = [_line(detail) for detail in details]
+ body = "\n".join(lines)
+ if len(body) <= MAX_SECTION_CHARS:
+ return body
+ # An error message can carry a whole query, so it is the value that overflows. Clipping the
+ # joined body would drop every detail after it, and the failure count is one of those.
+ share = (MAX_SECTION_CHARS - len(lines) + 1) // len(lines)
+ return "\n".join(clip_text(line, share) for line in lines)
+
+
+def blocks_for(message: AlertMessage) -> list[dict[str, Any]]:
+ blocks: list[dict[str, Any]] = [header_block(message.headline)]
+ if message.details:
+ blocks.append(section_block(_body(message.details)))
+ return blocks
+
+
+class SlackTransport:
+ provider = PROVIDER
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return target.get("slack_channel_id", "")
+
+ def deliver(
+ self,
+ *,
+ team_id: int,
+ target: AlertDestinationData,
+ message: AlertMessage,
+ in_reply_to: MessageHandle | None = None,
+ ) -> MessageHandle | None:
+ workspace_id = target.get("slack_workspace_id")
+ channel = target.get("slack_channel_id")
+ if workspace_id is None or channel is None:
+ raise DeliveryError("This Slack destination is missing its workspace or channel.")
+
+ slack = SlackIntegration(self._integration(team_id=team_id, workspace_id=workspace_id), source=EGRESS_SOURCE)
+ try:
+ response = post_message(
+ slack,
+ channel,
+ blocks_for(message),
+ # The one place the alert's name reaches mrkdwn: the header renders plain text.
+ escape_slack_mrkdwn(message.headline),
+ thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None,
+ )
+ except SlackApiError as error:
+ # A refusal a person can fix, such as a channel the bot has left, rather than a
+ # transport failure a retry would clear.
+ raise DeliveryError(f"Slack refused the message: {error.response.get('error')}") from error
+ timestamp = response.get("ts")
+ if not timestamp:
+ raise DeliveryError("Slack accepted the message but returned no timestamp to reply to.")
+ return MessageHandle(external_ref={"channel": channel, "ts": timestamp})
+
+ def _integration(self, *, team_id: int, workspace_id: int) -> Integration:
+ # Scoped by team as well as by id. The destination names an integration, and nothing
+ # between the destination and here checks that it still belongs to the sending team.
+ integration = Integration.objects.filter(
+ id=workspace_id, team_id=team_id, kind__in=SLACK_INTEGRATION_KINDS
+ ).first()
+ if integration is None:
+ raise DeliveryError("The Slack workspace for this alert is not connected.")
+ return integration
diff --git a/products/alerts/backend/delivery/telemetry.py b/products/alerts/backend/delivery/telemetry.py
new file mode 100644
index 000000000000..2850fca45189
--- /dev/null
+++ b/products/alerts/backend/delivery/telemetry.py
@@ -0,0 +1,38 @@
+"""Delivery outcomes, on the counters an alert's history reads.
+
+`app_source` is `alert`. A HogFunction delivery writes `hog_function`, so a surface showing an
+alert's delivery history has to read both. An alert that moves onto native delivery otherwise
+looks like its history starts over on the day it moved.
+"""
+
+import datetime as dt
+from typing import Final
+
+import structlog
+
+from posthog.kafka_client.routing import get_producer
+from posthog.kafka_client.topics import KAFKA_APP_METRICS2
+from posthog.models.event.util import format_clickhouse_timestamp
+
+ALERT_APP_SOURCE: Final = "alert"
+
+logger = structlog.get_logger(__name__)
+
+
+def record_delivery(*, team_id: int, configuration_id: str, provider: str, succeeded: bool) -> None:
+ payload = {
+ "team_id": team_id,
+ "app_source": ALERT_APP_SOURCE,
+ "app_source_id": configuration_id,
+ "instance_id": provider,
+ "timestamp": format_clickhouse_timestamp(dt.datetime.now(dt.UTC)),
+ "metric_kind": "success" if succeeded else "failure",
+ "metric_name": "succeeded" if succeeded else "failed",
+ "count": 1,
+ }
+ try:
+ producer = get_producer(topic=KAFKA_APP_METRICS2)
+ producer.produce(topic=KAFKA_APP_METRICS2, data=payload)
+ except Exception:
+ # A counter is not worth failing a send that already reached the provider.
+ logger.exception("Failed to emit alert delivery metrics", team_id=team_id, alert_id=configuration_id)
diff --git a/products/alerts/backend/delivery/thread_store.py b/products/alerts/backend/delivery/thread_store.py
new file mode 100644
index 000000000000..9c47769d626a
--- /dev/null
+++ b/products/alerts/backend/delivery/thread_store.py
@@ -0,0 +1,62 @@
+"""Where a provider conversation is remembered between sends.
+
+A resolve replies to the message that fired rather than posting beside it, which needs the
+handle from that first send. The store is an interface before it is a table: the key shape
+follows the delivery table in the implementation RFC, which is not settled, and the null
+implementation lets a transport ship without waiting on it.
+
+The key carries the firing as well, which the RFC's own shape does not. Without it the table
+holds one row per alert instead of one per firing, and there is no version of that decision
+under which a second firing should reply into the first firing's thread.
+
+It carries no `notification_key`. That field only ever differs from the group once fan-in
+ships, and fan-in was deprioritized on 2026-09-28, so the group is what identifies a
+conversation until then.
+"""
+
+from datetime import datetime
+from typing import Protocol
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.delivery.transport import MessageHandle
+
+
+@frozen
+class ThreadKey:
+ """Which conversation a message belongs to.
+
+ Two parts carry that. `grouping_key` separates one group's conversation from another's, and
+ `episode_started_at` separates one firing from the next. Without the episode a key names the
+ alert rather than the firing, so every resolve an alert ever sends replies into the thread
+ its first firing opened. Without the group, two groups of one configuration share a thread.
+
+ One object rather than five arguments, because four of the parts are strings and a caller
+ that passes them separately can reorder them without a typecheck noticing.
+ """
+
+ configuration_id: str
+ grouping_key: str
+ provider: str
+ channel_target: str
+ episode_started_at: datetime
+
+
+class ThreadStore(Protocol):
+ def handle_for(self, key: ThreadKey) -> MessageHandle | None: ...
+
+ def remember(self, key: ThreadKey, handle: MessageHandle) -> None: ...
+
+
+class NullThreadStore:
+ """Remembers nothing, so every message is a new one.
+
+ Not a regression: the platform sends nothing today, so there is no thread to continue. It
+ does mean a resolve posts beside the message that fired rather than under it.
+ """
+
+ def handle_for(self, key: ThreadKey) -> MessageHandle | None:
+ return None
+
+ def remember(self, key: ThreadKey, handle: MessageHandle) -> None:
+ return None
diff --git a/products/alerts/backend/delivery/transport.py b/products/alerts/backend/delivery/transport.py
new file mode 100644
index 000000000000..3d0fa06ed05d
--- /dev/null
+++ b/products/alerts/backend/delivery/transport.py
@@ -0,0 +1,57 @@
+"""The contract between the platform and one provider.
+
+A transport knows a provider's wire format and nothing about alerts beyond the message it is
+handed. What to say is decided before this, and where to send is resolved before this, so a
+transport that gains a provider needs no change anywhere else.
+"""
+
+from typing import Protocol
+
+from posthog.dataclasses import frozen
+
+from products.alerts.backend.delivery.message import AlertMessage
+from products.alerts.backend.facade.contracts import AlertDestinationData
+
+
+@frozen
+class MessageHandle:
+ """Where a provider put a message, so a later send can reply to it or edit it.
+
+ `external_ref` is the provider's own handle, for example `{"channel": ..., "ts": ...}` for
+ Slack. Only the transport that issued one reads it.
+ """
+
+ external_ref: dict[str, str]
+
+
+class DeliveryError(Exception):
+ """A send the provider refused. The caller decides whether to retry."""
+
+
+class DeliveryTransport(Protocol):
+ provider: str
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ """Which conversation this destination is, as the provider names it.
+
+ A repointed destination gives a different answer, which is what stops a reply going
+ into the thread the previous channel held.
+ """
+ ...
+
+ def deliver(
+ self,
+ *,
+ team_id: int,
+ target: AlertDestinationData,
+ message: AlertMessage,
+ in_reply_to: MessageHandle | None = None,
+ ) -> MessageHandle | None:
+ """Sends one message, and says where it landed.
+
+ Returns None when the provider gives nothing back to reply to, which a webhook does.
+ A transport that cannot thread ignores `in_reply_to`, so a caller never branches on the
+ provider. That optional argument is the whole mechanism: a declared capability set would
+ be a second statement of the same fact, free to disagree with it.
+ """
+ ...
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 7e95314635a1..633ee10f20a2 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -239,6 +239,47 @@ class GroupTransition:
value: float | None = None
+@frozen
+class AnnouncedTransition:
+ """One group's transition as delivery reads it back, projected from a history row.
+
+ The sibling of `GroupTransition`, and deliberately not the same type. A `GroupTransition`
+ crosses Temporal on the delivery payload, so it stays small. This never does: delivery holds
+ an address, reads the row, and builds one of these in the process that sends the message. So
+ it carries what a message states, including the two snapshots the row already keeps.
+
+ Every field here is a column on `platform_alert_events`, which is what makes a message state
+ what its own check decided however long after the check it is rendered.
+ """
+
+ grouping_key: str
+ kind: AlertEventKind
+ # The firing this transition concerns, which on a resolve is the firing that just ended.
+ # None when no firing is involved, which is a failed or a turned-off check.
+ episode_started_at: datetime | None
+ value: float | None
+ labels: dict[str, str]
+ condition: dict[str, Any]
+ source_config: dict[str, Any]
+ error_message: str | None
+
+
+@frozen
+class EvaluationAnnouncement:
+ """What one evaluation left for a destination to say.
+
+ One transition is one message. A level between this and the transitions would be the place a
+ fan-in policy lived, and fan-in was deprioritized on 2026-09-28, so there is nothing for it
+ to hold. It arrives with fan-in rather than waiting here empty.
+ """
+
+ alert_name: str
+ # Evaluation-level, so it sits here rather than on a transition: a failed check fails the
+ # whole evaluation, and every group in one announcement saw the same count.
+ consecutive_failures: int
+ transitions: tuple[AnnouncedTransition, ...]
+
+
@frozen
class AlertDeliveryPreview:
"""What delivery would send. The PoC records it instead of contacting a destination.
diff --git a/products/alerts/backend/test/test_delivery_dispatch.py b/products/alerts/backend/test/test_delivery_dispatch.py
new file mode 100644
index 000000000000..5884c8fcb0bb
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_dispatch.py
@@ -0,0 +1,199 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from products.alerts.backend.delivery.dispatch import deliver
+from products.alerts.backend.delivery.message import AlertMessage
+from products.alerts.backend.delivery.telemetry import record_delivery
+from products.alerts.backend.delivery.thread_store import NullThreadStore, ThreadKey
+from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertEventKind,
+ AnnouncedTransition,
+ EvaluationAnnouncement,
+)
+
+TARGET = cast(AlertDestinationData, {"type": "slack", "slack_workspace_id": 1, "slack_channel_id": "C-ENG"})
+FIRST_FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
+SECOND_FIRING = datetime(2026, 9, 30, 17, tzinfo=UTC)
+
+
+def _transition(
+ kind: AlertEventKind = AlertEventKind.FIRING,
+ episode_started_at: datetime | None = FIRST_FIRING,
+ grouping_key: str = "",
+) -> AnnouncedTransition:
+ return AnnouncedTransition(
+ grouping_key=grouping_key,
+ kind=kind,
+ episode_started_at=episode_started_at,
+ value=300.0,
+ labels={},
+ condition={"threshold_count": 100, "threshold_operator": "above"},
+ source_config={},
+ error_message=None,
+ )
+
+
+def _announcement(
+ kind: AlertEventKind = AlertEventKind.FIRING, episode_started_at: datetime | None = FIRST_FIRING
+) -> EvaluationAnnouncement:
+ return EvaluationAnnouncement(
+ alert_name="API errors",
+ consecutive_failures=0,
+ transitions=(_transition(kind, episode_started_at),),
+ )
+
+
+class FakeTransport:
+ provider = "fake"
+
+ def __init__(self, handle: MessageHandle | None = None, error: Exception | None = None) -> None:
+ self.handle = handle or MessageHandle(external_ref={"ts": "1"})
+ self.error = error
+ self.sends: list[tuple[AlertMessage, MessageHandle | None]] = []
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return "C-ENG"
+
+ def deliver(
+ self, *, team_id: int, target: AlertDestinationData, message: AlertMessage, in_reply_to: Any = None
+ ) -> MessageHandle | None:
+ self.sends.append((message, in_reply_to))
+ if self.error:
+ raise self.error
+ return self.handle
+
+
+class RecordingThreadStore(NullThreadStore):
+ """Keeps what a real store would keep, so the key dispatch builds is observable."""
+
+ def __init__(self) -> None:
+ self.threads: dict[ThreadKey, MessageHandle] = {}
+
+ def handle_for(self, key: ThreadKey) -> MessageHandle | None:
+ return self.threads.get(key)
+
+ def remember(self, key: ThreadKey, handle: MessageHandle) -> None:
+ self.threads[key] = handle
+
+ @property
+ def remembered(self) -> list[MessageHandle]:
+ return list(self.threads.values())
+
+
+class TestDeliveryDispatch(SimpleTestCase):
+ def _deliver(self, transport: FakeTransport, store: Any, announcement: Any = None) -> Any:
+ with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ deliver(
+ transport=transport,
+ thread_store=store,
+ team_id=2,
+ configuration_id="cfg-1",
+ target=TARGET,
+ announcement=announcement or _announcement(),
+ )
+ return recorded
+
+ def test_a_first_message_is_remembered_so_a_resolve_can_reply_to_it(self) -> None:
+ store = RecordingThreadStore()
+ transport = FakeTransport()
+
+ self._deliver(transport, store)
+
+ assert [handle.external_ref for handle in store.remembered] == [{"ts": "1"}]
+
+ def test_a_refused_send_is_counted_rather_than_passed_over(self) -> None:
+ transport = FakeTransport(error=DeliveryError("nope"))
+
+ with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ with pytest.raises(DeliveryError):
+ deliver(
+ transport=transport,
+ thread_store=NullThreadStore(),
+ team_id=2,
+ configuration_id="cfg-1",
+ target=TARGET,
+ announcement=_announcement(),
+ )
+
+ assert recorded.call_args.kwargs["succeeded"] is False
+
+ def test_a_resolve_replies_under_its_own_firing_rather_than_an_earlier_one(self) -> None:
+ store = RecordingThreadStore()
+ first = FakeTransport(handle=MessageHandle(external_ref={"ts": "morning"}))
+ self._deliver(first, store, _announcement(AlertEventKind.FIRING, FIRST_FIRING))
+
+ resolve = FakeTransport(handle=MessageHandle(external_ref={"ts": "resolve"}))
+ self._deliver(resolve, store, _announcement(AlertEventKind.RESOLVED, FIRST_FIRING))
+
+ second = FakeTransport(handle=MessageHandle(external_ref={"ts": "evening"}))
+ self._deliver(second, store, _announcement(AlertEventKind.FIRING, SECOND_FIRING))
+
+ assert [handle for _, handle in resolve.sends] == [MessageHandle(external_ref={"ts": "morning"})]
+ assert [handle for _, handle in second.sends] == [None]
+
+ def test_two_groups_firing_together_do_not_share_a_thread(self) -> None:
+ store = RecordingThreadStore()
+ transport = FakeTransport()
+ announcement = EvaluationAnnouncement(
+ alert_name="API errors",
+ consecutive_failures=0,
+ transitions=(_transition(grouping_key="checkout"), _transition(grouping_key="search")),
+ )
+
+ self._deliver(transport, store, announcement)
+
+ assert [handle for _, handle in transport.sends] == [None, None]
+ assert len(store.threads) == 2
+
+ def test_a_check_that_never_fired_starts_no_conversation(self) -> None:
+ store = RecordingThreadStore()
+ transport = FakeTransport()
+
+ self._deliver(transport, store, _announcement(AlertEventKind.ERRORED, None))
+
+ assert store.threads == {}
+
+ def test_a_provider_outage_is_counted_as_a_failed_delivery(self) -> None:
+ transport = FakeTransport(error=ConnectionError("slack unreachable"))
+
+ with patch("products.alerts.backend.delivery.dispatch.record_delivery") as recorded:
+ with pytest.raises(ConnectionError):
+ deliver(
+ transport=transport,
+ thread_store=NullThreadStore(),
+ team_id=2,
+ configuration_id="cfg-1",
+ target=TARGET,
+ announcement=_announcement(),
+ )
+
+ assert recorded.call_args.kwargs["succeeded"] is False
+
+ def test_a_store_that_remembers_nothing_still_delivers(self) -> None:
+ transport = FakeTransport()
+
+ self._deliver(transport, NullThreadStore())
+
+ assert [handle for _, handle in transport.sends] == [None]
+
+
+class TestDeliveryTelemetry(SimpleTestCase):
+ def test_an_outcome_is_keyed_to_alerts_rather_than_to_hog_functions(self) -> None:
+ with patch("products.alerts.backend.delivery.telemetry.get_producer") as producer:
+ record_delivery(team_id=2, configuration_id="cfg-1", provider="slack", succeeded=True)
+
+ payload = producer.return_value.produce.call_args.kwargs["data"]
+ assert payload["app_source"] == "alert"
+ assert payload["app_source_id"] == "cfg-1"
+ assert (payload["metric_kind"], payload["metric_name"]) == ("success", "succeeded")
+
+ def test_a_broken_producer_does_not_fail_a_send_that_already_happened(self) -> None:
+ with patch("products.alerts.backend.delivery.telemetry.get_producer", side_effect=RuntimeError("down")):
+ record_delivery(team_id=2, configuration_id="cfg-1", provider="slack", succeeded=True)
diff --git a/products/alerts/backend/test/test_delivery_message.py b/products/alerts/backend/test/test_delivery_message.py
new file mode 100644
index 000000000000..4caeb43c373a
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_message.py
@@ -0,0 +1,70 @@
+from typing import Any
+
+import pytest
+
+from products.alerts.backend.delivery.message import MessageDetail, build_message
+from products.alerts.backend.facade.contracts import AlertEventKind, AnnouncedTransition, EvaluationAnnouncement
+
+CONDITION = {"threshold_count": 100, "threshold_operator": "above", "window_minutes": 5}
+
+
+def _transition(kind: AlertEventKind, **overrides: Any) -> AnnouncedTransition:
+ fields: dict[str, Any] = {
+ "grouping_key": "",
+ "kind": kind,
+ "episode_started_at": None,
+ "value": 300.0,
+ "labels": {},
+ "condition": CONDITION,
+ "source_config": {},
+ "error_message": None,
+ }
+ fields.update(overrides)
+ return AnnouncedTransition(**fields)
+
+
+def _announcement(consecutive_failures: int = 0) -> EvaluationAnnouncement:
+ return EvaluationAnnouncement(alert_name="API errors", consecutive_failures=consecutive_failures, transitions=())
+
+
+class TestAlertMessage:
+ def test_a_breach_states_what_it_measured_against_what_it_allowed(self) -> None:
+ message = build_message(_announcement(), _transition(AlertEventKind.FIRING))
+
+ assert message.headline == "API errors is firing"
+ assert message.details == (
+ MessageDetail(label="Value", value="300"),
+ MessageDetail(label="Threshold", value="above 100"),
+ MessageDetail(label="Window", value="5 minutes"),
+ )
+
+ def test_a_failed_check_states_the_reason_rather_than_a_threshold(self) -> None:
+ message = build_message(
+ _announcement(consecutive_failures=3),
+ _transition(AlertEventKind.ERRORED, value=None, error_message="Query is too expensive"),
+ )
+
+ assert message.headline == "API errors could not be checked"
+ assert message.details == (
+ MessageDetail(label="Error", value="Query is too expensive"),
+ MessageDetail(label="Failed checks", value="3"),
+ )
+
+ @pytest.mark.parametrize(
+ "window_minutes,expected",
+ [(1, "1 minute"), (5, "5 minutes")],
+ )
+ def test_the_window_reads_as_a_duration(self, window_minutes: int, expected: str) -> None:
+ condition = {**CONDITION, "window_minutes": window_minutes}
+ message = build_message(_announcement(), _transition(AlertEventKind.FIRING, condition=condition))
+
+ assert MessageDetail(label="Window", value=expected) in message.details
+
+ def test_a_check_that_announces_nothing_has_no_message(self) -> None:
+ with pytest.raises(ValueError):
+ build_message(_announcement(), _transition(AlertEventKind.CHECK))
+
+ def test_a_partial_condition_drops_the_line_it_cannot_state(self) -> None:
+ message = build_message(_announcement(), _transition(AlertEventKind.FIRING, condition={}))
+
+ assert message.details == (MessageDetail(label="Value", value="300"),)
diff --git a/products/alerts/backend/test/test_delivery_slack.py b/products/alerts/backend/test/test_delivery_slack.py
new file mode 100644
index 000000000000..52e8b076406c
--- /dev/null
+++ b/products/alerts/backend/test/test_delivery_slack.py
@@ -0,0 +1,118 @@
+from typing import Any, cast
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import Integration
+from posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARS
+
+from products.alerts.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts.backend.delivery.slack import SlackTransport, blocks_for
+from products.alerts.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts.backend.facade.contracts import AlertDestinationData
+
+MESSAGE = AlertMessage(
+ headline="API errors is firing",
+ details=(MessageDetail(label="Value", value="300"), MessageDetail(label="Threshold", value="above 100")),
+)
+
+
+class TestSlackBlocks(SimpleTestCase):
+ def test_the_headline_is_clipped_to_what_slack_accepts(self) -> None:
+ message = AlertMessage(headline="x" * 400, details=())
+
+ header = blocks_for(message)[0]
+ assert len(header["text"]["text"]) <= MAX_HEADER_CHARS
+
+ def test_every_detail_reaches_the_body(self) -> None:
+ section = blocks_for(MESSAGE)[1]
+
+ assert section["text"]["text"] == "*Value:* 300\n*Threshold:* above 100"
+
+ def test_a_long_detail_keeps_the_body_inside_what_slack_accepts(self) -> None:
+ message = AlertMessage(
+ headline="API errors could not be checked",
+ details=(
+ MessageDetail(label="Error", value="x" * 5000),
+ MessageDetail(label="Failed checks", value="3"),
+ ),
+ )
+
+ section = blocks_for(message)[1]
+
+ # Over the limit Slack rejects the send outright, so the alert reaches nobody. Clipping
+ # the joined body instead would take the failure count out with the error.
+ assert len(section["text"]["text"]) <= MAX_SECTION_CHARS
+ assert "*Failed checks:* 3" in section["text"]["text"]
+
+ def test_a_query_error_cannot_speak_as_slack_markup(self) -> None:
+ message = AlertMessage(
+ headline="API errors could not be checked",
+ details=(MessageDetail(label="Error", value="no column <!channel> in <http://x|table>"),),
+ )
+
+ body = blocks_for(message)[1]["text"]["text"]
+
+ assert "<!channel>" not in body
+ assert "&lt;!channel&gt;" in body
+
+ def test_a_message_without_details_carries_no_empty_section(self) -> None:
+ blocks = blocks_for(AlertMessage(headline="API errors is resolved", details=()))
+
+ assert [block["type"] for block in blocks] == ["header"]
+
+
+class TestSlackTransport(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T-1", config={})
+ self.target = cast(
+ AlertDestinationData,
+ {"type": "slack", "slack_workspace_id": self.integration.id, "slack_channel_id": "C-ENG"},
+ )
+
+ def _send(self, **overrides: Any) -> Any:
+ with patch("products.alerts.backend.delivery.slack.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client.chat_postMessage.return_value = {"ts": "1700000000.1"}
+ handle = SlackTransport().deliver(
+ team_id=overrides.pop("team_id", self.team.id),
+ target=overrides.pop("target", self.target),
+ message=MESSAGE,
+ **overrides,
+ )
+ return handle, slack_integration.return_value.client.chat_postMessage
+
+ def test_a_send_returns_the_handle_a_reply_needs(self) -> None:
+ handle, post = self._send()
+
+ assert handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1700000000.1"})
+ assert post.call_args.kwargs["thread_ts"] is None
+
+ def test_a_reply_goes_into_the_thread_it_names(self) -> None:
+ _, post = self._send(in_reply_to=MessageHandle(external_ref={"channel": "C-ENG", "ts": "1699999999.9"}))
+
+ assert post.call_args.kwargs["thread_ts"] == "1699999999.9"
+
+ def test_a_workspace_another_team_owns_is_refused(self) -> None:
+ # An unscoped lookup finds the integration by id alone and sends into it.
+ with pytest.raises(DeliveryError):
+ self._send(team_id=self.team.id + 1)
+
+ def test_a_refusal_from_slack_becomes_a_delivery_error(self) -> None:
+ with patch("products.alerts.backend.delivery.slack.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client.chat_postMessage.side_effect = SlackApiError(
+ "channel_not_found", {"error": "channel_not_found"}
+ )
+ with pytest.raises(DeliveryError):
+ SlackTransport().deliver(team_id=self.team.id, target=self.target, message=MESSAGE)
+
+ def test_a_destination_missing_its_channel_is_refused(self) -> None:
+ target = cast(AlertDestinationData, {"type": "slack", "slack_workspace_id": self.integration.id})
+
+ with pytest.raises(DeliveryError):
+ self._send(target=target)