:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): match native logs alert messages to the legacy ones (#116664)
Jimmy Zhuae9c7fc6467f
diff --git a/posthog/slack/channels.py b/posthog/slack/channels.pyindex 1563eb6a6d65..9577f037d283 100644--- a/posthog/slack/channels.py+++ b/posthog/slack/channels.py@@ -160,6 +160,7 @@ def post_message(blocks: list[dict[str, Any]],text: str,thread_ts: str | None = None,+ reply_broadcast: bool = False,) -> SlackResponse:# No unfurls: the text is written over untrusted content, so a prompt-injected URL must not make# Slack's unfurler fetch an attacker's server from inside the workspace.@@ -168,6 +169,7 @@ def post_message(blocks=blocks,text=text,thread_ts=thread_ts,+ reply_broadcast=reply_broadcast,unfurl_links=False,unfurl_media=False,)diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.pyindex ec6d9c4ab933..bfa07e0aa8c5 100644--- a/products/alerts_platform/backend/delivery/dispatch.py+++ b/products/alerts_platform/backend/delivery/dispatch.py@@ -36,6 +36,7 @@ def deliver(target: AlertDestinationData,announcement: EvaluationAnnouncement,incident_action: IncidentAction | None = None,+ source_alert_url: str | None = None,) -> None:channel_target = transport.channel_target(target)busy = 0@@ -53,7 +54,13 @@ def deliver(team_id=team_id,configuration_id=configuration_id,target=target,- message=build_message(announcement, transition, team_id=team_id, incident_action=incident_action),+ message=build_message(+ announcement,+ transition,+ team_id=team_id,+ incident_action=incident_action,+ source_alert_url=source_alert_url,+ ),in_reply_to=None,)continue@@ -75,7 +82,13 @@ def deliver(team_id=team_id,configuration_id=configuration_id,target=target,- message=build_message(announcement, transition, team_id=team_id, incident_action=incident_action),+ message=build_message(+ announcement,+ transition,+ team_id=team_id,+ incident_action=incident_action,+ source_alert_url=source_alert_url,+ ),in_reply_to=claim.handle,)except Exception:diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex cee05297e34b..b5137c060986 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -216,6 +216,7 @@ def deliver_evaluation(request: AlertDeliveryRequest) -> DeliveryOutcome:target=target,announcement=replace(announced, transitions=transitions),incident_action=action_by_event_id.get(event_id),+ source_alert_url=request.source_alert_url,)except ThreadBusy as error:busy.append(str(error))diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.pyindex d50e1c267b7a..1ae5ce349079 100644--- a/products/alerts_platform/backend/delivery/message.py+++ b/products/alerts_platform/backend/delivery/message.py@@ -152,6 +152,7 @@ def build_message(*,team_id: int,incident_action: IncidentAction | None = None,+ source_alert_url: str | None = None,) -> AlertMessage:"""The message for one transition.@@ -183,7 +184,7 @@ def build_message(configuration_id=announcement.configuration_id,alert_name=announcement.alert_name,source=announcement.source,- alert_url=alert_url(project_id, announcement.configuration_id),+ alert_url=source_alert_url or alert_url(project_id, announcement.configuration_id),transition=transition,context=description.context,data_link=description.data_link,diff --git a/products/alerts_platform/backend/delivery/slack.py b/products/alerts_platform/backend/delivery/slack.pyindex 556c770a5b2c..b66107e7e514 100644--- a/products/alerts_platform/backend/delivery/slack.py+++ b/products/alerts_platform/backend/delivery/slack.py@@ -25,7 +25,7 @@ from posthog.slack.formatting import escape_slack_mrkdwnfrom products.alerts_platform.backend.delivery.message import AlertMessagefrom products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle-from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind, MessageDetailPROVIDER: Final = "slack"@@ -99,7 +99,13 @@ class SlackTransport:text = escape_slack_mrkdwn(message.title)try:response = post_message(- slack, channel, blocks, text, thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None+ slack,+ channel,+ blocks,+ text,+ thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None,+ # A root edit notifies nobody, so a resolve also goes to the channel, as legacy posted it.+ reply_broadcast=in_reply_to is not None and message.transition.kind == AlertEventKind.RESOLVED,)except SlackApiError as error:# A refusal a person can fix, such as a channel the bot has left, rather than adiff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 8fbf245dfdcb..05cf614641fd 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -365,6 +365,8 @@ class AlertDeliveryRequest:incident_actions: dict[str, IncidentAction] = field(default_factory=dict)sends_messages: bool = Trueevent_ids_by_incident_action: dict[str, str] = field(default_factory=dict)+ # The alert's page in the source's own product. Without one a message links to the platform's page.+ source_alert_url: str | None = Noneowned_by_platform: bool = Falsediff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.pyindex 134fff218009..09b7b7631752 100644--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py@@ -1,3 +1,4 @@+from dataclasses import replacefrom datetime import UTC, datetimefrom typing import Any, cast@@ -289,6 +290,20 @@ class TestDeliverEvaluation(APIBaseTest):assert RecordingTransport.sends == []assert outcome.sent == 0+ def test_every_message_links_to_the_alert_page_the_request_names(self) -> None:+ url = "https://app.example.com/project/7/logs/alerts/legacy-1"++ with (+ patch(f"{_MODULE}.posthoganalytics.feature_enabled", return_value=True),+ patch(f"{_MODULE}.announcement", return_value=_announcement(_transition(AlertEventKind.FIRING))),+ patch(f"{_MODULE}.list_alert_destination_groups", return_value=[_group(SLACK)]),+ patch(f"{_MODULE}.DatabaseThreadStore"),+ patch.dict(f"{_MODULE}._TRANSPORTS", {DestinationType.SLACK: RecordingTransport}),+ ):+ deliver_evaluation(replace(_request(self.team.id), source_alert_url=url))++ assert [m.alert_url for _, m in RecordingTransport.sends] == [url]+def test_an_evaluation_that_announced_nothing_sends_nothing(self) -> None:outcome = self._run(None, {FIRING_EVENT: [_group(SLACK)]})diff --git a/products/alerts_platform/backend/tests/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.pyindex 5ee143425c28..2605f2065177 100644--- a/products/alerts_platform/backend/tests/test_delivery_message.py+++ b/products/alerts_platform/backend/tests/test_delivery_message.py@@ -63,8 +63,11 @@ def _build(transition: AnnouncedTransition,*,incident_action: IncidentAction | None = None,+ source_alert_url: str | None = None,) -> AlertMessage:- return build_message(announcement, transition, team_id=7, incident_action=incident_action)+ return build_message(+ announcement, transition, team_id=7, incident_action=incident_action, source_alert_url=source_alert_url+ )class TestAlertMessage:@@ -90,6 +93,13 @@ class TestAlertMessage:assert message.headline == expected_headlineassert message.alert_url.endswith("/project/7/platform-alerts/cfg-1")+ def test_a_message_links_to_the_alert_page_its_source_names(self) -> None:+ url = "https://app.example.com/project/7/logs/alerts/legacy-1"++ message = _build(_announcement(), _transition(AlertEventKind.FIRING), source_alert_url=url)++ assert message.alert_url == url+@pytest.mark.parametrize("source", list(SourceKind))def test_every_source_kind_has_a_headline(self, source: SourceKind) -> None:message = _build(_announcement(source=source), _transition(AlertEventKind.FIRING))diff --git a/products/alerts_platform/backend/tests/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.pyindex 27e63c53258f..076f28c0a3ee 100644--- a/products/alerts_platform/backend/tests/test_delivery_slack.py+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py@@ -6,6 +6,7 @@ from unittest.mock import patchfrom django.test import SimpleTestCase+from parameterized import parameterizedfrom slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integration@@ -13,8 +14,13 @@ from posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARSfrom products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_forfrom products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle-from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail, MessageLink-from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,+ AlertEventKind,+ MessageDetail,+ MessageLink,+)+from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message, announced_transitionMESSAGE = alert_message(headline="API errors is firing",@@ -105,7 +111,7 @@ class TestSlackTransport(APIBaseTest):handle = SlackTransport().deliver(team_id=overrides.pop("team_id", self.team.id),target=overrides.pop("target", self.target),- message=MESSAGE,+ message=overrides.pop("message", MESSAGE),**overrides,)return handle, slack_integration.return_value.client.chat_postMessage@@ -117,10 +123,19 @@ class TestSlackTransport(APIBaseTest):assert handle.root_content == {"blocks": blocks_for(MESSAGE), "text": post.call_args.kwargs["text"]}assert post.call_args.kwargs["thread_ts"] is None- def test_a_reply_goes_into_the_thread_it_names_and_keeps_no_content(self) -> None:- handle, post = self._send(in_reply_to=MessageHandle(external_ref={"channel": "C-ENG", "ts": "1699999999.9"}))+ @parameterized.expand(+ [("a_resolve", AlertEventKind.RESOLVED, True), ("a_repeat_firing", AlertEventKind.FIRING, False)]+ )+ def test_a_reply_goes_into_the_thread_it_names_and_keeps_no_content(+ self, _name: str, kind: AlertEventKind, broadcast: bool+ ) -> None:+ handle, post = self._send(+ in_reply_to=MessageHandle(external_ref={"channel": "C-ENG", "ts": "1699999999.9"}),+ message=alert_message(transition=announced_transition(kind=kind)),+ )assert post.call_args.kwargs["thread_ts"] == "1699999999.9"+ assert post.call_args.kwargs["reply_broadcast"] is broadcastassert handle.root_content is Nonedef test_an_edit_keeps_the_opening_content_and_adds_the_state_above_the_buttons(self) -> None:diff --git a/products/logs/backend/alert_source_cycle.py b/products/logs/backend/alert_source_cycle.pyindex 17907df49d16..52a961ac3b3a 100644--- a/products/logs/backend/alert_source_cycle.py+++ b/products/logs/backend/alert_source_cycle.py@@ -26,6 +26,7 @@ import structlogfrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.dataclasses import frozenfrom posthog.models import Team+from posthog.utils import absolute_urifrom products.alerts.backend.facade.destinations import configured_destination_template_idsfrom products.alerts_platform.backend.facade.api import due_checks, slot_of@@ -396,6 +397,10 @@ def _request(# Logs does not group, so its one row has the empty grouping key.incident_actions={"": incident_action} if incident_action is not None else {},sends_messages=sends_messages,+ # The logs alert page, as the HogFunction messages linked. An alert with no logs row has none.+ source_alert_url=absolute_uri(f"/project/{check.team_id}/logs/alerts/{check.legacy_configuration_id}")+ if check.legacy_configuration_id is not None+ else None,owned_by_platform=check.owned_by_platform,)diff --git a/products/logs/backend/test/test_alert_evaluate.py b/products/logs/backend/test/test_alert_evaluate.pyindex 7ef706a0be14..e44d435a64b4 100644--- a/products/logs/backend/test/test_alert_evaluate.py+++ b/products/logs/backend/test/test_alert_evaluate.py@@ -115,15 +115,16 @@ class TestLogsAlertEvaluation(APIBaseTest):@parameterized.expand([- ("without_a_paging_destination", False, "source"),- ("with_a_paging_destination", True, "source"),- ("owned_by_the_platform", False, "platform"),+ ("without_a_paging_destination", False, "source", None),+ ("with_a_paging_destination", True, "source", None),+ ("owned_by_the_platform", False, "platform", None),+ ("copied_from_a_logs_alert", False, "source", UUID("01936a2e-0000-7000-8000-00000000abcd")),])def test_a_breaching_configuration_fires_and_records_its_own_state(- self, _name: str, paged: bool, owner: str+ self, _name: str, paged: bool, owner: str, legacy_id: UUID | None) -> None:- configuration = self._configuration(owner=owner)+ configuration = self._configuration(owner=owner, legacy_configuration_id=legacy_id)if paged:self._add_incident_destination(configuration)@@ -136,6 +137,11 @@ class TestLogsAlertEvaluation(APIBaseTest):]# The event a PagerDuty destination subscribes to, so the trigger reaches it.assert evaluation.deliveries[0].event_ids_by_incident_action["trigger"] == "$logs_alert_incident_opened"+ # Only an alert copied from a logs alert has a logs alert page to link to.+ source_alert_url = evaluation.deliveries[0].source_alert_url+ assert (source_alert_url.endswith(f"/logs/alerts/{legacy_id}") if source_alert_url else None) == (+ True if legacy_id else None+ )with team_scope(self.team.id):alert = platform_testing.alert_for(configuration.id)assert alert is not None