Skip to content

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

feat(alerts): keep the legacy webhook body for grandfathered teams (#116626)

Jimmy Zhu74266335818b
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.py
index ca2aa18eb4c7..f69628f80441 100644
--- a/products/alerts_platform/backend/delivery/evaluation.py
+++ b/products/alerts_platform/backend/delivery/evaluation.py
@@ -4,8 +4,9 @@ The layer that knows a transport exists. `dispatch.deliver` handles one destinat
is what decides which destinations there are and which transport each one takes.
"""
+from collections.abc import Callable
from dataclasses import replace
-from typing import Final
+from typing import Any, Final
import structlog
import posthoganalytics
@@ -13,14 +14,17 @@ import posthoganalytics
from posthog.dataclasses import frozen
from posthog.models import Team
+from products.alerts_platform.backend.delivery import legacy_webhook
from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
from products.alerts_platform.backend.delivery.discord import DiscordTransport
from products.alerts_platform.backend.delivery.dispatch import deliver
from products.alerts_platform.backend.delivery.email import EmailTransport
from products.alerts_platform.backend.delivery.in_app import InAppTransport
+from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport
from products.alerts_platform.backend.delivery.slack import SlackTransport
from products.alerts_platform.backend.delivery.teams import TeamsTransport
+from products.alerts_platform.backend.delivery.telemetry import record_delivery
from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusy
from products.alerts_platform.backend.delivery.transport import DeliveryError, DeliveryTransport
from products.alerts_platform.backend.delivery.webhook import WebhookTransport
@@ -73,19 +77,7 @@ def destinations_are_live(team: Team) -> bool:
is where everything was before this existed. Reading a blip the other way starts sending.
"""
try:
- return bool(
- posthoganalytics.feature_enabled(
- LIVE_DELIVERY_FLAG,
- str(team.uuid),
- groups={"organization": str(team.organization_id), "project": str(team.id)},
- group_properties={
- "organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
- },
- # This runs in a Temporal activity, where a captured event is silently dropped.
- send_feature_flag_events=False,
- )
- )
+ return bool(_team_flag_enabled(LIVE_DELIVERY_FLAG, team))
except Exception:
logger.warning(
"alerts_platform_live_delivery_flag_check_failed_defaulting_off",
@@ -95,6 +87,76 @@ def destinations_are_live(team: Team) -> bool:
return False
+def _team_flag_enabled(flag: str, team: Team) -> bool | None:
+ """None when the flag could not be evaluated: the SDK logs and swallows a failed lookup, and it
+ answers None for a flag that does not exist too."""
+ return posthoganalytics.feature_enabled(
+ flag,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ # Both regions read flags from one PostHog project, and project ids repeat across
+ # regions. A condition on the uuid names one team in one region.
+ "project": {"id": str(team.id), "uuid": str(team.uuid)},
+ },
+ # This runs in a Temporal activity, where a captured event is silently dropped.
+ send_feature_flag_events=False,
+ )
+
+
+class _WebhookTransports:
+ """The webhook transport for one evaluation, with the legacy body when the team keeps it.
+
+ The flag is read once, and only when a webhook destination is about to be sent to. Unlike the
+ live-delivery flag, a failed read is a failed delivery: a guess either way sends a body some
+ receiver cannot parse, and a retry costs only time.
+ """
+
+ def __init__(self, team: Team, request: AlertDeliveryRequest, announced: EvaluationAnnouncement) -> None:
+ self._team = team
+ self._request = request
+ self._announced = announced
+ self._transport: WebhookTransport | None = None
+ self._failure: DeliveryError | None = None
+
+ def get(self) -> WebhookTransport:
+ # A failed read is kept too, so a flags outage costs one lookup per evaluation rather than
+ # one per webhook, inside an activity whose time is shared by every destination.
+ if self._failure is not None:
+ raise self._failure
+ if self._transport is None:
+ try:
+ self._transport = WebhookTransport(legacy_body=self._legacy_body())
+ except DeliveryError as error:
+ self._failure = error
+ raise
+ return self._transport
+
+ def _legacy_body(self) -> Callable[[AlertMessage], dict[str, Any]] | None:
+ body = legacy_webhook.body_for(self._request.source)
+ if body is None:
+ return None
+ try:
+ keeps_legacy_body = _team_flag_enabled(legacy_webhook.LEGACY_WEBHOOK_BODY_FLAG, self._team)
+ except Exception as error:
+ raise DeliveryError("Could not read which webhook body this team receives.") from error
+ if keeps_legacy_body is None:
+ raise DeliveryError("Could not read which webhook body this team receives.")
+ if not keeps_legacy_body:
+ return None
+ team_id = self._team.id
+ alert_id = self._request.destination_alert_id
+ consecutive_failures = self._announced.consecutive_failures
+ return lambda message: body(
+ project_id=team_id,
+ alert_id=alert_id,
+ alert_name=message.alert_name,
+ consecutive_failures=consecutive_failures,
+ transition=message.transition,
+ )
+
+
def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
"""Sends what one evaluation decided, to every destination configured for it."""
team = Team.objects.filter(id=request.team_id).first()
@@ -123,15 +185,30 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:
action_by_event_id = {
event_id: IncidentAction(action) for action, event_id in request.event_ids_by_incident_action.items()
}
+ webhook_transports = _WebhookTransports(team, request, announced)
for event_id, transitions in _by_subscription(request, announced).items():
for target in _destinations(request, event_id):
transport_class = _TRANSPORTS.get(target["type"])
if transport_class is None:
skipped += 1
continue
+ try:
+ transport = webhook_transports.get() if transport_class is WebhookTransport else transport_class()
+ except DeliveryError as error:
+ # Fails before a send starts, where `deliver` counts its failures, so it is counted here.
+ for _ in transitions:
+ record_delivery(
+ team_id=request.team_id,
+ configuration_id=request.configuration_id,
+ provider=WebhookTransport.provider,
+ succeeded=False,
+ )
+ failures.append(str(error))
+ first_refusal = first_refusal or error
+ continue
try:
deliver(
- transport=transport_class(),
+ transport=transport,
thread_store=thread_store,
team_id=request.team_id,
configuration_id=request.configuration_id,
diff --git a/products/alerts_platform/backend/delivery/legacy_webhook.py b/products/alerts_platform/backend/delivery/legacy_webhook.py
new file mode 100644
index 000000000000..fc161b929942
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/legacy_webhook.py
@@ -0,0 +1,29 @@
+"""The webhook body a source's own stack sent, for the teams still allowed to receive it.
+
+A source registers its body when Django starts, the way it registers its describer. Teams that
+had webhook destinations before the platform delivered for them keep that body until a set date,
+so a receiver that parses it does not break when the platform takes over.
+"""
+
+from typing import Final
+
+from products.alerts_platform.backend.facade.contracts import LegacyWebhookBody, SourceKind
+
+# A closed list of teams. No team joins it after the platform delivers for its source.
+LEGACY_WEBHOOK_BODY_FLAG: Final = "alert-platform-legacy-webhook-body"
+
+# The header value the HogFunction path sends with its body.
+LEGACY_WEBHOOK_VERSION: Final = "1"
+
+_bodies: dict[SourceKind, LegacyWebhookBody] = {}
+
+
+def register(source: SourceKind, body: LegacyWebhookBody) -> None:
+ registered = _bodies.get(source)
+ if registered is not None and registered is not body:
+ raise RuntimeError(f"A different legacy webhook body is already registered for {source} alerts.")
+ _bodies[source] = body
+
+
+def body_for(source: SourceKind) -> LegacyWebhookBody | None:
+ return _bodies.get(source)
diff --git a/products/alerts_platform/backend/delivery/webhook.py b/products/alerts_platform/backend/delivery/webhook.py
index 15c4d0183dd4..f2d6d0f2ab25 100644
--- a/products/alerts_platform/backend/delivery/webhook.py
+++ b/products/alerts_platform/backend/delivery/webhook.py
@@ -6,11 +6,13 @@ transition is one message.
"""
import hashlib
+from collections.abc import Callable
from typing import Any, ClassVar, Final
from urllib.parse import urlsplit
from django.conf import settings
+from products.alerts_platform.backend.delivery.legacy_webhook import LEGACY_WEBHOOK_VERSION
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.transport import DeliveryError
from products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport
@@ -91,6 +93,14 @@ class WebhookTransport(WebhookUrlTransport):
display_name = "webhook"
headers: ClassVar[dict[str, str]] = {"X-PostHog-Webhook-Version": WEBHOOK_VERSION}
+ def __init__(self, legacy_body: Callable[[AlertMessage], dict[str, Any]] | None = None) -> None:
+ self._legacy_body = legacy_body
+
+ def headers_for(self) -> dict[str, str]:
+ if self._legacy_body is not None:
+ return {"X-PostHog-Webhook-Version": LEGACY_WEBHOOK_VERSION}
+ return self.headers
+
def check_url(self, url: str) -> None:
# Plain HTTP would expose the URL, which is the credential, and the alert body to anyone on
# the path. Teams and Discord URLs are always HTTPS, so only the generic webhook needs this.
@@ -98,4 +108,6 @@ class WebhookTransport(WebhookUrlTransport):
raise DeliveryError("This webhook destination's URL must use https.")
def body_for(self, message: AlertMessage) -> dict[str, Any]:
+ if self._legacy_body is not None:
+ return self._legacy_body(message)
return alertmanager_body(message)
diff --git a/products/alerts_platform/backend/delivery/webhook_url.py b/products/alerts_platform/backend/delivery/webhook_url.py
index ac35ffd036f9..ba3b576ee45e 100644
--- a/products/alerts_platform/backend/delivery/webhook_url.py
+++ b/products/alerts_platform/backend/delivery/webhook_url.py
@@ -40,13 +40,18 @@ class WebhookUrlTransport(ABC):
if not url:
raise DeliveryError(f"This {self.display_name} destination has no webhook URL.")
self.check_url(url)
- post_json(self.send_url(url), self.body_for(message), display_name=self.display_name, headers=self.headers)
+ post_json(
+ self.send_url(url), self.body_for(message), display_name=self.display_name, headers=self.headers_for()
+ )
return None
def check_url(self, url: str) -> None:
"""Refuses a URL this provider never issues. The SSRF check runs on every send regardless."""
return None
+ def headers_for(self) -> dict[str, str]:
+ return self.headers
+
def send_url(self, url: str) -> str:
"""The URL to post to, which a provider can extend with its own query parameters."""
return url
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 7691c4367a5b..70853f79ab38 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -290,6 +290,8 @@ class AnnouncedTransition:
error_message: str | None
# A resolve states this as the time its firing ended.
occurred_at: datetime
+ # The evaluation this transition came from, so a source can read back what it put in the key.
+ evaluation_key: str = ""
@frozen
@@ -648,6 +650,24 @@ class SourceDescriber(Protocol):
def __call__(self, *, project_id: int, transition: AnnouncedTransition) -> SourceDescription: ...
+class LegacyWebhookBody(Protocol):
+ """The webhook body a source's own stack sent, for teams whose receivers still parse it.
+
+ Runs on the send path like a describer, so it builds the body from its arguments and does no
+ I/O. `alert_id` is the id the source's destinations match on.
+ """
+
+ def __call__(
+ self,
+ *,
+ project_id: int,
+ alert_id: str,
+ alert_name: str,
+ consecutive_failures: int,
+ transition: AnnouncedTransition,
+ ) -> dict[str, Any]: ...
+
+
# Comparison against a source's own stack.
#
# What a comparison reads, and what a source must supply for one.
diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.py
index 6bf9951a8744..a6ddb8af7369 100644
--- a/products/alerts_platform/backend/facade/delivery.py
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -1,7 +1,12 @@
"""Facade for native delivery: how other products plug in destinations and their own wording."""
-from products.alerts_platform.backend.delivery import describers, destinations
-from products.alerts_platform.backend.facade.contracts import DestinationResolver, SourceDescriber, SourceKind
+from products.alerts_platform.backend.delivery import describers, destinations, legacy_webhook
+from products.alerts_platform.backend.facade.contracts import (
+ DestinationResolver,
+ LegacyWebhookBody,
+ SourceDescriber,
+ SourceKind,
+)
def register_destination_resolver(resolver: DestinationResolver) -> None:
@@ -10,3 +15,7 @@ def register_destination_resolver(resolver: DestinationResolver) -> None:
def register_source_describer(source: SourceKind, describer: SourceDescriber) -> None:
describers.register(source, describer)
+
+
+def register_legacy_webhook_body(source: SourceKind, body: LegacyWebhookBody) -> None:
+ legacy_webhook.register(source, body)
diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.py
index ab227a1b6207..c538a1abae65 100644
--- a/products/alerts_platform/backend/logic/platform_alert_events.py
+++ b/products/alerts_platform/backend/logic/platform_alert_events.py
@@ -202,6 +202,7 @@ def announcement(
source_config=_snapshot(source_config_snapshot),
error_message=error_message or None,
occurred_at=occurred_at,
+ evaluation_key=evaluation_key,
)
for grouping_key, kind, episode_started_at, value, labels, condition_snapshot, source_config_snapshot, error_message, occurred_at, _, _ in rows
)
diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
index 38929ef9e4a9..a5ebc9b5f683 100644
--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py
+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py
@@ -7,8 +7,10 @@ from unittest.mock import patch
from parameterized import parameterized
+from products.alerts_platform.backend.delivery import legacy_webhook
from products.alerts_platform.backend.delivery.destinations import list_alert_destination_groups
from products.alerts_platform.backend.delivery.evaluation import LIVE_DELIVERY_FLAG, deliver_evaluation
+from products.alerts_platform.backend.delivery.legacy_webhook import LEGACY_WEBHOOK_BODY_FLAG
from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.thread_store import ThreadBusy
from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
@@ -25,6 +27,8 @@ from products.alerts_platform.backend.facade.contracts import (
)
_MODULE = "products.alerts_platform.backend.delivery.evaluation"
+_LEGACY_MODULE = "products.alerts_platform.backend.delivery.legacy_webhook"
+_WEBHOOK_URL_MODULE = "products.alerts_platform.backend.delivery.webhook_url"
FIRING = datetime(2026, 9, 30, 9, tzinfo=UTC)
FIRING_EVENT = "$logs_alert_firing"
@@ -34,6 +38,9 @@ CLOSED_EVENT = "$logs_alert_incident_closed"
SLACK = cast(AlertDestinationData, {"type": DestinationType.SLACK, "slack_workspace_id": 1, "slack_channel_id": "C-1"})
WEBHOOK = cast(AlertDestinationData, {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/hook"})
+SECOND_WEBHOOK = cast(
+ AlertDestinationData, {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/other"}
+)
TEAMS = cast(AlertDestinationData, {"type": DestinationType.TEAMS, "webhook_url": "https://example.com/teams"})
PAGERDUTY = cast(AlertDestinationData, {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": "R-1"})
UNSUPPORTED = cast(AlertDestinationData, {"type": "opsgenie"})
@@ -293,6 +300,7 @@ class TestDeliverEvaluation(APIBaseTest):
assert flag.call_args.args[0] == LIVE_DELIVERY_FLAG
assert flag.call_args.kwargs["groups"]["project"] == str(self.team.id)
+ assert flag.call_args.kwargs["group_properties"]["project"]["uuid"] == str(self.team.uuid)
def test_a_flag_that_cannot_be_read_leaves_the_legacy_path_as_the_only_deliverer(self) -> None:
with patch(f"{_MODULE}.posthoganalytics.feature_enabled", side_effect=RuntimeError("flags unreachable")):
@@ -301,6 +309,59 @@ class TestDeliverEvaluation(APIBaseTest):
assert RecordingTransport.sends == []
assert outcome.live is False
+ @parameterized.expand(
+ [
+ ("keeps_the_legacy_body", True, "1", "legacy"),
+ ("moved_to_alertmanager", False, "2", "4"),
+ ("flag_unreadable", RuntimeError("flags unreachable"), None, None),
+ # The SDK swallows a failed lookup and answers None.
+ ("flag_lookup_swallowed", None, None, None),
+ ]
+ )
+ def test_a_webhook_gets_the_body_its_team_still_receives(
+ self, _name: str, keeps_legacy: bool | Exception | None, header: str | None, body_version: str | None
+ ) -> None:
+ flag_reads: list[str] = []
+
+ def flag(key: str, *_args: Any, **_kwargs: Any) -> bool | None:
+ flag_reads.append(key)
+ if key == LIVE_DELIVERY_FLAG:
+ return True
+ if isinstance(keeps_legacy, Exception):
+ raise keeps_legacy
+ return keeps_legacy
+
+ def legacy_body(**kwargs: Any) -> dict[str, Any]:
+ return {"version": "legacy", "alert_id": kwargs["alert_id"]}
+
+ with (
+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", side_effect=flag),
+ patch(f"{_MODULE}.announcement", return_value=_announcement(_transition(AlertEventKind.FIRING))),
+ patch(f"{_MODULE}.list_alert_destination_groups", return_value=[_group(WEBHOOK), _group(SECOND_WEBHOOK)]),
+ patch(f"{_MODULE}.DatabaseThreadStore"),
+ patch.dict(f"{_LEGACY_MODULE}._bodies", {SourceKind.LOGS: legacy_body}),
+ patch(f"{_WEBHOOK_URL_MODULE}.post_json") as post,
+ patch(f"{_MODULE}.record_delivery") as recorded,
+ ):
+ if header is None:
+ with pytest.raises(DeliveryError):
+ deliver_evaluation(_request(self.team.id))
+ post.assert_not_called()
+ # Each blocked webhook still counts as a failed delivery.
+ assert [c.kwargs["succeeded"] for c in recorded.call_args_list] == [False, False]
+ # One failed lookup per evaluation, however many webhooks it has.
+ assert flag_reads.count(LEGACY_WEBHOOK_BODY_FLAG) == 1
+ return
+ deliver_evaluation(_request(self.team.id))
+
+ assert post.call_args.kwargs["headers"] == {"X-PostHog-Webhook-Version": header}
+ assert post.call_args.args[1]["version"] == body_version
+
+ def test_logs_registers_its_legacy_webhook_body_at_startup(self) -> None:
+ # Every other case here patches the registry, so none of them notices a missing registration,
+ # which would send grandfathered teams the Alertmanager body without any error.
+ assert legacy_webhook.body_for(SourceKind.LOGS) is not None
+
def test_the_destination_owner_registers_its_lookup_at_startup(self) -> None:
# Every other case here patches the lookup, so none of them notices a missing registration.
assert (
diff --git a/products/logs/backend/alert_comparison.py b/products/logs/backend/alert_comparison.py
index 384ac07cd884..2852fb7a23f4 100644
--- a/products/logs/backend/alert_comparison.py
+++ b/products/logs/backend/alert_comparison.py
@@ -41,7 +41,8 @@ from products.alerts_platform.backend.facade.lifecycle import (
AlertState,
NotificationAction,
)
-from products.logs.backend.alert_source_cycle import is_in_quiet_hours, window_end_of
+from products.logs.backend.alert_evaluation_key import window_end_of
+from products.logs.backend.alert_source_cycle import is_in_quiet_hours
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
logger = structlog.get_logger(__name__)
diff --git a/products/logs/backend/alert_evaluation_key.py b/products/logs/backend/alert_evaluation_key.py
new file mode 100644
index 000000000000..072bd6947fa1
--- /dev/null
+++ b/products/logs/backend/alert_evaluation_key.py
@@ -0,0 +1,25 @@
+"""The window end a logs evaluation key carries.
+
+Kept out of the evaluation module so the message wording, which loads at startup, can read a key
+without importing the query layer.
+"""
+
+from datetime import datetime
+from typing import Final
+
+WINDOW_MARKER: Final = "window:"
+
+
+def window_end_of(evaluation_key: str) -> datetime | None:
+ """The window end the logs adapter put in a key, for a reader that has only the key.
+
+ The adapter mints keys with `WINDOW_MARKER`, so a change to one breaks the round trip test
+ rather than silently returning None to a reader in another module.
+ """
+ _, marker, tail = evaluation_key.rpartition(WINDOW_MARKER)
+ if not marker:
+ return None
+ try:
+ return datetime.fromisoformat(tail)
+ except ValueError:
+ return None
diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.py
index 9d0efebed255..74d52d5fe23d 100644
--- a/products/logs/backend/alert_source_cycle.py
+++ b/products/logs/backend/alert_source_cycle.py
@@ -75,6 +75,7 @@ from products.logs.backend.alert_check_query import (
)
from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.logs.backend.alert_error_classifier import classify as classify_alert_error
+from products.logs.backend.alert_evaluation_key import WINDOW_MARKER
from products.logs.backend.models import LogsAlertConfiguration
# Private to the production activity. Reimplementing either would let this path drift from
@@ -152,9 +153,6 @@ def _broken_condition(check: PlatformAlertCheckInput) -> str | None:
return None
-_WINDOW_MARKER = "window:"
-
-
def _evaluation_key(check: PlatformAlertCheckInput, window_end: datetime) -> str:
"""Names the scheduled check, and the window it answered for.
@@ -167,22 +165,7 @@ def _evaluation_key(check: PlatformAlertCheckInput, window_end: datetime) -> str
shape across sources. Both parts are read before anything is written, so a retry recomputes
the same key.
"""
- return f"slot:{slot_of(check.next_check_at, window_end)}|{_WINDOW_MARKER}{window_end.isoformat()}"
-
-
-def window_end_of(evaluation_key: str) -> datetime | None:
- """The window end `_evaluation_key` put in a key, for a reader that has only the key.
-
- The inverse lives next to the minter so a change to one breaks the round trip rather than
- silently returning None to a reader in another module.
- """
- _, marker, tail = evaluation_key.rpartition(_WINDOW_MARKER)
- if not marker:
- return None
- try:
- return datetime.fromisoformat(tail)
- except ValueError:
- return None
+ return f"slot:{slot_of(check.next_check_at, window_end)}|{WINDOW_MARKER}{window_end.isoformat()}"
@frozen
diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.py
index 2b69fb627155..46c059908fe2 100644
--- a/products/logs/backend/apps.py
+++ b/products/logs/backend/apps.py
@@ -13,10 +13,17 @@ class LogsConfig(AppConfig):
# transitively imports the whole query-runner layer, which would drag posthog.schema and
# HogQL into django.setup() for every process type.
# - The alerts platform cannot import this product, so native alert messages get the logs
- # wording through the describer registered below.
+ # wording, and grandfathered webhooks the legacy logs body, through the functions registered below.
from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415
- from products.alerts_platform.backend.facade.delivery import register_source_describer # noqa: PLC0415
+ from products.alerts_platform.backend.facade.delivery import ( # noqa: PLC0415
+ register_legacy_webhook_body,
+ register_source_describer,
+ )
from products.logs.backend import activity_logging # noqa: F401, PLC0415
- from products.logs.backend.platform_alert_wording import describe_logs_transition # noqa: PLC0415
+ from products.logs.backend.platform_alert_wording import ( # noqa: PLC0415
+ describe_logs_transition,
+ legacy_logs_webhook_body,
+ )
register_source_describer(SourceKind.LOGS, describe_logs_transition)
+ register_legacy_webhook_body(SourceKind.LOGS, legacy_logs_webhook_body)
diff --git a/products/logs/backend/platform_alert_wording.py b/products/logs/backend/platform_alert_wording.py
index aacac6bd0b59..9ad57688a1c2 100644
--- a/products/logs/backend/platform_alert_wording.py
+++ b/products/logs/backend/platform_alert_wording.py
@@ -6,8 +6,10 @@ messages use: a count of logs in a window, the filters the alert watches, and a
Imported from `ready()`, so it stays light: no models, no query layer.
"""
-from datetime import timedelta
-from typing import Any
+from dataclasses import replace
+from datetime import UTC, timedelta
+from typing import Any, Final
+from uuid import NAMESPACE_URL, uuid5
from posthog.utils import absolute_uri
@@ -18,6 +20,7 @@ from products.alerts_platform.backend.facade.contracts import (
MessageLink,
SourceDescription,
)
+from products.logs.backend.alert_evaluation_key import window_end_of
from products.logs.backend.logs_url_params import build_logs_url_params, has_filter_values
# A resolve reports the count that ended the firing, so it is not a breach. A held check, which
@@ -68,8 +71,79 @@ def _context(filters: dict[str, Any]) -> tuple[str, ...]:
def _logs_url(project_id: int, transition: AnnouncedTransition) -> str:
- # The window the check counted, so the link opens on the logs that decided it.
- date_to = transition.occurred_at
- date_from = date_to - timedelta(minutes=transition.condition["window_minutes"])
- params = build_logs_url_params(transition.source_config, date_from=date_from, date_to=date_to)
+ params = _window_params(transition)
return absolute_uri(f"/project/{project_id}/logs" + (f"?{params}" if params else ""))
+
+
+def _in_utc(transition: AnnouncedTransition) -> AnnouncedTransition:
+ # History rows come back from ClickHouse without a zone. A link or a body with zoneless times
+ # reads them in whatever zone the reader is in.
+ if transition.occurred_at.tzinfo is not None:
+ return transition
+ return replace(transition, occurred_at=transition.occurred_at.replace(tzinfo=UTC))
+
+
+def _window_params(transition: AnnouncedTransition) -> str:
+ # The window the check counted, so the link opens on the logs that decided it. The window end
+ # can sit before the record time, because the check clamps it to the ingestion checkpoint.
+ window_end = window_end_of(transition.evaluation_key)
+ date_to = _in_utc(replace(transition, occurred_at=window_end) if window_end else transition).occurred_at
+ date_from = date_to - timedelta(minutes=transition.condition["window_minutes"])
+ return build_logs_url_params(transition.source_config, date_from=date_from, date_to=date_to)
+
+
+_LEGACY_WEBHOOK_TYPES: Final = {
+ AlertEventKind.FIRING: "logs_alert.firing",
+ AlertEventKind.RESOLVED: "logs_alert.resolved",
+ AlertEventKind.ERRORED: "logs_alert.errored",
+ AlertEventKind.BROKEN: "logs_alert.auto_disabled",
+}
+
+
+def legacy_logs_webhook_body(
+ *,
+ project_id: int,
+ alert_id: str,
+ alert_name: str,
+ consecutive_failures: int,
+ transition: AnnouncedTransition,
+) -> dict[str, Any]:
+ """The body the logs alert webhook HogFunction sent, field for field.
+
+ Its template rendered a lone placeholder as the value's own type, so counts stay numbers and
+ filter lists stay lists here too.
+ """
+ transition = _in_utc(transition)
+ occurred_at = transition.occurred_at
+ filters = transition.source_config
+ alert_url = absolute_uri(f"/project/{project_id}/logs/alerts/{alert_id}")
+ data: dict[str, Any] = {
+ "alert_id": alert_id,
+ "alert_name": alert_name,
+ "service_names": filters.get("serviceNames", []),
+ "severity_levels": filters.get("severityLevels", []),
+ }
+ if transition.kind in (AlertEventKind.FIRING, AlertEventKind.RESOLVED):
+ condition = transition.condition
+ data |= {
+ "result_count": int(transition.value) if transition.value is not None else None,
+ "threshold_count": condition["threshold_count"],
+ "threshold_operator": condition["threshold_operator"],
+ "window_minutes": condition["window_minutes"],
+ # The legacy template always added the "?", even with no parameters.
+ "logs_url": absolute_uri(f"/project/{project_id}/logs?{_window_params(transition)}"),
+ }
+ else:
+ error_key = "last_error_message" if transition.kind == AlertEventKind.BROKEN else "error_message"
+ data |= {"consecutive_failures": consecutive_failures, error_key: transition.error_message or ""}
+ data["alert_url"] = alert_url
+ return {
+ # The HogFunction path sent its event's id. A stable id per transition lets a receiver
+ # drop a retried send.
+ "id": str(
+ uuid5(NAMESPACE_URL, f"{alert_id}|{transition.grouping_key}|{transition.kind}|{occurred_at.isoformat()}")
+ ),
+ "type": _LEGACY_WEBHOOK_TYPES[transition.kind],
+ "timestamp": occurred_at.isoformat(),
+ "data": data,
+ }
diff --git a/products/logs/backend/test/test_alert_comparison.py b/products/logs/backend/test/test_alert_comparison.py
index 4baec737b823..503ee1db77b0 100644
--- a/products/logs/backend/test/test_alert_comparison.py
+++ b/products/logs/backend/test/test_alert_comparison.py
@@ -18,7 +18,8 @@ from products.alerts_platform.backend.facade.contracts import (
)
from products.alerts_platform.backend.facade.testing import undeclared_policy_divergences
from products.logs.backend.alert_comparison import LOGS_INTENTIONAL_DIVERGENCES, LogsCorrespondence
-from products.logs.backend.alert_source_cycle import LogsAlertCondition, _evaluation_key, window_end_of
+from products.logs.backend.alert_evaluation_key import window_end_of
+from products.logs.backend.alert_source_cycle import LogsAlertCondition, _evaluation_key
from products.logs.backend.models import LogsAlertConfiguration, LogsAlertEvent
CHECKED_AT = datetime(2026, 9, 30, 12, 0, tzinfo=UTC)
diff --git a/products/logs/backend/test/test_platform_alert_wording.py b/products/logs/backend/test/test_platform_alert_wording.py
index c1031e53e1ee..4797eb0742f2 100644
--- a/products/logs/backend/test/test_platform_alert_wording.py
+++ b/products/logs/backend/test/test_platform_alert_wording.py
@@ -1,14 +1,20 @@
import json
-from datetime import UTC, datetime
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
from typing import Any
from urllib.parse import parse_qs, urlsplit
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition, MessageDetail
-from products.logs.backend.platform_alert_wording import describe_logs_transition
+from products.cdp.backend.validation import generate_template_bytecode
+from products.logs.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
+from products.logs.backend.logs_url_params import build_logs_url_params
+from products.logs.backend.platform_alert_wording import describe_logs_transition, legacy_logs_webhook_body
+
+from common.hogvm.python.execute import execute_bytecode
CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 10}
OCCURRED = datetime(2026, 10, 8, 18, 5, tzinfo=UTC)
@@ -93,3 +99,97 @@ class TestLogsPlatformAlertWording(SimpleTestCase):
"date_from": "2026-10-08T17:55:00+00:00",
"date_to": "2026-10-08T18:05:00+00:00",
}
+
+ @parameterized.expand(
+ [
+ ("firing", AlertEventKind.FIRING, "firing"),
+ ("resolved", AlertEventKind.RESOLVED, "resolved"),
+ ("errored", AlertEventKind.ERRORED, "errored"),
+ ("auto_disabled", AlertEventKind.BROKEN, "broken"),
+ ]
+ )
+ @override_settings(SITE_URL="https://us.posthog.com")
+ def test_the_legacy_webhook_body_matches_what_the_hog_function_sent(
+ self, _name: str, kind: AlertEventKind, legacy_kind: EventKind
+ ) -> None:
+ filters = {"serviceNames": ["api"], "severityLevels": ["error"]}
+ breach = kind in (AlertEventKind.FIRING, AlertEventKind.RESOLVED)
+ transition = replace(
+ _transition(kind, 11.0 if breach else None, filters), error_message=None if breach else "query timed out"
+ )
+
+ native = legacy_logs_webhook_body(
+ project_id=7, alert_id="alert-1", alert_name="API errors", consecutive_failures=2, transition=transition
+ )
+
+ # The properties the logs stack put on its event, rendered through the stock template.
+ properties = {
+ "alert_id": "alert-1",
+ "alert_name": "API errors",
+ "result_count": 11,
+ "threshold_count": 10,
+ "threshold_operator": "above",
+ "window_minutes": 10,
+ "service_names": ["api"],
+ "severity_levels": ["error"],
+ "logs_url_params": build_logs_url_params(
+ transition.source_config, date_from=OCCURRED - timedelta(minutes=10), date_to=OCCURRED
+ ),
+ "triggered_at": OCCURRED.isoformat(),
+ "consecutive_failures": 2,
+ "error_message": "query timed out",
+ "last_error_message": "query timed out",
+ }
+ globals_ = {
+ "event": {"uuid": native["id"], "properties": properties},
+ "project": {"url": "https://us.posthog.com/project/7"},
+ }
+ legacy = _render(generate_template_bytecode(EVENT_KIND_CONFIG[legacy_kind].webhook_body, set()), globals_)
+
+ assert native == legacy
+
+ def test_a_naive_history_timestamp_is_sent_as_utc(self) -> None:
+ naive = replace(_transition(), occurred_at=OCCURRED.replace(tzinfo=None))
+
+ body = legacy_logs_webhook_body(
+ project_id=7, alert_id="alert-1", alert_name="API errors", consecutive_failures=0, transition=naive
+ )
+ aware = legacy_logs_webhook_body(
+ project_id=7, alert_id="alert-1", alert_name="API errors", consecutive_failures=0, transition=_transition()
+ )
+
+ assert body["timestamp"] == OCCURRED.isoformat()
+ # The link's window carries the zone too, or a browser outside UTC shifts it.
+ assert body["data"]["logs_url"] == aware["data"]["logs_url"]
+
+ @parameterized.expand([("legacy_webhook_body",), ("message_link",)])
+ def test_a_logs_link_opens_the_window_the_check_queried(self, link: str) -> None:
+ # The ingestion checkpoint clamped this check's window end to well before it was recorded.
+ window_end = OCCURRED - timedelta(minutes=7)
+ transition = replace(
+ _transition(filters={"serviceNames": ["api"]}),
+ evaluation_key=f"slot:{OCCURRED.isoformat()}|window:{window_end.isoformat()}",
+ )
+
+ if link == "legacy_webhook_body":
+ url = legacy_logs_webhook_body(
+ project_id=7, alert_id="alert-1", alert_name="API errors", consecutive_failures=0, transition=transition
+ )["data"]["logs_url"]
+ else:
+ data_link = describe_logs_transition(project_id=7, transition=transition).data_link
+ assert data_link is not None
+ url = data_link.url
+
+ query = parse_qs(urlsplit(url).query)
+ date_range = json.loads(query["dateRange"][0])
+ assert date_range["date_to"] == window_end.isoformat()
+
+
+def _render(node: Any, globals_: dict[str, Any]) -> Any:
+ if isinstance(node, list) and node and node[0] in ("_H", "_h"):
+ return execute_bytecode(node, globals=globals_).result
+ if isinstance(node, dict):
+ return {key: _render(value, globals_) for key, value in node.items()}
+ if isinstance(node, list):
+ return [_render(item, globals_) for item in node]
+ return node