Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(alerts): key destination delete groups on config, not template (#84509)

Vasco de Krijger12ff0b2d1253
diff --git a/.agents/skills/adding-product-alerting/references/architecture.md b/.agents/skills/adding-product-alerting/references/architecture.md
index f236e7308a79..1c2dd1485b8b 100644
--- a/.agents/skills/adding-product-alerting/references/architecture.md
+++ b/.agents/skills/adding-product-alerting/references/architecture.md
@@ -66,9 +66,10 @@ Product-facing destination setup is exported from `products.alerts.backend.facad
- `soft_delete_all_alert_destinations`
- `send_alert_email`
-`EventKindSpec` describes destination-neutral content for one event kind. The shared builder converts it into Slack, Discord, webhook, or Microsoft Teams HogFunction payloads. Products own event IDs, event properties, wording, actions, and their allowed destination list.
+`EventKindSpec` describes destination-neutral content for one event kind. The shared builder converts it into a HogFunction payload through `DESTINATION_SPECS`, the registry where each destination type owns its template ID, required fields, input building, read-back, and read redaction. Adding a destination type means adding one entry there. Products own event IDs, event properties, wording, actions, and their allowed destination list.
Deletion is fail-closed. Always scope it with `team_id`, `alert_id`, and the product's allowed event IDs.
+`create_alert_destination_hog_functions` refuses any destination in the call that the alert already has, so call it with the alert row locked.
## Delivery contract
diff --git a/products/alerts/backend/destination_configs.py b/products/alerts/backend/destination_configs.py
index 22e8dd308804..e7751895d177 100644
--- a/products/alerts/backend/destination_configs.py
+++ b/products/alerts/backend/destination_configs.py
@@ -2,9 +2,11 @@
from __future__ import annotations
+from abc import ABC, abstractmethod
from collections.abc import Sequence
from dataclasses import dataclass
-from typing import Any, NotRequired, TypedDict
+from typing import Any, ClassVar, NotRequired, TypedDict
+from urllib.parse import urlsplit
from django.db import models
@@ -16,21 +18,6 @@ class DestinationType(models.TextChoices):
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]
@@ -152,6 +139,178 @@ def teams_text(spec: EventKindSpec) -> str:
return "\n\n".join(parts)
+def _input_value(inputs: dict[str, Any], key: str) -> Any:
+ entry = inputs.get(key)
+ return entry.get("value") if isinstance(entry, dict) else None
+
+
+class DestinationSpec(ABC):
+ """Everything one destination type knows about itself: how it is stored as a
+ HogFunction, how it is read back, and how it is safe to show in a read response."""
+
+ type: ClassVar[DestinationType]
+ template_id: ClassVar[str]
+ required_fields: ClassVar[tuple[str, ...]]
+
+ @abstractmethod
+ def build_name(self, data: AlertDestinationData) -> str: ...
+
+ @abstractmethod
+ def build_inputs(
+ self,
+ event_kind_spec: EventKindSpec,
+ data: AlertDestinationData,
+ *,
+ slack_context_elements: tuple[str, ...],
+ ) -> dict[str, Any]: ...
+
+ @abstractmethod
+ def read(self, inputs: dict[str, Any]) -> AlertDestinationData: ...
+
+ def redact(self, data: AlertDestinationData) -> AlertDestinationData:
+ return data
+
+
+class SlackDestination(DestinationSpec):
+ type = DestinationType.SLACK
+ template_id = "template-slack"
+ required_fields = ("slack_workspace_id", "slack_channel_id")
+
+ def build_name(self, data: AlertDestinationData) -> str:
+ return f"Slack #{data.get('slack_channel_name') or 'channel'}"
+
+ def build_inputs(
+ self,
+ event_kind_spec: EventKindSpec,
+ data: AlertDestinationData,
+ *,
+ slack_context_elements: tuple[str, ...],
+ ) -> dict[str, Any]:
+ return {
+ "blocks": {"value": slack_blocks(event_kind_spec, slack_context_elements)},
+ "text": {"value": event_kind_spec.header},
+ "slack_workspace": {"value": data["slack_workspace_id"]},
+ "channel": {"value": data["slack_channel_id"]},
+ }
+
+ def read(self, inputs: dict[str, Any]) -> AlertDestinationData:
+ data: AlertDestinationData = {"type": self.type}
+ slack_workspace_id = _input_value(inputs, "slack_workspace")
+ slack_channel_id = _input_value(inputs, "channel")
+ if isinstance(slack_workspace_id, int):
+ data["slack_workspace_id"] = slack_workspace_id
+ if isinstance(slack_channel_id, str):
+ data["slack_channel_id"] = slack_channel_id
+ return data
+
+
+class _WebhookUrlDestination(DestinationSpec):
+ """Base for the types whose whole configuration is one webhook URL."""
+
+ required_fields = ("webhook_url",)
+ url_input_key: ClassVar[str]
+
+ def read(self, inputs: dict[str, Any]) -> AlertDestinationData:
+ data: AlertDestinationData = {"type": self.type}
+ webhook_url = _input_value(inputs, self.url_input_key)
+ if isinstance(webhook_url, str):
+ data["webhook_url"] = webhook_url
+ return data
+
+ def redact(self, data: AlertDestinationData) -> AlertDestinationData:
+ webhook_url = data.get("webhook_url")
+ if webhook_url is None:
+ return data
+ redacted = data.copy()
+ redacted["webhook_url"] = _redact_url(webhook_url)
+ return redacted
+
+
+class WebhookDestination(_WebhookUrlDestination):
+ type = DestinationType.WEBHOOK
+ template_id = "template-webhook"
+ url_input_key = "url"
+
+ def build_name(self, data: AlertDestinationData) -> str:
+ return f"Webhook {data['webhook_url']}"
+
+ def build_inputs(
+ self,
+ event_kind_spec: EventKindSpec,
+ data: AlertDestinationData,
+ *,
+ slack_context_elements: tuple[str, ...],
+ ) -> dict[str, Any]:
+ return {
+ "body": {"value": event_kind_spec.webhook_body},
+ "url": {"value": data["webhook_url"]},
+ "headers": {"value": WEBHOOK_HEADERS},
+ }
+
+
+class DiscordDestination(_WebhookUrlDestination):
+ type = DestinationType.DISCORD
+ template_id = "template-discord"
+ url_input_key = "webhookUrl"
+
+ def build_name(self, data: AlertDestinationData) -> str:
+ return "Discord"
+
+ def build_inputs(
+ self,
+ event_kind_spec: EventKindSpec,
+ data: AlertDestinationData,
+ *,
+ slack_context_elements: tuple[str, ...],
+ ) -> dict[str, Any]:
+ return {
+ "content": {"value": teams_text(event_kind_spec)},
+ "webhookUrl": {"value": data["webhook_url"]},
+ }
+
+
+class TeamsDestination(_WebhookUrlDestination):
+ type = DestinationType.TEAMS
+ template_id = "template-microsoft-teams"
+ url_input_key = "webhookUrl"
+
+ def build_name(self, data: AlertDestinationData) -> str:
+ return "Microsoft Teams"
+
+ def build_inputs(
+ self,
+ event_kind_spec: EventKindSpec,
+ data: AlertDestinationData,
+ *,
+ slack_context_elements: tuple[str, ...],
+ ) -> dict[str, Any]:
+ return {
+ "webhookUrl": {"value": data["webhook_url"]},
+ "text": {"value": teams_text(event_kind_spec)},
+ }
+
+
+DESTINATION_SPECS: dict[DestinationType, DestinationSpec] = {
+ spec.type: spec for spec in (SlackDestination(), DiscordDestination(), WebhookDestination(), TeamsDestination())
+}
+
+SPEC_BY_TEMPLATE_ID: dict[str, DestinationSpec] = {spec.template_id: spec for spec in DESTINATION_SPECS.values()}
+
+
+def _redact_url(value: str) -> str:
+ """Keep only the parts a person needs to tell two destinations apart. The path,
+ query and userinfo carry the channel secret for every webhook-style provider."""
+ try:
+ parsed = urlsplit(value)
+ scheme, hostname, port = parsed.scheme, parsed.hostname, parsed.port
+ except ValueError:
+ return "<redacted>"
+ if not scheme or not hostname:
+ return "<redacted>"
+ authority = f"{hostname}:{port}" if port is not None else hostname
+ return f"{scheme}://{authority}"
+
+
def validate_destination_data(
data: AlertDestinationData,
*,
@@ -163,7 +322,9 @@ def validate_destination_data(
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))
+ missing_fields = tuple(
+ field for field in DESTINATION_SPECS[destination_type].required_fields if not data.get(field)
+ )
if len(missing_fields) == 1:
missing_field = missing_fields[0]
raise AlertDestinationValidationError(
@@ -183,37 +344,9 @@ def build_alert_destination_config(
data: AlertDestinationData,
slack_context_elements: tuple[str, ...],
) -> AlertDestinationConfig:
- destination_type = data["type"]
+ destination_spec = DESTINATION_SPECS[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)},
- }
+ destination_name = destination_spec.build_name(data)
return AlertDestinationConfig(
team=team,
@@ -223,7 +356,7 @@ def build_alert_destination_config(
"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,
+ "template_id": destination_spec.template_id,
+ "inputs": destination_spec.build_inputs(spec, data, slack_context_elements=slack_context_elements),
},
)
diff --git a/products/alerts/backend/destinations.py b/products/alerts/backend/destinations.py
index 1c2cc2a34b57..2458e317ab2d 100644
--- a/products/alerts/backend/destinations.py
+++ b/products/alerts/backend/destinations.py
@@ -6,7 +6,7 @@ import re
from collections.abc import Collection, Sequence
from dataclasses import asdict, dataclass
from datetime import datetime
-from typing import Any
+from typing import Any, NamedTuple, cast
from urllib.parse import urlsplit
from uuid import UUID
@@ -14,6 +14,7 @@ from django.db import transaction
from django.db.models import Q, QuerySet
import structlog
+import posthoganalytics
from prometheus_client import Counter
from rest_framework.exceptions import ValidationError
@@ -22,7 +23,11 @@ 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.alerts.backend.destination_configs import (
+ SPEC_BY_TEMPLATE_ID,
+ AlertDestinationConfig,
+ AlertDestinationData,
+)
from products.cdp.backend.api.hog_function import HogFunctionSerializer
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -61,28 +66,147 @@ class ActiveAlertDestination:
destination_type: str | None
-_TEMPLATE_ID_TO_DESTINATION_TYPE = {
- template_id: destination_type.value for destination_type, template_id in DESTINATION_TEMPLATE_IDS.items()
-}
+class AlertDestinationGroupKey(NamedTuple):
+ template_id: str
+ config: tuple[tuple[str, Any], ...] | None
+ @property
+ def is_config_readable(self) -> bool:
+ return self.config is not None
-def _active_alert_destinations_qs(
+
+class AlertDestinationRow(NamedTuple):
+ hog_function_id: UUID
+ template_id: str | None
+ inputs: dict[str, Any] | None
+
+
+@dataclass(frozen=True, kw_only=True)
+class AlertDestinationGroup:
+ hog_function_ids: tuple[UUID, ...]
+ data: AlertDestinationData
+ fully_enabled: bool
+
+
+def alert_destination_group_key(*, template_id: str, inputs: dict[str, Any] | None) -> AlertDestinationGroupKey:
+ spec = SPEC_BY_TEMPLATE_ID.get(template_id)
+ if spec is None:
+ return AlertDestinationGroupKey(template_id, None)
+ data = spec.read(inputs or {})
+ config = {key: value for key, value in data.items() if key != "type"}
+ return AlertDestinationGroupKey(template_id, tuple(sorted(config.items())) if config else None)
+
+
+def group_alert_destination_rows(rows: Collection[AlertDestinationRow]) -> dict[AlertDestinationGroupKey, set[UUID]]:
+ keys_by_row = [
+ (row.hog_function_id, alert_destination_group_key(template_id=row.template_id or "", inputs=row.inputs))
+ for row in rows
+ ]
+ templates_with_an_unreadable_row = {key.template_id for _, key in keys_by_row if not key.is_config_readable}
+
+ ids_by_group: dict[AlertDestinationGroupKey, set[UUID]] = {}
+ for hog_function_id, key in keys_by_row:
+ widened_key = (
+ AlertDestinationGroupKey(key.template_id, None)
+ if key.template_id in templates_with_an_unreadable_row
+ else key
+ )
+ ids_by_group.setdefault(widened_key, set()).add(hog_function_id)
+ return ids_by_group
+
+
+def list_alert_destination_groups(
*, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> list[AlertDestinationGroup]:
+ raw_rows = list(
+ owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids)
+ .order_by("created_at", "id")
+ .values_list("id", "template_id", "inputs", "enabled")
+ )
+ rows = [AlertDestinationRow(row_id, template_id, inputs) for row_id, template_id, inputs, _ in raw_rows]
+ grouped_ids = group_alert_destination_rows(rows)
+ enabled_by_id = {row_id: enabled for row_id, _, _, enabled in raw_rows}
+
+ groups: list[AlertDestinationGroup] = []
+ for key, ids in grouped_ids.items():
+ spec = SPEC_BY_TEMPLATE_ID.get(key.template_id)
+ if spec is None:
+ continue
+ data = cast(AlertDestinationData, {"type": spec.type, **dict(key.config or ())})
+ groups.append(
+ AlertDestinationGroup(
+ hog_function_ids=tuple(sorted(ids)),
+ data=data,
+ fully_enabled=all(enabled_by_id[hog_function_id] for hog_function_id in ids),
+ )
+ )
+ return groups
+
+
+def owned_alert_destinations_qs(
+ *, team_id: int, alert_ids: Collection[str], allowed_event_ids: Collection[str]
) -> QuerySet[HogFunction]:
+ alert_id_filter = Q(pk__in=[])
+ for alert_id in alert_ids:
+ alert_id_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])
return HogFunction.objects.filter(
+ alert_id_filter,
_allowed_event_filter(allowed_event_ids),
team_id=team_id,
deleted=False,
- enabled=True,
- template_id__in=DESTINATION_TEMPLATE_IDS.values(),
- filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
+ template_id__in=SPEC_BY_TEMPLATE_ID,
)
-def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig], *, request: Any) -> list[HogFunction]:
+def _active_alert_destinations_qs(
+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]
+) -> QuerySet[HogFunction]:
+ return owned_alert_destinations_qs(
+ team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids
+ ).filter(enabled=True)
+
+
+def _raise_if_alert_already_has_these_destination_configs(
+ *,
+ team_id: int,
+ alert_id: str,
+ allowed_event_ids: Collection[str],
+ configs: Collection[AlertDestinationConfig],
+) -> None:
+ wanted_keys = {
+ alert_destination_group_key(template_id=config.payload["template_id"], inputs=config.payload["inputs"])
+ for config in configs
+ }
+ # An unreadable config can't be compared, so it can't be proven a duplicate.
+ readable_keys = {key for key in wanted_keys if key.is_config_readable}
+ if not readable_keys:
+ return
+ stored_rows = (
+ owned_alert_destinations_qs(team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids)
+ .filter(template_id__in={key.template_id for key in readable_keys})
+ .values_list("template_id", "inputs")
+ )
+ if any(
+ alert_destination_group_key(template_id=template_id or "", inputs=inputs) in readable_keys
+ for template_id, inputs in stored_rows
+ ):
+ raise ValidationError("This destination is already configured for this alert.")
+
+
+def create_alert_destination_hog_functions(
+ configs: list[AlertDestinationConfig], *, request: Any, alert_id: str, allowed_event_ids: Collection[str]
+) -> list[HogFunction]:
+ if not configs:
+ return []
created: list[HogFunction] = []
hog_function_ids_by_team: dict[int, list[UUID]] = {}
with transaction.atomic():
+ _raise_if_alert_already_has_these_destination_configs(
+ team_id=configs[0].team.id,
+ alert_id=alert_id,
+ allowed_event_ids=allowed_event_ids,
+ configs=configs,
+ )
for config in configs:
team = config.team
serializer = HogFunctionSerializer(
@@ -103,6 +227,36 @@ def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig]
return created
+def _report_unreadable_destination_configs(
+ *, team_id: int, alert_id: str, rows: Collection[AlertDestinationRow]
+) -> None:
+ row_counts_by_template: dict[str, int] = {}
+ for row in rows:
+ template_id = row.template_id or ""
+ if not alert_destination_group_key(template_id=template_id, inputs=row.inputs).is_config_readable:
+ row_counts_by_template[template_id] = row_counts_by_template.get(template_id, 0) + 1
+ for template_id, count in row_counts_by_template.items():
+ posthoganalytics.capture(
+ distinct_id=f"team_{team_id}",
+ event="alert destination config unreadable",
+ properties={
+ "alert_id": alert_id,
+ "feature": "alerts",
+ "row_count": count,
+ "team_id": team_id,
+ "template_id": template_id,
+ },
+ )
+ if row_counts_by_template:
+ logger.warning(
+ "Alert destination config could not be read",
+ alert_id=alert_id,
+ feature="alerts",
+ row_counts_by_template=row_counts_by_template,
+ team_id=team_id,
+ )
+
+
def soft_delete_alert_destinations(
*,
team_id: int,
@@ -112,19 +266,15 @@ def soft_delete_alert_destinations(
) -> None:
unique_ids = set(hog_function_ids)
with transaction.atomic():
- event_filter = _allowed_event_filter(allowed_event_ids)
- owned_rows = list(
- HogFunction.objects.select_for_update()
- .filter(
- event_filter,
- team_id=team_id,
- deleted=False,
- template_id__in=DESTINATION_TEMPLATE_IDS.values(),
- filters__properties__contains=[{"key": "alert_id", "value": alert_id}],
+ owned_rows = [
+ AlertDestinationRow(*row)
+ for row in owned_alert_destinations_qs(
+ team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids
)
- .values_list("id", "template_id", "filters")
- )
- owned_ids = {hog_function_id for hog_function_id, _, _ in owned_rows}
+ .select_for_update()
+ .values_list("id", "template_id", "inputs")
+ ]
+ owned_ids = {row.hog_function_id for row in owned_rows}
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))
@@ -136,73 +286,36 @@ def soft_delete_alert_destinations(
}
)
- allowed_events = set(allowed_event_ids)
- rows_by_template: dict[str | None, list[tuple[UUID, str | None]]] = {}
- for hog_function_id, template_id, filters in owned_rows:
- event_id = next(
- (
- event_filter.get("id")
- for event_filter in (filters or {}).get("events", [])
- if isinstance(event_filter, dict) and event_filter.get("type") == "events"
- ),
- None,
- )
- rows_by_template.setdefault(template_id, []).append((hog_function_id, event_id))
-
- for group in rows_by_template.values():
- group_ids = {hog_function_id for hog_function_id, _ in group}
- if not unique_ids.intersection(group_ids):
- continue
- if group_ids != unique_ids.intersection(group_ids) or {event_id for _, event_id in group} != allowed_events:
- raise ValidationError(
- {"hog_function_ids": ["Delete every HogFunction in the destination group together."]}
+ _report_unreadable_destination_configs(team_id=team_id, alert_id=alert_id, rows=owned_rows)
+
+ for group_key, group_ids in group_alert_destination_rows(owned_rows).items():
+ names_only_part_of_the_group = bool(group_ids & unique_ids) and not group_ids <= unique_ids
+ if names_only_part_of_the_group:
+ message = (
+ "Delete all destinations in this group together."
+ if group_key.is_config_readable
+ else "Some destinations of this type have settings that can no longer be read. To delete any of them, remove every destination of this type together."
)
+ raise ValidationError({"hog_function_ids": [message]})
HogFunction.objects.filter(team_id=team_id, id__in=unique_ids).update(deleted=True, enabled=False)
_reload_hog_functions_after_commit(team_id=team_id, hog_function_ids=unique_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
+ return soft_delete_alert_destinations_for_alerts(
+ team_id=team_id, alert_ids=[alert_id], allowed_event_ids=allowed_event_ids
+ )
def soft_delete_alert_destinations_for_alerts(
*, team_id: int, alert_ids: Collection[str], allowed_event_ids: Collection[str]
) -> int:
- """Soft-delete alert-owned destinations in bulk when their execution team is removed."""
- event_filter = _allowed_event_filter(allowed_event_ids)
- if not alert_ids:
- return 0
- destination_ids: set[UUID] = set()
+ """Soft-delete alert-owned destinations in bulk."""
with transaction.atomic():
- alert_id_filter = Q(pk__in=[])
- for alert_id in alert_ids:
- alert_id_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])
destination_ids = set(
- HogFunction.objects.select_for_update()
- .filter(
- alert_id_filter,
- event_filter,
- team_id=team_id,
- deleted=False,
- template_id__in=DESTINATION_TEMPLATE_IDS.values(),
- )
+ owned_alert_destinations_qs(team_id=team_id, alert_ids=alert_ids, allowed_event_ids=allowed_event_ids)
+ .select_for_update()
.values_list("id", flat=True)
)
deleted_count = HogFunction.objects.filter(team_id=team_id, id__in=destination_ids).update(
@@ -253,12 +366,12 @@ def list_active_alert_destinations(
).values_list("id", "name", "template_id")
destinations = []
for hog_function_id, name, template_id in rows:
- destination_type = _TEMPLATE_ID_TO_DESTINATION_TYPE.get(template_id) if template_id else None
+ spec = SPEC_BY_TEMPLATE_ID.get(template_id) if template_id else None
destinations.append(
ActiveAlertDestination(
id=str(hog_function_id),
name=_destination_display_name(name) if name else "Destination",
- destination_type=destination_type,
+ destination_type=spec.type.value if spec else None,
)
)
return destinations
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index f9030da5e53e..e6a3531d7093 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -17,7 +17,7 @@ from posthog.utils import relative_date_parse
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.alerts.backend.destination_configs import (
- DESTINATION_TEMPLATE_IDS,
+ DESTINATION_SPECS,
AlertDestinationData,
AlertDestinationValidationError,
DestinationType,
@@ -26,6 +26,8 @@ from products.alerts.backend.destination_configs import (
)
from products.alerts.backend.destinations import (
create_alert_destination_hog_functions,
+ list_alert_destination_groups,
+ owned_alert_destinations_qs,
soft_delete_alert_destinations,
soft_delete_alert_destinations_for_alerts,
soft_delete_all_alert_destinations,
@@ -202,7 +204,7 @@ def snooze_alert_from_slack(
__all__ = [
- "DESTINATION_TEMPLATE_IDS",
+ "DESTINATION_SPECS",
"AlertDestinationData",
"AlertDestinationValidationError",
"AlertScheduleRestriction",
@@ -215,6 +217,8 @@ __all__ = [
"get_alert_team_id",
"insight_alerts_prefetch",
"insight_ids_with_alerts",
+ "list_alert_destination_groups",
+ "owned_alert_destinations_qs",
"serialize_insight_alerts",
"snooze_alert_from_slack",
"soft_delete_alert_destinations",
diff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.py
index f37d6a607539..4b12d9fcfdcb 100644
--- a/products/alerts/backend/test/test_destination_configs.py
+++ b/products/alerts/backend/test/test_destination_configs.py
@@ -1,4 +1,19 @@
-from products.alerts.backend.destination_configs import AlertDestinationAction, EventKindSpec, slack_blocks, teams_text
+from typing import Any
+
+import pytest
+
+from posthog.cdp.templates import HOG_FUNCTION_TEMPLATES
+
+from products.alerts.backend.destination_configs import (
+ DESTINATION_SPECS,
+ AlertDestinationAction,
+ AlertDestinationData,
+ DestinationType,
+ EventKindSpec,
+ build_alert_destination_config,
+ slack_blocks,
+ teams_text,
+)
DEFAULT_SPEC = EventKindSpec(
event_id="$insight_alert_firing",
@@ -54,3 +69,66 @@ class TestSpecVocabularyRendering:
assert teams_text(DEFAULT_SPEC) == (
"**Insight alert firing**\n\n**Threshold:** 30\n\n[View insight](https://example.com/insight)"
)
+
+
+_TEMPLATES_BY_ID = {template.id: template for template in HOG_FUNCTION_TEMPLATES}
+
+_TEMPLATE_IDS_DEFINED_IN_NODEJS = {"template-slack", "template-webhook"}
+
+_DESTINATION_DATA: dict[DestinationType, AlertDestinationData] = {
+ DestinationType.DISCORD: {"type": DestinationType.DISCORD, "webhook_url": "https://discord.example.com/hook"},
+ DestinationType.TEAMS: {"type": DestinationType.TEAMS, "webhook_url": "https://teams.example.com/hook"},
+}
+
+
+def _inputs_a_hog_function_would_keep(template: Any, inputs: dict[str, Any]) -> dict[str, Any]:
+ return {entry["key"]: inputs.get(entry["key"]) for entry in template.inputs_schema or [] if not entry.get("secret")}
+
+
+class TestDestinationTemplateContract:
+ def test_the_templates_defined_outside_python_are_the_ones_we_expect(self) -> None:
+ unreachable = {spec.template_id for spec in DESTINATION_SPECS.values()} - set(_TEMPLATES_BY_ID)
+
+ assert unreachable == _TEMPLATE_IDS_DEFINED_IN_NODEJS
+
+ @pytest.mark.parametrize("destination_type", list(_DESTINATION_DATA))
+ def test_a_config_read_back_from_the_inputs_a_template_keeps_equals_the_config_built(
+ self, destination_type: DestinationType
+ ) -> None:
+ template = _TEMPLATES_BY_ID[DESTINATION_SPECS[destination_type].template_id]
+ data = _DESTINATION_DATA[destination_type]
+ config = build_alert_destination_config(
+ team=None,
+ spec=DEFAULT_SPEC,
+ alert_id="alert-1",
+ alert_name="Signups",
+ data=data,
+ slack_context_elements=(),
+ )
+
+ stored_inputs = _inputs_a_hog_function_would_keep(template, config.payload["inputs"])
+
+ assert DESTINATION_SPECS[destination_type].read(stored_inputs) == data
+
+ def test_slack_channel_name_shapes_the_hog_function_name_and_is_never_stored_in_inputs(self) -> None:
+ data: AlertDestinationData = {
+ "type": DestinationType.SLACK,
+ "slack_workspace_id": 42,
+ "slack_channel_id": "C123",
+ "slack_channel_name": "eng",
+ }
+ config = build_alert_destination_config(
+ team=None,
+ spec=DEFAULT_SPEC,
+ alert_id="alert-1",
+ alert_name="Signups",
+ data=data,
+ slack_context_elements=(),
+ )
+
+ assert config.payload["name"].endswith("Slack #eng")
+ assert DESTINATION_SPECS[DestinationType.SLACK].read(config.payload["inputs"]) == {
+ "type": DestinationType.SLACK,
+ "slack_workspace_id": 42,
+ "slack_channel_id": "C123",
+ }
diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.py
index 250418aff548..279ace9901c7 100644
--- a/products/alerts/backend/test/test_destinations.py
+++ b/products/alerts/backend/test/test_destinations.py
@@ -1,12 +1,32 @@
+from typing import Any
+from uuid import uuid4
+
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
+from posthog.models.team.team import Team
+
+from products.alerts.backend.destination_configs import (
+ DESTINATION_SPECS,
+ AlertDestinationConfig,
+ AlertDestinationData,
+ DestinationType,
+ EventKindSpec,
+ build_alert_destination_config,
+)
from products.alerts.backend.destinations import (
+ SPEC_BY_TEMPLATE_ID,
AlertDelivery,
+ AlertDestinationGroupKey,
+ AlertDestinationRow,
+ _raise_if_alert_already_has_these_destination_configs,
+ alert_destination_group_key,
alert_internal_event_delivered,
+ group_alert_destination_rows,
list_active_alert_destinations,
serialize_deliveries,
soft_delete_alert_destinations,
@@ -14,21 +34,60 @@ from products.alerts.backend.destinations import (
)
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-ALLOWED_EVENT_IDS = ("$logs_alert_firing", "$logs_alert_resolved")
+ALLOWED_EVENT_IDS = (
+ "$logs_alert_firing",
+ "$logs_alert_resolved",
+ "$logs_alert_errored",
+ "$logs_alert_auto_disabled",
+)
+
+_DESTINATION_DATA: dict[DestinationType, AlertDestinationData] = {
+ DestinationType.SLACK: {"type": DestinationType.SLACK, "slack_workspace_id": 1, "slack_channel_id": "C-ENG"},
+ DestinationType.DISCORD: {"type": DestinationType.DISCORD, "webhook_url": "https://discord.example.com/hook"},
+ DestinationType.WEBHOOK: {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/hook"},
+ DestinationType.TEAMS: {"type": DestinationType.TEAMS, "webhook_url": "https://teams.example.com/hook"},
+}
+
+
+def slack_inputs(channel_id: str, *, workspace_id: int = 1) -> dict[str, Any]:
+ return {"slack_workspace": {"value": workspace_id}, "channel": {"value": channel_id}}
+
+def webhook_inputs(url: str) -> dict[str, Any]:
+ return {"url": {"value": url}}
-class TestSoftDeleteAlertDestinations(APIBaseTest):
+
+_READABLE_INPUTS_BY_TEMPLATE: dict[str, dict[str, Any]] = {
+ "template-slack": slack_inputs("C-ENG"),
+ "template-webhook": webhook_inputs("https://example.com/hook"),
+ "template-microsoft-teams": {"webhookUrl": {"value": "https://teams.example.com/hook"}},
+}
+
+
+def _schema_declaring_every_input(inputs: dict[str, Any]) -> list[dict[str, Any]]:
+ return [{"key": key, "type": "string"} for key in inputs]
+
+
+class AlertDestinationTestCase(APIBaseTest):
def _make_hog_function(
- self, *, template_id: str, alert_id: str, event_id: str = "$logs_alert_firing"
+ self,
+ *,
+ template_id: str,
+ alert_id: str,
+ event_id: str = "$logs_alert_firing",
+ inputs: dict[str, Any] | None = None,
+ team: Team | None = None,
+ name: str = "Test destination",
) -> HogFunction:
+ resolved_inputs = _READABLE_INPUTS_BY_TEMPLATE.get(template_id, {}) if inputs is None else inputs
return HogFunction.objects.create(
- team=self.team,
- name="Test destination",
+ team=team or self.team,
+ name=name,
type="destination",
template_id=template_id,
enabled=True,
- inputs_schema=[],
- inputs={},
+ inputs_schema=_schema_declaring_every_input(resolved_inputs),
+ inputs=resolved_inputs,
hog="return event",
filters={
"events": [{"id": event_id, "type": "events"}],
@@ -36,12 +95,194 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
},
)
- def _make_group(self, *, template_id: str, alert_id: str) -> list[HogFunction]:
+ def _make_group(
+ self,
+ *,
+ template_id: str,
+ alert_id: str,
+ inputs: dict[str, Any] | None = None,
+ team: Team | None = None,
+ ) -> list[HogFunction]:
return [
- self._make_hog_function(template_id=template_id, alert_id=alert_id, event_id=event_id)
+ self._make_hog_function(
+ template_id=template_id, alert_id=alert_id, event_id=event_id, inputs=inputs, team=team
+ )
for event_id in ALLOWED_EVENT_IDS
]
+ def _assert_deleted(self, hog_functions: list[HogFunction]) -> None:
+ for hog_function in hog_functions:
+ hog_function.refresh_from_db()
+ assert hog_function.deleted is True
+ assert hog_function.enabled is False
+
+ def _assert_intact(self, hog_functions: list[HogFunction]) -> None:
+ for hog_function in hog_functions:
+ hog_function.refresh_from_db()
+ assert hog_function.deleted is False
+ assert hog_function.enabled is True
+
+
+def _config_for(destination_type: DestinationType, event_id: str) -> AlertDestinationConfig:
+ return build_alert_destination_config(
+ team=None,
+ spec=EventKindSpec(
+ event_id=event_id,
+ display_kind=event_id,
+ header=f"Logs alert {event_id}",
+ details=(("Event", event_id),),
+ primary_action_url="https://example.com/alert",
+ primary_action_label="View alert",
+ webhook_body={"event": event_id},
+ ),
+ alert_id="alert-1",
+ alert_name="Signups",
+ data=_DESTINATION_DATA[destination_type],
+ slack_context_elements=(),
+ )
+
+
+def _group_key_of(config: AlertDestinationConfig) -> AlertDestinationGroupKey:
+ return alert_destination_group_key(template_id=config.payload["template_id"], inputs=config.payload["inputs"])
+
+
+class TestAlertDestinationGroupKey:
+ @pytest.mark.parametrize("destination_type", list(DestinationType))
+ def test_a_config_built_for_any_destination_type_is_readable(self, destination_type: DestinationType) -> None:
+ assert _group_key_of(_config_for(destination_type, "$logs_alert_firing")).is_config_readable
+
+ def test_every_event_kind_of_one_destination_shares_a_group_key(self) -> None:
+ configs = [_config_for(DestinationType.SLACK, event_id) for event_id in ALLOWED_EVENT_IDS]
+
+ assert len({_group_key_of(config) for config in configs}) == 1
+ assert {config.payload["inputs"]["text"]["value"] for config in configs} == {
+ f"Logs alert {event_id}" for event_id in ALLOWED_EVENT_IDS
+ }
+
+ def test_template_ids_and_destination_types_name_each_other_one_to_one(self) -> None:
+ assert set(SPEC_BY_TEMPLATE_ID) == {spec.template_id for spec in DESTINATION_SPECS.values()}
+ assert {spec.type for spec in SPEC_BY_TEMPLATE_ID.values()} == set(DestinationType)
+
+
+class TestGroupAlertDestinationRows:
+ def test_groups_two_configs_of_one_template_separately(self) -> None:
+ eng, ops = uuid4(), uuid4()
+
+ groups = group_alert_destination_rows(
+ [
+ AlertDestinationRow(eng, "template-slack", slack_inputs("C-ENG")),
+ AlertDestinationRow(ops, "template-slack", slack_inputs("C-OPS")),
+ ]
+ )
+
+ assert groups == {
+ AlertDestinationGroupKey("template-slack", (("slack_channel_id", "C-ENG"), ("slack_workspace_id", 1))): {
+ eng
+ },
+ AlertDestinationGroupKey("template-slack", (("slack_channel_id", "C-OPS"), ("slack_workspace_id", 1))): {
+ ops
+ },
+ }
+
+ def test_an_unreadable_row_collapses_its_whole_template_into_one_group(self) -> None:
+ unreadable, readable, webhook = uuid4(), uuid4(), uuid4()
+
+ groups = group_alert_destination_rows(
+ [
+ AlertDestinationRow(unreadable, "template-slack", {}),
+ AlertDestinationRow(readable, "template-slack", slack_inputs("C-ENG")),
+ AlertDestinationRow(webhook, "template-webhook", webhook_inputs("https://example.com/hook")),
+ ]
+ )
+
+ assert groups == {
+ AlertDestinationGroupKey("template-slack", None): {unreadable, readable},
+ AlertDestinationGroupKey("template-webhook", (("webhook_url", "https://example.com/hook"),)): {webhook},
+ }
+
+ def test_groups_come_out_in_the_order_their_first_row_was_seen(self) -> None:
+ ops, eng = uuid4(), uuid4()
+
+ groups = group_alert_destination_rows(
+ [
+ AlertDestinationRow(ops, "template-slack", slack_inputs("C-OPS")),
+ AlertDestinationRow(eng, "template-slack", slack_inputs("C-ENG")),
+ ]
+ )
+
+ assert [key.config for key in groups] == [
+ (("slack_channel_id", "C-OPS"), ("slack_workspace_id", 1)),
+ (("slack_channel_id", "C-ENG"), ("slack_workspace_id", 1)),
+ ]
+
+
+class TestRaiseIfAlertAlreadyHasTheseDestinationConfigs(AlertDestinationTestCase):
+ def _raise_if_exists(self, *, configs: list[tuple[str, dict[str, Any]]], alert_id: str = "alert-1") -> None:
+ _raise_if_alert_already_has_these_destination_configs(
+ team_id=self.team.id,
+ alert_id=alert_id,
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ configs=[
+ AlertDestinationConfig(team=self.team, payload={"template_id": template_id, "inputs": inputs})
+ for template_id, inputs in configs
+ ],
+ )
+
+ def test_rejects_a_destination_whose_config_already_exists(self) -> None:
+ self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a"))
+
+ with self.assertRaisesRegex(ValidationError, "already configured for this alert"):
+ self._raise_if_exists(configs=[("template-webhook", webhook_inputs("https://a"))])
+
+ def test_allows_a_second_destination_with_a_different_config(self) -> None:
+ self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a"))
+
+ self._raise_if_exists(configs=[("template-webhook", webhook_inputs("https://b"))])
+
+ def test_allows_a_config_that_only_matches_another_alerts_destination(self) -> None:
+ self._make_group(template_id="template-webhook", alert_id="alert-2", inputs=webhook_inputs("https://a"))
+
+ self._raise_if_exists(configs=[("template-webhook", webhook_inputs("https://a"))])
+
+ def test_allows_a_config_whose_only_match_is_deleted(self) -> None:
+ destinations = self._make_group(
+ template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a")
+ )
+ HogFunction.objects.filter(id__in=[destination.id for destination in destinations]).update(deleted=True)
+
+ self._raise_if_exists(configs=[("template-webhook", webhook_inputs("https://a"))])
+
+ def test_rejects_a_duplicate_of_a_disabled_destination(self) -> None:
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-ENG"))
+ HogFunction.objects.filter(id__in=[destination.id for destination in destinations]).update(enabled=False)
+
+ with self.assertRaisesRegex(ValidationError, "already configured for this alert"):
+ self._raise_if_exists(configs=[("template-slack", slack_inputs("C-ENG"))])
+
+ def test_allows_a_destination_whose_config_cannot_be_read(self) -> None:
+ self._make_group(template_id="template-slack", alert_id="alert-1", inputs={})
+
+ self._raise_if_exists(configs=[("template-slack", {})])
+
+ def test_rejects_a_duplicate_that_is_not_the_first_config_in_the_call(self) -> None:
+ self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://a"))
+
+ with self.assertRaisesRegex(ValidationError, "already configured for this alert"):
+ self._raise_if_exists(
+ configs=[
+ ("template-slack", slack_inputs("C-NEW")),
+ ("template-webhook", webhook_inputs("https://a")),
+ ]
+ )
+
+ def test_allows_a_config_that_matches_another_templates_destination(self) -> None:
+ webhook_url = {"webhookUrl": {"value": "https://hooks.example.com/x"}}
+ self._make_group(template_id="template-microsoft-teams", alert_id="alert-1", inputs=webhook_url)
+
+ self._raise_if_exists(configs=[("template-discord", webhook_url)])
+
+
+class TestSoftDeleteAlertDestinations(AlertDestinationTestCase):
def test_deletes_alert_destination_with_matching_alert_id(self) -> None:
destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
@@ -52,15 +293,12 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
hog_function_ids=[destination.id for destination in destinations],
)
- for destination in destinations:
- destination.refresh_from_db()
- assert destination.deleted is True
- assert destination.enabled is False
+ self._assert_deleted(destinations)
def test_rejects_partial_destination_group(self) -> None:
destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
- with self.assertRaisesRegex(ValidationError, "Delete every HogFunction"):
+ with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):
soft_delete_alert_destinations(
team_id=self.team.id,
alert_id="alert-1",
@@ -68,7 +306,251 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
hog_function_ids=[destinations[0].id],
)
- assert not HogFunction.objects.filter(id__in=[destination.id for destination in destinations], deleted=True)
+ self._assert_intact(destinations)
+
+ @parameterized.expand(
+ [
+ ("slack_channels", "template-slack", slack_inputs("C-ENG"), slack_inputs("C-OPS")),
+ (
+ "webhook_urls",
+ "template-webhook",
+ webhook_inputs("https://example.com/a"),
+ webhook_inputs("https://example.com/b"),
+ ),
+ ]
+ )
+ def test_deletes_one_of_two_destinations_of_the_same_type(
+ self, _name: str, template_id: str, first_inputs: dict[str, Any], second_inputs: dict[str, Any]
+ ) -> None:
+ first = self._make_group(template_id=template_id, alert_id="alert-1", inputs=first_inputs)
+ second = self._make_group(template_id=template_id, alert_id="alert-1", inputs=second_inputs)
+
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in first],
+ )
+
+ self._assert_deleted(first)
+ self._assert_intact(second)
+
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in second],
+ )
+
+ self._assert_deleted(second)
+
+ def test_destination_missing_an_event_kind_is_still_deletable(self) -> None:
+ destinations = [
+ self._make_hog_function(template_id="template-slack", alert_id="alert-1", event_id=event_id)
+ for event_id in ALLOWED_EVENT_IDS[:-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 for destination in destinations],
+ )
+
+ self._assert_deleted(destinations)
+
+ def test_a_disabled_row_must_be_deleted_with_the_rest_of_its_group(self) -> None:
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
+ HogFunction.objects.filter(id=destinations[0].id).update(enabled=False)
+
+ with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in destinations[1:]],
+ )
+
+ assert HogFunction.objects.filter(
+ id__in=[destination.id for destination in destinations], deleted=False
+ ).count() == len(destinations)
+
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in destinations],
+ )
+
+ self._assert_deleted(destinations)
+
+ def test_rejects_partial_group_when_another_destination_of_the_same_type_exists(self) -> None:
+ first = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-ENG"))
+ second = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-OPS"))
+
+ with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[first[0].id, *(destination.id for destination in second)],
+ )
+
+ self._assert_intact([*first, *second])
+
+ def test_deletes_a_pre_existing_duplicate_pair_together(self) -> None:
+ first = self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://x"))
+ second = self._make_group(
+ template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://x")
+ )
+
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in (*first, *second)],
+ )
+
+ self._assert_deleted([*first, *second])
+
+ def test_rejects_deleting_half_of_a_pre_existing_duplicate_pair(self) -> None:
+ first = self._make_group(template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://x"))
+ second = self._make_group(
+ template_id="template-webhook", alert_id="alert-1", inputs=webhook_inputs("https://x")
+ )
+
+ with self.assertRaisesRegex(ValidationError, "Delete all destinations in this group"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in first],
+ )
+
+ self._assert_intact([*first, *second])
+
+ def test_rejects_partial_delete_when_a_row_config_cannot_be_read(self) -> None:
+ orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
+
+ with self.assertRaisesRegex(ValidationError, "can no longer be read"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in destinations],
+ )
+
+ self._assert_intact([orphan, *destinations])
+
+ def test_rejects_deleting_only_the_row_whose_config_cannot_be_read(self) -> None:
+ orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
+
+ with self.assertRaisesRegex(ValidationError, "can no longer be read"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[orphan.id],
+ )
+
+ self._assert_intact([orphan, *destinations])
+
+ def test_deletes_every_row_of_a_template_that_has_an_unreadable_config(self) -> None:
+ orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})
+ destinations = self._make_group(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=[orphan.id, *(destination.id for destination in destinations)],
+ )
+
+ self._assert_deleted([orphan, *destinations])
+
+ def test_unreadable_config_does_not_block_deleting_another_template(self) -> None:
+ orphan = self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})
+ webhooks = self._make_group(template_id="template-webhook", 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 for destination in webhooks],
+ )
+
+ self._assert_deleted(webhooks)
+ self._assert_intact([orphan])
+
+ @patch("products.alerts.backend.destinations.logger")
+ @patch("products.alerts.backend.destinations.posthoganalytics.capture")
+ def test_unreadable_config_is_captured_and_logged(self, capture, logger) -> None:
+ self._make_hog_function(template_id="template-slack", alert_id="alert-1", inputs={})
+ webhooks = self._make_group(template_id="template-webhook", 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 for destination in webhooks],
+ )
+
+ capture.assert_called_once_with(
+ distinct_id=f"team_{self.team.id}",
+ event="alert destination config unreadable",
+ properties={
+ "alert_id": "alert-1",
+ "feature": "alerts",
+ "row_count": 1,
+ "team_id": self.team.id,
+ "template_id": "template-slack",
+ },
+ )
+ assert logger.warning.call_args.args == ("Alert destination config could not be read",)
+ assert logger.warning.call_args.kwargs["row_counts_by_template"] == {"template-slack": 1}
+
+ def test_rejects_destinations_belonging_to_another_alert(self) -> None:
+ destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
+ other_alert = self._make_group(template_id="template-slack", alert_id="alert-2")
+
+ with self.assertRaisesRegex(ValidationError, "do not belong to this alert"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in other_alert],
+ )
+
+ self._assert_intact([*destinations, *other_alert])
+
+ def test_rejects_destinations_belonging_to_another_team(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_team_destinations = self._make_group(template_id="template-slack", alert_id="alert-1", team=other_team)
+
+ with self.assertRaisesRegex(ValidationError, "do not belong to this alert"):
+ soft_delete_alert_destinations(
+ team_id=self.team.id,
+ alert_id="alert-1",
+ allowed_event_ids=ALLOWED_EVENT_IDS,
+ hog_function_ids=[destination.id for destination in other_team_destinations],
+ )
+
+ self._assert_intact(other_team_destinations)
+
+ def test_deletes_every_destination_of_the_alert_including_same_type_siblings(self) -> None:
+ first = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-ENG"))
+ second = self._make_group(template_id="template-slack", alert_id="alert-1", inputs=slack_inputs("C-OPS"))
+ other_alert = self._make_group(template_id="template-slack", alert_id="alert-2")
+
+ 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 == len(first) + len(second)
+ self._assert_deleted([*first, *second])
+ self._assert_intact(other_alert)
def test_reports_invalid_ids_and_does_not_delete_any_destinations(self) -> None:
destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
@@ -88,10 +570,7 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
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 (*destinations, other):
- hog_function.refresh_from_db()
- assert hog_function.deleted is False
- assert hog_function.enabled is True
+ self._assert_intact([*destinations, other])
def test_deletes_all_destinations_for_alert_only(self) -> None:
slack_destination = self._make_hog_function(template_id="template-slack", alert_id="alert-1")
@@ -107,15 +586,8 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
)
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
+ self._assert_deleted([slack_destination, webhook_destination])
+ self._assert_intact([other_alert_destination, non_destination, unrelated_event_destination])
def test_rejects_empty_allowed_event_ids_without_deleting_destinations(self) -> None:
destinations = self._make_group(template_id="template-slack", alert_id="alert-1")
@@ -123,10 +595,7 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
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=())
- for destination in destinations:
- destination.refresh_from_db()
- assert destination.deleted is False
- assert destination.enabled is True
+ self._assert_intact(destinations)
@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:
@@ -157,10 +626,7 @@ class TestSoftDeleteAlertDestinations(APIBaseTest):
hog_function_ids=[destination.id for destination in destinations],
)
- for destination in destinations:
- destination.refresh_from_db()
- assert destination.deleted is True
- assert destination.enabled is False
+ self._assert_deleted(destinations)
class TestAlertInternalEventDelivery(APIBaseTest):
@@ -185,25 +651,7 @@ class TestAlertInternalEventDelivery(APIBaseTest):
delivery_failures.labels.return_value.inc.assert_called_once_with()
-class TestListActiveAlertDestinations(APIBaseTest):
- def _make_hog_function(
- self, *, template_id: str, alert_id: str, event_id: str = "$logs_alert_firing", name: str = "Test destination"
- ) -> HogFunction:
- return HogFunction.objects.create(
- team=self.team,
- name=name,
- 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}],
- },
- )
-
+class TestListActiveAlertDestinations(AlertDestinationTestCase):
def test_list_active_alert_destinations_returns_name_and_type(self) -> None:
self._make_hog_function(
template_id="template-slack", alert_id="alert-1", name="Alerts — Signups (firing) → Slack #eng-alerts"
diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.ts
index b76298b04ed6..3ff04936abab 100644
--- a/products/billing/frontend/generated/api.schemas.ts
+++ b/products/billing/frontend/generated/api.schemas.ts
@@ -205,8 +205,8 @@ export interface BillingAlertDestinationCreateDataApi {
export interface BillingAlertDestinationChangesApi {
/**
- * @items.minItems 4
- * @items.maxItems 4
+ * @items.minItems 1
+ * @items.maxItems 100
*/
delete?: string[][]
create?: BillingAlertDestinationCreateDataApi[]
@@ -632,8 +632,8 @@ export interface BillingAlertDestinationResponseApi {
export interface BillingAlertDeleteDestinationApi {
/**
* HogFunction IDs to delete as one atomic destination group.
- * @minItems 4
- * @maxItems 4
+ * @minItems 1
+ * @maxItems 100
*/
hog_function_ids: string[]
}
diff --git a/products/billing/frontend/generated/api.zod.ts b/products/billing/frontend/generated/api.zod.ts
index 318c04338594..85311eaf1db8 100644
--- a/products/billing/frontend/generated/api.zod.ts
+++ b/products/billing/frontend/generated/api.zod.ts
@@ -99,8 +99,7 @@ export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72
export const billingAlertsCreateBodyCooldownHoursMin = 0
export const billingAlertsCreateBodyCooldownHoursMax = 720
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),
@@ -159,12 +158,7 @@ export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
destination_changes: zod
.object({
delete: zod
- .array(
- zod
- .array(zod.uuid())
- .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)
- )
+ .array(zod.array(zod.uuid()).min(1).max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax))
.optional(),
create: zod
.array(
@@ -209,8 +203,7 @@ export const billingAlertsUpdateBodyEvaluationDelayHoursMax = 72
export const billingAlertsUpdateBodyCooldownHoursMin = 0
export const billingAlertsUpdateBodyCooldownHoursMax = 720
-export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(billingAlertsUpdateBodyNameMax).describe('Display name for this billing alert.'),
@@ -269,12 +262,7 @@ export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({
destination_changes: zod
.object({
delete: zod
- .array(
- zod
- .array(zod.uuid())
- .min(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax)
- )
+ .array(zod.array(zod.uuid()).min(1).max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax))
.optional(),
create: zod
.array(
@@ -319,8 +307,7 @@ export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72
export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0
export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
@@ -384,10 +371,7 @@ export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.object({
delete: zod
.array(
- zod
- .array(zod.uuid())
- .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
+ zod.array(zod.uuid()).min(1).max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
)
.optional(),
create: zod
@@ -437,13 +421,12 @@ export const BillingAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
/**
* Delete a notification destination by deleting its HogFunction group atomically.
*/
-export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin = 4
-export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4
+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 100
export const BillingAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
hog_function_ids: zod
.array(zod.uuid())
- .min(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin)
+ .min(1)
.max(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)
.describe('HogFunction IDs to delete as one atomic destination group.'),
})
diff --git a/products/billing_alerts/backend/alert_destinations.py b/products/billing_alerts/backend/alert_destinations.py
index 0aacf7bf7ff0..e73af9a50f4f 100644
--- a/products/billing_alerts/backend/alert_destinations.py
+++ b/products/billing_alerts/backend/alert_destinations.py
@@ -2,18 +2,15 @@ from __future__ import annotations
from typing import Final, Literal
-from django.db.models import Q
-
from products.alerts.backend.destination_configs import DestinationType, EventKindSpec
-from products.alerts.backend.facade.api import DESTINATION_TEMPLATE_IDS
-from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.alerts.backend.facade.api import DESTINATION_SPECS, owned_alert_destinations_qs
EventKind = Literal["firing", "resolved", "errored", "broken"]
BILLING_DESTINATION_TYPES = (DestinationType.SLACK, DestinationType.WEBHOOK, DestinationType.TEAMS)
DESTINATION_TYPE_BY_TEMPLATE_ID = {
- DESTINATION_TEMPLATE_IDS[destination_type]: destination_type for destination_type in BILLING_DESTINATION_TYPES
+ DESTINATION_SPECS[destination_type].template_id: destination_type for destination_type in BILLING_DESTINATION_TYPES
}
_PRODUCT_LABEL = "billing alert"
@@ -123,24 +120,19 @@ def destination_groups_for_alerts(
) -> dict[str, dict[str, dict[str, str]]]:
"""Map alert id -> destination type value -> event id -> HogFunction id for enabled,
billing-owned destinations.
-
- This is the single implementation of destination-group resolution; callers enforce the
- complete-group invariant (a group must cover every event kind) on the returned mapping.
"""
if not team_ids or not alert_ids:
return {}
- ownership_filter = Q(pk__in=[])
- for alert_id in alert_ids:
- ownership_filter |= Q(filters__properties__contains=[{"key": "alert_id", "value": alert_id}])
-
- rows = HogFunction.objects.filter(
- ownership_filter,
- team_id__in=team_ids,
- enabled=True,
- deleted=False,
- template_id__in=list(DESTINATION_TYPE_BY_TEMPLATE_ID),
- ).values_list("id", "template_id", "filters")
+ rows = [
+ row
+ for team_id in team_ids
+ for row in owned_alert_destinations_qs(
+ team_id=team_id, alert_ids=alert_ids, allowed_event_ids=BILLING_ALERT_EVENT_IDS
+ )
+ .filter(enabled=True, template_id__in=list(DESTINATION_TYPE_BY_TEMPLATE_ID))
+ .values_list("id", "template_id", "filters")
+ ]
groups: dict[str, dict[str, dict[str, str]]] = {}
for hog_function_id, template_id, filters in rows:
diff --git a/products/billing_alerts/backend/facade/api.py b/products/billing_alerts/backend/facade/api.py
index 15ac08b7f320..15d31c1bb15e 100644
--- a/products/billing_alerts/backend/facade/api.py
+++ b/products/billing_alerts/backend/facade/api.py
@@ -183,6 +183,14 @@ def slack_integration_belongs_to_team(*, integration_id: int, team_id: int) -> b
).exists()
+def _raise_if_billing_alert_already_has_this_destination_type(
+ alert: BillingAlertConfiguration, destination_type: DestinationType
+) -> None:
+ existing_types = {destination["type"] for destination in destinations_for_alerts([alert]).get(str(alert.id), [])}
+ if destination_type.value in existing_types:
+ raise DRFValidationError({"type": f"A {destination_type.label} destination already exists."})
+
+
def create_destination(alert: BillingAlertConfiguration, *, request: Any, data: dict[str, Any]) -> list[UUID]:
destination_data = cast(AlertDestinationData, data)
validate_destination_data(destination_data, allowed_destination_types=BILLING_DESTINATION_TYPES)
@@ -204,11 +212,7 @@ def create_destination(alert: BillingAlertConfiguration, *, request: Any, data:
raise DRFValidationError(
{"slack_workspace_id": "Slack integration does not belong to this billing alert execution team."}
)
- existing_types = {
- destination["type"] for destination in destinations_for_alerts([locked_alert]).get(str(locked_alert.id), [])
- }
- if destination_data["type"].value in existing_types:
- raise DRFValidationError({"type": f"A {destination_data['type'].label} destination already exists."})
+ _raise_if_billing_alert_already_has_this_destination_type(locked_alert, destination_data["type"])
configs = [
build_alert_destination_config(
team=locked_alert.team,
@@ -220,7 +224,12 @@ def create_destination(alert: BillingAlertConfiguration, *, request: Any, data:
)
for kind in EVENT_KINDS
]
- hog_functions = create_alert_destination_hog_functions(configs, request=request)
+ hog_functions = create_alert_destination_hog_functions(
+ configs,
+ request=request,
+ alert_id=str(locked_alert.id),
+ allowed_event_ids=BILLING_ALERT_EVENT_IDS,
+ )
return [hog_function.id for hog_function in hog_functions]
diff --git a/products/billing_alerts/backend/presentation/serializers.py b/products/billing_alerts/backend/presentation/serializers.py
index 30c5244ef559..97f7db5cd100 100644
--- a/products/billing_alerts/backend/presentation/serializers.py
+++ b/products/billing_alerts/backend/presentation/serializers.py
@@ -27,6 +27,8 @@ from products.billing_alerts.backend.facade.api import (
_DESTINATIONS_CACHE_KEY = "_billing_alert_destinations_by_alert_id"
_NOT_PROVIDED = object()
+MAX_DESTINATION_IDS_PER_DELETE_REQUEST = 100
+
def _any_field_changed(
instance: BillingAlertConfiguration,
@@ -160,8 +162,8 @@ class BillingAlertDestinationChangesSerializer(serializers.Serializer):
delete = serializers.ListField(
child=serializers.ListField(
child=serializers.UUIDField(),
- min_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
- max_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ min_length=1,
+ max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
),
required=False,
default=list,
@@ -438,8 +440,8 @@ class BillingAlertConfigurationSerializer(serializers.ModelSerializer):
class BillingAlertDeleteDestinationSerializer(serializers.Serializer):
hog_function_ids = serializers.ListField(
child=serializers.UUIDField(),
- min_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
- max_length=len(billing_alerts_api.BILLING_ALERT_EVENT_IDS),
+ min_length=1,
+ max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
help_text="HogFunction IDs to delete as one atomic destination group.",
)
diff --git a/products/billing_alerts/backend/test/test_alert_destinations.py b/products/billing_alerts/backend/test/test_alert_destinations.py
index 4438e40f512f..06fe988fa710 100644
--- a/products/billing_alerts/backend/test/test_alert_destinations.py
+++ b/products/billing_alerts/backend/test/test_alert_destinations.py
@@ -194,6 +194,20 @@ class TestBillingAlertDestinations(APIBaseTest):
BILLING_ALERT_EVENT_IDS
)
+ def test_create_destination_rejects_a_duplicate_of_a_disabled_group(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+ payload = {"type": "webhook", "webhook_url": "https://example.com/billing-alert"}
+ first = self.client.post(f"{self.url}{alert.id}/destinations/", payload, format="json")
+ assert first.status_code == status.HTTP_201_CREATED, first.json()
+ HogFunction.objects.filter(id__in=first.json()["hog_function_ids"]).update(enabled=False)
+
+ second = self.client.post(f"{self.url}{alert.id}/destinations/", payload, format="json")
+
+ assert second.status_code == status.HTTP_400_BAD_REQUEST
+ assert second.json()["detail"] == "This destination is already configured for this alert."
+ assert HogFunction.objects.filter(team=self.team, deleted=False).count() == len(BILLING_ALERT_EVENT_IDS)
+
def test_create_destination_locks_alert_before_duplicate_check(self) -> None:
self._sync_webhook_template()
alert = self._alert()
@@ -227,6 +241,56 @@ class TestBillingAlertDestinations(APIBaseTest):
id__in=[destination.id for destination in destinations], deleted=True
).count() == len(destinations)
+ def test_delete_destination_removes_a_group_whose_config_is_readable(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+ created = self.client.post(
+ f"{self.url}{alert.id}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/billing-alert"},
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ hog_function_ids = created.json()["hog_function_ids"]
+
+ response = self.client.post(
+ f"{self.url}{alert.id}/destinations/delete/",
+ {"hog_function_ids": hog_function_ids},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.json()
+ assert HogFunction.objects.filter(id__in=hog_function_ids, deleted=False).count() == 0
+
+ def test_delete_destination_removes_a_group_widened_by_an_unreadable_row(self) -> None:
+ self._sync_webhook_template()
+ alert = self._alert()
+ created = self.client.post(
+ f"{self.url}{alert.id}/destinations/",
+ {"type": "webhook", "webhook_url": "https://example.com/billing-alert"},
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ hog_function_ids = created.json()["hog_function_ids"]
+ unreadable = self._destination(alert, BILLING_ALERT_EVENT_IDS[0])
+
+ partial = self.client.post(
+ f"{self.url}{alert.id}/destinations/delete/",
+ {"hog_function_ids": hog_function_ids},
+ format="json",
+ )
+
+ assert partial.status_code == status.HTTP_400_BAD_REQUEST
+ assert "can no longer be read" in partial.json()["detail"]
+
+ response = self.client.post(
+ f"{self.url}{alert.id}/destinations/delete/",
+ {"hog_function_ids": [*hog_function_ids, str(unreadable.id)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.json()
+ assert HogFunction.objects.filter(id__in=[*hog_function_ids, unreadable.id], deleted=False).count() == 0
+
def test_delete_destination_rejects_another_alerts_hog_function(self) -> None:
alert = self._alert()
other_alert = self._alert("Other alert")
diff --git a/products/billing_alerts/frontend/generated/api.schemas.ts b/products/billing_alerts/frontend/generated/api.schemas.ts
index 8462995242e9..5c685f937475 100644
--- a/products/billing_alerts/frontend/generated/api.schemas.ts
+++ b/products/billing_alerts/frontend/generated/api.schemas.ts
@@ -95,8 +95,8 @@ export interface BillingAlertDestinationCreateDataApi {
export interface BillingAlertDestinationChangesApi {
/**
- * @items.minItems 4
- * @items.maxItems 4
+ * @items.minItems 1
+ * @items.maxItems 100
*/
delete?: string[][]
create?: BillingAlertDestinationCreateDataApi[]
@@ -522,8 +522,8 @@ export interface BillingAlertDestinationResponseApi {
export interface BillingAlertDeleteDestinationApi {
/**
* HogFunction IDs to delete as one atomic destination group.
- * @minItems 4
- * @maxItems 4
+ * @minItems 1
+ * @maxItems 100
*/
hog_function_ids: string[]
}
diff --git a/products/billing_alerts/frontend/generated/api.zod.ts b/products/billing_alerts/frontend/generated/api.zod.ts
index 2d5445e92614..05ebe2302ad6 100644
--- a/products/billing_alerts/frontend/generated/api.zod.ts
+++ b/products/billing_alerts/frontend/generated/api.zod.ts
@@ -22,8 +22,7 @@ export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72
export const billingAlertsCreateBodyCooldownHoursMin = 0
export const billingAlertsCreateBodyCooldownHoursMax = 720
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),
@@ -82,12 +81,7 @@ export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
destination_changes: zod
.object({
delete: zod
- .array(
- zod
- .array(zod.uuid())
- .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)
- )
+ .array(zod.array(zod.uuid()).min(1).max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax))
.optional(),
create: zod
.array(
@@ -132,8 +126,7 @@ export const billingAlertsUpdateBodyEvaluationDelayHoursMax = 72
export const billingAlertsUpdateBodyCooldownHoursMin = 0
export const billingAlertsUpdateBodyCooldownHoursMax = 720
-export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(billingAlertsUpdateBodyNameMax).describe('Display name for this billing alert.'),
@@ -192,12 +185,7 @@ export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({
destination_changes: zod
.object({
delete: zod
- .array(
- zod
- .array(zod.uuid())
- .min(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax)
- )
+ .array(zod.array(zod.uuid()).min(1).max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax))
.optional(),
create: zod
.array(
@@ -242,8 +230,7 @@ export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72
export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0
export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
@@ -307,10 +294,7 @@ export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.object({
delete: zod
.array(
- zod
- .array(zod.uuid())
- .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
+ zod.array(zod.uuid()).min(1).max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
)
.optional(),
create: zod
@@ -360,13 +344,12 @@ export const BillingAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
/**
* Delete a notification destination by deleting its HogFunction group atomically.
*/
-export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin = 4
-export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4
+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 100
export const BillingAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
hog_function_ids: zod
.array(zod.uuid())
- .min(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin)
+ .min(1)
.max(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)
.describe('HogFunction IDs to delete as one atomic destination group.'),
})
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index 0472efc3126b..66dfdc7afd6a 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -29,19 +29,20 @@ from posthog.models.user import User
from posthog.utils import relative_date_parse
from products.alerts.backend.facade.api import (
- DESTINATION_TEMPLATE_IDS,
+ DESTINATION_SPECS,
AlertDestinationData,
AlertDestinationValidationError,
AlertScheduleRestriction,
DestinationType,
build_alert_destination_config,
create_alert_destination_hog_functions,
+ list_alert_destination_groups,
+ owned_alert_destinations_qs,
soft_delete_alert_destinations,
soft_delete_all_alert_destinations,
validate_and_normalize_schedule_restriction,
validate_destination_data,
)
-from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.logs.backend.alert_check_query import AlertCheckQuery, BucketedCount
from products.logs.backend.alert_destinations import (
EVENT_KIND_CONFIG,
@@ -81,6 +82,7 @@ UNCAPPED_ALERT_TEAM_IDS: frozenset[int] = frozenset(
)
MAX_SIMULATE_LOOKBACK_DAYS = 30
MAX_SIMULATE_BUCKETS = 15_000
+MAX_DESTINATION_IDS_PER_DELETE_REQUEST = 100
class LogsAlertListQuerySerializer(serializers.Serializer):
@@ -159,6 +161,27 @@ class ScheduleRestrictionField(serializers.JSONField):
pass
+class LogsAlertDestinationResponseSerializer(serializers.Serializer):
+ hog_function_ids = serializers.ListField(child=serializers.UUIDField())
+
+
+class LogsAlertDestinationConfigSerializer(LogsAlertDestinationResponseSerializer):
+ type = serializers.ChoiceField(choices=LOGS_DESTINATION_TYPES, help_text="Notification destination type.")
+ enabled = serializers.BooleanField(
+ help_text=(
+ "Whether every HogFunction in the group is enabled, so the destination notifies for all "
+ "alert event kinds. This is the stored setting: a destination PostHog stopped delivering "
+ "to after repeated failures still reads as true."
+ )
+ )
+ slack_workspace_id = serializers.IntegerField(required=False)
+ slack_channel_id = serializers.CharField(required=False)
+ webhook_url = serializers.CharField(
+ required=False,
+ help_text="Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret.",
+ )
+
+
class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(
read_only=True,
@@ -376,16 +399,14 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
@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
+ # Only template_id is read. Reading the whole destination would pull its stored
+ # inputs, several KB per row, for every alert on the page.
+ # N+1 is acceptable: max 20 alerts per team, each query a fast indexed lookup.
configured_template_ids = set(
- HogFunction.objects.filter(
- team_id=team_id,
- deleted=False,
- 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)}],
+ owned_alert_destinations_qs(
+ team_id=obj.team_id,
+ alert_ids=[str(obj.id)],
+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,
)
.values_list("template_id", flat=True)
.distinct()
@@ -393,7 +414,7 @@ class LogsAlertConfigurationSerializer(serializers.ModelSerializer):
return sorted(
destination_type.value
for destination_type in LOGS_DESTINATION_TYPES
- if DESTINATION_TEMPLATE_IDS[destination_type] in configured_template_ids
+ if DESTINATION_SPECS[destination_type].template_id in configured_template_ids
)
@extend_schema_field(serializers.CharField(allow_null=True))
@@ -617,6 +638,39 @@ def _validate_filters(filters: dict) -> None:
)
+class LogsAlertConfigurationDetailSerializer(LogsAlertConfigurationSerializer):
+ """One alert, with the destinations attached to it. The list endpoint leaves them out:
+ reading a destination pulls its stored inputs, which run to several KB per row."""
+
+ destinations = serializers.SerializerMethodField(
+ help_text=(
+ "This alert's notification destinations, one entry per destination. Each carries the "
+ "HogFunction IDs that delete it as a group, and its configuration with credential-bearing "
+ "URL components removed."
+ ),
+ )
+
+ class Meta(LogsAlertConfigurationSerializer.Meta):
+ fields = [*LogsAlertConfigurationSerializer.Meta.fields, "destinations"]
+ read_only_fields = [*LogsAlertConfigurationSerializer.Meta.read_only_fields, "destinations"]
+
+ @extend_schema_field(LogsAlertDestinationConfigSerializer(many=True))
+ def get_destinations(self, obj: LogsAlertConfiguration) -> list[dict[str, Any]]:
+ groups = list_alert_destination_groups(
+ team_id=obj.team_id,
+ alert_id=str(obj.id),
+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,
+ )
+ return [
+ {
+ "hog_function_ids": list(group.hog_function_ids),
+ "enabled": group.fully_enabled,
+ **DESTINATION_SPECS[DestinationType(group.data["type"])].redact(group.data),
+ }
+ for group in groups
+ ]
+
+
class LogsAlertEventSerializer(serializers.ModelSerializer):
class Meta:
model = LogsAlertEvent
@@ -753,15 +807,10 @@ 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.",
)
-class LogsAlertDestinationResponseSerializer(serializers.Serializer):
- hog_function_ids = serializers.ListField(child=serializers.UUIDField())
-
-
def _build_reason(
prev_state: AlertState,
outcome: AlertCheckOutcome,
@@ -862,6 +911,13 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = LogsAlertConfigurationSerializer
lookup_field = "id"
+ def get_serializer_class(self) -> type[LogsAlertConfigurationSerializer]:
+ # Only a single-alert read carries the destinations. Every other action would pay
+ # for their stored inputs without a caller that wants them.
+ if self.action == "retrieve":
+ return LogsAlertConfigurationDetailSerializer
+ return LogsAlertConfigurationSerializer
+
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
if self.action == "list":
query_serializer = LogsAlertListQuerySerializer(data=self.request.query_params)
@@ -967,7 +1023,12 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
for kind in EVENT_KINDS
]
- hog_functions = create_alert_destination_hog_functions(configs, request=self.request)
+ hog_functions = create_alert_destination_hog_functions(
+ configs,
+ request=self.request,
+ alert_id=str(alert.id),
+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,
+ )
report_user_action(
request.user,
@@ -991,6 +1052,14 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
with transaction.atomic():
alert = self._get_locked_alert()
+ groups = list_alert_destination_groups(
+ team_id=self.team_id,
+ alert_id=str(alert.id),
+ allowed_event_ids=LOGS_ALERT_EVENT_IDS,
+ )
+ largest_server_group = max((len(group.hog_function_ids) for group in groups), default=0)
+ if len(hog_function_ids) > max(MAX_DESTINATION_IDS_PER_DELETE_REQUEST, largest_server_group):
+ raise ValidationError({"hog_function_ids": "Too many destination IDs."})
soft_delete_alert_destinations(
team_id=self.team_id,
alert_id=str(alert.id),
diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.py
index aa90e9cea864..366607cc3be8 100644
--- a/products/logs/backend/test/test_alerts_api.py
+++ b/products/logs/backend/test/test_alerts_api.py
@@ -27,6 +27,8 @@ from products.logs.backend.presentation.views.alerts_api import (
ALLOWED_WINDOW_MINUTES,
LOGS_ALERT_EVENT_IDS,
MAX_ALERTS_PER_TEAM,
+ MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
+ LogsAlertViewSet,
)
@@ -801,6 +803,11 @@ class TestLogsAlertAPI(APIBaseTest):
def _destinations_url(self, alert_id: str) -> str:
return f"{self.base_url}{alert_id}/destinations/"
+ def _read_destinations(self, alert_id: str) -> list[dict]:
+ response = self.client.get(f"{self.base_url}{alert_id}/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return response.json()["destinations"]
+
def _destinations_delete_url(self, alert_id: str) -> str:
return f"{self.base_url}{alert_id}/destinations/delete/"
@@ -926,6 +933,84 @@ class TestLogsAlertAPI(APIBaseTest):
assert text_value.startswith("**")
assert "[View logs](" in text_value or "[View alert](" in text_value
+ def test_reading_an_alert_groups_its_destinations_and_strips_webhook_credentials(self) -> None:
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ webhook_url = "https://user:[email protected]:8443/hooks/credential?token=secret"
+ create_response = self.client.post(
+ self._destinations_url(created["id"]),
+ {"type": "webhook", "webhook_url": webhook_url},
+ format="json",
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED
+
+ response = self.client.get(f"{self.base_url}{created['id']}/")
+
+ assert response.status_code == status.HTTP_200_OK
+ destinations = response.json()["destinations"]
+ assert len(destinations) == 1
+ assert set(destinations[0]["hog_function_ids"]) == set(create_response.json()["hog_function_ids"])
+ assert destinations[0]["type"] == "webhook"
+ # Host and port survive so two webhooks are tellable apart; the secret does not.
+ assert destinations[0]["webhook_url"] == "https://example.com:8443"
+ body = response.content.decode()
+ assert "password" not in body
+ assert "token=secret" not in body
+
+ def test_reading_an_alert_redacts_a_malformed_stored_webhook_url(self) -> None:
+ 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",
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED
+ hog_function = HogFunction.objects.get(id=create_response.json()["hog_function_ids"][0])
+ inputs = hog_function.inputs or {}
+ inputs["url"]["value"] = "https://[broken/path"
+ hog_function.inputs = inputs
+ hog_function.save(update_fields=["inputs"])
+
+ assert self._read_destinations(created["id"])[0]["webhook_url"] == "<redacted>"
+
+ def test_listing_alerts_reports_destination_types_without_reading_each_destination(self) -> None:
+ 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",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+
+ listed = self.client.get(self.base_url)
+
+ assert listed.status_code == status.HTTP_200_OK
+ alert = next(row for row in listed.json()["results"] if row["id"] == created["id"])
+ assert alert["destination_types"] == ["webhook"]
+ # Reading a destination pulls its stored inputs, so the list must not carry them.
+ assert "destinations" not in alert
+
+ def test_a_destination_reports_disabled_when_one_of_its_hog_functions_is_off(self) -> None:
+ 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",
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED
+ hog_function_ids = create_response.json()["hog_function_ids"]
+ assert self._read_destinations(created["id"])[0]["enabled"] is True
+
+ HogFunction.objects.filter(id=hog_function_ids[0]).update(enabled=False)
+
+ destinations = self._read_destinations(created["id"])
+ assert len(destinations) == 1
+ assert destinations[0]["enabled"] is False
+ assert set(destinations[0]["hog_function_ids"]) == set(hog_function_ids)
+
@parameterized.expand(
[
("slack_missing_workspace", {"type": "slack", "slack_channel_id": "C1"}),
@@ -1021,17 +1106,220 @@ class TestLogsAlertAPI(APIBaseTest):
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):
+ def test_delete_destination_rejects_more_ids_than_the_request_cap(self):
+ created = self._create_via_api()
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": [str(uuid4()) for _ in range(MAX_DESTINATION_IDS_PER_DELETE_REQUEST + 1)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "hog_function_ids"
+
+ def _create_destination(self, alert_id: str, payload: dict) -> list[str]:
+ response = self.client.post(self._destinations_url(alert_id), payload, format="json")
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ return response.json()["hog_function_ids"]
+
+ @parameterized.expand(
+ [
+ (
+ "two_slack_channels",
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C111", "slack_channel_name": "eng"},
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C222", "slack_channel_name": "ops"},
+ ),
+ (
+ "two_webhook_urls",
+ {"type": "webhook", "webhook_url": "https://example.com/a"},
+ {"type": "webhook", "webhook_url": "https://example.com/b"},
+ ),
+ ]
+ )
+ def test_delete_destination_removes_only_the_named_destination(
+ self, _name: str, first_payload: dict, second_payload: dict
+ ):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ first_ids = self._create_destination(created["id"], first_payload)
+ second_ids = self._create_destination(created["id"], second_payload)
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": first_ids},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.json()
+ assert HogFunction.objects.filter(id__in=first_ids, deleted=False).count() == 0
+ assert HogFunction.objects.filter(id__in=second_ids, deleted=False, enabled=True).count() == len(second_ids)
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": second_ids},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.json()
+ assert HogFunction.objects.filter(id__in=second_ids, deleted=False).count() == 0
+
+ def test_delete_destination_rejects_partial_group(self):
+ self._sync_destination_templates()
created = self._create_via_api()
+ ids = self._create_destination(created["id"], {"type": "webhook", "webhook_url": "https://example.com/hook"})
response = self.client.post(
self._destinations_delete_url(created["id"]),
- {"hog_function_ids": [str(uuid4()) for _ in range(len(LOGS_ALERT_EVENT_IDS) + 1)]},
+ {"hog_function_ids": ids[:-1]},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["attr"] == "hog_function_ids"
+ assert "Delete all destinations in this group together." in response.json()["detail"]
+ assert HogFunction.objects.filter(id__in=ids, deleted=False, enabled=True).count() == len(ids)
+
+ @parameterized.expand(
+ [
+ (
+ "slack_channel",
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C111", "slack_channel_name": "eng"},
+ ),
+ ("webhook_url", {"type": "webhook", "webhook_url": "https://example.com/hook"}),
+ ]
+ )
+ def test_create_destination_rejects_a_duplicate_of_an_existing_destination(self, _name: str, payload: dict):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ ids = self._create_destination(created["id"], payload)
+
+ response = self.client.post(self._destinations_url(created["id"]), payload, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == "This destination is already configured for this alert."
+ assert HogFunction.objects.filter(id__in=ids, deleted=False, enabled=True).count() == len(ids)
+ assert HogFunction.objects.filter(team=self.team, deleted=False).count() == len(LOGS_ALERT_EVENT_IDS)
+
+ def test_create_destination_locks_the_alert_row_before_the_duplicate_check(self):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+
+ with patch.object(
+ LogsAlertViewSet,
+ "_get_locked_alert",
+ autospec=True,
+ side_effect=LogsAlertViewSet._get_locked_alert,
+ ) as get_locked_alert:
+ response = self.client.post(
+ self._destinations_url(created["id"]),
+ {"type": "webhook", "webhook_url": "https://example.com/hook"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ get_locked_alert.assert_called_once()
+
+ def _clone_row_without_the_duplicate_check(self, hog_function: HogFunction) -> HogFunction:
+ return HogFunction.objects.create(
+ team=self.team,
+ name=hog_function.name,
+ type=hog_function.type,
+ template_id=hog_function.template_id,
+ enabled=True,
+ inputs_schema=hog_function.inputs_schema,
+ inputs=hog_function.inputs,
+ hog=hog_function.hog,
+ filters=hog_function.filters,
+ )
+
+ def test_delete_destination_removes_a_pre_existing_duplicate_pair(self):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ ids = self._create_destination(created["id"], {"type": "webhook", "webhook_url": "https://example.com/hook"})
+ duplicate_ids = [
+ str(self._clone_row_without_the_duplicate_check(hog_function).id)
+ for hog_function in HogFunction.objects.filter(id__in=ids)
+ ]
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": [*ids, *duplicate_ids]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.json()
+ assert HogFunction.objects.filter(id__in=[*ids, *duplicate_ids], deleted=False).count() == 0
+
+ def test_delete_destination_accepts_a_server_group_larger_than_100_ids(self) -> None:
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ ids = self._create_destination(created["id"], {"type": "webhook", "webhook_url": "https://example.com/hook"})
+ source = HogFunction.objects.get(id=ids[0])
+ duplicate_ids = [str(self._clone_row_without_the_duplicate_check(source).id) for _ in range(100)]
+ source.inputs = {}
+ source.save(update_fields=["inputs"])
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": [*ids, *duplicate_ids]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert HogFunction.objects.filter(id__in=[*ids, *duplicate_ids], deleted=False).count() == 0
+
+ def test_delete_destination_rejects_more_ids_than_any_server_group(self) -> None:
+ created = self._create_via_api()
+
+ response = self.client.post(
+ self._destinations_delete_url(created["id"]),
+ {"hog_function_ids": [str(uuid4()) for _ in range(101)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Too many destination IDs" in str(response.json())
+
+ def test_delete_alert_removes_both_destinations_of_the_same_type(self):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ first_ids = self._create_destination(created["id"], {"type": "webhook", "webhook_url": "https://example.com/a"})
+ second_ids = self._create_destination(
+ created["id"], {"type": "webhook", "webhook_url": "https://example.com/b"}
+ )
+
+ response = self.client.delete(f"{self.base_url}{created['id']}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert HogFunction.objects.filter(id__in=[*first_ids, *second_ids], deleted=False).count() == 0
+
+ def test_destination_types_ignores_a_row_carrying_another_products_event(self):
+ self._sync_destination_templates()
+ created = self._create_via_api()
+ self._create_destination(
+ created["id"],
+ {"type": "slack", "slack_workspace_id": 42, "slack_channel_id": "C111", "slack_channel_name": "eng"},
+ )
+ HogFunction.objects.create(
+ team=self.team,
+ name="Billing alert destination",
+ type="destination",
+ template_id="template-webhook",
+ enabled=True,
+ inputs_schema=[{"key": "url", "type": "string"}],
+ inputs={"url": {"value": "https://example.com/hook"}},
+ hog="return event",
+ filters={
+ "events": [{"id": "$billing_alert_firing", "type": "events"}],
+ "properties": [{"key": "alert_id", "value": created["id"]}],
+ },
+ )
+
+ response = self.client.get(f"{self.base_url}{created['id']}/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["destination_types"] == ["slack"]
# --- Reset ---
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index c2ab570680e4..bd70df818495 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -634,6 +634,128 @@ export interface PaginatedLogsAlertConfigurationListApi {
results: LogsAlertConfigurationApi[]
}
+export interface LogsAlertDestinationConfigApi {
+ hog_function_ids: string[]
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams */
+ type: NotificationDestinationTypeEnumApi
+ /** Whether every HogFunction in the group is enabled, so the destination notifies for all alert event kinds. This is the stored setting: a destination PostHog stopped delivering to after repeated failures still reads as true. */
+ enabled: boolean
+ slack_workspace_id?: number
+ slack_channel_id?: string
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string
+}
+
+/**
+ * One alert, with the destinations attached to it. The list endpoint leaves them out:
+ * reading a destination pulls its stored inputs, which run to several KB per row.
+ */
+export interface LogsAlertConfigurationDetailApi {
+ /** Unique identifier for this alert. */
+ readonly id: string
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string
+ /** Whether the alert is actively being evaluated. Disabling resets the state to not_firing. */
+ enabled?: boolean
+ /** Filter criteria — subset of LogsViewerFilters. Must contain at least one of: severityLevels (list of severity strings), serviceNames (list of service name strings), or filterGroup (property filter group object). May be empty on draft alerts (enabled=false). */
+ filters?: LogsAlertFiltersApi
+ /**
+ * Number of matching log entries that constitutes a threshold breach within the evaluation window. Defaults to 100. Use 0 with the 'above' operator to fire on any matching log.
+ * @minimum 0
+ */
+ threshold_count?: number
+ /** Whether the alert fires when the count is above or below the threshold.
+ *
+ * * `above` - Above
+ * * `below` - Below */
+ threshold_operator?: LogsAlertThresholdOperatorEnumApi
+ /** Time window in minutes over which log entries are counted. Allowed values: 5, 10, 15, 30, 60. */
+ window_minutes?: number
+ /** How often the alert is evaluated, in minutes. Server-managed. */
+ readonly check_interval_minutes: number
+ /** Current alert state: not_firing, firing, pending_resolve, errored, or snoozed. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: LogsAlertConfigurationStateEnumApi
+ /**
+ * Total number of check periods in the sliding evaluation window for firing (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number
+ /**
+ * How many periods within the evaluation window must breach the threshold to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number
+ /**
+ * Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestrictionApi | null
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at: string | null
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at: string | null
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at: string | null
+ /** Number of consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures: number
+ /**
+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.
+ * @nullable
+ */
+ readonly last_error_message: string | null
+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */
+ readonly state_timeline: readonly LogsAlertStateIntervalApi[]
+ /** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
+ readonly destination_types: readonly NotificationDestinationTypeEnumApi[]
+ /**
+ * When the alert was first enabled. Null means the alert is still in draft state.
+ * @nullable
+ */
+ readonly first_enabled_at: string | null
+ /** When the alert was created. */
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at: string | null
+ /** This alert's notification destinations, one entry per destination. Each carries the HogFunction IDs that delete it as a group, and its configuration with credential-bearing URL components removed. */
+ readonly destinations: readonly LogsAlertDestinationConfigApi[]
+}
+
export interface PatchedLogsAlertConfigurationApi {
/** Unique identifier for this alert. */
readonly id?: string
@@ -759,7 +881,6 @@ 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.ts b/products/logs/frontend/generated/api.ts
index 6e1bfcafaf7b..08532467a085 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
ExplainRequestApi,
LogsAlertConfigurationApi,
+ LogsAlertConfigurationDetailApi,
LogsAlertCreateDestinationApi,
LogsAlertDeleteDestinationApi,
LogsAlertDestinationResponseApi,
@@ -143,8 +144,8 @@ export const logsAlertsRetrieve = async (
projectId: string,
id: string,
options?: RequestInit
-): Promise<LogsAlertConfigurationApi> => {
- return apiMutator<LogsAlertConfigurationApi>(getLogsAlertsRetrieveUrl(projectId, id), {
+): Promise<LogsAlertConfigurationDetailApi> => {
+ return apiMutator<LogsAlertConfigurationDetailApi>(getLogsAlertsRetrieveUrl(projectId, id), {
...options,
method: 'GET',
})
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index e565b8d141c2..68b8de29c44a 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -395,13 +395,11 @@ export const LogsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
/**
* Delete a notification destination by deleting its HogFunction group atomically.
*/
-export const logsAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4
export 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/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
index 7d6683e90493..47d848bf18dd 100644
--- a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts
@@ -39,6 +39,7 @@ import {
} from 'products/logs/frontend/generated/api.schemas'
import type { LogsAlertFormType } from '../../components/LogsAlerting/logsAlertFormLogic'
+import type { LogsAlertConfigurationDetailApi } from '../../generated/api.schemas'
export type LogsAlertDetailTab = 'configuration' | 'notifications' | 'history' | 'logs'
const VALID_TABS: LogsAlertDetailTab[] = ['configuration', 'notifications', 'history', 'logs']
@@ -120,10 +121,10 @@ export interface logsAlertDetailSceneLogicActions {
errorObject?: any
}
loadAlertSuccess: (
- alert: LogsAlertConfigurationApi,
+ alert: LogsAlertConfigurationDetailApi,
payload?: any
) => {
- alert: LogsAlertConfigurationApi
+ alert: LogsAlertConfigurationDetailApi
payload?: any
}
loadSparkline7d: () => any
diff --git a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/logsAlertNotificationDetailSceneLogic.ts b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/logsAlertNotificationDetailSceneLogic.ts
index aacfd5026fa0..9b186c9c8bd8 100644
--- a/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/logsAlertNotificationDetailSceneLogic.ts
+++ b/products/logs/frontend/scenes/LogsAlertNotificationDetailScene/logsAlertNotificationDetailSceneLogic.ts
@@ -22,6 +22,8 @@ import {
import { logsAlertsDestinationsDeleteCreate, logsAlertsRetrieve } from 'products/logs/frontend/generated/api'
import { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'
+import type { LogsAlertConfigurationDetailApi } from '../../generated/api.schemas'
+
export interface LogsAlertNotificationDetailSceneLogicProps {
alertId: string
hogFunctionId: string
@@ -63,10 +65,10 @@ export interface logsAlertNotificationDetailSceneLogicActions {
errorObject?: any
}
loadAlertSuccess: (
- alert: LogsAlertConfigurationApi | null,
+ alert: LogsAlertConfigurationDetailApi | null,
payload?: any
) => {
- alert: LogsAlertConfigurationApi | null
+ alert: LogsAlertConfigurationDetailApi | null
payload?: any
}
loadHogFunctions: () => any
diff --git a/pyproject.toml b/pyproject.toml
index 25bb41ce48d4..6c09b6416f03 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -612,7 +612,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.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 sandbox
# directly. Thin it to parse -> facade -> serialize and delete each entry.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c784fb698586..dd3a52f4bc78 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13598,8 +13598,8 @@ export namespace Schemas {
export interface BillingAlertDestinationChanges {
/**
- * @items.minItems 4
- * @items.maxItems 4
+ * @items.minItems 1
+ * @items.maxItems 100
*/
delete?: string[][];
create?: BillingAlertDestinationCreateData[];
@@ -13732,8 +13732,8 @@ export namespace Schemas {
export interface BillingAlertDeleteDestination {
/**
* HogFunction IDs to delete as one atomic destination group.
- * @minItems 4
- * @maxItems 4
+ * @minItems 1
+ * @maxItems 100
*/
hog_function_ids: string[];
}
@@ -46491,6 +46491,128 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ export interface LogsAlertDestinationConfig {
+ hog_function_ids: string[];
+ /** Notification destination type.
+ *
+ * * `slack` - slack
+ * * `webhook` - webhook
+ * * `teams` - teams */
+ type: NotificationDestinationTypeEnum;
+ /** Whether every HogFunction in the group is enabled, so the destination notifies for all alert event kinds. This is the stored setting: a destination PostHog stopped delivering to after repeated failures still reads as true. */
+ enabled: boolean;
+ slack_workspace_id?: number;
+ slack_channel_id?: string;
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string;
+ }
+
+ /**
+ * One alert, with the destinations attached to it. The list endpoint leaves them out:
+ * reading a destination pulls its stored inputs, which run to several KB per row.
+ */
+ export interface LogsAlertConfigurationDetail {
+ /** Unique identifier for this alert. */
+ readonly id: string;
+ /**
+ * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
+ * @maxLength 255
+ */
+ name?: string;
+ /** Whether the alert is actively being evaluated. Disabling resets the state to not_firing. */
+ enabled?: boolean;
+ /** Filter criteria — subset of LogsViewerFilters. Must contain at least one of: severityLevels (list of severity strings), serviceNames (list of service name strings), or filterGroup (property filter group object). May be empty on draft alerts (enabled=false). */
+ filters?: LogsAlertFilters;
+ /**
+ * Number of matching log entries that constitutes a threshold breach within the evaluation window. Defaults to 100. Use 0 with the 'above' operator to fire on any matching log.
+ * @minimum 0
+ */
+ threshold_count?: number;
+ /** Whether the alert fires when the count is above or below the threshold.
+ *
+ * * `above` - Above
+ * * `below` - Below */
+ threshold_operator?: LogsAlertThresholdOperatorEnum;
+ /** Time window in minutes over which log entries are counted. Allowed values: 5, 10, 15, 30, 60. */
+ window_minutes?: number;
+ /** How often the alert is evaluated, in minutes. Server-managed. */
+ readonly check_interval_minutes: number;
+ /** Current alert state: not_firing, firing, pending_resolve, errored, or snoozed. Server-managed.
+ *
+ * * `not_firing` - Not firing
+ * * `firing` - Firing
+ * * `pending_resolve` - Pending resolve
+ * * `errored` - Errored
+ * * `snoozed` - Snoozed
+ * * `broken` - Broken */
+ readonly state: LogsAlertConfigurationStateEnum;
+ /**
+ * Total number of check periods in the sliding evaluation window for firing (M in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ evaluation_periods?: number;
+ /**
+ * How many periods within the evaluation window must breach the threshold to fire (N in N-of-M).
+ * @minimum 1
+ * @maximum 10
+ */
+ datapoints_to_alarm?: number;
+ /**
+ * Minimum minutes between repeated notifications after the alert fires. 0 means no cooldown.
+ * @minimum 0
+ */
+ cooldown_minutes?: number;
+ /** Blocked local time windows when the alert must not run. Times use the project timezone. Null disables quiet hours. */
+ schedule_restriction?: AlertScheduleRestriction | null;
+ /**
+ * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
+ * @nullable
+ */
+ snooze_until?: string | null;
+ /**
+ * When the next evaluation is scheduled. Server-managed.
+ * @nullable
+ */
+ readonly next_check_at: string | null;
+ /**
+ * When the last notification was sent. Server-managed.
+ * @nullable
+ */
+ readonly last_notified_at: string | null;
+ /**
+ * When the alert was last evaluated. Server-managed.
+ * @nullable
+ */
+ readonly last_checked_at: string | null;
+ /** Number of consecutive evaluation failures. Resets on success. Server-managed. */
+ readonly consecutive_failures: number;
+ /**
+ * Error message from the most recent errored check, or null if the alert's most recent check was successful. Sourced from LogsAlertEvent without denormalization so retention-aware cleanup rules stay the only source of truth.
+ * @nullable
+ */
+ readonly last_error_message: string | null;
+ /** Continuous state intervals over the last 24h, ordered oldest-first. Each interval covers a span during which (state, enabled) was constant. Derived from LogsAlertEvent rows walked in chronological order; consecutive identical intervals are collapsed. Drives the 'Last 24h' status bar on the alert list. */
+ readonly state_timeline: readonly LogsAlertStateInterval[];
+ /** Notification destination types configured for this alert — e.g. 'slack', 'webhook'. Empty list means no notifications will fire. One or more destinations should be added after creating an alert. */
+ readonly destination_types: readonly NotificationDestinationTypeEnum[];
+ /**
+ * When the alert was first enabled. Null means the alert is still in draft state.
+ * @nullable
+ */
+ readonly first_enabled_at: string | null;
+ /** When the alert was created. */
+ readonly created_at: string;
+ readonly created_by: UserBasic;
+ /**
+ * When the alert was last modified.
+ * @nullable
+ */
+ readonly updated_at: string | null;
+ /** This alert's notification destinations, one entry per destination. Each carries the HogFunction IDs that delete it as a group, and its configuration with credential-bearing URL components removed. */
+ readonly destinations: readonly LogsAlertDestinationConfig[];
+ }
+
export interface LogsAlertCreateDestination {
/** Notification destination type.
*
@@ -46512,7 +46634,6 @@ 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/billing_alerts/api.ts b/services/mcp/src/generated/billing_alerts/api.ts
index 11d8f500a49f..82b27baa047a 100644
--- a/services/mcp/src/generated/billing_alerts/api.ts
+++ b/services/mcp/src/generated/billing_alerts/api.ts
@@ -29,8 +29,7 @@ export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72
export const billingAlertsCreateBodyCooldownHoursMin = 0
export const billingAlertsCreateBodyCooldownHoursMax = 720
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),
@@ -89,12 +88,7 @@ export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({
destination_changes: zod
.object({
delete: zod
- .array(
- zod
- .array(zod.string())
- .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)
- )
+ .array(zod.array(zod.string()).min(1).max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax))
.optional(),
create: zod
.array(
@@ -148,8 +142,7 @@ export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72
export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0
export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4
-export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4
+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 100
export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
@@ -213,10 +206,7 @@ export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({
.object({
delete: zod
.array(
- zod
- .array(zod.string())
- .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)
- .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
+ zod.array(zod.string()).min(1).max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)
)
.optional(),
create: zod
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index 97b09a79f604..6cde3fc2bfa7 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -3636,13 +3636,10 @@ 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.ts
index 5772a6a3d75a..189a80408ea8 100644
--- a/services/mcp/src/tools/generated/logs.ts
+++ b/services/mcp/src/tools/generated/logs.ts
@@ -352,12 +352,12 @@ const logsAlertsPartialUpdate = (): ToolBase<typeof LogsAlertsPartialUpdateSchem
const LogsAlertsRetrieveSchema = LogsAlertsRetrieveParams.omit({ project_id: true })
-const logsAlertsRetrieve = (): ToolBase<typeof LogsAlertsRetrieveSchema, Schemas.LogsAlertConfiguration> => ({
+const logsAlertsRetrieve = (): ToolBase<typeof LogsAlertsRetrieveSchema, Schemas.LogsAlertConfigurationDetail> => ({
name: 'logs-alerts-retrieve',
schema: LogsAlertsRetrieveSchema,
handler: async (context: Context, params: z.infer<typeof LogsAlertsRetrieveSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.LogsAlertConfiguration>({
+ const result = await context.api.request<Schemas.LogsAlertConfigurationDetail>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/${encodeURIComponent(String(params.id))}/`,
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json
index f837f92d233a..3683509a0820 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-create.json
@@ -56,8 +56,8 @@
"items": {
"type": "string"
},
- "maxItems": 4,
- "minItems": 4,
+ "maxItems": 100,
+ "minItems": 1,
"type": "array"
},
"type": "array"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json
index 0b8c7968a83e..be7198c060f2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-alert-update.json
@@ -56,8 +56,8 @@
"items": {
"type": "string"
},
- "maxItems": 4,
- "minItems": 4,
+ "maxItems": 100,
+ "minItems": 1,
"type": "array"
},
"type": "array"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-delete-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-delete-create.json
index 0b0c28ea9454..3a115dad03aa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-delete-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-alerts-destinations-delete-create.json
@@ -6,7 +6,6 @@
"items": {
"type": "string"
},
- "maxItems": 4,
"minItems": 1,
"type": "array"
},