: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): improve slack alert messages (#123533)
Matt Puab55ec32c3be4
diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex b3b96da0c52e..93e5b64b7162 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -1431,90 +1431,137 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, Honame: 'Post to Slack on insight alert firing',description: 'Post to a Slack channel when this insight alert fires',inputs: {- blocks: {+ blocks: { value: [] },+ attachments: {value: [{- type: 'header',- text: {- type: 'plain_text',- text: "Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'",- },- },- {- // 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',- text: '{event.properties.breaches}',- },- },- {- type: 'context',- elements: [{ type: 'mrkdwn', text: 'Project: <{project.url}|{project.name}>' }],- },- // A hog template that is a single {…} expression resolves to the expression's raw- // value, so this string becomes a whole block: a chart of the alerted insight when- // one was rendered (`insight_chart_url`, set for any firing alert by- // dispatch_alert_notification), otherwise the plain divider. Slack has no way to- // omit a block conditionally, and an image block with an empty URL fails the send.- "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}",- {- type: 'actions',- // The alert id in the block_id is what lets the datetimepicker action identify- // its alert — unlike select options, datetimepicker elements carry no value.- block_id: 'insight_alert_snooze:{event.properties.alert_id}',- elements: [+ color: '#D97706',+ fallback:+ "{concat(event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘', event.properties.alert_name, '’ triggered')}",+ blocks: [{- // 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}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack',- text: { text: 'View Insight', type: 'plain_text' },- type: 'button',- },- {- action_id: 'insight_alert_snooze',- placeholder: { text: 'Snooze…', type: 'plain_text' },- options: [+ type: 'rich_text',+ elements: [{- text: { text: 'For 1 hour', type: 'plain_text' },- value: '{event.properties.alert_id}|1h',+ type: 'rich_text_section',+ elements: [+ {+ type: 'text',+ text: "{concat('⚠️ ', event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘')}",+ style: {+ bold: true,+ },+ },+ {+ type: 'link',+ url: '{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}',+ text: '{event.properties.alert_name}',+ style: { bold: true },+ },+ { type: 'text', text: '’ triggered', style: { bold: true } },+ ],},+ ],+ },+ {+ type: 'rich_text',+ elements: [{- text: { text: 'For 6 hours', type: 'plain_text' },- value: '{event.properties.alert_id}|6h',+ type: 'rich_text_section',+ elements: [+ {+ type: 'text',+ text: '📁 Project: ',+ },+ {+ type: 'link',+ url: '{project.url}',+ text: '{project.name}',+ },+ ],},+ ],+ },+ "{event.properties.slack_alert_details ?? {'type': 'section', 'text': {'type': 'plain_text', 'text': substring(event.properties.breaches, 1, 3000)}}}",+ "{event.properties.slack_alert_timing ?? {'type': 'context', 'elements': [{'type': 'plain_text', 'text': event.timestamp}]}}",+ "{event.properties.slack_alert_tags ?? {'type': 'divider'}}",+ ],+ },+ {+ blocks: [+ "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}",+ {+ type: 'actions',+ block_id: 'insight_alert_snooze:{event.properties.alert_id}',+ elements: [{- text: { text: 'For 1 day', type: 'plain_text' },- value: '{event.properties.alert_id}|1d',+ 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',},{- text: { text: 'For 1 week', type: 'plain_text' },- value: '{event.properties.alert_id}|1w',+ 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',},{- text: { text: 'Pick a date & time…', type: 'plain_text' },- value: '{event.properties.alert_id}|custom',+ action_id: 'insight_alert_snooze',+ placeholder: {+ text: 'Snooze…',+ type: 'plain_text',+ },+ options: [+ {+ text: {+ text: 'For 1 hour',+ type: 'plain_text',+ },+ value: '{event.properties.alert_id}|1h',+ },+ {+ text: {+ text: 'For 6 hours',+ type: 'plain_text',+ },+ value: '{event.properties.alert_id}|6h',+ },+ {+ text: {+ text: 'For 1 day',+ type: 'plain_text',+ },+ value: '{event.properties.alert_id}|1d',+ },+ {+ text: {+ text: 'For 1 week',+ type: 'plain_text',+ },+ value: '{event.properties.alert_id}|1w',+ },+ {+ text: {+ text: 'Pick a date & time…',+ type: 'plain_text',+ },+ value: '{event.properties.alert_id}|custom',+ },+ ],+ type: 'static_select',},],- type: 'static_select',},],},],},- text: {- value: 'Alert triggered: {event.properties.insight_name}',- },+ text: { value: '' },},},{diff --git a/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.ts b/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.tsindex 3f3adf689c22..60ca89596cdd 100644--- a/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.ts@@ -61,6 +61,17 @@ describe('slack template', () => {expect(fetchResponse.execResult).toEqual({ channel: 'C0123ABC', ts: '1700000000.000200' })})+ it('preserves separate metadata and chart attachments', async () => {+ const attachments = [+ { color: '#D97706', blocks: [{ type: 'section', text: { type: 'plain_text', text: 'Limit crossed' } }] },+ { blocks: [{ type: 'image', image_url: 'https://example.com/chart.png', alt_text: 'Insight chart' }] },+ ]+ const response = await tester.invoke({ ...commonInputs, text: '', attachments })++ expect(response.error).toBeUndefined()+ expect(bodyOf(response.invocation.queueParameters)).toMatchObject({ attachments, text: '', blocks: [] })+ })+it.each([['a top-level post, reply under that post', {}, '1700000000.000100'],['a thread reply, reply in the same thread', { thread_ts: '1699999999.000000' }, '1699999999.000000'],diff --git a/nodejs/src/cdp/templates/_destinations/slack/slack.template.ts b/nodejs/src/cdp/templates/_destinations/slack/slack.template.tsindex 879b810c1f75..607cab5028c6 100644--- a/nodejs/src/cdp/templates/_destinations/slack/slack.template.ts+++ b/nodejs/src/cdp/templates/_destinations/slack/slack.template.ts@@ -17,6 +17,10 @@ let body := {'text': inputs.text};+if (not empty(inputs.attachments)) {+ body['attachments'] := inputs.attachments;+}+// Slack rejects an empty thread_ts, so only send it when there is one to reply under.if (not empty(inputs.thread_ts)) {body['thread_ts'] := inputs.thread_ts;@@ -52,6 +56,13 @@ if (res.status != 200 or res.body.ok == false) {return {'channel': res.body.channel, 'ts': res.body.ts};`.trim(),inputs_schema: [+ {+ key: 'attachments',+ type: 'json',+ label: 'Attachments',+ description: 'Optional Slack attachments for grouped message content.',+ required: false,+ },{key: 'slack_workspace',type: 'integration',diff --git a/nodejs/tests/fixtures/hog-bytecode/161acb3af6ed424f98f4b452c4b97d4fbbbd9329154fd5d86144b05003b27440.json b/nodejs/tests/fixtures/hog-bytecode/161acb3af6ed424f98f4b452c4b97d4fbbbd9329154fd5d86144b05003b27440.jsonnew file mode 100644index 000000000000..4374e7e5f9ad--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/161acb3af6ed424f98f4b452c4b97d4fbbbd9329154fd5d86144b05003b27440.json@@ -0,0 +1 @@+["_H",1,32,"image",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/5faf67ccf5d0cb4cb9475b3e164a01023fa68b356c2d4b10551c0bbccf879f31.json b/nodejs/tests/fixtures/hog-bytecode/5faf67ccf5d0cb4cb9475b3e164a01023fa68b356c2d4b10551c0bbccf879f31.jsonnew file mode 100644index 000000000000..bfeccae3f460--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/5faf67ccf5d0cb4cb9475b3e164a01023fa68b356c2d4b10551c0bbccf879f31.json@@ -0,0 +1 @@+["_H",1,32,"https://example.com/chart.png",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/63e4808aeffac2445e2af31df3e45b63facd4bbe17f760bd271f3f7311f3d618.json b/nodejs/tests/fixtures/hog-bytecode/63e4808aeffac2445e2af31df3e45b63facd4bbe17f760bd271f3f7311f3d618.jsonnew file mode 100644index 000000000000..1bda75cfb61f--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/63e4808aeffac2445e2af31df3e45b63facd4bbe17f760bd271f3f7311f3d618.json@@ -0,0 +1 @@+["_H",1,32,"plain_text",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/8cbf1d11ae7242e1df90e7c246a90834d109f4716027fe7fcf21f5601f0e19eb.json b/nodejs/tests/fixtures/hog-bytecode/8cbf1d11ae7242e1df90e7c246a90834d109f4716027fe7fcf21f5601f0e19eb.jsonnew file mode 100644index 000000000000..d308ccb94e6b--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/8cbf1d11ae7242e1df90e7c246a90834d109f4716027fe7fcf21f5601f0e19eb.json@@ -0,0 +1 @@+["_H",1,32,"Limit crossed",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/d441f80f85f60c70b965212c0fa59be14ad70d70e69fb9b9db98e29c6c6a4b87.json b/nodejs/tests/fixtures/hog-bytecode/d441f80f85f60c70b965212c0fa59be14ad70d70e69fb9b9db98e29c6c6a4b87.jsonnew file mode 100644index 000000000000..79db5c6b6559--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/d441f80f85f60c70b965212c0fa59be14ad70d70e69fb9b9db98e29c6c6a4b87.json@@ -0,0 +1 @@+["_H",1,32,"#D97706",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/efc87981149c5866ef28ec3c5dbe5c3120533134913c7304b3291a5e33d527cd.json b/nodejs/tests/fixtures/hog-bytecode/efc87981149c5866ef28ec3c5dbe5c3120533134913c7304b3291a5e33d527cd.jsonnew file mode 100644index 000000000000..f7bebeb9fa3f--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/efc87981149c5866ef28ec3c5dbe5c3120533134913c7304b3291a5e33d527cd.json@@ -0,0 +1 @@+["_H",1,32,"Insight chart",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/f9df65fd832aa59d83d6257f167998e513d639e6960ba4991902067516478bd4.json b/nodejs/tests/fixtures/hog-bytecode/f9df65fd832aa59d83d6257f167998e513d639e6960ba4991902067516478bd4.jsonnew file mode 100644index 000000000000..6cf9f46dfffe--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/f9df65fd832aa59d83d6257f167998e513d639e6960ba4991902067516478bd4.json@@ -0,0 +1 @@+["_H",1,32,"channel",32,"channel",32,"inputs",1,2,32,"blocks",32,"blocks",32,"inputs",1,2,32,"text",32,"text",32,"inputs",1,2,42,3,32,"attachments",32,"inputs",1,2,2,"empty",1,5,40,11,36,0,32,"attachments",32,"attachments",32,"inputs",1,2,46,32,"thread_ts",32,"inputs",1,2,2,"empty",1,5,40,11,36,0,32,"thread_ts",32,"thread_ts",32,"inputs",1,2,46,32,"scope",32,"slack_workspace",32,"inputs",1,3,47,3,35,32,"",32," ",32,"",2,"replaceAll",3,36,1,2,"empty",1,32,",",36,1,2,"splitByString",2,32,"chat:write.customize",2,"has",2,4,2,36,2,32,"icon_emoji",32,"inputs",1,2,2,"empty",1,5,3,2,40,11,36,0,32,"icon_emoji",32,"icon_emoji",32,"inputs",1,2,46,36,2,32,"username",32,"inputs",1,2,2,"empty",1,5,3,2,40,11,36,0,32,"username",32,"username",32,"inputs",1,2,46,32,"https://slack.com/api/chat.postMessage",32,"body",36,0,32,"method",32,"POST",32,"headers",32,"Authorization",32,"Bearer ",32,"access_token",32,"slack_workspace",32,"inputs",1,3,2,"concat",2,32,"Content-Type",32,"application/json",42,2,42,3,2,"fetch",2,33,200,36,3,32,"status",45,12,30,36,3,32,"body",45,32,"ok",45,11,4,2,40,21,32,"Failed to post message to Slack: ",36,3,32,"status",45,32,": ",36,3,32,"body",45,2,"concat",4,2,"Error",1,49,32,"channel",36,3,32,"body",45,32,"channel",45,32,"ts",36,3,32,"body",45,32,"ts",45,42,2,38,35,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/fb5d937fa54af493b1161ef38cbceaff8828bca4b8d2b8ed8db3f79e33335a8e.json b/nodejs/tests/fixtures/hog-bytecode/fb5d937fa54af493b1161ef38cbceaff8828bca4b8d2b8ed8db3f79e33335a8e.jsonnew file mode 100644index 000000000000..aefe10578e69--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/fb5d937fa54af493b1161ef38cbceaff8828bca4b8d2b8ed8db3f79e33335a8e.json@@ -0,0 +1 @@+["_H",1,32,"section",38]diff --git a/posthog/slack/markdown.py b/posthog/slack/markdown.pyindex 0315f7a94ac0..6ed852be3d4b 100644--- a/posthog/slack/markdown.py+++ b/posthog/slack/markdown.py@@ -8,6 +8,9 @@ rules its text must hold to are stated once rather than per product.from __future__ import annotationsimport re+from typing import Any++from markdown_it import MarkdownIt# Slack budgets 12,000 characters across every markdown block in one message. A message carries# one, and the headroom covers the blocks around it.@@ -50,3 +53,66 @@ def slack_markdown_block(text: str) -> dict:show and within `SLACK_MARKDOWN_TEXT_MAX_LEN`, because Slack rejects the whole messageotherwise."""return {"type": "markdown", "text": text}+++_INLINE_MARKUP = re.compile(+ r"(?P<link>\[[^\[\]\n]*\]\((?:[^()\s]|\([^)]*\))+\))|"+ r"<u>(?P<underline>[\s\S]+?)</u>|(?P<bold_marker>\*{1,2})(?P<bold>[^*\n]+)(?P=bold_marker)|"+ r"(?<!\w)_(?P<italic>[^_\n]+)_(?!\w)|~(?P<strike>[^~\n]+)~|`(?P<code>[^`\n]+)`"+)+++def _inline_elements(text: str, style: dict[str, bool], allowed_root: str) -> list[dict[str, Any]]:+ # Deferred: markdown_safety pulls in posthog.api.utils, which is too heavy for the django.setup() path.+ from posthog.helpers.markdown_safety import is_allowed_link_url++ elements: list[dict[str, Any]] = []+ cursor = 0+ for match in _INLINE_MARKUP.finditer(text):+ if match.start() > cursor:+ elements.append({"type": "text", "text": text[cursor : match.start()], "style": style})+ if match.group("link") is not None:+ tokens = MarkdownIt("commonmark", {"html": False}).parseInline(match.group("link"))[0].children or []+ destination = next((str(token.attrGet("href")) for token in tokens if token.type == "link_open"), "")+ label = "".join(token.content for token in tokens if token.type in {"text", "code_inline"})+ if is_allowed_link_url(destination, allowed_root):+ elements.append({"type": "link", "url": destination, "text": label, "style": style})+ else:+ elements.append({"type": "text", "text": label, "style": style})+ for name in ("bold", "italic", "underline", "strike", "code"):+ content = match.group(name)+ if content is not None:+ nested_style = {**style, name: True}+ if name == "code":+ elements.append({"type": "text", "text": content, "style": nested_style})+ else:+ elements.extend(_inline_elements(content, nested_style, allowed_root))+ break+ cursor = match.end()+ if cursor < len(text):+ elements.append({"type": "text", "text": text[cursor:], "style": style})+ return elements+++def slack_rich_text(summary: str, *, allowed_root: str) -> dict[str, Any]:+ elements: list[dict[str, Any]] = []+ for line in summary.splitlines():+ line = line.strip()+ if not line:+ if elements and elements[-1]["type"] == "rich_text_list":+ elements.append({"type": "rich_text_section", "elements": [{"type": "text", "text": "\n"}]})+ continue+ bullet = re.match(r"^(?:[•*-]\s+|(\d+)[.)]\s+)(.+)$", line)+ content = line+ if bullet:+ content = bullet.group(2)+ section = {"type": "rich_text_section", "elements": _inline_elements(content, {}, allowed_root)}+ if bullet:+ list_style = "ordered" if bullet.group(1) else "bullet"+ if elements and elements[-1]["type"] == "rich_text_list" and elements[-1]["style"] == list_style:+ elements[-1]["elements"].append(section)+ else:+ elements.append({"type": "rich_text_list", "style": list_style, "elements": [section]})+ else:+ elements.append(section)+ return {"type": "rich_text", "elements": elements}diff --git a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py b/posthog/tasks/alerts/test/test_trends_absolute_alerts.pyindex 27a4348be2c6..b383dc675adb 100644--- a/posthog/tasks/alerts/test/test_trends_absolute_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_absolute_alerts.py@@ -172,6 +172,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (0) is less than lower threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_high_threshold_breached(self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock) -> None:@@ -212,6 +213,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (2) is more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_currency_value_formatted_in_breach(@@ -238,6 +240,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week ($2.00) is more than upper threshold ($1.00)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_no_threshold_breached(self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock) -> None:@@ -351,6 +354,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up - Chrome) for previous week (2) is more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_breakdown_low_threshold_breached(@@ -399,6 +403,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up - Firefox) for previous week (1) is less than lower threshold (2)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_breakdown_no_threshold_breached(@@ -491,6 +496,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for current interval (3) is more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_aggregate_trend_with_breakdown_high_threshold_breached(@@ -539,6 +545,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up - Chrome) for current interval (2) is more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_current_interval_high_threshold_breached(@@ -582,6 +589,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for current week (2) is more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_trend_current_interval_should_not_fallback_to_previous_high_threshold_breached(@@ -710,6 +718,7 @@ class TestTimeSeriesTrendsAbsoluteAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (0) is less than lower threshold (2)"],idempotency_key=ANY,+ extra_properties=ANY,)@patch(diff --git a/posthog/tasks/alerts/test/test_trends_relative_alerts.py b/posthog/tasks/alerts/test/test_trends_relative_alerts.pyindex 5f1f527ccbd9..4428e6c3e9b3 100644--- a/posthog/tasks/alerts/test/test_trends_relative_alerts.py+++ b/posthog/tasks/alerts/test/test_trends_relative_alerts.py@@ -203,6 +203,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (2) increased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_relative_increase_upper_threshold_breached(@@ -378,6 +379,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (-1) increased less than lower threshold (2)"],idempotency_key=ANY,+ extra_properties=ANY,)# check percentage alert@@ -401,6 +403,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (-50.00%) increased less than lower threshold (50.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_relative_increase_lower_threshold_breached_2(@@ -576,6 +579,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (2) decreased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)run_alert_check(percentage_alert["id"])@@ -598,6 +602,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (66.67%) decreased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_relative_decrease_lower_threshold_breached(@@ -677,6 +682,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (1) decreased less than lower threshold (2)"],idempotency_key=ANY,+ extra_properties=ANY,)run_alert_check(percentage_alert["id"])@@ -699,6 +705,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (50.00%) decreased less than lower threshold (80.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_relative_increase_no_threshold_breached(@@ -1004,6 +1011,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (2) increased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,),call(ANY,@@ -1011,6 +1019,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (200.00%) increased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,),])@@ -1132,6 +1141,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Firefox) for previous week (0) increased less than lower threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,),call(ANY,@@ -1139,6 +1149,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Firefox) for previous week (0.00%) increased less than lower threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,),])@@ -1260,6 +1271,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (-2) decreased less than lower threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,),call(ANY,@@ -1267,6 +1279,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (-200.00%) decreased less than lower threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,),])@@ -1389,6 +1402,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (2) decreased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,),call(ANY,@@ -1396,6 +1410,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMix"The insight value (signed_up - Chrome) for previous week (66.67%) decreased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,),])@@ -1696,6 +1711,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for current week (2) increased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)run_alert_check(percentage_alert["id"])@@ -1718,6 +1734,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for current week (200.00%) increased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_current_interval_relative_increase_does_not_fallback_to_previous_interval(@@ -1899,6 +1916,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (2) increased more than upper threshold (1)"],idempotency_key=ANY,+ extra_properties=ANY,)run_alert_check(percentage_alert["id"])@@ -1921,6 +1939,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (inf%) increased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)def test_relative_decrease_when_previous_value_is_0(@@ -2006,6 +2025,7 @@ class TestTimeSeriesTrendsRelativeAlerts(APIBaseTest, ClickhouseDestroyTablesMixANY,["The insight value (signed_up) for previous week (inf%) decreased more than upper threshold (20.00%)"],idempotency_key=ANY,+ extra_properties=ANY,)@patch(diff --git a/posthog/tasks/alerts/test/test_utils.py b/posthog/tasks/alerts/test/test_utils.pyindex 54da670e2b7e..9b3d8fd170e5 100644--- a/posthog/tasks/alerts/test/test_utils.py+++ b/posthog/tasks/alerts/test/test_utils.py@@ -334,8 +334,7 @@ class TestDispatchAlertInsightChart(APIBaseTest):dispatch_alert_notification(self.alert, self.alert_check, ["breach"])mock_prepare.assert_not_called()- # No chart keeps the common threshold-alert call shape (no extra_properties forwarded).- assert "extra_properties" not in mock_send.call_args.kwargs+ assert "insight_chart_url" not in mock_send.call_args.kwargs["extra_properties"]@patch("posthog.tasks.alerts.utils.prepare_alert_insight_chart_url")@patch("posthog.tasks.alerts.utils.send_notifications_for_breaches", return_value=[])diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex 799577da00a6..fe610b849b5a 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -18,12 +18,14 @@ from posthog.ph_client import ph_background_capturefrom posthog.slo.context import get_current_slofrom posthog.slo.types import SloOperationfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction+from posthog.utils import absolute_urifrom products.alerts.backend.facade.api import LLM_DETECTOR_UNAVAILABLE_ERROR_CODEfrom products.alerts.backend.facade.destinations import (ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS,alert_internal_event_delivered,flush_alert_internal_events,+ insight_alert_slack_properties,list_active_alert_destinations,produce_alert_internal_event,serialize_deliveries,@@ -262,7 +264,7 @@ def send_notifications_for_breaches(alert: AlertConfiguration,breaches: list[str],idempotency_key: str,- extra_properties: dict[str, str] | None = None,+ extra_properties: dict[str, Any] | None = None,) -> list[AlertDelivery]:"""A stable idempotency_key (typically alert_check.id) lets MessagingRecord enforceper-recipient at-most-once email delivery on retries.@@ -532,7 +534,7 @@ def dispatch_alert_notification(alert: AlertConfiguration,alert_check: AlertCheck,breaches: list[str] | None,- extra_properties: dict[str, str] | None = None,+ extra_properties: dict[str, Any] | None = None,idempotency_key: str | None = None,render_chart: bool = True,) -> list[AlertDelivery] | None:@@ -618,6 +620,45 @@ def dispatch_alert_notification(**detector_verdict_event_fields(alert_check.triggered_metadata),**(extra_properties or {}),}+ detected_at = (+ alert_check.created_at.astimezone(ZoneInfo(alert.team.timezone)).strftime("%d %b %Y, %H:%M %Z")+ + f" ({alert.team.timezone})"+ )+ insight_query = alert.insight.query or {}+ insight_source = insight_query.get("source") or insight_query+ breach_details = (alert_check.triggered_metadata or {}).get("breach_details") or []+ affected_interval = next(+ (detail["interval"] for detail in breach_details if detail.get("interval")),+ insight_source.get("interval"),+ )+ properties.update(+ insight_alert_slack_properties(+ breaches=breaches,+ breach_details=(alert_check.triggered_metadata or {}).get("breach_details"),+ is_anomaly=bool(alert.detector_config),+ affected_dates=alert_check.triggered_dates+ or [+ detail["date"]+ for detail in (alert_check.triggered_metadata or {}).get("breach_details", [])+ if detail.get("date")+ ],+ affected_interval=affected_interval,+ project_timezone=alert.team.timezone,+ metric_description=properties.get("investigation_metric_description"),+ next_step=properties.get("investigation_next_step"),+ tags=list(+ alert.insight.tagged_items.filter(tag__team_id=alert.team_id)+ .values_list("tag__name", flat=True)+ .order_by("tag__name")[:10]+ ),+ metric_name=alert.insight.name or alert.insight.derived_name or "Insight",+ summary=properties.get("investigation_summary") or alert_check.investigation_summary,+ verdict=properties.get("investigation_verdict") or alert_check.investigation_verdict,+ investigation_status=alert_check.investigation_status,+ detected_at=detected_at,+ allowed_root=absolute_uri("/"),+ )+ )# Attach the chart for any firing alert whose caller did not already supply# one, so ordinary threshold and anomaly alerts get the chart too, not just# the anomaly investigation path (which renders it early and passes it in).diff --git a/products/alerts/backend/destination_backfill.py b/products/alerts/backend/destination_backfill.pyindex fb0d790865ec..6c1a42fb0e8f 100644--- a/products/alerts/backend/destination_backfill.py+++ b/products/alerts/backend/destination_backfill.py@@ -23,9 +23,15 @@ from posthog.dataclasses import frozenfrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workersfrom posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT-from products.alerts.backend.logic.insight_alert_destinations import INSIGHT_CHART_BLOCK, SLACK_TEMPLATE_ID-from products.cdp.backend.facade.models import HogFunction-from products.cdp.backend.validation import generate_template_bytecode+from products.alerts.backend.logic.destination_eligibility import STOCK_INPUT_VALUES+from products.alerts.backend.logic.insight_alert_destinations import (+ INSIGHT_CHART_BLOCK,+ SLACK_TEMPLATE_ID,+ _slack_attachments,+ _slack_blocks,+)+from products.cdp.backend.facade.models import HogFunction, HogFunctionTemplate+from products.cdp.backend.validation import compile_hog, generate_template_bytecodelogger = structlog.get_logger(__name__)@@ -72,13 +78,28 @@ def blocks_with_chart(blocks: Any) -> list[Any] | None:return [*blocks[: actions_index - 1], INSIGHT_CHART_BLOCK, *blocks[actions_index:]]+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"]:+ return None+ return _slack_blocks()++def backfill_insight_alert_chart_blocks(*,team_ids: Sequence[int] | None = None,limit: int | None = None,batch_size: int = 100,apply: bool = False,+ format_messages: bool = False,) -> ChartBlockBackfill:+ template = HogFunctionTemplate.get_template(SLACK_TEMPLATE_ID) if format_messages else None+ known_codes: set[str] = set()+ if format_messages:+ if template is None or not any(item.get("key") == "attachments" for item in template.inputs_schema):+ raise ValueError("Sync Slack templates before updating alert message formatting.")+ known_codes = set(+ HogFunctionTemplate.objects.filter(template_id=SLACK_TEMPLATE_ID).values_list("code", flat=True)+ )destinations = insight_alert_slack_destinations(team_ids)if limit is not None:destinations = destinations[:limit]@@ -93,14 +114,32 @@ def backfill_insight_alert_chart_blocks(blocks_input: dict[str, Any] = raw_blocks_input if isinstance(raw_blocks_input, dict) else {}blocks = blocks_input.get("value")- if mentions_chart(blocks):+ if (+ format_messages+ and template is not None+ and blocks == []+ and ((destination.inputs or {}).get("attachments") or {}).get("value") == _slack_attachments()+ and destination.hog == template.code+ ) or (not format_messages and mentions_chart(destination.inputs)):already_current += 1continue# Liquid blocks are rendered by the worker rather than compiled, so the hog expression the# chart block is written in would reach Slack as literal text.is_hog_templated = blocks_input.get("templating", "hog") == "hog"- upgraded = blocks_with_chart(blocks) if is_hog_templated else None+ upgrade = blocks_with_readable_message if format_messages else blocks_with_chart+ upgraded = upgrade(blocks) if is_hog_templated else None+ if format_messages:+ text_input = (destination.inputs or {}).get("text", {})+ attachments_input = (destination.inputs or {}).get("attachments", {})+ stock_text = (+ isinstance(text_input, dict)+ and text_input.get("templating", "hog") == "hog"+ and text_input.get("value") in [None, "", *STOCK_INPUT_VALUES[SLACK_TEMPLATE_ID]["text"]]+ )+ no_attachments = isinstance(attachments_input, dict) and attachments_input.get("value") in (None, [])+ if destination.hog not in known_codes or not stock_text or not no_attachments:+ upgraded = Noneif upgraded is None:left_alone += 1logger.info(@@ -115,6 +154,9 @@ 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 []+ 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:# Recompiling covers the whole block list, so an edit elsewhere in it that the compiler# now rejects lands here. One destination must not stop the sweep.@@ -130,12 +172,28 @@ def backfill_insight_alert_chart_blocks(**(destination.inputs or {}),"blocks": {**blocks_input, "value": upgraded, "bytecode": bytecode},}+ if format_messages and template is not None:+ destination.inputs["blocks"] = {"value": []}+ destination.inputs["text"] = {"value": ""}+ destination.inputs["attachments"] = {+ "value": attachments,+ "bytecode": attachment_bytecode,+ }+ destination.hog = template.code+ destination.bytecode = sender_bytecode+ destination.inputs_schema = [+ item for item in (destination.inputs_schema or []) if item.get("key") != "attachments"+ ] + [item for item in template.inputs_schema if item.get("key") == "attachments"]repaired.append(destination)ids_by_team.setdefault(destination.team_id, []).append(destination.id)if apply and repaired:with transaction.atomic():- HogFunction.objects.bulk_update(repaired, ["inputs"], batch_size=batch_size)+ HogFunction.objects.bulk_update(+ repaired,+ ["inputs", "hog", "bytecode", "inputs_schema"] if format_messages else ["inputs"],+ batch_size=batch_size,+ )for team_id, hog_function_ids in ids_by_team.items():# bulk_update skips post_save, so the running workers need telling by hand._reload_after_commit(team_id=team_id, hog_function_ids=hog_function_ids)diff --git a/products/alerts/backend/evaluation/comparator.py b/products/alerts/backend/evaluation/comparator.pyindex b3ca68427788..8be11e9a7127 100644--- a/products/alerts/backend/evaluation/comparator.py+++ b/products/alerts/backend/evaluation/comparator.py@@ -11,7 +11,7 @@ from posthog.schema import (from posthog.tasks.alerts.utils import AlertEvaluationResult-from products.alerts.backend.evaluation.contract import ExtractionResult+from products.alerts.backend.evaluation.contract import ComparableSeries, ExtractionResult# Aggregated (any-row) breach lists are capped so a wide violation doesn't flood the notification.# The persisted structured detail uses the same cap.@@ -105,6 +105,50 @@ def _relative_value(return numerator / previous+def _breach_detail(+ result: ExtractionResult,+ series: ComparableSeries,+ condition: AlertCondition,+ threshold: InsightThreshold,+ calculated: float,+) -> dict[str, str]:+ def format_value(value: float, *, change: bool = False) -> str:+ if change and threshold.type == InsightThresholdType.PERCENTAGE:+ return f"{value:.2%}"+ if result.value_formatter is not None:+ return result.value_formatter(value)+ return f"{value:g}{result.unit}"++ current = series.points[series.current_index]+ previous = series.points[series.current_index - 1] if series.current_index > 0 else None+ detail = {"observed": format_value(current.value if current.value is not None else calculated)}+ if result.framed or result.is_breakdown or result.include_series_label:+ detail["group"] = series.label[:400]+ if current.date:+ detail["date"] = current.date+ if result.interval_type:+ detail["interval"] = result.interval_type+ relative = condition.type != AlertConditionType.ABSOLUTE_VALUE+ if previous is not None and previous.value is not None:+ detail["previous"] = format_value(previous.value)+ detail["previous_label"] = "Previous interval"+ if relative:+ if previous.value == 0 and threshold.type == InsightThresholdType.PERCENTAGE:+ detail["change"] = "Not defined from zero"+ else:+ arrow = "▲" if current.value is not None and current.value > previous.value else "▼"+ detail["change"] = f"{arrow} {format_value(abs(calculated), change=True)}"+ if threshold.bounds is not None:+ for side, bound in (("lower", threshold.bounds.lower), ("upper", threshold.bounds.upper)):+ if bound is not None and (+ (side == "lower" and calculated < bound) or (side == "upper" and calculated > bound)+ ):+ detail["limit_label"] = "Change limit" if relative else f"{side.capitalize()} limit"+ detail["limit"] = format_value(bound, change=relative)+ break+ return detail++def evaluate_threshold(result: ExtractionResult,condition: AlertCondition,@@ -126,6 +170,7 @@ def evaluate_threshold(calculated: float | None = Noneall_breaches: list[str] = []breaching_rows: list[dict] = []+ breach_details: list[dict[str, str]] = []first_breach_value: float | None = Nonefor s in result.series:anchor = s.points[s.current_index].value@@ -155,8 +200,13 @@ def evaluate_threshold(value_formatter=result.value_formatter,)if breaches:+ detail = _breach_detail(result, s, condition, threshold, calculated)if not result.aggregate_breaches:- return AlertEvaluationResult(value=calculated, breaches=breaches)+ return AlertEvaluationResult(+ value=calculated, breaches=breaches, triggered_metadata={"breach_details": [detail]}+ )+ if len(breach_details) < MAX_BREACH_MESSAGES:+ breach_details.append(detail)if first_breach_value is None:# Representative value = the first breaching row in result order; the full list# of breaching rows is carried by ``breaches`` and ``triggered_metadata``.@@ -167,6 +217,7 @@ def evaluate_threshold(if all_breaches:capped = all_breaches[:MAX_BREACH_MESSAGES]if len(all_breaches) > MAX_BREACH_MESSAGES:+ breach_details[-1]["other_groups"] = str(len(breaching_rows) - MAX_BREACH_MESSAGES)capped.append(f"...and {len(all_breaches) - MAX_BREACH_MESSAGES} more rows breach")# Persist which rows breached on the check record — notifications are transient, and the# row labels have no other durable source of truth.@@ -175,6 +226,7 @@ def evaluate_threshold(breaches=capped,triggered_metadata={"breaching_rows": breaching_rows[:MAX_BREACH_MESSAGES],+ "breach_details": breach_details,"breaching_row_count": len(breaching_rows),},)diff --git a/products/alerts/backend/evaluation/test/test_comparator.py b/products/alerts/backend/evaluation/test/test_comparator.pyindex 965f8c6bcbe4..cb5c0f26f3eb 100644--- a/products/alerts/backend/evaluation/test/test_comparator.py+++ b/products/alerts/backend/evaluation/test/test_comparator.py@@ -71,6 +71,12 @@ def test_unit_suffix_renders_in_breach_message():assert out.breaches is not None and len(out.breaches) == 1assert "(40.0%)" in out.breaches[0]assert "lower threshold (50.0%)" in out.breaches[0]+ assert out.triggered_metadata is not None+ assert out.triggered_metadata["breach_details"][0] == {+ "observed": "40%",+ "limit_label": "Lower limit",+ "limit": "50%",+ }@pytest.mark.parametrize(@@ -103,6 +109,12 @@ def test_relative_value_computation(]result = evaluate_threshold(_result(series), condition, _threshold(type_=threshold_type, upper=upper))assert result.value == expected_value+ assert result.triggered_metadata is not None+ detail = result.triggered_metadata["breach_details"][0]+ assert detail["observed"] == f"{values[current_index]:g}"+ assert detail["previous"] == f"{values[current_index - 1]:g}"+ if values[current_index - 1] == 0 and threshold_type == InsightThresholdType.PERCENTAGE:+ assert detail["change"] == "Not defined from zero"if expected_message is not None:assert result.breaches is not None and expected_message in result.breaches[0]@@ -203,6 +215,8 @@ def test_framed_message_includes_series_and_interval():result = evaluate_threshold(_result(series, interval_type=IntervalType.DAY), ABSOLUTE, _threshold(lower=10))assert result.breaches is not Noneassert result.breaches[0] == "The insight value (US) for previous day (5.0) is less than lower threshold (10.0)"+ assert result.triggered_metadata is not None+ assert result.triggered_metadata["breach_details"][0]["group"] == "US"def test_unframed_message_uses_subject_without_interval_framing():diff --git a/products/alerts/backend/evaluation/test/test_evaluation_delay.py b/products/alerts/backend/evaluation/test/test_evaluation_delay.pyindex 2e0fa1785354..51e8985515ea 100644--- a/products/alerts/backend/evaluation/test/test_evaluation_delay.py+++ b/products/alerts/backend/evaluation/test/test_evaluation_delay.py@@ -72,8 +72,9 @@ class TestEvaluationDelay(SimpleTestCase):self.assertEqual(result.value, expected)assert result.breaches is not Noneself.assertEqual(bool(result.breaches), fires)+ assert result.triggered_metadata is not Noneself.assertEqual(- result.triggered_metadata,+ {k: v for k, v in result.triggered_metadata.items() if k != "breach_details"},{"evaluation_delay_intervals": 2,"evaluated_interval_start": dates[1],diff --git a/products/alerts/backend/evaluation/test/test_hogql_extractor.py b/products/alerts/backend/evaluation/test/test_hogql_extractor.pyindex 7a222c4fe2f4..28066a776994 100644--- a/products/alerts/backend/evaluation/test/test_hogql_extractor.py+++ b/products/alerts/backend/evaluation/test/test_hogql_extractor.py@@ -325,7 +325,8 @@ def test_any_row_reports_every_breaching_row():"The SQL insight value (BR) (0.5) is more than upper threshold (0.25)",]# Which rows breached is persisted on the check record — notifications are transient.- assert evaluation.triggered_metadata == {+ assert evaluation.triggered_metadata is not None+ assert {key: evaluation.triggered_metadata[key] for key in ("breaching_rows", "breaching_row_count")} == {"breaching_rows": [{"label": "DE", "value": 0.4},{"label": "FR", "value": 0.3},diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pyindex 18000086eda0..e83d4e00b848 100644--- a/products/alerts/backend/facade/destinations.py+++ b/products/alerts/backend/facade/destinations.py@@ -37,6 +37,7 @@ from ..logic import (destination_eligibility,destinations,insight_alert_destinations,+ insight_alert_message,)from .contracts import (AlertEmailRecipientResolver,@@ -111,6 +112,43 @@ def build_insight_alert_slack_config()+def insight_alert_slack_properties(+ *,+ breaches: list[str],+ metric_name: str,+ is_anomaly: bool = False,+ tags: list[str] | None = None,+ breach_details: list[dict[str, str]] | None = None,+ affected_dates: list[str] | None = None,+ affected_interval: str | None = None,+ project_timezone: str = "UTC",+ metric_description: str | None = None,+ next_step: str | None = None,+ summary: str | None,+ verdict: str | None,+ investigation_status: str | None,+ detected_at: str,+ allowed_root: str,+) -> dict[str, Any]:+ return insight_alert_message.insight_alert_slack_properties(+ breaches=breaches,+ metric_name=metric_name,+ is_anomaly=is_anomaly,+ tags=tags,+ breach_details=breach_details,+ affected_dates=affected_dates,+ affected_interval=affected_interval,+ project_timezone=project_timezone,+ metric_description=metric_description,+ next_step=next_step,+ summary=summary,+ verdict=verdict,+ investigation_status=investigation_status,+ detected_at=detected_at,+ allowed_root=allowed_root,+ )++def create_alert_destination_hog_functions(configs: list[AlertDestinationConfig],*,diff --git a/products/alerts/backend/logic/destination_stock_inputs.json b/products/alerts/backend/logic/destination_stock_inputs.jsonindex 48a9f1f77758..68f21583a34e 100644--- a/products/alerts/backend/logic/destination_stock_inputs.json+++ b/products/alerts/backend/logic/destination_stock_inputs.json@@ -825,7 +825,8 @@}]}- ]+ ],+ []],"body": [{@@ -866,7 +867,143 @@"*{person.name}* triggered event: '{event.event}'","Alert triggered: {event.properties.insight_name}"],- "username": ["PostHog"]+ "username": ["PostHog"],+ "attachments": [+ [+ {+ "color": "#D97706",+ "fallback": "{concat(event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘', event.properties.alert_name, '’ triggered')}",+ "blocks": [+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {+ "type": "text",+ "text": "{concat('⚠️ ', event.properties.slack_alert_type == 'Anomaly detected' ? 'Anomaly alert' : 'Insight alert', ' ‘')}",+ "style": {+ "bold": true+ }+ },+ {+ "type": "link",+ "url": "{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}",+ "text": "{event.properties.alert_name}",+ "style": {+ "bold": true+ }+ },+ {+ "type": "text",+ "text": "’ triggered",+ "style": {+ "bold": true+ }+ }+ ]+ }+ ]+ },+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {+ "type": "text",+ "text": "📁 Project: "+ },+ {+ "type": "link",+ "url": "{project.url}",+ "text": "{project.name}"+ }+ ]+ }+ ]+ },+ "{event.properties.slack_alert_details ?? {'type': 'section', 'text': {'type': 'plain_text', 'text': substring(event.properties.breaches, 1, 3000)}}}",+ "{event.properties.slack_alert_timing ?? {'type': 'context', 'elements': [{'type': 'plain_text', 'text': event.timestamp}]}}",+ "{event.properties.slack_alert_tags ?? {'type': 'divider'}}"+ ]+ },+ {+ "blocks": [+ "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}",+ {+ "type": "actions",+ "block_id": "insight_alert_snooze:{event.properties.alert_id}",+ "elements": [+ {+ "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}?utm_source=alert&utm_campaign=alert_check_firing&utm_medium=slack",+ "text": {+ "text": "📊 View insight",+ "type": "plain_text"+ },+ "type": "button"+ },+ {+ "action_id": "insight_alert_snooze",+ "placeholder": {+ "text": "Snooze…",+ "type": "plain_text"+ },+ "options": [+ {+ "text": {+ "text": "For 1 hour",+ "type": "plain_text"+ },+ "value": "{event.properties.alert_id}|1h"+ },+ {+ "text": {+ "text": "For 6 hours",+ "type": "plain_text"+ },+ "value": "{event.properties.alert_id}|6h"+ },+ {+ "text": {+ "text": "For 1 day",+ "type": "plain_text"+ },+ "value": "{event.properties.alert_id}|1d"+ },+ {+ "text": {+ "text": "For 1 week",+ "type": "plain_text"+ },+ "value": "{event.properties.alert_id}|1w"+ },+ {+ "text": {+ "text": "Pick a date & time…",+ "type": "plain_text"+ },+ "value": "{event.properties.alert_id}|custom"+ }+ ],+ "type": "static_select"+ }+ ]+ }+ ]+ }+ ]+ ]},"template-webhook": {"body": [diff --git a/products/alerts/backend/logic/insight_alert_destinations.py b/products/alerts/backend/logic/insight_alert_destinations.pyindex 693d2ab157ca..4519d33b26f0 100644--- a/products/alerts/backend/logic/insight_alert_destinations.py+++ b/products/alerts/backend/logic/insight_alert_destinations.py@@ -64,48 +64,99 @@ def snooze_select(alert_id: str) -> dict[str, Any]:}-def _slack_blocks() -> list[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",+) -> list[Any]:return [- {- "type": "header",- "text": {- "type": "plain_text",- "text": "Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'",- },- },- {- # 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", "text": "{event.properties.breaches}"},- },- {- "type": "context",- "elements": [{"type": "mrkdwn", "text": "Project: <{project.url}|{project.name}>"}],- },- INSIGHT_CHART_BLOCK,+ chart,{"type": "actions",# 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": "insight_alert_snooze:{event.properties.alert_id}",+ "block_id": f"insight_alert_snooze:{alert_id}","elements": [{- "url": _PRIMARY_BUTTON_URL,+ "url": primary_url,"text": {- "text": "{event.properties.investigation_notebook_url ? 'View Investigation' : 'View Alert'}",+ "text": primary_label,"type": "plain_text",},"type": "button",},{- "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"},+ "url": insight_url,+ "text": {"text": "📊 View insight", "type": "plain_text"},"type": "button",},- snooze_select("{event.properties.alert_id}"),+ snooze_select(alert_id),+ ],+ },+ ]+++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,+) -> list[Any]:+ return [+ {+ "color": "#D97706",+ "fallback": fallback,+ "blocks": [+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {+ "type": "text",+ "text": heading_prefix,+ "style": {"bold": True},+ },+ {+ "type": "link",+ "url": alert_url,+ "text": alert_name,+ "style": {"bold": True},+ },+ {"type": "text", "text": "’ triggered", "style": {"bold": True}},+ ],+ }+ ],+ },+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {"type": "text", "text": "📁 Project: "},+ {"type": "link", "url": project_url, "text": project_name},+ ],+ }+ ],+ },+ details,+ timing,+ tags,],},+ {"blocks": _slack_blocks() if blocks is None else blocks},]@@ -121,8 +172,9 @@ def build_insight_alert_slack_config("name": clip_hog_function_name(f"{alert_name or 'Alert'}: Slack #{channel_name}"),"template_id": SLACK_TEMPLATE_ID,"inputs": {- "blocks": {"value": _slack_blocks()},- "text": {"value": "Alert triggered: {event.properties.insight_name}"},+ "blocks": {"value": []},+ "attachments": {"value": _slack_attachments()},+ "text": {"value": ""},"slack_workspace": {"value": data["slack_workspace_id"]},"channel": {"value": data["slack_channel_id"]},},diff --git a/products/alerts/backend/logic/insight_alert_message.py b/products/alerts/backend/logic/insight_alert_message.pynew file mode 100644index 000000000000..2065aafb0033--- /dev/null+++ b/products/alerts/backend/logic/insight_alert_message.py@@ -0,0 +1,271 @@+from __future__ import annotations++import re+from datetime import UTC, datetime+from typing import Any+from zoneinfo import ZoneInfo++from dateutil.relativedelta import relativedelta++from posthog.slack.formatting import escape_slack_mrkdwn+from posthog.slack.markdown import slack_rich_text++_VERDICTS = {+ "true_positive": "Unusual change confirmed",+ "false_positive": "Expected behavior",+ "inconclusive": "Investigation inconclusive",+}+_TIME_OR_VALUE = re.compile(+ r"(?P<time>\b\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?\b|\b\d{1,2}:\d{2}(?::\d{2})?\b)"+ r"|(?P<value>(?<![\w])[-+~]?\d+(?:[.,]\d+)*(?:\s?(?:ms|seconds?|minutes?|hours?|days?|%|s))?(?!\w))"+)+++def _breach_elements(text: str, metric_name: str) -> list[dict[str, Any]]:+ pattern = _TIME_OR_VALUE+ if metric_name:+ pattern = re.compile(f"(?P<metric>{re.escape(metric_name)})|{_TIME_OR_VALUE.pattern}")+ elements: list[dict[str, Any]] = []+ cursor = 0+ for match in pattern.finditer(text):+ if match.start() > cursor:+ elements.append({"type": "text", "text": text[cursor : match.start()]})+ style = {"code": True}+ if match.lastgroup == "time":+ style = {"italic": True}+ elements.append({"type": "text", "text": match.group(), "style": style})+ cursor = match.end()+ if cursor < len(text):+ elements.append({"type": "text", "text": text[cursor:]})+ return elements+++_INTERVAL_DELTAS = {+ "second": relativedelta(seconds=1),+ "minute": relativedelta(minutes=1),+ "hour": relativedelta(hours=1),+ "day": relativedelta(days=1),+ "week": relativedelta(weeks=1),+ "month": relativedelta(months=1),+ "quarter": relativedelta(months=3),+ "year": relativedelta(years=1),+}+++def _affected_period(dates: list[str], project_timezone: str, interval: str | None) -> str:+ labels: list[str] = []+ endpoints = [dates[0], dates[-1]]+ delta = _INTERVAL_DELTAS.get(interval or "")+ if delta is not None:+ try:+ end = datetime.fromisoformat(dates[-1])+ if end.tzinfo is None and interval in {"second", "minute", "hour"}:+ end = end.replace(tzinfo=ZoneInfo(project_timezone))+ if end.tzinfo is not None:+ end = end.astimezone(ZoneInfo(project_timezone))+ if interval in {"second", "minute", "hour"} and end.tzinfo is not None:+ end = end.astimezone(UTC) + delta+ else:+ end += delta+ endpoints[-1] = end.isoformat()+ except ValueError:+ pass+ timezone = ZoneInfo(project_timezone)+ offsets = set()+ for value in endpoints:+ try:+ point = datetime.fromisoformat(value)+ except ValueError:+ continue+ if point.tzinfo is not None:+ offsets.add(point.astimezone(timezone).utcoffset())+ show_zone = len(offsets) > 1+ for value in dict.fromkeys(endpoints):+ try:+ point = datetime.fromisoformat(value)+ except ValueError:+ labels.append(value[:100])+ continue+ if point.tzinfo is not None:+ point = point.astimezone(ZoneInfo(project_timezone))+ label = point.strftime("%d %b %Y")+ if len(value) > 10:+ time_format = "%d %b %Y, %H:%M:%S" if interval == "second" else "%d %b %Y, %H:%M"+ if show_zone:+ time_format += " %Z"+ label = point.strftime(time_format)+ labels.append(label)+ return " to ".join(labels) + f" ({project_timezone})"+++def insight_alert_slack_properties(+ *,+ breaches: list[str],+ metric_name: str,+ is_anomaly: bool = False,+ tags: list[str] | None = None,+ breach_details: list[dict[str, str]] | None = None,+ affected_dates: list[str] | None = None,+ affected_interval: str | None = None,+ project_timezone: str = "UTC",+ metric_description: str | None = None,+ next_step: str | None = None,+ summary: str | None,+ verdict: str | None,+ investigation_status: str | None,+ detected_at: str,+ allowed_root: str,+) -> dict[str, Any]:+ investigation = _VERDICTS.get(verdict or "", "")+ if investigation_status in {"pending", "running"}:+ investigation = "In progress"+ elif investigation_status == "failed":+ investigation = "Incomplete"+ content: dict[str, Any]+ if breach_details and not summary:+ sections: list[dict[str, Any]] = []+ for detail in breach_details[:5]:+ elements: list[dict[str, Any]] = []+ if detail.get("group"):+ elements.extend(+ [+ {"type": "text", "text": detail["group"][:400], "style": {"code": True}},+ {"type": "text", "text": ": "},+ ]+ )+ elements.extend(+ [+ {"type": "text", "text": "Reached "},+ {"type": "text", "text": detail["observed"][:400], "style": {"code": True}},+ ]+ )+ if detail.get("limit"):+ label = detail.get("limit_label", "Limit").lower()+ if detail.get("change"):+ elements.extend(+ [+ {"type": "text", "text": " ("},+ {"type": "text", "text": detail["change"][:400], "style": {"code": True}},+ {"type": "text", "text": "), beyond the change limit of "},+ ]+ )+ else:+ elements.append({"type": "text", "text": ", beyond the " + label + " of "})+ elements.append({"type": "text", "text": detail["limit"][:400], "style": {"code": True}})+ elements.append({"type": "text", "text": "."})+ if detail.get("previous"):+ elements.extend(+ [+ {"type": "text", "text": "\nPrevious interval: "},+ {"type": "text", "text": detail["previous"][:400], "style": {"code": True}},+ {"type": "text", "text": "."},+ ]+ )+ sections.append({"type": "rich_text_section", "elements": elements})+ if detail.get("other_groups"):+ sections.append(+ {+ "type": "rich_text_section",+ "elements": [+ {+ "type": "text",+ "text": f"{detail['other_groups']} more affected groups. Open the insight for details.",+ }+ ],+ }+ )+ content = {"type": "rich_text", "elements": sections}+ elif summary and summary.strip():+ if len(summary) > 2800:+ summary = summary[:2797] + "..."+ content = slack_rich_text(summary, allowed_root=allowed_root)+ else:+ sections = []+ budget = 2600+ for breach in breaches:+ if not breach.strip():+ continue+ if budget < 100 or len(sections) == 10:+ break+ text = breach+ if len(text) > budget:+ text = text[: budget - 3] + "..."+ sections.append({"type": "rich_text_section", "elements": _breach_elements(text, metric_name)})+ budget -= len(text)+ if not sections:+ sections.append(+ {+ "type": "rich_text_section",+ "elements": [{"type": "text", "text": "Alert fired. Open the insight for details."}],+ }+ )+ content = {+ "type": "rich_text",+ "elements": [{"type": "rich_text_list", "style": "bullet", "elements": sections}],+ }+ omitted = max(0, sum(bool(breach.strip()) for breach in breaches) - len(sections))+ if omitted:+ content["elements"].append(+ {+ "type": "rich_text_section",+ "elements": [{"type": "text", "text": f"{omitted} more breaches. Open the insight for details."}],+ }+ )+ timing: dict[str, Any] = {"type": "divider"}+ if affected_dates:+ label = "📅 Affected period" if affected_interval in _INTERVAL_DELTAS else "📅 Affected data points"+ period = escape_slack_mrkdwn(_affected_period(affected_dates, project_timezone, affected_interval))+ timing = {"type": "section", "text": {"type": "mrkdwn", "text": f"*{label}*\n_{period}_"}}+ child_blocks: list[dict[str, Any]] = []+ if metric_description:+ child_blocks.append(+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {"type": "text", "text": "Measures: ", "style": {"bold": True}},+ {"type": "text", "text": metric_description[:400]},+ ],+ }+ ],+ }+ )+ child_blocks.append(content)+ if investigation:+ child_blocks.append(+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_section",+ "elements": [+ {"type": "text", "text": "Investigation: ", "style": {"bold": True}},+ {"type": "text", "text": investigation},+ ],+ }+ ],+ }+ )+ if next_step:+ child_blocks.append(slack_rich_text("**Next check:** " + next_step[:500], allowed_root=allowed_root))+ tag_elements: list[dict[str, Any]] = [{"type": "text", "text": "Insight tags: ", "style": {"bold": True}}]+ for tag in (tags or [])[:10]:+ if len(tag_elements) > 1:+ tag_elements.append({"type": "text", "text": " "})+ tag_elements.append({"type": "text", "text": tag[:255], "style": {"code": True}})+ tag_block: dict[str, Any] = {"type": "divider"}+ if tags:+ tag_block = {"type": "rich_text", "elements": [{"type": "rich_text_section", "elements": tag_elements}]}+ return {+ "slack_alert_tags": tag_block,+ "slack_alert_type": "Anomaly detected" if is_anomaly else "Limit crossed",+ "slack_alert_status": "Triggered",+ "slack_alert_timing": timing,+ "slack_alert_detected_at": detected_at,+ "slack_alert_details": {+ "type": "rich_text",+ "elements": [element for block in child_blocks for element in block["elements"]],+ },+ }diff --git a/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.py b/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.pyindex 448e69c0c189..b9e832dbbd96 100644--- a/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.py+++ b/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.py@@ -25,6 +25,9 @@ class Command(BaseCommand):parser.add_argument("--team-ids", type=str, default=None, help="Comma-separated team ids to limit to")parser.add_argument("--limit", type=int, default=None, help="Look at no more than this many destinations")parser.add_argument("--batch-size", type=int, default=100, help="Rows per UPDATE (default: 100)")+ parser.add_argument(+ "--format-messages", action="store_true", help="Upgrade unchanged stock messages to the formatted layout"+ )parser.add_argument("--apply", action="store_true", default=False, help="Write them (default: report only)")def handle(self, *args: Any, **options: Any) -> None:@@ -34,6 +37,7 @@ class Command(BaseCommand):limit=options["limit"],batch_size=options["batch_size"],apply=apply,+ format_messages=options["format_messages"],)counts = [diff --git a/products/alerts/backend/test/test_destination_backfill.py b/products/alerts/backend/test/test_destination_backfill.pyindex 9c5fc7e6ea08..984201d2acc3 100644--- a/products/alerts/backend/test/test_destination_backfill.py+++ b/products/alerts/backend/test/test_destination_backfill.py@@ -1,7 +1,10 @@+from copy import deepcopy+from types import SimpleNamespacefrom typing import Anyfrom uuid import uuid4from posthog.test.base import BaseTest+from unittest.mock import patchfrom django.test import SimpleTestCase@@ -14,6 +17,7 @@ from products.alerts.backend.destination_backfill import (backfill_insight_alert_chart_blocks,blocks_with_chart,)+from products.alerts.backend.logic.destination_eligibility import STOCK_INPUT_VALUESfrom products.cdp.backend.facade.models import HogFunctionHEADER_BLOCK = {"type": "header", "text": {"type": "plain_text", "text": "Alert firing"}}@@ -208,3 +212,42 @@ class TestBackfillInsightAlertChartBlocks(BaseTest):assert (result.scanned, result.repaired) == (1, 1)assert self._stored_blocks(mine)["value"][2] == INSIGHT_CHART_BLOCKassert self._stored_blocks(theirs)["value"] == PRE_CHART_BLOCKS+++class TestReadableMessageBackfill(SimpleTestCase):+ @parameterized.expand(+ [+ ("stock", {}, True),+ ("custom_text", {"text": {"value": "A custom message"}}, False),+ ("custom_attachments", {"attachments": {"value": [{"text": "Custom content"}]}}, False),+ ("liquid_text", {"text": {"value": "", "templating": "liquid"}}, False),+ ]+ )+ def test_upgrade_preserves_custom_message_inputs(+ self, _name: str, overrides: dict[str, Any], repaired: bool+ ) -> None:+ template = SimpleNamespace(code="return null;", inputs_schema=[{"key": "attachments", "type": "json"}])+ inputs = {+ "blocks": {"value": STOCK_INPUT_VALUES["template-slack"]["blocks"][0]},+ "text": {"value": ""},+ **overrides,+ }+ original = deepcopy(inputs)+ destination = SimpleNamespace(+ inputs=inputs, hog=template.code, type="internal_destination", team_id=1, id=uuid4(), inputs_schema=[]+ )+ with (+ patch(+ "products.alerts.backend.destination_backfill.insight_alert_slack_destinations",+ return_value=[destination],+ ),+ patch(+ "products.alerts.backend.destination_backfill.HogFunctionTemplate.get_template", return_value=template+ ),+ patch("products.alerts.backend.destination_backfill.HogFunctionTemplate.objects.filter") as versions,+ ):+ versions.return_value.values_list.return_value = [template.code]+ result = backfill_insight_alert_chart_blocks(format_messages=True)+ assert result.repaired == int(repaired)+ if not repaired:+ assert destination.inputs == originaldiff --git a/products/alerts/backend/test/test_destination_eligibility.py b/products/alerts/backend/test/test_destination_eligibility.pyindex 7de9291cfc38..7dcdbe9ced70 100644--- a/products/alerts/backend/test/test_destination_eligibility.py+++ b/products/alerts/backend/test/test_destination_eligibility.py@@ -21,6 +21,7 @@ from products.alerts.backend.facade.destinations import (unbound_alert_destinations,)from products.alerts.backend.logic.destination_bucket_report import bucketed_destinations+from products.alerts.backend.logic.destination_eligibility import STOCK_INPUT_VALUESfrom products.alerts.backend.logic.insight_alert_destinations import build_insight_alert_slack_configfrom products.alerts_platform.backend.facade.contracts import AlertDestinationData, DestinationTypefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction@@ -356,7 +357,14 @@ class TestDestinationEligibility(APIBaseTest):@parameterized.expand([- ("stock_blocks", {}, None, ()),+ ("stock_message", {}, None, ()),+ ("custom_attachments", {"attachments": [{"text": "Custom message"}]}, None, (DestinationHoldBack.MESSAGE,)),+ (+ "legacy_stock_blocks",+ {"blocks": STOCK_INPUT_VALUES["template-slack"]["blocks"][0]},+ None,+ (),+ ),("text_edited_before_the_first_save", {"text": "Look at this"}, {}, (DestinationHoldBack.MESSAGE,)),("text_edited_with_no_revision", {"text": "Look at this"}, None, (DestinationHoldBack.MESSAGE,)),("an_emptied_text", {"text": ""}, None, ()),diff --git a/products/alerts/backend/test/test_insight_alert_message.py b/products/alerts/backend/test/test_insight_alert_message.pynew file mode 100644index 000000000000..b3fa3f7744bc--- /dev/null+++ b/products/alerts/backend/test/test_insight_alert_message.py@@ -0,0 +1,113 @@+import json+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized++from products.alerts.backend.logic.insight_alert_destinations import _slack_attachments+from products.alerts.backend.logic.insight_alert_message import insight_alert_slack_properties+from products.cdp.backend.validation import generate_template_bytecode++from common.hogvm.python.execute import execute_bytecode+++class TestInsightAlertMessage(SimpleTestCase):+ def _properties(self, **overrides: Any) -> dict[str, Any]:+ return insight_alert_slack_properties(+ **{+ "breaches": ["Request time reached 240 ms, above 200 ms."],+ "metric_name": "Request time",+ "summary": None,+ "verdict": None,+ "investigation_status": None,+ "detected_at": "23 Oct 2026, 10:00 UTC",+ "allowed_root": "https://example.com/",+ **overrides,+ }+ )++ def test_compiled_message_preserves_controls(self) -> None:+ properties = self._properties(+ affected_dates=["2026-10-23T14:00:00+00:00"],+ project_timezone="America/Toronto",+ affected_interval="hour",+ )+ properties.update(+ {+ "alert_name": "Response time",+ "alert_id": "sample-alert",+ "insight_id": "sample01",+ "insight_name": "Request time",+ "breaches": "Request time reached 240 ms.",+ }+ )+ globals_ = {+ "event": {"properties": properties, "timestamp": "2026-10-23T10:00:00Z"},+ "project": {"url": "https://example.com/project/1", "name": "Example project"},+ }++ def render(value: Any) -> Any:+ if isinstance(value, list):+ if value and value[0] == "_H":+ return execute_bytecode(value, globals=globals_).result+ return [render(item) for item in value]+ if isinstance(value, dict):+ return {key: render(item) for key, item in value.items()}+ return value++ blocks = render(generate_template_bytecode(_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"+ assert len(blocks[-1]["blocks"][-1]["elements"][-1]["options"]) == 5++ def test_untrusted_breach_names_stay_literal(self) -> None:+ message = self._properties(breaches=["<!channel> [click](https://untrusted.example) reached 240 ms."])+ content = message["slack_alert_details"]+ elements = content["elements"][0]["elements"][0]["elements"]+ assert all(element["type"] == "text" for element in elements)+ assert any(element["text"] == "240 ms" and element.get("style", {}).get("code") for element in elements)++ def test_summary_keeps_emphasis_and_blocks_external_links(self) -> None:+ message = self._properties(+ summary="- **Request time** reached **240 ms** at _10:00 UTC_.\n- [Report](https://untrusted.example/report)"+ )+ content = message["slack_alert_details"]+ elements = content["elements"][0]["elements"][0]["elements"]+ assert any(element.get("style", {}).get("bold") for element in elements)+ assert any(element.get("style", {}).get("italic") for element in elements)+ assert '"type": "link"' not in json.dumps(content)++ def test_grouped_summary_preserves_groups_and_next_step(self) -> None:+ details = [+ {"group": f"Region {index}", "observed": "240 ms", "limit": "200 ms", "previous": "100 ms"}+ for index in range(5)+ ]+ details[-1]["other_groups"] = "3"+ message = self._properties(+ breach_details=details,+ metric_description="Request time by region.",+ verdict="true_positive",+ next_step="Compare the regions in the insight.",+ )+ blocks = message["slack_alert_details"]["elements"]+ assert all(f"Region {index}" in json.dumps(blocks) for index in range(5))+ assert "3 more affected groups" in json.dumps(blocks)+ assert "Unusual change confirmed" in json.dumps(blocks)+ assert "Compare the regions" in json.dumps(blocks)++ @parameterized.expand(+ [+ ("fall_back", "2026-11-01T05:00:00+00:00", "01:00 EDT", "01:00 EST"),+ ("spring_forward", "2026-03-08T06:00:00+00:00", "01:00 EST", "03:00 EDT"),+ ("spring_forward_naive", "2026-03-08 01:00:00", "01:00", "03:00"),+ ]+ )+ def test_period_distinguishes_daylight_saving_offsets(self, _name: str, start: str, first: str, last: str) -> None:+ properties = self._properties(+ affected_dates=[start], affected_interval="hour", project_timezone="America/Toronto"+ )+ timing = properties["slack_alert_timing"]["text"]["text"]+ assert first in timing+ assert last in timingdiff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex aa1ee62d20f5..d8d17299e423 100644--- a/products/alerts/backend/tests/api/test_alert.py+++ b/products/alerts/backend/tests/api/test_alert.py@@ -2876,7 +2876,12 @@ class TestAlertDestinations(APIBaseTest):{"key": "alert_id", "value": str(self.alert.id), "operator": "exact", "type": "event"}]# The Slack snooze handler finds its alert through these two ids.- actions = next(block for block in (hog_function.inputs or {})["blocks"]["value"] if _is_actions_block(block))+ attachment_blocks = [+ block+ for attachment in (hog_function.inputs or {})["attachments"]["value"]+ for block in attachment["blocks"]+ ]+ actions = next(block for block in attachment_blocks if _is_actions_block(block))assert actions["block_id"] == "insight_alert_snooze:{event.properties.alert_id}"assert any(element.get("action_id") == "insight_alert_snooze" for element in actions["elements"])diff --git a/products/cdp/backend/facade/models.py b/products/cdp/backend/facade/models.pyindex 826f0f3cf70e..9c242d6dc1f2 100644--- a/products/cdp/backend/facade/models.py+++ b/products/cdp/backend/facade/models.py@@ -4,6 +4,7 @@ Model-class wiring for cdp.Re-exports the HogFunction model surface cross-product consumers dispatch on. Light."""+from products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState, HogFunctionType-__all__ = ["HogFunction", "HogFunctionState", "HogFunctionType"]+__all__ = ["HogFunction", "HogFunctionState", "HogFunctionType", "HogFunctionTemplate"]diff --git a/products/cdp/backend/templates/fixtures.py b/products/cdp/backend/templates/fixtures.pyindex cb94b48d4307..58dc42b035e1 100644--- a/products/cdp/backend/templates/fixtures.py+++ b/products/cdp/backend/templates/fixtures.py@@ -60,6 +60,14 @@ if (res.status != 200 or res.body.ok == false) {"required": False,"hidden": False,},+ {+ "key": "attachments",+ "type": "json",+ "label": "Attachments",+ "secret": False,+ "required": False,+ "hidden": False,+ },{"key": "text","type": "string",diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex db10839e2a44..3ba7d904dca6 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -5842,7 +5842,9 @@ def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:return HttpResponse(status=200)-def _replace_message_stripping_actions(payload: dict, text: str, *, keep_link_buttons: bool = True) -> None:+def _replace_message_stripping_actions(+ payload: dict, text: str, *, keep_link_buttons: bool = True, process_attachments: bool = False+) -> None:"""Best-effort: replace the original message's interactive buttons with a context line.When keep_link_buttons is True, link buttons (elements with a "url" key, e.g. "View in@@ -5853,18 +5855,28 @@ def _replace_message_stripping_actions(payload: dict, text: str, *, keep_link_bureturnoriginal_message = payload.get("message", {})- kept_blocks = []- for block in original_message.get("blocks", []):- if block.get("type") != "actions":- kept_blocks.append(block)- continue- if keep_link_buttons:- kept_elements = [el for el in block.get("elements", []) if "url" in el]- if kept_elements:- kept_blocks.append({**block, "elements": kept_elements})- kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})- inbox_interactivity.post_response_url(response_url, {"replace_original": True, "text": text, "blocks": kept_blocks})+ def without_actions(blocks: list[dict]) -> list[dict]:+ kept_blocks = []+ for block in blocks:+ if block.get("type") != "actions":+ kept_blocks.append(block)+ continue+ if keep_link_buttons:+ kept_elements = [el for el in block.get("elements", []) if "url" in el]+ if kept_elements:+ kept_blocks.append({**block, "elements": kept_elements})+ return kept_blocks++ kept_blocks = without_actions(original_message.get("blocks", []))+ kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})+ response: dict = {"replace_original": True, "text": text, "blocks": kept_blocks}+ if process_attachments and original_message.get("attachments"):+ response["attachments"] = [+ {**attachment, "blocks": without_actions(attachment.get("blocks", []))}+ for attachment in original_message["attachments"]+ ]+ inbox_interactivity.post_response_url(response_url, response)def _post_signals_dismiss_feedback(payload: dict, *, dismissed: bool, slack_user_id: str) -> None:@@ -6051,7 +6063,9 @@ def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:return HttpResponse(status=200)if outcome == "disabled":logger.info("insight_alert_snooze_alert_disabled", alert_id=str(alert_uuid))- _replace_message_stripping_actions(payload, "This alert is disabled, so there is nothing to snooze.")+ _replace_message_stripping_actions(+ payload, "This alert is disabled, so there is nothing to snooze.", process_attachments=True+ )return HttpResponse(status=200)if outcome == "not_snoozable":logger.warning("insight_alert_snooze_refused_by_platform", alert_id=str(alert_uuid))@@ -6083,7 +6097,7 @@ def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:assert until is not Nonesnoozed_wording = f"until {until.strftime('%Y-%m-%d %H:%M')} UTC"actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"- _replace_message_stripping_actions(payload, f"😴 Snoozed {snoozed_wording} by {actor}")+ _replace_message_stripping_actions(payload, f"😴 Snoozed {snoozed_wording} by {actor}", process_attachments=True)return HttpResponse(status=200)diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.pyindex d6dd6efaed6f..6dc25750dec4 100644--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py@@ -30,6 +30,7 @@ from products.slack_app.backend.api import (_extract_alert_snooze_hints,_handle_insight_alert_snooze,_handle_insight_alert_snooze_modal_submit,+ _replace_message_stripping_actions,)from products.slack_app.backend.tests.helpers import sign_slack_request@@ -1166,3 +1167,37 @@ class TestInsightAlertSnoozeModal(TestCase):assert self.alert.state == AlertState.FIRINGassert self.alert.snoozed_until is Nonemock_slack.return_value.client.chat_postMessage.assert_not_called()+++class TestMessageActionReplacement(SimpleTestCase):+ @parameterized.expand([(False,), (True,)])+ @patch("products.slack_app.backend.api.inbox_interactivity.post_response_url")+ def test_attachment_controls_require_explicit_opt_in(+ self, process_attachments: bool, post_response: MagicMock+ ) -> None:+ link = {"type": "button", "url": "https://example.com", "text": {"type": "plain_text", "text": "View"}}+ control = {"type": "button", "action_id": "sample_action", "text": {"type": "plain_text", "text": "Act"}}+ image = {"type": "image", "image_url": "https://example.com/chart.png", "alt_text": "Sample chart"}+ payload: dict[str, Any] = {+ "response_url": "https://example.com/response",+ "message": {+ "blocks": [{"type": "actions", "elements": [link, control]}],+ "attachments": [+ {"color": "#D97706", "blocks": [image, {"type": "actions", "elements": [link, control]}]}+ ],+ },+ }++ options = {"process_attachments": True} if process_attachments else {}+ _replace_message_stripping_actions(payload, "Action complete", **options)++ response = post_response.call_args.args[1]+ assert response["blocks"][0]["elements"] == [link]+ assert response["blocks"][-1]["elements"][0]["text"] == "Action complete"+ if process_attachments:+ assert response["attachments"] == [+ {"color": "#D97706", "blocks": [image, {"type": "actions", "elements": [link]}]}+ ]+ else:+ assert "attachments" not in response+ assert payload["message"]["attachments"][0]["blocks"][1]["elements"] == [link, control]diff --git a/products/subscriptions/backend/logic/slack_subscriptions.py b/products/subscriptions/backend/logic/slack_subscriptions.pyindex a105141a4ea8..3f7ae83e1210 100644--- a/products/subscriptions/backend/logic/slack_subscriptions.py+++ b/products/subscriptions/backend/logic/slack_subscriptions.py@@ -1,4 +1,3 @@-import reimport jsonimport asynciofrom dataclasses import dataclass, field@@ -8,15 +7,14 @@ from django.conf import settingsimport aiohttpimport structlog-from markdown_it import MarkdownItfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.web.async_client import AsyncWebClientfrom slack_sdk.web.async_slack_response import AsyncSlackResponsefrom posthog.dataclasses import frozen-from posthog.helpers.markdown_safety import is_allowed_link_urlfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.slack.formatting import channel_id_from_target+from posthog.slack.markdown import slack_rich_textfrom posthog.storage import object_storagefrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_uri@@ -166,64 +164,8 @@ def _subscription_header_blocks(]-_SUMMARY_INLINE_MARKUP = re.compile(- r"(?P<link>\[[^\[\]\n]*\]\((?:[^()\s]|\([^)]*\))+\))|"- r"<u>(?P<underline>[\s\S]+?)</u>|(?P<bold_marker>\*{1,2})(?P<bold>[^*\n]+)(?P=bold_marker)|"- r"(?<!\w)_(?P<italic>[^_\n]+)_(?!\w)|~(?P<strike>[^~\n]+)~|`(?P<code>[^`\n]+)`"-)---def _summary_inline_elements(text: str, style: dict[str, bool]) -> list[dict[str, Any]]:- elements: list[dict[str, Any]] = []- cursor = 0- for match in _SUMMARY_INLINE_MARKUP.finditer(text):- if match.start() > cursor:- elements.append({"type": "text", "text": text[cursor : match.start()], "style": style})- if match.group("link") is not None:- tokens = MarkdownIt("commonmark", {"html": False}).parseInline(match.group("link"))[0].children or []- destination = next((str(token.attrGet("href")) for token in tokens if token.type == "link_open"), "")- label = "".join(token.content for token in tokens if token.type in {"text", "code_inline"})- if is_allowed_link_url(destination, absolute_uri("/")):- elements.append({"type": "link", "url": destination, "text": label, "style": style})- else:- elements.append({"type": "text", "text": label, "style": style})- for name in ("bold", "italic", "underline", "strike", "code"):- content = match.group(name)- if content is not None:- nested_style = {**style, name: True}- if name == "code":- elements.append({"type": "text", "text": content, "style": nested_style})- else:- elements.extend(_summary_inline_elements(content, nested_style))- break- cursor = match.end()- if cursor < len(text):- elements.append({"type": "text", "text": text[cursor:], "style": style})- return elements--def _summary_rich_text(summary: str) -> dict[str, Any]:- elements: list[dict[str, Any]] = []- for line in summary.splitlines():- line = line.strip()- if not line:- if elements and elements[-1]["type"] == "rich_text_list":- elements.append({"type": "rich_text_section", "elements": [{"type": "text", "text": "\n"}]})- continue- bullet = re.match(r"^(?:[•*-]\s+|(\d+)[.)]\s+)(.+)$", line)- content = line- if bullet:- content = bullet.group(2)- section = {"type": "rich_text_section", "elements": _summary_inline_elements(content, {})}- if bullet:- list_style = "ordered" if bullet.group(1) else "bullet"- if elements and elements[-1]["type"] == "rich_text_list" and elements[-1]["style"] == list_style:- elements[-1]["elements"].append(section)- else:- elements.append({"type": "rich_text_list", "style": list_style, "elements": [section]})- else:- elements.append(section)- return {"type": "rich_text", "elements": elements}+ return slack_rich_text(summary, allowed_root=absolute_uri("/"))def _ai_summary_block(change_summary: str) -> dict[str, Any]: