: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): add pagerduty as a logs alert destination (#112198)
Jimmy Zhu210a728ebc09
diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.mdindex 28065167ecbd..48d50e9c6dec 100644--- a/.agents/skills/adding-product-alerting/references/architecture.md+++ b/.agents/skills/adding-product-alerting/references/architecture.md@@ -74,6 +74,7 @@ Error behavior is load-bearing:Product-facing destination setup lives in `products.alerts.backend.facade.destinations`. Read that module for the full surface. An adopter starts from:- `validate_destination_data`+- `destination_handles_event_kind`- `build_alert_destination_config`- `create_alert_destination_hog_functions`- `soft_delete_alert_destinations`@@ -89,6 +90,12 @@ another facade read.`EventKindSpec` describes destination-neutral content for one event kind. The shared builder converts it into a HogFunction payload through an internal registry where each destination type owns its template ID, required fields, input building, read-back, and read redaction. Adding a destination type means adding one entry there. Products own event IDs, event properties, wording, actions, and their allowed destination list.+Not every destination type has something to send for every event kind. An incident manager such as PagerDuty follows only the kinds that trigger or resolve an incident, which a product marks with `EventKindSpec.incident_action`. Every other destination type follows only the kinds without it. Filter a product's event kinds with `destination_handles_event_kind` before building configs; `build_alert_destination_config` raises for a kind the destination type does not handle.++An incident manager needs a resolve for every trigger, or the incident it opened stays open and absorbs the next trigger on the same deduplication key. So the incident kinds follow the firing state, not the notification: emit one on every transition into and out of firing, even when cooldown suppresses the notification. Logs alerts do this with `$logs_alert_incident_opened` and `$logs_alert_incident_closed`, read from `incident_edge` in `products/logs/backend/alert_state_machine.py`.++A destination type whose configuration is a credential, such as the PagerDuty integration key, stores it as a secret template input. The read path merges `encrypted_inputs` back before it reads a config, so grouping and duplicate detection see the real value while `redact_destination_data` keeps it out of API responses.+Validation failures raise `AlertDestinationValidationError`, a plain exception with a message and an optional field name. The adopter's view translates it into its own framework's validation error, because the facade has no HTTP layer of its own. `as_drf_validation_error` in `posthog.exceptions` does that translation for a DRF view.Deletion is fail-closed. Always scope it with `team_id`, `alert_id`, and the product's allowed event IDs.diff --git a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.mdindex 55dfeeff3d05..f1f4c4b124cb 100644--- a/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md+++ b/.agents/skills/adding-product-alerting/references/extending-platform-alerting.md@@ -42,9 +42,9 @@ If the change crosses rows, update each row deliberately. Do not hide a cross-laA new destination type normally requires all of these:-1. Add the enum value in `products/alerts/backend/facade/contracts.py`, and the HogFunction template ID and required fields in `products/alerts/backend/logic/destination_configs.py`.+1. Add the enum value in `products/alerts_platform/backend/facade/contracts.py`, and the HogFunction template ID and required fields in `products/alerts/backend/logic/destination_configs.py`.2. Extend validation and `build_alert_destination_config(...)` without changing existing payloads.-3. Add or update the transport template under `posthog/cdp/templates/<destination>/template_<destination>.py` and its adjacent tests.+3. Add the transport template under `nodejs/src/cdp/templates/_destinations/<destination>/<destination>.template.ts`, register it in `nodejs/src/cdp/templates/index.ts`, and test it with `TemplateTester` next to it. Django tests that need the template in the database sync a stand-in from `posthog/cdp/templates/fixtures.py`; its inputs schema must track which inputs are secret, because that decides what a saved destination keeps in `inputs` versus `encrypted_inputs`. Only update an existing template under `posthog/cdp/templates/` when it already lives there.4. Add alert-specific template compatibility in `frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts`.5. Decide which products explicitly allow the destination and update their destination editors or display logic.6. Add the option to `AlertWizard` only where supported by the relevant sub-template.diff --git a/nodejs/src/cdp/managed-alert-events.ts b/nodejs/src/cdp/managed-alert-events.tsindex 705505b4b8e5..e7707d2649eb 100644--- a/nodejs/src/cdp/managed-alert-events.ts+++ b/nodejs/src/cdp/managed-alert-events.ts@@ -1,6 +1,7 @@// Mirror of `posthog/cdp/internal_events.py`. The managed-alert event boundary and the legacy// insight-alert exemption must match the Python side exactly, so keep the two in sync.-export const MANAGED_ALERT_EVENT_PATTERN = /^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match)$/+export const MANAGED_ALERT_EVENT_PATTERN =+ /^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match|incident_opened|incident_closed)$/export const LEGACY_INSIGHT_ALERT_EVENT = '$insight_alert_firing'/** Return whether an internal event is reserved for an alert-owned destination. */diff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.pyindex 92472a164ac2..ff5df7064b1e 100644--- a/posthog/cdp/internal_events.py+++ b/posthog/cdp/internal_events.py@@ -16,7 +16,9 @@ logger = structlog.get_logger(__name__)# Single source of truth for the managed-alert event boundary. Also used as a Postgres regex# filter (products/cdp hog_function queryset) and mirrored in the Node CDP consumer, so keep it# POSIX-compatible (no (?:...) groups).-MANAGED_ALERT_EVENT_PATTERN = r"^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match)$"+MANAGED_ALERT_EVENT_PATTERN = (+ r"^\$[a-z0-9_]+_alert_(firing|resolved|errored|auto_disabled|match|incident_opened|incident_closed)$"+)LEGACY_INSIGHT_ALERT_EVENT = "$insight_alert_firing"_MANAGED_ALERT_EVENT = re.compile(MANAGED_ALERT_EVENT_PATTERN)diff --git a/posthog/cdp/templates/fixtures.py b/posthog/cdp/templates/fixtures.pyindex 93d4fc08d973..59b9b1f42716 100644--- a/posthog/cdp/templates/fixtures.py+++ b/posthog/cdp/templates/fixtures.py@@ -78,3 +78,103 @@ if (res.status != 200 or res.body.ok == false) {},],)++# Same arrangement for the PagerDuty destination (nodejs/src/cdp/templates/_destinations/pagerduty).+# The inputs schema does track the nodejs template, because which inputs are secret decides what a+# saved destination keeps in `inputs` versus `encrypted_inputs`, and the alert destination tests+# depend on that split.+template_pagerduty = HogFunctionTemplateDC(+ status="stable",+ free=True,+ type="destination",+ id="template-pagerduty",+ name="PagerDuty",+ description="Sends an event to the PagerDuty Events API v2 to trigger, acknowledge or resolve an incident",+ icon_url="/static/services/pagerduty.png",+ category=["Monitoring & Alerts"],+ code_language="hog",+ code="""+let endpoint := 'https://events.pagerduty.com/v2/enqueue'+if (inputs.region == 'eu') {+ endpoint := 'https://events.eu.pagerduty.com/v2/enqueue'+}++let payload := {+ 'summary': inputs.summary,+ 'source': inputs.source,+ 'severity': inputs.severity+}+if (not empty(inputs.custom_details)) {+ payload['custom_details'] := inputs.custom_details+}++let body := {+ 'routing_key': inputs.routing_key,+ 'event_action': inputs.event_action,+ 'payload': payload,+ 'client': 'PostHog'+}+if (not empty(inputs.dedup_key)) {+ body['dedup_key'] := inputs.dedup_key+}+if (not empty(inputs.links)) {+ body['links'] := inputs.links+}++let res := fetch(endpoint, {+ 'method': 'POST',+ 'headers': {+ 'Content-Type': 'application/json'+ },+ 'body': body+});++if (res.status >= 400) {+ throw Error(f'Failed to send event to PagerDuty: {res.status}: {res.body}');+}+""".strip(),+ inputs_schema=[+ {"key": "routing_key", "type": "string", "label": "Integration key", "secret": True, "required": True},+ {+ "key": "region",+ "type": "choice",+ "label": "Service region",+ "choices": [{"label": "US", "value": "us"}, {"label": "EU", "value": "eu"}],+ "default": "us",+ "secret": False,+ "required": True,+ },+ {+ "key": "event_action",+ "type": "choice",+ "label": "Event action",+ "choices": [+ {"label": "Trigger", "value": "trigger"},+ {"label": "Acknowledge", "value": "acknowledge"},+ {"label": "Resolve", "value": "resolve"},+ ],+ "default": "trigger",+ "secret": False,+ "required": True,+ },+ {"key": "dedup_key", "type": "string", "label": "Deduplication key", "secret": False, "required": False},+ {"key": "summary", "type": "string", "label": "Summary", "secret": False, "required": True},+ {"key": "source", "type": "string", "label": "Source", "secret": False, "required": True},+ {+ "key": "severity",+ "type": "choice",+ "label": "Severity",+ "choices": [+ {"label": "Critical", "value": "critical"},+ {"label": "Error", "value": "error"},+ {"label": "Warning", "value": "warning"},+ {"label": "Info", "value": "info"},+ ],+ "default": "error",+ "secret": False,+ "required": True,+ },+ {"key": "custom_details", "type": "json", "label": "Custom details", "secret": False, "required": False},+ {"key": "links", "type": "json", "label": "Links", "secret": False, "required": False},+ ],+)diff --git a/posthog/management/commands/sync_hog_function_templates.py b/posthog/management/commands/sync_hog_function_templates.pyindex 8a3f3299cba4..cc0123112435 100644--- a/posthog/management/commands/sync_hog_function_templates.py+++ b/posthog/management/commands/sync_hog_function_templates.py@@ -33,6 +33,7 @@ TEST_INCLUDE_PYTHON_TEMPLATE_IDS = [TEST_INCLUDE_NODEJS_TEMPLATE_IDS = ["template-slack","template-webhook",+ "template-pagerduty","template-geoip","plugin-posthog-plugin-geoip","plugin-taxonomy-plugin",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 89499091c28b..56d1f8c84244 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -670,6 +670,9 @@ SPECTACULAR_SETTINGS = {"DiagnosticSeverityEnum": ["error", "warning"],"InitialPermissionModeEnum": ["default", "acceptEdits", "plan", "bypassPermissions", "auto"],"NotificationDestinationTypeEnum": ["slack", "webhook", "teams"],+ "LogsAlertDestinationTypeEnum": ["slack", "webhook", "teams", "pagerduty"],+ "PagerDutySeverityEnum": ["critical", "error", "warning", "info"],+ "PagerDutyRegionEnum": ["us", "eu"],# growth's identity-matching tier and the signals scout suggestion confidence."ConfidenceTierEnum": ["low", "medium", "high"],#diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pyindex 2c43144409fa..8e3b6b6da992 100644--- a/products/alerts/backend/facade/destinations.py+++ b/products/alerts/backend/facade/destinations.py@@ -58,6 +58,15 @@ def validate_destination_data(destination_configs.validate_destination_data(data, allowed_destination_types=allowed_destination_types)+def destination_handles_event_kind(destination_type: DestinationType, spec: EventKindSpec) -> bool:+ """Whether a destination type has something to send for one event kind.++ An incident manager such as PagerDuty follows only the kinds that trigger or resolve an+ incident, so a product filters its event kinds with this before it builds configs.+ """+ return destination_configs.destination_handles_event_kind(destination_type, spec)++def build_alert_destination_config(*,spec: EventKindSpec,diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.pyindex db9c52141265..482a000f6c9a 100644--- a/products/alerts/backend/logic/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -2,6 +2,7 @@from __future__ import annotations+import refrom abc import ABC, abstractmethodfrom collections.abc import Sequencefrom typing import Any, ClassVar@@ -14,12 +15,17 @@ from products.alerts_platform.backend.facade.contracts import (AlertDestinationValidationError,DestinationType,EventKindSpec,+ PagerDutyRegion,+ PagerDutySeverity,)WEBHOOK_HEADERS = {"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}_HOG_FUNCTION_NAME_MAX_LEN = 400+# An Events API v2 integration key as PagerDuty issues it.+_PAGERDUTY_ROUTING_KEY_RE = re.compile(r"[A-Za-z0-9]{32}")+def clip_hog_function_name(name: str) -> str:if len(name) <= _HOG_FUNCTION_NAME_MAX_LEN:@@ -42,6 +48,13 @@ def destination_filter(alert_id: str, event_id: str) -> dict[str, Any]:}+def spec_actions(spec: EventKindSpec) -> tuple[AlertDestinationAction, ...]:+ return (+ AlertDestinationAction(url=spec.primary_action_url, label=spec.primary_action_label),+ *spec.additional_actions,+ )++def slack_body(spec: EventKindSpec) -> str:parts = []if spec.intro_lines:@@ -68,10 +81,7 @@ def slack_blocks(spec: EventKindSpec, context_elements: tuple[str, ...]) -> list"text": {"text": action.label, "type": "plain_text"},"type": "button",}- for action in (- AlertDestinationAction(url=spec.primary_action_url, label=spec.primary_action_label),- *spec.additional_actions,- )+ for action in spec_actions(spec)],},]@@ -82,18 +92,28 @@ def teams_text(spec: EventKindSpec) -> str:parts.extend(spec.intro_lines)if spec.details:parts.append("\n\n".join(f"**{label}:** {value}" for label, value in spec.details))- parts.append(- " · ".join(- f"[{action.label}]({action.url})"- for action in (- AlertDestinationAction(url=spec.primary_action_url, label=spec.primary_action_label),- *spec.additional_actions,- )- )- )+ parts.append(" · ".join(f"[{action.label}]({action.url})" for action in spec_actions(spec)))return "\n\n".join(parts)+def pagerduty_summary(spec: EventKindSpec) -> str:+ """The incident title: the header, plus the first detail so the page says what breached."""+ if not spec.details:+ return spec.header+ return f"{spec.header}: {spec.details[0][1]}"+++def pagerduty_custom_details(spec: EventKindSpec) -> dict[str, str]:+ details = dict(spec.details)+ if spec.intro_lines:+ details = {"Details": "\n".join(spec.intro_lines), **details}+ return details+++def pagerduty_links(spec: EventKindSpec) -> list[dict[str, str]]:+ return [{"href": action.url, "text": action.label} for action in spec_actions(spec)]++def _input_value(inputs: dict[str, Any], key: str) -> Any:entry = inputs.get(key)return entry.get("value") if isinstance(entry, dict) else None@@ -107,6 +127,26 @@ class DestinationSpec(ABC):template_id: ClassVar[str]required_fields: ClassVar[tuple[str, ...]]+ def validate(self, data: AlertDestinationData) -> None:+ """Raise `AlertDestinationValidationError` when the payload cannot become a destination of this type."""+ missing_fields = tuple(field for field in self.required_fields if not data.get(field))+ if len(missing_fields) == 1:+ missing_field = missing_fields[0]+ raise AlertDestinationValidationError(+ f"{missing_field} is required for {self.type.label} destinations.", field=missing_field+ )+ if missing_fields:+ formatted_fields = " and ".join(missing_fields)+ raise AlertDestinationValidationError(f"{self.type.label} destinations require {formatted_fields}.")++ def handles(self, event_kind_spec: EventKindSpec) -> bool:+ """Whether this destination type has something to send for one event kind.++ A message destination skips the incident kinds, because they repeat what the notification+ kinds already said and ignore cooldown.+ """+ return event_kind_spec.incident_action is None+@abstractmethoddef build_name(self, data: AlertDestinationData) -> str: ...@@ -245,8 +285,98 @@ class TeamsDestination(_WebhookUrlDestination):}+class PagerDutyDestination(DestinationSpec):+ """One incident per alert: the incident kinds trigger and resolve it, tied together by a+ deduplication key derived from the alert id."""++ type = DestinationType.PAGERDUTY+ template_id = "template-pagerduty"+ required_fields = ("pagerduty_routing_key",)++ def validate(self, data: AlertDestinationData) -> None:+ super().validate(data)+ routing_key = data["pagerduty_routing_key"]+ if not isinstance(routing_key, str) or not _PAGERDUTY_ROUTING_KEY_RE.fullmatch(routing_key):+ raise AlertDestinationValidationError(+ "Enter the 32-character integration key of a PagerDuty Events API v2 integration.",+ field="pagerduty_routing_key",+ )+ severity = data.get("pagerduty_severity")+ if severity is not None and severity not in PagerDutySeverity:+ choices = ", ".join(choice.value for choice in PagerDutySeverity)+ raise AlertDestinationValidationError(f"Choose a severity: {choices}.", field="pagerduty_severity")+ region = data.get("pagerduty_region")+ if region is not None and region not in PagerDutyRegion:+ choices = ", ".join(choice.value for choice in PagerDutyRegion)+ raise AlertDestinationValidationError(f"Choose a region: {choices}.", field="pagerduty_region")++ def handles(self, event_kind_spec: EventKindSpec) -> bool:+ return event_kind_spec.incident_action is not None++ def build_name(self, data: AlertDestinationData) -> str:+ return f"PagerDuty {_redact_routing_key(data['pagerduty_routing_key'])}"++ def build_inputs(+ self,+ event_kind_spec: EventKindSpec,+ data: AlertDestinationData,+ *,+ slack_context_elements: tuple[str, ...],+ ) -> dict[str, Any]:+ if event_kind_spec.incident_action is None:+ 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},+ "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},+ "custom_details": {"value": pagerduty_custom_details(event_kind_spec)},+ "links": {"value": pagerduty_links(event_kind_spec)},+ }++ def read(self, inputs: dict[str, Any]) -> AlertDestinationData:+ data: AlertDestinationData = {"type": self.type}+ routing_key = _input_value(inputs, "routing_key")+ # Without the key two PagerDuty destinations cannot be told apart, so a config that+ # lacks it reads as unreadable rather than as "the same as every other one".+ if not isinstance(routing_key, str) or not routing_key:+ return data+ data["pagerduty_routing_key"] = routing_key+ severity = _input_value(inputs, "severity")+ region = _input_value(inputs, "region")+ if isinstance(severity, str):+ data["pagerduty_severity"] = severity+ if isinstance(region, str):+ data["pagerduty_region"] = region+ return data++ def redact(self, data: AlertDestinationData) -> AlertDestinationData:+ routing_key = data.get("pagerduty_routing_key")+ if routing_key is None:+ return data+ redacted = data.copy()+ redacted["pagerduty_routing_key"] = _redact_routing_key(routing_key)+ return redacted+++def _redact_routing_key(value: str) -> str:+ """Keep the tail a person needs to tell two integration keys apart."""+ return f"••••{value[-4:]}"++DESTINATION_SPECS: dict[DestinationType, DestinationSpec] = {- spec.type: spec for spec in (SlackDestination(), DiscordDestination(), WebhookDestination(), TeamsDestination())+ spec.type: spec+ for spec in (+ SlackDestination(),+ DiscordDestination(),+ WebhookDestination(),+ TeamsDestination(),+ PagerDutyDestination(),+ )}SPEC_BY_TEMPLATE_ID: dict[str, DestinationSpec] = {spec.template_id: spec for spec in DESTINATION_SPECS.values()}@@ -284,18 +414,11 @@ def validate_destination_data(if destination_type is None:choices = ", ".join(f"{choice.label} ({choice.value})" for choice in allowed_destination_types)raise AlertDestinationValidationError(f"Choose a supported destination type: {choices}.", field="type")+ DESTINATION_SPECS[destination_type].validate(data)- missing_fields = tuple(- field for field in DESTINATION_SPECS[destination_type].required_fields if not data.get(field)- )- if len(missing_fields) == 1:- missing_field = missing_fields[0]- raise AlertDestinationValidationError(- f"{missing_field} is required for {destination_type.label} destinations.", field=missing_field- )- if missing_fields:- formatted_fields = " and ".join(missing_fields)- raise AlertDestinationValidationError(f"{destination_type.label} destinations require {formatted_fields}.")++def destination_handles_event_kind(destination_type: DestinationType, spec: EventKindSpec) -> bool:+ return DESTINATION_SPECS[destination_type].handles(spec)def build_alert_destination_config(@@ -307,6 +430,11 @@ def build_alert_destination_config(slack_context_elements: tuple[str, ...],) -> AlertDestinationConfig:destination_spec = DESTINATION_SPECS[data["type"]]+ if not destination_spec.handles(spec):+ raise ValueError(+ f"{destination_spec.type.label} destinations have nothing to send for the {spec.display_kind} event kind. "+ "Filter event kinds with destination_handles_event_kind first."+ )product_name = spec.product_label.capitalize()destination_name = destination_spec.build_name(data)diff --git a/products/alerts/backend/logic/destinations.py b/products/alerts/backend/logic/destinations.pyindex acbf246672db..d74c83fdaae5 100644--- a/products/alerts/backend/logic/destinations.py+++ b/products/alerts/backend/logic/destinations.py@@ -56,6 +56,12 @@ class AlertDestinationRow(NamedTuple):inputs: dict[str, Any] | None+def stored_inputs(inputs: dict[str, Any] | None, encrypted_inputs: dict[str, Any] | None) -> dict[str, Any]:+ """The inputs a destination was built with. A HogFunction keeps its secret inputs in a+ separate encrypted column, and a read that tells destinations apart needs them back."""+ return {**(inputs or {}), **(encrypted_inputs or {})}++def alert_destination_group_key(*, template_id: str, inputs: dict[str, Any] | None) -> AlertDestinationGroupKey:spec = SPEC_BY_TEMPLATE_ID.get(template_id)if spec is None:@@ -89,11 +95,14 @@ def list_alert_destination_groups(raw_rows = list(owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids).order_by("created_at", "id")- .values_list("id", "template_id", "inputs", "enabled")+ .values_list("id", "template_id", "inputs", "encrypted_inputs", "enabled"))- rows = [AlertDestinationRow(row_id, template_id, inputs) for row_id, template_id, inputs, _ in raw_rows]+ rows = [+ AlertDestinationRow(row_id, template_id, stored_inputs(inputs, encrypted_inputs))+ for row_id, template_id, inputs, encrypted_inputs, _ in raw_rows+ ]grouped_ids = group_alert_destination_rows(rows)- enabled_by_id = {row_id: enabled for row_id, _, _, enabled in raw_rows}+ enabled_by_id = {row_id: enabled for row_id, _, _, _, enabled in raw_rows}groups: list[AlertDestinationGroup] = []for key, ids in grouped_ids.items():@@ -196,11 +205,12 @@ def _raise_if_alert_already_has_these_destination_configs(stored_rows = (owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids).filter(template_id__in={key.template_id for key in readable_keys})- .values_list("template_id", "inputs")+ .values_list("template_id", "inputs", "encrypted_inputs"))if any(- alert_destination_group_key(template_id=template_id or "", inputs=inputs) in readable_keys- for template_id, inputs in stored_rows+ alert_destination_group_key(template_id=template_id or "", inputs=stored_inputs(inputs, encrypted_inputs))+ in readable_keys+ for template_id, inputs, encrypted_inputs in stored_rows):raise AlertDestinationValidationError("This destination is already configured for this alert.")@@ -276,12 +286,12 @@ def soft_delete_alert_destinations(unique_ids = set(hog_function_ids)with transaction.atomic():owned_rows = [- AlertDestinationRow(*row)- for row in owned_alert_destinations_qs(+ AlertDestinationRow(row_id, template_id, stored_inputs(inputs, encrypted_inputs))+ for row_id, template_id, inputs, encrypted_inputs in owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids).select_for_update()- .values_list("id", "template_id", "inputs")+ .values_list("id", "template_id", "inputs", "encrypted_inputs")]owned_ids = {row.hog_function_id for row in owned_rows}invalid_ids = unique_ids - owned_idsdiff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.pyindex dd7121a12043..bf95fd119a00 100644--- a/products/alerts/backend/test/test_destination_configs.py+++ b/products/alerts/backend/test/test_destination_configs.py@@ -1,20 +1,27 @@+from dataclasses import replacefrom typing import Anyimport pytestfrom posthog.cdp.templates import HOG_FUNCTION_TEMPLATES+from posthog.cdp.templates.fixtures import template_pagerdutyfrom products.alerts.backend.logic.destination_configs import (DESTINATION_SPECS,build_alert_destination_config,+ destination_handles_event_kind,slack_blocks,teams_text,+ validate_destination_data,)+from products.alerts.backend.logic.destinations import stored_inputsfrom products.alerts_platform.backend.facade.contracts import (AlertDestinationAction,AlertDestinationData,+ AlertDestinationValidationError,DestinationType,EventKindSpec,+ IncidentAction,)DEFAULT_SPEC = EventKindSpec(@@ -27,6 +34,19 @@ DEFAULT_SPEC = EventKindSpec(webhook_body={},)+TRIGGER_SPEC = replace(DEFAULT_SPEC, event_id="$insight_alert_incident_opened", incident_action=IncidentAction.TRIGGER)++RESOLVED_SPEC = EventKindSpec(+ event_id="$insight_alert_resolved",+ display_kind="resolved",+ header="Insight alert resolved",+ details=(("Current value", "12"),),+ primary_action_url="https://example.com/insight",+ primary_action_label="View insight",+ webhook_body={},+ incident_action=IncidentAction.RESOLVE,+)+MULTI_DETAIL_SPEC = EventKindSpec(event_id="$insight_alert_broken",display_kind="broken",@@ -100,23 +120,38 @@ class TestSpecVocabularyRendering:)-_TEMPLATES_BY_ID = {template.id: template for template in HOG_FUNCTION_TEMPLATES}+_PYTHON_TEMPLATE_IDS = {template.id for template in HOG_FUNCTION_TEMPLATES}++_TEMPLATE_IDS_DEFINED_IN_NODEJS = {"template-slack", "template-webhook", "template-pagerduty"}-_TEMPLATE_IDS_DEFINED_IN_NODEJS = {"template-slack", "template-webhook"}+# The PagerDuty template lives in nodejs; its fixture stand-in tracks the nodejs inputs schema.+_TEMPLATES_BY_ID = {template.id: template for template in (*HOG_FUNCTION_TEMPLATES, template_pagerduty)}++PAGERDUTY_ROUTING_KEY = "0123456789abcdef0123456789abcdef"_DESTINATION_DATA: dict[DestinationType, AlertDestinationData] = {DestinationType.DISCORD: {"type": DestinationType.DISCORD, "webhook_url": "https://discord.example.com/hook"},DestinationType.TEAMS: {"type": DestinationType.TEAMS, "webhook_url": "https://teams.example.com/hook"},+ DestinationType.PAGERDUTY: {+ "type": DestinationType.PAGERDUTY,+ "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY,+ "pagerduty_severity": "error",+ "pagerduty_region": "eu",+ },}-def _inputs_a_hog_function_would_keep(template: Any, inputs: dict[str, Any]) -> dict[str, Any]:- return {entry["key"]: inputs.get(entry["key"]) for entry in template.inputs_schema or [] if not entry.get("secret")}+def _inputs_the_read_path_sees(template: Any, inputs: dict[str, Any]) -> dict[str, Any]:+ # A saved HogFunction splits its inputs by the template schema: plain ones stay in+ # `inputs`, secret ones move to `encrypted_inputs`. The read path merges them back.+ plain = {entry["key"]: inputs.get(entry["key"]) for entry in template.inputs_schema if not entry.get("secret")}+ secret = {entry["key"]: inputs.get(entry["key"]) for entry in template.inputs_schema if entry.get("secret")}+ return stored_inputs(plain, secret)class TestDestinationTemplateContract:def test_the_templates_defined_outside_python_are_the_ones_we_expect(self) -> None:- unreachable = {spec.template_id for spec in DESTINATION_SPECS.values()} - set(_TEMPLATES_BY_ID)+ unreachable = {spec.template_id for spec in DESTINATION_SPECS.values()} - _PYTHON_TEMPLATE_IDSassert unreachable == _TEMPLATE_IDS_DEFINED_IN_NODEJS@@ -127,16 +162,17 @@ class TestDestinationTemplateContract:template = _TEMPLATES_BY_ID[DESTINATION_SPECS[destination_type].template_id]data = _DESTINATION_DATA[destination_type]config = build_alert_destination_config(- spec=DEFAULT_SPEC,+ spec=TRIGGER_SPEC if destination_type == DestinationType.PAGERDUTY else DEFAULT_SPEC,alert_id="alert-1",alert_name="Signups",data=data,slack_context_elements=(),)- stored_inputs = _inputs_a_hog_function_would_keep(template, config.payload["inputs"])-- assert DESTINATION_SPECS[destination_type].read(stored_inputs) == data+ assert (+ DESTINATION_SPECS[destination_type].read(_inputs_the_read_path_sees(template, config.payload["inputs"]))+ == data+ )@pytest.mark.parametrize("webhook_url",@@ -179,3 +215,125 @@ class TestDestinationTemplateContract:"slack_workspace_id": 42,"slack_channel_id": "C123",}+++def _pagerduty_config(spec: EventKindSpec, data: AlertDestinationData | None = None) -> dict[str, Any]:+ config = build_alert_destination_config(+ spec=spec,+ alert_id="alert-1",+ alert_name="Signups",+ data=data or _DESTINATION_DATA[DestinationType.PAGERDUTY],+ slack_context_elements=(),+ )+ return config.payload+++class TestPagerDutyDestination:+ def test_firing_and_resolved_address_the_same_incident(self) -> None:+ firing = _pagerduty_config(TRIGGER_SPEC)["inputs"]+ resolved = _pagerduty_config(RESOLVED_SPEC)["inputs"]++ assert firing["event_action"]["value"] == "trigger"+ assert resolved["event_action"]["value"] == "resolve"+ assert (+ firing["dedup_key"]["value"]+ == resolved["dedup_key"]["value"]+ == "posthog-alert-{event.properties.alert_id}"+ )+ assert firing["routing_key"]["value"] == PAGERDUTY_ROUTING_KEY+ assert firing["region"]["value"] == "eu"+ assert firing["severity"]["value"] == "error"+ assert firing["summary"]["value"] == "Insight alert firing: 30"+ assert firing["custom_details"]["value"] == {"Threshold": "30"}+ assert firing["links"]["value"] == [{"href": "https://example.com/insight", "text": "View insight"}]++ def test_severity_and_region_default_when_a_caller_leaves_them_out(self) -> None:+ inputs = _pagerduty_config(+ TRIGGER_SPEC, {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY}+ )["inputs"]++ assert inputs["severity"]["value"] == "critical"+ assert inputs["region"]["value"] == "us"++ def test_the_name_and_the_read_response_keep_only_the_tail_of_the_key(self) -> None:+ payload = _pagerduty_config(TRIGGER_SPEC)++ assert payload["name"].endswith("→ PagerDuty ••••cdef")+ redacted = DESTINATION_SPECS[DestinationType.PAGERDUTY].redact(_DESTINATION_DATA[DestinationType.PAGERDUTY])+ assert redacted["pagerduty_routing_key"] == "••••cdef"+ assert PAGERDUTY_ROUTING_KEY not in str(redacted)++ @pytest.mark.parametrize(+ "destination_type,spec,handled",+ [+ (DestinationType.PAGERDUTY, TRIGGER_SPEC, True),+ (DestinationType.PAGERDUTY, RESOLVED_SPEC, True),+ (DestinationType.PAGERDUTY, DEFAULT_SPEC, False),+ (DestinationType.PAGERDUTY, MULTI_DETAIL_SPEC, False),+ (DestinationType.SLACK, DEFAULT_SPEC, True),+ (DestinationType.SLACK, TRIGGER_SPEC, False),+ (DestinationType.TEAMS, MULTI_DETAIL_SPEC, True),+ (DestinationType.WEBHOOK, RESOLVED_SPEC, False),+ ],+ )+ def test_incident_kinds_go_only_to_incident_managers(+ self, destination_type: DestinationType, spec: EventKindSpec, handled: bool+ ) -> None:+ assert destination_handles_event_kind(destination_type, spec) is handled+ if not handled:+ with pytest.raises(ValueError, match="nothing to send"):+ build_alert_destination_config(+ spec=spec,+ alert_id="alert-1",+ alert_name="Signups",+ data=_DESTINATION_DATA.get(destination_type)+ or {"type": destination_type, "webhook_url": "https://hooks.example.com/hook"},+ slack_context_elements=(),+ )++ def test_a_config_without_the_key_reads_as_unreadable_rather_than_as_a_duplicate(self) -> None:+ masked = {"routing_key": {"secret": True}, "severity": {"value": "critical"}, "region": {"value": "us"}}++ assert DESTINATION_SPECS[DestinationType.PAGERDUTY].read(masked) == {"type": DestinationType.PAGERDUTY}++ @pytest.mark.parametrize(+ "data,field,message",+ [+ (+ {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": "too-short"},+ "pagerduty_routing_key",+ "Enter the 32-character integration key of a PagerDuty Events API v2 integration.",+ ),+ (+ {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": 12345},+ "pagerduty_routing_key",+ "Enter the 32-character integration key of a PagerDuty Events API v2 integration.",+ ),+ (+ {+ "type": DestinationType.PAGERDUTY,+ "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY,+ "pagerduty_severity": "urgent",+ },+ "pagerduty_severity",+ "Choose a severity: critical, error, warning, info.",+ ),+ (+ {+ "type": DestinationType.PAGERDUTY,+ "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY,+ "pagerduty_region": "apac",+ },+ "pagerduty_region",+ "Choose a region: us, eu.",+ ),+ ],+ )+ def test_validation_rejects_a_malformed_pagerduty_payload(+ self, data: AlertDestinationData, field: str, message: str+ ) -> None:+ with pytest.raises(AlertDestinationValidationError) as error:+ validate_destination_data(data, allowed_destination_types=(DestinationType.PAGERDUTY,))++ assert error.value.field == field+ assert error.value.message == messagediff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pyindex 9a4a8d901887..e3f04b4cc290 100644--- a/products/alerts/backend/test/test_destinations.py+++ b/products/alerts/backend/test/test_destinations.py@@ -35,6 +35,7 @@ from products.alerts_platform.backend.facade.contracts import (AlertDestinationValidationError,DestinationType,EventKindSpec,+ IncidentAction,)from products.cdp.backend.facade.models import HogFunction@@ -50,6 +51,12 @@ _DESTINATION_DATA: dict[DestinationType, AlertDestinationData] = {DestinationType.DISCORD: {"type": DestinationType.DISCORD, "webhook_url": "https://discord.example.com/hook"},DestinationType.WEBHOOK: {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/hook"},DestinationType.TEAMS: {"type": DestinationType.TEAMS, "webhook_url": "https://teams.example.com/hook"},+ DestinationType.PAGERDUTY: {+ "type": DestinationType.PAGERDUTY,+ "pagerduty_routing_key": "0123456789abcdef0123456789abcdef",+ "pagerduty_severity": "critical",+ "pagerduty_region": "us",+ },}@@ -61,15 +68,20 @@ def webhook_inputs(url: str) -> dict[str, Any]:return {"url": {"value": url}}+def pagerduty_inputs(routing_key: str, *, severity: str = "critical") -> dict[str, Any]:+ return {"routing_key": {"value": routing_key}, "severity": {"value": severity}, "region": {"value": "us"}}++_READABLE_INPUTS_BY_TEMPLATE: dict[str, dict[str, Any]] = {"template-slack": slack_inputs("C-ENG"),"template-webhook": webhook_inputs("https://example.com/hook"),"template-microsoft-teams": {"webhookUrl": {"value": "https://teams.example.com/hook"}},+ "template-pagerduty": pagerduty_inputs("0123456789abcdef0123456789abcdef"),}-def _schema_declaring_every_input(inputs: dict[str, Any]) -> list[dict[str, Any]]:- return [{"key": key, "type": "string"} for key in inputs]+def _schema_declaring_every_input(inputs: dict[str, Any], secret_keys: set[str]) -> list[dict[str, Any]]:+ return [{"key": key, "type": "string", "secret": key in secret_keys} for key in inputs]class AlertDestinationTestCase(APIBaseTest):@@ -82,6 +94,7 @@ class AlertDestinationTestCase(APIBaseTest):inputs: dict[str, Any] | None = None,team: Team | None = None,name: str = "Test destination",+ secret_keys: set[str] | None = None,) -> HogFunction:resolved_inputs = _READABLE_INPUTS_BY_TEMPLATE.get(template_id, {}) if inputs is None else inputsreturn HogFunction.objects.create(@@ -90,7 +103,7 @@ class AlertDestinationTestCase(APIBaseTest):type="destination",template_id=template_id,enabled=True,- inputs_schema=_schema_declaring_every_input(resolved_inputs),+ inputs_schema=_schema_declaring_every_input(resolved_inputs, secret_keys or set()),inputs=resolved_inputs,hog="return event",filters={@@ -106,10 +119,16 @@ class AlertDestinationTestCase(APIBaseTest):alert_id: str,inputs: dict[str, Any] | None = None,team: Team | None = None,+ secret_keys: set[str] | None = None,) -> list[HogFunction]:return [self._make_hog_function(- template_id=template_id, alert_id=alert_id, event_id=event_id, inputs=inputs, team=team+ template_id=template_id,+ alert_id=alert_id,+ event_id=event_id,+ inputs=inputs,+ team=team,+ secret_keys=secret_keys,)for event_id in ALLOWED_EVENT_IDS]@@ -137,6 +156,7 @@ def _config_for(destination_type: DestinationType, event_id: str) -> AlertDestinprimary_action_url="https://example.com/alert",primary_action_label="View alert",webhook_body={"event": event_id},+ incident_action=IncidentAction.TRIGGER if destination_type == DestinationType.PAGERDUTY else None,),alert_id="alert-1",alert_name="Signups",@@ -284,6 +304,19 @@ class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCaseself._raise_if_exists(configs=[("template-discord", webhook_url)])+ def test_compares_against_a_secret_input_stored_in_the_encrypted_column(self) -> None:+ stored = self._make_group(+ template_id="template-pagerduty",+ alert_id="alert-1",+ inputs=pagerduty_inputs("a" * 32),+ secret_keys={"routing_key"},+ )+ assert "routing_key" not in (stored[0].inputs or {})++ self._raise_if_exists(configs=[("template-pagerduty", pagerduty_inputs("b" * 32))])+ with self.assertRaisesRegex(AlertDestinationValidationError, "already configured for this alert"):+ self._raise_if_exists(configs=[("template-pagerduty", pagerduty_inputs("a" * 32))])+class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):def test_deletes_alert_destination_with_matching_alert_id(self) -> None:diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex f101a6bf76b6..b6e672434a48 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -439,6 +439,26 @@ class DestinationType(LabeledStrEnum):DISCORD = "discord", "Discord"WEBHOOK = "webhook", "Webhook"TEAMS = "teams", "Microsoft Teams"+ PAGERDUTY = "pagerduty", "PagerDuty"+++class PagerDutySeverity(StrEnum):+ CRITICAL = "critical"+ ERROR = "error"+ WARNING = "warning"+ INFO = "info"+++class PagerDutyRegion(StrEnum):+ US = "us"+ EU = "eu"+++class IncidentAction(StrEnum):+ """What one event kind does to the incident an alert holds open in an incident manager."""++ TRIGGER = "trigger"+ RESOLVE = "resolve"class AlertDestinationData(TypedDict):@@ -447,6 +467,9 @@ class AlertDestinationData(TypedDict):slack_channel_id: NotRequired[str]slack_channel_name: NotRequired[str]webhook_url: NotRequired[str]+ pagerduty_routing_key: NotRequired[str]+ pagerduty_severity: NotRequired[str]+ pagerduty_region: NotRequired[str]class AlertDestinationValidationError(Exception):@@ -479,6 +502,9 @@ class EventKindSpec:product_label: str = "alert"intro_lines: tuple[str, ...] = ()additional_actions: tuple[AlertDestinationAction, ...] = ()+ # Set only on the kinds that open or close an incident. An incident manager destination+ # subscribes to those kinds and no others; every other destination subscribes to the rest.+ incident_action: IncidentAction | None = Nonedef destination_description(self, alert_name: str) -> str:return f'Sends {self.display_kind} notifications for {self.product_label} "{alert_name}".'@@ -524,7 +550,7 @@ class AlertDelivery:channel: str # "email" | "hog_function"target: str # email address or destination nametarget_id: str | None = None # hog function id- template: str | None = None # "slack" | "discord" | "webhook" | "teams"+ template: str | None = None # "slack" | "discord" | "webhook" | "teams" | "pagerduty"status: str = "accepted"at: str # ISO-8601 timestampdiff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex 4b31a5164f87..f9fe31b31469 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -192,15 +192,16 @@ class TestHogFunctionAPIWithoutAvailableFeature(ClickhouseTestMixin, APIBaseTest)self.assertEqual(delete_response.status_code, status.HTTP_200_OK, delete_response.json())- def test_generic_api_cannot_subscribe_to_managed_alert_events(self):+ @parameterized.expand([("$billing_alert_firing",), ("$logs_alert_incident_closed",)])+ def test_generic_api_cannot_subscribe_to_managed_alert_events(self, event_id):response = self.client.post(f"/api/projects/{self.team.id}/hog_functions/",data={- "name": "Forged billing destination",+ "name": "Forged alert destination","hog": "fetch('https://example.com');","type": "internal_destination","enabled": True,- "filters": {"events": [{"id": "$billing_alert_firing", "type": "events"}]},+ "filters": {"events": [{"id": event_id, "type": "events"}]},},)diff --git a/products/logs/backend/alert_destinations.py b/products/logs/backend/alert_destinations.pyindex 43ea3231f695..21741c333a49 100644--- a/products/logs/backend/alert_destinations.py+++ b/products/logs/backend/alert_destinations.py@@ -2,15 +2,30 @@from __future__ import annotations+from dataclasses import replacefrom typing import Literal-from products.alerts_platform.backend.facade.contracts import DestinationType, EventKindSpec+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationAction,+ DestinationType,+ EventKindSpec,+ IncidentAction,+)++EventKind = Literal["firing", "resolved", "broken", "errored", "incident_opened", "incident_closed"]+LOGS_DESTINATION_TYPES = (+ DestinationType.SLACK,+ DestinationType.WEBHOOK,+ DestinationType.TEAMS,+ DestinationType.PAGERDUTY,+)-EventKind = Literal["firing", "resolved", "broken", "errored"]-LOGS_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)+LOGS_ALERT_INCIDENT_OPENED_EVENT = "$logs_alert_incident_opened"+LOGS_ALERT_INCIDENT_CLOSED_EVENT = "$logs_alert_incident_closed"_PRODUCT_LABEL = "logs alert"+_ALERT_URL = "{project.url}/logs/alerts/{event.properties.alert_id}"_FIRE_RESOLVE_DATA: dict[str, str] = {"alert_id": "{event.properties.alert_id}","alert_name": "{event.properties.alert_name}",@@ -21,7 +36,7 @@ _FIRE_RESOLVE_DATA: dict[str, str] = {"service_names": "{event.properties.service_names}","severity_levels": "{event.properties.severity_levels}","logs_url": "{project.url}/logs?{event.properties.logs_url_params}",- "alert_url": "{project.url}/logs/alerts/{event.properties.alert_id}",+ "alert_url": _ALERT_URL,}_BROKEN_ERRORED_BASE_DATA: dict[str, str] = {@@ -30,32 +45,35 @@ _BROKEN_ERRORED_BASE_DATA: dict[str, str] = {"consecutive_failures": "{event.properties.consecutive_failures}","service_names": "{event.properties.service_names}","severity_levels": "{event.properties.severity_levels}",- "alert_url": "{project.url}/logs/alerts/{event.properties.alert_id}",+ "alert_url": _ALERT_URL,}-EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {- "firing": EventKindSpec(- event_id="$logs_alert_firing",- display_kind="firing",- header="🔴 Log alert '{event.properties.alert_name}' is firing",- details=(- (- "Threshold breached",- "{event.properties.result_count} logs in {event.properties.window_minutes}m "- "(threshold: {event.properties.threshold_operator} {event.properties.threshold_count})",- ),+_FIRING = EventKindSpec(+ event_id="$logs_alert_firing",+ display_kind="firing",+ header="🔴 Log alert '{event.properties.alert_name}' is firing",+ details=(+ (+ "Threshold breached",+ "{event.properties.result_count} logs in {event.properties.window_minutes}m "+ "(threshold: {event.properties.threshold_operator} {event.properties.threshold_count})",),- primary_action_url="{project.url}/logs?{event.properties.logs_url_params}",- primary_action_label="View logs",- webhook_body={- "id": "{event.uuid}",- "type": "logs_alert.firing",- "timestamp": "{event.properties.triggered_at}",- "data": _FIRE_RESOLVE_DATA,- },- product_label=_PRODUCT_LABEL,),+ primary_action_url="{project.url}/logs?{event.properties.logs_url_params}",+ primary_action_label="View logs",+ webhook_body={+ "id": "{event.uuid}",+ "type": "logs_alert.firing",+ "timestamp": "{event.properties.triggered_at}",+ "data": _FIRE_RESOLVE_DATA,+ },+ product_label=_PRODUCT_LABEL,+)+++EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {+ "firing": _FIRING,"resolved": EventKindSpec(event_id="$logs_alert_resolved",display_kind="resolved",@@ -85,7 +103,7 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {("Reason", "{event.properties.consecutive_failures} consecutive check failures."),("Last error", "{event.properties.last_error_message}"),),- primary_action_url="{project.url}/logs/alerts/{event.properties.alert_id}",+ primary_action_url=_ALERT_URL,primary_action_label="View alert",webhook_body={"id": "{event.uuid}",@@ -106,7 +124,7 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {("Reason", "{event.properties.error_message}"),("Failure count", "{event.properties.consecutive_failures}"),),- primary_action_url="{project.url}/logs/alerts/{event.properties.alert_id}",+ primary_action_url=_ALERT_URL,primary_action_label="View alert",webhook_body={"id": "{event.uuid}",@@ -119,6 +137,27 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {},product_label=_PRODUCT_LABEL,),+ # The edge kinds follow every move into and out of FIRING, whatever cooldown decided. An incident+ # manager needs a resolve for every trigger, or the incident it opened stays open.+ "incident_opened": replace(+ _FIRING,+ event_id=LOGS_ALERT_INCIDENT_OPENED_EVENT,+ display_kind="incident opened",+ webhook_body={},+ additional_actions=(AlertDestinationAction(url=_ALERT_URL, label="View alert"),),+ incident_action=IncidentAction.TRIGGER,+ ),+ "incident_closed": EventKindSpec(+ event_id=LOGS_ALERT_INCIDENT_CLOSED_EVENT,+ display_kind="incident closed",+ header="Log alert '{event.properties.alert_name}' stopped firing",+ details=(("Reason", "{event.properties.reason}"),),+ primary_action_url=_ALERT_URL,+ primary_action_label="View alert",+ webhook_body={},+ product_label=_PRODUCT_LABEL,+ incident_action=IncidentAction.RESOLVE,+ ),}EVENT_KINDS: tuple[EventKind, ...] = tuple(EVENT_KIND_CONFIG.keys())diff --git a/products/logs/backend/alert_state_machine.py b/products/logs/backend/alert_state_machine.pyindex 178224a8cbc6..5af8011ea523 100644--- a/products/logs/backend/alert_state_machine.py+++ b/products/logs/backend/alert_state_machine.py@@ -18,9 +18,11 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom datetime import datetime, timedelta+from enum import StrEnumfrom typing import TYPE_CHECKINGfrom products.alerts_platform.backend.facade.lifecycle import (+ FIRING_STATES,LOGS_ALERT_POLICY,MAX_CONSECUTIVE_FAILURES,AlertCheckOutcome,@@ -50,6 +52,8 @@ __all__ = ["AlertState","CheckResult","ControlPlaneOutcome",+ "IncidentCloseReason",+ "IncidentEdge","InvalidTransition","NotificationAction","Outcome",@@ -61,6 +65,7 @@ __all__ = ["apply_unsnooze","apply_user_reset","evaluate_alert_check",+ "incident_edge",]@@ -85,6 +90,31 @@ class AlertSnapshot:recent_events_breached: tuple[bool, ...]+class IncidentEdge(StrEnum):+ OPENED = "opened"+ CLOSED = "closed"+++class IncidentCloseReason(StrEnum):+ RESOLVED = "resolved"+ BROKEN = "broken"+++def incident_edge(state_before: str, new_state: AlertState) -> IncidentEdge | None:+ """Whether a transition starts or ends a firing.++ Read from the states, not from the notification, because cooldown can suppress a notification+ while the state still moves. An incident manager needs a resolve for every trigger it received.+ """+ was_firing = state_before in FIRING_STATES+ is_firing = new_state in FIRING_STATES+ if is_firing and not was_firing:+ return IncidentEdge.OPENED+ if was_firing and not is_firing:+ return IncidentEdge.CLOSED+ return None++def evaluate_alert_check(snapshot: AlertSnapshot,check: CheckResult,diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 2c7bd3683337..8fccdf604b4a 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -33,6 +33,7 @@ from products.alerts.backend.facade.destinations import (build_alert_destination_config,configured_destination_template_ids,create_alert_destination_hog_functions,+ destination_handles_event_kind,destination_template_id,list_alert_destination_groups,redact_destination_data,@@ -44,6 +45,8 @@ from products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertDestinationValidationError,DestinationType,+ PagerDutyRegion,+ PagerDutySeverity,)from products.alerts_platform.backend.facade.scheduling import validate_and_normalize_schedule_restrictionfrom products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionField@@ -179,6 +182,20 @@ class LogsAlertDestinationConfigSerializer(LogsAlertDestinationResponseSerializerequired=False,help_text="Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret.",)+ pagerduty_routing_key = serializers.CharField(+ required=False,+ help_text="PagerDuty integration key reduced to its last four characters.",+ )+ pagerduty_severity = serializers.ChoiceField(+ choices=[choice.value for choice in PagerDutySeverity],+ required=False,+ help_text="Severity of the PagerDuty incident.",+ )+ pagerduty_region = serializers.ChoiceField(+ choices=[choice.value for choice in PagerDutyRegion],+ required=False,+ help_text="PagerDuty service region the events go to.",+ )class LogsAlertConfigurationSerializer(serializers.ModelSerializer):@@ -783,6 +800,23 @@ class LogsAlertCreateDestinationSerializer(serializers.Serializer):required=False,help_text="HTTPS endpoint to post to. Required for webhook and teams.",)+ pagerduty_routing_key = serializers.CharField(+ required=False,+ trim_whitespace=True,+ help_text="Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.",+ )+ pagerduty_severity = serializers.ChoiceField(+ choices=[choice.value for choice in PagerDutySeverity],+ required=False,+ default=PagerDutySeverity.CRITICAL.value,+ help_text="Severity PagerDuty records on the incident. Used when type=pagerduty.",+ )+ pagerduty_region = serializers.ChoiceField(+ choices=[choice.value for choice in PagerDutyRegion],+ required=False,+ default=PagerDutyRegion.US.value,+ help_text="PagerDuty service region of the account. Used when type=pagerduty.",+ )def validate(self, attrs: dict) -> dict:data = cast(AlertDestinationData, attrs)@@ -995,13 +1029,21 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):@extend_schema(request=LogsAlertCreateDestinationSerializer,responses={201: LogsAlertDestinationResponseSerializer},- description="Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.",+ description=(+ "Create a notification destination for this alert. One HogFunction is created per alert event kind "+ "(firing, resolved, ...) atomically. A PagerDuty destination gets the incident opened and incident closed "+ "kinds instead. They follow every start and end of a firing, cooldown included, so each incident it "+ "opens is resolved."+ ),)@action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["logs:write"])def create_destination(self, request: Request, *args: object, **kwargs: object) -> Response:serializer = LogsAlertCreateDestinationSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = cast(AlertDestinationData, serializer.validated_data)+ event_kinds = [+ kind for kind in EVENT_KINDS if destination_handles_event_kind(data["type"], EVENT_KIND_CONFIG[kind])+ ]with transaction.atomic():alert = self._get_locked_alert()@@ -1013,7 +1055,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):data=data,slack_context_elements=LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,)- for kind in EVENT_KINDS+ for kind in event_kinds]try:hog_function_ids = create_alert_destination_hog_functions(@@ -1029,7 +1071,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):report_user_action(request.user,"logs alert destination created",- {"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(EVENT_KINDS)},+ {"alert_id": str(alert.id), "type": data["type"], "event_kinds": event_kinds},request=request,)response = LogsAlertDestinationResponseSerializer({"hog_function_ids": list(hog_function_ids)})diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex e0571d964329..daa3168808c2 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -29,6 +29,7 @@ from posthog.sync import database_sync_to_async_poolfrom products.alerts.backend.facade.destinations import (alert_internal_event_delivered,+ configured_destination_template_ids,flush_alert_internal_events,produce_alert_internal_event,)@@ -43,6 +44,7 @@ from products.logs.backend.alert_check_query import (resolve_alert_date_to,rolling_check_lookback_minutes,)+from products.logs.backend.alert_destinations import LOGS_ALERT_INCIDENT_CLOSED_EVENT, LOGS_ALERT_INCIDENT_OPENED_EVENTfrom products.logs.backend.alert_error_classifier import (AlertErrorCode,classify as classify_alert_error,@@ -57,9 +59,12 @@ from products.logs.backend.alert_state_machine import (AlertState,CheckResult,ControlPlaneOutcome,+ IncidentCloseReason,+ IncidentEdge,NotificationAction,apply_outcome,evaluate_alert_check,+ incident_edge,)from products.logs.backend.alert_utils import (advance_next_check_at,@@ -285,17 +290,29 @@ class _DispatchedAlert:`produce_result` is the pending Kafka delivery for this alert'snotification (None when no notification was attempted or the enqueue itself- failed). `produce()` only buffers locally, so `notification_failed` isn't- final until `_resolve_notification_deliveries` flushes the producer and- folds delivery failures in — persisting before that point would record- "notified" for a message that may never reach the broker.+ failed). `incident_produce_result` is the same for the incident edge event,+ and a failed delivery of either rolls the state back. `produce()` only+ buffers locally, so `notification_failed` isn't final until+ `_resolve_notification_deliveries` flushes the producer and folds delivery+ failures in — persisting before that point would record "notified" for a+ message that may never reach the broker.++ Delivery is therefore at least once. For an alert with both an incident+ destination and a message destination, a lost incident event also resends a+ notification the broker already took. Retrying only the incident event would+ need the pending edge stored on the alert row."""evaluation: _AlertEvaluationnotification_failed: boolproduce_result: ProduceResult | None = None+ incident_produce_result: ProduceResult | None = Nonesuppressed_by_quiet_hours: bool = False+ @property+ def produced(self) -> bool:+ return self.produce_result is not None or self.incident_produce_result is not None+@propertydef committed_outcome(self) -> AlertCheckOutcome:if self.notification_failed:@@ -483,11 +500,24 @@ def _mark_alert_broken_for_bad_config(alert_id: str, reason: str) -> None:invalid and can never succeed. Runs in the same sync DB pool as discovery —each call is its own short transaction so a failure on one row doesn'troll back the others.++ A firing alert with an incident destination closes its incident first. Discovery skips BROKEN+ alerts, so the close must be delivered before the transition commits. When it is not, the alert+ keeps its state, and the next discovery cycle finds the same bad config and tries again."""try:+ state_seen = LogsAlertConfiguration.objects.values_list("state", flat=True).get(pk=alert_id)+ if state_seen == LogsAlertConfiguration.State.BROKEN:+ return+ if incident_edge(state_seen, AlertState.BROKEN) == IncidentEdge.CLOSED:+ alert_for_close = LogsAlertConfiguration.objects.get(pk=alert_id)+ if _has_incident_destination(alert_for_close) and not _close_incident_for_bad_config(alert_for_close):+ logger.warning("Deferring BROKEN until the incident close is delivered", alert_id=alert_id)+ returnwith transaction.atomic():alert = LogsAlertConfiguration.objects.select_for_update().get(pk=alert_id)- if alert.state == LogsAlertConfiguration.State.BROKEN:+ if alert.state != state_seen:+ # The state moved after the close decision, so decide again on the next cycle.returnstate_before = alert.stateoutcome = ControlPlaneOutcome(@@ -514,6 +544,20 @@ def _mark_alert_broken_for_bad_config(alert_id: str, reason: str) -> None:capture_exception(e)+def _close_incident_for_bad_config(alert: LogsAlertConfiguration) -> bool:+ """Send the close for an alert about to break on bad config. Return whether the broker took it."""+ produce_result = _emit_incident_closed_event(alert, IncidentCloseReason.BROKEN, datetime.now(UTC))+ if produce_result is None:+ return False+ flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)+ return alert_internal_event_delivered(+ produce_result,+ team_id=alert.team_id,+ alert_id=str(alert.id),+ event_name=LOGS_ALERT_INCIDENT_CLOSED_EVENT,+ )++def _cohort_manifests_from_alerts(rows: Sequence[dict],*,@@ -748,7 +792,7 @@ async def evaluate_cohort_batch_activity(input: EvaluateCohortBatchInput) -> Eva# back and get retried next cycle. flush() blocks, so run it off# the event loop, and only when something was actually produced,# sparing quiet cohorts the thread hop.- if any(d.produce_result is not None for d in dispatched):+ if any(d.produced for d in dispatched):dispatched = await asyncio.to_thread(_resolve_notification_deliveries, dispatched)for dispatched_alert in dispatched:@@ -1070,8 +1114,53 @@ def _dispatch_for_alert(evaluation: _AlertEvaluation, now: datetime) -> _Dispatcdate_from=evaluation.date_from,date_to=evaluation.date_to,)- enqueue_failed = evaluation.outcome.notification != NotificationAction.NONE and produce_result is None- return _DispatchedAlert(evaluation=evaluation, notification_failed=enqueue_failed, produce_result=produce_result)+ edge = incident_edge(evaluation.state_before, evaluation.outcome.new_state)+ incident_expected = edge is not None and _has_incident_destination(evaluation.alert)+ incident_produce_result = _dispatch_incident_edge(edge, evaluation, now) if edge and incident_expected else None+ enqueue_failed = (evaluation.outcome.notification != NotificationAction.NONE and produce_result is None) or (+ incident_expected and incident_produce_result is None+ )+ return _DispatchedAlert(+ evaluation=evaluation,+ notification_failed=enqueue_failed,+ produce_result=produce_result,+ incident_produce_result=incident_produce_result,+ )+++def _has_incident_destination(alert: LogsAlertConfiguration) -> bool:+ """Whether a destination of this alert follows the incident kinds.++ An alert without one sends no incident events, so a lost incident event can never roll back a+ notification its Slack, Teams or webhook destinations already received.+ """+ return bool(+ configured_destination_template_ids(+ team_id=alert.team_id,+ alert_id=str(alert.id),+ allowed_event_ids=(LOGS_ALERT_INCIDENT_OPENED_EVENT, LOGS_ALERT_INCIDENT_CLOSED_EVENT),+ )+ )+++def _dispatch_incident_edge(edge: IncidentEdge, evaluation: _AlertEvaluation, now: datetime) -> ProduceResult | None:+ alert = evaluation.alert+ if edge == IncidentEdge.OPENED:+ return _emit_alert_event(+ alert,+ LOGS_ALERT_INCIDENT_OPENED_EVENT,+ evaluation.check_result,+ now,+ date_from=evaluation.date_from,+ date_to=evaluation.date_to,+ )+ else:+ reason = (+ IncidentCloseReason.BROKEN+ if evaluation.outcome.new_state == AlertState.BROKEN+ else IncidentCloseReason.RESOLVED+ )+ return _emit_incident_closed_event(alert, reason, now)def _resolve_notification_deliveries(dispatched: list[_DispatchedAlert]) -> list[_DispatchedAlert]:@@ -1088,25 +1177,30 @@ def _resolve_notification_deliveries(dispatched: list[_DispatchedAlert]) -> listwith rolled-back state beats no save at all — the cohort erroring out herewould skip the save entirely."""- if all(d.produce_result is None for d in dispatched):+ if not any(d.produced for d in dispatched):return dispatchedflush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)resolved: list[_DispatchedAlert] = []for d in dispatched:- if d.produce_result is None:- resolved.append(d)- continue- if alert_internal_event_delivered(- d.produce_result,- team_id=d.evaluation.alert.team_id,- alert_id=str(d.evaluation.alert.id),- event_name=d.evaluation.outcome.notification.value,- ):- resolved.append(d)- else:- resolved.append(dataclasses.replace(d, notification_failed=True))+ alert = d.evaluation.alert+ edge = incident_edge(d.evaluation.state_before, d.evaluation.outcome.new_state)+ incident_event = (+ LOGS_ALERT_INCIDENT_OPENED_EVENT if edge == IncidentEdge.OPENED else LOGS_ALERT_INCIDENT_CLOSED_EVENT+ )+ deliveries = (+ (d.produce_result, d.evaluation.outcome.notification.value),+ (d.incident_produce_result, incident_event),+ )+ delivered = all(+ alert_internal_event_delivered(+ produce_result, team_id=alert.team_id, alert_id=str(alert.id), event_name=event_name+ )+ for produce_result, event_name in deliveries+ if produce_result is not None+ )+ resolved.append(d if delivered else dataclasses.replace(d, notification_failed=True))return resolved@@ -1544,6 +1638,21 @@ def _emit_auto_disabled_event(return _produce_alert_internal_event(alert, "$logs_alert_auto_disabled", properties, now)+def _emit_incident_closed_event(+ alert: LogsAlertConfiguration,+ reason: IncidentCloseReason,+ now: datetime,+) -> ProduceResult | None:+ properties = {+ "alert_id": str(alert.id),+ "alert_name": alert.name,+ "team_id": alert.team_id,+ "reason": reason.value,+ "triggered_at": now.isoformat(),+ }+ return _produce_alert_internal_event(alert, LOGS_ALERT_INCIDENT_CLOSED_EVENT, properties, now)++def _emit_alert_errored_event(alert: LogsAlertConfiguration,outcome: AlertCheckOutcome,diff --git a/products/logs/backend/test/test_alert_destinations.py b/products/logs/backend/test/test_alert_destinations.pyindex 17e4df450d77..fe4fbffd3bfa 100644--- a/products/logs/backend/test/test_alert_destinations.py+++ b/products/logs/backend/test/test_alert_destinations.py@@ -57,7 +57,8 @@ class TestDestinationValidation(SimpleTestCase):assert error.exception.field == "type"assert error.exception.message == (- "Choose a supported destination type: Slack (slack), Webhook (webhook), Microsoft Teams (teams)."+ "Choose a supported destination type: Slack (slack), Webhook (webhook), Microsoft Teams (teams), "+ "PagerDuty (pagerduty).")@@ -78,8 +79,11 @@ def destination_inputs(kind: EventKind, data: AlertDestinationData) -> dict[str,return config.payload["inputs"]+MESSAGE_KINDS = [kind for kind in EVENT_KINDS if EVENT_KIND_CONFIG[kind].incident_action is None]++class TestRenderedDestinationContent(SimpleTestCase):- @parameterized.expand([(kind,) for kind in EVENT_KINDS])+ @parameterized.expand([(kind,) for kind in MESSAGE_KINDS])def test_slack_body_puts_every_detail_on_its_own_line(self, kind: EventKind) -> None:spec = EVENT_KIND_CONFIG[kind]blocks = destination_inputs(kind, SLACK_DATA)["blocks"]["value"]@@ -90,7 +94,7 @@ class TestRenderedDestinationContent(SimpleTestCase):# Slack mrkdwn bolds with one asterisk, so a `**` pair would render as literal text.assert "**" not in body- @parameterized.expand([(kind,) for kind in EVENT_KINDS])+ @parameterized.expand([(kind,) for kind in MESSAGE_KINDS])def test_teams_text_is_adaptive_card_markdown(self, kind: EventKind) -> None:spec = EVENT_KIND_CONFIG[kind]text = destination_inputs(kind, TEAMS_DATA)["text"]["value"]diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex ffdfc6aca7ba..88d39d53a98f 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -11,7 +11,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.cdp.templates.fixtures import template_slack+from posthog.cdp.templates.fixtures import template_pagerduty, template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.cdp.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teamsfrom posthog.clickhouse.client import sync_execute@@ -24,12 +24,13 @@ from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCoufrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEventfrom products.logs.backend.presentation.views.alerts_api import (ALLOWED_WINDOW_MINUTES,- LOGS_ALERT_EVENT_IDS,MAX_ALERTS_PER_TEAM,MAX_DESTINATION_IDS_PER_DELETE_REQUEST,LogsAlertViewSet,)+PAGERDUTY_ROUTING_KEY = "0123456789abcdef0123456789abcdef"+def _make_log_row(*, team_id: int, service: str, uuid: str, ts: datetime, body: str) -> dict:return {@@ -815,6 +816,7 @@ class TestLogsAlertAPI(APIBaseTest):# which looks up a HogFunctionTemplate by template_id.sync_template_to_db(template_slack)sync_template_to_db(template_microsoft_teams)+ sync_template_to_db(template_pagerduty)HogFunctionTemplate.objects.get_or_create(template_id="template-webhook",defaults={@@ -934,6 +936,41 @@ class TestLogsAlertAPI(APIBaseTest):assert text_value.startswith("**")assert "[View logs](" in text_value or "[View alert](" in text_value+ def test_create_pagerduty_destination_pairs_a_trigger_with_a_resolve_and_hides_the_key(self):+ self._sync_destination_templates()+ created = self._create_via_api()+ response = self.client.post(+ self._destinations_url(created["id"]),+ {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY, "pagerduty_severity": "warning"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ ids = response.json()["hog_function_ids"]+ assert len(ids) == 2++ action_by_event = {}+ for hf in HogFunction.objects.filter(id__in=ids):+ assert hf.template_id == "template-pagerduty"+ # The key is a secret input, so it lives in the encrypted column and never in `inputs`.+ assert "routing_key" not in (hf.inputs or {})+ assert (hf.encrypted_inputs or {})["routing_key"]["value"] == PAGERDUTY_ROUTING_KEY+ inputs = hf.inputs or {}+ assert inputs["dedup_key"]["value"] == "posthog-alert-{event.properties.alert_id}"+ assert inputs["severity"]["value"] == "warning"+ assert inputs["region"]["value"] == "us"+ action_by_event[(hf.filters or {})["events"][0]["id"]] = inputs["event_action"]["value"]+ assert action_by_event == {"$logs_alert_incident_opened": "trigger", "$logs_alert_incident_closed": "resolve"}++ detail = self.client.get(f"{self.base_url}{created['id']}/")+ assert detail.status_code == status.HTTP_200_OK+ destinations = detail.json()["destinations"]+ assert len(destinations) == 1+ assert set(destinations[0]["hog_function_ids"]) == set(ids)+ assert destinations[0]["type"] == "pagerduty"+ assert destinations[0]["pagerduty_routing_key"] == "••••" + PAGERDUTY_ROUTING_KEY[-4:]+ assert destinations[0]["pagerduty_severity"] == "warning"+ assert PAGERDUTY_ROUTING_KEY not in detail.content.decode()+def test_reading_an_alert_groups_its_destinations_and_strips_webhook_credentials(self) -> None:self._sync_destination_templates()created = self._create_via_api()@@ -1020,6 +1057,12 @@ class TestLogsAlertAPI(APIBaseTest):("webhook_invalid_url", {"type": "webhook", "webhook_url": "not-a-url"}),("teams_missing_url", {"type": "teams"}),("teams_invalid_url", {"type": "teams", "webhook_url": "not-a-url"}),+ ("pagerduty_missing_key", {"type": "pagerduty"}),+ ("pagerduty_malformed_key", {"type": "pagerduty", "pagerduty_routing_key": "not-a-key"}),+ (+ "pagerduty_unknown_severity",+ {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY, "pagerduty_severity": "urgent"},+ ),])def test_create_destination_rejects_invalid_payloads(self, _name: str, payload: dict) -> None:@@ -1136,6 +1179,11 @@ class TestLogsAlertAPI(APIBaseTest):{"type": "webhook", "webhook_url": "https://example.com/a"},{"type": "webhook", "webhook_url": "https://example.com/b"},),+ (+ "two_pagerduty_keys",+ {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY},+ {"type": "pagerduty", "pagerduty_routing_key": "b" * 32},+ ),])def test_delete_destination_removes_only_the_named_destination(@@ -1188,6 +1236,7 @@ class TestLogsAlertAPI(APIBaseTest):{"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C111", "slack_channel_name": "eng"},),("webhook_url", {"type": "webhook", "webhook_url": "https://example.com/hook"}),+ ("pagerduty_key", {"type": "pagerduty", "pagerduty_routing_key": PAGERDUTY_ROUTING_KEY}),])def test_create_destination_rejects_a_duplicate_of_an_existing_destination(self, _name: str, payload: dict):@@ -1200,7 +1249,7 @@ class TestLogsAlertAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert response.json()["detail"] == "This destination is already configured for this alert."assert HogFunction.objects.filter(id__in=ids, deleted=False, enabled=True).count() == len(ids)- assert HogFunction.objects.filter(team=self.team, deleted=False).count() == len(LOGS_ALERT_EVENT_IDS)+ assert HogFunction.objects.filter(team=self.team, deleted=False).count() == len(ids)def test_create_destination_locks_the_alert_row_before_the_duplicate_check(self):self._sync_destination_templates()diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex a2134b3b88f6..5e7697e533ee 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -22,6 +22,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.errors import QueryErrorCategoryfrom posthog.slo.types import SloOperation, SloOutcome+from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.logs.backend.alert_check_query import AlertCheckQuery, BatchedBucketedResult, BucketedCountfrom products.logs.backend.alert_signal_emitter import AlertSignalAction, NotifiedAlertfrom products.logs.backend.alert_state_machine import AlertCheckOutcome, AlertState, CheckResult, NotificationAction@@ -69,6 +70,26 @@ def _evaluate_and_save_one(stats["errored"] += 1+def _add_incident_destination(alert: LogsAlertConfiguration) -> None:+ HogFunction.objects.create(+ team_id=alert.team_id,+ type="internal_destination",+ name="PagerDuty",+ template_id="template-pagerduty",+ hog="return event",+ enabled=True,+ filters={+ "source": "internal-events",+ "events": [{"id": "$logs_alert_incident_closed", "type": "events"}],+ "properties": [{"key": "alert_id", "value": str(alert.id), "operator": "exact", "type": "event"}],+ },+ )+++def _produced_events(mock_produce: MagicMock) -> list[str]:+ return [c.kwargs["event_name"] for c in mock_produce.call_args_list if "event_name" in c.kwargs]++def _make_stats() -> dict[str, int]:return {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}@@ -286,20 +307,27 @@ class TestResolveNotificationDeliveries(unittest.TestCase):@parameterized.expand([- ("delivered", None, False),- ("delivery_error", Exception("delivery failed"), True),- ("still_pending_after_flush", TimeoutError("undelivered"), True),+ (f"{outcome}_{field}", field, get_side_effect, expect_failed)+ for outcome, get_side_effect, expect_failed in (+ ("delivered", None, False),+ ("delivery_error", Exception("delivery failed"), True),+ ("still_pending_after_flush", TimeoutError("undelivered"), True),+ )+ for field in ("produce_result", "incident_produce_result")])@patch("products.logs.backend.temporal.activities.flush_alert_internal_events")- def test_folds_delivery_outcome_into_notification_failed(self, _name, get_side_effect, expect_failed, mock_flush):+ def test_folds_delivery_outcome_into_notification_failed(+ self, _name, field, get_side_effect, expect_failed, mock_flush+ ):from products.logs.backend.temporal.activities import _resolve_notification_deliveriesresult = MagicMock()if get_side_effect is not None:result.get.side_effect = get_side_effect+ dispatched = dataclasses.replace(self._dispatched(None), **{field: result})- resolved = _resolve_notification_deliveries([self._dispatched(result)])+ resolved = _resolve_notification_deliveries([dispatched])assert resolved[0].notification_failed is expect_failedmock_flush.assert_called_once()@@ -698,12 +726,22 @@ class TestEvaluateSingleAlert(APIBaseTest):defaults.update(kwargs)return LogsAlertConfiguration.objects.create(**defaults)+ @parameterized.expand(+ [+ ("without_incident_destination", False, ["$logs_alert_firing"]),+ ("with_incident_destination", True, ["$logs_alert_firing", "$logs_alert_incident_opened"]),+ ]+ )@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")@patch("products.logs.backend.temporal.activities.produce_alert_internal_event")- def test_threshold_breached_transitions_to_firing(self, mock_produce, mock_query_cls):+ def test_threshold_breached_transitions_to_firing(+ self, _name, has_incident_destination, expected_events, mock_produce, mock_query_cls+ ):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()+ if has_incident_destination:+ _add_incident_destination(alert)stats = {"checked": 0, "fired": 0, "resolved": 0, "errored": 0}now = datetime(2025, 1, 1, 0, 1, 0, tzinfo=UTC)@@ -713,8 +751,7 @@ class TestEvaluateSingleAlert(APIBaseTest):assert alert.state == LogsAlertConfiguration.State.FIRINGassert stats["checked"] == 1assert stats["fired"] == 1- mock_produce.assert_called_once()- assert mock_produce.call_args.kwargs["event_name"] == "$logs_alert_firing"+ assert _produced_events(mock_produce) == expected_events@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.AlertCheckQuery")@@ -1068,6 +1105,7 @@ class TestEvaluateSingleAlert(APIBaseTest):cooldown_minutes=60,last_notified_at=datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC),)+ _add_incident_destination(alert)# Create an event row so get_recent_breaches has dataLogsAlertEvent.objects.create(alert=alert,@@ -1083,8 +1121,9 @@ class TestEvaluateSingleAlert(APIBaseTest):alert.refresh_from_db()# State transitions to NOT_FIRING regardless of cooldownassert alert.state == LogsAlertConfiguration.State.NOT_FIRING- # But notification is suppressed by cooldown- mock_produce.assert_not_called()+ # Cooldown suppresses the resolved notification, but never the incident close.+ assert _produced_events(mock_produce) == ["$logs_alert_incident_closed"]+ assert mock_produce.call_args.kwargs["properties"]["reason"] == "resolved"@parameterized.expand([@@ -1096,6 +1135,14 @@ class TestEvaluateSingleAlert(APIBaseTest):5,1,),+ (+ "hits_threshold_while_firing",+ 4,+ LogsAlertConfiguration.State.FIRING,+ LogsAlertConfiguration.State.BROKEN,+ 5,+ 1,+ ),("below_threshold",3,@@ -1133,6 +1180,7 @@ class TestEvaluateSingleAlert(APIBaseTest):consecutive_failures=initial_failures,state=initial_state,)+ _add_incident_destination(alert)mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("Code: 160. DB::Exception: Estimated query execution time is too long")@@ -1156,6 +1204,12 @@ class TestEvaluateSingleAlert(APIBaseTest):# Auto-disabled event surfaces the classified user message, never the raw CH exception.assert props["last_error_message"] == "Query is too expensive. Try narrower filters or a shorter window."assert "DB::Exception" not in props["last_error_message"]+ closed_reasons = [+ c.kwargs["properties"]["reason"]+ for c in mock_produce.call_args_list+ if c.kwargs.get("event_name") == "$logs_alert_incident_closed"+ ]+ assert closed_reasons == (["broken"] if initial_state == LogsAlertConfiguration.State.FIRING else [])@time_machine.travel("2025-01-01T00:01:00Z", tick=False)@patch("products.logs.backend.temporal.activities.increment_state_transition")@@ -2103,8 +2157,9 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):assert len(result.manifests) == 1assert len(result.manifests[0].alert_ids) == 2+ @parameterized.expand([("close_delivered", True), ("close_lost", False)])@time_machine.travel("2026-05-05T10:00:00Z", tick=False)- def test_transitions_alert_with_broken_filter_config_to_broken(self):+ def test_transitions_alert_with_broken_filter_config_to_broken(self, _name, close_delivered):from products.logs.backend.temporal.activities import DiscoverCohortsInput, discover_cohorts_activityhealthy = LogsAlertConfiguration.objects.create(@@ -2129,22 +2184,35 @@ class TestDiscoverCohortsActivity(NonAtomicBaseTest):filters={"filterGroup": [{"type": "AND", "values": []}]},enabled=True,next_check_at=None,+ state=LogsAlertConfiguration.State.FIRING,)+ _add_incident_destination(broken)- result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))+ with patch("products.logs.backend.temporal.activities.produce_alert_internal_event") as mock_produce:+ if not close_delivered:+ mock_produce.return_value.get.side_effect = TimeoutError("undelivered")+ result = asyncio.run(discover_cohorts_activity(DiscoverCohortsInput()))manifest_alert_ids = {aid for m in result.manifests for aid in m.alert_ids}assert str(healthy.id) in manifest_alert_idsassert str(broken.id) not in manifest_alert_ids+ assert mock_produce.call_args.kwargs["properties"]["reason"] == "broken"++ from products.logs.backend.models import LogsAlertEventbroken.refresh_from_db()+ if not close_delivered:+ # Discovery skips BROKEN alerts, so the alert stays firing until a later cycle delivers the close.+ assert broken.state == LogsAlertConfiguration.State.FIRING+ assert not LogsAlertEvent.objects.filter(alert=broken, kind=LogsAlertEvent.Kind.BROKEN_CONFIG).exists()+ returnassert broken.state == LogsAlertConfiguration.State.BROKEN- from products.logs.backend.models import LogsAlertEvent-event = LogsAlertEvent.objects.get(alert=broken, kind=LogsAlertEvent.Kind.BROKEN_CONFIG)assert event.state_after == LogsAlertConfiguration.State.BROKENassert event.error_message is not None and "filterGroup" in event.error_message+ assert _produced_events(mock_produce) == ["$logs_alert_incident_closed"]+ assert mock_produce.call_args.kwargs["properties"]["alert_id"] == str(broken.id)class TestCohortFromManifest(unittest.TestCase):diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsxindex 088b5ac1ee29..0a1671fb3e4e 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx@@ -20,11 +20,12 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'import { urls } from 'scenes/urls'import IconMicrosoftTeams from 'public/services/microsoft-teams.png'+import IconPagerDuty from 'public/services/pagerduty.png'import IconSlack from 'public/services/slack.png'import IconWebhook from 'public/services/webhook.svg'import {- NotificationDestinationTypeEnumApi,+ LogsAlertDestinationTypeEnumApi,LogsAlertConfigurationApi,LogsAlertConfigurationStateEnumApi,LogsAlertConfigurationThresholdOperatorEnumApi,@@ -36,9 +37,10 @@ import { LogsAlertStateTimeline } from './LogsAlertStateTimeline'import { SNOOZE_DURATIONS } from './logsAlertUtils'const DESTINATION_TAGS = [- { type: NotificationDestinationTypeEnumApi.Slack, label: 'Slack', icon: IconSlack },- { type: NotificationDestinationTypeEnumApi.Webhook, label: 'Webhook', icon: IconWebhook },- { type: NotificationDestinationTypeEnumApi.Teams, label: 'Teams', icon: IconMicrosoftTeams },+ { type: LogsAlertDestinationTypeEnumApi.Slack, label: 'Slack', icon: IconSlack },+ { type: LogsAlertDestinationTypeEnumApi.Webhook, label: 'Webhook', icon: IconWebhook },+ { type: LogsAlertDestinationTypeEnumApi.Teams, label: 'Teams', icon: IconMicrosoftTeams },+ { type: LogsAlertDestinationTypeEnumApi.Pagerduty, label: 'PagerDuty', icon: IconPagerDuty },] as constfunction formatThreshold(alert: LogsAlertConfigurationApi): string {@@ -49,7 +51,7 @@ function formatThreshold(alert: LogsAlertConfigurationApi): string {export function LogsAlertDestinationTags({types,}: {- types: readonly NotificationDestinationTypeEnumApi[]+ types: readonly LogsAlertDestinationTypeEnumApi[]}): JSX.Element {return (<div className="flex gap-1">diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex ba9fa8ba02e1..3540ffdf5175 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -504,14 +504,16 @@ export interface LogsAlertStateIntervalApi {* * `slack` - slack* * `webhook` - webhook* * `teams` - teams+ * * `pagerduty` - pagerduty*/-export type NotificationDestinationTypeEnumApi =- (typeof NotificationDestinationTypeEnumApi)[keyof typeof NotificationDestinationTypeEnumApi]+export type LogsAlertDestinationTypeEnumApi =+ (typeof LogsAlertDestinationTypeEnumApi)[keyof typeof LogsAlertDestinationTypeEnumApi]-export const NotificationDestinationTypeEnumApi = {+export const LogsAlertDestinationTypeEnumApi = {Slack: 'slack',Webhook: 'webhook',Teams: 'teams',+ Pagerduty: 'pagerduty',} as const/**@@ -655,7 +657,7 @@ export interface LogsAlertConfigurationApi {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types: readonly NotificationDestinationTypeEnumApi[]+ readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullable@@ -680,20 +682,61 @@ export interface PaginatedLogsAlertConfigurationListApi {results: LogsAlertConfigurationApi[]}+/**+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info+ */+export type PagerDutySeverityEnumApi = (typeof PagerDutySeverityEnumApi)[keyof typeof PagerDutySeverityEnumApi]++export const PagerDutySeverityEnumApi = {+ Critical: 'critical',+ Error: 'error',+ Warning: 'warning',+ Info: 'info',+} as const++/**+ * * `us` - us+ * * `eu` - eu+ */+export type PagerDutyRegionEnumApi = (typeof PagerDutyRegionEnumApi)[keyof typeof PagerDutyRegionEnumApi]++export const PagerDutyRegionEnumApi = {+ Us: 'us',+ Eu: 'eu',+} as const+export interface LogsAlertDestinationConfigApi {hog_function_ids: string[]/** Notification destination type.** * `slack` - slack* * `webhook` - webhook- * * `teams` - teams */- type: NotificationDestinationTypeEnumApi+ * * `teams` - teams+ * * `pagerduty` - pagerduty */+ type: LogsAlertDestinationTypeEnumApi/** Whether every HogFunction in the group is enabled, so the destination notifies for all alert event kinds. This is the stored setting: a destination PostHog stopped delivering to after repeated failures still reads as true. */enabled: booleanslack_workspace_id?: numberslack_channel_id?: string/** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */webhook_url?: string+ /** PagerDuty integration key reduced to its last four characters. */+ pagerduty_routing_key?: string+ /** Severity of the PagerDuty incident.+ *+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info */+ pagerduty_severity?: PagerDutySeverityEnumApi+ /** PagerDuty service region the events go to.+ *+ * * `us` - us+ * * `eu` - eu */+ pagerduty_region?: PagerDutyRegionEnumApi}/**@@ -784,7 +827,7 @@ export interface LogsAlertConfigurationDetailApi {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types: readonly NotificationDestinationTypeEnumApi[]+ readonly destination_types: readonly LogsAlertDestinationTypeEnumApi[]/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullable@@ -886,7 +929,7 @@ export interface PatchedLogsAlertConfigurationApi {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline?: readonly LogsAlertStateIntervalApi[]/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types?: readonly NotificationDestinationTypeEnumApi[]+ readonly destination_types?: readonly LogsAlertDestinationTypeEnumApi[]/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullable@@ -907,8 +950,9 @@ export interface LogsAlertCreateDestinationApi {** * `slack` - slack* * `webhook` - webhook- * * `teams` - teams */- type: NotificationDestinationTypeEnumApi+ * * `teams` - teams+ * * `pagerduty` - pagerduty */+ type: LogsAlertDestinationTypeEnumApi/** Integration ID for the Slack workspace. Required when type=slack. */slack_workspace_id?: number/** Slack channel ID. Required when type=slack. */@@ -917,6 +961,20 @@ export interface LogsAlertCreateDestinationApi {slack_channel_name?: string/** HTTPS endpoint to post to. Required for webhook and teams. */webhook_url?: string+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */+ pagerduty_routing_key?: string+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.+ *+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info */+ pagerduty_severity?: PagerDutySeverityEnumApi+ /** PagerDuty service region of the account. Used when type=pagerduty.+ *+ * * `us` - us+ * * `eu` - eu */+ pagerduty_region?: PagerDutyRegionEnumApi}export interface LogsAlertDestinationResponseApi {diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex 0967de76997f..a4867e6cc4d3 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -252,7 +252,7 @@ export const getLogsAlertsDestinationsCreateUrl = (projectId: string, id: string}/**- * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.+ * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically. A PagerDuty destination gets the incident opened and incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each incident it opens is resolved.*/export const logsAlertsDestinationsCreate = async (projectId: string,diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 407fe59d2128..468bdbfc1f89 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -418,13 +418,18 @@ export const LogsAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({})/**- * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.+ * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically. A PagerDuty destination gets the incident opened and incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each incident it opens is resolved.*/+export const logsAlertsDestinationsCreateBodyPagerdutySeverityDefault = `critical`+export const logsAlertsDestinationsCreateBodyPagerdutyRegionDefault = `us`+export const LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({type: zod- .enum(['slack', 'webhook', 'teams'])- .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')- .describe('Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'),+ .enum(['slack', 'webhook', 'teams', 'pagerduty'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `pagerduty` - pagerduty')+ .describe(+ 'Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `pagerduty` - pagerduty'+ ),slack_workspace_id: zod.number().optional()@@ -432,6 +437,22 @@ export const LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook and teams.'),+ pagerduty_routing_key: zod+ .string()+ .optional()+ .describe('Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.'),+ pagerduty_severity: zod+ .enum(['critical', 'error', 'warning', 'info'])+ .describe('\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info')+ .default(logsAlertsDestinationsCreateBodyPagerdutySeverityDefault)+ .describe(+ 'Severity PagerDuty records on the incident. Used when type=pagerduty.\n\n\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info'+ ),+ pagerduty_region: zod+ .enum(['us', 'eu'])+ .describe('\* `us` - us\n\* `eu` - eu')+ .default(logsAlertsDestinationsCreateBodyPagerdutyRegionDefault)+ .describe('PagerDuty service region of the account. Used when type=pagerduty.\n\n\* `us` - us\n\* `eu` - eu'),})/**diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex cd7dfbbcc9d9..0ea2efa41fab 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -67,14 +67,16 @@ tools:idempotent: falsetitle: Attach alert destinationdescription: >- Attach a Slack, webhook, or Microsoft Teams notification destination to a log alert. Without a destination- an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved,- broken, errored) atomically. The returned hog_function_ids identify the destination group.+ Attach a Slack, webhook, Microsoft Teams, or PagerDuty notification destination to a log alert. Without a+ destination an alert evaluates silently and never notifies. One HogFunction is created per event kind+ (firing, resolved, broken, errored) atomically. A PagerDuty destination gets the incident opened and+ incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each+ incident it opens is resolved. The returned hog_function_ids identify the destination group.param_overrides:type:description: >- Destination type. Use slack, webhook, or teams. Slack requires slack_workspace_id and- slack_channel_id. Webhook and teams require webhook_url.+ Destination type. Use slack, webhook, teams, or pagerduty. Slack requires slack_workspace_id and+ slack_channel_id. Webhook and teams require webhook_url. PagerDuty requires pagerduty_routing_key.slack_workspace_id:description: Slack workspace integration ID. Required when type is slack.slack_channel_id:@@ -83,6 +85,14 @@ tools:description: Optional Slack channel name used for display.webhook_url:description: Required when type is webhook or teams.+ pagerduty_routing_key:+ description: >+ The 32-character integration key of an Events API v2 integration on the PagerDuty service. Required+ when type is pagerduty.+ pagerduty_severity:+ description: Incident severity for PagerDuty. One of critical, error, warning, info. Defaults to critical.+ pagerduty_region:+ description: PagerDuty service region, us or eu. Defaults to us.response:include:- hog_function_idsdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 868cbf958c2d..634e4a8d5dac 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8768,7 +8768,7 @@}},"logs-alerts-destinations-create": {- "description": "Attach a Slack, webhook, or Microsoft Teams notification destination to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically. The returned hog_function_ids identify the destination group.",+ "description": "Attach a Slack, webhook, Microsoft Teams, or PagerDuty notification destination to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically. A PagerDuty destination gets the incident opened and incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each incident it opens is resolved. The returned hog_function_ids identify the destination group.","category": "Logs","feature": "logs","summary": "Attach alert destination",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8cd486f32a7a..79e4ed63f0a3 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9147,7 +9147,7 @@}},"logs-alerts-destinations-create": {- "description": "Attach a Slack, webhook, or Microsoft Teams notification destination to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically. The returned hog_function_ids identify the destination group.",+ "description": "Attach a Slack, webhook, Microsoft Teams, or PagerDuty notification destination to a log alert. Without a destination an alert evaluates silently and never notifies. One HogFunction is created per event kind (firing, resolved, broken, errored) atomically. A PagerDuty destination gets the incident opened and incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each incident it opens is resolved. The returned hog_function_ids identify the destination group.","category": "Logs","feature": "logs","summary": "Attach alert destination",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c2860951bc41..1bd90285d30e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -60235,6 +60235,22 @@ export namespace Schemas {enabled: boolean;}+ /**+ * * `slack` - slack+ * * `webhook` - webhook+ * * `teams` - teams+ * * `pagerduty` - pagerduty+ */+ export type LogsAlertDestinationTypeEnum = typeof LogsAlertDestinationTypeEnum[keyof typeof LogsAlertDestinationTypeEnum];+++ export const LogsAlertDestinationTypeEnum = {+ Slack: 'slack',+ Webhook: 'webhook',+ Teams: 'teams',+ Pagerduty: 'pagerduty',+ } as const;+export interface LogsAlertConfiguration {/** Unique identifier for this alert. */readonly id: string;@@ -60319,7 +60335,7 @@ export namespace Schemas {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types: readonly NotificationDestinationTypeEnum[];+ readonly destination_types: readonly LogsAlertDestinationTypeEnum[];/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullable@@ -60335,20 +60351,63 @@ export namespace Schemas {readonly updated_at: string | null;}+ /**+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info+ */+ export type PagerDutySeverityEnum = typeof PagerDutySeverityEnum[keyof typeof PagerDutySeverityEnum];+++ export const PagerDutySeverityEnum = {+ Critical: 'critical',+ Error: 'error',+ Warning: 'warning',+ Info: 'info',+ } as const;++ /**+ * * `us` - us+ * * `eu` - eu+ */+ export type PagerDutyRegionEnum = typeof PagerDutyRegionEnum[keyof typeof PagerDutyRegionEnum];+++ export const PagerDutyRegionEnum = {+ Us: 'us',+ Eu: 'eu',+ } as const;+export interface LogsAlertDestinationConfig {hog_function_ids: string[];/** Notification destination type.** * `slack` - slack* * `webhook` - webhook- * * `teams` - teams */- type: NotificationDestinationTypeEnum;+ * * `teams` - teams+ * * `pagerduty` - pagerduty */+ type: LogsAlertDestinationTypeEnum;/** Whether every HogFunction in the group is enabled, so the destination notifies for all alert event kinds. This is the stored setting: a destination PostHog stopped delivering to after repeated failures still reads as true. */enabled: boolean;slack_workspace_id?: number;slack_channel_id?: string;/** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */webhook_url?: string;+ /** PagerDuty integration key reduced to its last four characters. */+ pagerduty_routing_key?: string;+ /** Severity of the PagerDuty incident.+ *+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info */+ pagerduty_severity?: PagerDutySeverityEnum;+ /** PagerDuty service region the events go to.+ *+ * * `us` - us+ * * `eu` - eu */+ pagerduty_region?: PagerDutyRegionEnum;}/**@@ -60439,7 +60498,7 @@ export namespace Schemas {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types: readonly NotificationDestinationTypeEnum[];+ readonly destination_types: readonly LogsAlertDestinationTypeEnum[];/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullable@@ -60462,8 +60521,9 @@ export namespace Schemas {** * `slack` - slack* * `webhook` - webhook- * * `teams` - teams */- type: NotificationDestinationTypeEnum;+ * * `teams` - teams+ * * `pagerduty` - pagerduty */+ type: LogsAlertDestinationTypeEnum;/** Integration ID for the Slack workspace. Required when type=slack. */slack_workspace_id?: number;/** Slack channel ID. Required when type=slack. */@@ -60472,6 +60532,20 @@ export namespace Schemas {slack_channel_name?: string;/** HTTPS endpoint to post to. Required for webhook and teams. */webhook_url?: string;+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */+ pagerduty_routing_key?: string;+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.+ *+ * * `critical` - critical+ * * `error` - error+ * * `warning` - warning+ * * `info` - info */+ pagerduty_severity?: PagerDutySeverityEnum;+ /** PagerDuty service region of the account. Used when type=pagerduty.+ *+ * * `us` - us+ * * `eu` - eu */+ pagerduty_region?: PagerDutyRegionEnum;}export interface LogsAlertDeleteDestination {@@ -78956,7 +79030,7 @@ export namespace Schemas {/** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */readonly state_timeline?: readonly LogsAlertStateInterval[];/** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */- readonly destination_types?: readonly NotificationDestinationTypeEnum[];+ readonly destination_types?: readonly LogsAlertDestinationTypeEnum[];/*** When the alert was first enabled. Null means the alert is still in draft state.* @nullablediff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 81c0bf3f740b..b29c7850afec 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -3599,7 +3599,7 @@ export const LogsAlertsDestroyParams = () => zod.object({})/**- * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically.+ * Create a notification destination for this alert. One HogFunction is created per alert event kind (firing, resolved, ...) atomically. A PagerDuty destination gets the incident opened and incident closed kinds instead. They follow every start and end of a firing, cooldown included, so each incident it opens is resolved.*/export const LogsAlertsDestinationsCreateParams = () => zod.object({id: zod.string().describe('A UUID string identifying this logs alert configuration.'),@@ -3610,11 +3610,16 @@ export const LogsAlertsDestinationsCreateParams = () => zod.object({),})+export const logsAlertsDestinationsCreateBodyPagerdutySeverityDefault = `critical`+export const logsAlertsDestinationsCreateBodyPagerdutyRegionDefault = `us`+export const LogsAlertsDestinationsCreateBody = () => zod.object({type: zod- .enum(['slack', 'webhook', 'teams'])- .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')- .describe('Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'),+ .enum(['slack', 'webhook', 'teams', 'pagerduty'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `pagerduty` - pagerduty')+ .describe(+ 'Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams\n\* `pagerduty` - pagerduty'+ ),slack_workspace_id: zod.number().optional()@@ -3622,6 +3627,22 @@ export const LogsAlertsDestinationsCreateBody = () => zod.object({slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook and teams.'),+ pagerduty_routing_key: zod+ .string()+ .optional()+ .describe('Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.'),+ pagerduty_severity: zod+ .enum(['critical', 'error', 'warning', 'info'])+ .describe('\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info')+ .default(logsAlertsDestinationsCreateBodyPagerdutySeverityDefault)+ .describe(+ 'Severity PagerDuty records on the incident. Used when type=pagerduty.\n\n\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info'+ ),+ pagerduty_region: zod+ .enum(['us', 'eu'])+ .describe('\* `us` - us\n\* `eu` - eu')+ .default(logsAlertsDestinationsCreateBodyPagerdutyRegionDefault)+ .describe('PagerDuty service region of the account. Used when type=pagerduty.\n\n\* `us` - us\n\* `eu` - eu'),})/**diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex 9863281c0850..89954e27d132 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -89,7 +89,7 @@ const LogsAlertsDestinationsCreateSchema = () => {.extend(LogsAlertsDestinationsCreateBody.shape).extend({type: LogsAlertsDestinationsCreateBody.shape['type'].describe(- 'Destination type. Use slack, webhook, or teams. Slack requires slack_workspace_id and slack_channel_id. Webhook and teams require webhook_url.'+ 'Destination type. Use slack, webhook, teams, or pagerduty. Slack requires slack_workspace_id and slack_channel_id. Webhook and teams require webhook_url. PagerDuty requires pagerduty_routing_key.'),slack_workspace_id: LogsAlertsDestinationsCreateBody.shape['slack_workspace_id'].describe('Slack workspace integration ID. Required when type is slack.'@@ -103,6 +103,15 @@ const LogsAlertsDestinationsCreateSchema = () => {webhook_url: LogsAlertsDestinationsCreateBody.shape['webhook_url'].describe('Required when type is webhook or teams.'),+ pagerduty_routing_key: LogsAlertsDestinationsCreateBody.shape['pagerduty_routing_key'].describe(+ 'The 32-character integration key of an Events API v2 integration on the PagerDuty service. Required when type is pagerduty.'+ ),+ pagerduty_severity: LogsAlertsDestinationsCreateBody.shape['pagerduty_severity'].describe(+ 'Incident severity for PagerDuty. One of critical, error, warning, info. Defaults to critical.'+ ),+ pagerduty_region: LogsAlertsDestinationsCreateBody.shape['pagerduty_region'].describe(+ 'PagerDuty service region, us or eu. Defaults to us.'+ ),})}@@ -130,6 +139,15 @@ const logsAlertsDestinationsCreate = (): ToolBase<if (params.webhook_url !== undefined) {body['webhook_url'] = params.webhook_url}+ if (params.pagerduty_routing_key !== undefined) {+ body['pagerduty_routing_key'] = params.pagerduty_routing_key+ }+ if (params.pagerduty_severity !== undefined) {+ body['pagerduty_severity'] = params.pagerduty_severity+ }+ if (params.pagerduty_region !== undefined) {+ body['pagerduty_region'] = params.pagerduty_region+ }const result = await context.api.request<Schemas.LogsAlertDestinationResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/destinations/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-create.jsonindex 238878f23980..9c1a4df95003 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-create.json@@ -5,6 +5,22 @@"description": "A UUID string identifying this logs alert configuration.","type": "string"},+ "pagerduty_region": {+ "default": "us",+ "description": "PagerDuty service region, us or eu. Defaults to us.",+ "enum": ["us", "eu"],+ "type": "string"+ },+ "pagerduty_routing_key": {+ "description": "The 32-character integration key of an Events API v2 integration on the PagerDuty service. Required when type is pagerduty.",+ "type": "string"+ },+ "pagerduty_severity": {+ "default": "critical",+ "description": "Incident severity for PagerDuty. One of critical, error, warning, info. Defaults to critical.",+ "enum": ["critical", "error", "warning", "info"],+ "type": "string"+ },"slack_channel_id": {"description": "Slack channel ID. Required when type is slack.","type": "string"@@ -18,8 +34,8 @@"type": "number"},"type": {- "description": "Destination type. Use slack, webhook, or teams. Slack requires slack_workspace_id and slack_channel_id. Webhook and teams require webhook_url.",- "enum": ["slack", "webhook", "teams"],+ "description": "Destination type. Use slack, webhook, teams, or pagerduty. Slack requires slack_workspace_id and slack_channel_id. Webhook and teams require webhook_url. PagerDuty requires pagerduty_routing_key.",+ "enum": ["slack", "webhook", "teams", "pagerduty"],"type": "string"},"webhook_url": {