: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
refactor(alerts): reuse slack formatting for native delivery (#123536)
Matt Pua9de7758ef233
diff --git a/docs/internal/alerts-platform-temporal.md b/docs/internal/alerts-platform-temporal.mdindex 4319a9367ef9..3d205f7ee325 100644--- a/docs/internal/alerts-platform-temporal.md+++ b/docs/internal/alerts-platform-temporal.md@@ -47,6 +47,16 @@ Reverting the code that registers a schedule does not remove one already registeVerify the Postgres activity result and the delivery child's completion separately.Parent completion does not prove either succeeded. Schedule creation also does not prove worker availability.+### Slack message formatting++- Sources can register a Slack renderer with `register_source_slack_renderer` through the delivery facade.+- Insight alert firings use the same attachment and control builders as their HogFunction templates.+- Sources without a custom renderer, and insight transitions other than firings, use the platform's default layout.+- The Slack transport preserves attachments for later message updates. If Slack rejects a chart image, it retries without the image and retains the remaining content.+- A renderer always sets `text`. A push notification and a screen reader read it, and an attachment does not carry it.+- A renderer that raises is counted on `alerts_platform_slack_renderer_failures_total` and the message goes out in the platform's layout.+- A card that lives in an attachment also stores one stand-in block. A reader from before attachments edits `blocks` and indexes its last element, so an empty list would fail that edit during a rolling deploy.+### Turning a production deployment onA production tick is a shadow run. Delivery stops at `alerts-platform-deliver-preview`, which records whatdiff --git a/posthog/slack/channels.py b/posthog/slack/channels.pyindex 3f41ebeea548..cf3278af1a97 100644--- a/posthog/slack/channels.py+++ b/posthog/slack/channels.py@@ -165,6 +165,7 @@ def post_message(text: str,thread_ts: str | None = None,reply_broadcast: bool = False,+ attachments: list[dict[str, Any]] | None = None,) -> 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.@@ -176,6 +177,7 @@ def post_message(reply_broadcast=reply_broadcast,unfurl_links=False,unfurl_media=False,+ attachments=attachments,)@@ -185,9 +187,16 @@ def update_message(ts: str,blocks: list[dict[str, Any]],text: str,+ attachments: list[dict[str, Any]] | None = None,) -> SlackResponse:"""Replace a message the app posted. Slack keeps its place in the channel and marks it edited."""- return slack.client.chat_update(channel=channel_id, ts=ts, blocks=blocks, text=text)+ return slack.client.chat_update(+ channel=channel_id,+ ts=ts,+ blocks=blocks,+ text=text,+ attachments=attachments,+ )def join_channel(slack: SlackIntegration, channel_id: str) -> str | None:diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.pyindex 805468a0d1d4..f777a664326e 100644--- a/products/alerts/backend/apps.py+++ b/products/alerts/backend/apps.py@@ -25,6 +25,7 @@ class AlertsConfig(AppConfig):from products.alerts.backend.platform_hooks import ( # noqa: PLC0415emit_insight_legacy_events,insight_chart_image,+ render_insight_slack_message,)from products.alerts.backend.platform_source_config import load_insight_source_config # noqa: PLC0415from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415@@ -34,6 +35,7 @@ class AlertsConfig(AppConfig):register_image_resolver,register_legacy_event_emitter,register_source_describer,+ register_source_slack_renderer,)from products.alerts_platform.backend.facade.source_configs import register_source_config # noqa: PLC0415@@ -42,4 +44,5 @@ class AlertsConfig(AppConfig):register_legacy_event_emitter(SourceKind.INSIGHT, emit_insight_legacy_events)register_source_describer(SourceKind.INSIGHT, describe_insight_transition)register_image_resolver(SourceKind.INSIGHT, insight_chart_image)+ register_source_slack_renderer(SourceKind.INSIGHT, render_insight_slack_message)register_source_config(SourceKind.INSIGHT, load_insight_source_config)diff --git a/products/alerts/backend/destination_backfill.py b/products/alerts/backend/destination_backfill.pyindex 6c1a42fb0e8f..373234cecded 100644--- a/products/alerts/backend/destination_backfill.py+++ b/products/alerts/backend/destination_backfill.py@@ -27,8 +27,8 @@ from products.alerts.backend.logic.destination_eligibility import STOCK_INPUT_VAfrom products.alerts.backend.logic.insight_alert_destinations import (INSIGHT_CHART_BLOCK,SLACK_TEMPLATE_ID,- _slack_attachments,- _slack_blocks,+ hog_slack_attachments,+ hog_slack_blocks,)from products.cdp.backend.facade.models import HogFunction, HogFunctionTemplatefrom products.cdp.backend.validation import compile_hog, generate_template_bytecode@@ -79,9 +79,9 @@ def blocks_with_chart(blocks: Any) -> list[Any] | None:def blocks_with_readable_message(blocks: Any) -> list[Any] | None:- if blocks != _slack_blocks() and blocks not in STOCK_INPUT_VALUES[SLACK_TEMPLATE_ID]["blocks"]:+ if blocks != hog_slack_blocks() and blocks not in STOCK_INPUT_VALUES[SLACK_TEMPLATE_ID]["blocks"]:return None- return _slack_blocks()+ return hog_slack_blocks()def backfill_insight_alert_chart_blocks(@@ -118,7 +118,7 @@ def backfill_insight_alert_chart_blocks(format_messagesand template is not Noneand blocks == []- and ((destination.inputs or {}).get("attachments") or {}).get("value") == _slack_attachments()+ and ((destination.inputs or {}).get("attachments") or {}).get("value") == hog_slack_attachments()and destination.hog == template.code) or (not format_messages and mentions_chart(destination.inputs)):already_current += 1@@ -154,7 +154,7 @@ def backfill_insight_alert_chart_blocks(# The worker renders the stored bytecode, not the value, so a value written without a# matching recompile would keep posting the old blocks.bytecode = generate_template_bytecode(upgraded, set(), function_type=destination.type)- attachments = _slack_attachments() if format_messages else []+ attachments = hog_slack_attachments() if format_messages else []attachment_bytecode = generate_template_bytecode(attachments, set(), function_type=destination.type)sender_bytecode = compile_hog(template.code, "internal_destination") if template is not None else Noneexcept Exception:diff --git a/products/alerts/backend/logic/insight_alert_destinations.py b/products/alerts/backend/logic/insight_alert_destinations.pyindex 4519d33b26f0..4b4d1a998924 100644--- a/products/alerts/backend/logic/insight_alert_destinations.py+++ b/products/alerts/backend/logic/insight_alert_destinations.py@@ -66,12 +66,34 @@ def snooze_select(alert_id: str) -> dict[str, Any]:def _slack_blocks(*,- chart: Any = INSIGHT_CHART_BLOCK,- alert_id: str = "{event.properties.alert_id}",- primary_url: str = _PRIMARY_BUTTON_URL,- primary_label: str = "{event.properties.investigation_notebook_url ? '🔎 View investigation' : '🔎 View alert'}",- insight_url: str = "{project.url}/insights/{event.properties.insight_id}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack",+ chart: Any,+ alert_id: str,+ primary_url: str,+ primary_label: str,+ insight_url: str | None,) -> list[Any]:+ """The chart and the action row. Every argument is required, because a caller that renders a+ real message cannot inherit a Hog template expression as a default — see `hog_slack_blocks`."""+ elements: list[Any] = [+ {+ "url": primary_url,+ "text": {+ "text": primary_label,+ "type": "plain_text",+ },+ "type": "button",+ },+ ]+ # Without a short id the button would point at `/insights/None`, so the message drops it.+ if insight_url is not None:+ elements.append(+ {+ "url": insight_url,+ "text": {"text": "📊 View insight", "type": "plain_text"},+ "type": "button",+ }+ )+ elements.append(snooze_select(alert_id))return [chart,{@@ -79,39 +101,54 @@ def _slack_blocks(# A datetimepicker element carries no value, unlike a select option, so the alert id# in the block_id is the only way the snooze action can identify its alert."block_id": f"insight_alert_snooze:{alert_id}",- "elements": [- {- "url": primary_url,- "text": {- "text": primary_label,- "type": "plain_text",- },- "type": "button",- },- {- "url": insight_url,- "text": {"text": "📊 View insight", "type": "plain_text"},- "type": "button",- },- snooze_select(alert_id),- ],+ "elements": elements,},]+def hog_slack_blocks() -> list[Any]:+ """The blocks a HogFunction destination stores, where each field is a Hog template expression+ the destination resolves per event."""+ return _slack_blocks(+ chart=INSIGHT_CHART_BLOCK,+ alert_id="{event.properties.alert_id}",+ primary_url=_PRIMARY_BUTTON_URL,+ primary_label="{event.properties.investigation_notebook_url ? '🔎 View investigation' : '🔎 View alert'}",+ insight_url="{project.url}/insights/{event.properties.insight_id}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack",+ )++def _slack_attachments(*,- heading_prefix: str = "{concat('⚠️ ', event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘')}",- alert_name: str = "{event.properties.alert_name}",- alert_url: str = "{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}",- project_name: str = "{project.name}",- project_url: str = "{project.url}",- details: Any = "{event.properties.slack_alert_details ?? {'type': 'section', 'text': {'type': 'plain_text', 'text': substring(event.properties.breaches, 1, 3000)}}}",- timing: Any = "{event.properties.slack_alert_timing ?? {'type': 'context', 'elements': [{'type': 'plain_text', 'text': event.timestamp}]}}",- tags: Any = "{event.properties.slack_alert_tags ?? {'type': 'divider'}}",- fallback: str = "{concat(event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘', event.properties.alert_name, '’ triggered')}",- blocks: list[Any] | None = None,+ heading_prefix: str,+ alert_name: str,+ alert_url: str,+ project_name: str | None,+ project_url: str,+ details: Any,+ timing: Any,+ tags: Any,+ fallback: str,+ blocks: list[Any],) -> list[Any]:+ """The alert card. Every argument is required, for the reason given on `_slack_blocks`."""+ project_blocks: list[Any] = []+ # A link whose text is empty renders as a bare stub, so a nameless project drops the line.+ if project_name:+ project_blocks.append(+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {"type": "text", "text": "📁 Project: "},+ {"type": "link", "url": project_url, "text": project_name},+ ],+ }+ ],+ }+ )return [{"color": "#D97706",@@ -139,27 +176,33 @@ def _slack_attachments(}],},- {- "type": "rich_text",- "elements": [- {- "type": "rich_text_section",- "elements": [- {"type": "text", "text": "📁 Project: "},- {"type": "link", "url": project_url, "text": project_name},- ],- }- ],- },+ *project_blocks,details,timing,tags,],},- {"blocks": _slack_blocks() if blocks is None else blocks},+ {"blocks": blocks},]+def hog_slack_attachments() -> list[Any]:+ """The attachments a HogFunction destination stores, where each field is a Hog template+ expression the destination resolves per event."""+ return _slack_attachments(+ heading_prefix="{concat('⚠️ ', event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘')}",+ alert_name="{event.properties.alert_name}",+ alert_url="{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}",+ project_name="{project.name}",+ project_url="{project.url}",+ details="{event.properties.slack_alert_details ?? {'type': 'section', 'text': {'type': 'plain_text', 'text': substring(event.properties.breaches, 1, 3000)}}}",+ timing="{event.properties.slack_alert_timing ?? {'type': 'context', 'elements': [{'type': 'plain_text', 'text': event.timestamp}]}}",+ tags="{event.properties.slack_alert_tags ?? {'type': 'divider'}}",+ fallback="{concat(event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘', event.properties.alert_name, '’ triggered')}",+ blocks=hog_slack_blocks(),+ )++def build_insight_alert_slack_config(*, alert_id: str, alert_name: str | None, data: AlertDestinationData) -> AlertDestinationConfig:@@ -173,7 +216,7 @@ def build_insight_alert_slack_config("template_id": SLACK_TEMPLATE_ID,"inputs": {"blocks": {"value": []},- "attachments": {"value": _slack_attachments()},+ "attachments": {"value": hog_slack_attachments()},"text": {"value": ""},"slack_workspace": {"value": data["slack_workspace_id"]},"channel": {"value": data["slack_channel_id"]},diff --git a/products/alerts/backend/platform_alert_legacy_events.py b/products/alerts/backend/platform_alert_legacy_events.pyindex bf070a502f80..f4ea948604b4 100644--- a/products/alerts/backend/platform_alert_legacy_events.py+++ b/products/alerts/backend/platform_alert_legacy_events.py@@ -14,12 +14,15 @@ from collections.abc import Sequencefrom typing import Any, Finalfrom uuid import NAMESPACE_URL, uuid5+import structlog+from posthog.schema_enums import AlertStatefrom posthog.tasks.alerts.utils import RenderedInsightChart, detector_verdict_event_fields, insight_chart_urlfrom products.alerts.backend.facade.contracts import AlertInternalEventfrom products.alerts.backend.logic.destinations import emit_alert_internal_eventsfrom products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.platform_alert_slack import insight_transition_propertiesfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertEventKind,@@ -30,6 +33,8 @@ from products.alerts_platform.backend.facade.contracts import ()from products.cdp.backend.internal_events import LEGACY_INSIGHT_ALERT_EVENT+logger = structlog.get_logger(__name__)+# Below the delivery activity's own timeout, which a flush must not use up.FLUSH_TIMEOUT_SECONDS: Final = 5.0@@ -79,12 +84,30 @@ def insight_chart_image(*, team_id: int, transition: AnnouncedTransition) -> Mesreturn MessageImage(url=url, alt_text="Insight chart") if url else None+def _formatting_properties(transition: AnnouncedTransition) -> dict[str, Any]:+ """The Slack card fields, or none of them.++ These enrich the event; the destinations it reaches do not depend on them. A stored detail the+ formatter cannot read must cost the firing its card, never its delivery.+ """+ try:+ return insight_transition_properties(transition)+ except Exception:+ logger.exception("alerts_insight_legacy_event_formatting_failed")+ return {}++def _firing_event(alert: AlertConfiguration, transition: AnnouncedTransition) -> AlertInternalEvent:detail = transition.source_detailproperties: dict[str, Any] = {+ # From the transition, not the alert row: the platform never writes `state` or+ # `last_checked_at`, so a platform-owned alert past its shadow window would report the+ # frozen `not_firing` default on the very event that announces a firing.**alert.internal_event_properties(state=AlertState.FIRING.value, last_checked_at=transition.occurred_at),+ # Joined with newlines so each breach renders on its own line, as the insight stack sends it."breaches": "\n".join(detail.get("breaches") or []),**detector_verdict_event_fields(detail.get("triggered_metadata")),+ **_formatting_properties(transition),}if chart_url := insight_chart_url_of(alert.team_id, detail):properties["insight_chart_url"] = chart_urldiff --git a/products/alerts/backend/platform_alert_slack.py b/products/alerts/backend/platform_alert_slack.pynew file mode 100644index 000000000000..5de654765896--- /dev/null+++ b/products/alerts/backend/platform_alert_slack.py@@ -0,0 +1,115 @@+from __future__ import annotations++from typing import Any, Final+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from posthog.slack.channels import clip_text+from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.utils import absolute_uri++from products.alerts.backend.logic.insight_alert_destinations import _slack_attachments, _slack_blocks+from products.alerts.backend.logic.insight_alert_message import insight_alert_slack_properties+from products.alerts_platform.backend.facade.contracts import (+ AlertEventKind,+ AnnouncedTransition,+ MessageImage,+ MessageLink,+ SlackMessageContent,+)++# A name reaches the card unescaped, so it is bounded here rather than costing the whole message.+MAX_NAME_CHARS: Final = 150+++def _zone(name: str) -> ZoneInfo:+ """The recorded timezone, or UTC.++ `source_detail` crosses Temporal as untyped JSON, and a zone a check recorded can be renamed or+ dropped from the system database before the message goes out.+ """+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError, TypeError):+ return ZoneInfo("UTC")+++def insight_transition_properties(transition: AnnouncedTransition) -> dict[str, Any]:+ detail = transition.source_detail+ breaches = detail.get("breaches") or []+ # Rows come from a stored detail, so their shape is checked rather than assumed. The formatter+ # reads `observed` directly, so a row without it would raise there.+ rows = [row for row in (detail.get("breach_details") or []) if isinstance(row, dict)]+ breach_details = [row for row in rows if row.get("observed")]+ timezone = detail.get("timezone") or "UTC"+ zone = _zone(timezone)+ detected_at = transition.occurred_at.astimezone(zone).strftime("%d %b %Y, %H:%M %Z") + f" ({timezone})"+ affected_dates = detail.get("triggered_dates") or [row["date"] for row in rows if row.get("date")]+ affected_interval = (+ detail.get("interval")+ or next((row["interval"] for row in rows if row.get("interval")), None)+ or detail.get("insight_interval")+ )+ return insight_alert_slack_properties(+ breaches=breaches,+ breach_details=breach_details,+ affected_dates=affected_dates,+ affected_interval=affected_interval,+ project_timezone=zone.key,+ metric_name=detail.get("metric_name") or "Insight",+ is_anomaly=bool(detail.get("is_anomaly")),+ tags=detail.get("tags") or [],+ # Native delivery sends as the check finishes, before any anomaly investigation runs, so it+ # has no summary, verdict or next step to show. The HogFunction path sends later and does.+ summary=None,+ verdict=None,+ investigation_status=None,+ detected_at=detected_at,+ allowed_root=absolute_uri("/"),+ )+++def render_insight_slack_message(+ *,+ team_id: int,+ transition: AnnouncedTransition,+ alert_name: str,+ alert_url: str,+ project: MessageLink | None,+ image: MessageImage | None,+) -> SlackMessageContent | None:+ if transition.kind != AlertEventKind.FIRING:+ return None+ alert_id = transition.source_detail.get("alert_id")+ if not alert_id:+ return None+ properties = insight_transition_properties(transition)+ kind = "Anomaly alert" if properties["slack_alert_type"] == "Anomaly detected" else "Insight alert"+ project_url = project.url if project else absolute_uri(f"/project/{team_id}")+ project_name = project.label if project else transition.source_detail.get("team_name") or ""+ insight_short_id = transition.source_detail.get("insight_short_id")+ name = clip_text(alert_name, MAX_NAME_CHARS)+ fallback = f"{kind} ‘{name}’ triggered"+ blocks = _slack_blocks(+ chart={"type": "image", "image_url": image.url, "alt_text": image.alt_text} if image else {"type": "divider"},+ alert_id=str(alert_id),+ primary_url=alert_url,+ primary_label="🔎 View alert",+ insight_url=absolute_uri(f"/project/{team_id}/insights/{insight_short_id}") if insight_short_id else None,+ )+ attachments = _slack_attachments(+ heading_prefix=f"⚠️ {kind} ‘",+ alert_name=name,+ alert_url=alert_url,+ project_name=clip_text(project_name, MAX_NAME_CHARS) or None,+ project_url=project_url,+ details=properties["slack_alert_details"],+ timing=properties["slack_alert_timing"],+ tags=properties["slack_alert_tags"],+ fallback=fallback,+ blocks=blocks,+ )+ # The card lives in the attachment, but `text` is what Slack reads out in a push notification+ # and what a screen reader announces, so it repeats the fallback rather than going out empty.+ # Escaped, because `text` is mrkdwn and the name is user-written: `<!channel>` would broadcast.+ # The attachment's own fallback and the rich-text elements are not mrkdwn, so they stay literal.+ return SlackMessageContent(text=escape_slack_mrkdwn(fallback), blocks=[], attachments=attachments)diff --git a/products/alerts/backend/platform_hooks.py b/products/alerts/backend/platform_hooks.pyindex a39c6c508c20..065f20d3d3d4 100644--- a/products/alerts/backend/platform_hooks.py+++ b/products/alerts/backend/platform_hooks.py@@ -17,6 +17,8 @@ if TYPE_CHECKING:EvaluationAnnouncement,LegacyEventEmission,MessageImage,+ MessageLink,+ SlackMessageContent,)@@ -38,3 +40,19 @@ def insight_chart_image(*, team_id: int, transition: AnnouncedTransition) -> Mes)return platform_alert_legacy_events.insight_chart_image(team_id=team_id, transition=transition)+++def render_insight_slack_message(+ *,+ team_id: int,+ transition: AnnouncedTransition,+ alert_name: str,+ alert_url: str,+ project: MessageLink | None,+ image: MessageImage | None,+) -> SlackMessageContent | None:+ from products.alerts.backend import platform_alert_slack # noqa: PLC0415 - keeps alert models off the startup path++ return platform_alert_slack.render_insight_slack_message(+ team_id=team_id, transition=transition, alert_name=alert_name, alert_url=alert_url, project=project, image=image+ )diff --git a/products/alerts/backend/platform_source_cycle.py b/products/alerts/backend/platform_source_cycle.pyindex ad0fef4bbeb2..bbff6244a1c5 100644--- a/products/alerts/backend/platform_source_cycle.py+++ b/products/alerts/backend/platform_source_cycle.py@@ -16,6 +16,7 @@ A check that production skips without a query is skipped here too, so both stacksame set of checks."""+import jsonimport timeimport asynciofrom collections.abc import Collection, Iterator, Sequence@@ -39,6 +40,7 @@ from posthog.temporal.alerts.admission import admit_evaluation_slots, release_evfrom posthog.temporal.alerts.retry_policy import alert_timeoutsfrom products.alerts.backend.evaluation import check_alert_for_insight+from products.alerts.backend.evaluation.comparator import MAX_BREACH_MESSAGESfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.dispatcher import PerSeriesEvaluation, check_alert_per_seriesfrom products.alerts.backend.insight_alert_state_machine import INSIGHT_ALERT_POLICY, insight_snapshot@@ -533,6 +535,10 @@ def _legacy_alert(check: PlatformAlertCheckInput) -> AlertConfiguration | None:return Nonereturn (AlertConfiguration.objects.select_related("insight", "team", "threshold", "created_by")+ # A firing's card names the insight's tags. Prefetched with the alert, because a reverse+ # many-to-many cannot be selected, and the read would otherwise be its own round trip+ # inside the window the check holds its admission slot.+ .prefetch_related("insight__tagged_items__tag").filter(team_id=check.team_id, id=check.legacy_configuration_id).first())@@ -670,6 +676,7 @@ def _decide(query_duration_ms=duration_ms,firing=(alert, result.breaches or []),check_detail=detector_detail(result) if alert.detector_config else None,+ breach_details=(result.triggered_metadata or {}).get("breach_details"),)@@ -766,6 +773,15 @@ BREAKDOWN_GROUPING_KEY = "breakdown"# and every group's detail rides in the outcome Temporal carries, so a long label must not grow it.MAX_DETAIL_BREACHES: Final = 10MAX_BREACH_CHARS: Final = 500+MAX_DETAIL_ROWS: Final = MAX_BREACH_MESSAGES+MAX_TAGS: Final = 10+MAX_TAG_CHARS: Final = 100+# A breakdown alert announces up to `max_instances` groups in one outcome, and each group repeats+# the card fields. Per-group caps bound one group, not their sum, so the sum is bounded here: once+# a grouped evaluation has spent this much on detail, the groups after it keep only the fields the+# message cannot be built without. Well under Temporal's payload limit, which the outcome shares+# with the rest of the verdicts.+MAX_TOTAL_DETAIL_CHARS: Final = 200_000# A breakdown value can be muted on its own, which production cannot express, so the platform's# mute applies: the value is still judged and only its announcement is held. A snooze of the@@ -825,28 +841,33 @@ def _decide_grouped(if any(verdict.outcome.notification == NotificationAction.FIRE for verdict in decision.verdicts):# The row `decide_groups` judged for each key: the first, unless a later one breaches and it did not.breaches: dict[str, list[str]] = {}+ details_by_key: dict[str, list[dict[str, str]]] = {}for series in evaluated.series:key, found = bounded_grouping_key(series.identity), series.result.breaches or []if key not in breaches or (found and not breaches[key]):breaches[key] = found+ details_by_key[key] = (series.result.triggered_metadata or {}).get("breach_details", [])wants_chart = _wants_chart(check, alert)- decision = replace(- decision,- verdicts=tuple(- replace(- verdict,- group=replace(- verdict.group,- source_detail=_detail(- alert, breaches.get(verdict.group.grouping_key, []), wants_chart=wants_chart- ),- ),- )- if verdict.outcome.notification == NotificationAction.FIRE- else verdict- for verdict in decision.verdicts- ),- )+ # One insight, so its tags are read once rather than once per firing breakdown value.+ tags = _insight_tags(alert)+ budget = _DetailBudget()+ verdicts = []+ for verdict in decision.verdicts:+ if verdict.outcome.notification != NotificationAction.FIRE:+ verdicts.append(verdict)+ continue+ key = verdict.group.grouping_key+ full = budget.allows()+ detail = _detail(+ alert,+ breaches.get(key, []),+ wants_chart=wants_chart,+ breach_details=details_by_key.get(key) if full else None,+ tags=tags if full else [],+ )+ budget.charge(detail)+ verdicts.append(replace(verdict, group=replace(verdict.group, source_detail=detail)))+ decision = replace(decision, verdicts=tuple(verdicts))return decision.as_outcome(configuration_id=check.id,evaluation_key=_evaluation_key(check, now),@@ -857,10 +878,14 @@ def _decide_grouped(def _firing_detail(- check: PlatformAlertCheckInput, alert: AlertConfiguration, breaches: Sequence[str]+ check: PlatformAlertCheckInput,+ alert: AlertConfiguration,+ breaches: Sequence[str],+ *,+ breach_details: list[dict[str, str]] | None = None,) -> dict[str, Any]:"""What production's `$insight_alert_firing` carries beside the verdict, which only the check can know."""- return _detail(alert, breaches, wants_chart=_wants_chart(check, alert))+ return _detail(alert, breaches, wants_chart=_wants_chart(check, alert), breach_details=breach_details)def _wants_chart(check: PlatformAlertCheckInput, alert: AlertConfiguration) -> bool:@@ -903,14 +928,69 @@ def _clipped(text: str, limit: int = MAX_BREACH_CHARS) -> str:return text if len(text) <= limit else text[: limit - 1] + "…"-def _detail(alert: AlertConfiguration, breaches: Sequence[str], *, wants_chart: bool) -> dict[str, Any]:+def _insight_interval(alert: AlertConfiguration) -> str | None:+ """The insight's own interval, read the way production reads it.++ A stored query can carry an explicit `"source": null`, which a `.get` default never replaces,+ so the source is bound first and checked. This runs on the firing path, where an `AttributeError`+ would cost the check rather than the label.+ """+ query = alert.insight.query if isinstance(alert.insight.query, dict) else {}+ source = query.get("source")+ return (source if isinstance(source, dict) else query).get("interval")+++class _DetailBudget:+ """Keeps one grouped evaluation's details inside `MAX_TOTAL_DETAIL_CHARS` in total.++ Each group is built in full while the budget holds. After it runs out the rest are built+ without the repeated fields, so a wide breakdown announces every group it fired on rather than+ losing the whole outcome to a payload the activity cannot carry.+ """++ def __init__(self) -> None:+ self._spent = 0++ def allows(self) -> bool:+ return self._spent < MAX_TOTAL_DETAIL_CHARS++ def charge(self, detail: dict[str, Any]) -> None:+ self._spent += len(json.dumps(detail, default=str))+++def _insight_tags(alert: AlertConfiguration) -> list[str]:+ # Sorted and sliced in Python so the prefetch on `_legacy_alert` is used. A `filter()` here+ # would build a new queryset and go back to the database for every firing.+ names = sorted(item.tag.name for item in alert.insight.tagged_items.all() if item.tag.team_id == alert.team_id)+ return [_clipped(name, MAX_TAG_CHARS) for name in names[:MAX_TAGS]]+++def _detail(+ alert: AlertConfiguration,+ breaches: Sequence[str],+ *,+ wants_chart: bool,+ breach_details: list[dict[str, str]] | None = None,+ tags: list[str] | None = None,+) -> dict[str, Any]:# Bounded, because the outcome crosses into Temporal and a breach names user-written labels.detail: dict[str, Any] = {"breaches": [_clipped(breach) for breach in breaches[:MAX_DETAIL_BREACHES]],**_context(alert),# The legacy alert's id, which a native message's snooze menu snoozes."alert_id": str(alert.id),+ # Recorded now so the Slack card is a function of the transition and a later rename or delete cannot change it.+ "metric_name": _clipped(alert.insight.name or alert.insight.derived_name or "Insight", MAX_TAG_CHARS),+ "timezone": alert.team.timezone,+ "is_anomaly": bool(alert.detector_config),+ "insight_interval": _insight_interval(alert),+ "tags": _insight_tags(alert) if tags is None else tags,+ "team_name": _clipped(alert.team.name, MAX_TAG_CHARS),}+ if breach_details:+ detail["breach_details"] = [+ {key: _clipped(str(value)) for key, value in row.items()} for row in breach_details[:MAX_DETAIL_ROWS]+ ]if wants_chart:detail[CHART_PENDING_KEY] = str(alert.id)return detail@@ -953,13 +1033,14 @@ def _verdict(query_duration_ms: int | None = None,skip: SkipReason | None = None,firing: tuple[AlertConfiguration, Sequence[str]] | None = None,+ breach_details: list[dict[str, str]] | None = None,context: dict[str, Any] | None = None,check_detail: dict[str, Any] | None = None,) -> PlatformAlertOutcome:outcome = evaluate_alert_check(snapshot, check_input, now, policy=INSIGHT_ALERT_POLICY)source_detail: dict[str, Any] | Noneif firing is not None and outcome.notification == NotificationAction.FIRE:- source_detail = _firing_detail(check, *firing)+ source_detail = _firing_detail(check, *firing, breach_details=breach_details)elif outcome.notification != NotificationAction.NONE:source_detail = contextelse:diff --git a/products/alerts/backend/test/test_insight_alert_message.py b/products/alerts/backend/test/test_insight_alert_message.pyindex b3fa3f7744bc..66a8e75da3ab 100644--- a/products/alerts/backend/test/test_insight_alert_message.py+++ b/products/alerts/backend/test/test_insight_alert_message.py@@ -1,12 +1,15 @@import json+from datetime import UTC, datetimefrom typing import Anyfrom django.test import SimpleTestCasefrom parameterized import parameterized-from products.alerts.backend.logic.insight_alert_destinations import _slack_attachments+from products.alerts.backend.logic.insight_alert_destinations import hog_slack_attachmentsfrom products.alerts.backend.logic.insight_alert_message import insight_alert_slack_properties+from products.alerts.backend.platform_alert_slack import render_insight_slack_message+from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransitionfrom products.cdp.backend.validation import generate_template_bytecodefrom common.hogvm.python.execute import execute_bytecode@@ -56,7 +59,9 @@ class TestInsightAlertMessage(SimpleTestCase):return {key: render(item) for key, item in value.items()}return value- blocks = render(generate_template_bytecode(_slack_attachments(), set(), function_type="internal_destination"))+ blocks = render(+ generate_template_bytecode(hog_slack_attachments(), set(), function_type="internal_destination")+ )assert "23 Oct 2026, 10:00 to 23 Oct 2026, 11:00 (America/Toronto)" in json.dumps(blocks)assert "https://example.com/project/1" in json.dumps(blocks)assert blocks[-1]["blocks"][-1]["elements"][-1]["action_id"] == "insight_alert_snooze"@@ -111,3 +116,111 @@ class TestInsightAlertMessage(SimpleTestCase):timing = properties["slack_alert_timing"]["text"]["text"]assert first in timingassert last in timing++ @parameterized.expand(+ [+ ("that_fired", "original-insight"),+ # A transition recorded before the check stored the short id would otherwise link to+ # `/insights/None`, which is a live button onto a dead page.+ ("it_does_not_know", None),+ ]+ )+ def test_native_message_links_to_the_insight(self, _name: str, short_id: str | None) -> None:+ now = datetime(2026, 1, 1, tzinfo=UTC)+ detail: dict[str, Any] = {"alert_id": "00000000-0000-4000-8000-000000000001"}+ if short_id is not None:+ detail["insight_short_id"] = short_id+ transition = AnnouncedTransition(+ grouping_key="",+ kind=AlertEventKind.FIRING,+ episode_started_at=now,+ value=240,+ labels={},+ condition={},+ source_config={},+ error_message=None,+ occurred_at=now,+ source_detail=detail,+ )+ content = render_insight_slack_message(+ team_id=1,+ transition=transition,+ alert_name="Example alert",+ alert_url="https://example.com/alert",+ project=None,+ image=None,+ )+ assert content is not None+ links = [+ element["url"]+ for element in content.attachments[1]["blocks"][-1]["elements"]+ if element.get("text", {}).get("text") == "📊 View insight"+ ]+ assert [link.split("/project/")[-1] for link in links] == ([f"1/insights/{short_id}"] if short_id else [])++ @parameterized.expand(+ [+ ("says_what_it_is", "Example alert", "Insight alert ‘Example alert’ triggered"),+ # `text` is mrkdwn, so an alert a project member named `<!channel>` would otherwise+ # broadcast to everyone in the channel on every firing.+ ("cannot_speak_as_slack_markup", "<!channel>", "Insight alert ‘<!channel>’ triggered"),+ ]+ )+ def test_the_text_slack_notifies_with(self, _name: str, alert_name: str, expected: str) -> None:+ # The card is an attachment, which a push notification and a screen reader do not read.+ now = datetime(2026, 1, 1, tzinfo=UTC)+ transition = AnnouncedTransition(+ grouping_key="",+ kind=AlertEventKind.FIRING,+ episode_started_at=now,+ value=240,+ labels={},+ condition={},+ source_config={},+ error_message=None,+ occurred_at=now,+ source_detail={"alert_id": "00000000-0000-4000-8000-000000000001"},+ )+ content = render_insight_slack_message(+ team_id=1,+ transition=transition,+ alert_name=alert_name,+ alert_url="https://example.com/alert",+ project=None,+ image=None,+ )+ assert content is not None+ assert content.text == expected+ # The attachment fallback is plain text, so it keeps the name as written.+ assert alert_name in content.attachments[0]["fallback"]++ def test_native_anomaly_message_shows_the_affected_period(self) -> None:+ now = datetime(2026, 1, 2, tzinfo=UTC)+ transition = AnnouncedTransition(+ grouping_key="",+ kind=AlertEventKind.FIRING,+ episode_started_at=now,+ value=240,+ labels={},+ condition={},+ source_config={},+ error_message=None,+ occurred_at=now,+ source_detail={+ "alert_id": "00000000-0000-4000-8000-000000000001",+ "insight_short_id": "original-insight",+ "is_anomaly": True,+ "triggered_dates": ["2026-01-01"],+ "interval": "day",+ },+ )+ content = render_insight_slack_message(+ team_id=1,+ transition=transition,+ alert_name="Example alert",+ alert_url="https://example.com/alert",+ project=None,+ image=None,+ )+ assert content is not None+ assert "Affected period" in str(content.attachments)diff --git a/products/alerts/backend/test/test_platform_alert_legacy_events.py b/products/alerts/backend/test/test_platform_alert_legacy_events.pyindex 69193180b1f5..766e52b0895a 100644--- a/products/alerts/backend/test/test_platform_alert_legacy_events.py+++ b/products/alerts/backend/test/test_platform_alert_legacy_events.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom posthog.test.base import APIBaseTest@@ -27,6 +27,15 @@ _MODULE = "products.alerts.backend.platform_alert_legacy_events"CHECKED_AT = datetime(2026, 10, 20, 9, 0, tzinfo=UTC)CHART_URL = "https://example.com/chart.png"_EMITTER = "products.alerts.backend.platform_alert_legacy_events"+# What the platform adds on top of what the insight stack sends: the pre-rendered Slack card.+_SLACK_CARD_PROPERTIES = {+ "slack_alert_tags",+ "slack_alert_type",+ "slack_alert_status",+ "slack_alert_timing",+ "slack_alert_detected_at",+ "slack_alert_details",+}class TestInsightLegacyEvents(APIBaseTest):@@ -105,14 +114,48 @@ class TestInsightLegacyEvents(APIBaseTest):trigger_alert_hog_functions(self.alert, {"breaches": "\n".join(breaches), **sent})with patch(f"{_EMITTER}.insight_chart_url", return_value=CHART_URL) as mint:- (event,) = self._emit(self._emission(detail={"breaches": breaches, **stored}))+ (event,) = self._emit(self._emission(detail={"breaches": breaches, "is_anomaly": True, **stored}))assert event.event_name == produce.call_args.kwargs["event_name"]- assert event.properties == produce.call_args.kwargs["properties"]+ expected = produce.call_args.kwargs["properties"]+ assert {key: event.properties[key] for key in expected} == expected+ # Named rather than left open, so a property the insight stack never sends cannot appear+ # here unnoticed and reach a customer's HogFunction template.+ assert set(event.properties) - set(expected) == _SLACK_CARD_PROPERTIES+ assert event.properties["slack_alert_type"] == "Anomaly detected"# The URL opens the chart without a login, so it is minted for the user that rendered it.if "insight_chart_asset_id" in stored:assert mint.call_args.kwargs["chart"] == RenderedInsightChart(asset_id=7, render_user_id=3)+ def test_a_firing_states_the_transition_it_announces_not_the_alert_row(self) -> None:+ # The platform writes neither column, so a platform-owned alert's row keeps whatever the+ # insight stack last left there — `Not firing` once the shadow check stops.+ self.alert.state = AlertState.NOT_FIRING.value+ self.alert.last_checked_at = CHECKED_AT - timedelta(days=30)+ self.alert.save(update_fields=["state", "last_checked_at"])++ (event,) = self._emit(self._emission(detail={"breaches": ["above 100"]}))++ assert event.properties["state"] == AlertState.FIRING.value+ assert event.properties["last_checked_at"] == CHECKED_AT.isoformat()++ @parameterized.expand(+ [+ ("an_unknown_timezone", {"timezone": "Mars/Olympus"}),+ ("a_breach_row_that_is_not_a_dict", {"breach_details": ["above 100"]}),+ ("a_breach_row_without_an_observed_value", {"breach_details": [{"group": "Chrome"}]}),+ ]+ )+ def test_a_detail_the_card_cannot_be_built_from_still_emits_the_event(+ self, _name: str, detail: dict[str, Any]+ ) -> None:+ # The card is an extra. Losing it must not take the event, because the event is what every+ # HogFunction destination — Slack, webhook, email — listens on.+ (event,) = self._emit(self._emission(detail={"breaches": ["above 100"], **detail}))++ assert event.properties["alert_id"] == str(self.alert.id)+ assert event.properties["breaches"] == "above 100"+@parameterized.expand([("an_error", AlertEventKind.ERRORED, True, None),diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.pyindex 3701a3eab886..f7bc8e8e519a 100644--- a/products/alerts/backend/test/test_platform_source_cycle.py+++ b/products/alerts/backend/test/test_platform_source_cycle.py@@ -1,3 +1,4 @@+import jsonimport timefrom collections.abc import Callablefrom contextlib import AbstractContextManager@@ -162,6 +163,23 @@ class TestPlatformInsightEvaluation(APIBaseTest):expected = {"Chrome": "firing"} | ({"Firefox": missing_state} if missing_state else {})assert {group.grouping_key: group.new_state for group in resolved.groups} == expected+ def test_a_wide_breakdown_firing_stays_inside_what_temporal_carries(self) -> None:+ # Every firing group repeats the card fields, so a field added per group multiplies by the+ # group limit. The whole outcome crosses an activity boundary that refuses ~2 MiB.+ grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("breakdown",))+ configuration = self._copy(self._alert(), grouping=grouping.to_stored())++ fired = self._evaluate_per_series(+ configuration, {f"value-{index}": 150.0 for index in range(120)}, breach="x" * 2000+ )++ assert len(fired.groups) > 1+ assert len(json.dumps([group.source_detail for group in fired.groups], default=str)) < 1_000_000+ # Trimming drops the repeated fields, never the group's own identity or its breaches.+ for group in fired.groups:+ assert group.source_detail["alert_id"]+ assert group.source_detail["breaches"]+def test_a_breakdown_value_reported_twice_keeps_the_breach_of_the_row_that_fired(self) -> None:grouping = Grouping(mode=GroupingMode.BY_RESULT_LABELS, keys=("breakdown",))configuration = self._copy(self._alert(), grouping=grouping.to_stored())@@ -219,6 +237,13 @@ class TestPlatformInsightEvaluation(APIBaseTest):"insight_name": alert.insight.name,"insight_short_id": alert.insight.short_id,"alert_id": str(alert.id),+ # Recorded at trigger time so the card stays a function of the transition.+ "metric_name": alert.insight.name,+ "timezone": self.team.timezone,+ "is_anomaly": False,+ "insight_interval": "day",+ "tags": [],+ "team_name": self.team.name,**({CHART_PENDING_KEY: str(alert.id)} if wants_chart else {}),}@@ -232,6 +257,28 @@ class TestPlatformInsightEvaluation(APIBaseTest):# A render takes up to a minute and a half, so it never runs while the check holds its pool slot.render.assert_not_called()+ @parameterized.expand(+ [+ ("a_wrapped_query", {"kind": "InsightVizNode", "source": {"interval": "week"}}, "week"),+ # A `.get("source", default)` never replaces an explicit null, so this shape used to+ # raise inside the check — losing the firing over a label on its card.+ ("an_explicit_null_source", {"kind": "InsightVizNode", "source": None, "interval": "hour"}, "hour"),+ ("a_source_that_is_not_a_query", {"source": "trends", "interval": "month"}, "month"),+ ]+ )+ def test_a_firing_records_the_interval_of_any_stored_query_shape(+ self, _name: str, query: dict[str, Any], interval: str+ ) -> None:+ alert = self._alert()+ alert.insight.query = query+ alert.insight.save(update_fields=["query"])+ configuration = self._copy(alert)++ outcome, _ = self._evaluate(configuration, result=AlertEvaluationResult(value=150.0, breaches=["above 100"]))++ assert outcome is not None+ assert outcome.groups[0].source_detail["insight_interval"] == interval+@override_settings(ALERTS_PLATFORM_INSIGHT_MAX_INFLIGHT_CHART_RENDERS=1)def test_a_chart_render_holds_a_render_slot_only_while_it_runs(self) -> None:alert = self._alert()diff --git a/products/alerts_platform/backend/delivery/describers.py b/products/alerts_platform/backend/delivery/describers.pyindex e82eeee66df0..65c112e27a97 100644--- a/products/alerts_platform/backend/delivery/describers.py+++ b/products/alerts_platform/backend/delivery/describers.py@@ -17,6 +17,7 @@ from products.alerts_platform.backend.facade.contracts import (SourceDescription,SourceImageResolver,SourceKind,+ SourceSlackRenderer,)# A source's context names things a user chose, such as services, so its size is unbounded. The@@ -36,6 +37,7 @@ logger = structlog.get_logger(__name__)_describers: dict[SourceKind, SourceDescriber] = {}_image_resolvers: dict[SourceKind, SourceImageResolver] = {}+_slack_renderers: dict[SourceKind, SourceSlackRenderer] = {}def register(source: SourceKind, describer: SourceDescriber) -> None:@@ -112,3 +114,14 @@ def resolve_image(source: SourceKind, *, team_id: int, transition: AnnouncedTranlogger.warning("alerts_platform.image_url_too_long", source=source.value, length=len(image.url))return Nonereturn MessageImage(url=image.url, alt_text=clip_text(image.alt_text, MAX_IMAGE_ALT_TEXT_CHARS))+++def register_slack_renderer(source: SourceKind, renderer: SourceSlackRenderer) -> None:+ registered = _slack_renderers.get(source)+ if registered is not None and registered is not renderer:+ raise RuntimeError(f"A different Slack renderer is already registered for {source} alerts.")+ _slack_renderers[source] = renderer+++def slack_renderer_for(source: SourceKind) -> SourceSlackRenderer | None:+ return _slack_renderers.get(source)diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.pyindex a6a27d420736..5ed733ff6da1 100644--- a/products/alerts_platform/backend/delivery/message.py+++ b/products/alerts_platform/backend/delivery/message.py@@ -39,6 +39,8 @@ _SYMBOLS: Final[dict[AlertEventKind, str]] = {AlertEventKind.BROKEN: "⚠️",}+UNTRACKED_GROUPS_LABEL: Final = "Untracked groups"+_SOURCE_LABELS: Final[dict[SourceKind, str]] = {SourceKind.LOGS: "Log",SourceKind.INSIGHT: "Insight",@@ -196,7 +198,7 @@ def build_message(untracked = f"At least {untracked}"details.append(MessageDetail(- label="Untracked groups",+ label=UNTRACKED_GROUPS_LABEL,value=f"{untracked} not tracked because this alert is at its group limit",))diff --git a/products/alerts_platform/backend/delivery/slack.py b/products/alerts_platform/backend/delivery/slack.pyindex c8b49e1d9b9f..1dcead578150 100644--- a/products/alerts_platform/backend/delivery/slack.py+++ b/products/alerts_platform/backend/delivery/slack.py@@ -7,6 +7,7 @@ message becomes blocks.from typing import Any, Final+import structlogfrom slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import SLACK_INTEGRATION_KINDS, Integration, SlackIntegration@@ -24,9 +25,17 @@ from posthog.slack.channels import ()from posthog.slack.formatting import escape_slack_mrkdwn-from products.alerts_platform.backend.delivery.message import AlertMessage+from products.alerts_platform.backend.delivery.describers import slack_renderer_for+from products.alerts_platform.backend.delivery.message import UNTRACKED_GROUPS_LABEL, AlertMessagefrom products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle-from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind, MessageDetail+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,+ AlertEventKind,+ MessageDetail,+ SlackMessageContent,+)++logger = structlog.get_logger(__name__)PROVIDER: Final = "slack"@@ -84,15 +93,86 @@ def _without_images(blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:return [block for block in blocks if block.get("type") != "image"]-def _refused_image(error: SlackApiError, blocks: list[dict[str, Any]]) -> bool:- return error.response.get("error") == IMAGE_REFUSAL and len(_without_images(blocks)) < len(blocks)+def content_for(*, team_id: int, message: AlertMessage) -> SlackMessageContent:+ renderer = slack_renderer_for(message.source)+ if renderer is not None:+ try:+ content = renderer(+ team_id=team_id,+ transition=message.transition,+ alert_name=message.alert_name,+ alert_url=message.alert_url,+ project=message.project,+ image=message.image,+ )+ if content is not None:+ return _with_untracked_groups(content, message)+ except Exception:+ logger.exception("alerts_platform.slack_renderer_failed", source=message.source.value)+ # Counted as well as logged: the fallback is invisible to the recipient, so a renderer+ # broken for every message would otherwise show up only as a card nobody recognizes.+ # Imported here because source apps reach this module from ready(), and the metrics+ # module would load temporalio into every process at startup.+ from products.alerts_platform.backend.temporal.metrics import ( # noqa: PLC0415 - keeps temporalio off the import path+ increment_slack_renderer_failures,+ safe_record,+ )++ safe_record(increment_slack_renderer_failures, message.source.value)+ return SlackMessageContent(text=escape_slack_mrkdwn(message.title), blocks=blocks_for(message))+++def _above_actions(blocks: list[dict[str, Any]], notice: dict[str, Any]) -> list[dict[str, Any]]:+ """`notice` inserted above the action row, or appended when the blocks have none.++ By position rather than by index from the end, because `SourceSlackRenderer` promises nothing+ about the block order a source returns.+ """+ for index, block in enumerate(blocks):+ if block.get("type") == "actions":+ return [*blocks[:index], notice, *blocks[index:]]+ return [*blocks, notice]+++def _with_untracked_groups(content: SlackMessageContent, message: AlertMessage) -> SlackMessageContent:+ notices = [detail for detail in message.details if detail.label == UNTRACKED_GROUPS_LABEL]+ if not notices:+ return content+ notice = section_block(_body(tuple(notices)))+ # The warning says the alert is at its group limit, so a reader who misses it reads a truncated+ # alert as a complete one. It goes wherever the renderer left room, never nowhere.+ if not content.attachments:+ return SlackMessageContent(+ text=content.text, blocks=_above_actions(content.blocks, notice), attachments=content.attachments+ )+ last = content.attachments[-1]+ attachments = [*content.attachments[:-1], {**last, "blocks": _above_actions(last.get("blocks", []), notice)}]+ return SlackMessageContent(text=content.text, blocks=content.blocks, attachments=attachments)+++def _without_image_content(content: SlackMessageContent) -> SlackMessageContent:+ return SlackMessageContent(+ text=content.text,+ blocks=_without_images(content.blocks),+ attachments=[+ {**attachment, "blocks": _without_images(attachment.get("blocks", []))}+ for attachment in content.attachments+ ],+ )+++def _refused_image(error: SlackApiError, content: SlackMessageContent) -> bool:+ return error.response.get("error") == IMAGE_REFUSAL and _without_image_content(content) != contentdef _with_state_line(blocks: list[dict[str, Any]], state_line: str) -> list[dict[str, Any]]:"""The opening blocks unchanged, with the state line above the buttons `blocks_for` ends with.The state line is platform text, built from a state and a time, so it is not escaped.+ A source renderer promises no trailing action row, so an empty list appends instead."""+ if not blocks:+ return [context_block(state_line)]return [*blocks[:-1], context_block(state_line), blocks[-1]]@@ -116,32 +196,31 @@ class SlackTransport:raise DeliveryError("This Slack destination is missing its workspace or channel.")slack = SlackIntegration(self._integration(team_id=team_id, workspace_id=workspace_id), source=EGRESS_SOURCE)- blocks = blocks_for(message)- # The one place the alert's name reaches mrkdwn: the header renders plain text.- text = escape_slack_mrkdwn(message.title)+ content = content_for(team_id=team_id, message=message)- def post(blocks: list[dict[str, Any]]) -> Any:+ def post(content: SlackMessageContent) -> Any:return post_message(slack,channel,- blocks,- text,+ content.blocks,+ content.text,thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None,# A root edit notifies nobody, and a thread reply notifies only the people who follow# the thread. So a resolve and a repeat firing also go to the channel, where legacy# posted each one as a new message.reply_broadcast=in_reply_to is not Noneand message.transition.kind in (AlertEventKind.RESOLVED, AlertEventKind.FIRING),+ **({"attachments": content.attachments} if content.attachments else {}),)try:try:- response = post(blocks)+ response = post(content)except SlackApiError as error:- if not _refused_image(error, blocks):+ if not _refused_image(error, content):raise- blocks = _without_images(blocks)- response = post(blocks)+ content = _without_image_content(content)+ response = post(content)except SlackApiError as error:# A refusal a person can fix, such as a channel the bot has left, rather than a# transport failure a retry would clear.@@ -149,8 +228,16 @@ class SlackTransport:timestamp = response.get("ts")if not timestamp:raise DeliveryError("Slack accepted the message but returned no timestamp to reply to.")- # An opening message keeps what it posted, so an edit can restate it word for word.- root_content = {"blocks": blocks, "text": text} if in_reply_to is None else None+ root_content = None+ if in_reply_to is None:+ root_content = {"blocks": content.blocks, "text": content.text}+ if content.attachments:+ root_content["attachments"] = content.attachments+ # An attachment card posts no blocks, but a reader from before attachments existed+ # edits `blocks` and indexes its last element. During a rolling deploy or a+ # rollback that reader handles the resolve, so it is given one block to work on.+ # `edit_root` below ignores this and sends the posted blocks instead.+ root_content["blocks"] = content.blocks or [section_block(content.text)]return MessageHandle(external_ref={"channel": channel, "ts": timestamp}, root_content=root_content)def edit_root(self, *, team_id: int, target: AlertDestinationData, root: MessageHandle, state_line: str) -> None:@@ -160,18 +247,45 @@ class SlackTransport:if workspace_id is None or not channel or not ts or not root.root_content:raise DeliveryError("This Slack conversation has no opening message to edit.")slack = SlackIntegration(self._integration(team_id=team_id, workspace_id=workspace_id), source=EGRESS_SOURCE)- blocks = _with_state_line(root.root_content["blocks"], state_line)- # Screen readers read the fallback text rather than the blocks, so it carries the current- # state too.- text = f"{root.root_content['text']} ({state_line})"+ original = root.root_content+ attachments = original.get("attachments") or []+ text = f"{original['text']} ({state_line})" if original["text"] else ""+ if attachments:+ attachments = [+ *attachments[:-1],+ {+ **attachments[-1],+ # Screen readers read the fallback text rather than the blocks, so it carries the+ # current state too.+ "fallback": f"{attachments[-1].get('fallback', '')} ({state_line})",+ "blocks": _with_state_line(attachments[-1].get("blocks", []), state_line),+ },+ ]+ # The card is the attachment. `original["blocks"]` holds only the stand-in an older+ # reader would need, so the edit restores what the opening message actually posted.+ blocks: list[dict[str, Any]] = []+ else:+ blocks = _with_state_line(original["blocks"], state_line)+ content = SlackMessageContent(text=text, blocks=blocks, attachments=attachments)++ def update(content: SlackMessageContent) -> None:+ update_message(+ slack,+ channel,+ ts,+ content.blocks,+ content.text,+ **({"attachments": content.attachments} if content.attachments else {}),+ )+try:try:- update_message(slack, channel, ts, blocks, text)+ update(content)except SlackApiError as error:# A chart URL expires, so an edit long after the opening message can lose it.- if not _refused_image(error, blocks):+ if not _refused_image(error, content):raise- update_message(slack, channel, ts, _without_images(blocks), text)+ update(_without_image_content(content))except SlackApiError as error:raise DeliveryError(f"Slack refused the edit: {error.response.get('error')}") from errordiff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex c801b022e942..7c7a15eff88b 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -1402,6 +1402,38 @@ class SourceDescriber(Protocol):def __call__(self, *, project_id: int, transition: AnnouncedTransition) -> SourceDescription: ...+@frozen+class SlackMessageContent:+ text: str+ blocks: list[dict[str, Any]]+ attachments: list[dict[str, Any]] = field(default_factory=list)+++class SourceSlackRenderer(Protocol):+ """A source's own Slack layout for a transition, or None to use the platform's.++ Runs on the send path, so it reads only the transition it is given. The platform catches a+ renderer that raises and sends its own layout instead, so a broken renderer costs the card+ rather than the notification.++ `text` is what a push notification and a screen reader read, so it is never empty, whether or+ not the card itself lives in `attachments`. The platform adds the group-limit warning to the+ content wherever it finds room, and adds the state line to it on a later edit; neither assumes+ a particular block order.+ """++ def __call__(+ self,+ *,+ team_id: int,+ transition: AnnouncedTransition,+ alert_name: str,+ alert_url: str,+ project: MessageLink | None,+ image: MessageImage | None,+ ) -> SlackMessageContent | None: ...++class SourceImageResolver(Protocol):"""The picture a message shows for a transition, such as an insight's chart, or None.diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.pyindex b83246e078b8..589ee4ab49f2 100644--- a/products/alerts_platform/backend/facade/delivery.py+++ b/products/alerts_platform/backend/facade/delivery.py@@ -20,6 +20,7 @@ from products.alerts_platform.backend.facade.contracts import (SourceDescriber,SourceImageResolver,SourceKind,+ SourceSlackRenderer,)if TYPE_CHECKING:@@ -71,3 +72,7 @@ def has_legacy_event_emitter(source: SourceKind) -> bool:def native_sends_legacy_webhook_body(source: SourceKind, team: Team) -> bool | None:"""Whether a stock webhook receives the body its HogFunction sent when delivered natively. None when unknown."""return legacy_webhook.native_sends_legacy_body(source, team)+++def register_source_slack_renderer(source: SourceKind, renderer: SourceSlackRenderer) -> None:+ describers.register_slack_renderer(source, renderer)diff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.pyindex db70b513de88..8e69c68939c3 100644--- a/products/alerts_platform/backend/temporal/metrics.py+++ b/products/alerts_platform/backend/temporal/metrics.py@@ -169,6 +169,14 @@ def increment_describer_failures(source: str) -> None:).add(1)+def increment_slack_renderer_failures(source: str) -> None:+ """A source's Slack renderer raised, so its alerts went out in the platform's generic layout."""+ get_metric_meter({"source": source}).create_counter(+ "alerts_platform_slack_renderer_failures_total",+ "Slack messages sent in the platform's layout because the source's renderer raised",+ ).add(1)++def increment_root_edit_failures(provider: str) -> None:"""An opening message could not be brought up to date, so it shows an older state."""get_metric_meter({"provider": provider}).create_counter(diff --git a/products/alerts_platform/backend/tests/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.pyindex 1ac443fc5503..906a5a9254cb 100644--- a/products/alerts_platform/backend/tests/test_delivery_slack.py+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py@@ -13,7 +13,8 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integrationfrom posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARS-from products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_for+from products.alerts_platform.backend.delivery.message import UNTRACKED_GROUPS_LABEL+from products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_for, content_forfrom products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandlefrom products.alerts_platform.backend.facade.contracts import (AlertDestinationData,@@ -21,6 +22,7 @@ from products.alerts_platform.backend.facade.contracts import (MessageDetail,MessageImage,MessageLink,+ SlackMessageContent,)from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message, announced_transition@@ -219,3 +221,86 @@ class TestSlackTransport(APIBaseTest):with pytest.raises(DeliveryError):self._send(target=target)+++class TestSlackAttachmentTransport(SimpleTestCase):+ @parameterized.expand([(False,), (True,)])+ def test_attachments_survive_send_retry_and_state_update(self, refuse_image: bool) -> None:+ image = {"type": "image", "image_url": "https://example.com/chart.png", "alt_text": "Chart"}+ actions = {+ "type": "actions",+ "elements": [+ {"type": "button", "url": "https://example.com", "text": {"type": "plain_text", "text": "View"}}+ ],+ }+ metadata = {+ "color": "#D97706",+ "blocks": [{"type": "section", "text": {"type": "plain_text", "text": "Limit exceeded"}}],+ }+ content = SlackMessageContent(text="", blocks=[], attachments=[metadata, {"blocks": [image, actions]}])+ target = cast(AlertDestinationData, {"type": "slack", "slack_workspace_id": 1, "slack_channel_id": "C-SAMPLE"})+ with (+ patch("products.alerts_platform.backend.delivery.slack.slack_renderer_for") as renderer,+ patch.object(SlackTransport, "_integration"),+ patch("products.alerts_platform.backend.delivery.slack.SlackIntegration") as integration,+ ):+ renderer.return_value.return_value = content+ post = integration.return_value.client.chat_postMessage+ responses: list[Any] = [{"ts": "1700000000.1"}]+ if refuse_image:+ responses.insert(0, SlackApiError("invalid_blocks", {"error": "invalid_blocks"}))+ post.side_effect = responses+ transport = SlackTransport()+ handle = transport.deliver(team_id=1, target=target, message=MESSAGE)+ assert handle is not None+ sent = post.call_args.kwargs["attachments"]+ assert sent[0] == metadata+ assert sent[1]["blocks"][-1] == actions+ assert any(block["type"] == "image" for block in sent[1]["blocks"]) is not refuse_image+ transport.edit_root(team_id=1, target=target, root=handle, state_line="Resolved")+ update = integration.return_value.client.chat_update.call_args.kwargs+ updated = update["attachments"]+ assert updated[0] == metadata+ assert updated[1]["blocks"][-1] == actions+ assert updated[1]["blocks"][-2]["elements"][0]["text"] == "Resolved"+ # The card is the attachment, so the edit must not promote the stand-in below.+ assert update["blocks"] == []+ assert handle.root_content is not None+ assert handle.root_content["attachments"] == sent+ # A reader from before attachments existed edits `blocks` and indexes its last element,+ # so an attachment card leaves it something to work on rather than an empty list.+ assert handle.root_content["blocks"]+ assert content.attachments[1]["blocks"] == [image, actions]+++class TestSourceRendererKeepsGroupLimitNotice(SimpleTestCase):+ @parameterized.expand(+ [+ # The renderer contract promises neither an attachment nor a trailing action row, and+ # the notice is the only sign that the alert stopped at its group limit.+ ("an_attachment", False, False),+ ("blocks_alone", True, False),+ ("blocks_without_an_action_row", True, True),+ ]+ )+ def test_untracked_groups_detail_survives_any_renderer_shape(+ self, _name: str, blocks_only: bool, without_actions: bool+ ) -> None:+ rendered: list[dict[str, Any]] = [{"type": "divider"}]+ if not without_actions:+ rendered.append({"type": "actions", "elements": []})+ content = (+ SlackMessageContent(text="Alert", blocks=rendered)+ if blocks_only+ else SlackMessageContent(text="Alert", blocks=[], attachments=[{"blocks": rendered}])+ )+ message = replace(+ MESSAGE, details=(MessageDetail(label=UNTRACKED_GROUPS_LABEL, value="2 more groups not tracked"),)+ )+ with patch("products.alerts_platform.backend.delivery.slack.slack_renderer_for") as renderer:+ renderer.return_value.return_value = content+ result = content_for(team_id=1, message=message)+ blocks = result.blocks if blocks_only else result.attachments[0]["blocks"]+ assert "2 more groups not tracked" in str(blocks)+ # Above the buttons when there are buttons, so the notice is never read as one of them.+ assert blocks[-1]["type"] == ("section" if without_actions else "actions")