: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
fix(alerts): format anomaly investigation Slack alerts nicely (#70449)
Radu Raicea4a058accc5b6
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex 7529af59de05..df066d318ebc 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -934,6 +934,8 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Ho},},{+ // plain_text (not mrkdwn) so user-controlled names in the breach text can't+ // inject Slack markup/links/mentions. Newlines still render as line breaks.type: 'section',text: {type: 'plain_text',@@ -949,13 +951,19 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Hotype: 'actions',elements: [{- url: '{project.url}/insights/{event.properties.insight_id}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack',- text: { text: 'View Insight', type: 'plain_text' },+ // Points to the anomaly investigation notebook when present, otherwise falls+ // back to the alert page (Slack can't conditionally hide a button, so the+ // one button does double duty).+ url: "{event.properties.investigation_notebook_url ? event.properties.investigation_notebook_url : concat(project.url, '/insights/', event.properties.insight_id, '/alerts?alert_id=', event.properties.alert_id, '&utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack')}",+ text: {+ text: "{event.properties.investigation_notebook_url ? 'View Investigation' : 'View Alert'}",+ type: 'plain_text',+ },type: 'button',},{- url: '{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}&utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack',- text: { text: 'View Alert', type: 'plain_text' },+ url: '{project.url}/insights/{event.properties.insight_id}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack',+ text: { text: 'View Insight', type: 'plain_text' },type: 'button',},],diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 01c649357ebe..e39609346fe2 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -213,9 +213,17 @@ def trigger_alert_hog_functions(alert: AlertConfiguration, properties: dict) ->)-def send_notifications_for_breaches(alert: AlertConfiguration, breaches: list[str], idempotency_key: str) -> list[str]:+def send_notifications_for_breaches(+ alert: AlertConfiguration,+ breaches: list[str],+ idempotency_key: str,+ extra_properties: dict[str, str] | None = None,+) -> list[str]:"""A stable idempotency_key (typically alert_check.id) lets MessagingRecord enforceper-recipient at-most-once delivery on retries.++ `extra_properties` are merged into the internal-event properties that HogFunction+ destinations render (e.g. the anomaly investigation notebook URL for the Slack button)."""email_targets = alert.get_subscribed_users_emails()if email_targets:@@ -243,7 +251,9 @@ def send_notifications_for_breaches(alert: AlertConfiguration, breaches: list[stlogger.info("send_notifications_for_breaches", alert_id=alert.id, anomaly_count=len(breaches))message.send()- trigger_alert_hog_functions(alert=alert, properties={"breaches": ", ".join(breaches)})+ # Join with newlines so each breach/investigation line renders on its own line in+ # Slack/Discord/Teams destinations rather than as one run-on comma-separated string.+ trigger_alert_hog_functions(alert=alert, properties={"breaches": "\n".join(breaches), **(extra_properties or {})})return email_targets@@ -281,6 +291,7 @@ def dispatch_alert_notification(alert: AlertConfiguration,alert_check: AlertCheck,breaches: list[str] | None,+ extra_properties: dict[str, str] | None = None,) -> list[str] | None:"""Route an AlertCheck to the correct notification sender.@@ -313,6 +324,12 @@ def dispatch_alert_notification("caller must pass the breaches list from AlertEvaluationResult")logger.info("Sending alert firing notifications", alert_id=alert.id)+ # Only forward extra_properties when there's something to add (anomaly investigations),+ # keeping the common threshold-alert call unchanged.+ if extra_properties:+ return send_notifications_for_breaches(+ alert, breaches, idempotency_key=str(alert_check.id), extra_properties=extra_properties+ )return send_notifications_for_breaches(alert, breaches, idempotency_key=str(alert_check.id))case _:raise AssertionError(f"dispatch_alert_notification: unhandled alert state: {alert_check.state}")diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.pyindex 7c5d1d4f6deb..cb988be04386 100644--- a/posthog/temporal/ai/anomaly_investigation/workflow.py+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py@@ -6,6 +6,7 @@ Triggered from posthog/temporal/alerts/workflows.py when an alert transitions tofrom __future__ import annotations+import reimport jsonimport asynciofrom dataclasses import dataclass@@ -44,6 +45,10 @@ ANOMALY_INVESTIGATION_ACTIVITY_MAX_ATTEMPTS = 2MAX_SUMMARY_CHARS = 500+# Matches a sentence-ending punctuation mark followed by whitespace or end-of-string,+# used to clip the summary teaser on a sentence boundary instead of mid-word.+_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")+@dataclassclass AnomalyInvestigationWorkflowInputs:@@ -223,8 +228,16 @@ def _dispatch_gated_notification(breaches = _build_breach_descriptions(alert_check=check, verdict=verdict, summary=summary, notebook_short_id=notebook_short_id)+ # Surface the notebook URL as an event property so the Slack destination can render a+ # "View Investigation" button. Absent when the investigation produced no notebook, in+ # which case the button falls back to "View Alert".+ extra_properties = (+ {"investigation_notebook_url": absolute_uri(f"/notebooks/{notebook_short_id}")}+ if notebook_short_id+ else None+ )try:- targets = dispatch_alert_notification(alert, check, breaches)+ targets = dispatch_alert_notification(alert, check, breaches, extra_properties=extra_properties)if targets is not None:record_alert_delivery(alert, check, targets)except Exception:@@ -288,6 +301,20 @@ def _truncate_summary(summary: str | None) -> str | None:return Noneif len(trimmed) <= MAX_SUMMARY_CHARS:return trimmed++ window = trimmed[:MAX_SUMMARY_CHARS]+ # Prefer clipping at the last complete sentence, but only if it keeps enough of the+ # teaser — otherwise a short lead sentence would drop most of the summary.+ sentence_ends = [match.end() for match in _SENTENCE_END_RE.finditer(window)]+ if sentence_ends and sentence_ends[-1] >= MAX_SUMMARY_CHARS // 2:+ # Always append the ellipsis: the boundary might be an abbreviation (e.g. "U.S."),+ # not a real sentence end, so a clean-looking stop would hide that we dropped the rest.+ return window[: sentence_ends[-1]].rstrip() + " …"++ # No usable sentence boundary — fall back to the last word boundary with an ellipsis.+ word_end = window.rstrip().rfind(" ")+ if word_end != -1:+ return window[:word_end].rstrip() + "…"return trimmed[: MAX_SUMMARY_CHARS - 1].rstrip() + "…"diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_summary.py b/posthog/temporal/tests/ai/test_anomaly_investigation_summary.pyindex 4ddbbdae4a08..d57205daa23d 100644--- a/posthog/temporal/tests/ai/test_anomaly_investigation_summary.py+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_summary.py@@ -23,3 +23,14 @@ def test_truncate_summary_clips_long_text_with_ellipsis() -> None:assert clipped is not Noneassert len(clipped) == MAX_SUMMARY_CHARSassert clipped.endswith("…")+++def test_truncate_summary_clips_on_sentence_boundary() -> None:+ text = "All systems nominal here. " * 40 # > MAX_SUMMARY_CHARS, sentence ends past the midpoint+ clipped = _truncate_summary(text)+ assert clipped is not None+ # Clips on a full sentence (not mid-word) and always signals truncation with an ellipsis.+ assert clipped.endswith("…")+ body = clipped.removesuffix(" …")+ assert body.endswith(".")+ assert text.startswith(body)