: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(alerts): extract shared alert destination management and dispatch (2/7) (#68937)
Matt Pua4b5f27c30b7d
diff --git a/posthog/cdp/templates/discord/template_discord.py b/posthog/cdp/templates/discord/template_discord.pyindex 3eb719816d5a..dc74a4e8d6e3 100644--- a/posthog/cdp/templates/discord/template_discord.py+++ b/posthog/cdp/templates/discord/template_discord.py@@ -28,7 +28,10 @@ if (not match(inputs.webhookUrl, '^https://discord.com/api/webhooks/.*')) {let res := fetch(inputs.webhookUrl, {'body': {- 'content': inputs.content+ 'content': inputs.content,+ 'allowed_mentions': {+ 'parse': []+ }},'method': 'POST','headers': {diff --git a/posthog/cdp/templates/discord/test_template_discord.py b/posthog/cdp/templates/discord/test_template_discord.pyindex dc554c67d742..62c9929749c3 100644--- a/posthog/cdp/templates/discord/test_template_discord.py+++ b/posthog/cdp/templates/discord/test_template_discord.py@@ -10,7 +10,7 @@ class TestTemplateDiscord(BaseHogFunctionTemplateTest):def _inputs(self, **kwargs):inputs = {"webhookUrl": "https://discord.com/api/webhooks/00000000000000000/xxxxxxxxxxxxxx",- "content": "**[email protected]** triggered event: '$pageview'",+ "content": "Alert <@123456789> triggered",}inputs.update(kwargs)return inputs@@ -26,7 +26,8 @@ class TestTemplateDiscord(BaseHogFunctionTemplateTest):"Content-Type": "application/json",},"body": {- "content": "**[email protected]** triggered event: '$pageview'",+ "content": "Alert <@123456789> triggered",+ "allowed_mentions": {"parse": []},},},)diff --git a/products/alerts/backend/destination_configs.py b/products/alerts/backend/destination_configs.pynew file mode 100644index 000000000000..22e8dd308804--- /dev/null+++ b/products/alerts/backend/destination_configs.py@@ -0,0 +1,229 @@+"""Shared configuration builders for alert destinations."""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass+from typing import Any, NotRequired, TypedDict++from django.db import models+++class DestinationType(models.TextChoices):+ SLACK = "slack", "Slack"+ DISCORD = "discord", "Discord"+ WEBHOOK = "webhook", "Webhook"+ TEAMS = "teams", "Microsoft Teams"+++DESTINATION_TEMPLATE_IDS: dict[DestinationType, str] = {+ DestinationType.SLACK: "template-slack",+ DestinationType.DISCORD: "template-discord",+ DestinationType.WEBHOOK: "template-webhook",+ DestinationType.TEAMS: "template-microsoft-teams",+}++DESTINATION_REQUIRED_FIELDS: dict[DestinationType, tuple[str, ...]] = {+ DestinationType.SLACK: ("slack_workspace_id", "slack_channel_id"),+ DestinationType.DISCORD: ("webhook_url",),+ DestinationType.WEBHOOK: ("webhook_url",),+ DestinationType.TEAMS: ("webhook_url",),+}+++class AlertDestinationData(TypedDict):+ type: DestinationType+ slack_workspace_id: NotRequired[int]+ slack_channel_id: NotRequired[str]+ slack_channel_name: NotRequired[str]+ webhook_url: NotRequired[str]+++class AlertDestinationValidationError(Exception):+ def __init__(self, message: str, *, field: str | None = None) -> None:+ self.message = message+ self.field = field+ super().__init__(message)+++WEBHOOK_HEADERS = {"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}++_HOG_FUNCTION_NAME_MAX_LEN = 400+++@dataclass(frozen=True)+class AlertDestinationConfig:+ team: Any+ payload: dict[str, Any]+++@dataclass(frozen=True)+class AlertDestinationAction:+ url: str+ label: str+++@dataclass(frozen=True)+class EventKindSpec:+ event_id: str+ display_kind: str+ header: str+ details: tuple[tuple[str, str], ...]+ primary_action_url: str+ primary_action_label: str+ webhook_body: dict[str, Any]+ product_label: str = "alert"+ intro_lines: tuple[str, ...] = ()+ additional_actions: tuple[AlertDestinationAction, ...] = ()++ def destination_description(self, alert_name: str) -> str:+ return f'Sends {self.display_kind} notifications for {self.product_label} "{alert_name}".'+++def clip_hog_function_name(name: str) -> str:+ if len(name) <= _HOG_FUNCTION_NAME_MAX_LEN:+ return name+ return name[: _HOG_FUNCTION_NAME_MAX_LEN - 1] + "…"+++def destination_filter(alert_id: str, event_id: str) -> dict[str, Any]:+ return {+ "events": [{"id": event_id, "type": "events"}],+ "properties": [+ {+ "key": "alert_id",+ "value": alert_id,+ "operator": "exact",+ "type": "event",+ }+ ],+ }+++def slack_body(spec: EventKindSpec) -> str:+ parts = []+ if spec.intro_lines:+ parts.append("\n".join(spec.intro_lines))+ if spec.details:+ parts.append("\n".join(f"*{label}:* {value}" for label, value in spec.details))+ return "\n\n".join(parts)+++def slack_blocks(spec: EventKindSpec, context_elements: tuple[str, ...]) -> list[dict]:+ return [+ {"type": "header", "text": {"type": "plain_text", "text": spec.header}},+ {"type": "section", "text": {"type": "mrkdwn", "text": slack_body(spec)}},+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": element} for element in context_elements],+ },+ {"type": "divider"},+ {+ "type": "actions",+ "elements": [+ {+ "url": action.url,+ "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,+ )+ ],+ },+ ]+++def teams_text(spec: EventKindSpec) -> str:+ parts = [f"**{spec.header}**"]+ 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,+ )+ )+ )+ return "\n\n".join(parts)+++def validate_destination_data(+ data: AlertDestinationData,+ *,+ allowed_destination_types: Sequence[DestinationType],+) -> None:+ raw_destination_type = data.get("type")+ destination_type = next((choice for choice in allowed_destination_types if choice == raw_destination_type), None)+ 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")++ missing_fields = tuple(field for field in DESTINATION_REQUIRED_FIELDS[destination_type] 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 build_alert_destination_config(+ *,+ team: Any,+ spec: EventKindSpec,+ alert_id: str,+ alert_name: str,+ data: AlertDestinationData,+ slack_context_elements: tuple[str, ...],+) -> AlertDestinationConfig:+ destination_type = data["type"]+ product_name = spec.product_label.capitalize()++ if destination_type == DestinationType.SLACK:+ channel_display = data.get("slack_channel_name") or "channel"+ destination_name = f"Slack #{channel_display}"+ inputs = {+ "blocks": {"value": slack_blocks(spec, slack_context_elements)},+ "text": {"value": spec.header},+ "slack_workspace": {"value": data["slack_workspace_id"]},+ "channel": {"value": data["slack_channel_id"]},+ }+ elif destination_type == DestinationType.WEBHOOK:+ destination_name = f"Webhook {data['webhook_url']}"+ inputs = {+ "body": {"value": spec.webhook_body},+ "url": {"value": data["webhook_url"]},+ "headers": {"value": WEBHOOK_HEADERS},+ }+ elif destination_type == DestinationType.DISCORD:+ destination_name = "Discord"+ inputs = {+ "content": {"value": teams_text(spec)},+ "webhookUrl": {"value": data["webhook_url"]},+ }+ else:+ destination_name = "Microsoft Teams"+ inputs = {+ "webhookUrl": {"value": data["webhook_url"]},+ "text": {"value": teams_text(spec)},+ }++ return AlertDestinationConfig(+ team=team,+ payload={+ "type": "internal_destination",+ "enabled": True,+ "filters": destination_filter(alert_id, spec.event_id),+ "name": clip_hog_function_name(f"{product_name} — {alert_name} ({spec.display_kind}) → {destination_name}"),+ "description": spec.destination_description(alert_name),+ "template_id": DESTINATION_TEMPLATE_IDS[destination_type],+ "inputs": inputs,+ },+ )diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.pynew file mode 100644index 000000000000..ad28a2b585b1--- /dev/null+++ b/products/alerts/backend/destinations.py@@ -0,0 +1,189 @@+"""Django persistence and dispatch for alert notification destinations."""++from __future__ import annotations++from collections.abc import Collection+from datetime import datetime+from typing import Any+from uuid import UUID++from django.db import transaction+from django.db.models import Q++import structlog+from prometheus_client import Counter+from rest_framework.exceptions import ValidationError++from posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_event+from posthog.exceptions_capture import capture_exception+from posthog.kafka_client.client import ProduceResult+from posthog.plugins.plugin_server_api import reload_hog_functions_on_workers++from products.alerts.backend.destination_configs import DESTINATION_TEMPLATE_IDS, AlertDestinationConfig+from products.cdp.backend.api.hog_function import HogFunctionSerializer+from products.cdp.backend.models.hog_functions.hog_function import HogFunction++logger = structlog.get_logger(__name__)++ALERT_INTERNAL_EVENT_DELIVERY_FAILURES = Counter(+ "posthog_alert_internal_event_delivery_failures_total",+ "Number of alert internal events that failed delivery",+ labelnames=["event_name"],+)+++def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig], *, request: Any) -> list[HogFunction]:+ created: list[HogFunction] = []+ hog_function_ids_by_team: dict[int, list[UUID]] = {}+ with transaction.atomic():+ for config in configs:+ team = config.team+ serializer = HogFunctionSerializer(+ data=config.payload,+ context={"request": request, "get_team": lambda team=team: team, "is_create": True},+ )+ serializer.is_valid(raise_exception=True)+ hog_function = serializer.save(team=team)+ created.append(hog_function)+ hog_function_ids_by_team.setdefault(team.id, []).append(hog_function.id)+ for team_id, hog_function_ids in hog_function_ids_by_team.items():+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=hog_function_ids)+ return created+++def soft_delete_alert_destinations(+ *,+ team_id: int,+ alert_id: str,+ allowed_event_ids: Collection[str],+ hog_function_ids: list[UUID],+) -> None:+ unique_ids = set(hog_function_ids)+ with transaction.atomic():+ event_filter = _allowed_event_filter(allowed_event_ids)+ owned_ids = set(+ HogFunction.objects.select_for_update()+ .filter(+ event_filter,+ team_id=team_id,+ id__in=unique_ids,+ template_id__in=DESTINATION_TEMPLATE_IDS.values(),+ filters__properties__contains=[{"key": "alert_id", "value": alert_id}],+ )+ .values_list("id", flat=True)+ )+ invalid_ids = unique_ids - owned_ids+ if invalid_ids:+ formatted_ids = ", ".join(str(hog_function_id) for hog_function_id in sorted(invalid_ids, key=str))+ raise ValidationError(+ {+ "hog_function_ids": [+ f"These HogFunctions do not belong to this alert: {formatted_ids}. Refresh the alert and try again."+ ]+ }+ )+ HogFunction.objects.filter(team_id=team_id, id__in=owned_ids).update(deleted=True, enabled=False)+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=owned_ids)+++def soft_delete_all_alert_destinations(*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]) -> int:+ with transaction.atomic():+ owned_ids = set(+ HogFunction.objects.select_for_update()+ .filter(+ _allowed_event_filter(allowed_event_ids),+ team_id=team_id,+ deleted=False,+ template_id__in=DESTINATION_TEMPLATE_IDS.values(),+ filters__properties__contains=[{"key": "alert_id", "value": alert_id}],+ )+ .values_list("id", flat=True)+ )+ deleted_count = HogFunction.objects.filter(team_id=team_id, id__in=owned_ids).update(+ deleted=True, enabled=False+ )+ _reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=owned_ids)+ return deleted_count+++def _allowed_event_filter(allowed_event_ids: Collection[str]) -> Q:+ if not allowed_event_ids:+ raise ValueError("allowed_event_ids must not be empty")++ event_filter = Q()+ for event_id in allowed_event_ids:+ event_filter |= Q(filters__events__contains=[{"id": event_id, "type": "events"}])+ return event_filter+++def _reload_hog_functions_after_commit(*, team_id: int, hog_function_ids: Collection[UUID]) -> None:+ serialized_ids = sorted(str(hog_function_id) for hog_function_id in hog_function_ids)+ if serialized_ids:+ transaction.on_commit(+ lambda: reload_hog_functions_on_workers(team_id=team_id, hog_function_ids=serialized_ids),+ robust=True,+ )+++def produce_alert_internal_event(+ *,+ team_id: int,+ event_name: str,+ properties: dict[str, Any],+ timestamp: datetime | None = None,+ uuid: str | None = None,+) -> ProduceResult | None:+ try:+ return produce_internal_event(+ team_id=team_id,+ event=InternalEventEvent(+ event=event_name,+ distinct_id=f"team_{team_id}",+ properties=properties,+ timestamp=timestamp.isoformat() if timestamp else None,+ uuid=uuid,+ ),+ )+ except Exception as error:+ context = {+ "alert_id": properties.get("alert_id"),+ "event_name": event_name,+ "feature": "alerts",+ "team_id": team_id,+ }+ capture_exception(error, context)+ logger.exception("Failed to enqueue alert internal event", **context)+ return None+++def flush_alert_internal_events(timeout_seconds: float) -> None:+ try:+ remaining = flush_internal_events_producer(timeout_seconds)+ if remaining:+ logger.warning("Alert internal event flush timed out", remaining=remaining)+ except Exception as error:+ context = {"feature": "alerts", "phase": "notification_flush"}+ capture_exception(error, context)+ logger.exception("Failed to flush alert internal events", **context)+++def alert_internal_event_delivered(+ produce_result: ProduceResult,+ *,+ team_id: int,+ alert_id: str,+ event_name: str,+) -> bool:+ try:+ produce_result.get(timeout=0)+ return True+ except Exception as error:+ context = {+ "alert_id": alert_id,+ "event_name": event_name,+ "feature": "alerts",+ "team_id": team_id,+ }+ ALERT_INTERNAL_EVENT_DELIVERY_FAILURES.labels(event_name=event_name).inc()+ logger.warning("Alert internal event was not delivered", error=str(error), **context)+ return Falsediff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pynew file mode 100644index 000000000000..27426ea4c853--- /dev/null+++ b/products/alerts/backend/facade/api.py@@ -0,0 +1,25 @@+from products.alerts.backend.destination_configs import (+ DESTINATION_TEMPLATE_IDS,+ AlertDestinationData,+ AlertDestinationValidationError,+ DestinationType,+ build_alert_destination_config,+ validate_destination_data,+)+from products.alerts.backend.destinations import (+ create_alert_destination_hog_functions,+ soft_delete_alert_destinations,+ soft_delete_all_alert_destinations,+)++__all__ = [+ "DESTINATION_TEMPLATE_IDS",+ "AlertDestinationData",+ "AlertDestinationValidationError",+ "DestinationType",+ "build_alert_destination_config",+ "create_alert_destination_hog_functions",+ "soft_delete_alert_destinations",+ "soft_delete_all_alert_destinations",+ "validate_destination_data",+]diff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.pynew file mode 100644index 000000000000..f37d6a607539--- /dev/null+++ b/products/alerts/backend/test/test_destination_configs.py@@ -0,0 +1,56 @@+from products.alerts.backend.destination_configs import AlertDestinationAction, EventKindSpec, slack_blocks, teams_text++DEFAULT_SPEC = EventKindSpec(+ event_id="$insight_alert_firing",+ display_kind="firing",+ header="Insight alert firing",+ details=(("Threshold", "30"),),+ primary_action_url="https://example.com/insight",+ primary_action_label="View insight",+ webhook_body={},+)++PROSE_SPEC = EventKindSpec(+ event_id="$insight_alert_firing",+ display_kind="firing",+ header="Insight alert firing",+ details=(),+ primary_action_url="https://example.com/insight",+ primary_action_label="View insight",+ webhook_body={},+ intro_lines=("Pageviews is 42, breaching 30", "Signups is 7, breaching 5"),+ additional_actions=(AlertDestinationAction(url="https://example.com/alert", label="Manage alert"),),+)+++class TestSpecVocabularyRendering:+ def test_slack_renders_intro_lines_and_additional_actions(self) -> None:+ blocks = slack_blocks(PROSE_SPEC, context_elements=("Project: PostHog", "Alert ID: alert-1"))++ section = next(b for b in blocks if b["type"] == "section")+ assert "Pageviews is 42, breaching 30\nSignups is 7, breaching 5" in section["text"]["text"]++ context = next(b for b in blocks if b["type"] == "context")+ assert context["elements"] == [+ {"type": "mrkdwn", "text": "Project: PostHog"},+ {"type": "mrkdwn", "text": "Alert ID: alert-1"},+ ]++ actions = next(b for b in blocks if b["type"] == "actions")+ assert [(e["url"], e["text"]["text"]) for e in actions["elements"]] == [+ ("https://example.com/insight", "View insight"),+ ("https://example.com/alert", "Manage alert"),+ ]++ def test_teams_renders_intro_lines_and_additional_actions(self) -> None:+ text = teams_text(PROSE_SPEC)+ assert "Pageviews is 42, breaching 30" in text+ assert "[View insight](https://example.com/insight) · [Manage alert](https://example.com/alert)" in text++ def test_defaults_render_single_button_and_details_only(self) -> None:+ blocks = slack_blocks(DEFAULT_SPEC, context_elements=())+ actions = next(b for b in blocks if b["type"] == "actions")+ assert len(actions["elements"]) == 1+ assert teams_text(DEFAULT_SPEC) == (+ "**Insight alert firing**\n\n**Threshold:** 30\n\n[View insight](https://example.com/insight)"+ )diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pynew file mode 100644index 000000000000..1ae71c564ac1--- /dev/null+++ b/products/alerts/backend/test/test_destinations.py@@ -0,0 +1,159 @@+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from rest_framework.exceptions import ValidationError++from products.alerts.backend.destinations import (+ alert_internal_event_delivered,+ soft_delete_alert_destinations,+ soft_delete_all_alert_destinations,+)+from products.cdp.backend.models.hog_functions.hog_function import HogFunction++ALLOWED_EVENT_IDS = ("$logs_alert_firing", "$logs_alert_resolved")+++class TestSoftDeleteAlertDestinations(APIBaseTest):+ def _make_hog_function(+ self, *, template_id: str, alert_id: str, event_id: str = "$logs_alert_firing"+ ) -> HogFunction:+ return HogFunction.objects.create(+ team=self.team,+ name="Test destination",+ type="destination",+ template_id=template_id,+ enabled=True,+ inputs_schema=[],+ inputs={},+ hog="return event",+ filters={+ "events": [{"id": event_id, "type": "events"}],+ "properties": [{"key": "alert_id", "value": alert_id}],+ },+ )++ def test_deletes_alert_destination_with_matching_alert_id(self) -> None:+ destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")++ soft_delete_alert_destinations(+ team_id=self.team.id,+ alert_id="alert-1",+ allowed_event_ids=ALLOWED_EVENT_IDS,+ hog_function_ids=[destination.id],+ )++ destination.refresh_from_db()+ assert destination.deleted is True+ assert destination.enabled is False++ def test_reports_invalid_ids_and_does_not_delete_any_destinations(self) -> None:+ destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")+ other = self._make_hog_function(template_id="template-webhook", alert_id="alert-1", event_id="$unrelated_event")++ with self.assertRaises(ValidationError) as error:+ soft_delete_alert_destinations(+ team_id=self.team.id,+ alert_id="alert-1",+ allowed_event_ids=ALLOWED_EVENT_IDS,+ hog_function_ids=[destination.id, other.id],+ )++ assert isinstance(error.exception.detail, dict)+ hog_function_id_errors = error.exception.detail["hog_function_ids"]+ assert isinstance(hog_function_id_errors, list)+ assert str(hog_function_id_errors[0]) == (+ f"These HogFunctions do not belong to this alert: {other.id}. Refresh the alert and try again."+ )+ for hog_function in (destination, other):+ hog_function.refresh_from_db()+ assert hog_function.deleted is False+ assert hog_function.enabled is True++ def test_deletes_all_destinations_for_alert_only(self) -> None:+ slack_destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")+ webhook_destination = self._make_hog_function(template_id="template-webhook", alert_id="alert-1")+ other_alert_destination = self._make_hog_function(template_id="template-slack", alert_id="alert-2")+ non_destination = self._make_hog_function(template_id="template-webhook-custom", alert_id="alert-1")+ unrelated_event_destination = self._make_hog_function(+ template_id="template-webhook", alert_id="alert-1", event_id="$unrelated_event"+ )++ deleted_count = soft_delete_all_alert_destinations(+ team_id=self.team.id, alert_id="alert-1", allowed_event_ids=ALLOWED_EVENT_IDS+ )++ assert deleted_count == 2+ for destination in (slack_destination, webhook_destination):+ destination.refresh_from_db()+ assert destination.deleted is True+ assert destination.enabled is False++ for destination in (other_alert_destination, non_destination, unrelated_event_destination):+ destination.refresh_from_db()+ assert destination.deleted is False+ assert destination.enabled is True++ def test_rejects_empty_allowed_event_ids_without_deleting_destinations(self) -> None:+ destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")++ with self.assertRaisesRegex(ValueError, "allowed_event_ids must not be empty"):+ soft_delete_all_alert_destinations(team_id=self.team.id, alert_id="alert-1", allowed_event_ids=())++ destination.refresh_from_db()+ assert destination.deleted is False+ assert destination.enabled is True++ @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ def test_reload_happens_after_destination_delete_commits(self, reload_hog_functions_on_workers) -> None:+ destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")++ with self.captureOnCommitCallbacks(execute=True):+ soft_delete_alert_destinations(+ team_id=self.team.id,+ alert_id="alert-1",+ allowed_event_ids=ALLOWED_EVENT_IDS,+ hog_function_ids=[destination.id],+ )+ reload_hog_functions_on_workers.assert_not_called()++ reload_hog_functions_on_workers.assert_called_once_with(+ team_id=self.team.id, hog_function_ids=[str(destination.id)]+ )++ @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers", side_effect=RuntimeError("boom"))+ def test_reload_failure_does_not_fail_committed_delete(self, _reload_hog_functions_on_workers) -> None:+ destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")++ with self.captureOnCommitCallbacks(execute=True):+ soft_delete_alert_destinations(+ team_id=self.team.id,+ alert_id="alert-1",+ allowed_event_ids=ALLOWED_EVENT_IDS,+ hog_function_ids=[destination.id],+ )++ destination.refresh_from_db()+ assert destination.deleted is True+ assert destination.enabled is False+++class TestAlertInternalEventDelivery(APIBaseTest):+ @patch("products.alerts.backend.destinations.capture_exception")+ @patch("products.alerts.backend.destinations.ALERT_INTERNAL_EVENT_DELIVERY_FAILURES")+ def test_expected_delivery_failure_records_metric_without_capturing_exception(+ self, delivery_failures, capture_exception+ ) -> None:+ produce_result = MagicMock()+ produce_result.get.side_effect = RuntimeError("delivery failed")++ delivered = alert_internal_event_delivered(+ produce_result,+ team_id=self.team.id,+ alert_id="alert-1",+ event_name="$logs_alert_firing",+ )++ assert delivered is False+ capture_exception.assert_not_called()+ delivery_failures.labels.assert_called_once_with(event_name="$logs_alert_firing")+ delivery_failures.labels.return_value.inc.assert_called_once_with()diff --git a/products/logs/backend/alert_destinations.py b/products/logs/backend/alert_destinations.pyindex 09923e26f0f6..139f0aae6b68 100644--- a/products/logs/backend/alert_destinations.py+++ b/products/logs/backend/alert_destinations.py@@ -2,29 +2,15 @@from __future__ import annotations-from dataclasses import dataclass-from typing import Any, Literal+from typing import Literal-from products.logs.backend.models import LogsAlertConfiguration+from products.alerts.backend.destination_configs import DestinationType, EventKindSpecEventKind = Literal["firing", "resolved", "broken", "errored"]+LOGS_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)-@dataclass(frozen=True)-class EventKindSpec:- event_id: str- display_kind: str- header: str- # Plain-text (label, value) pairs; each destination renders these in its own markup.- details: tuple[tuple[str, str], ...]- button_url: str- button_label: str- webhook_body: dict[str, Any]-- def destination_description(self, alert_name: str) -> str:- return f'Sends {self.display_kind} notifications for logs alert "{alert_name}".'--+_PRODUCT_LABEL = "logs alert"_FIRE_RESOLVE_DATA: dict[str, str] = {"alert_id": "{event.properties.alert_id}","alert_name": "{event.properties.alert_name}",@@ -60,14 +46,15 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {"(threshold: {event.properties.threshold_operator} {event.properties.threshold_count})",),),- button_url="{project.url}/logs?{event.properties.logs_url_params}",- button_label="View logs",+ 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,),"resolved": EventKindSpec(event_id="$logs_alert_resolved",@@ -80,14 +67,15 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {"(threshold: {event.properties.threshold_operator} {event.properties.threshold_count})",),),- button_url="{project.url}/logs?{event.properties.logs_url_params}",- button_label="View logs",+ primary_action_url="{project.url}/logs?{event.properties.logs_url_params}",+ primary_action_label="View logs",webhook_body={"id": "{event.uuid}","type": "logs_alert.resolved","timestamp": "{event.properties.triggered_at}","data": _FIRE_RESOLVE_DATA,},+ product_label=_PRODUCT_LABEL,),"broken": EventKindSpec(event_id="$logs_alert_auto_disabled",@@ -97,8 +85,8 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {("Reason", "{event.properties.consecutive_failures} consecutive check failures."),("Last error", "{event.properties.last_error_message}"),),- button_url="{project.url}/logs/alerts/{event.properties.alert_id}",- button_label="View alert",+ primary_action_url="{project.url}/logs/alerts/{event.properties.alert_id}",+ primary_action_label="View alert",webhook_body={"id": "{event.uuid}","type": "logs_alert.auto_disabled",@@ -108,6 +96,7 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {"last_error_message": "{event.properties.last_error_message}",},},+ product_label=_PRODUCT_LABEL,),"errored": EventKindSpec(event_id="$logs_alert_errored",@@ -117,8 +106,8 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {("Reason", "{event.properties.error_message}"),("Failure count", "{event.properties.consecutive_failures}"),),- button_url="{project.url}/logs/alerts/{event.properties.alert_id}",- button_label="View alert",+ primary_action_url="{project.url}/logs/alerts/{event.properties.alert_id}",+ primary_action_label="View alert",webhook_body={"id": "{event.uuid}","type": "logs_alert.errored",@@ -128,21 +117,12 @@ EVENT_KIND_CONFIG: dict[EventKind, EventKindSpec] = {"error_message": "{event.properties.error_message}",},},+ product_label=_PRODUCT_LABEL,),}EVENT_KINDS: tuple[EventKind, ...] = tuple(EVENT_KIND_CONFIG.keys())-# HogFunction.name is `models.CharField(max_length=400)` — clip rendered names to fit.-_HOG_FUNCTION_NAME_MAX_LEN = 400---def _clip_name(name: str) -> str:- if len(name) <= _HOG_FUNCTION_NAME_MAX_LEN:- return name- return name[: _HOG_FUNCTION_NAME_MAX_LEN - 1] + "…"--_SEVERITY_SERVICE_CONTEXT = ("{if(length(event.properties.severity_levels) > 0 or length(event.properties.service_names) > 0,"" concat("@@ -158,123 +138,7 @@ _SEVERITY_SERVICE_CONTEXT = (" 'All log levels and services')}")--def _slack_body(spec: EventKindSpec) -> str:- # Slack mrkdwn: *single asterisks* for bold, one line per detail.- return "\n".join(f"*{label}:* {value}" for label, value in spec.details)---def _slack_blocks(spec: EventKindSpec) -> list[dict]:- return [- {"type": "header", "text": {"type": "plain_text", "text": spec.header}},- {"type": "section", "text": {"type": "mrkdwn", "text": _slack_body(spec)}},- {- "type": "context",- "elements": [- {"type": "mrkdwn", "text": _SEVERITY_SERVICE_CONTEXT},- {"type": "mrkdwn", "text": "Project: <{project.url}|{project.name}>"},- ],- },- {"type": "divider"},- {- "type": "actions",- "elements": [- {- "url": spec.button_url,- "text": {"text": spec.button_label, "type": "plain_text"},- "type": "button",- }- ],- },- ]---def _teams_text(spec: EventKindSpec) -> str:- # The Microsoft Teams template renders a single Adaptive Card TextBlock from `text`, so fold- # the header, details, and action into one markdown string (the button becomes an inline link).- # Adaptive Card markdown: **double asterisks** for bold, blank lines between paragraphs.- details = "\n\n".join(f"**{label}:** {value}" for label, value in spec.details)- return f"**{spec.header}**\n\n{details}\n\n[{spec.button_label}]({spec.button_url})"---def _filter_for(alert: LogsAlertConfiguration, kind: EventKind) -> dict[str, Any]:- return {- "events": [{"id": EVENT_KIND_CONFIG[kind].event_id, "type": "events"}],- "properties": [- {- "key": "alert_id",- "value": str(alert.id),- "operator": "exact",- "type": "event",- }- ],- }---def build_slack_config(- alert: LogsAlertConfiguration,- kind: EventKind,- slack_workspace_id: int,- slack_channel_id: str,- slack_channel_name: str | None,-) -> dict[str, Any]:- spec = EVENT_KIND_CONFIG[kind]- channel_display = slack_channel_name or "channel"- return {- "team": alert.team,- "type": "internal_destination",- "enabled": True,- "filters": _filter_for(alert, kind),- "name": _clip_name(f"Logs alert — {alert.name} ({spec.display_kind}) → Slack #{channel_display}"),- "description": spec.destination_description(alert.name),- "template_id": "template-slack",- "inputs": {- "blocks": {"value": _slack_blocks(spec)},- "text": {"value": spec.header},- "slack_workspace": {"value": slack_workspace_id},- "channel": {"value": slack_channel_id},- },- }---def build_webhook_config(- alert: LogsAlertConfiguration,- kind: EventKind,- webhook_url: str,-) -> dict[str, Any]:- spec = EVENT_KIND_CONFIG[kind]- return {- "team": alert.team,- "type": "internal_destination",- "enabled": True,- "filters": _filter_for(alert, kind),- "name": _clip_name(f"Logs alert — {alert.name} ({spec.display_kind}) → Webhook {webhook_url}"),- "description": spec.destination_description(alert.name),- "template_id": "template-webhook",- "inputs": {- "body": {"value": spec.webhook_body},- "url": {"value": webhook_url},- "headers": {"value": {"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}},- },- }---def build_teams_config(- alert: LogsAlertConfiguration,- kind: EventKind,- webhook_url: str,-) -> dict[str, Any]:- spec = EVENT_KIND_CONFIG[kind]- return {- "team": alert.team,- "type": "internal_destination",- "enabled": True,- "filters": _filter_for(alert, kind),- "name": _clip_name(f"Logs alert — {alert.name} ({spec.display_kind}) → Microsoft Teams"),- "description": spec.destination_description(alert.name),- "template_id": "template-microsoft-teams",- "inputs": {- "webhookUrl": {"value": webhook_url},- "text": {"value": _teams_text(spec)},- },- }+LOGS_ALERT_SLACK_CONTEXT_ELEMENTS = (+ _SEVERITY_SERVICE_CONTEXT,+ "Project: <{project.url}|{project.name}>",+)diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex 39e62fb7ffed..b793144c0a31 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -1,11 +1,12 @@import osimport datetime as dtfrom datetime import UTC, datetime-from typing import Final, TypedDict, cast+from typing import Final, Literal, TypedDict, castfrom zoneinfo import ZoneInfo-from django.db import models, transaction+from django.db import transactionfrom django.db.models import F, OuterRef, Prefetch, Q, QuerySet, Subquery+from django.shortcuts import get_object_or_404from django.utils import timezonefrom drf_spectacular.utils import extend_schema, extend_schema_field@@ -28,15 +29,24 @@ from posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermissionfrom posthog.utils import relative_date_parse-from products.cdp.backend.api.hog_function import HogFunctionSerializer+from products.alerts.backend.facade.api import (+ DESTINATION_TEMPLATE_IDS,+ AlertDestinationData,+ AlertDestinationValidationError,+ DestinationType,+ build_alert_destination_config,+ create_alert_destination_hog_functions,+ soft_delete_alert_destinations,+ soft_delete_all_alert_destinations,+ validate_destination_data,+)from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCountfrom products.logs.backend.alert_destinations import (+ EVENT_KIND_CONFIG,EVENT_KINDS,- EventKind,- build_slack_config,- build_teams_config,- build_webhook_config,+ LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,+ LOGS_DESTINATION_TYPES,)from products.logs.backend.alert_state_machine import (AlertCheckOutcome,@@ -58,6 +68,7 @@ from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfigALLOWED_WINDOW_MINUTES = {5, 10, 15, 30, 60}MAX_ALERTS_PER_TEAM = 20+LOGS_ALERT_EVENT_IDS: Final = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())# Comma-separated team IDs that bypass MAX_ALERTS_PER_TEAM. Configured via# argocd for internal dogfood projects whose observability needs exceed the# customer-facing cap; the cap's correctness assumptions (bounded N+1 in list,@@ -81,12 +92,6 @@ def _any_field_changed(instance: LogsAlertConfiguration, validated_data: dict, freturn any(f in validated_data and validated_data[f] != getattr(instance, f) for f in fields)-class DestinationType(models.TextChoices):- SLACK = "slack"- WEBHOOK = "webhook"- TEAMS = "teams"--class LogsAlertStateIntervalSerializer(serializers.Serializer):start = serializers.DateTimeField(help_text="Interval start (UTC, inclusive).")end = serializers.DateTimeField(help_text="Interval end (UTC, exclusive).")@@ -348,22 +353,27 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):)return intervals- @extend_schema_field(serializers.ListField(child=serializers.ChoiceField(choices=list(DestinationType))))+ @extend_schema_field(serializers.ListField(child=serializers.ChoiceField(choices=LOGS_DESTINATION_TYPES)))def get_destination_types(self, obj: LogsAlertConfiguration) -> list[str]:# N+1 is acceptable: max 20 alerts per team, each query is a fast indexed lookup.team_id = obj.team_id- template_ids = (+ configured_template_ids = set(HogFunction.objects.filter(team_id=team_id,deleted=False,- template_id__in=["template-slack", "template-webhook", "template-microsoft-teams"],+ template_id__in=(+ DESTINATION_TEMPLATE_IDS[destination_type] for destination_type in LOGS_DESTINATION_TYPES+ ),filters__properties__contains=[{"key": "alert_id", "value": str(obj.id)}],).values_list("template_id", flat=True).distinct())- type_map = {"template-slack": "slack", "template-webhook": "webhook", "template-microsoft-teams": "teams"}- return sorted(type_map[tid] for tid in template_ids if tid in type_map)+ return sorted(+ destination_type.value+ for destination_type in LOGS_DESTINATION_TYPES+ if DESTINATION_TEMPLATE_IDS[destination_type] in configured_template_ids+ )@extend_schema_field(serializers.CharField(allow_null=True))def get_last_error_message(self, obj: LogsAlertConfiguration) -> str | None:@@ -664,9 +674,7 @@ class LogsAlertSimulateResponseSerializer(serializers.Serializer):class LogsAlertCreateDestinationSerializer(serializers.Serializer):- type = serializers.ChoiceField(- choices=list(DestinationType), help_text="Destination type — slack, webhook, or teams."- )+ type = serializers.ChoiceField(choices=LOGS_DESTINATION_TYPES, help_text="Notification destination type.")slack_workspace_id = serializers.IntegerField(required=False, help_text="Integration ID for the Slack workspace. Required when type=slack.")@@ -676,17 +684,18 @@ class LogsAlertCreateDestinationSerializer(serializers.Serializer):)webhook_url = serializers.URLField(required=False,- help_text="HTTPS endpoint to POST to. Required when type=webhook, or the Teams webhook URL when type=teams.",+ help_text="HTTPS endpoint to post to. Required for webhook and teams.",)def validate(self, attrs: dict) -> dict:- destination_type = attrs["type"]- if destination_type == "slack":- if not attrs.get("slack_workspace_id") or not attrs.get("slack_channel_id"):- raise ValidationError("slack_workspace_id and slack_channel_id are required for slack destinations.")- elif destination_type in ("webhook", "teams"):- if not attrs.get("webhook_url"):- raise ValidationError(f"webhook_url is required for {destination_type} destinations.")+ data = cast(AlertDestinationData, attrs)+ data["type"] = DestinationType(attrs["type"])+ try:+ validate_destination_data(data, allowed_destination_types=LOGS_DESTINATION_TYPES)+ except AlertDestinationValidationError as error:+ if error.field:+ raise ValidationError({error.field: error.message})+ raise ValidationError(error.message)return attrs@@ -694,6 +703,7 @@ class LogsAlertDeleteDestinationSerializer(serializers.Serializer):hog_function_ids = serializers.ListField(child=serializers.UUIDField(),min_length=1,+ max_length=len(LOGS_ALERT_EVENT_IDS),help_text="HogFunction IDs to delete as one atomic destination group.",)@@ -856,6 +866,13 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)return context+ def _get_locked_alert(self) -> LogsAlertConfiguration:+ queryset = self.filter_queryset(self.get_queryset()).select_for_update()+ lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field+ alert = get_object_or_404(queryset, **{self.lookup_field: self.kwargs[lookup_url_kwarg]})+ self.check_object_permissions(self.request, alert)+ return alert+@extend_schema(request=LogsAlertCreateDestinationSerializer,responses={201: LogsAlertDestinationResponseSerializer},@@ -863,13 +880,24 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(detail=True, methods=["POST"], url_path="destinations", required_scopes=["logs:write"])def create_destination(self, request: Request, *args: object, **kwargs: object) -> Response:- alert = self.get_object()serializer = LogsAlertCreateDestinationSerializer(data=request.data)serializer.is_valid(raise_exception=True)- data = serializer.validated_data+ data = cast(AlertDestinationData, serializer.validated_data)with transaction.atomic():- hog_functions = [self._build_and_create_hog_function(alert, data, kind) for kind in EVENT_KINDS]+ alert = self._get_locked_alert()+ configs = [+ build_alert_destination_config(+ team=alert.team,+ spec=EVENT_KIND_CONFIG[kind],+ alert_id=str(alert.id),+ alert_name=alert.name,+ data=data,+ slack_context_elements=LOGS_ALERT_SLACK_CONTEXT_ELEMENTS,+ )+ for kind in EVENT_KINDS+ ]+ hog_functions = create_alert_destination_hog_functions(configs, request=self.request)report_user_action(request.user,@@ -886,21 +914,18 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(detail=True, methods=["POST"], url_path="destinations/delete", required_scopes=["logs:write"])def delete_destination(self, request: Request, *args: object, **kwargs: object) -> Response:- alert = self.get_object()serializer = LogsAlertDeleteDestinationSerializer(data=request.data)serializer.is_valid(raise_exception=True)hog_function_ids = serializer.validated_data["hog_function_ids"]with transaction.atomic():- updated = HogFunction.objects.filter(+ alert = self._get_locked_alert()+ soft_delete_alert_destinations(team_id=self.team_id,- id__in=hog_function_ids,- filters__properties__contains=[{"key": "alert_id", "value": str(alert.id)}],- ).update(deleted=True)- if updated != len(hog_function_ids):- # Ownership check: if the filtered UPDATE touched fewer rows than we were asked- # to delete, something in the list doesn't belong to this alert. Roll back.- raise ValidationError("One or more HogFunctions do not belong to this alert.")+ alert_id=str(alert.id),+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,+ hog_function_ids=hog_function_ids,+ )report_user_action(request.user,@@ -909,34 +934,6 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)return Response(status=204)- def _build_and_create_hog_function(- self,- alert: LogsAlertConfiguration,- data: dict,- kind: EventKind,- ) -> HogFunction:- if data["type"] == "slack":- config = build_slack_config(- alert,- kind,- slack_workspace_id=data["slack_workspace_id"],- slack_channel_id=data["slack_channel_id"],- slack_channel_name=data.get("slack_channel_name"),- )- elif data["type"] == "teams":- config = build_teams_config(alert, kind, webhook_url=data["webhook_url"])- else:- config = build_webhook_config(alert, kind, webhook_url=data["webhook_url"])-- # Route through HogFunctionSerializer so template lookup and bytecode compilation run.- team = config.pop("team")- serializer = HogFunctionSerializer(- data=config,- context={"request": self.request, "get_team": lambda: team, "is_create": True},- )- serializer.is_valid(raise_exception=True)- return serializer.save(team=team)-@extend_schema(request=None,responses={200: LogsAlertEventSerializer(many=True)},@@ -1169,13 +1166,14 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):response_serializer = LogsAlertSimulateResponseSerializer(response_data)return Response(response_serializer.data)- def _track(self, event: str, instance: LogsAlertConfiguration) -> None:+ def _track(self, action: Literal["created", "updated", "deleted"], instance: LogsAlertConfiguration) -> None:report_user_action(self.request.user,- event,+ f"alert {action}",{- "id": str(instance.id),- "name": instance.name,+ "alert_id": str(instance.id),+ "alert_name": instance.name,+ "config_type": "LogsAlertConfig","enabled": instance.enabled,"threshold_count": instance.threshold_count,"threshold_operator": instance.threshold_operator,@@ -1186,11 +1184,24 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)def perform_create(self, serializer) -> None:- self._track("logs alert created", serializer.save())+ self._track("created", serializer.save())def perform_update(self, serializer) -> None:- self._track("logs alert updated", serializer.save())+ self._track("updated", serializer.save())def perform_destroy(self, instance: LogsAlertConfiguration) -> None:- self._track("logs alert deleted", instance)- super().perform_destroy(instance)+ with transaction.atomic():+ locked_instance = (+ LogsAlertConfiguration.objects.select_for_update()+ .filter(team_id=instance.team_id, id=instance.id)+ .first()+ )+ if locked_instance is None:+ return+ soft_delete_all_alert_destinations(+ team_id=locked_instance.team_id,+ alert_id=str(locked_instance.id),+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,+ )+ super().perform_destroy(locked_instance)+ transaction.on_commit(lambda: self._track("deleted", locked_instance), robust=True)diff --git a/products/logs/backend/temporal/activities.py b/products/logs/backend/temporal/activities.pyindex 593205233764..8d083ea62a59 100644--- a/products/logs/backend/temporal/activities.py+++ b/products/logs/backend/temporal/activities.py@@ -20,12 +20,16 @@ from pydantic import ValidationError as PydanticValidationErrorfrom posthog.schema import PropertyGroupFilter-from posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_eventfrom posthog.exceptions_capture import capture_exceptionfrom posthog.kafka_client.client import ProduceResultfrom posthog.models import Teamfrom posthog.sync import database_sync_to_async_pool+from products.alerts.backend.destinations import (+ alert_internal_event_delivered,+ flush_alert_internal_events,+ produce_alert_internal_event,+)from products.logs.backend.alert_check_query import (AlertCheckQuery,BatchedAlertCheckQuery,@@ -931,31 +935,21 @@ def _resolve_notification_deliveries(dispatched: list[_DispatchedAlert]) -> listif all(d.produce_result is None for d in dispatched):return dispatched- try:- remaining = flush_internal_events_producer(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)- if remaining:- logger.warning("Kafka flush timed out with undelivered messages", remaining=remaining)- except Exception as e:- logger.exception("Kafka flush failed", error=str(e))- capture_exception(e, {"phase": "notification_flush"})+ flush_alert_internal_events(NOTIFICATION_FLUSH_TIMEOUT_SECONDS)resolved: list[_DispatchedAlert] = []for d in dispatched:if d.produce_result is None:resolved.append(d)continue- try:- # Delivery callbacks only fire while flush()/poll() pumps the queue,- # so after the flush above each result is already resolved or never- # will be this cycle — timeout=0 reads the outcome without blocking.- d.produce_result.get(timeout=0)+ 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)- except Exception:- logger.warning(- "Notification not delivered before flush deadline; rolling back state for retry",- alert_id=str(d.evaluation.alert.id),- team_id=d.evaluation.alert.team_id,- )+ else:resolved.append(dataclasses.replace(d, notification_failed=True))return resolved@@ -1314,19 +1308,12 @@ def _produce_alert_internal_event(properties: dict,now: datetime,) -> ProduceResult | None:- try:- return produce_internal_event(- team_id=alert.team_id,- event=InternalEventEvent(- event=event_name,- distinct_id=f"team_{alert.team_id}",- properties=properties,- timestamp=now.isoformat(),- ),- )- except Exception as e:- capture_exception(e, {"alert_id": str(alert.id), "event": event_name})- return None+ return produce_alert_internal_event(+ team_id=alert.team_id,+ event_name=event_name,+ properties=properties,+ timestamp=now,+ )def _emit_alert_event(diff --git a/products/logs/backend/test/test_alert_destinations.py b/products/logs/backend/test/test_alert_destinations.pyindex af8341d9580e..f329d67794ae 100644--- a/products/logs/backend/test/test_alert_destinations.py+++ b/products/logs/backend/test/test_alert_destinations.py@@ -1,8 +1,60 @@+from typing import cast+from django.test import SimpleTestCasefrom parameterized import parameterized-from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EVENT_KINDS, EventKind, _slack_body, _teams_text+from products.alerts.backend.destination_configs import (+ AlertDestinationData,+ AlertDestinationValidationError,+ DestinationType,+ slack_body as _slack_body,+ teams_text as _teams_text,+ validate_destination_data,+)+from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EVENT_KINDS, LOGS_DESTINATION_TYPES, EventKind+++class TestDestinationValidation(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "multiple_slack_fields",+ {"type": DestinationType.SLACK},+ None,+ "Slack destinations require slack_workspace_id and slack_channel_id.",+ ),+ (+ "teams_webhook_url",+ {"type": DestinationType.TEAMS},+ "webhook_url",+ "webhook_url is required for Microsoft Teams destinations.",+ ),+ ]+ )+ def test_reports_missing_destination_fields(+ self,+ _name: str,+ data: AlertDestinationData,+ expected_field: str | None,+ expected_message: str,+ ) -> None:+ with self.assertRaises(AlertDestinationValidationError) as error:+ validate_destination_data(data, allowed_destination_types=LOGS_DESTINATION_TYPES)++ assert error.exception.field == expected_field+ assert error.exception.message == expected_message++ def test_reports_unsupported_destination_type(self) -> None:+ data = cast(AlertDestinationData, {"type": "email"})++ with self.assertRaises(AlertDestinationValidationError) as error:+ validate_destination_data(data, allowed_destination_types=LOGS_DESTINATION_TYPES)++ assert error.exception.field == "type"+ assert error.exception.message == (+ "Choose a supported destination type: Slack (slack), Webhook (webhook), Microsoft Teams (teams)."+ )class TestSlackBody(SimpleTestCase):@@ -35,7 +87,7 @@ class TestTeamsText(SimpleTestCase):assert text.startswith(f"**{spec.header}**")for label, value in spec.details:assert f"**{label}:** {value}" in text- assert f"[{spec.button_label}]({spec.button_url})" in text+ assert f"[{spec.primary_action_label}]({spec.primary_action_url})" in text# Every asterisk must belong to a `**` pair — no Slack-style single-asterisk bold.assert "*" not in text.replace("**", "")diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 934398f1478f..88e94230ec3c 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -11,13 +11,22 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.cdp.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teams+from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.clickhouse.client import sync_executefrom posthog.models.team.team import Team+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate+from products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCountfrom products.logs.backend.alert_utils import compute_shard_offset_secondsfrom products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent-from products.logs.backend.presentation.views.alerts_api import ALLOWED_WINDOW_MINUTES, MAX_ALERTS_PER_TEAM+from products.logs.backend.presentation.views.alerts_api import (+ ALLOWED_WINDOW_MINUTES,+ LOGS_ALERT_EVENT_IDS,+ MAX_ALERTS_PER_TEAM,+)def _make_log_row(*, team_id: int, service: str, uuid: str, ts: datetime, body: str) -> dict:@@ -72,9 +81,10 @@ class TestLogsAlertAPI(APIBaseTest):assert data["filters"] == {"severityLevels": ["error"]}mock_report.assert_called_once()- assert mock_report.call_args[0][1] == "logs alert created"- assert mock_report.call_args[0][2]["name"] == "High error rate"- assert mock_report.call_args[0][2]["threshold_count"] == 10+ assert mock_report.call_args.args[1] == "alert created"+ assert mock_report.call_args.args[2]["config_type"] == "LogsAlertConfig"+ assert mock_report.call_args.args[2]["alert_name"] == "High error rate"+ assert mock_report.call_args.args[2]["threshold_count"] == 10def test_list(self):self._create_via_api(name="Alert 1")@@ -186,21 +196,22 @@ class TestLogsAlertAPI(APIBaseTest):assert response.json()["name"] == "Patched"mock_report.assert_called_once()- assert mock_report.call_args[0][1] == "logs alert updated"- assert mock_report.call_args[0][2]["name"] == "Patched"+ assert mock_report.call_args.args[1] == "alert updated"+ assert mock_report.call_args.args[2]["alert_name"] == "Patched"@patch("products.logs.backend.presentation.views.alerts_api.report_user_action")def test_delete(self, mock_report):created = self._create_via_api()mock_report.reset_mock()- response = self.client.delete(f"{self.base_url}{created['id']}/")+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.delete(f"{self.base_url}{created['id']}/")assert response.status_code == status.HTTP_204_NO_CONTENTassert not LogsAlertConfiguration.objects.filter(pk=created["id"]).exists()mock_report.assert_called_once()- assert mock_report.call_args[0][1] == "logs alert deleted"- assert mock_report.call_args[0][2]["name"] == "High error rate"+ assert mock_report.call_args.args[1] == "alert deleted"+ assert mock_report.call_args.args[2]["alert_name"] == "High error rate"# --- Team isolation ---@@ -722,13 +733,7 @@ class TestLogsAlertAPI(APIBaseTest):def _sync_destination_templates(self) -> None:# Destination creation goes through the full HogFunctionSerializer pipeline,- # which looks up a HogFunctionTemplate by template_id. Seed Slack + Teams + webhook.- from posthog.cdp.templates.hog_function_template import sync_template_to_db- from posthog.cdp.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teams- from posthog.cdp.templates.slack.template_slack import template as template_slack-- from products.cdp.backend.models.hog_function_template import HogFunctionTemplate-+ # which looks up a HogFunctionTemplate by template_id.sync_template_to_db(template_slack)sync_template_to_db(template_microsoft_teams)HogFunctionTemplate.objects.get_or_create(@@ -750,8 +755,6 @@ class TestLogsAlertAPI(APIBaseTest):@patch("products.logs.backend.presentation.views.alerts_api.report_user_action")def test_create_slack_destination_creates_one_hog_function_per_event_kind(self, mock_report):self._sync_destination_templates()- from products.cdp.backend.models.hog_functions.hog_function import HogFunction-created = self._create_via_api()response = self.client.post(self._destinations_url(created["id"]),@@ -793,19 +796,26 @@ class TestLogsAlertAPI(APIBaseTest):reset_calls = [c for c in mock_report.call_args_list if c.args[1] == "logs alert destination created"]assert len(reset_calls) == 1- def test_create_webhook_destination_creates_one_hog_function_per_event_kind(self):- from products.cdp.backend.models.hog_functions.hog_function import HogFunction-+ @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")+ def test_create_webhook_destination_creates_one_hog_function_per_event_kind(+ self, signal_reload_hog_functions, alert_reload_hog_functions+ ):self._sync_destination_templates()created = self._create_via_api()- response = self.client.post(- self._destinations_url(created["id"]),- {"type": "webhook", "webhook_url": "https://example.com/hook"},- format="json",- )+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ self._destinations_url(created["id"]),+ {"type": "webhook", "webhook_url": "https://example.com/hook"},+ format="json",+ )+ assert signal_reload_hog_functions.call_count == 4+ alert_reload_hog_functions.assert_not_called()+assert response.status_code == status.HTTP_201_CREATED, response.json()ids = response.json()["hog_function_ids"]assert len(ids) == 4 # firing + resolved + broken + errored+ alert_reload_hog_functions.assert_called_once_with(team_id=self.team.id, hog_function_ids=sorted(ids))hog_functions = HogFunction.objects.filter(id__in=ids)for hf in hog_functions:@@ -821,8 +831,6 @@ class TestLogsAlertAPI(APIBaseTest):)def test_create_teams_destination_creates_one_hog_function_per_event_kind(self):- from products.cdp.backend.models.hog_functions.hog_function import HogFunction-self._sync_destination_templates()created = self._create_via_api()teams_url = "https://prod-00.westus.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke?api-version=2016-06-01"@@ -872,9 +880,8 @@ class TestLogsAlertAPI(APIBaseTest):)assert response.status_code == status.HTTP_404_NOT_FOUND- def test_delete_destination_removes_hog_functions(self):- from products.cdp.backend.models.hog_functions.hog_function import HogFunction-+ @patch("products.alerts.backend.destinations.reload_hog_functions_on_workers")+ def test_delete_destination_removes_hog_functions(self, reload_hog_functions):self._sync_destination_templates()created = self._create_via_api()create_response = self.client.post(@@ -884,13 +891,34 @@ class TestLogsAlertAPI(APIBaseTest):)ids = create_response.json()["hog_function_ids"]- delete_response = self.client.post(- self._destinations_delete_url(created["id"]),- {"hog_function_ids": ids},+ with self.captureOnCommitCallbacks(execute=True):+ delete_response = self.client.post(+ self._destinations_delete_url(created["id"]),+ {"hog_function_ids": ids},+ format="json",+ )+ reload_hog_functions.assert_not_called()++ assert delete_response.status_code == status.HTTP_204_NO_CONTENT+ assert HogFunction.objects.filter(id__in=ids, deleted=False).count() == 0+ assert HogFunction.objects.filter(id__in=ids, enabled=True).count() == 0+ reload_hog_functions.assert_called_once_with(team_id=self.team.id, hog_function_ids=sorted(ids))++ def test_delete_alert_soft_deletes_destination_hog_functions(self):+ self._sync_destination_templates()+ created = self._create_via_api()+ create_response = self.client.post(+ self._destinations_url(created["id"]),+ {"type": "webhook", "webhook_url": "https://example.com/hook"},format="json",)+ ids = create_response.json()["hog_function_ids"]++ delete_response = self.client.delete(f"{self.base_url}{created['id']}/")assert delete_response.status_code == status.HTTP_204_NO_CONTENT+ assert not LogsAlertConfiguration.objects.filter(id=created["id"]).exists()assert HogFunction.objects.filter(id__in=ids, deleted=False).count() == 0+ assert HogFunction.objects.filter(id__in=ids, enabled=True).count() == 0def test_delete_destination_rejects_foreign_hog_function_ids(self):self._sync_destination_templates()@@ -908,13 +936,29 @@ class TestLogsAlertAPI(APIBaseTest):format="json",).json()["hog_function_ids"]- # Trying to delete alert A's HogFunctions via alert B's endpoint should fail.response = self.client.post(self._destinations_delete_url(created_b["id"]),- {"hog_function_ids": a_ids + b_ids},+ {"hog_function_ids": [a_ids[0], b_ids[0]]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "hog_function_ids"+ message = response.json()["detail"]+ assert a_ids[0] in message+ assert b_ids[0] not in message+ assert "Refresh the alert and try again." in message++ def test_delete_destination_rejects_more_ids_than_one_destination_group(self):+ created = self._create_via_api()++ response = self.client.post(+ self._destinations_delete_url(created["id"]),+ {"hog_function_ids": [str(uuid4()) for _ in range(len(LOGS_ALERT_EVENT_IDS) + 1)]},format="json",)+assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "hog_function_ids"# --- Reset ---@@ -1731,7 +1775,7 @@ class TestSimulateEvaluatorLifecycleParity(ClickhouseTestMixin, APIBaseTest):# A None return would read as "enqueue failed" and roll back every# notification, so the fake must return a (mock) ProduceResult.self._kafka_patcher = patch(- "products.logs.backend.temporal.activities.produce_internal_event",+ "products.alerts.backend.destinations.produce_internal_event",return_value=MagicMock(),)self._kafka_patcher.start()@@ -2041,10 +2085,13 @@ class TestLogsAlertAPIPersonalAPIKeyScopes(APIBaseTest):def test_create_destination_allowed_with_logs_write_scope(self):key = self.create_personal_api_key_with_scopes(["logs:write"])- # Detail action against a non-existent UUID: get_object 404s before the body runs,- # proving the scope gate passed (a bare `!= 403` would also pass on a 401/500).url = f"{self.base_url}{uuid4()}/destinations/"- response = self.client.post(url, {}, format="json", **self._auth(key))+ response = self.client.post(+ url,+ {"type": "webhook", "webhook_url": "https://example.com/hook"},+ format="json",+ **self._auth(key),+ )assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()@parameterized.expand(@@ -2065,7 +2112,12 @@ class TestLogsAlertAPIPersonalAPIKeyScopes(APIBaseTest):def test_delete_destination_allowed_with_logs_write_scope(self):key = self.create_personal_api_key_with_scopes(["logs:write"])url = f"{self.base_url}{uuid4()}/destinations/delete/"- response = self.client.post(url, {}, format="json", **self._auth(key))+ response = self.client.post(+ url,+ {"hog_function_ids": [str(uuid4())]},+ format="json",+ **self._auth(key),+ )assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()@parameterized.expand(diff --git a/products/logs/backend/test/test_logs_alerting_activities.py b/products/logs/backend/test/test_logs_alerting_activities.pyindex 6a2e56286ec3..d4f3932bf4bb 100644--- a/products/logs/backend/test/test_logs_alerting_activities.py+++ b/products/logs/backend/test/test_logs_alerting_activities.py@@ -288,8 +288,11 @@ class TestResolveNotificationDeliveries(unittest.TestCase):("still_pending_after_flush", TimeoutError("undelivered"), True),])- @patch("products.logs.backend.temporal.activities.flush_internal_events_producer", return_value=0)- def test_folds_delivery_outcome_into_notification_failed(self, _name, get_side_effect, expect_failed, mock_flush):+ @patch("products.alerts.backend.destinations.flush_internal_events_producer", return_value=0)+ @patch("products.alerts.backend.destinations.capture_exception")+ def test_folds_delivery_outcome_into_notification_failed(+ self, _name, get_side_effect, expect_failed, _mock_capture, mock_flush+ ):from products.logs.backend.temporal.activities import _resolve_notification_deliveriesresult = MagicMock()@@ -301,7 +304,7 @@ class TestResolveNotificationDeliveries(unittest.TestCase):assert resolved[0].notification_failed is expect_failedmock_flush.assert_called_once()- @patch("products.logs.backend.temporal.activities.flush_internal_events_producer")+ @patch("products.alerts.backend.destinations.flush_internal_events_producer")def test_skips_flush_when_nothing_was_produced(self, mock_flush):from products.logs.backend.temporal.activities import _resolve_notification_deliveries@@ -312,9 +315,9 @@ class TestResolveNotificationDeliveries(unittest.TestCase):assert resolved == [dispatched]mock_flush.assert_not_called()- @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch("products.alerts.backend.destinations.capture_exception")@patch(- "products.logs.backend.temporal.activities.flush_internal_events_producer",+ "products.alerts.backend.destinations.flush_internal_events_producer",side_effect=Exception("kafka down"),)def test_flush_failure_does_not_raise_and_marks_pending_failed(self, mock_flush, _mock_capture):@@ -640,7 +643,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_threshold_breached_transitions_to_firing(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -658,7 +661,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_threshold_not_breached_stays_not_firing(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert()@@ -675,7 +678,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_steady_state_writes_no_alert_event(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5]) # below threshold → stays NOT_FIRINGalert = self._make_alert()@@ -686,7 +689,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_creates_event_row(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -707,7 +710,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_advances_next_check_at(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(next_check_at=datetime(2025, 1, 1, 0, 0, 0, tzinfo=UTC))@@ -721,7 +724,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")@patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,@@ -748,7 +751,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_emit_event_uses_team_distinct_id(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -762,7 +765,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_last_notified_at_set_after_kafka_success(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -776,8 +779,8 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))+ @patch("products.alerts.backend.destinations.capture_exception")def test_last_notified_at_not_set_on_kafka_failure(self, mock_capture, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -800,7 +803,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_threshold_operators(self, _name, operator, count, should_fire, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [count])alert = self._make_alert(threshold_operator=operator, threshold_count=10)@@ -819,7 +822,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_resolution_emits_resolved_event(self, mock_produce, mock_query_cls):alert = self._make_alert(state=LogsAlertConfiguration.State.FIRING)# First check breached to create an event row for get_recent_breaches@@ -841,7 +844,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_cooldown_suppresses_notification(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [50])alert = self._make_alert(@@ -860,7 +863,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_n_of_m_requires_multiple_breaches_to_fire(self, mock_produce, mock_query_cls):# Stateless eval: a single bucketed query returns the M-bucket history.# State machine derives the N-of-M decision from those buckets directly.@@ -890,7 +893,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_event_properties_include_logs_url_params(self, mock_produce, mock_query_cls):alert = self._make_alert(threshold_count=5,@@ -911,7 +914,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_logs_url_params_includes_absolute_date_range(self, mock_produce, mock_query_cls):alert = self._make_alert(threshold_count=5,@@ -930,7 +933,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_resolution_within_cooldown_suppresses_resolved_event(self, mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [0])alert = self._make_alert(@@ -986,7 +989,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_break_on_consecutive_failures(self,_name,@@ -1032,7 +1035,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_state_transition")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_state_transition_counter_fires_on_state_change(self, _mock_produce, mock_query_cls, mock_transition):_mock_buckets(mock_query_cls, [50])alert = self._make_alert()@@ -1044,7 +1047,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_state_transition")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_state_transition_counter_silent_when_state_unchanged(self, _mock_produce, mock_query_cls, mock_transition):_mock_buckets(mock_query_cls, [5])self._make_alert()@@ -1064,8 +1067,8 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))+ @patch("products.alerts.backend.destinations.capture_exception")def test_notification_failures_counter(self,expected_action_name,@@ -1088,7 +1091,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_notification_failures_silent_on_success(self, _mock_produce, mock_query_cls, mock_notif_failures):_mock_buckets(mock_query_cls, [50])self._make_alert()@@ -1110,7 +1113,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_check_errors")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_check_errors_counter_labelled_by_classifier(self,expected_category,@@ -1135,7 +1138,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_check_errors")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_check_errors_counter_silent_on_success(self, _mock_produce, mock_query_cls, mock_check_errors):_mock_buckets(mock_query_cls, [5])self._make_alert()@@ -1148,7 +1151,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_query_uses_checkpoint_as_date_to_when_in_past(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(window_minutes=5)@@ -1163,7 +1166,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_query_uses_now_when_checkpoint_is_in_future(self, _mock_produce, mock_query_cls):# Defensive case: if clocks are skewed so checkpoint > now, don't query the future._mock_buckets(mock_query_cls, [5])@@ -1179,7 +1182,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_query_uses_now_when_checkpoint_is_none(self, _mock_produce, mock_query_cls):_mock_buckets(mock_query_cls, [5])alert = self._make_alert(window_minutes=5)@@ -1193,7 +1196,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T01:00:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_query_ignores_stale_checkpoint_quiet_partition_case(self, _mock_produce, mock_query_cls):# Quiet partitions pin min(max_observed_timestamp) backwards. If that's older than# CHECKPOINT_MAX_STALENESS we must ignore the checkpoint — otherwise a spike of@@ -1219,7 +1222,7 @@ class TestEvaluateSingleAlert(APIBaseTest):)@freeze_time("2025-01-01T05:00:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_date_from_covers_full_rolling_check_lookback(self, _name, window_minutes, evaluation_periods, expected_range_minutes, _mock_produce, mock_query_cls):@@ -1239,7 +1242,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_errored_notification_emitted_on_first_error(self, mock_produce, mock_query_cls):mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("Code: 160. DB::Exception: Estimated query execution time is too long"@@ -1277,7 +1280,7 @@ class TestEvaluateSingleAlert(APIBaseTest):# failure must then roll back the failure counter, or the second check# never sees the 0 -> 1 notify edge and the notification is lost.with (- patch("products.logs.backend.temporal.activities.produce_internal_event") as mock_produce,+ patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,@@ -1311,7 +1314,7 @@ class TestEvaluateSingleAlert(APIBaseTest):now2 = datetime(2025, 1, 1, 0, 6, 0, tzinfo=UTC)with (- patch("products.logs.backend.temporal.activities.produce_internal_event") as mock_produce,+ patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,@@ -1337,7 +1340,7 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch("products.alerts.backend.destinations.capture_exception")def test_broken_notification_retried_after_kafka_failure(self, _mock_capture, mock_query_cls):mock_query_cls.return_value.execute_rolling_checks.side_effect = Exception("Code: 160. DB::Exception: Estimated query execution time is too long"@@ -1348,7 +1351,7 @@ class TestEvaluateSingleAlert(APIBaseTest):now2 = datetime(2025, 1, 1, 0, 6, 0, tzinfo=UTC)with (- patch("products.logs.backend.temporal.activities.produce_internal_event") as mock_produce,+ patch("products.alerts.backend.destinations.produce_internal_event") as mock_produce,patch("products.logs.backend.alert_error_classifier.classify_query_error",return_value=QueryErrorCategory.QUERY_PERFORMANCE_ERROR,@@ -1377,8 +1380,8 @@ class TestEvaluateSingleAlert(APIBaseTest):@freeze_time("2025-01-01T00:01:00Z")@patch("products.logs.backend.temporal.activities.increment_notification_failures")@patch("products.logs.backend.temporal.activities.AlertCheckQuery")- @patch("products.logs.backend.temporal.activities.produce_internal_event", side_effect=Exception("Kafka down"))- @patch("products.logs.backend.temporal.activities.capture_exception")+ @patch("products.alerts.backend.destinations.produce_internal_event", side_effect=Exception("Kafka down"))+ @patch("products.alerts.backend.destinations.capture_exception")def test_notification_failures_counter_for_error_and_broken(self,_name,@@ -1521,7 +1524,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):"""@freeze_time("2025-12-16T10:33:00Z")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_breach_against_real_clickhouse_fires_alert(self, _mock_produce):# Five logs at 10:30 with a unique service. next_check_at=10:33,# window=5, M=1 → activity's query window is [10:28, 10:33), capturing@@ -1585,7 +1588,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):return LogsAlertConfiguration.objects.create(**defaults)@freeze_time("2025-12-16T10:35:00Z")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_n_of_m_progression_across_consecutive_evals(self, _mock_produce):# Real-CH version of the N-of-M progression test. M=3 N=2 over 5-min buckets.# Symmetric N-of-M: stays firing while breach_count >= N, resolves only@@ -1646,7 +1649,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):assert alert.state == LogsAlertConfiguration.State.NOT_FIRING@freeze_time("2025-12-16T10:25:00Z")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_cooldown_suppresses_resolve_notification_within_window(self, mock_produce):# Alert fires at next_check_at #1, resolve attempted at next_check_at #2# within cooldown_minutes → state transitions to NOT_FIRING but@@ -1679,7 +1682,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):assert mock_produce.call_count == 1 # but no second notification dispatched@freeze_time("2025-12-16T10:33:00Z")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_below_operator_fires_on_truly_silent_service(self, _mock_produce):# `execute_rolling_checks` always returns exactly `period_count` entries (zero# counts for silent services, since each period is a fixed-width@@ -1701,7 +1704,7 @@ class TestEvaluateSingleAlertEndToEnd(ClickhouseTestMixin, APIBaseTest):)@freeze_time("2025-12-16T10:33:00Z")- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.produce_internal_event")def test_first_run_with_null_nca_anchors_on_now(self, _mock_produce):# Alert created with next_check_at=None (first eval after enable). The# activity falls back to `now` as the anchor; the query window is@@ -2135,8 +2138,8 @@ class TestEvaluateCohortBatchActivity(NonAtomicBaseTest):assert result.alerts_checked == 1@freeze_time("2025-01-01T00:01:00Z")- @patch("products.logs.backend.temporal.activities.flush_internal_events_producer", return_value=0)- @patch("products.logs.backend.temporal.activities.produce_internal_event")+ @patch("products.alerts.backend.destinations.flush_internal_events_producer", return_value=0)+ @patch("products.alerts.backend.destinations.produce_internal_event")@patch("products.logs.backend.temporal.activities._run_cohort_query")def test_undelivered_notification_rolls_back_state_before_save(self, mock_run_cohort_query, mock_produce, _mock_flushdiff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsxindex f8f2e7c1cf2d..801fd902f929 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx@@ -33,11 +33,34 @@ import { LogsAlertStateIndicator } from './LogsAlertStateIndicator'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 },+] as const+function formatThreshold(alert: LogsAlertConfigurationApi): string {const operator = alert.threshold_operator === LogsAlertThresholdOperatorEnumApi.Below ? '<' : '>'return `${operator} ${alert.threshold_count} in ${alert.window_minutes}m`}+export function LogsAlertDestinationTags({+ types,+}: {+ types: readonly NotificationDestinationTypeEnumApi[]+}): JSX.Element {+ return (+ <div className="flex gap-1">+ {DESTINATION_TAGS.filter(({ type }) => types.includes(type)).map(({ type, label, icon }) => (+ <LemonTag key={type}>+ <img src={icon} alt="" className="h-3 w-3 object-contain" />+ {label}+ </LemonTag>+ ))}+ </div>+ )+}+export function LogsAlertList(): JSX.Element {const { alerts, alertsLoading, resettingAlertIds, creatingAlert } = useValues(logsAlertingLogic)const {@@ -139,26 +162,7 @@ export function LogsAlertList(): JSX.Element {}return (<div className="flex items-center gap-1">- <div className="flex gap-1">- {types.includes(NotificationDestinationTypeEnumApi.Slack) && (- <LemonTag>- <img src={IconSlack} alt="" className="h-3 w-3 object-contain" />- Slack- </LemonTag>- )}- {types.includes(NotificationDestinationTypeEnumApi.Webhook) && (- <LemonTag>- <img src={IconWebhook} alt="" className="h-3 w-3 object-contain" />- Webhook- </LemonTag>- )}- {types.includes(NotificationDestinationTypeEnumApi.Teams) && (- <LemonTag>- <img src={IconMicrosoftTeams} alt="" className="h-3 w-3 object-contain" />- Teams- </LemonTag>- )}- </div>+ <LogsAlertDestinationTags types={types} /><LemonButtonsize="small"type="tertiary"diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.tsindex e70c17284f2e..af7828786363 100644--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertUtils.test.ts@@ -53,6 +53,7 @@ describe('logsAlertUtils', () => {id,name: `slack-${id}`,enabled,+ template: { id: 'template-slack' },inputs: { channel: { value: channel } },filters: {},}) as unknown as HogFunctionType@@ -62,16 +63,17 @@ describe('logsAlertUtils', () => {id,name: `webhook-${id}`,enabled,+ template: { id: 'template-webhook' },inputs: { url: { value: url } },filters: {},}) as unknown as HogFunctionType- // The Microsoft Teams template stores its URL under `webhookUrl`, not `url`.const teamsHf = (id: string, url: string, enabled = true): HogFunctionType =>({id,name: `teams-${id}`,enabled,+ template: { id: 'template-microsoft-teams' },inputs: { webhookUrl: { value: url } },filters: {},}) as unknown as HogFunctionTypediff --git a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.tsindex 134c925352c6..5de26a3b272c 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertUtils.ts@@ -239,27 +239,27 @@ export function groupLogsAlertDestinations(): LogsAlertDestinationGroup[] {const groups = new Map<string, LogsAlertDestinationGroup>()for (const hf of hogFunctions) {- const slackChannelValue = hf.inputs?.channel?.value- // The Microsoft Teams template stores its URL under `webhookUrl`; the generic webhook uses `url`.- const teamsUrl = hf.inputs?.webhookUrl?.value- const webhookUrl = hf.inputs?.url?.value+ const templateId = hf.template_id ?? hf.template?.id+ const slackChannelValue = hf.inputs?.channel?.value as string | undefined+ const destinationWebhookUrl = hf.inputs?.webhookUrl?.value as string | undefined+ const webhookUrl = hf.inputs?.url?.value as string | undefinedlet key: stringlet type: LogsAlertNotificationTypelet label: string- if (typeof slackChannelValue === 'string') {+ if (templateId === 'template-slack') {type = LOGS_ALERT_NOTIFICATION_TYPE_SLACK- key = `slack:${slackChannelValue}`- const channelName = resolveSlackLabel(slackChannelValue)+ key = `slack:${slackChannelValue ?? hf.id}`+ const channelName = slackChannelValue ? resolveSlackLabel(slackChannelValue) : nulllabel = channelName ? `Slack #${channelName}` : 'Slack'- } else if (typeof teamsUrl === 'string') {+ } else if (templateId === 'template-microsoft-teams') {type = LOGS_ALERT_NOTIFICATION_TYPE_TEAMS- key = `teams:${teamsUrl}`- label = `Microsoft Teams ${teamsUrl}`- } else if (typeof webhookUrl === 'string') {+ key = `teams:${destinationWebhookUrl ?? hf.id}`+ label = destinationWebhookUrl ? `Microsoft Teams ${destinationWebhookUrl}` : 'Microsoft Teams'+ } else if (templateId === 'template-webhook') {type = LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOK- key = `webhook:${webhookUrl}`- label = `Webhook ${webhookUrl}`+ key = `webhook:${webhookUrl ?? hf.id}`+ label = webhookUrl ? `Webhook ${webhookUrl}` : 'Webhook'} else {type = LOGS_ALERT_NOTIFICATION_TYPE_WEBHOOKkey = `unknown:${hf.id}`diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 3568d3cd9eb9..a68a1710d633 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -647,7 +647,7 @@ export interface PatchedLogsAlertConfigurationApi {}export interface LogsAlertCreateDestinationApi {- /** Destination type — slack, webhook, or teams.+ /** Notification destination type.** * `slack` - slack* * `webhook` - webhook@@ -659,7 +659,7 @@ export interface LogsAlertCreateDestinationApi {slack_channel_id?: string/** Human-readable channel name for display. */slack_channel_name?: string- /** HTTPS endpoint to POST to. Required when type=webhook, or the Teams webhook URL when type=teams. */+ /** HTTPS endpoint to post to. Required for webhook and teams. */webhook_url?: string}@@ -671,6 +671,7 @@ export interface LogsAlertDeleteDestinationApi {/*** HogFunction IDs to delete as one atomic destination group.* @minItems 1+ * @maxItems 4*/hog_function_ids: string[]}diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 072bb706bb12..a4275f443539 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -298,29 +298,26 @@ export const LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({type: zod.enum(['slack', 'webhook', 'teams']).describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')- .describe(- 'Destination type — slack, webhook, or teams.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'- ),+ .describe('Notification destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'),slack_workspace_id: zod.number().optional().describe('Integration ID for the Slack workspace. Required when type=slack.'),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 when type=webhook, or the Teams webhook URL when type=teams.'),+ webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook and teams.'),})/*** Delete a notification destination by deleting its HogFunction group atomically.*/+export const logsAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4export const LogsAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({hog_function_ids: zod.array(zod.uuid()).min(1)+ .max(logsAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax).describe('HogFunction IDs to delete as one atomic destination group.'),})diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yamlindex e2e716cd7d23..8520d6a0d837 100644--- a/products/logs/mcp/tools.yaml+++ b/products/logs/mcp/tools.yaml@@ -67,9 +67,22 @@ tools:idempotent: falsetitle: Attach alert destinationdescription: >- Attach a notification destination (Slack channel or webhook) 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, 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.+ 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.+ slack_workspace_id:+ description: Slack workspace integration ID. Required when type is slack.+ slack_channel_id:+ description: Slack channel ID. Required when type is slack.+ slack_channel_name:+ description: Optional Slack channel name used for display.+ webhook_url:+ description: Required when type is webhook or teams.feature_flag: logs-alertingresponse:include:diff --git a/products/logs/skills/authoring-log-alerts/SKILL.md b/products/logs/skills/authoring-log-alerts/SKILL.mdindex bc3d7d5c07e4..0d75bf91cb26 100644--- a/products/logs/skills/authoring-log-alerts/SKILL.md+++ b/products/logs/skills/authoring-log-alerts/SKILL.md@@ -33,7 +33,7 @@ are trying to land thresholds that fire 0–3 times per week on real production| `posthog:logs-count-ranges` | Adaptive time-bucketed counts for a filter. | Step 3 — baseline. || `posthog:logs-alerts-simulate-create` | Replay a draft config against `-7d` history with full state machine. | Step 4 — validate. || `posthog:logs-alerts-create` | Persist the alert. | Step 5 — ship. |-| `posthog:logs-alerts-destinations-create` | Wire the alert to Slack or webhook. | Step 5 — ship. |+| `posthog:logs-alerts-destinations-create` | Wire the alert to Slack, webhook, or Microsoft Teams. | Step 5: ship. |Do **not** call `posthog:query-logs` during authoring. You need distributions, not rows. Reserve `posthog:query-logs` forthe very end if the user asks "show me a sample of what would have fired" — `limit: 10` is plenty.@@ -143,7 +143,12 @@ Once a draft simulates cleanly:1. Call `posthog:logs-alerts-create` with the validated config. Use a name like `<service> error rate (auto)` so theuser can see at a glance which alerts came from this skill.2. Call `posthog:logs-alerts-destinations-create` to wire it to a notification target. **An alert with no destination- is silent.** Always confirm the channel name or webhook URL with the user before attaching — never wire+ is silent.** Supported destination fields:+ - Slack: `type: "slack"`, `slack_workspace_id`, and `slack_channel_id`. `slack_channel_name` is optional.+ - Webhook: `type: "webhook"` and `webhook_url`.+ - Microsoft Teams: `type: "teams"` and `webhook_url`.++ Always confirm the channel name or webhook URL with the user before attaching. Never wirean auto-generated alert to a production channel without explicit confirmation. If the user is unsure,suggest a low-traffic testing channel for the first few alerts.diff --git a/pyproject.toml b/pyproject.tomlindex 86595dcc744c..17d1e0a83e77 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -570,7 +570,6 @@ ignore_imports = [# still make directly. These resolve once cdp/exports expose the needed facades, so# they outlive the in-product cleanup above."products.logs.backend.presentation.views.api -> products.exports.backend.models.exported_asset",- "products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.api.hog_function","products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.models.hog_functions.hog_function",# TODO: notebooks presentation wave — the moved NotebookViewSet still reaches in-product# internals (collab, kernel runtime, query validation, models) and the tasks sandboxdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex c3719250b6bf..14aa139c60bd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5443,7 +5443,7 @@"feature_flag": "logs-alerting"},"logs-alerts-destinations-create": {- "description": "Attach a notification destination (Slack channel or webhook) 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, 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.","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 3a3538580cb3..970069872fbf 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5878,7 +5878,7 @@"feature_flag": "logs-alerting"},"logs-alerts-destinations-create": {- "description": "Attach a notification destination (Slack channel or webhook) 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, 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.","category": "Logs","feature": "logs","summary": "Attach alert destination",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 599478fd1c29..f5b440e949ee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -32760,7 +32760,7 @@ export namespace Schemas {}export interface LogsAlertCreateDestination {- /** Destination type — slack, webhook, or teams.+ /** Notification destination type.** * `slack` - slack* * `webhook` - webhook@@ -32772,7 +32772,7 @@ export namespace Schemas {slack_channel_id?: string;/** Human-readable channel name for display. */slack_channel_name?: string;- /** HTTPS endpoint to POST to. Required when type=webhook, or the Teams webhook URL when type=teams. */+ /** HTTPS endpoint to post to. Required for webhook and teams. */webhook_url?: string;}@@ -32780,6 +32780,7 @@ export namespace Schemas {/*** HogFunction IDs to delete as one atomic destination group.* @minItems 1+ * @maxItems 4*/hog_function_ids: string[];}diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 37eb1e3e1a8c..3ea527c04cc8 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -2483,19 +2483,14 @@ export const LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({type: zod.enum(['slack', 'webhook', 'teams']).describe('* `slack` - slack\n* `webhook` - webhook\n* `teams` - teams')- .describe(- 'Destination type — slack, webhook, or teams.\n\n* `slack` - slack\n* `webhook` - webhook\n* `teams` - teams'- ),+ .describe('Notification destination type.\n\n* `slack` - slack\n* `webhook` - webhook\n* `teams` - teams'),slack_workspace_id: zod.number().optional().describe('Integration ID for the Slack workspace. Required when type=slack.'),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 when type=webhook, or the Teams webhook URL when type=teams.'),+ webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook and teams.'),})/**@@ -2510,10 +2505,13 @@ export const LogsAlertsDestinationsDeleteCreateParams = /* @__PURE__ */ zod.obje),})+export const logsAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4+export const LogsAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({hog_function_ids: zod.array(zod.string()).min(1)+ .max(logsAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax).describe('HogFunction IDs to delete as one atomic destination group.'),})diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex 2ddf77e44915..d84fdd89b651 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -99,9 +99,25 @@ const logsAlertsCreate = (): ToolBase<typeof LogsAlertsCreateSchema, Schemas.Log},})-const LogsAlertsDestinationsCreateSchema = LogsAlertsDestinationsCreateParams.omit({ project_id: true }).extend(- LogsAlertsDestinationsCreateBody.shape-)+const LogsAlertsDestinationsCreateSchema = LogsAlertsDestinationsCreateParams.omit({ project_id: true })+ .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.'+ ),+ slack_workspace_id: LogsAlertsDestinationsCreateBody.shape['slack_workspace_id'].describe(+ 'Slack workspace integration ID. Required when type is slack.'+ ),+ slack_channel_id: LogsAlertsDestinationsCreateBody.shape['slack_channel_id'].describe(+ 'Slack channel ID. Required when type is slack.'+ ),+ slack_channel_name: LogsAlertsDestinationsCreateBody.shape['slack_channel_name'].describe(+ 'Optional Slack channel name used for display.'+ ),+ webhook_url: LogsAlertsDestinationsCreateBody.shape['webhook_url'].describe(+ 'Required when type is webhook or teams.'+ ),+ })const logsAlertsDestinationsCreate = (): ToolBase<typeof LogsAlertsDestinationsCreateSchema,diff --git a/tach.toml b/tach.tomlindex 90b95e91156a..a5fb1c50cba8 100644--- a/tach.toml+++ b/tach.toml@@ -425,6 +425,7 @@ layer = "modules"path = "products.logs"depends_on = ["posthog",+ "products.alerts","products.cdp","products.exports","products.signals",