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): deliver incident edges to PagerDuty natively (#113006)

Jimmy Zhu7a6a0595b79e
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.md
index f59325a4a198..19e7bcb008cc 100644
--- a/docs/internal/alerts-platform-temporal.md
+++ b/docs/internal/alerts-platform-temporal.md
@@ -363,6 +363,12 @@ The legacy logs stack's `incident_edge` wraps the same rule.
incident actions has `sends_messages=False`, and none of its rows reach a message destination.
- `announcement()` also returns the held CHECK row of a group in `incident_grouping_keys`.
- A mute never holds an incident edge: a fire inside quiet hours or a snooze triggers the incident.
+- Delivery routes each action to the event id in `event_ids_by_incident_action`, which only an incident
+ manager destination subscribes to. A message destination never sees an incident action.
+- The PagerDuty transport sends a trigger or a resolve with the `dedup_key`
+ `<configuration_id>:<grouping_key>:<episode_started_at>`, so a resolve closes the incident of its own
+ firing episode. It names the platform in `source`, because a team on the pilot also gets the HogFunction
+ path's incident.
A fire a mute swallowed is still owed an announcement.
`_firing_is_unannounced` in `facade/lifecycle.py` decides that, and its docstring holds the rule.
diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.py
index 482a000f6c9a..fafdd9590d51 100644
--- a/products/alerts/backend/logic/destination_configs.py
+++ b/products/alerts/backend/logic/destination_configs.py
@@ -9,6 +9,8 @@ from typing import Any, ClassVar
from urllib.parse import urlsplit
from products.alerts_platform.backend.facade.contracts import (
+ DEFAULT_PAGERDUTY_REGION,
+ DEFAULT_PAGERDUTY_SEVERITY,
AlertDestinationAction,
AlertDestinationConfig,
AlertDestinationData,
@@ -327,13 +329,13 @@ class PagerDutyDestination(DestinationSpec):
raise ValueError(f"PagerDuty has nothing to send for the {event_kind_spec.display_kind} event kind.")
return {
"routing_key": {"value": data["pagerduty_routing_key"]},
- "region": {"value": data.get("pagerduty_region") or PagerDutyRegion.US.value},
+ "region": {"value": data.get("pagerduty_region") or DEFAULT_PAGERDUTY_REGION.value},
"event_action": {"value": event_kind_spec.incident_action.value},
# Both incident kinds carry `alert_id`, so a trigger and its resolve share one key.
"dedup_key": {"value": "posthog-alert-{event.properties.alert_id}"},
"summary": {"value": pagerduty_summary(event_kind_spec)},
"source": {"value": "{project.name}"},
- "severity": {"value": data.get("pagerduty_severity") or PagerDutySeverity.CRITICAL.value},
+ "severity": {"value": data.get("pagerduty_severity") or DEFAULT_PAGERDUTY_SEVERITY.value},
"custom_details": {"value": pagerduty_custom_details(event_kind_spec)},
"links": {"value": pagerduty_links(event_kind_spec)},
}
diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.py
index 751cbd78fc04..2a6ea610c1b7 100644
--- a/products/alerts_platform/backend/delivery/dispatch.py
+++ b/products/alerts_platform/backend/delivery/dispatch.py
@@ -13,6 +13,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AnnouncedTransition,
EvaluationAnnouncement,
+ IncidentAction,
)
@@ -25,6 +26,7 @@ def deliver(
evaluation_key: str,
target: AlertDestinationData,
announcement: EvaluationAnnouncement,
+ incident_action: IncidentAction | None = None,
) -> None:
channel_target = transport.channel_target(target)
busy = 0
@@ -42,7 +44,7 @@ def deliver(
team_id=team_id,
configuration_id=configuration_id,
target=target,
- message=build_message(announcement, transition),
+ message=build_message(announcement, transition, incident_action=incident_action),
in_reply_to=None,
)
continue
@@ -64,7 +66,7 @@ def deliver(
team_id=team_id,
configuration_id=configuration_id,
target=target,
- message=build_message(announcement, transition),
+ message=build_message(announcement, transition, incident_action=incident_action),
in_reply_to=claim.handle,
)
except Exception:
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index b5a05d05a64c..13b6526bc7c2 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -16,6 +16,7 @@ from posthog.models import Team
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
+from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport
from products.alerts_platform.backend.delivery.slack import SlackTransport
from products.alerts_platform.backend.delivery.teams import TeamsTransport
from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusy
@@ -27,6 +28,7 @@ from products.alerts_platform.backend.facade.contracts import (
AnnouncedTransition,
DestinationType,
EvaluationAnnouncement,
+ IncidentAction,
)
from products.alerts_platform.backend.logic.platform_alert_events import announcement
@@ -47,6 +49,7 @@ _TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {
DestinationType.WEBHOOK: WebhookTransport,
DestinationType.TEAMS: TeamsTransport,
DestinationType.DISCORD: DiscordTransport,
+ DestinationType.PAGERDUTY: PagerDutyTransport,
}
@@ -112,6 +115,9 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
# 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.
+ action_by_event_id = {
+ event_id: IncidentAction(action) for action, event_id in request.event_ids_by_incident_action.items()
+ }
for event_id, transitions in _by_subscription(request, announced).items():
for target in _destinations(request, event_id):
transport_class = _TRANSPORTS.get(target["type"])
@@ -127,6 +133,7 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
evaluation_key=request.evaluation_key,
target=target,
announcement=replace(announced, transitions=transitions),
+ incident_action=action_by_event_id.get(event_id),
)
except ThreadBusy as error:
busy.append(str(error))
@@ -155,20 +162,22 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
def _by_subscription(
request: AlertDeliveryRequest, announced: EvaluationAnnouncement
) -> dict[str, tuple[AnnouncedTransition, ...]]:
- """The transitions this evaluation announced, grouped by the event a destination subscribes to.
+ """The transitions this evaluation announced or moved an incident with, 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. Nor does anything on a delivery the source did not announce, which exists only for
- its incident actions.
+ for it. Nor does a message on a delivery the source did not announce, which exists only for
+ its incident actions. An incident event is set apart from every message event, so a chat
+ destination never hears about an incident and an incident manager never gets a message.
"""
- if not request.sends_messages:
- return {}
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)
+ 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):
+ if event_id is not None:
+ grouped.setdefault(event_id, []).append(transition)
return {event_id: tuple(transitions) for event_id, transitions in grouped.items()}
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index 965a14c284e9..92ce1c420ee0 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -14,6 +14,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
AnnouncedTransition,
EvaluationAnnouncement,
+ IncidentAction,
)
_HEADLINES: Final[dict[AlertEventKind, str]] = {
@@ -23,6 +24,12 @@ _HEADLINES: Final[dict[AlertEventKind, str]] = {
AlertEventKind.BROKEN: "{name} is turned off",
}
+# What a held row says, when cooldown or mute kept its announcement and only its incident moved.
+_INCIDENT_KINDS: Final[dict[IncidentAction, AlertEventKind]] = {
+ IncidentAction.TRIGGER: AlertEventKind.FIRING,
+ IncidentAction.RESOLVE: AlertEventKind.RESOLVED,
+}
+
@frozen
class MessageDetail:
@@ -39,6 +46,7 @@ class AlertMessage:
`headline` and `details` are the copy, and a provider that renders text uses only those. The
other fields are the facts the copy was written from, for a provider whose body is data.
+ `incident_action` is set only on a message for an incident manager destination.
"""
headline: str
@@ -46,6 +54,7 @@ class AlertMessage:
configuration_id: str
alert_name: str
transition: AnnouncedTransition
+ incident_action: IncidentAction | None = None
def _number(value: float) -> str:
@@ -83,17 +92,25 @@ def _failure_details(transition: AnnouncedTransition, consecutive_failures: int)
return details
-def build_message(announcement: EvaluationAnnouncement, transition: AnnouncedTransition) -> AlertMessage:
+def build_message(
+ announcement: EvaluationAnnouncement,
+ transition: AnnouncedTransition,
+ *,
+ incident_action: IncidentAction | None = None,
+) -> 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)
+ kind = transition.kind
+ if kind == AlertEventKind.CHECK and incident_action is not None:
+ kind = _INCIDENT_KINDS[incident_action]
+ headline = _HEADLINES.get(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.
+ # `announcement` returns a check row only for a group whose incident moved, so a check
+ # here without an incident action means that filter is gone.
raise ValueError(f"{transition.kind} announces nothing and has no message")
failure_kinds = (AlertEventKind.ERRORED, AlertEventKind.BROKEN)
@@ -108,4 +125,5 @@ def build_message(announcement: EvaluationAnnouncement, transition: AnnouncedTra
configuration_id=announcement.configuration_id,
alert_name=announcement.alert_name,
transition=transition,
+ incident_action=incident_action,
)
diff --git a/products/alerts_platform/backend/delivery/pagerduty.py b/products/alerts_platform/backend/delivery/pagerduty.py
new file mode 100644
index 000000000000..52af31b18e9b
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/pagerduty.py
@@ -0,0 +1,114 @@
+"""PagerDuty delivery, as Events API v2 trigger and resolve events.
+
+PagerDuty holds an incident open until it receives a resolve with the trigger's `dedup_key`, so
+this transport sends only incident actions, never messages. The dedup key names one firing
+episode of one group, which is how a resolve finds the incident its trigger opened.
+
+The routing key is the credential, and it travels in the body. It never reaches an error message,
+a log line or a metric label, and the thread store keys on a digest of it.
+
+These sends do not go through `posthog/egress`. The routing key belongs to the customer's own
+PagerDuty account, and PagerDuty limits events per integration key, so no PostHog-wide budget
+models it. A 429 fails the send, and the activity's retry backs off.
+
+The thread store claims each send, so a retry of a send that already landed does not post again.
+It does not order sends across evaluations: a trigger whose delivery failed and is retried after
+its resolve landed reopens the incident under the same dedup key.
+"""
+
+import hashlib
+from typing import Any, Final
+
+from products.alerts_platform.backend.delivery.message import AlertMessage
+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.delivery.wire import credential_digest, post_json, rfc3339
+from products.alerts_platform.backend.facade.contracts import (
+ DEFAULT_PAGERDUTY_REGION,
+ DEFAULT_PAGERDUTY_SEVERITY,
+ AlertDestinationData,
+ IncidentAction,
+ PagerDutyRegion,
+ PagerDutySeverity,
+)
+
+PROVIDER: Final = "pagerduty"
+
+ENDPOINTS: Final[dict[PagerDutyRegion, str]] = {
+ PagerDutyRegion.US: "https://events.pagerduty.com/v2/enqueue",
+ PagerDutyRegion.EU: "https://events.eu.pagerduty.com/v2/enqueue",
+}
+
+# Names the framework that sent an event, because a team on the pilot also receives the
+# HogFunction path's incident for the same firing.
+SOURCE: Final = "PostHog alerts platform"
+
+_MAX_SUMMARY_LENGTH: Final = 1024
+_MAX_DEDUP_KEY_LENGTH: Final = 255
+
+
+def dedup_key(message: AlertMessage) -> str:
+ """One firing episode of one group, so its trigger and its resolve address the same incident.
+
+ A firing that began before the platform recorded starts has no known start. Its resolve then
+ addresses an incident the platform never opened, which PagerDuty ignores.
+ """
+ transition = message.transition
+ episode = rfc3339(transition.episode_started_at) if transition.episode_started_at else "unknown"
+ key = f"{message.configuration_id}:{transition.grouping_key}:{episode}"
+ if len(key) <= _MAX_DEDUP_KEY_LENGTH:
+ return key
+ return f"{message.configuration_id}:{hashlib.sha256(key.encode()).hexdigest()}"
+
+
+def pagerduty_body(message: AlertMessage, *, routing_key: str, severity: PagerDutySeverity) -> dict[str, Any]:
+ if message.incident_action is None:
+ raise DeliveryError("A PagerDuty destination receives only incident events.")
+ body: dict[str, Any] = {
+ "routing_key": routing_key,
+ "event_action": message.incident_action.value,
+ "dedup_key": dedup_key(message),
+ }
+ if message.incident_action == IncidentAction.RESOLVE:
+ return body
+ transition = message.transition
+ body["client"] = "PostHog"
+ body["payload"] = {
+ "summary": message.headline[:_MAX_SUMMARY_LENGTH],
+ "source": SOURCE,
+ "severity": severity.value,
+ "timestamp": rfc3339(transition.occurred_at),
+ "custom_details": {
+ **{detail.label: detail.value for detail in message.details},
+ "delivered_by": SOURCE,
+ "configuration_id": message.configuration_id,
+ },
+ }
+ return body
+
+
+class PagerDutyTransport:
+ provider = PROVIDER
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return credential_digest(target.get("pagerduty_routing_key", ""))
+
+ def deliver(
+ self,
+ *,
+ team_id: int,
+ target: AlertDestinationData,
+ message: AlertMessage,
+ in_reply_to: MessageHandle | None = None,
+ ) -> MessageHandle | None:
+ routing_key = target.get("pagerduty_routing_key")
+ if not routing_key:
+ raise DeliveryError("This PagerDuty destination has no integration key.")
+ try:
+ region = PagerDutyRegion(target.get("pagerduty_region") or DEFAULT_PAGERDUTY_REGION)
+ severity = PagerDutySeverity(target.get("pagerduty_severity") or DEFAULT_PAGERDUTY_SEVERITY)
+ except ValueError:
+ raise DeliveryError("This PagerDuty destination has an unknown region or severity.") from None
+ body = pagerduty_body(message, routing_key=routing_key, severity=severity)
+ post_json(ENDPOINTS[region], body, display_name="PagerDuty")
+ # PagerDuty answers with the dedup key, which this transport derives again for the resolve.
+ return None
diff --git a/products/alerts_platform/backend/delivery/webhook.py b/products/alerts_platform/backend/delivery/webhook.py
index d2be69bd1840..97b2c81a0172 100644
--- a/products/alerts_platform/backend/delivery/webhook.py
+++ b/products/alerts_platform/backend/delivery/webhook.py
@@ -6,7 +6,6 @@ transition is one message.
"""
import hashlib
-from datetime import UTC, datetime
from typing import Any, ClassVar, Final
from urllib.parse import urlsplit
@@ -15,6 +14,7 @@ from django.conf import settings
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.transport import DeliveryError
from products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport
+from products.alerts_platform.backend.delivery.wire import rfc3339
from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition
PROVIDER: Final = "webhook"
@@ -29,13 +29,6 @@ _NOT_ENDED: Final = "0001-01-01T00:00:00Z"
_BREACH_KINDS: Final = (AlertEventKind.FIRING, AlertEventKind.RESOLVED)
-def _rfc3339(moment: datetime) -> str:
- # The ClickHouse HTTP client returns naive datetimes. The history columns hold UTC, and
- # Alertmanager receivers reject a timestamp with no offset.
- aware = moment.replace(tzinfo=UTC) if moment.tzinfo is None else moment.astimezone(UTC)
- return aware.isoformat()
-
-
def _fingerprint(configuration_id: str, transition: AnnouncedTransition) -> str:
# A failed or a turned-off check is a separate alert to a receiver. With the breach's
# fingerprint, the breach's resolve would close it, and a later breach would read as an
@@ -80,8 +73,8 @@ def alertmanager_body(message: AlertMessage) -> dict[str, Any]:
"status": status,
"labels": labels,
"annotations": annotations,
- "startsAt": _rfc3339(transition.episode_started_at or transition.occurred_at),
- "endsAt": _rfc3339(transition.occurred_at) if status == "resolved" else _NOT_ENDED,
+ "startsAt": rfc3339(transition.episode_started_at or transition.occurred_at),
+ "endsAt": rfc3339(transition.occurred_at) if status == "resolved" else _NOT_ENDED,
"generatorURL": "",
"fingerprint": _fingerprint(configuration_id, transition),
}
diff --git a/products/alerts_platform/backend/delivery/webhook_url.py b/products/alerts_platform/backend/delivery/webhook_url.py
index f386ed0cab75..ac35ffd036f9 100644
--- a/products/alerts_platform/backend/delivery/webhook_url.py
+++ b/products/alerts_platform/backend/delivery/webhook_url.py
@@ -9,25 +9,14 @@ None of these providers returns a handle to reply to, so a send returns None and
posts as a new message.
"""
-import json
-import hashlib
from abc import ABC, abstractmethod
-from typing import Any, ClassVar, Final
-
-import requests
-
-from posthog.security.pinned_requests import SSRFBlockedError, pinned_session
+from typing import Any, ClassVar
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
+from products.alerts_platform.backend.delivery.wire import credential_digest, post_json
from products.alerts_platform.backend.facade.contracts import AlertDestinationData
-# Both fit inside the deliver activity's 10-second start_to_close, so a stalled destination fails
-# this attempt instead of outliving it. A send still in flight when Temporal starts the next
-# attempt posts a second copy, because no webhook provider takes an idempotency key.
-CONNECT_TIMEOUT_SECONDS: Final = 3.0
-READ_TIMEOUT_SECONDS: Final = 5.0
-
class WebhookUrlTransport(ABC):
provider: str
@@ -35,10 +24,9 @@ class WebhookUrlTransport(ABC):
headers: ClassVar[dict[str, str]] = {}
def channel_target(self, target: AlertDestinationData) -> str:
- # A digest rather than the URL: the thread row would otherwise store the credential, and
- # some Teams URLs are longer than the column. A changed URL gives a new digest, so a
- # repointed destination starts a new thread.
- return hashlib.sha256(target.get("webhook_url", "").encode()).hexdigest()
+ # Some Teams URLs are longer than the column, which a digest also avoids. A changed URL
+ # gives a new digest, so a repointed destination starts a new thread.
+ return credential_digest(target.get("webhook_url", ""))
def deliver(
self,
@@ -52,7 +40,7 @@ class WebhookUrlTransport(ABC):
if not url:
raise DeliveryError(f"This {self.display_name} destination has no webhook URL.")
self.check_url(url)
- self._post(self.send_url(url), self.body_for(message))
+ post_json(self.send_url(url), self.body_for(message), display_name=self.display_name, headers=self.headers)
return None
def check_url(self, url: str) -> None:
@@ -65,48 +53,3 @@ class WebhookUrlTransport(ABC):
@abstractmethod
def body_for(self, message: AlertMessage) -> dict[str, Any]: ...
-
- def _post(self, url: str, body: dict[str, Any]) -> None:
- try:
- # `pinned_session` validates the URL and connects to the IPs it validated, which
- # closes the window where DNS changes between the check and the connection.
- with pinned_session(url) as session:
- request = session.prepare_request(
- requests.Request(
- "POST",
- url,
- # UTF-8 rather than `json=`, which escapes every non-ASCII character to six
- # bytes or more. A provider limits the bytes it receives, so a body sized by
- # its UTF-8 length must be sent as UTF-8.
- data=json.dumps(body, ensure_ascii=False).encode(),
- headers={"Content-Type": "application/json", **self.headers},
- )
- )
- settings = session.merge_environment_settings(request.url, {}, True, None, None)
- # The adapter rather than `session.send`, and `stream=True` with no read. Even with
- # redirects off, the session reads a redirect's whole body to work out where it
- # points, so a destination answering 3xx with an unbounded body would fill the
- # worker's memory. The adapter returns the response unread and follows nothing.
- response = session.get_adapter(request.url or url).send(
- request,
- stream=True,
- timeout=(CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS),
- # Typed as optional, but it falls back to the session's own setting, which is True.
- verify=True if settings["verify"] is None else settings["verify"],
- cert=settings["cert"],
- proxies=settings["proxies"],
- )
- status = response.status_code
- response.close()
- except SSRFBlockedError:
- raise DeliveryError(
- f"The {self.display_name} destination URL points to an address PostHog does not send to."
- ) from None
- except requests.RequestException as error:
- # Only the class name, and `from None` to keep the original out of the failure chain:
- # the text of a `requests` error carries the whole URL.
- raise DeliveryError(
- f"The {self.display_name} destination could not be reached: {type(error).__name__}"
- ) from None
- if not 200 <= status < 300:
- raise DeliveryError(f"The {self.display_name} destination refused the message with status {status}.")
diff --git a/products/alerts_platform/backend/delivery/wire.py b/products/alerts_platform/backend/delivery/wire.py
new file mode 100644
index 000000000000..26784b48c5bf
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/wire.py
@@ -0,0 +1,78 @@
+"""What every HTTP transport sends the same way: the JSON post, the credential digest, timestamps.
+
+Each transport's credential, a webhook URL or a PagerDuty routing key, never reaches an error
+message, a log line or a metric label, so the errors here name a status or an exception class only.
+"""
+
+import json
+import hashlib
+from datetime import UTC, datetime
+from typing import Any, Final
+
+import requests
+
+from posthog.security.pinned_requests import SSRFBlockedError, pinned_session
+
+from products.alerts_platform.backend.delivery.transport import DeliveryError
+
+# Both fit inside the deliver activity's 10-second start_to_close, so a stalled destination fails
+# this attempt instead of outliving it. A send still in flight when Temporal starts the next
+# attempt posts a second copy, because no webhook provider takes an idempotency key.
+CONNECT_TIMEOUT_SECONDS: Final = 3.0
+READ_TIMEOUT_SECONDS: Final = 5.0
+
+
+def credential_digest(credential: str) -> str:
+ """What the thread store keys a destination on, because the row would otherwise store the credential."""
+ return hashlib.sha256(credential.encode()).hexdigest()
+
+
+def rfc3339(moment: datetime) -> str:
+ # The ClickHouse HTTP client returns naive datetimes. The history columns hold UTC, and
+ # receivers reject a timestamp with no offset.
+ aware = moment.replace(tzinfo=UTC) if moment.tzinfo is None else moment.astimezone(UTC)
+ return aware.isoformat()
+
+
+def post_json(url: str, body: dict[str, Any], *, display_name: str, headers: dict[str, str] | None = None) -> None:
+ try:
+ # `pinned_session` validates the URL and connects to the IPs it validated, which
+ # closes the window where DNS changes between the check and the connection.
+ with pinned_session(url) as session:
+ request = session.prepare_request(
+ requests.Request(
+ "POST",
+ url,
+ # UTF-8 rather than `json=`, which escapes every non-ASCII character to six
+ # bytes or more. A provider limits the bytes it receives, so a body sized by
+ # its UTF-8 length must be sent as UTF-8.
+ data=json.dumps(body, ensure_ascii=False).encode(),
+ headers={"Content-Type": "application/json", **(headers or {})},
+ )
+ )
+ settings = session.merge_environment_settings(request.url, {}, True, None, None)
+ # The adapter rather than `session.send`, and `stream=True` with no read. Even with
+ # redirects off, the session reads a redirect's whole body to work out where it
+ # points, so a destination answering 3xx with an unbounded body would fill the
+ # worker's memory. The adapter returns the response unread and follows nothing.
+ response = session.get_adapter(request.url or url).send(
+ request,
+ stream=True,
+ timeout=(CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS),
+ # Typed as optional, but it falls back to the session's own setting, which is True.
+ verify=True if settings["verify"] is None else settings["verify"],
+ cert=settings["cert"],
+ proxies=settings["proxies"],
+ )
+ status = response.status_code
+ response.close()
+ except SSRFBlockedError:
+ raise DeliveryError(
+ f"The {display_name} destination URL points to an address PostHog does not send to."
+ ) from None
+ except requests.RequestException as error:
+ # Only the class name, and `from None` to keep the original out of the failure chain:
+ # the text of a `requests` error carries the whole URL.
+ raise DeliveryError(f"The {display_name} destination could not be reached: {type(error).__name__}") from None
+ if not 200 <= status < 300:
+ raise DeliveryError(f"The {display_name} destination refused the message with status {status}.")
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index aef58e2c0a1b..e16f02f2d22d 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -309,6 +309,8 @@ class AlertDeliveryRequest:
`event_ids_by_kind`. It is set even when cooldown or mute held the announcement back, which
is the case it exists for. `sends_messages` is False on a delivery that exists only for those
actions, so its rows reach no message destination even when their kind has an event id.
+ `event_ids_by_incident_action` maps each action onto the event id an incident manager
+ destination filters on, the way `event_ids_by_kind` does for a message.
"""
source: SourceKind
@@ -319,6 +321,7 @@ class AlertDeliveryRequest:
event_ids_by_kind: dict[str, str]
incident_actions: dict[str, IncidentAction] = field(default_factory=dict)
sends_messages: bool = True
+ event_ids_by_incident_action: dict[str, str] = field(default_factory=dict)
@frozen
@@ -462,6 +465,11 @@ class PagerDutyRegion(StrEnum):
EU = "eu"
+# What a PagerDuty destination that names neither gets, on every path that sends to one.
+DEFAULT_PAGERDUTY_SEVERITY: Final = PagerDutySeverity.CRITICAL
+DEFAULT_PAGERDUTY_REGION: Final = PagerDutyRegion.US
+
+
class IncidentAction(StrEnum):
"""What one event kind does to the incident an alert holds open in an incident manager."""
diff --git a/products/alerts_platform/backend/tests/delivery_messages.py b/products/alerts_platform/backend/tests/delivery_messages.py
index 0372d1e6bc9e..a7b23e7f3444 100644
--- a/products/alerts_platform/backend/tests/delivery_messages.py
+++ b/products/alerts_platform/backend/tests/delivery_messages.py
@@ -11,7 +11,7 @@ from requests.adapters import BaseAdapter
from requests.structures import CaseInsensitiveDict
from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
-from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition
+from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition, IncidentAction
EPISODE_STARTED = datetime(2026, 9, 30, 9, tzinfo=UTC)
OCCURRED = datetime(2026, 9, 30, 10, tzinfo=UTC)
@@ -38,6 +38,7 @@ def alert_message(
details: tuple[MessageDetail, ...] = (),
transition: AnnouncedTransition | None = None,
alert_name: str = "API errors",
+ incident_action: IncidentAction | None = None,
) -> AlertMessage:
return AlertMessage(
headline=headline,
@@ -45,6 +46,7 @@ def alert_message(
configuration_id="cfg-1",
alert_name=alert_name,
transition=transition or announced_transition(),
+ incident_action=incident_action,
)
@@ -92,6 +94,6 @@ def pinned_post(
session = Session()
session.mount("https://", adapter)
session.mount("http://", adapter)
- with patch("products.alerts_platform.backend.delivery.webhook_url.pinned_session") as pinned_session:
+ with patch("products.alerts_platform.backend.delivery.wire.pinned_session") as pinned_session:
pinned_session.return_value.__enter__.return_value = session
yield adapter
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index d4bf79d3a47b..adbff192cf6d 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -20,6 +20,7 @@ from products.alerts_platform.backend.facade.contracts import (
AnnouncedTransition,
DestinationType,
EvaluationAnnouncement,
+ IncidentAction,
SourceKind,
)
@@ -28,11 +29,14 @@ FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
FIRING_EVENT = "$logs_alert_firing"
RESOLVED_EVENT = "$logs_alert_resolved"
+OPENED_EVENT = "$logs_alert_incident_opened"
+CLOSED_EVENT = "$logs_alert_incident_closed"
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"})
TEAMS = cast(AlertDestinationData, {"type": DestinationType.TEAMS, "webhook_url": "https://example.com/teams"})
-UNSUPPORTED = cast(AlertDestinationData, {"type": "pagerduty"})
+PAGERDUTY = cast(AlertDestinationData, {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": "R-1"})
+UNSUPPORTED = cast(AlertDestinationData, {"type": "opsgenie"})
class RecordingTransport:
@@ -51,6 +55,13 @@ class RecordingTransport:
return MessageHandle(external_ref={"channel": self.channel_target(target), "ts": "1"})
+class PagingTransport(RecordingTransport):
+ provider = "pagerduty"
+
+ def channel_target(self, target: AlertDestinationData) -> str:
+ return str(target.get("pagerduty_routing_key", ""))
+
+
class RefusingTransport(RecordingTransport):
provider = "webhook"
@@ -65,7 +76,9 @@ class HeldTransport(RecordingTransport):
raise ThreadBusy("thread is being posted to by another send")
-def _request(team_id: int, *, sends_messages: bool = True) -> AlertDeliveryRequest:
+def _request(
+ team_id: int, *, sends_messages: bool = True, incident_actions: dict[str, IncidentAction] | None = None
+) -> AlertDeliveryRequest:
return AlertDeliveryRequest(
source=SourceKind.LOGS,
team_id=team_id,
@@ -74,6 +87,8 @@ def _request(team_id: int, *, sends_messages: bool = True) -> AlertDeliveryReque
destination_alert_id="legacy-1",
event_ids_by_kind={"firing": FIRING_EVENT, "resolved": RESOLVED_EVENT},
sends_messages=sends_messages,
+ incident_actions=incident_actions or {},
+ event_ids_by_incident_action={"trigger": OPENED_EVENT, "resolve": CLOSED_EVENT},
)
@@ -113,6 +128,7 @@ class TestDeliverEvaluation(APIBaseTest):
live: bool = True,
transports: dict[DestinationType, type] | None = None,
sends_messages: bool = True,
+ incident_actions: dict[str, IncidentAction] | None = None,
) -> Any:
def groups(*, team_id: int, alert_id: str, allowed_event_ids: list[str]) -> list[AlertDestinationGroup]:
return by_event.get(allowed_event_ids[0], [])
@@ -122,9 +138,18 @@ class TestDeliverEvaluation(APIBaseTest):
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, **(transports or {})}),
+ patch.dict(
+ f"{_MODULE}._TRANSPORTS",
+ {
+ DestinationType.SLACK: RecordingTransport,
+ DestinationType.PAGERDUTY: PagingTransport,
+ **(transports or {}),
+ },
+ ),
):
- return deliver_evaluation(_request(self.team.id, sends_messages=sends_messages))
+ return deliver_evaluation(
+ _request(self.team.id, sends_messages=sends_messages, incident_actions=incident_actions)
+ )
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
@@ -167,6 +192,36 @@ class TestDeliverEvaluation(APIBaseTest):
assert RecordingTransport.sends == []
assert outcome.sent == 0
+ @parameterized.expand(
+ [
+ # Cooldown held the resolve, so chat hears nothing and the incident still closes.
+ ("a_held_resolve", AlertEventKind.CHECK, False, IncidentAction.RESOLVE, []),
+ ("an_announced_fire", AlertEventKind.FIRING, True, IncidentAction.TRIGGER, ["API errors is firing"]),
+ ]
+ )
+ def test_an_incident_action_reaches_only_the_incident_subscription(
+ self,
+ _name: str,
+ kind: AlertEventKind,
+ sends_messages: bool,
+ action: IncidentAction,
+ chat_headlines: list[str],
+ ) -> None:
+ self._run(
+ _announcement(_transition(kind)),
+ {
+ FIRING_EVENT: [_group(SLACK)],
+ RESOLVED_EVENT: [_group(SLACK)],
+ OPENED_EVENT: [_group(PAGERDUTY)],
+ CLOSED_EVENT: [_group(PAGERDUTY)],
+ },
+ sends_messages=sends_messages,
+ incident_actions={"": action},
+ )
+
+ assert [m.headline for channel, m in RecordingTransport.sends if channel == "C-1"] == chat_headlines
+ assert [m.incident_action for channel, m in RecordingTransport.sends if channel == "R-1"] == [action]
+
def test_a_destination_with_no_transport_is_skipped_rather_than_failing_the_send(self) -> None:
outcome = self._run(
_announcement(_transition(AlertEventKind.FIRING)),
diff --git a/products/alerts_platform/backend/tests/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.py
index 7d04fd26fb52..7b136745a0c2 100644
--- a/products/alerts_platform/backend/tests/test_delivery_message.py
+++ b/products/alerts_platform/backend/tests/test_delivery_message.py
@@ -8,6 +8,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
AnnouncedTransition,
EvaluationAnnouncement,
+ IncidentAction,
)
CONDITION = {"threshold_count": 100, "threshold_operator": "above", "window_minutes": 5}
@@ -72,6 +73,15 @@ class TestAlertMessage:
with pytest.raises(ValueError):
build_message(_announcement(), _transition(AlertEventKind.CHECK))
+ @pytest.mark.parametrize(
+ "action,expected",
+ [(IncidentAction.TRIGGER, "API errors is firing"), (IncidentAction.RESOLVE, "API errors is resolved")],
+ )
+ def test_a_held_check_speaks_for_the_incident_it_moved(self, action: IncidentAction, expected: str) -> None:
+ message = build_message(_announcement(), _transition(AlertEventKind.CHECK), incident_action=action)
+
+ assert (message.headline, message.incident_action) == (expected, action)
+
def test_a_partial_condition_drops_the_line_it_cannot_state(self) -> None:
message = build_message(_announcement(), _transition(AlertEventKind.FIRING, condition={}))
diff --git a/products/alerts_platform/backend/tests/test_delivery_pagerduty.py b/products/alerts_platform/backend/tests/test_delivery_pagerduty.py
new file mode 100644
index 000000000000..dde429cde1a9
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_delivery_pagerduty.py
@@ -0,0 +1,142 @@
+import json
+from datetime import datetime
+from typing import Any, cast
+
+import pytest
+
+from django.test import SimpleTestCase
+
+import requests
+from parameterized import parameterized
+
+from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport, pagerduty_body
+from products.alerts_platform.backend.delivery.transport import DeliveryError
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertEventKind,
+ IncidentAction,
+ PagerDutySeverity,
+)
+from products.alerts_platform.backend.tests.delivery_messages import alert_message, announced_transition, pinned_post
+
+ROUTING_KEY = "not-a-real-routing-key-0000000000"
+TARGET = cast(AlertDestinationData, {"type": "pagerduty", "pagerduty_routing_key": ROUTING_KEY})
+
+
+def _message(action: IncidentAction | None, **transition: Any) -> AlertMessage:
+ kind = AlertEventKind.RESOLVED if action == IncidentAction.RESOLVE else AlertEventKind.FIRING
+ return alert_message(
+ details=(MessageDetail(label="Value", value="312"),),
+ transition=announced_transition(kind, **transition),
+ incident_action=action,
+ )
+
+
+class TestPagerDutyBody(SimpleTestCase):
+ def test_a_trigger_names_the_platform_and_its_firing(self) -> None:
+ body = pagerduty_body(
+ _message(IncidentAction.TRIGGER), routing_key=ROUTING_KEY, severity=PagerDutySeverity.CRITICAL
+ )
+
+ assert body == {
+ "routing_key": ROUTING_KEY,
+ "event_action": "trigger",
+ "dedup_key": "cfg-1::2026-09-30T09:00:00+00:00",
+ "client": "PostHog",
+ "payload": {
+ "summary": "API errors is firing",
+ "source": "PostHog alerts platform",
+ "severity": "critical",
+ "timestamp": "2026-09-30T10:00:00+00:00",
+ "custom_details": {
+ "Value": "312",
+ "delivered_by": "PostHog alerts platform",
+ "configuration_id": "cfg-1",
+ },
+ },
+ }
+
+ def test_a_resolve_addresses_the_incident_its_trigger_opened(self) -> None:
+ def key(action: IncidentAction, **transition: Any) -> str:
+ body = pagerduty_body(
+ _message(action, **transition), routing_key=ROUTING_KEY, severity=PagerDutySeverity.ERROR
+ )
+ return body["dedup_key"]
+
+ trigger = key(IncidentAction.TRIGGER)
+ # A naive start from ClickHouse is the same instant, and must not open a second incident.
+ assert key(IncidentAction.RESOLVE, episode_started_at=datetime(2026, 9, 30, 9)) == trigger
+ assert key(IncidentAction.TRIGGER, grouping_key="search") != trigger
+ assert key(IncidentAction.TRIGGER, episode_started_at=datetime(2026, 9, 30, 11)) != trigger
+
+ def test_an_oversized_key_stays_within_what_pagerduty_accepts(self) -> None:
+ body = pagerduty_body(
+ _message(IncidentAction.TRIGGER, grouping_key="g" * 300),
+ routing_key=ROUTING_KEY,
+ severity=PagerDutySeverity.ERROR,
+ )
+
+ assert len(body["dedup_key"]) <= 255
+
+
+class TestPagerDutyTransport(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("unset", None, "https://events.pagerduty.com/v2/enqueue"),
+ ("us", "us", "https://events.pagerduty.com/v2/enqueue"),
+ ("eu", "eu", "https://events.eu.pagerduty.com/v2/enqueue"),
+ ]
+ )
+ def test_the_region_picks_the_endpoint(self, _name: str, region: str | None, endpoint: str) -> None:
+ target = cast(AlertDestinationData, {**TARGET, **({"pagerduty_region": region} if region else {})})
+
+ with pinned_post(202) as adapter:
+ handle = PagerDutyTransport().deliver(team_id=2, target=target, message=_message(IncidentAction.TRIGGER))
+
+ sent = json.loads(adapter.sent[-1].body or b"")
+ assert handle is None
+ assert adapter.sent[-1].url == endpoint
+ assert sent["routing_key"] == ROUTING_KEY
+ # The HogFunction path's default, so one firing pages at one severity on both paths.
+ assert sent["payload"]["severity"] == "critical"
+
+ @parameterized.expand(
+ [
+ ("bad_request", 400, None),
+ ("throttled", 429, None),
+ ("unreachable", 0, requests.ConnectionError(f"body was {{'routing_key': '{ROUTING_KEY}'}}")),
+ ]
+ )
+ def test_a_failed_send_never_repeats_the_routing_key(
+ self, _name: str, status: int, error: Exception | None
+ ) -> None:
+ with pinned_post(status, error):
+ with pytest.raises(DeliveryError) as raised:
+ PagerDutyTransport().deliver(team_id=2, target=TARGET, message=_message(IncidentAction.TRIGGER))
+
+ assert ROUTING_KEY not in str(raised.value)
+ assert raised.value.__cause__ is None
+
+ @parameterized.expand(
+ [
+ ("no_incident_action", TARGET, None),
+ ("no_routing_key", cast(AlertDestinationData, {"type": "pagerduty"}), IncidentAction.TRIGGER),
+ (
+ "unknown_region",
+ cast(AlertDestinationData, {**TARGET, "pagerduty_region": "apac"}),
+ IncidentAction.TRIGGER,
+ ),
+ ]
+ )
+ def test_an_event_pagerduty_cannot_route_is_refused_before_sending(
+ self, _name: str, target: AlertDestinationData, action: IncidentAction | None
+ ) -> None:
+ with pinned_post() as adapter:
+ with pytest.raises(DeliveryError):
+ PagerDutyTransport().deliver(team_id=2, target=target, message=_message(action))
+
+ assert adapter.sent == []
+
+ def test_the_thread_store_never_holds_the_routing_key(self) -> None:
+ assert ROUTING_KEY not in PagerDutyTransport().channel_target(TARGET)
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 1c2bb6cbc33d..e9d31d40a310 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -71,12 +71,7 @@ from products.logs.backend.alert_check_query import (
resolve_alert_date_to,
rolling_check_lookback_minutes,
)
-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_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
# Private to the production activity. Reimplementing either would let this path drift from
@@ -347,6 +342,7 @@ def _request(
evaluation_key=recorded.evaluation_key,
destination_alert_id=destination_alert_id,
event_ids_by_kind=_EVENT_IDS_BY_KIND,
+ event_ids_by_incident_action=_EVENT_IDS_BY_INCIDENT_ACTION,
# Logs does not group, so its one row has the empty grouping key.
incident_actions={"": incident_action} if incident_action is not None else {},
sends_messages=sends_messages,
@@ -359,7 +355,7 @@ def _has_incident_destination(team_id: int, destination_alert_id: str) -> bool:
configured_destination_template_ids(
team_id=team_id,
alert_id=destination_alert_id,
- allowed_event_ids=(LOGS_ALERT_INCIDENT_OPENED_EVENT, LOGS_ALERT_INCIDENT_CLOSED_EVENT),
+ allowed_event_ids=tuple(_EVENT_IDS_BY_INCIDENT_ACTION.values()),
)
)
@@ -372,6 +368,11 @@ _EVENT_IDS_BY_KIND: Final[dict[str, str]] = {
if kind.value in EVENT_KIND_CONFIG
}
+# Which event id an incident manager destination filters on for each incident action.
+_EVENT_IDS_BY_INCIDENT_ACTION: Final[dict[str, str]] = {
+ spec.incident_action.value: spec.event_id for spec in EVENT_KIND_CONFIG.values() if spec.incident_action
+}
+
def _evaluate_one(
check: PlatformAlertCheckInput, buckets: list[BucketedCount], *, now: datetime, muted: bool
diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.py
index 046a9bd8a978..0ef5ea3abe6d 100644
--- a/products/logs/backend/test/test_alert_evaluate.py
+++ b/products/logs/backend/test/test_alert_evaluate.py
@@ -122,6 +122,8 @@ class TestLogsAlertEvaluation(APIBaseTest):
assert [(d.sends_messages, d.incident_actions) for d in evaluation.deliveries] == [
(True, {"": IncidentAction.TRIGGER} if paged else {})
]
+ # The event a PagerDuty destination subscribes to, so the trigger reaches it.
+ assert evaluation.deliveries[0].event_ids_by_incident_action["trigger"] == "$logs_alert_incident_opened"
with team_scope(self.team.id):
alert = platform_testing.alert_for(configuration.id)
assert alert is not None